Add files using upload-large-folder tool
Browse files- .githooks/pre-commit +44 -44
- internal/playbooks/playbook-live-load-unload.md +156 -156
- internal/playbooks/playbook-random-load-unload.md +294 -294
- internal/playbooks/playbook-real-world.md +274 -274
- scripts/build_dashboard_graph_index.py +169 -169
- scripts/ci_classifier.py +150 -150
- scripts/ci_no_test_policy.py +178 -178
- scripts/ci_preflight.py +308 -308
- scripts/ci_required.py +146 -146
- scripts/clean_host_contract.py +850 -850
- scripts/graph_artifact_guard.py +196 -196
- scripts/overlay_wiki_entities.py +540 -540
- scripts/sync_huggingface.py +309 -282
- src/tests/fixtures/fake_mcp_server.py +224 -224
- src/tests/fixtures/pulsemcp_listing_excerpt.html +170 -170
- src/tests/test_agent_add.py +217 -217
- src/tests/test_artifact_promotion.py +143 -143
- src/tests/test_bundle_orchestrator.py +215 -215
- src/tests/test_catalog_builder.py +917 -917
- src/tests/test_change_detector.py +869 -869
- src/tests/test_config.py +373 -373
- src/tests/test_context_monitor.py +529 -529
- src/tests/test_ctx_init.py +1368 -1348
- src/tests/test_dedup_check.py +286 -286
- src/tests/test_fs_utils.py +207 -207
- src/tests/test_harness_contract.py +744 -744
- src/tests/test_harness_state.py +674 -674
- src/tests/test_incremental_attach_shadow.py +210 -210
- src/tests/test_inject_hooks_security.py +376 -376
- src/tests/test_mcp_enrich_render_scalar.py +121 -121
- src/tests/test_mcp_router.py +423 -423
- src/tests/test_mcp_sources_awesome.py +169 -169
- src/tests/test_patch_graph.py +394 -394
- src/tests/test_query.py +247 -247
- src/tests/test_resolve_skills.py +758 -758
- src/tests/test_safe_name.py +228 -228
- src/tests/test_similarity_precision_recall.py +314 -314
- src/tests/test_skill_loader.py +372 -372
- src/tests/test_skill_mirror.py +322 -322
- src/tests/test_skill_quality_bench.py +141 -141
- src/tests/test_skill_telemetry.py +329 -329
- src/tests/test_update_repo_stats.py +391 -338
- src/tests/test_validate_graph_artifacts.py +1193 -1192
.githooks/pre-commit
CHANGED
|
@@ -1,44 +1,44 @@
|
|
| 1 |
-
#!/usr/bin/env bash
|
| 2 |
-
# pre-commit -- refresh cheap repo stats without leaking local wiki state.
|
| 3 |
-
#
|
| 4 |
-
# Enable with: git config core.hooksPath .githooks
|
| 5 |
-
# Disable with: git config --unset core.hooksPath
|
| 6 |
-
#
|
| 7 |
-
# This hook intentionally does not rebuild graph/wiki artifacts from
|
| 8 |
-
# ~/.claude/skill-wiki. That directory can contain private local entities.
|
| 9 |
-
# Release graph artifacts must be created by explicit, reproducible commands
|
| 10 |
-
# and staged by the user or CI.
|
| 11 |
-
|
| 12 |
-
set -u
|
| 13 |
-
|
| 14 |
-
REPO_ROOT="$(git rev-parse --show-toplevel)"
|
| 15 |
-
UPDATER="$REPO_ROOT/src/update_repo_stats.py"
|
| 16 |
-
|
| 17 |
-
PYTHON="${PYTHON:-python3}"
|
| 18 |
-
command -v "$PYTHON" >/dev/null 2>&1 || PYTHON="python"
|
| 19 |
-
STATS_TIMEOUT="${CTX_REPO_STATS_TIMEOUT:-240s}"
|
| 20 |
-
|
| 21 |
-
STAGED_CHANGES=$(git diff --cached --name-only)
|
| 22 |
-
log() { echo "[pre-commit] $*" >&2; }
|
| 23 |
-
|
| 24 |
-
if echo "$STAGED_CHANGES" | grep -qE '^(README\.md|docs/index\.md|graph/(wiki-graph\.tar\.gz|communities\.json|skills-sh-catalog\.json\.gz)|src/update_repo_stats\.py)$' ; then
|
| 25 |
-
if [[ -f "$UPDATER" ]]; then
|
| 26 |
-
STATS_CMD=("$PYTHON" "$UPDATER")
|
| 27 |
-
if command -v timeout >/dev/null 2>&1; then
|
| 28 |
-
STATS_CMD=(timeout "$STATS_TIMEOUT" "${STATS_CMD[@]}")
|
| 29 |
-
fi
|
| 30 |
-
if ! "${STATS_CMD[@]}" 2> >(sed 's/^/[pre-commit stats] /' >&2); then
|
| 31 |
-
log "stats updater failed or timed out; continuing without README refresh"
|
| 32 |
-
elif ! git diff --quiet -- README.md docs/index.md; then
|
| 33 |
-
git add README.md docs/index.md
|
| 34 |
-
log "README.md and docs/index.md refreshed and re-staged"
|
| 35 |
-
fi
|
| 36 |
-
fi
|
| 37 |
-
fi
|
| 38 |
-
|
| 39 |
-
if echo "$STAGED_CHANGES" | grep -qE '^(skills|agents|harnesses|imported-skills|graph/skills-sh-catalog\.json\.gz)' ; then
|
| 40 |
-
log "entity source changed; graph/wiki tarball not rebuilt by pre-commit"
|
| 41 |
-
log "run the explicit graph release command and stage graph/wiki-graph.tar.gz if needed"
|
| 42 |
-
fi
|
| 43 |
-
|
| 44 |
-
exit 0
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# pre-commit -- refresh cheap repo stats without leaking local wiki state.
|
| 3 |
+
#
|
| 4 |
+
# Enable with: git config core.hooksPath .githooks
|
| 5 |
+
# Disable with: git config --unset core.hooksPath
|
| 6 |
+
#
|
| 7 |
+
# This hook intentionally does not rebuild graph/wiki artifacts from
|
| 8 |
+
# ~/.claude/skill-wiki. That directory can contain private local entities.
|
| 9 |
+
# Release graph artifacts must be created by explicit, reproducible commands
|
| 10 |
+
# and staged by the user or CI.
|
| 11 |
+
|
| 12 |
+
set -u
|
| 13 |
+
|
| 14 |
+
REPO_ROOT="$(git rev-parse --show-toplevel)"
|
| 15 |
+
UPDATER="$REPO_ROOT/src/update_repo_stats.py"
|
| 16 |
+
|
| 17 |
+
PYTHON="${PYTHON:-python3}"
|
| 18 |
+
command -v "$PYTHON" >/dev/null 2>&1 || PYTHON="python"
|
| 19 |
+
STATS_TIMEOUT="${CTX_REPO_STATS_TIMEOUT:-240s}"
|
| 20 |
+
|
| 21 |
+
STAGED_CHANGES=$(git diff --cached --name-only)
|
| 22 |
+
log() { echo "[pre-commit] $*" >&2; }
|
| 23 |
+
|
| 24 |
+
if echo "$STAGED_CHANGES" | grep -qE '^(README\.md|docs/index\.md|graph/(wiki-graph\.tar\.gz|communities\.json|skills-sh-catalog\.json\.gz)|src/update_repo_stats\.py)$' ; then
|
| 25 |
+
if [[ -f "$UPDATER" ]]; then
|
| 26 |
+
STATS_CMD=("$PYTHON" "$UPDATER")
|
| 27 |
+
if command -v timeout >/dev/null 2>&1; then
|
| 28 |
+
STATS_CMD=(timeout "$STATS_TIMEOUT" "${STATS_CMD[@]}")
|
| 29 |
+
fi
|
| 30 |
+
if ! "${STATS_CMD[@]}" 2> >(sed 's/^/[pre-commit stats] /' >&2); then
|
| 31 |
+
log "stats updater failed or timed out; continuing without README refresh"
|
| 32 |
+
elif ! git diff --quiet -- README.md docs/index.md; then
|
| 33 |
+
git add README.md docs/index.md
|
| 34 |
+
log "README.md and docs/index.md refreshed and re-staged"
|
| 35 |
+
fi
|
| 36 |
+
fi
|
| 37 |
+
fi
|
| 38 |
+
|
| 39 |
+
if echo "$STAGED_CHANGES" | grep -qE '^(skills|agents|harnesses|imported-skills|graph/skills-sh-catalog\.json\.gz)' ; then
|
| 40 |
+
log "entity source changed; graph/wiki tarball not rebuilt by pre-commit"
|
| 41 |
+
log "run the explicit graph release command and stage graph/wiki-graph.tar.gz if needed"
|
| 42 |
+
fi
|
| 43 |
+
|
| 44 |
+
exit 0
|
internal/playbooks/playbook-live-load-unload.md
CHANGED
|
@@ -1,156 +1,156 @@
|
|
| 1 |
-
# Live load / unload verification playbook
|
| 2 |
-
|
| 3 |
-
> Does ctx actually observe skills and agents being loaded and unloaded
|
| 4 |
-
> on the fly, in real time, during a live Claude Code session? If yes,
|
| 5 |
-
> the telemetry pipeline is truly live. If no, this is a CODE RED — the
|
| 6 |
-
> "real-time knowledge graph" claim is broken and we escalate to an
|
| 7 |
-
> expert swarm.
|
| 8 |
-
|
| 9 |
-
## What "live load/unload" means in ctx's model
|
| 10 |
-
|
| 11 |
-
There is no central controller that "loads" a skill. Claude Code
|
| 12 |
-
itself decides when a skill's content is injected into the prompt
|
| 13 |
-
based on user intent + the skill's `description` match. ctx is an
|
| 14 |
-
**observer**, not a driver. Its claim is:
|
| 15 |
-
|
| 16 |
-
1. **Observe** — `PostToolUse` hook fires `context_monitor.py` on
|
| 17 |
-
every tool call. When a tool call's content matches a skill-name
|
| 18 |
-
signal, the event is recorded.
|
| 19 |
-
2. **Suggest** — unmatched signals accumulate in
|
| 20 |
-
`~/.claude/pending-skills.json`. `skill_suggest.py` surfaces them
|
| 21 |
-
into Claude's context as `hookSpecificOutput.additionalContext`,
|
| 22 |
-
so Claude raises them to the user on next response.
|
| 23 |
-
3. **Record** — when Claude actually uses a skill (via its own load
|
| 24 |
-
mechanism), the event lands in `~/.claude/skill-events.jsonl` as
|
| 25 |
-
`{"event": "load", "skill": "<slug>", ...}`.
|
| 26 |
-
4. **Score** — the `Stop` hook runs `quality_on_session_end.py`,
|
| 27 |
-
which recomputes the sidecar for every slug with new events. The
|
| 28 |
-
telemetry signal reflects the load within seconds.
|
| 29 |
-
|
| 30 |
-
The pipeline is **only live if every one of those four links works
|
| 31 |
-
with no gap**. This playbook tests each.
|
| 32 |
-
|
| 33 |
-
## Prerequisites
|
| 34 |
-
|
| 35 |
-
- `claude-ctx` 0.5.0-rc6 installed (`pip install claude-ctx`).
|
| 36 |
-
- `~/.claude/skill-wiki/` present and graph pre-built
|
| 37 |
-
(`graphify-out/graph.json` has 2,253 nodes / 454K edges).
|
| 38 |
-
- `~/.claude/settings.json` has the PostToolUse + Stop hooks wired.
|
| 39 |
-
- Baseline snapshot of `~/.claude/skill-events.jsonl` (line count).
|
| 40 |
-
- Baseline snapshot of 3 sidecars (`python-patterns`, `fastapi-pro`,
|
| 41 |
-
`stripe-integration`) — raw JSON copies under `/tmp/baseline/`.
|
| 42 |
-
|
| 43 |
-
## Test matrix — each must PASS
|
| 44 |
-
|
| 45 |
-
### 1. Hook registration
|
| 46 |
-
- [ ] `settings.json` `PostToolUse` contains
|
| 47 |
-
`context_monitor.py --from-stdin`.
|
| 48 |
-
- [ ] `settings.json` `PostToolUse` contains
|
| 49 |
-
`skill_add_detector.py --from-stdin`.
|
| 50 |
-
- [ ] `settings.json` `PostToolUse` contains `skill_suggest.py`.
|
| 51 |
-
- [ ] `settings.json` `PostToolUse` contains
|
| 52 |
-
`backup_on_change.py` under an `Edit|Write|MultiEdit` matcher.
|
| 53 |
-
- [ ] `settings.json` `Stop` contains `usage_tracker.py --sync`.
|
| 54 |
-
- [ ] `settings.json` `Stop` contains `quality_on_session_end.py`.
|
| 55 |
-
- [ ] All hook commands use `--from-stdin` (no
|
| 56 |
-
`$CLAUDE_TOOL_INPUT`/`$CLAUDE_TOOL_NAME` argv interpolation).
|
| 57 |
-
|
| 58 |
-
### 2. Observe — context_monitor detects a known signal
|
| 59 |
-
- [ ] Feed `context_monitor.py --from-stdin` a synthetic tool-use
|
| 60 |
-
event whose `tool_input.file_path` contains `fastapi`.
|
| 61 |
-
- [ ] Before: read `~/.claude/pending-skills.json` line count (or
|
| 62 |
-
its `unmatched_signals` array length).
|
| 63 |
-
- [ ] After: length grew OR `graph_suggestions` changed.
|
| 64 |
-
- [ ] Repeat with `stripe`, `postgres`, `pci` — all three now in
|
| 65 |
-
`KEYWORD_SIGNALS` as of rc5.
|
| 66 |
-
|
| 67 |
-
### 3. Suggest — skill_suggest surfaces pending skills
|
| 68 |
-
- [ ] Run `skill_suggest.py` with no args.
|
| 69 |
-
- [ ] Stdout is a valid JSON object with
|
| 70 |
-
`hookSpecificOutput.hookEventName == "PostToolUse"` and
|
| 71 |
-
`additionalContext` referencing at least one candidate skill
|
| 72 |
-
from the pending-signals added in step 2.
|
| 73 |
-
|
| 74 |
-
### 4. Record — skill-events.jsonl grows on a simulated load
|
| 75 |
-
- [ ] Before: `wc -l ~/.claude/skill-events.jsonl`.
|
| 76 |
-
- [ ] Append three synthetic events:
|
| 77 |
-
`load fastapi-pro`, `load pci-compliance`,
|
| 78 |
-
`unload fastapi-pro` (distinct `event_id`, realistic
|
| 79 |
-
timestamp, distinct `session_id` from baseline).
|
| 80 |
-
- [ ] After: line count grew by exactly 3.
|
| 81 |
-
|
| 82 |
-
### 5. Score — sidecar refreshes on session end
|
| 83 |
-
- [ ] Save sidecar `fastapi-pro.json` copy → `/tmp/baseline/`.
|
| 84 |
-
- [ ] Run `python hooks/quality_on_session_end.py`.
|
| 85 |
-
- [ ] Stdout should include `fastapi-pro` in the "recomputed" list
|
| 86 |
-
(only slugs with new events should be touched).
|
| 87 |
-
- [ ] Compare `~/.claude/skill-quality/fastapi-pro.json` mtime —
|
| 88 |
-
must be newer than baseline by >0 seconds.
|
| 89 |
-
- [ ] Telemetry signal `load_count` increased by 2 (the two loads
|
| 90 |
-
we appended); `recent_load_count` increased by 2.
|
| 91 |
-
- [ ] Overall `score` changed OR `grade` changed (F→D→C→B→A).
|
| 92 |
-
|
| 93 |
-
### 6. End-to-end timing
|
| 94 |
-
- [ ] From the moment the synthetic load event is written to
|
| 95 |
-
skill-events.jsonl, how many seconds until
|
| 96 |
-
`ctx-skill-quality explain fastapi-pro` reflects it?
|
| 97 |
-
- Required: **< 30 seconds** with `quality_on_session_end.py`
|
| 98 |
-
fired manually.
|
| 99 |
-
- Stretch: **< 5 seconds** if the Stop hook fires on session
|
| 100 |
-
close.
|
| 101 |
-
- [ ] Record the measured latency.
|
| 102 |
-
|
| 103 |
-
### 7. Session attribution — can we tell which session loaded what?
|
| 104 |
-
- [ ] Scan `skill-events.jsonl` for the test `session_id`.
|
| 105 |
-
- [ ] All 3 test events appear with that session_id.
|
| 106 |
-
- [ ] `ctx-skill-quality explain <slug>` doesn't currently surface
|
| 107 |
-
per-session detail — **gap; track as future work**.
|
| 108 |
-
|
| 109 |
-
## Pass / fail criteria
|
| 110 |
-
|
| 111 |
-
**PASS** — all of 1–5 pass, and step 6 measured latency is under
|
| 112 |
-
30 seconds. This proves the pipeline is live.
|
| 113 |
-
|
| 114 |
-
**PARTIAL** — 4 of 5 pass; latency acceptable; one gap exists.
|
| 115 |
-
Ship the rc, file the gap as a follow-up issue.
|
| 116 |
-
|
| 117 |
-
**FAIL** — any of steps 2, 4, or 5 fails. The
|
| 118 |
-
observe→record→score loop is broken. This is a **CODE RED**:
|
| 119 |
-
|
| 120 |
-
1. Escalate to an expert swarm (Anthropic, OpenAI, Mistral,
|
| 121 |
-
Microsoft observability + agent-system engineers).
|
| 122 |
-
2. Goal: design a minimum change set that makes the pipeline live.
|
| 123 |
-
3. Output: a 1-pager plan with the smallest possible code change
|
| 124 |
-
and a test that would have caught the regression.
|
| 125 |
-
|
| 126 |
-
## What "expert swarm" looks like
|
| 127 |
-
|
| 128 |
-
Five sub-agents spawned in parallel, each briefed differently:
|
| 129 |
-
|
| 130 |
-
- **Anthropic engineer** — Claude Code hook model, `stdin` format,
|
| 131 |
-
ordering guarantees of PostToolUse vs Stop. Tells us if what we
|
| 132 |
-
expect is actually guaranteed by Claude Code.
|
| 133 |
-
- **OpenAI engineer** — event-driven telemetry design, how
|
| 134 |
-
function-call / tool-call streams are typically observed in
|
| 135 |
-
production ChatGPT-style systems. Tells us if our jsonl approach
|
| 136 |
-
is sound or if we're missing a standard pattern.
|
| 137 |
-
- **Mistral engineer** — lightweight on-device observability, how
|
| 138 |
-
to keep the observer cheap when the agent environment is local.
|
| 139 |
-
Tells us whether our hook fan-out is causing latency.
|
| 140 |
-
- **Microsoft engineer** — VS Code extension + language-server
|
| 141 |
-
observability. Tells us what hook contract an IDE-hosted agent
|
| 142 |
-
should expose for a pluggable observer like ctx.
|
| 143 |
-
- **Consolidator** — takes the four reports and outputs a single
|
| 144 |
-
plan with a "minimum viable fix" ranked by effort/reward.
|
| 145 |
-
|
| 146 |
-
Each agent gets **the same failing evidence**: the events.jsonl
|
| 147 |
-
before/after, the sidecar mtime check, the captured hook output.
|
| 148 |
-
Their job is to diagnose, not to re-run the test.
|
| 149 |
-
|
| 150 |
-
## Next steps after verification
|
| 151 |
-
|
| 152 |
-
- If PASS: ship the audit-log feature, ship `ctx-monitor serve`
|
| 153 |
-
with per-session view.
|
| 154 |
-
- If PARTIAL: ship the gap fix, document the session-attribution
|
| 155 |
-
limitation in the README.
|
| 156 |
-
- If FAIL: execute the expert-swarm plan, iterate until PASS.
|
|
|
|
| 1 |
+
# Live load / unload verification playbook
|
| 2 |
+
|
| 3 |
+
> Does ctx actually observe skills and agents being loaded and unloaded
|
| 4 |
+
> on the fly, in real time, during a live Claude Code session? If yes,
|
| 5 |
+
> the telemetry pipeline is truly live. If no, this is a CODE RED — the
|
| 6 |
+
> "real-time knowledge graph" claim is broken and we escalate to an
|
| 7 |
+
> expert swarm.
|
| 8 |
+
|
| 9 |
+
## What "live load/unload" means in ctx's model
|
| 10 |
+
|
| 11 |
+
There is no central controller that "loads" a skill. Claude Code
|
| 12 |
+
itself decides when a skill's content is injected into the prompt
|
| 13 |
+
based on user intent + the skill's `description` match. ctx is an
|
| 14 |
+
**observer**, not a driver. Its claim is:
|
| 15 |
+
|
| 16 |
+
1. **Observe** — `PostToolUse` hook fires `context_monitor.py` on
|
| 17 |
+
every tool call. When a tool call's content matches a skill-name
|
| 18 |
+
signal, the event is recorded.
|
| 19 |
+
2. **Suggest** — unmatched signals accumulate in
|
| 20 |
+
`~/.claude/pending-skills.json`. `skill_suggest.py` surfaces them
|
| 21 |
+
into Claude's context as `hookSpecificOutput.additionalContext`,
|
| 22 |
+
so Claude raises them to the user on next response.
|
| 23 |
+
3. **Record** — when Claude actually uses a skill (via its own load
|
| 24 |
+
mechanism), the event lands in `~/.claude/skill-events.jsonl` as
|
| 25 |
+
`{"event": "load", "skill": "<slug>", ...}`.
|
| 26 |
+
4. **Score** — the `Stop` hook runs `quality_on_session_end.py`,
|
| 27 |
+
which recomputes the sidecar for every slug with new events. The
|
| 28 |
+
telemetry signal reflects the load within seconds.
|
| 29 |
+
|
| 30 |
+
The pipeline is **only live if every one of those four links works
|
| 31 |
+
with no gap**. This playbook tests each.
|
| 32 |
+
|
| 33 |
+
## Prerequisites
|
| 34 |
+
|
| 35 |
+
- `claude-ctx` 0.5.0-rc6 installed (`pip install claude-ctx`).
|
| 36 |
+
- `~/.claude/skill-wiki/` present and graph pre-built
|
| 37 |
+
(`graphify-out/graph.json` has 2,253 nodes / 454K edges).
|
| 38 |
+
- `~/.claude/settings.json` has the PostToolUse + Stop hooks wired.
|
| 39 |
+
- Baseline snapshot of `~/.claude/skill-events.jsonl` (line count).
|
| 40 |
+
- Baseline snapshot of 3 sidecars (`python-patterns`, `fastapi-pro`,
|
| 41 |
+
`stripe-integration`) — raw JSON copies under `/tmp/baseline/`.
|
| 42 |
+
|
| 43 |
+
## Test matrix — each must PASS
|
| 44 |
+
|
| 45 |
+
### 1. Hook registration
|
| 46 |
+
- [ ] `settings.json` `PostToolUse` contains
|
| 47 |
+
`context_monitor.py --from-stdin`.
|
| 48 |
+
- [ ] `settings.json` `PostToolUse` contains
|
| 49 |
+
`skill_add_detector.py --from-stdin`.
|
| 50 |
+
- [ ] `settings.json` `PostToolUse` contains `skill_suggest.py`.
|
| 51 |
+
- [ ] `settings.json` `PostToolUse` contains
|
| 52 |
+
`backup_on_change.py` under an `Edit|Write|MultiEdit` matcher.
|
| 53 |
+
- [ ] `settings.json` `Stop` contains `usage_tracker.py --sync`.
|
| 54 |
+
- [ ] `settings.json` `Stop` contains `quality_on_session_end.py`.
|
| 55 |
+
- [ ] All hook commands use `--from-stdin` (no
|
| 56 |
+
`$CLAUDE_TOOL_INPUT`/`$CLAUDE_TOOL_NAME` argv interpolation).
|
| 57 |
+
|
| 58 |
+
### 2. Observe — context_monitor detects a known signal
|
| 59 |
+
- [ ] Feed `context_monitor.py --from-stdin` a synthetic tool-use
|
| 60 |
+
event whose `tool_input.file_path` contains `fastapi`.
|
| 61 |
+
- [ ] Before: read `~/.claude/pending-skills.json` line count (or
|
| 62 |
+
its `unmatched_signals` array length).
|
| 63 |
+
- [ ] After: length grew OR `graph_suggestions` changed.
|
| 64 |
+
- [ ] Repeat with `stripe`, `postgres`, `pci` — all three now in
|
| 65 |
+
`KEYWORD_SIGNALS` as of rc5.
|
| 66 |
+
|
| 67 |
+
### 3. Suggest — skill_suggest surfaces pending skills
|
| 68 |
+
- [ ] Run `skill_suggest.py` with no args.
|
| 69 |
+
- [ ] Stdout is a valid JSON object with
|
| 70 |
+
`hookSpecificOutput.hookEventName == "PostToolUse"` and
|
| 71 |
+
`additionalContext` referencing at least one candidate skill
|
| 72 |
+
from the pending-signals added in step 2.
|
| 73 |
+
|
| 74 |
+
### 4. Record — skill-events.jsonl grows on a simulated load
|
| 75 |
+
- [ ] Before: `wc -l ~/.claude/skill-events.jsonl`.
|
| 76 |
+
- [ ] Append three synthetic events:
|
| 77 |
+
`load fastapi-pro`, `load pci-compliance`,
|
| 78 |
+
`unload fastapi-pro` (distinct `event_id`, realistic
|
| 79 |
+
timestamp, distinct `session_id` from baseline).
|
| 80 |
+
- [ ] After: line count grew by exactly 3.
|
| 81 |
+
|
| 82 |
+
### 5. Score — sidecar refreshes on session end
|
| 83 |
+
- [ ] Save sidecar `fastapi-pro.json` copy → `/tmp/baseline/`.
|
| 84 |
+
- [ ] Run `python hooks/quality_on_session_end.py`.
|
| 85 |
+
- [ ] Stdout should include `fastapi-pro` in the "recomputed" list
|
| 86 |
+
(only slugs with new events should be touched).
|
| 87 |
+
- [ ] Compare `~/.claude/skill-quality/fastapi-pro.json` mtime —
|
| 88 |
+
must be newer than baseline by >0 seconds.
|
| 89 |
+
- [ ] Telemetry signal `load_count` increased by 2 (the two loads
|
| 90 |
+
we appended); `recent_load_count` increased by 2.
|
| 91 |
+
- [ ] Overall `score` changed OR `grade` changed (F→D→C→B→A).
|
| 92 |
+
|
| 93 |
+
### 6. End-to-end timing
|
| 94 |
+
- [ ] From the moment the synthetic load event is written to
|
| 95 |
+
skill-events.jsonl, how many seconds until
|
| 96 |
+
`ctx-skill-quality explain fastapi-pro` reflects it?
|
| 97 |
+
- Required: **< 30 seconds** with `quality_on_session_end.py`
|
| 98 |
+
fired manually.
|
| 99 |
+
- Stretch: **< 5 seconds** if the Stop hook fires on session
|
| 100 |
+
close.
|
| 101 |
+
- [ ] Record the measured latency.
|
| 102 |
+
|
| 103 |
+
### 7. Session attribution — can we tell which session loaded what?
|
| 104 |
+
- [ ] Scan `skill-events.jsonl` for the test `session_id`.
|
| 105 |
+
- [ ] All 3 test events appear with that session_id.
|
| 106 |
+
- [ ] `ctx-skill-quality explain <slug>` doesn't currently surface
|
| 107 |
+
per-session detail — **gap; track as future work**.
|
| 108 |
+
|
| 109 |
+
## Pass / fail criteria
|
| 110 |
+
|
| 111 |
+
**PASS** — all of 1–5 pass, and step 6 measured latency is under
|
| 112 |
+
30 seconds. This proves the pipeline is live.
|
| 113 |
+
|
| 114 |
+
**PARTIAL** — 4 of 5 pass; latency acceptable; one gap exists.
|
| 115 |
+
Ship the rc, file the gap as a follow-up issue.
|
| 116 |
+
|
| 117 |
+
**FAIL** — any of steps 2, 4, or 5 fails. The
|
| 118 |
+
observe→record→score loop is broken. This is a **CODE RED**:
|
| 119 |
+
|
| 120 |
+
1. Escalate to an expert swarm (Anthropic, OpenAI, Mistral,
|
| 121 |
+
Microsoft observability + agent-system engineers).
|
| 122 |
+
2. Goal: design a minimum change set that makes the pipeline live.
|
| 123 |
+
3. Output: a 1-pager plan with the smallest possible code change
|
| 124 |
+
and a test that would have caught the regression.
|
| 125 |
+
|
| 126 |
+
## What "expert swarm" looks like
|
| 127 |
+
|
| 128 |
+
Five sub-agents spawned in parallel, each briefed differently:
|
| 129 |
+
|
| 130 |
+
- **Anthropic engineer** — Claude Code hook model, `stdin` format,
|
| 131 |
+
ordering guarantees of PostToolUse vs Stop. Tells us if what we
|
| 132 |
+
expect is actually guaranteed by Claude Code.
|
| 133 |
+
- **OpenAI engineer** — event-driven telemetry design, how
|
| 134 |
+
function-call / tool-call streams are typically observed in
|
| 135 |
+
production ChatGPT-style systems. Tells us if our jsonl approach
|
| 136 |
+
is sound or if we're missing a standard pattern.
|
| 137 |
+
- **Mistral engineer** — lightweight on-device observability, how
|
| 138 |
+
to keep the observer cheap when the agent environment is local.
|
| 139 |
+
Tells us whether our hook fan-out is causing latency.
|
| 140 |
+
- **Microsoft engineer** — VS Code extension + language-server
|
| 141 |
+
observability. Tells us what hook contract an IDE-hosted agent
|
| 142 |
+
should expose for a pluggable observer like ctx.
|
| 143 |
+
- **Consolidator** — takes the four reports and outputs a single
|
| 144 |
+
plan with a "minimum viable fix" ranked by effort/reward.
|
| 145 |
+
|
| 146 |
+
Each agent gets **the same failing evidence**: the events.jsonl
|
| 147 |
+
before/after, the sidecar mtime check, the captured hook output.
|
| 148 |
+
Their job is to diagnose, not to re-run the test.
|
| 149 |
+
|
| 150 |
+
## Next steps after verification
|
| 151 |
+
|
| 152 |
+
- If PASS: ship the audit-log feature, ship `ctx-monitor serve`
|
| 153 |
+
with per-session view.
|
| 154 |
+
- If PARTIAL: ship the gap fix, document the session-attribution
|
| 155 |
+
limitation in the README.
|
| 156 |
+
- If FAIL: execute the expert-swarm plan, iterate until PASS.
|
internal/playbooks/playbook-random-load-unload.md
CHANGED
|
@@ -1,294 +1,294 @@
|
|
| 1 |
-
# Random load → unload playbook
|
| 2 |
-
|
| 3 |
-
> Pick a skill the user hasn't touched recently, verify ctx suggests
|
| 4 |
-
> loading it, verify the skill actually enters the loaded set, wait
|
| 5 |
-
> for staleness, verify ctx suggests unloading it, verify it actually
|
| 6 |
-
> leaves. Every claim is backed by a concrete file-system observation,
|
| 7 |
-
> not a log-line assumption.
|
| 8 |
-
|
| 9 |
-
## Why this scenario matters
|
| 10 |
-
|
| 11 |
-
Previous playbooks verified the *pipeline* (observer → suggest →
|
| 12 |
-
record → score). This one verifies the **economic** part: skills
|
| 13 |
-
come in and go back out, and the user can observe both halves of
|
| 14 |
-
the cycle. Without this, the "nothing rots" claim in the README is
|
| 15 |
-
untested.
|
| 16 |
-
|
| 17 |
-
## What we'll use
|
| 18 |
-
|
| 19 |
-
- **ctx-monitor** (rc8+) to watch the audit log live via SSE. The
|
| 20 |
-
test agent keeps the dashboard open at
|
| 21 |
-
`http://127.0.0.1:8765/session/<test-session-id>` and screenshots
|
| 22 |
-
the audit timeline before/after.
|
| 23 |
-
- **ctx_audit_log** event stream (`~/.claude/ctx-audit.jsonl`).
|
| 24 |
-
- **skill-events.jsonl** for the ground-truth load/unload record.
|
| 25 |
-
- **pending-unload.json** for the suggest-to-unload signal.
|
| 26 |
-
- **skill_quality explain <slug>** to read the sidecar after each
|
| 27 |
-
phase.
|
| 28 |
-
|
| 29 |
-
## Preconditions
|
| 30 |
-
|
| 31 |
-
1. `claude-ctx` 0.5.0-rc8 installed from PyPI.
|
| 32 |
-
2. `~/.claude/skill-wiki/` pre-built (2,253 nodes, 454K edges).
|
| 33 |
-
3. `~/.claude/skills/` has ≥ 1,500 skills installed.
|
| 34 |
-
4. `~/.claude/settings.json` has all rc7 hooks wired
|
| 35 |
-
(PostToolUse: context_monitor + skill_add_detector + skill_suggest
|
| 36 |
-
+ backup_on_change; Stop: usage_tracker + quality_on_session_end).
|
| 37 |
-
5. Stale-threshold override for the test run. Write it into
|
| 38 |
-
`~/.claude/skill-system-config.json` — there is no env var
|
| 39 |
-
shortcut; the threshold only comes from config:
|
| 40 |
-
```bash
|
| 41 |
-
python -c "
|
| 42 |
-
import json, os
|
| 43 |
-
from pathlib import Path
|
| 44 |
-
p = Path(os.path.expanduser('~/.claude/skill-system-config.json'))
|
| 45 |
-
cfg = json.loads(p.read_text()) if p.exists() else {}
|
| 46 |
-
cfg.setdefault('usage_tracker', {})['stale_threshold_sessions'] = 3
|
| 47 |
-
p.write_text(json.dumps(cfg, indent=2))
|
| 48 |
-
"
|
| 49 |
-
```
|
| 50 |
-
Default is 30 — too slow to observe in one sitting.
|
| 51 |
-
6. `ctx-monitor serve --port 8765` running in a background tab.
|
| 52 |
-
|
| 53 |
-
## The scenario
|
| 54 |
-
|
| 55 |
-
### Step 1 — Pick a random candidate
|
| 56 |
-
|
| 57 |
-
Pick a skill whose sidecar has:
|
| 58 |
-
- `hard_floor: "never_loaded_stale"` — these all map to **grade D**
|
| 59 |
-
(grade F is reserved for `intake_fail`), AND
|
| 60 |
-
- `intake.score >= 0.8` (structurally valid), AND
|
| 61 |
-
- **tag overlap with `context_monitor.KEYWORD_SIGNALS`** — otherwise
|
| 62 |
-
the skill can never surface through the observe→suggest path
|
| 63 |
-
(learned the hard way on rc8's verification run), AND
|
| 64 |
-
- not a meta-skill (`skill-router`, `file-reading`, etc.).
|
| 65 |
-
|
| 66 |
-
```bash
|
| 67 |
-
python - <<'PY'
|
| 68 |
-
import json, random, re
|
| 69 |
-
from pathlib import Path
|
| 70 |
-
|
| 71 |
-
# Seed: installed KEYWORD_SIGNALS from context_monitor.
|
| 72 |
-
# Load dynamically to survive future vocabulary changes.
|
| 73 |
-
import importlib.util
|
| 74 |
-
src = Path.home() / ".claude" / "skills" # may differ per install
|
| 75 |
-
spec_path = None
|
| 76 |
-
for candidate in [
|
| 77 |
-
Path(__file__).resolve().parents[1] / "src" / "context_monitor.py",
|
| 78 |
-
Path.home() / ".local" / "lib" / "python3.11" / "site-packages" / "context_monitor.py",
|
| 79 |
-
]:
|
| 80 |
-
if candidate.exists():
|
| 81 |
-
spec_path = candidate; break
|
| 82 |
-
spec = importlib.util.spec_from_file_location("_cm", spec_path)
|
| 83 |
-
cm = importlib.util.module_from_spec(spec); spec.loader.exec_module(cm)
|
| 84 |
-
keywords = set(cm.KEYWORD_SIGNALS.keys())
|
| 85 |
-
|
| 86 |
-
sidecar_dir = Path.home() / ".claude" / "skill-quality"
|
| 87 |
-
candidates: list[str] = []
|
| 88 |
-
for p in sidecar_dir.glob("*.json"):
|
| 89 |
-
if p.name.startswith(".") or p.name.endswith(".lifecycle.json"):
|
| 90 |
-
continue
|
| 91 |
-
try:
|
| 92 |
-
sc = json.loads(p.read_text())
|
| 93 |
-
except Exception:
|
| 94 |
-
continue
|
| 95 |
-
if sc.get("hard_floor") != "never_loaded_stale" or sc.get("grade") != "D":
|
| 96 |
-
continue
|
| 97 |
-
intake = (sc.get("signals") or {}).get("intake", {}) or {}
|
| 98 |
-
if intake.get("score", 0) < 0.8:
|
| 99 |
-
continue
|
| 100 |
-
slug = sc["slug"]
|
| 101 |
-
if slug in {"skill-router", "file-reading", "context-monitor"}:
|
| 102 |
-
continue
|
| 103 |
-
# Require ≥2 tag tokens in the slug that also appear as KEYWORD_SIGNALS
|
| 104 |
-
slug_tokens = set(re.split(r"[^a-z0-9]+", slug.lower()))
|
| 105 |
-
if len(slug_tokens & keywords) >= 2:
|
| 106 |
-
candidates.append(slug)
|
| 107 |
-
|
| 108 |
-
random.shuffle(candidates)
|
| 109 |
-
print(candidates[0] if candidates else "NONE_FOUND")
|
| 110 |
-
PY
|
| 111 |
-
```
|
| 112 |
-
|
| 113 |
-
Record the picked slug. Call it `$TARGET`.
|
| 114 |
-
|
| 115 |
-
**Expected**: $TARGET has `grade=D`, `load_count=0`,
|
| 116 |
-
`never_loaded=True`, `hard_floor=never_loaded_stale`.
|
| 117 |
-
|
| 118 |
-
### Step 2 — Inject a stack signal that should surface $TARGET
|
| 119 |
-
|
| 120 |
-
Look at the target skill's `tags`. Synthesize a PostToolUse payload
|
| 121 |
-
whose `tool_input.file_path` or content contains 3+ of those tags
|
| 122 |
-
(crossing the `UNMATCHED_SIGNAL_THRESHOLD` in
|
| 123 |
-
`context_monitor.py`).
|
| 124 |
-
|
| 125 |
-
Pipe it into `context_monitor.py --from-stdin` 3 times. On the
|
| 126 |
-
third call, ctx should add $TARGET to
|
| 127 |
-
`~/.claude/pending-skills.json` under `graph_suggestions`.
|
| 128 |
-
|
| 129 |
-
```bash
|
| 130 |
-
for i in 1 2 3; do
|
| 131 |
-
echo '{"session_id":"random-load-test","tool_name":"Write",
|
| 132 |
-
"tool_input":{"file_path":"app/<tag-heavy-path>.py",
|
| 133 |
-
"content":"<content with target tags>"}}' \
|
| 134 |
-
| python -m context_monitor --from-stdin
|
| 135 |
-
done
|
| 136 |
-
|
| 137 |
-
cat ~/.claude/pending-skills.json | python -m json.tool | head -30
|
| 138 |
-
```
|
| 139 |
-
|
| 140 |
-
**Expected**: `graph_suggestions` array contains $TARGET with a
|
| 141 |
-
non-empty `shared_tags` list and `score > 0`.
|
| 142 |
-
|
| 143 |
-
### Step 3 — Run skill_suggest.py, verify the suggestion surfaces
|
| 144 |
-
|
| 145 |
-
```bash
|
| 146 |
-
python -m skill_suggest
|
| 147 |
-
```
|
| 148 |
-
|
| 149 |
-
**Expected**: stdout is valid JSON with
|
| 150 |
-
`hookSpecificOutput.additionalContext` containing $TARGET's slug or
|
| 151 |
-
its description. If absent: the graph-walk → suggestion path is
|
| 152 |
-
broken.
|
| 153 |
-
|
| 154 |
-
### Step 4 — Simulate the user accepting the suggestion (skill load)
|
| 155 |
-
|
| 156 |
-
In a live session, Claude would invoke `skill_loader.py load
|
| 157 |
-
$TARGET` here. Simulate by appending the load event:
|
| 158 |
-
|
| 159 |
-
```bash
|
| 160 |
-
python -c "
|
| 161 |
-
import json, uuid
|
| 162 |
-
from pathlib import Path
|
| 163 |
-
from datetime import datetime, timezone
|
| 164 |
-
e = Path.home()/'.claude'/'skill-events.jsonl'
|
| 165 |
-
line = {
|
| 166 |
-
'event': 'load',
|
| 167 |
-
'event_id': uuid.uuid4().hex,
|
| 168 |
-
'meta': {'source':'random-load-test'},
|
| 169 |
-
'session_id': 'random-load-test',
|
| 170 |
-
'skill': '$TARGET',
|
| 171 |
-
'timestamp': datetime.now(timezone.utc).isoformat(),
|
| 172 |
-
}
|
| 173 |
-
with e.open('a') as f: f.write(json.dumps(line)+'\n')
|
| 174 |
-
"
|
| 175 |
-
```
|
| 176 |
-
|
| 177 |
-
**Expected**:
|
| 178 |
-
- `skill-events.jsonl` grew by exactly 1 line with `skill=$TARGET`.
|
| 179 |
-
- Audit log (`ctx-audit.jsonl`) will not yet have a `skill.loaded`
|
| 180 |
-
row — that event is written by the hook Claude Code fires when
|
| 181 |
-
it actually injects the skill. For the simulation we record it
|
| 182 |
-
manually too:
|
| 183 |
-
|
| 184 |
-
```bash
|
| 185 |
-
python -c "from ctx_audit_log import log_skill_event; \
|
| 186 |
-
log_skill_event('skill.loaded','$TARGET', \
|
| 187 |
-
session_id='random-load-test', meta={'via':'sim'})"
|
| 188 |
-
```
|
| 189 |
-
|
| 190 |
-
### Step 5 — Verify the skill is loaded
|
| 191 |
-
|
| 192 |
-
`skill_loader.py` (or its simulation) updates the manifest:
|
| 193 |
-
|
| 194 |
-
```bash
|
| 195 |
-
jq '.load[].skill' ~/.claude/skill-manifest.json | grep -x '"$TARGET"'
|
| 196 |
-
```
|
| 197 |
-
|
| 198 |
-
Plus read it from ctx-monitor's dashboard:
|
| 199 |
-
|
| 200 |
-
```
|
| 201 |
-
curl -s http://127.0.0.1:8765/api/sessions.json | \
|
| 202 |
-
jq '.[] | select(.session_id=="random-load-test")'
|
| 203 |
-
```
|
| 204 |
-
|
| 205 |
-
**Expected**: `skills_loaded` array of the test session includes
|
| 206 |
-
$TARGET.
|
| 207 |
-
|
| 208 |
-
### Step 6 — Force a Stop hook (end-of-session)
|
| 209 |
-
|
| 210 |
-
The Stop hook reads `session_id` from stdin (Claude Code delivers
|
| 211 |
-
the session payload there in production). **Do NOT use `< /dev/null`**
|
| 212 |
-
— it strips the session_id and the `skill.score_updated` audit row
|
| 213 |
-
gets a synthesized id instead of the real one, so the dashboard's
|
| 214 |
-
per-session timeline drops the middle event in the triad.
|
| 215 |
-
|
| 216 |
-
```bash
|
| 217 |
-
SID="random-load-test"
|
| 218 |
-
echo "{\"session_id\":\"$SID\"}" | python hooks/quality_on_session_end.py
|
| 219 |
-
python -m usage_tracker --sync
|
| 220 |
-
```
|
| 221 |
-
|
| 222 |
-
**Expected**:
|
| 223 |
-
- Sidecar for $TARGET now shows `load_count >= 1`,
|
| 224 |
-
`never_loaded=False`, `hard_floor=null`, grade shifted from D
|
| 225 |
-
to something higher (usually C or B).
|
| 226 |
-
- Audit log has a new `skill.score_updated` row with
|
| 227 |
-
`session_id=random-load-test` for $TARGET. Confirm via
|
| 228 |
-
`grep score_updated ~/.claude/ctx-audit.jsonl | tail -1`.
|
| 229 |
-
|
| 230 |
-
### Step 7 — Wait for staleness
|
| 231 |
-
|
| 232 |
-
Run `usage_tracker --sync` two more times without any
|
| 233 |
-
corresponding `used` signal (i.e., no recent intent-log entry for
|
| 234 |
-
the tags that originally surfaced $TARGET). With
|
| 235 |
-
`CTX_STALE_THRESHOLD_SESSIONS=3` and `session_count` bumped on each
|
| 236 |
-
sync, $TARGET should cross the stale threshold on the 3rd sync.
|
| 237 |
-
|
| 238 |
-
```bash
|
| 239 |
-
for i in 1 2 3; do python -m usage_tracker --sync; done
|
| 240 |
-
cat ~/.claude/pending-unload.json | python -m json.tool
|
| 241 |
-
```
|
| 242 |
-
|
| 243 |
-
**Expected**: `pending-unload.json` contains $TARGET with
|
| 244 |
-
`reason: stale session_count=3 use_count=0`.
|
| 245 |
-
|
| 246 |
-
### Step 8 — Simulate user approving the unload
|
| 247 |
-
|
| 248 |
-
```bash
|
| 249 |
-
python -m skill_unload --slug $TARGET --session-id random-load-test
|
| 250 |
-
```
|
| 251 |
-
|
| 252 |
-
(If `skill_unload` CLI isn't wired to the same module, append an
|
| 253 |
-
`unload` event manually — same shape as step 4 with `event=unload`.)
|
| 254 |
-
|
| 255 |
-
**Expected**:
|
| 256 |
-
- `skill-events.jsonl` has an `unload` line for $TARGET.
|
| 257 |
-
- `skill-manifest.json`'s `load[]` no longer contains $TARGET.
|
| 258 |
-
- Audit log gains a `skill.unloaded` row.
|
| 259 |
-
- ctx-monitor `/session/random-load-test` now shows $TARGET in
|
| 260 |
-
both `skills_loaded` AND `skills_unloaded`.
|
| 261 |
-
|
| 262 |
-
### Step 9 — Final verification via dashboard
|
| 263 |
-
|
| 264 |
-
Open `http://127.0.0.1:8765/session/random-load-test` in a browser.
|
| 265 |
-
|
| 266 |
-
The audit timeline must show, in order:
|
| 267 |
-
|
| 268 |
-
1. `skill.loaded` $TARGET
|
| 269 |
-
2. `skill.score_updated` $TARGET (after Stop hook)
|
| 270 |
-
3. `skill.unloaded` $TARGET
|
| 271 |
-
|
| 272 |
-
Screenshot this. That is the end-to-end proof.
|
| 273 |
-
|
| 274 |
-
## Pass / fail criteria
|
| 275 |
-
|
| 276 |
-
- **PASS**: all 9 steps produce the expected on-disk + dashboard
|
| 277 |
-
evidence. The load → stale → unload cycle works.
|
| 278 |
-
- **PARTIAL**: suggestion surfaces but `pending-unload.json` never
|
| 279 |
-
gains an entry (step 7 fails). Staleness detection is broken;
|
| 280 |
-
release but file the issue.
|
| 281 |
-
- **FAIL**: step 5 fails — the skill can be "suggested" but never
|
| 282 |
-
actually reaches the manifest's `load[]` set. The observer is
|
| 283 |
-
blind to real loads. Release blocker — escalate.
|
| 284 |
-
|
| 285 |
-
## Known honest limitations
|
| 286 |
-
|
| 287 |
-
- We can't fully test Claude Code's own load mechanism from a
|
| 288 |
-
simulation — we simulate the load event write. The verification
|
| 289 |
-
is therefore of the ctx half of the contract (suggest → observe →
|
| 290 |
-
queue-for-unload), not the IDE half (inject skill into prompt).
|
| 291 |
-
- `context_monitor` only suggests based on KEYWORD_SIGNALS +
|
| 292 |
-
graph walks. If $TARGET has no tags that match any keyword, the
|
| 293 |
-
suggestion won't surface. The candidate picker in step 1 filters
|
| 294 |
-
on tag richness for that reason.
|
|
|
|
| 1 |
+
# Random load → unload playbook
|
| 2 |
+
|
| 3 |
+
> Pick a skill the user hasn't touched recently, verify ctx suggests
|
| 4 |
+
> loading it, verify the skill actually enters the loaded set, wait
|
| 5 |
+
> for staleness, verify ctx suggests unloading it, verify it actually
|
| 6 |
+
> leaves. Every claim is backed by a concrete file-system observation,
|
| 7 |
+
> not a log-line assumption.
|
| 8 |
+
|
| 9 |
+
## Why this scenario matters
|
| 10 |
+
|
| 11 |
+
Previous playbooks verified the *pipeline* (observer → suggest →
|
| 12 |
+
record → score). This one verifies the **economic** part: skills
|
| 13 |
+
come in and go back out, and the user can observe both halves of
|
| 14 |
+
the cycle. Without this, the "nothing rots" claim in the README is
|
| 15 |
+
untested.
|
| 16 |
+
|
| 17 |
+
## What we'll use
|
| 18 |
+
|
| 19 |
+
- **ctx-monitor** (rc8+) to watch the audit log live via SSE. The
|
| 20 |
+
test agent keeps the dashboard open at
|
| 21 |
+
`http://127.0.0.1:8765/session/<test-session-id>` and screenshots
|
| 22 |
+
the audit timeline before/after.
|
| 23 |
+
- **ctx_audit_log** event stream (`~/.claude/ctx-audit.jsonl`).
|
| 24 |
+
- **skill-events.jsonl** for the ground-truth load/unload record.
|
| 25 |
+
- **pending-unload.json** for the suggest-to-unload signal.
|
| 26 |
+
- **skill_quality explain <slug>** to read the sidecar after each
|
| 27 |
+
phase.
|
| 28 |
+
|
| 29 |
+
## Preconditions
|
| 30 |
+
|
| 31 |
+
1. `claude-ctx` 0.5.0-rc8 installed from PyPI.
|
| 32 |
+
2. `~/.claude/skill-wiki/` pre-built (2,253 nodes, 454K edges).
|
| 33 |
+
3. `~/.claude/skills/` has ≥ 1,500 skills installed.
|
| 34 |
+
4. `~/.claude/settings.json` has all rc7 hooks wired
|
| 35 |
+
(PostToolUse: context_monitor + skill_add_detector + skill_suggest
|
| 36 |
+
+ backup_on_change; Stop: usage_tracker + quality_on_session_end).
|
| 37 |
+
5. Stale-threshold override for the test run. Write it into
|
| 38 |
+
`~/.claude/skill-system-config.json` — there is no env var
|
| 39 |
+
shortcut; the threshold only comes from config:
|
| 40 |
+
```bash
|
| 41 |
+
python -c "
|
| 42 |
+
import json, os
|
| 43 |
+
from pathlib import Path
|
| 44 |
+
p = Path(os.path.expanduser('~/.claude/skill-system-config.json'))
|
| 45 |
+
cfg = json.loads(p.read_text()) if p.exists() else {}
|
| 46 |
+
cfg.setdefault('usage_tracker', {})['stale_threshold_sessions'] = 3
|
| 47 |
+
p.write_text(json.dumps(cfg, indent=2))
|
| 48 |
+
"
|
| 49 |
+
```
|
| 50 |
+
Default is 30 — too slow to observe in one sitting.
|
| 51 |
+
6. `ctx-monitor serve --port 8765` running in a background tab.
|
| 52 |
+
|
| 53 |
+
## The scenario
|
| 54 |
+
|
| 55 |
+
### Step 1 — Pick a random candidate
|
| 56 |
+
|
| 57 |
+
Pick a skill whose sidecar has:
|
| 58 |
+
- `hard_floor: "never_loaded_stale"` — these all map to **grade D**
|
| 59 |
+
(grade F is reserved for `intake_fail`), AND
|
| 60 |
+
- `intake.score >= 0.8` (structurally valid), AND
|
| 61 |
+
- **tag overlap with `context_monitor.KEYWORD_SIGNALS`** — otherwise
|
| 62 |
+
the skill can never surface through the observe→suggest path
|
| 63 |
+
(learned the hard way on rc8's verification run), AND
|
| 64 |
+
- not a meta-skill (`skill-router`, `file-reading`, etc.).
|
| 65 |
+
|
| 66 |
+
```bash
|
| 67 |
+
python - <<'PY'
|
| 68 |
+
import json, random, re
|
| 69 |
+
from pathlib import Path
|
| 70 |
+
|
| 71 |
+
# Seed: installed KEYWORD_SIGNALS from context_monitor.
|
| 72 |
+
# Load dynamically to survive future vocabulary changes.
|
| 73 |
+
import importlib.util
|
| 74 |
+
src = Path.home() / ".claude" / "skills" # may differ per install
|
| 75 |
+
spec_path = None
|
| 76 |
+
for candidate in [
|
| 77 |
+
Path(__file__).resolve().parents[1] / "src" / "context_monitor.py",
|
| 78 |
+
Path.home() / ".local" / "lib" / "python3.11" / "site-packages" / "context_monitor.py",
|
| 79 |
+
]:
|
| 80 |
+
if candidate.exists():
|
| 81 |
+
spec_path = candidate; break
|
| 82 |
+
spec = importlib.util.spec_from_file_location("_cm", spec_path)
|
| 83 |
+
cm = importlib.util.module_from_spec(spec); spec.loader.exec_module(cm)
|
| 84 |
+
keywords = set(cm.KEYWORD_SIGNALS.keys())
|
| 85 |
+
|
| 86 |
+
sidecar_dir = Path.home() / ".claude" / "skill-quality"
|
| 87 |
+
candidates: list[str] = []
|
| 88 |
+
for p in sidecar_dir.glob("*.json"):
|
| 89 |
+
if p.name.startswith(".") or p.name.endswith(".lifecycle.json"):
|
| 90 |
+
continue
|
| 91 |
+
try:
|
| 92 |
+
sc = json.loads(p.read_text())
|
| 93 |
+
except Exception:
|
| 94 |
+
continue
|
| 95 |
+
if sc.get("hard_floor") != "never_loaded_stale" or sc.get("grade") != "D":
|
| 96 |
+
continue
|
| 97 |
+
intake = (sc.get("signals") or {}).get("intake", {}) or {}
|
| 98 |
+
if intake.get("score", 0) < 0.8:
|
| 99 |
+
continue
|
| 100 |
+
slug = sc["slug"]
|
| 101 |
+
if slug in {"skill-router", "file-reading", "context-monitor"}:
|
| 102 |
+
continue
|
| 103 |
+
# Require ≥2 tag tokens in the slug that also appear as KEYWORD_SIGNALS
|
| 104 |
+
slug_tokens = set(re.split(r"[^a-z0-9]+", slug.lower()))
|
| 105 |
+
if len(slug_tokens & keywords) >= 2:
|
| 106 |
+
candidates.append(slug)
|
| 107 |
+
|
| 108 |
+
random.shuffle(candidates)
|
| 109 |
+
print(candidates[0] if candidates else "NONE_FOUND")
|
| 110 |
+
PY
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
Record the picked slug. Call it `$TARGET`.
|
| 114 |
+
|
| 115 |
+
**Expected**: $TARGET has `grade=D`, `load_count=0`,
|
| 116 |
+
`never_loaded=True`, `hard_floor=never_loaded_stale`.
|
| 117 |
+
|
| 118 |
+
### Step 2 — Inject a stack signal that should surface $TARGET
|
| 119 |
+
|
| 120 |
+
Look at the target skill's `tags`. Synthesize a PostToolUse payload
|
| 121 |
+
whose `tool_input.file_path` or content contains 3+ of those tags
|
| 122 |
+
(crossing the `UNMATCHED_SIGNAL_THRESHOLD` in
|
| 123 |
+
`context_monitor.py`).
|
| 124 |
+
|
| 125 |
+
Pipe it into `context_monitor.py --from-stdin` 3 times. On the
|
| 126 |
+
third call, ctx should add $TARGET to
|
| 127 |
+
`~/.claude/pending-skills.json` under `graph_suggestions`.
|
| 128 |
+
|
| 129 |
+
```bash
|
| 130 |
+
for i in 1 2 3; do
|
| 131 |
+
echo '{"session_id":"random-load-test","tool_name":"Write",
|
| 132 |
+
"tool_input":{"file_path":"app/<tag-heavy-path>.py",
|
| 133 |
+
"content":"<content with target tags>"}}' \
|
| 134 |
+
| python -m context_monitor --from-stdin
|
| 135 |
+
done
|
| 136 |
+
|
| 137 |
+
cat ~/.claude/pending-skills.json | python -m json.tool | head -30
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
+
**Expected**: `graph_suggestions` array contains $TARGET with a
|
| 141 |
+
non-empty `shared_tags` list and `score > 0`.
|
| 142 |
+
|
| 143 |
+
### Step 3 — Run skill_suggest.py, verify the suggestion surfaces
|
| 144 |
+
|
| 145 |
+
```bash
|
| 146 |
+
python -m skill_suggest
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
**Expected**: stdout is valid JSON with
|
| 150 |
+
`hookSpecificOutput.additionalContext` containing $TARGET's slug or
|
| 151 |
+
its description. If absent: the graph-walk → suggestion path is
|
| 152 |
+
broken.
|
| 153 |
+
|
| 154 |
+
### Step 4 — Simulate the user accepting the suggestion (skill load)
|
| 155 |
+
|
| 156 |
+
In a live session, Claude would invoke `skill_loader.py load
|
| 157 |
+
$TARGET` here. Simulate by appending the load event:
|
| 158 |
+
|
| 159 |
+
```bash
|
| 160 |
+
python -c "
|
| 161 |
+
import json, uuid
|
| 162 |
+
from pathlib import Path
|
| 163 |
+
from datetime import datetime, timezone
|
| 164 |
+
e = Path.home()/'.claude'/'skill-events.jsonl'
|
| 165 |
+
line = {
|
| 166 |
+
'event': 'load',
|
| 167 |
+
'event_id': uuid.uuid4().hex,
|
| 168 |
+
'meta': {'source':'random-load-test'},
|
| 169 |
+
'session_id': 'random-load-test',
|
| 170 |
+
'skill': '$TARGET',
|
| 171 |
+
'timestamp': datetime.now(timezone.utc).isoformat(),
|
| 172 |
+
}
|
| 173 |
+
with e.open('a') as f: f.write(json.dumps(line)+'\n')
|
| 174 |
+
"
|
| 175 |
+
```
|
| 176 |
+
|
| 177 |
+
**Expected**:
|
| 178 |
+
- `skill-events.jsonl` grew by exactly 1 line with `skill=$TARGET`.
|
| 179 |
+
- Audit log (`ctx-audit.jsonl`) will not yet have a `skill.loaded`
|
| 180 |
+
row — that event is written by the hook Claude Code fires when
|
| 181 |
+
it actually injects the skill. For the simulation we record it
|
| 182 |
+
manually too:
|
| 183 |
+
|
| 184 |
+
```bash
|
| 185 |
+
python -c "from ctx_audit_log import log_skill_event; \
|
| 186 |
+
log_skill_event('skill.loaded','$TARGET', \
|
| 187 |
+
session_id='random-load-test', meta={'via':'sim'})"
|
| 188 |
+
```
|
| 189 |
+
|
| 190 |
+
### Step 5 — Verify the skill is loaded
|
| 191 |
+
|
| 192 |
+
`skill_loader.py` (or its simulation) updates the manifest:
|
| 193 |
+
|
| 194 |
+
```bash
|
| 195 |
+
jq '.load[].skill' ~/.claude/skill-manifest.json | grep -x '"$TARGET"'
|
| 196 |
+
```
|
| 197 |
+
|
| 198 |
+
Plus read it from ctx-monitor's dashboard:
|
| 199 |
+
|
| 200 |
+
```
|
| 201 |
+
curl -s http://127.0.0.1:8765/api/sessions.json | \
|
| 202 |
+
jq '.[] | select(.session_id=="random-load-test")'
|
| 203 |
+
```
|
| 204 |
+
|
| 205 |
+
**Expected**: `skills_loaded` array of the test session includes
|
| 206 |
+
$TARGET.
|
| 207 |
+
|
| 208 |
+
### Step 6 — Force a Stop hook (end-of-session)
|
| 209 |
+
|
| 210 |
+
The Stop hook reads `session_id` from stdin (Claude Code delivers
|
| 211 |
+
the session payload there in production). **Do NOT use `< /dev/null`**
|
| 212 |
+
— it strips the session_id and the `skill.score_updated` audit row
|
| 213 |
+
gets a synthesized id instead of the real one, so the dashboard's
|
| 214 |
+
per-session timeline drops the middle event in the triad.
|
| 215 |
+
|
| 216 |
+
```bash
|
| 217 |
+
SID="random-load-test"
|
| 218 |
+
echo "{\"session_id\":\"$SID\"}" | python hooks/quality_on_session_end.py
|
| 219 |
+
python -m usage_tracker --sync
|
| 220 |
+
```
|
| 221 |
+
|
| 222 |
+
**Expected**:
|
| 223 |
+
- Sidecar for $TARGET now shows `load_count >= 1`,
|
| 224 |
+
`never_loaded=False`, `hard_floor=null`, grade shifted from D
|
| 225 |
+
to something higher (usually C or B).
|
| 226 |
+
- Audit log has a new `skill.score_updated` row with
|
| 227 |
+
`session_id=random-load-test` for $TARGET. Confirm via
|
| 228 |
+
`grep score_updated ~/.claude/ctx-audit.jsonl | tail -1`.
|
| 229 |
+
|
| 230 |
+
### Step 7 — Wait for staleness
|
| 231 |
+
|
| 232 |
+
Run `usage_tracker --sync` two more times without any
|
| 233 |
+
corresponding `used` signal (i.e., no recent intent-log entry for
|
| 234 |
+
the tags that originally surfaced $TARGET). With
|
| 235 |
+
`CTX_STALE_THRESHOLD_SESSIONS=3` and `session_count` bumped on each
|
| 236 |
+
sync, $TARGET should cross the stale threshold on the 3rd sync.
|
| 237 |
+
|
| 238 |
+
```bash
|
| 239 |
+
for i in 1 2 3; do python -m usage_tracker --sync; done
|
| 240 |
+
cat ~/.claude/pending-unload.json | python -m json.tool
|
| 241 |
+
```
|
| 242 |
+
|
| 243 |
+
**Expected**: `pending-unload.json` contains $TARGET with
|
| 244 |
+
`reason: stale session_count=3 use_count=0`.
|
| 245 |
+
|
| 246 |
+
### Step 8 — Simulate user approving the unload
|
| 247 |
+
|
| 248 |
+
```bash
|
| 249 |
+
python -m skill_unload --slug $TARGET --session-id random-load-test
|
| 250 |
+
```
|
| 251 |
+
|
| 252 |
+
(If `skill_unload` CLI isn't wired to the same module, append an
|
| 253 |
+
`unload` event manually — same shape as step 4 with `event=unload`.)
|
| 254 |
+
|
| 255 |
+
**Expected**:
|
| 256 |
+
- `skill-events.jsonl` has an `unload` line for $TARGET.
|
| 257 |
+
- `skill-manifest.json`'s `load[]` no longer contains $TARGET.
|
| 258 |
+
- Audit log gains a `skill.unloaded` row.
|
| 259 |
+
- ctx-monitor `/session/random-load-test` now shows $TARGET in
|
| 260 |
+
both `skills_loaded` AND `skills_unloaded`.
|
| 261 |
+
|
| 262 |
+
### Step 9 — Final verification via dashboard
|
| 263 |
+
|
| 264 |
+
Open `http://127.0.0.1:8765/session/random-load-test` in a browser.
|
| 265 |
+
|
| 266 |
+
The audit timeline must show, in order:
|
| 267 |
+
|
| 268 |
+
1. `skill.loaded` $TARGET
|
| 269 |
+
2. `skill.score_updated` $TARGET (after Stop hook)
|
| 270 |
+
3. `skill.unloaded` $TARGET
|
| 271 |
+
|
| 272 |
+
Screenshot this. That is the end-to-end proof.
|
| 273 |
+
|
| 274 |
+
## Pass / fail criteria
|
| 275 |
+
|
| 276 |
+
- **PASS**: all 9 steps produce the expected on-disk + dashboard
|
| 277 |
+
evidence. The load → stale → unload cycle works.
|
| 278 |
+
- **PARTIAL**: suggestion surfaces but `pending-unload.json` never
|
| 279 |
+
gains an entry (step 7 fails). Staleness detection is broken;
|
| 280 |
+
release but file the issue.
|
| 281 |
+
- **FAIL**: step 5 fails — the skill can be "suggested" but never
|
| 282 |
+
actually reaches the manifest's `load[]` set. The observer is
|
| 283 |
+
blind to real loads. Release blocker — escalate.
|
| 284 |
+
|
| 285 |
+
## Known honest limitations
|
| 286 |
+
|
| 287 |
+
- We can't fully test Claude Code's own load mechanism from a
|
| 288 |
+
simulation — we simulate the load event write. The verification
|
| 289 |
+
is therefore of the ctx half of the contract (suggest → observe →
|
| 290 |
+
queue-for-unload), not the IDE half (inject skill into prompt).
|
| 291 |
+
- `context_monitor` only suggests based on KEYWORD_SIGNALS +
|
| 292 |
+
graph walks. If $TARGET has no tags that match any keyword, the
|
| 293 |
+
suggestion won't surface. The candidate picker in step 1 filters
|
| 294 |
+
on tag richness for that reason.
|
internal/playbooks/playbook-real-world.md
CHANGED
|
@@ -1,274 +1,274 @@
|
|
| 1 |
-
# Real-world ctx playbook
|
| 2 |
-
|
| 3 |
-
> Canonical end-to-end scenario exercising every ctx surface: scan → graph
|
| 4 |
-
> suggest → skill load/unload → toolbox council → skill_add → lifecycle
|
| 5 |
-
> archive → KPI. Assumes the user's environment already has the graph
|
| 6 |
-
> (`~/.claude/skill-wiki/graphify-out/graph.json`) and wiki
|
| 7 |
-
> (`~/.claude/skill-wiki/`) **pre-built** — we do NOT rebuild in this
|
| 8 |
-
> playbook.
|
| 9 |
-
|
| 10 |
-
## Persona
|
| 11 |
-
|
| 12 |
-
**Maya** — senior backend engineer at a B2C fintech. Installing `claude-ctx`
|
| 13 |
-
fresh. First project on ctx: a **PCI-compliant checkout microservice**
|
| 14 |
-
(FastAPI + SQLAlchemy + PostgreSQL + Stripe + pytest). Target: working
|
| 15 |
-
endpoint + council-signed commit by end of day.
|
| 16 |
-
|
| 17 |
-
She has `~/.claude/skills/` with 1,789 skills and `~/.claude/agents/`
|
| 18 |
-
with 464 agents pre-installed (extracted from `graph/wiki-graph.tar.gz`).
|
| 19 |
-
Graph is pre-built (2,253 nodes / 454K edges / 93 communities). She has
|
| 20 |
-
never run ctx before.
|
| 21 |
-
|
| 22 |
-
## Environment precondition
|
| 23 |
-
|
| 24 |
-
```
|
| 25 |
-
~/.claude/skill-wiki/graphify-out/graph.json # pre-built, 454K edges
|
| 26 |
-
~/.claude/skill-wiki/entities/ # 2,253 entity pages
|
| 27 |
-
~/.claude/skill-wiki/converted/ # 952 compressed skills
|
| 28 |
-
~/.claude/skill-quality/ # 1,891 sidecars
|
| 29 |
-
```
|
| 30 |
-
|
| 31 |
-
`pip install claude-ctx` is done. The four console scripts are on PATH.
|
| 32 |
-
|
| 33 |
-
---
|
| 34 |
-
|
| 35 |
-
## Phase 1 — Project bootstrap + first stack scan
|
| 36 |
-
|
| 37 |
-
```bash
|
| 38 |
-
mkdir ~/work/checkout-svc && cd ~/work/checkout-svc
|
| 39 |
-
git init
|
| 40 |
-
cat > requirements.txt <<EOF
|
| 41 |
-
fastapi
|
| 42 |
-
sqlalchemy
|
| 43 |
-
psycopg2-binary
|
| 44 |
-
pydantic
|
| 45 |
-
stripe
|
| 46 |
-
pytest
|
| 47 |
-
EOF
|
| 48 |
-
echo "app" > .gitignore
|
| 49 |
-
mkdir -p app tests
|
| 50 |
-
```
|
| 51 |
-
|
| 52 |
-
Maya runs:
|
| 53 |
-
|
| 54 |
-
```bash
|
| 55 |
-
ctx-scan-repo --repo . --output .ctx/stack.json
|
| 56 |
-
```
|
| 57 |
-
|
| 58 |
-
**Expected ctx behavior**
|
| 59 |
-
1. `scan_repo` detects: python / fastapi / sqlalchemy / pytest /
|
| 60 |
-
stripe / postgres (from `psycopg2-binary` signature).
|
| 61 |
-
2. `resolve_skills` walks the **pre-built graph** from those stack tags
|
| 62 |
-
and recommends ~10–15 skills:
|
| 63 |
-
- direct/fuzzy matches: `fastapi-pro`, `python-patterns`,
|
| 64 |
-
`python-fastapi-development`, `pydantic-models-py`,
|
| 65 |
-
`stripe-integration`, `payment-integration`, `pci-compliance`,
|
| 66 |
-
`postgresql-optimization`
|
| 67 |
-
- graph neighbors (edge-weight ≥ 1.5): `test-automator`,
|
| 68 |
-
`python-pro`, `async-python-patterns`, `backend-security-coder`,
|
| 69 |
-
`api-security-best-practices`
|
| 70 |
-
|
| 71 |
-
**Verification**
|
| 72 |
-
- Manifest has 10–15 `load` entries with mixed `reason` fields:
|
| 73 |
-
`fuzzy match for detected stack 'fastapi'`, `graph neighbor of ...`.
|
| 74 |
-
- No warnings for "not installed" when fuzzy fallback found an alternative.
|
| 75 |
-
|
| 76 |
-
---
|
| 77 |
-
|
| 78 |
-
## Phase 2 — Claude session starts; context monitor observes
|
| 79 |
-
|
| 80 |
-
Maya launches Claude Code in `~/work/checkout-svc/`. `PostToolUse` hooks
|
| 81 |
-
fire on every tool call; `Stop` fires at session end.
|
| 82 |
-
|
| 83 |
-
Maya asks Claude: *"scaffold the checkout endpoint with Stripe payment
|
| 84 |
-
intents".*
|
| 85 |
-
|
| 86 |
-
**Expected ctx behavior during the session**
|
| 87 |
-
1. **PostToolUse** fires `context_monitor.py --from-stdin` on every
|
| 88 |
-
tool call. The monitor reads the tool input, detects signals:
|
| 89 |
-
- file path `app/api/checkout.py` → stack signal `python`, `fastapi`
|
| 90 |
-
- content containing `stripe.PaymentIntent` → new signal `stripe`
|
| 91 |
-
2. When an unmatched signal accumulates past threshold (3 by default),
|
| 92 |
-
`context_monitor` writes to `~/.claude/pending-skills.json` and
|
| 93 |
-
`skill_suggest.py` surfaces it to Claude's context as a
|
| 94 |
-
`hookSpecificOutput.additionalContext` blob.
|
| 95 |
-
3. Claude reads the suggestion ("You may want to load `stripe-integration`
|
| 96 |
-
and `pci-compliance`") and asks Maya to confirm.
|
| 97 |
-
4. Maya says *"yes, load pci-compliance"*. Claude loads it via its
|
| 98 |
-
normal skill-load mechanism; an event lands in `skill-events.jsonl`:
|
| 99 |
-
`{"event": "load", "skill": "pci-compliance", ...}`.
|
| 100 |
-
5. The quality sidecar for `pci-compliance` increments `load_count`;
|
| 101 |
-
`telemetry` score rises on next recompute.
|
| 102 |
-
|
| 103 |
-
**Verification**
|
| 104 |
-
- `tail -1 ~/.claude/skill-events.jsonl` shows the new load event.
|
| 105 |
-
- `ctx-skill-quality explain pci-compliance` shows `load_count ≥ 1`,
|
| 106 |
-
`never_loaded: False`, floor cleared, grade improved.
|
| 107 |
-
|
| 108 |
-
---
|
| 109 |
-
|
| 110 |
-
## Phase 3 — First real feature + live suggestion cycle
|
| 111 |
-
|
| 112 |
-
Maya writes `app/api/checkout.py`:
|
| 113 |
-
|
| 114 |
-
```python
|
| 115 |
-
from fastapi import APIRouter, HTTPException
|
| 116 |
-
import stripe
|
| 117 |
-
from app.schemas import CheckoutRequest, CheckoutResponse
|
| 118 |
-
|
| 119 |
-
router = APIRouter()
|
| 120 |
-
|
| 121 |
-
@router.post("/checkout", response_model=CheckoutResponse)
|
| 122 |
-
async def create_checkout(req: CheckoutRequest) -> CheckoutResponse:
|
| 123 |
-
intent = stripe.PaymentIntent.create(
|
| 124 |
-
amount=req.amount_cents, currency="usd",
|
| 125 |
-
metadata={"user_id": req.user_id},
|
| 126 |
-
)
|
| 127 |
-
return CheckoutResponse(client_secret=intent.client_secret)
|
| 128 |
-
```
|
| 129 |
-
|
| 130 |
-
She runs `pytest` (no tests yet) → exits 0 (no-op). She realizes she
|
| 131 |
-
needs test coverage.
|
| 132 |
-
|
| 133 |
-
**Expected ctx behavior**
|
| 134 |
-
1. Editing files under `tests/` triggers `context_monitor` to detect
|
| 135 |
-
the `testing` signal.
|
| 136 |
-
2. `skill_suggest` surfaces `test-driven-development`,
|
| 137 |
-
`python-testing`, `pytest-patterns` from the graph.
|
| 138 |
-
3. Maya loads `python-testing`. Sidecar updates.
|
| 139 |
-
|
| 140 |
-
---
|
| 141 |
-
|
| 142 |
-
## Phase 4 — Pre-commit council (toolbox run)
|
| 143 |
-
|
| 144 |
-
Before committing, Maya wants a security review. She has `toolbox init`
|
| 145 |
-
output 5 starter toolboxes. She activates `security-sweep`:
|
| 146 |
-
|
| 147 |
-
```bash
|
| 148 |
-
ctx-toolbox activate security-sweep
|
| 149 |
-
ctx-toolbox run --event pre-commit
|
| 150 |
-
```
|
| 151 |
-
|
| 152 |
-
**Expected ctx behavior**
|
| 153 |
-
1. `toolbox.py run` reads the active toolbox config.
|
| 154 |
-
2. Council is assembled: `security-reviewer`, `security-auditor`,
|
| 155 |
-
`penetration-tester`, `compliance-auditor`,
|
| 156 |
-
`threat-detection-engineer`.
|
| 157 |
-
3. `council_runner.py` builds a `RunPlan` with scope=`diff` (files
|
| 158 |
-
changed since last commit), budget=300K tokens, guardrail=True.
|
| 159 |
-
4. Claude Code picks up the plan, dispatches each agent, collects
|
| 160 |
-
findings.
|
| 161 |
-
5. `toolbox_verdict.py` merges findings by stable id, escalates level.
|
| 162 |
-
6. If any HIGH/CRITICAL finding exists, `run --event pre-commit`
|
| 163 |
-
exits 2 → blocks `git commit`.
|
| 164 |
-
|
| 165 |
-
**Expected finding** (realistic): `security-reviewer` flags the
|
| 166 |
-
checkout endpoint lacks webhook signature verification and Stripe key
|
| 167 |
-
is read from env but never validated as non-empty → MEDIUM. No block.
|
| 168 |
-
|
| 169 |
-
---
|
| 170 |
-
|
| 171 |
-
## Phase 5 — Custom skill for the domain (skill_add)
|
| 172 |
-
|
| 173 |
-
Maya realizes her team reuses the same `PaymentIntent` error-mapping
|
| 174 |
-
pattern across 3 services. She wants to capture it as a custom skill.
|
| 175 |
-
|
| 176 |
-
```bash
|
| 177 |
-
mkdir -p .skills/stripe-error-mapping
|
| 178 |
-
cat > .skills/stripe-error-mapping/SKILL.md <<EOF
|
| 179 |
-
---
|
| 180 |
-
name: stripe-error-mapping
|
| 181 |
-
description: Canonical Stripe API error → domain exception mapping for fintech backends
|
| 182 |
-
tags: [stripe, payments, error-handling, pci]
|
| 183 |
-
---
|
| 184 |
-
|
| 185 |
-
# Stripe error mapping
|
| 186 |
-
|
| 187 |
-
## When to use
|
| 188 |
-
Whenever a service integrates with Stripe's PaymentIntent, Charge, or
|
| 189 |
-
Setup Intent APIs. This skill ensures every Stripe error (rate-limit,
|
| 190 |
-
card-declined, authentication, API connection, idempotency) maps to
|
| 191 |
-
a stable domain exception with an actionable error code.
|
| 192 |
-
|
| 193 |
-
## Mapping table
|
| 194 |
-
|
| 195 |
-
| Stripe error class | Domain exception | HTTP status |
|
| 196 |
-
| ... |
|
| 197 |
-
|
| 198 |
-
EOF
|
| 199 |
-
|
| 200 |
-
ctx-skill-quality recompute stripe-error-mapping # will fail — not yet installed
|
| 201 |
-
# Install path:
|
| 202 |
-
python -m skill_add --skill-path .skills/stripe-error-mapping/SKILL.md
|
| 203 |
-
```
|
| 204 |
-
|
| 205 |
-
**Expected ctx behavior**
|
| 206 |
-
1. `skill_add` runs the intake gate (`intake_gate.py`):
|
| 207 |
-
frontmatter-present, has-description, body-long-enough, has-H2.
|
| 208 |
-
2. Similarity check against existing skills via embedding backend
|
| 209 |
-
(falls back to structural-only if sentence-transformers missing).
|
| 210 |
-
3. If novel: writes `~/.claude/skills/stripe-error-mapping/SKILL.md`,
|
| 211 |
-
adds entity page at
|
| 212 |
-
`~/.claude/skill-wiki/entities/skills/stripe-error-mapping.md`
|
| 213 |
-
with frontmatter (tags, use_count=0, last_used=null, status=installed).
|
| 214 |
-
4. Returns success: manifest counter `1,579 → 1,580`.
|
| 215 |
-
|
| 216 |
-
**Post-add follow-ups**
|
| 217 |
-
- Graph rebuild required to include the new skill as a node with edges
|
| 218 |
-
to `stripe`, `payments`, `pci` tag communities.
|
| 219 |
-
- `ctx-skill-quality recompute stripe-error-mapping` seeds the sidecar.
|
| 220 |
-
|
| 221 |
-
---
|
| 222 |
-
|
| 223 |
-
## Phase 6 — Session end + lifecycle pruning
|
| 224 |
-
|
| 225 |
-
End of day. Claude's `Stop` hook fires:
|
| 226 |
-
1. `usage_tracker.py --sync` updates skill usage stats from
|
| 227 |
-
`skill-events.jsonl`.
|
| 228 |
-
2. `hooks/quality_on_session_end.py` recomputes sidecars for only
|
| 229 |
-
the slugs touched this session (incremental).
|
| 230 |
-
3. `ctx_lifecycle` reviews sidecars; any skill that sat in `_demoted`
|
| 231 |
-
past the 14-day archive threshold is moved to `_archive`.
|
| 232 |
-
|
| 233 |
-
Maya runs:
|
| 234 |
-
|
| 235 |
-
```bash
|
| 236 |
-
ctx-toolbox status
|
| 237 |
-
python -m kpi_dashboard render
|
| 238 |
-
open ~/.claude/skill-quality/kpi.md
|
| 239 |
-
```
|
| 240 |
-
|
| 241 |
-
She sees:
|
| 242 |
-
- Grade distribution (A: 2, B: 18, C: 240, D: 1320, F: 311).
|
| 243 |
-
- Hard-floor reasons.
|
| 244 |
-
- Top demotion candidates. Skills she never used in 30 days get
|
| 245 |
-
auto-archived next tick.
|
| 246 |
-
|
| 247 |
-
Optionally she launches the claude-mem web monitor:
|
| 248 |
-
|
| 249 |
-
```bash
|
| 250 |
-
npx claude-mem start
|
| 251 |
-
# browser opens http://localhost:37777
|
| 252 |
-
```
|
| 253 |
-
|
| 254 |
-
---
|
| 255 |
-
|
| 256 |
-
## Success criteria (what "good" looks like at end of day)
|
| 257 |
-
|
| 258 |
-
| Check | Pass when |
|
| 259 |
-
|---|---|
|
| 260 |
-
| Phase 1 manifest | 10–15 loads, mixed fuzzy + graph-neighbor reasons |
|
| 261 |
-
| Phase 2 events log | Every Claude tool call produced a PostToolUse invocation |
|
| 262 |
-
| Phase 3 suggest | `pending-skills.json` gained ≥ 1 new entry for Stripe |
|
| 263 |
-
| Phase 4 verdict | Council runs, findings file written, exits 0 or 2 cleanly |
|
| 264 |
-
| Phase 5 skill_add | New skill appears in skills dir + wiki; dedup fired |
|
| 265 |
-
| Phase 6 KPI | `kpi.md` reflects today's sessions; archived skills moved |
|
| 266 |
-
|
| 267 |
-
## Known gaps this playbook will surface
|
| 268 |
-
|
| 269 |
-
- `wiki_sync` has no drift detection (skill edits don't re-sync wiki).
|
| 270 |
-
- `batch_convert` hash-gated idempotency looks like no-op on re-run.
|
| 271 |
-
- `scan_repo` doesn't detect pytest from pyproject `[dev]` deps.
|
| 272 |
-
- `skill_add` CLI raises false `BODY_MISSING_H2` — in-process API works.
|
| 273 |
-
|
| 274 |
-
Each gap is tracked as a separate issue and will be fixed post-playbook.
|
|
|
|
| 1 |
+
# Real-world ctx playbook
|
| 2 |
+
|
| 3 |
+
> Canonical end-to-end scenario exercising every ctx surface: scan → graph
|
| 4 |
+
> suggest → skill load/unload → toolbox council → skill_add → lifecycle
|
| 5 |
+
> archive → KPI. Assumes the user's environment already has the graph
|
| 6 |
+
> (`~/.claude/skill-wiki/graphify-out/graph.json`) and wiki
|
| 7 |
+
> (`~/.claude/skill-wiki/`) **pre-built** — we do NOT rebuild in this
|
| 8 |
+
> playbook.
|
| 9 |
+
|
| 10 |
+
## Persona
|
| 11 |
+
|
| 12 |
+
**Maya** — senior backend engineer at a B2C fintech. Installing `claude-ctx`
|
| 13 |
+
fresh. First project on ctx: a **PCI-compliant checkout microservice**
|
| 14 |
+
(FastAPI + SQLAlchemy + PostgreSQL + Stripe + pytest). Target: working
|
| 15 |
+
endpoint + council-signed commit by end of day.
|
| 16 |
+
|
| 17 |
+
She has `~/.claude/skills/` with 1,789 skills and `~/.claude/agents/`
|
| 18 |
+
with 464 agents pre-installed (extracted from `graph/wiki-graph.tar.gz`).
|
| 19 |
+
Graph is pre-built (2,253 nodes / 454K edges / 93 communities). She has
|
| 20 |
+
never run ctx before.
|
| 21 |
+
|
| 22 |
+
## Environment precondition
|
| 23 |
+
|
| 24 |
+
```
|
| 25 |
+
~/.claude/skill-wiki/graphify-out/graph.json # pre-built, 454K edges
|
| 26 |
+
~/.claude/skill-wiki/entities/ # 2,253 entity pages
|
| 27 |
+
~/.claude/skill-wiki/converted/ # 952 compressed skills
|
| 28 |
+
~/.claude/skill-quality/ # 1,891 sidecars
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
`pip install claude-ctx` is done. The four console scripts are on PATH.
|
| 32 |
+
|
| 33 |
+
---
|
| 34 |
+
|
| 35 |
+
## Phase 1 — Project bootstrap + first stack scan
|
| 36 |
+
|
| 37 |
+
```bash
|
| 38 |
+
mkdir ~/work/checkout-svc && cd ~/work/checkout-svc
|
| 39 |
+
git init
|
| 40 |
+
cat > requirements.txt <<EOF
|
| 41 |
+
fastapi
|
| 42 |
+
sqlalchemy
|
| 43 |
+
psycopg2-binary
|
| 44 |
+
pydantic
|
| 45 |
+
stripe
|
| 46 |
+
pytest
|
| 47 |
+
EOF
|
| 48 |
+
echo "app" > .gitignore
|
| 49 |
+
mkdir -p app tests
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
Maya runs:
|
| 53 |
+
|
| 54 |
+
```bash
|
| 55 |
+
ctx-scan-repo --repo . --output .ctx/stack.json
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
**Expected ctx behavior**
|
| 59 |
+
1. `scan_repo` detects: python / fastapi / sqlalchemy / pytest /
|
| 60 |
+
stripe / postgres (from `psycopg2-binary` signature).
|
| 61 |
+
2. `resolve_skills` walks the **pre-built graph** from those stack tags
|
| 62 |
+
and recommends ~10–15 skills:
|
| 63 |
+
- direct/fuzzy matches: `fastapi-pro`, `python-patterns`,
|
| 64 |
+
`python-fastapi-development`, `pydantic-models-py`,
|
| 65 |
+
`stripe-integration`, `payment-integration`, `pci-compliance`,
|
| 66 |
+
`postgresql-optimization`
|
| 67 |
+
- graph neighbors (edge-weight ≥ 1.5): `test-automator`,
|
| 68 |
+
`python-pro`, `async-python-patterns`, `backend-security-coder`,
|
| 69 |
+
`api-security-best-practices`
|
| 70 |
+
|
| 71 |
+
**Verification**
|
| 72 |
+
- Manifest has 10–15 `load` entries with mixed `reason` fields:
|
| 73 |
+
`fuzzy match for detected stack 'fastapi'`, `graph neighbor of ...`.
|
| 74 |
+
- No warnings for "not installed" when fuzzy fallback found an alternative.
|
| 75 |
+
|
| 76 |
+
---
|
| 77 |
+
|
| 78 |
+
## Phase 2 — Claude session starts; context monitor observes
|
| 79 |
+
|
| 80 |
+
Maya launches Claude Code in `~/work/checkout-svc/`. `PostToolUse` hooks
|
| 81 |
+
fire on every tool call; `Stop` fires at session end.
|
| 82 |
+
|
| 83 |
+
Maya asks Claude: *"scaffold the checkout endpoint with Stripe payment
|
| 84 |
+
intents".*
|
| 85 |
+
|
| 86 |
+
**Expected ctx behavior during the session**
|
| 87 |
+
1. **PostToolUse** fires `context_monitor.py --from-stdin` on every
|
| 88 |
+
tool call. The monitor reads the tool input, detects signals:
|
| 89 |
+
- file path `app/api/checkout.py` → stack signal `python`, `fastapi`
|
| 90 |
+
- content containing `stripe.PaymentIntent` → new signal `stripe`
|
| 91 |
+
2. When an unmatched signal accumulates past threshold (3 by default),
|
| 92 |
+
`context_monitor` writes to `~/.claude/pending-skills.json` and
|
| 93 |
+
`skill_suggest.py` surfaces it to Claude's context as a
|
| 94 |
+
`hookSpecificOutput.additionalContext` blob.
|
| 95 |
+
3. Claude reads the suggestion ("You may want to load `stripe-integration`
|
| 96 |
+
and `pci-compliance`") and asks Maya to confirm.
|
| 97 |
+
4. Maya says *"yes, load pci-compliance"*. Claude loads it via its
|
| 98 |
+
normal skill-load mechanism; an event lands in `skill-events.jsonl`:
|
| 99 |
+
`{"event": "load", "skill": "pci-compliance", ...}`.
|
| 100 |
+
5. The quality sidecar for `pci-compliance` increments `load_count`;
|
| 101 |
+
`telemetry` score rises on next recompute.
|
| 102 |
+
|
| 103 |
+
**Verification**
|
| 104 |
+
- `tail -1 ~/.claude/skill-events.jsonl` shows the new load event.
|
| 105 |
+
- `ctx-skill-quality explain pci-compliance` shows `load_count ≥ 1`,
|
| 106 |
+
`never_loaded: False`, floor cleared, grade improved.
|
| 107 |
+
|
| 108 |
+
---
|
| 109 |
+
|
| 110 |
+
## Phase 3 — First real feature + live suggestion cycle
|
| 111 |
+
|
| 112 |
+
Maya writes `app/api/checkout.py`:
|
| 113 |
+
|
| 114 |
+
```python
|
| 115 |
+
from fastapi import APIRouter, HTTPException
|
| 116 |
+
import stripe
|
| 117 |
+
from app.schemas import CheckoutRequest, CheckoutResponse
|
| 118 |
+
|
| 119 |
+
router = APIRouter()
|
| 120 |
+
|
| 121 |
+
@router.post("/checkout", response_model=CheckoutResponse)
|
| 122 |
+
async def create_checkout(req: CheckoutRequest) -> CheckoutResponse:
|
| 123 |
+
intent = stripe.PaymentIntent.create(
|
| 124 |
+
amount=req.amount_cents, currency="usd",
|
| 125 |
+
metadata={"user_id": req.user_id},
|
| 126 |
+
)
|
| 127 |
+
return CheckoutResponse(client_secret=intent.client_secret)
|
| 128 |
+
```
|
| 129 |
+
|
| 130 |
+
She runs `pytest` (no tests yet) → exits 0 (no-op). She realizes she
|
| 131 |
+
needs test coverage.
|
| 132 |
+
|
| 133 |
+
**Expected ctx behavior**
|
| 134 |
+
1. Editing files under `tests/` triggers `context_monitor` to detect
|
| 135 |
+
the `testing` signal.
|
| 136 |
+
2. `skill_suggest` surfaces `test-driven-development`,
|
| 137 |
+
`python-testing`, `pytest-patterns` from the graph.
|
| 138 |
+
3. Maya loads `python-testing`. Sidecar updates.
|
| 139 |
+
|
| 140 |
+
---
|
| 141 |
+
|
| 142 |
+
## Phase 4 — Pre-commit council (toolbox run)
|
| 143 |
+
|
| 144 |
+
Before committing, Maya wants a security review. She has `toolbox init`
|
| 145 |
+
output 5 starter toolboxes. She activates `security-sweep`:
|
| 146 |
+
|
| 147 |
+
```bash
|
| 148 |
+
ctx-toolbox activate security-sweep
|
| 149 |
+
ctx-toolbox run --event pre-commit
|
| 150 |
+
```
|
| 151 |
+
|
| 152 |
+
**Expected ctx behavior**
|
| 153 |
+
1. `toolbox.py run` reads the active toolbox config.
|
| 154 |
+
2. Council is assembled: `security-reviewer`, `security-auditor`,
|
| 155 |
+
`penetration-tester`, `compliance-auditor`,
|
| 156 |
+
`threat-detection-engineer`.
|
| 157 |
+
3. `council_runner.py` builds a `RunPlan` with scope=`diff` (files
|
| 158 |
+
changed since last commit), budget=300K tokens, guardrail=True.
|
| 159 |
+
4. Claude Code picks up the plan, dispatches each agent, collects
|
| 160 |
+
findings.
|
| 161 |
+
5. `toolbox_verdict.py` merges findings by stable id, escalates level.
|
| 162 |
+
6. If any HIGH/CRITICAL finding exists, `run --event pre-commit`
|
| 163 |
+
exits 2 → blocks `git commit`.
|
| 164 |
+
|
| 165 |
+
**Expected finding** (realistic): `security-reviewer` flags the
|
| 166 |
+
checkout endpoint lacks webhook signature verification and Stripe key
|
| 167 |
+
is read from env but never validated as non-empty → MEDIUM. No block.
|
| 168 |
+
|
| 169 |
+
---
|
| 170 |
+
|
| 171 |
+
## Phase 5 — Custom skill for the domain (skill_add)
|
| 172 |
+
|
| 173 |
+
Maya realizes her team reuses the same `PaymentIntent` error-mapping
|
| 174 |
+
pattern across 3 services. She wants to capture it as a custom skill.
|
| 175 |
+
|
| 176 |
+
```bash
|
| 177 |
+
mkdir -p .skills/stripe-error-mapping
|
| 178 |
+
cat > .skills/stripe-error-mapping/SKILL.md <<EOF
|
| 179 |
+
---
|
| 180 |
+
name: stripe-error-mapping
|
| 181 |
+
description: Canonical Stripe API error → domain exception mapping for fintech backends
|
| 182 |
+
tags: [stripe, payments, error-handling, pci]
|
| 183 |
+
---
|
| 184 |
+
|
| 185 |
+
# Stripe error mapping
|
| 186 |
+
|
| 187 |
+
## When to use
|
| 188 |
+
Whenever a service integrates with Stripe's PaymentIntent, Charge, or
|
| 189 |
+
Setup Intent APIs. This skill ensures every Stripe error (rate-limit,
|
| 190 |
+
card-declined, authentication, API connection, idempotency) maps to
|
| 191 |
+
a stable domain exception with an actionable error code.
|
| 192 |
+
|
| 193 |
+
## Mapping table
|
| 194 |
+
|
| 195 |
+
| Stripe error class | Domain exception | HTTP status |
|
| 196 |
+
| ... |
|
| 197 |
+
|
| 198 |
+
EOF
|
| 199 |
+
|
| 200 |
+
ctx-skill-quality recompute stripe-error-mapping # will fail — not yet installed
|
| 201 |
+
# Install path:
|
| 202 |
+
python -m skill_add --skill-path .skills/stripe-error-mapping/SKILL.md
|
| 203 |
+
```
|
| 204 |
+
|
| 205 |
+
**Expected ctx behavior**
|
| 206 |
+
1. `skill_add` runs the intake gate (`intake_gate.py`):
|
| 207 |
+
frontmatter-present, has-description, body-long-enough, has-H2.
|
| 208 |
+
2. Similarity check against existing skills via embedding backend
|
| 209 |
+
(falls back to structural-only if sentence-transformers missing).
|
| 210 |
+
3. If novel: writes `~/.claude/skills/stripe-error-mapping/SKILL.md`,
|
| 211 |
+
adds entity page at
|
| 212 |
+
`~/.claude/skill-wiki/entities/skills/stripe-error-mapping.md`
|
| 213 |
+
with frontmatter (tags, use_count=0, last_used=null, status=installed).
|
| 214 |
+
4. Returns success: manifest counter `1,579 → 1,580`.
|
| 215 |
+
|
| 216 |
+
**Post-add follow-ups**
|
| 217 |
+
- Graph rebuild required to include the new skill as a node with edges
|
| 218 |
+
to `stripe`, `payments`, `pci` tag communities.
|
| 219 |
+
- `ctx-skill-quality recompute stripe-error-mapping` seeds the sidecar.
|
| 220 |
+
|
| 221 |
+
---
|
| 222 |
+
|
| 223 |
+
## Phase 6 — Session end + lifecycle pruning
|
| 224 |
+
|
| 225 |
+
End of day. Claude's `Stop` hook fires:
|
| 226 |
+
1. `usage_tracker.py --sync` updates skill usage stats from
|
| 227 |
+
`skill-events.jsonl`.
|
| 228 |
+
2. `hooks/quality_on_session_end.py` recomputes sidecars for only
|
| 229 |
+
the slugs touched this session (incremental).
|
| 230 |
+
3. `ctx_lifecycle` reviews sidecars; any skill that sat in `_demoted`
|
| 231 |
+
past the 14-day archive threshold is moved to `_archive`.
|
| 232 |
+
|
| 233 |
+
Maya runs:
|
| 234 |
+
|
| 235 |
+
```bash
|
| 236 |
+
ctx-toolbox status
|
| 237 |
+
python -m kpi_dashboard render
|
| 238 |
+
open ~/.claude/skill-quality/kpi.md
|
| 239 |
+
```
|
| 240 |
+
|
| 241 |
+
She sees:
|
| 242 |
+
- Grade distribution (A: 2, B: 18, C: 240, D: 1320, F: 311).
|
| 243 |
+
- Hard-floor reasons.
|
| 244 |
+
- Top demotion candidates. Skills she never used in 30 days get
|
| 245 |
+
auto-archived next tick.
|
| 246 |
+
|
| 247 |
+
Optionally she launches the claude-mem web monitor:
|
| 248 |
+
|
| 249 |
+
```bash
|
| 250 |
+
npx claude-mem start
|
| 251 |
+
# browser opens http://localhost:37777
|
| 252 |
+
```
|
| 253 |
+
|
| 254 |
+
---
|
| 255 |
+
|
| 256 |
+
## Success criteria (what "good" looks like at end of day)
|
| 257 |
+
|
| 258 |
+
| Check | Pass when |
|
| 259 |
+
|---|---|
|
| 260 |
+
| Phase 1 manifest | 10–15 loads, mixed fuzzy + graph-neighbor reasons |
|
| 261 |
+
| Phase 2 events log | Every Claude tool call produced a PostToolUse invocation |
|
| 262 |
+
| Phase 3 suggest | `pending-skills.json` gained ≥ 1 new entry for Stripe |
|
| 263 |
+
| Phase 4 verdict | Council runs, findings file written, exits 0 or 2 cleanly |
|
| 264 |
+
| Phase 5 skill_add | New skill appears in skills dir + wiki; dedup fired |
|
| 265 |
+
| Phase 6 KPI | `kpi.md` reflects today's sessions; archived skills moved |
|
| 266 |
+
|
| 267 |
+
## Known gaps this playbook will surface
|
| 268 |
+
|
| 269 |
+
- `wiki_sync` has no drift detection (skill edits don't re-sync wiki).
|
| 270 |
+
- `batch_convert` hash-gated idempotency looks like no-op on re-run.
|
| 271 |
+
- `scan_repo` doesn't detect pytest from pyproject `[dev]` deps.
|
| 272 |
+
- `skill_add` CLI raises false `BODY_MISSING_H2` — in-process API works.
|
| 273 |
+
|
| 274 |
+
Each gap is tracked as a separate issue and will be fixed post-playbook.
|
scripts/build_dashboard_graph_index.py
CHANGED
|
@@ -1,169 +1,169 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""Build the compact dashboard graph-neighborhood SQLite index."""
|
| 3 |
-
|
| 4 |
-
from __future__ import annotations
|
| 5 |
-
|
| 6 |
-
import argparse
|
| 7 |
-
import json
|
| 8 |
-
import os
|
| 9 |
-
import sqlite3
|
| 10 |
-
import zlib
|
| 11 |
-
from pathlib import Path
|
| 12 |
-
from typing import Any
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
def _graph_edges(data: dict[str, Any]) -> list[dict[str, Any]]:
|
| 16 |
-
raw = data.get("links") if "links" in data else data.get("edges", [])
|
| 17 |
-
if not isinstance(raw, list):
|
| 18 |
-
return []
|
| 19 |
-
return [item for item in raw if isinstance(item, dict)]
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
def build_dashboard_index(graph_json: Path, output: Path, *, top_k: int = 40) -> None:
|
| 23 |
-
data = json.loads(graph_json.read_text(encoding="utf-8"))
|
| 24 |
-
nodes_raw = [item for item in data.get("nodes", []) if isinstance(item, dict)]
|
| 25 |
-
edges_raw = _graph_edges(data)
|
| 26 |
-
nodes: dict[str, dict[str, Any]] = {}
|
| 27 |
-
slug_rows: list[tuple[str, str, str]] = []
|
| 28 |
-
neighbors: dict[str, list[dict[str, Any]]] = {}
|
| 29 |
-
|
| 30 |
-
for node in nodes_raw:
|
| 31 |
-
node_id = node.get("id")
|
| 32 |
-
if not isinstance(node_id, str) or not node_id:
|
| 33 |
-
continue
|
| 34 |
-
slug = node_id.split(":", 1)[-1]
|
| 35 |
-
node_type = str(node.get("type") or node_id.split(":", 1)[0])
|
| 36 |
-
raw_tags = node.get("tags")
|
| 37 |
-
tags = raw_tags if isinstance(raw_tags, list) else []
|
| 38 |
-
nodes[node_id] = {
|
| 39 |
-
"id": node_id,
|
| 40 |
-
"label": node.get("label") or slug,
|
| 41 |
-
"type": node_type,
|
| 42 |
-
"tags": tags[:8],
|
| 43 |
-
"description": node.get("description") or "",
|
| 44 |
-
"quality_score": node.get("quality_score"),
|
| 45 |
-
"usage_score": node.get("usage_score"),
|
| 46 |
-
"degree": 0,
|
| 47 |
-
}
|
| 48 |
-
slug_rows.append((slug, node_type, node_id))
|
| 49 |
-
neighbors[node_id] = []
|
| 50 |
-
|
| 51 |
-
for edge in edges_raw:
|
| 52 |
-
source = edge.get("source")
|
| 53 |
-
target = edge.get("target")
|
| 54 |
-
if not isinstance(source, str) or not isinstance(target, str):
|
| 55 |
-
continue
|
| 56 |
-
if source not in nodes or target not in nodes:
|
| 57 |
-
continue
|
| 58 |
-
weight = float(edge.get("weight", 1.0) or 0.0)
|
| 59 |
-
row = {
|
| 60 |
-
"target": target,
|
| 61 |
-
"weight": weight,
|
| 62 |
-
"shared_tags": (edge.get("shared_tags") or [])[:4],
|
| 63 |
-
"reasons": (edge.get("reasons") or edge.get("edge_reasons") or [])[:4],
|
| 64 |
-
"semantic": edge.get("semantic"),
|
| 65 |
-
"tag_sim": edge.get("tag_sim"),
|
| 66 |
-
"slug_token_sim": edge.get("slug_token_sim"),
|
| 67 |
-
"source_overlap": edge.get("source_overlap"),
|
| 68 |
-
}
|
| 69 |
-
neighbors[source].append(row)
|
| 70 |
-
reverse = dict(row)
|
| 71 |
-
reverse["target"] = source
|
| 72 |
-
neighbors[target].append(reverse)
|
| 73 |
-
|
| 74 |
-
for node_id, rows in neighbors.items():
|
| 75 |
-
rows.sort(key=lambda row: -float(row.get("weight") or 0.0))
|
| 76 |
-
nodes[node_id]["degree"] = len(rows)
|
| 77 |
-
del rows[top_k:]
|
| 78 |
-
|
| 79 |
-
output.parent.mkdir(parents=True, exist_ok=True)
|
| 80 |
-
build_path = output.with_name(f".{output.name}.{os.getpid()}.tmp")
|
| 81 |
-
if build_path.exists():
|
| 82 |
-
build_path.unlink()
|
| 83 |
-
try:
|
| 84 |
-
conn = sqlite3.connect(build_path)
|
| 85 |
-
try:
|
| 86 |
-
conn.execute("PRAGMA journal_mode=OFF")
|
| 87 |
-
conn.execute("PRAGMA synchronous=OFF")
|
| 88 |
-
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
|
| 89 |
-
conn.execute(
|
| 90 |
-
"CREATE TABLE nodes("
|
| 91 |
-
"id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,description TEXT,"
|
| 92 |
-
"quality_score REAL,usage_score REAL,degree INTEGER)"
|
| 93 |
-
)
|
| 94 |
-
conn.execute(
|
| 95 |
-
"CREATE TABLE slug_index("
|
| 96 |
-
"slug TEXT,type TEXT,node_id TEXT,PRIMARY KEY(slug,type,node_id))"
|
| 97 |
-
)
|
| 98 |
-
conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
|
| 99 |
-
meta = {
|
| 100 |
-
"version": 1,
|
| 101 |
-
"export_id": data.get("graph", {}).get("export_id"),
|
| 102 |
-
"nodes_count": len(nodes),
|
| 103 |
-
"edges_count": len(edges_raw),
|
| 104 |
-
"max_degree": max((int(node["degree"]) for node in nodes.values()), default=1),
|
| 105 |
-
"top_k": top_k,
|
| 106 |
-
}
|
| 107 |
-
conn.executemany(
|
| 108 |
-
"INSERT INTO meta(key,value) VALUES(?,?)",
|
| 109 |
-
[(key, json.dumps(value)) for key, value in meta.items()],
|
| 110 |
-
)
|
| 111 |
-
conn.executemany(
|
| 112 |
-
"INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
|
| 113 |
-
[
|
| 114 |
-
(
|
| 115 |
-
node["id"],
|
| 116 |
-
node["label"],
|
| 117 |
-
node["type"],
|
| 118 |
-
json.dumps(node["tags"], separators=(",", ":")),
|
| 119 |
-
node["description"],
|
| 120 |
-
node["quality_score"],
|
| 121 |
-
node["usage_score"],
|
| 122 |
-
node["degree"],
|
| 123 |
-
)
|
| 124 |
-
for node in nodes.values()
|
| 125 |
-
],
|
| 126 |
-
)
|
| 127 |
-
conn.executemany("INSERT OR IGNORE INTO slug_index VALUES(?,?,?)", slug_rows)
|
| 128 |
-
neighbor_rows = []
|
| 129 |
-
for source, rows in neighbors.items():
|
| 130 |
-
slim = [
|
| 131 |
-
{
|
| 132 |
-
key: value
|
| 133 |
-
for key, value in row.items()
|
| 134 |
-
if value not in (None, [], "")
|
| 135 |
-
}
|
| 136 |
-
for row in rows
|
| 137 |
-
]
|
| 138 |
-
payload = zlib.compress(
|
| 139 |
-
json.dumps(slim, separators=(",", ":")).encode("utf-8"),
|
| 140 |
-
level=6,
|
| 141 |
-
)
|
| 142 |
-
neighbor_rows.append((source, payload))
|
| 143 |
-
if len(neighbor_rows) >= 10_000:
|
| 144 |
-
conn.executemany("INSERT INTO neighbors VALUES(?,?)", neighbor_rows)
|
| 145 |
-
neighbor_rows.clear()
|
| 146 |
-
if neighbor_rows:
|
| 147 |
-
conn.executemany("INSERT INTO neighbors VALUES(?,?)", neighbor_rows)
|
| 148 |
-
conn.execute("CREATE INDEX idx_slug_index_slug ON slug_index(slug)")
|
| 149 |
-
conn.commit()
|
| 150 |
-
conn.execute("VACUUM")
|
| 151 |
-
finally:
|
| 152 |
-
conn.close()
|
| 153 |
-
os.replace(build_path, output)
|
| 154 |
-
finally:
|
| 155 |
-
if build_path.exists():
|
| 156 |
-
build_path.unlink()
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
def main() -> None:
|
| 160 |
-
parser = argparse.ArgumentParser()
|
| 161 |
-
parser.add_argument("--graph-json", type=Path, required=True)
|
| 162 |
-
parser.add_argument("--output", type=Path, required=True)
|
| 163 |
-
parser.add_argument("--top-k", type=int, default=40)
|
| 164 |
-
args = parser.parse_args()
|
| 165 |
-
build_dashboard_index(args.graph_json, args.output, top_k=args.top_k)
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
if __name__ == "__main__":
|
| 169 |
-
main()
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Build the compact dashboard graph-neighborhood SQLite index."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import sqlite3
|
| 10 |
+
import zlib
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _graph_edges(data: dict[str, Any]) -> list[dict[str, Any]]:
|
| 16 |
+
raw = data.get("links") if "links" in data else data.get("edges", [])
|
| 17 |
+
if not isinstance(raw, list):
|
| 18 |
+
return []
|
| 19 |
+
return [item for item in raw if isinstance(item, dict)]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def build_dashboard_index(graph_json: Path, output: Path, *, top_k: int = 40) -> None:
|
| 23 |
+
data = json.loads(graph_json.read_text(encoding="utf-8"))
|
| 24 |
+
nodes_raw = [item for item in data.get("nodes", []) if isinstance(item, dict)]
|
| 25 |
+
edges_raw = _graph_edges(data)
|
| 26 |
+
nodes: dict[str, dict[str, Any]] = {}
|
| 27 |
+
slug_rows: list[tuple[str, str, str]] = []
|
| 28 |
+
neighbors: dict[str, list[dict[str, Any]]] = {}
|
| 29 |
+
|
| 30 |
+
for node in nodes_raw:
|
| 31 |
+
node_id = node.get("id")
|
| 32 |
+
if not isinstance(node_id, str) or not node_id:
|
| 33 |
+
continue
|
| 34 |
+
slug = node_id.split(":", 1)[-1]
|
| 35 |
+
node_type = str(node.get("type") or node_id.split(":", 1)[0])
|
| 36 |
+
raw_tags = node.get("tags")
|
| 37 |
+
tags = raw_tags if isinstance(raw_tags, list) else []
|
| 38 |
+
nodes[node_id] = {
|
| 39 |
+
"id": node_id,
|
| 40 |
+
"label": node.get("label") or slug,
|
| 41 |
+
"type": node_type,
|
| 42 |
+
"tags": tags[:8],
|
| 43 |
+
"description": node.get("description") or "",
|
| 44 |
+
"quality_score": node.get("quality_score"),
|
| 45 |
+
"usage_score": node.get("usage_score"),
|
| 46 |
+
"degree": 0,
|
| 47 |
+
}
|
| 48 |
+
slug_rows.append((slug, node_type, node_id))
|
| 49 |
+
neighbors[node_id] = []
|
| 50 |
+
|
| 51 |
+
for edge in edges_raw:
|
| 52 |
+
source = edge.get("source")
|
| 53 |
+
target = edge.get("target")
|
| 54 |
+
if not isinstance(source, str) or not isinstance(target, str):
|
| 55 |
+
continue
|
| 56 |
+
if source not in nodes or target not in nodes:
|
| 57 |
+
continue
|
| 58 |
+
weight = float(edge.get("weight", 1.0) or 0.0)
|
| 59 |
+
row = {
|
| 60 |
+
"target": target,
|
| 61 |
+
"weight": weight,
|
| 62 |
+
"shared_tags": (edge.get("shared_tags") or [])[:4],
|
| 63 |
+
"reasons": (edge.get("reasons") or edge.get("edge_reasons") or [])[:4],
|
| 64 |
+
"semantic": edge.get("semantic"),
|
| 65 |
+
"tag_sim": edge.get("tag_sim"),
|
| 66 |
+
"slug_token_sim": edge.get("slug_token_sim"),
|
| 67 |
+
"source_overlap": edge.get("source_overlap"),
|
| 68 |
+
}
|
| 69 |
+
neighbors[source].append(row)
|
| 70 |
+
reverse = dict(row)
|
| 71 |
+
reverse["target"] = source
|
| 72 |
+
neighbors[target].append(reverse)
|
| 73 |
+
|
| 74 |
+
for node_id, rows in neighbors.items():
|
| 75 |
+
rows.sort(key=lambda row: -float(row.get("weight") or 0.0))
|
| 76 |
+
nodes[node_id]["degree"] = len(rows)
|
| 77 |
+
del rows[top_k:]
|
| 78 |
+
|
| 79 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 80 |
+
build_path = output.with_name(f".{output.name}.{os.getpid()}.tmp")
|
| 81 |
+
if build_path.exists():
|
| 82 |
+
build_path.unlink()
|
| 83 |
+
try:
|
| 84 |
+
conn = sqlite3.connect(build_path)
|
| 85 |
+
try:
|
| 86 |
+
conn.execute("PRAGMA journal_mode=OFF")
|
| 87 |
+
conn.execute("PRAGMA synchronous=OFF")
|
| 88 |
+
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
|
| 89 |
+
conn.execute(
|
| 90 |
+
"CREATE TABLE nodes("
|
| 91 |
+
"id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,description TEXT,"
|
| 92 |
+
"quality_score REAL,usage_score REAL,degree INTEGER)"
|
| 93 |
+
)
|
| 94 |
+
conn.execute(
|
| 95 |
+
"CREATE TABLE slug_index("
|
| 96 |
+
"slug TEXT,type TEXT,node_id TEXT,PRIMARY KEY(slug,type,node_id))"
|
| 97 |
+
)
|
| 98 |
+
conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
|
| 99 |
+
meta = {
|
| 100 |
+
"version": 1,
|
| 101 |
+
"export_id": data.get("graph", {}).get("export_id"),
|
| 102 |
+
"nodes_count": len(nodes),
|
| 103 |
+
"edges_count": len(edges_raw),
|
| 104 |
+
"max_degree": max((int(node["degree"]) for node in nodes.values()), default=1),
|
| 105 |
+
"top_k": top_k,
|
| 106 |
+
}
|
| 107 |
+
conn.executemany(
|
| 108 |
+
"INSERT INTO meta(key,value) VALUES(?,?)",
|
| 109 |
+
[(key, json.dumps(value)) for key, value in meta.items()],
|
| 110 |
+
)
|
| 111 |
+
conn.executemany(
|
| 112 |
+
"INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
|
| 113 |
+
[
|
| 114 |
+
(
|
| 115 |
+
node["id"],
|
| 116 |
+
node["label"],
|
| 117 |
+
node["type"],
|
| 118 |
+
json.dumps(node["tags"], separators=(",", ":")),
|
| 119 |
+
node["description"],
|
| 120 |
+
node["quality_score"],
|
| 121 |
+
node["usage_score"],
|
| 122 |
+
node["degree"],
|
| 123 |
+
)
|
| 124 |
+
for node in nodes.values()
|
| 125 |
+
],
|
| 126 |
+
)
|
| 127 |
+
conn.executemany("INSERT OR IGNORE INTO slug_index VALUES(?,?,?)", slug_rows)
|
| 128 |
+
neighbor_rows = []
|
| 129 |
+
for source, rows in neighbors.items():
|
| 130 |
+
slim = [
|
| 131 |
+
{
|
| 132 |
+
key: value
|
| 133 |
+
for key, value in row.items()
|
| 134 |
+
if value not in (None, [], "")
|
| 135 |
+
}
|
| 136 |
+
for row in rows
|
| 137 |
+
]
|
| 138 |
+
payload = zlib.compress(
|
| 139 |
+
json.dumps(slim, separators=(",", ":")).encode("utf-8"),
|
| 140 |
+
level=6,
|
| 141 |
+
)
|
| 142 |
+
neighbor_rows.append((source, payload))
|
| 143 |
+
if len(neighbor_rows) >= 10_000:
|
| 144 |
+
conn.executemany("INSERT INTO neighbors VALUES(?,?)", neighbor_rows)
|
| 145 |
+
neighbor_rows.clear()
|
| 146 |
+
if neighbor_rows:
|
| 147 |
+
conn.executemany("INSERT INTO neighbors VALUES(?,?)", neighbor_rows)
|
| 148 |
+
conn.execute("CREATE INDEX idx_slug_index_slug ON slug_index(slug)")
|
| 149 |
+
conn.commit()
|
| 150 |
+
conn.execute("VACUUM")
|
| 151 |
+
finally:
|
| 152 |
+
conn.close()
|
| 153 |
+
os.replace(build_path, output)
|
| 154 |
+
finally:
|
| 155 |
+
if build_path.exists():
|
| 156 |
+
build_path.unlink()
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def main() -> None:
|
| 160 |
+
parser = argparse.ArgumentParser()
|
| 161 |
+
parser.add_argument("--graph-json", type=Path, required=True)
|
| 162 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 163 |
+
parser.add_argument("--top-k", type=int, default=40)
|
| 164 |
+
args = parser.parse_args()
|
| 165 |
+
build_dashboard_index(args.graph_json, args.output, top_k=args.top_k)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
if __name__ == "__main__":
|
| 169 |
+
main()
|
scripts/ci_classifier.py
CHANGED
|
@@ -1,150 +1,150 @@
|
|
| 1 |
-
"""Classify changed paths for CI workflow decisions."""
|
| 2 |
-
|
| 3 |
-
from __future__ import annotations
|
| 4 |
-
|
| 5 |
-
import argparse
|
| 6 |
-
import fnmatch
|
| 7 |
-
import os
|
| 8 |
-
from pathlib import Path
|
| 9 |
-
from typing import Iterable
|
| 10 |
-
|
| 11 |
-
OUTPUT_NAMES = (
|
| 12 |
-
"browser_changed",
|
| 13 |
-
"ci_changed",
|
| 14 |
-
"docs_changed",
|
| 15 |
-
"docs_only",
|
| 16 |
-
"graph_artifact_changed",
|
| 17 |
-
"graph_changed",
|
| 18 |
-
"graph_only",
|
| 19 |
-
"package_changed",
|
| 20 |
-
"similarity_changed",
|
| 21 |
-
"source_changed",
|
| 22 |
-
)
|
| 23 |
-
|
| 24 |
-
DOCS_PATTERNS = (
|
| 25 |
-
"*.md",
|
| 26 |
-
"docs/**",
|
| 27 |
-
"graph/README.md",
|
| 28 |
-
"LICENSE",
|
| 29 |
-
"mkdocs.yml",
|
| 30 |
-
"requirements-docs.txt",
|
| 31 |
-
)
|
| 32 |
-
GRAPH_ARTIFACT_PATTERNS = (
|
| 33 |
-
"graph/communities.json",
|
| 34 |
-
"graph/entity-overlays.jsonl",
|
| 35 |
-
"graph/skills-sh-catalog.json.gz",
|
| 36 |
-
"graph/wiki-graph-runtime.tar.gz",
|
| 37 |
-
"graph/wiki-graph.tar.gz",
|
| 38 |
-
"graph/*.html",
|
| 39 |
-
)
|
| 40 |
-
BROWSER_PATTERNS = (
|
| 41 |
-
".github/workflows/test.yml",
|
| 42 |
-
"dashboard/**",
|
| 43 |
-
"pyproject.toml",
|
| 44 |
-
"src/**/browser/**",
|
| 45 |
-
"src/**/monitor/**",
|
| 46 |
-
"src/ctx_monitor.py",
|
| 47 |
-
"src/ctx/utils/_safe_name.py",
|
| 48 |
-
"src/tests/test_ctx_monitor_browser.py",
|
| 49 |
-
)
|
| 50 |
-
PACKAGE_PATTERNS = (
|
| 51 |
-
"MANIFEST.in",
|
| 52 |
-
"pyproject.toml",
|
| 53 |
-
"src/*.py",
|
| 54 |
-
"src/ctx/**",
|
| 55 |
-
)
|
| 56 |
-
SOURCE_PATTERNS = (
|
| 57 |
-
"hooks/**",
|
| 58 |
-
"pyproject.toml",
|
| 59 |
-
"scripts/**",
|
| 60 |
-
"src/**",
|
| 61 |
-
)
|
| 62 |
-
SIMILARITY_PATTERNS = (
|
| 63 |
-
".github/workflows/test.yml",
|
| 64 |
-
"graph/entity-overlays.jsonl",
|
| 65 |
-
"pyproject.toml",
|
| 66 |
-
"src/corpus_cache.py",
|
| 67 |
-
"src/config.json",
|
| 68 |
-
"src/cosine_ranker.py",
|
| 69 |
-
"src/ctx/adapters/claude_code/hooks/context_monitor.py",
|
| 70 |
-
"src/ctx/adapters/generic/ctx_core_tools.py",
|
| 71 |
-
"src/ctx_config.py",
|
| 72 |
-
"src/ctx/core/graph/**",
|
| 73 |
-
"src/ctx/core/resolve/**",
|
| 74 |
-
"src/ctx/core/wiki/wiki_graphify.py",
|
| 75 |
-
"src/embedding_backend.py",
|
| 76 |
-
"src/intake_gate.py",
|
| 77 |
-
"src/tests/test_similarity_precision_recall.py",
|
| 78 |
-
)
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
def _matches(path: str, patterns: Iterable[str]) -> bool:
|
| 82 |
-
return any(fnmatch.fnmatch(path, pattern) for pattern in patterns)
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
def _normalize_path(path: str) -> str:
|
| 86 |
-
return path.strip().lstrip("\ufeff").replace("\\", "/")
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
def _is_graph_artifact_path(path: str) -> bool:
|
| 90 |
-
if _matches(path, GRAPH_ARTIFACT_PATTERNS):
|
| 91 |
-
return True
|
| 92 |
-
return _matches(path, ("graph/**",)) and path != "graph/README.md"
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
def classify_paths(paths: Iterable[str]) -> dict[str, bool]:
|
| 96 |
-
files = [
|
| 97 |
-
normalized
|
| 98 |
-
for path in paths
|
| 99 |
-
if (normalized := _normalize_path(path))
|
| 100 |
-
]
|
| 101 |
-
ci_changed = any(_matches(path, (".github/workflows/**",)) for path in files)
|
| 102 |
-
docs_changed = any(_matches(path, DOCS_PATTERNS) for path in files)
|
| 103 |
-
graph_artifact_changed = any(_is_graph_artifact_path(path) for path in files)
|
| 104 |
-
graph_only = bool(files) and all(_matches(path, ("graph/**",)) for path in files)
|
| 105 |
-
return {
|
| 106 |
-
"browser_changed": ci_changed
|
| 107 |
-
or any(_matches(path, BROWSER_PATTERNS) for path in files),
|
| 108 |
-
"ci_changed": ci_changed,
|
| 109 |
-
"docs_changed": docs_changed,
|
| 110 |
-
"docs_only": bool(files) and all(_matches(path, DOCS_PATTERNS) for path in files),
|
| 111 |
-
"graph_artifact_changed": graph_artifact_changed,
|
| 112 |
-
"graph_changed": any(_matches(path, ("graph/**",)) for path in files),
|
| 113 |
-
"graph_only": graph_only,
|
| 114 |
-
"package_changed": ci_changed
|
| 115 |
-
or any(_matches(path, PACKAGE_PATTERNS) for path in files),
|
| 116 |
-
"similarity_changed": ci_changed
|
| 117 |
-
or any(_matches(path, SIMILARITY_PATTERNS) for path in files),
|
| 118 |
-
"source_changed": ci_changed
|
| 119 |
-
or any(_matches(path, SOURCE_PATTERNS) for path in files),
|
| 120 |
-
}
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
def write_github_outputs(flags: dict[str, bool], output_path: Path) -> None:
|
| 124 |
-
with output_path.open("a", encoding="utf-8") as output:
|
| 125 |
-
for name in OUTPUT_NAMES:
|
| 126 |
-
output.write(f"{name}={str(flags[name]).lower()}\n")
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
def main(argv: list[str] | None = None) -> int:
|
| 130 |
-
parser = argparse.ArgumentParser()
|
| 131 |
-
parser.add_argument("changed_files", type=Path)
|
| 132 |
-
args = parser.parse_args(argv)
|
| 133 |
-
|
| 134 |
-
files = args.changed_files.read_text(encoding="utf-8").splitlines()
|
| 135 |
-
flags = classify_paths(files)
|
| 136 |
-
github_output = os.environ.get("GITHUB_OUTPUT")
|
| 137 |
-
if github_output:
|
| 138 |
-
write_github_outputs(flags, Path(github_output))
|
| 139 |
-
|
| 140 |
-
print("Changed files:")
|
| 141 |
-
for path in [path for line in files if (path := _normalize_path(line))]:
|
| 142 |
-
print(f" {path}")
|
| 143 |
-
print("Classification:")
|
| 144 |
-
for name in OUTPUT_NAMES:
|
| 145 |
-
print(f" {name}={str(flags[name]).lower()}")
|
| 146 |
-
return 0
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
if __name__ == "__main__":
|
| 150 |
-
raise SystemExit(main())
|
|
|
|
| 1 |
+
"""Classify changed paths for CI workflow decisions."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import fnmatch
|
| 7 |
+
import os
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Iterable
|
| 10 |
+
|
| 11 |
+
OUTPUT_NAMES = (
|
| 12 |
+
"browser_changed",
|
| 13 |
+
"ci_changed",
|
| 14 |
+
"docs_changed",
|
| 15 |
+
"docs_only",
|
| 16 |
+
"graph_artifact_changed",
|
| 17 |
+
"graph_changed",
|
| 18 |
+
"graph_only",
|
| 19 |
+
"package_changed",
|
| 20 |
+
"similarity_changed",
|
| 21 |
+
"source_changed",
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
DOCS_PATTERNS = (
|
| 25 |
+
"*.md",
|
| 26 |
+
"docs/**",
|
| 27 |
+
"graph/README.md",
|
| 28 |
+
"LICENSE",
|
| 29 |
+
"mkdocs.yml",
|
| 30 |
+
"requirements-docs.txt",
|
| 31 |
+
)
|
| 32 |
+
GRAPH_ARTIFACT_PATTERNS = (
|
| 33 |
+
"graph/communities.json",
|
| 34 |
+
"graph/entity-overlays.jsonl",
|
| 35 |
+
"graph/skills-sh-catalog.json.gz",
|
| 36 |
+
"graph/wiki-graph-runtime.tar.gz",
|
| 37 |
+
"graph/wiki-graph.tar.gz",
|
| 38 |
+
"graph/*.html",
|
| 39 |
+
)
|
| 40 |
+
BROWSER_PATTERNS = (
|
| 41 |
+
".github/workflows/test.yml",
|
| 42 |
+
"dashboard/**",
|
| 43 |
+
"pyproject.toml",
|
| 44 |
+
"src/**/browser/**",
|
| 45 |
+
"src/**/monitor/**",
|
| 46 |
+
"src/ctx_monitor.py",
|
| 47 |
+
"src/ctx/utils/_safe_name.py",
|
| 48 |
+
"src/tests/test_ctx_monitor_browser.py",
|
| 49 |
+
)
|
| 50 |
+
PACKAGE_PATTERNS = (
|
| 51 |
+
"MANIFEST.in",
|
| 52 |
+
"pyproject.toml",
|
| 53 |
+
"src/*.py",
|
| 54 |
+
"src/ctx/**",
|
| 55 |
+
)
|
| 56 |
+
SOURCE_PATTERNS = (
|
| 57 |
+
"hooks/**",
|
| 58 |
+
"pyproject.toml",
|
| 59 |
+
"scripts/**",
|
| 60 |
+
"src/**",
|
| 61 |
+
)
|
| 62 |
+
SIMILARITY_PATTERNS = (
|
| 63 |
+
".github/workflows/test.yml",
|
| 64 |
+
"graph/entity-overlays.jsonl",
|
| 65 |
+
"pyproject.toml",
|
| 66 |
+
"src/corpus_cache.py",
|
| 67 |
+
"src/config.json",
|
| 68 |
+
"src/cosine_ranker.py",
|
| 69 |
+
"src/ctx/adapters/claude_code/hooks/context_monitor.py",
|
| 70 |
+
"src/ctx/adapters/generic/ctx_core_tools.py",
|
| 71 |
+
"src/ctx_config.py",
|
| 72 |
+
"src/ctx/core/graph/**",
|
| 73 |
+
"src/ctx/core/resolve/**",
|
| 74 |
+
"src/ctx/core/wiki/wiki_graphify.py",
|
| 75 |
+
"src/embedding_backend.py",
|
| 76 |
+
"src/intake_gate.py",
|
| 77 |
+
"src/tests/test_similarity_precision_recall.py",
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _matches(path: str, patterns: Iterable[str]) -> bool:
|
| 82 |
+
return any(fnmatch.fnmatch(path, pattern) for pattern in patterns)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _normalize_path(path: str) -> str:
|
| 86 |
+
return path.strip().lstrip("\ufeff").replace("\\", "/")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _is_graph_artifact_path(path: str) -> bool:
|
| 90 |
+
if _matches(path, GRAPH_ARTIFACT_PATTERNS):
|
| 91 |
+
return True
|
| 92 |
+
return _matches(path, ("graph/**",)) and path != "graph/README.md"
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def classify_paths(paths: Iterable[str]) -> dict[str, bool]:
|
| 96 |
+
files = [
|
| 97 |
+
normalized
|
| 98 |
+
for path in paths
|
| 99 |
+
if (normalized := _normalize_path(path))
|
| 100 |
+
]
|
| 101 |
+
ci_changed = any(_matches(path, (".github/workflows/**",)) for path in files)
|
| 102 |
+
docs_changed = any(_matches(path, DOCS_PATTERNS) for path in files)
|
| 103 |
+
graph_artifact_changed = any(_is_graph_artifact_path(path) for path in files)
|
| 104 |
+
graph_only = bool(files) and all(_matches(path, ("graph/**",)) for path in files)
|
| 105 |
+
return {
|
| 106 |
+
"browser_changed": ci_changed
|
| 107 |
+
or any(_matches(path, BROWSER_PATTERNS) for path in files),
|
| 108 |
+
"ci_changed": ci_changed,
|
| 109 |
+
"docs_changed": docs_changed,
|
| 110 |
+
"docs_only": bool(files) and all(_matches(path, DOCS_PATTERNS) for path in files),
|
| 111 |
+
"graph_artifact_changed": graph_artifact_changed,
|
| 112 |
+
"graph_changed": any(_matches(path, ("graph/**",)) for path in files),
|
| 113 |
+
"graph_only": graph_only,
|
| 114 |
+
"package_changed": ci_changed
|
| 115 |
+
or any(_matches(path, PACKAGE_PATTERNS) for path in files),
|
| 116 |
+
"similarity_changed": ci_changed
|
| 117 |
+
or any(_matches(path, SIMILARITY_PATTERNS) for path in files),
|
| 118 |
+
"source_changed": ci_changed
|
| 119 |
+
or any(_matches(path, SOURCE_PATTERNS) for path in files),
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def write_github_outputs(flags: dict[str, bool], output_path: Path) -> None:
|
| 124 |
+
with output_path.open("a", encoding="utf-8") as output:
|
| 125 |
+
for name in OUTPUT_NAMES:
|
| 126 |
+
output.write(f"{name}={str(flags[name]).lower()}\n")
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def main(argv: list[str] | None = None) -> int:
|
| 130 |
+
parser = argparse.ArgumentParser()
|
| 131 |
+
parser.add_argument("changed_files", type=Path)
|
| 132 |
+
args = parser.parse_args(argv)
|
| 133 |
+
|
| 134 |
+
files = args.changed_files.read_text(encoding="utf-8").splitlines()
|
| 135 |
+
flags = classify_paths(files)
|
| 136 |
+
github_output = os.environ.get("GITHUB_OUTPUT")
|
| 137 |
+
if github_output:
|
| 138 |
+
write_github_outputs(flags, Path(github_output))
|
| 139 |
+
|
| 140 |
+
print("Changed files:")
|
| 141 |
+
for path in [path for line in files if (path := _normalize_path(line))]:
|
| 142 |
+
print(f" {path}")
|
| 143 |
+
print("Classification:")
|
| 144 |
+
for name in OUTPUT_NAMES:
|
| 145 |
+
print(f" {name}={str(flags[name]).lower()}")
|
| 146 |
+
return 0
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
if __name__ == "__main__":
|
| 150 |
+
raise SystemExit(main())
|
scripts/ci_no_test_policy.py
CHANGED
|
@@ -1,178 +1,178 @@
|
|
| 1 |
-
"""Enforce that product/CI contract changes include test changes."""
|
| 2 |
-
|
| 3 |
-
from __future__ import annotations
|
| 4 |
-
|
| 5 |
-
import argparse
|
| 6 |
-
import json
|
| 7 |
-
import re
|
| 8 |
-
import subprocess
|
| 9 |
-
from dataclasses import dataclass
|
| 10 |
-
from typing import Iterable
|
| 11 |
-
|
| 12 |
-
RELEASE_METADATA_FILES = {
|
| 13 |
-
"CHANGELOG.md",
|
| 14 |
-
"pyproject.toml",
|
| 15 |
-
"src/__init__.py",
|
| 16 |
-
"src/ctx/__init__.py",
|
| 17 |
-
}
|
| 18 |
-
RELEASE_GENERATED_STATS_FILES = {
|
| 19 |
-
"README.md",
|
| 20 |
-
"docs/index.md",
|
| 21 |
-
}
|
| 22 |
-
VERSION_LINE_RE = re.compile(r'version = "\d+\.\d+\.\d+(?:[-+._a-zA-Z0-9]*)?"')
|
| 23 |
-
INIT_VERSION_LINE_RE = re.compile(
|
| 24 |
-
r'__version__ = "\d+\.\d+\.\d+(?:[-+._a-zA-Z0-9]*)?"'
|
| 25 |
-
)
|
| 26 |
-
TEST_COUNT_STATS_RE = re.compile(
|
| 27 |
-
r".*(Tests-\d+_collected|[\d,]+ tests collected).*"
|
| 28 |
-
)
|
| 29 |
-
RELEASE_DOCS_LINE_RE = re.compile(r"\*\*v\d+\.\d+\.\d+(?:[-+._a-zA-Z0-9]*)?\*\*.*")
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
@dataclass(frozen=True)
|
| 33 |
-
class PolicyResult:
|
| 34 |
-
passed: bool
|
| 35 |
-
message: str
|
| 36 |
-
contract_files: tuple[str, ...] = ()
|
| 37 |
-
test_files: tuple[str, ...] = ()
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
def is_contract_file(path: str) -> bool:
|
| 41 |
-
return (
|
| 42 |
-
(path.startswith("src/") and path.endswith((".py", ".json")))
|
| 43 |
-
or path.startswith("scripts/ci_")
|
| 44 |
-
or path == "scripts/clean_host_contract.py"
|
| 45 |
-
or path == "pyproject.toml"
|
| 46 |
-
or (
|
| 47 |
-
path.startswith(".github/workflows/")
|
| 48 |
-
and path.endswith((".yml", ".yaml"))
|
| 49 |
-
)
|
| 50 |
-
) and not path.startswith("src/tests/")
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
def is_test_file(path: str) -> bool:
|
| 54 |
-
return path.startswith("src/tests/") and path.endswith((".py", ".json"))
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
def is_release_metadata_only(
|
| 58 |
-
changed_files: Iterable[str],
|
| 59 |
-
diffs_by_file: dict[str, str],
|
| 60 |
-
) -> bool:
|
| 61 |
-
files = tuple(path.strip().replace("\\", "/") for path in changed_files if path)
|
| 62 |
-
allowed_files = RELEASE_METADATA_FILES | RELEASE_GENERATED_STATS_FILES
|
| 63 |
-
if not files or any(path not in allowed_files for path in files):
|
| 64 |
-
return False
|
| 65 |
-
if not any(path in RELEASE_METADATA_FILES for path in files):
|
| 66 |
-
return False
|
| 67 |
-
|
| 68 |
-
for path in files:
|
| 69 |
-
if path == "CHANGELOG.md":
|
| 70 |
-
continue
|
| 71 |
-
if path in RELEASE_GENERATED_STATS_FILES:
|
| 72 |
-
for line in diffs_by_file.get(path, "").splitlines():
|
| 73 |
-
if not line.startswith(("+", "-")) or line.startswith(("+++", "---")):
|
| 74 |
-
continue
|
| 75 |
-
text = line[1:].strip()
|
| 76 |
-
if not TEST_COUNT_STATS_RE.fullmatch(text) and not (
|
| 77 |
-
path == "docs/index.md" and RELEASE_DOCS_LINE_RE.fullmatch(text)
|
| 78 |
-
):
|
| 79 |
-
return False
|
| 80 |
-
continue
|
| 81 |
-
expected = VERSION_LINE_RE if path == "pyproject.toml" else INIT_VERSION_LINE_RE
|
| 82 |
-
for line in diffs_by_file.get(path, "").splitlines():
|
| 83 |
-
if not line.startswith(("+", "-")) or line.startswith(("+++", "---")):
|
| 84 |
-
continue
|
| 85 |
-
if not expected.fullmatch(line[1:].strip()):
|
| 86 |
-
return False
|
| 87 |
-
return True
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
def evaluate_policy(
|
| 91 |
-
changed_files: Iterable[str],
|
| 92 |
-
labels: Iterable[str],
|
| 93 |
-
diffs_by_file: dict[str, str],
|
| 94 |
-
) -> PolicyResult:
|
| 95 |
-
files = tuple(path.strip().replace("\\", "/") for path in changed_files if path)
|
| 96 |
-
contract = tuple(path for path in files if is_contract_file(path))
|
| 97 |
-
tests = tuple(path for path in files if is_test_file(path))
|
| 98 |
-
if not contract:
|
| 99 |
-
return PolicyResult(True, "No product or CI/package contract changes.")
|
| 100 |
-
if tests:
|
| 101 |
-
return PolicyResult(True, "Policy satisfied.", contract, tests)
|
| 102 |
-
if "no-tests-needed" in set(labels):
|
| 103 |
-
return PolicyResult(True, "Policy exempted by no-tests-needed label.", contract)
|
| 104 |
-
if is_release_metadata_only(files, diffs_by_file):
|
| 105 |
-
return PolicyResult(True, "Policy exempted for release metadata-only changes.", contract)
|
| 106 |
-
return PolicyResult(False, "Contract files changed without accompanying tests.", contract)
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
def _git_lines(*args: str) -> tuple[str, ...]:
|
| 110 |
-
proc = subprocess.run(
|
| 111 |
-
["git", *args],
|
| 112 |
-
check=True,
|
| 113 |
-
text=True,
|
| 114 |
-
stdout=subprocess.PIPE,
|
| 115 |
-
)
|
| 116 |
-
return tuple(line.strip() for line in proc.stdout.splitlines() if line.strip())
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
def _git_text(*args: str) -> str:
|
| 120 |
-
proc = subprocess.run(
|
| 121 |
-
["git", *args],
|
| 122 |
-
check=True,
|
| 123 |
-
text=True,
|
| 124 |
-
stdout=subprocess.PIPE,
|
| 125 |
-
)
|
| 126 |
-
return proc.stdout
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
def _changed_files(base: str, head: str) -> tuple[str, ...]:
|
| 130 |
-
return _git_lines("diff", "--name-only", base, head)
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
def _diffs_by_file(base: str, head: str, files: Iterable[str]) -> dict[str, str]:
|
| 134 |
-
return {
|
| 135 |
-
path: _git_text("diff", "--unified=0", base, head, "--", path)
|
| 136 |
-
for path in files
|
| 137 |
-
}
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
def _parse_labels(raw: str) -> tuple[str, ...]:
|
| 141 |
-
try:
|
| 142 |
-
labels = json.loads(raw)
|
| 143 |
-
except json.JSONDecodeError:
|
| 144 |
-
return ()
|
| 145 |
-
if not isinstance(labels, list):
|
| 146 |
-
return ()
|
| 147 |
-
return tuple(label for label in labels if isinstance(label, str))
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
def main(argv: list[str] | None = None) -> int:
|
| 151 |
-
parser = argparse.ArgumentParser()
|
| 152 |
-
parser.add_argument("--base", required=True)
|
| 153 |
-
parser.add_argument("--head", required=True)
|
| 154 |
-
parser.add_argument("--labels-json", default="[]")
|
| 155 |
-
args = parser.parse_args(argv)
|
| 156 |
-
|
| 157 |
-
files = _changed_files(args.base, args.head)
|
| 158 |
-
result = evaluate_policy(
|
| 159 |
-
files,
|
| 160 |
-
_parse_labels(args.labels_json),
|
| 161 |
-
_diffs_by_file(args.base, args.head, files),
|
| 162 |
-
)
|
| 163 |
-
print(result.message)
|
| 164 |
-
if result.contract_files:
|
| 165 |
-
print("Contract files:")
|
| 166 |
-
print("\n".join(result.contract_files))
|
| 167 |
-
if result.test_files:
|
| 168 |
-
print("Test files:")
|
| 169 |
-
print("\n".join(result.test_files))
|
| 170 |
-
if not result.passed:
|
| 171 |
-
print("::error::Policy violation - contract files changed but no tests changed.")
|
| 172 |
-
print("Fix: add/update tests, or use release metadata-only changes.")
|
| 173 |
-
return 1
|
| 174 |
-
return 0
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
if __name__ == "__main__":
|
| 178 |
-
raise SystemExit(main())
|
|
|
|
| 1 |
+
"""Enforce that product/CI contract changes include test changes."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
import re
|
| 8 |
+
import subprocess
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
from typing import Iterable
|
| 11 |
+
|
| 12 |
+
RELEASE_METADATA_FILES = {
|
| 13 |
+
"CHANGELOG.md",
|
| 14 |
+
"pyproject.toml",
|
| 15 |
+
"src/__init__.py",
|
| 16 |
+
"src/ctx/__init__.py",
|
| 17 |
+
}
|
| 18 |
+
RELEASE_GENERATED_STATS_FILES = {
|
| 19 |
+
"README.md",
|
| 20 |
+
"docs/index.md",
|
| 21 |
+
}
|
| 22 |
+
VERSION_LINE_RE = re.compile(r'version = "\d+\.\d+\.\d+(?:[-+._a-zA-Z0-9]*)?"')
|
| 23 |
+
INIT_VERSION_LINE_RE = re.compile(
|
| 24 |
+
r'__version__ = "\d+\.\d+\.\d+(?:[-+._a-zA-Z0-9]*)?"'
|
| 25 |
+
)
|
| 26 |
+
TEST_COUNT_STATS_RE = re.compile(
|
| 27 |
+
r".*(Tests-\d+_collected|[\d,]+ tests collected).*"
|
| 28 |
+
)
|
| 29 |
+
RELEASE_DOCS_LINE_RE = re.compile(r"\*\*v\d+\.\d+\.\d+(?:[-+._a-zA-Z0-9]*)?\*\*.*")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@dataclass(frozen=True)
|
| 33 |
+
class PolicyResult:
|
| 34 |
+
passed: bool
|
| 35 |
+
message: str
|
| 36 |
+
contract_files: tuple[str, ...] = ()
|
| 37 |
+
test_files: tuple[str, ...] = ()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def is_contract_file(path: str) -> bool:
|
| 41 |
+
return (
|
| 42 |
+
(path.startswith("src/") and path.endswith((".py", ".json")))
|
| 43 |
+
or path.startswith("scripts/ci_")
|
| 44 |
+
or path == "scripts/clean_host_contract.py"
|
| 45 |
+
or path == "pyproject.toml"
|
| 46 |
+
or (
|
| 47 |
+
path.startswith(".github/workflows/")
|
| 48 |
+
and path.endswith((".yml", ".yaml"))
|
| 49 |
+
)
|
| 50 |
+
) and not path.startswith("src/tests/")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def is_test_file(path: str) -> bool:
|
| 54 |
+
return path.startswith("src/tests/") and path.endswith((".py", ".json"))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def is_release_metadata_only(
|
| 58 |
+
changed_files: Iterable[str],
|
| 59 |
+
diffs_by_file: dict[str, str],
|
| 60 |
+
) -> bool:
|
| 61 |
+
files = tuple(path.strip().replace("\\", "/") for path in changed_files if path)
|
| 62 |
+
allowed_files = RELEASE_METADATA_FILES | RELEASE_GENERATED_STATS_FILES
|
| 63 |
+
if not files or any(path not in allowed_files for path in files):
|
| 64 |
+
return False
|
| 65 |
+
if not any(path in RELEASE_METADATA_FILES for path in files):
|
| 66 |
+
return False
|
| 67 |
+
|
| 68 |
+
for path in files:
|
| 69 |
+
if path == "CHANGELOG.md":
|
| 70 |
+
continue
|
| 71 |
+
if path in RELEASE_GENERATED_STATS_FILES:
|
| 72 |
+
for line in diffs_by_file.get(path, "").splitlines():
|
| 73 |
+
if not line.startswith(("+", "-")) or line.startswith(("+++", "---")):
|
| 74 |
+
continue
|
| 75 |
+
text = line[1:].strip()
|
| 76 |
+
if not TEST_COUNT_STATS_RE.fullmatch(text) and not (
|
| 77 |
+
path == "docs/index.md" and RELEASE_DOCS_LINE_RE.fullmatch(text)
|
| 78 |
+
):
|
| 79 |
+
return False
|
| 80 |
+
continue
|
| 81 |
+
expected = VERSION_LINE_RE if path == "pyproject.toml" else INIT_VERSION_LINE_RE
|
| 82 |
+
for line in diffs_by_file.get(path, "").splitlines():
|
| 83 |
+
if not line.startswith(("+", "-")) or line.startswith(("+++", "---")):
|
| 84 |
+
continue
|
| 85 |
+
if not expected.fullmatch(line[1:].strip()):
|
| 86 |
+
return False
|
| 87 |
+
return True
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def evaluate_policy(
|
| 91 |
+
changed_files: Iterable[str],
|
| 92 |
+
labels: Iterable[str],
|
| 93 |
+
diffs_by_file: dict[str, str],
|
| 94 |
+
) -> PolicyResult:
|
| 95 |
+
files = tuple(path.strip().replace("\\", "/") for path in changed_files if path)
|
| 96 |
+
contract = tuple(path for path in files if is_contract_file(path))
|
| 97 |
+
tests = tuple(path for path in files if is_test_file(path))
|
| 98 |
+
if not contract:
|
| 99 |
+
return PolicyResult(True, "No product or CI/package contract changes.")
|
| 100 |
+
if tests:
|
| 101 |
+
return PolicyResult(True, "Policy satisfied.", contract, tests)
|
| 102 |
+
if "no-tests-needed" in set(labels):
|
| 103 |
+
return PolicyResult(True, "Policy exempted by no-tests-needed label.", contract)
|
| 104 |
+
if is_release_metadata_only(files, diffs_by_file):
|
| 105 |
+
return PolicyResult(True, "Policy exempted for release metadata-only changes.", contract)
|
| 106 |
+
return PolicyResult(False, "Contract files changed without accompanying tests.", contract)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _git_lines(*args: str) -> tuple[str, ...]:
|
| 110 |
+
proc = subprocess.run(
|
| 111 |
+
["git", *args],
|
| 112 |
+
check=True,
|
| 113 |
+
text=True,
|
| 114 |
+
stdout=subprocess.PIPE,
|
| 115 |
+
)
|
| 116 |
+
return tuple(line.strip() for line in proc.stdout.splitlines() if line.strip())
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _git_text(*args: str) -> str:
|
| 120 |
+
proc = subprocess.run(
|
| 121 |
+
["git", *args],
|
| 122 |
+
check=True,
|
| 123 |
+
text=True,
|
| 124 |
+
stdout=subprocess.PIPE,
|
| 125 |
+
)
|
| 126 |
+
return proc.stdout
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _changed_files(base: str, head: str) -> tuple[str, ...]:
|
| 130 |
+
return _git_lines("diff", "--name-only", base, head)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _diffs_by_file(base: str, head: str, files: Iterable[str]) -> dict[str, str]:
|
| 134 |
+
return {
|
| 135 |
+
path: _git_text("diff", "--unified=0", base, head, "--", path)
|
| 136 |
+
for path in files
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _parse_labels(raw: str) -> tuple[str, ...]:
|
| 141 |
+
try:
|
| 142 |
+
labels = json.loads(raw)
|
| 143 |
+
except json.JSONDecodeError:
|
| 144 |
+
return ()
|
| 145 |
+
if not isinstance(labels, list):
|
| 146 |
+
return ()
|
| 147 |
+
return tuple(label for label in labels if isinstance(label, str))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def main(argv: list[str] | None = None) -> int:
|
| 151 |
+
parser = argparse.ArgumentParser()
|
| 152 |
+
parser.add_argument("--base", required=True)
|
| 153 |
+
parser.add_argument("--head", required=True)
|
| 154 |
+
parser.add_argument("--labels-json", default="[]")
|
| 155 |
+
args = parser.parse_args(argv)
|
| 156 |
+
|
| 157 |
+
files = _changed_files(args.base, args.head)
|
| 158 |
+
result = evaluate_policy(
|
| 159 |
+
files,
|
| 160 |
+
_parse_labels(args.labels_json),
|
| 161 |
+
_diffs_by_file(args.base, args.head, files),
|
| 162 |
+
)
|
| 163 |
+
print(result.message)
|
| 164 |
+
if result.contract_files:
|
| 165 |
+
print("Contract files:")
|
| 166 |
+
print("\n".join(result.contract_files))
|
| 167 |
+
if result.test_files:
|
| 168 |
+
print("Test files:")
|
| 169 |
+
print("\n".join(result.test_files))
|
| 170 |
+
if not result.passed:
|
| 171 |
+
print("::error::Policy violation - contract files changed but no tests changed.")
|
| 172 |
+
print("Fix: add/update tests, or use release metadata-only changes.")
|
| 173 |
+
return 1
|
| 174 |
+
return 0
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
if __name__ == "__main__":
|
| 178 |
+
raise SystemExit(main())
|
scripts/ci_preflight.py
CHANGED
|
@@ -1,308 +1,308 @@
|
|
| 1 |
-
"""Run local checks that mirror the required GitHub PR gates.
|
| 2 |
-
|
| 3 |
-
This is intentionally conservative: it uses the same path classifier as
|
| 4 |
-
`.github/workflows/test.yml`, runs the local equivalents of required jobs, and
|
| 5 |
-
prints any CI-only coverage that cannot be reproduced on the current OS.
|
| 6 |
-
"""
|
| 7 |
-
|
| 8 |
-
from __future__ import annotations
|
| 9 |
-
|
| 10 |
-
import argparse
|
| 11 |
-
from dataclasses import dataclass
|
| 12 |
-
import os
|
| 13 |
-
from pathlib import Path
|
| 14 |
-
import shutil
|
| 15 |
-
import subprocess
|
| 16 |
-
import sys
|
| 17 |
-
import time
|
| 18 |
-
|
| 19 |
-
REPO_ROOT = Path(__file__).resolve().parents[1]
|
| 20 |
-
if str(REPO_ROOT) not in sys.path:
|
| 21 |
-
sys.path.insert(0, str(REPO_ROOT))
|
| 22 |
-
|
| 23 |
-
from scripts.ci_classifier import classify_paths # noqa: E402
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
GRAPH_VALIDATE_ARGS = (
|
| 27 |
-
"src/validate_graph_artifacts.py",
|
| 28 |
-
"--graph-dir",
|
| 29 |
-
"graph",
|
| 30 |
-
"--deep",
|
| 31 |
-
"--min-nodes",
|
| 32 |
-
"100000",
|
| 33 |
-
"--min-edges",
|
| 34 |
-
"2000000",
|
| 35 |
-
"--min-skills-sh-nodes",
|
| 36 |
-
"89000",
|
| 37 |
-
"--min-semantic-edges",
|
| 38 |
-
"1000000",
|
| 39 |
-
"--expected-nodes",
|
| 40 |
-
"102928",
|
| 41 |
-
"--expected-edges",
|
| 42 |
-
"2913960",
|
| 43 |
-
"--expected-semantic-edges",
|
| 44 |
-
"1683193",
|
| 45 |
-
"--expected-harness-nodes",
|
| 46 |
-
"207",
|
| 47 |
-
"--expected-skills-sh-nodes",
|
| 48 |
-
"89471",
|
| 49 |
-
"--expected-skills-sh-catalog-entries",
|
| 50 |
-
"89465",
|
| 51 |
-
"--expected-skills-sh-converted",
|
| 52 |
-
"89465",
|
| 53 |
-
"--expected-skill-pages",
|
| 54 |
-
"91464",
|
| 55 |
-
"--expected-agent-pages",
|
| 56 |
-
"467",
|
| 57 |
-
"--expected-mcp-pages",
|
| 58 |
-
"10790",
|
| 59 |
-
"--expected-harness-pages",
|
| 60 |
-
"207",
|
| 61 |
-
"--line-threshold",
|
| 62 |
-
"180",
|
| 63 |
-
"--max-stage-lines",
|
| 64 |
-
"40",
|
| 65 |
-
)
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
@dataclass(frozen=True)
|
| 69 |
-
class Check:
|
| 70 |
-
name: str
|
| 71 |
-
argv: tuple[str, ...]
|
| 72 |
-
env: dict[str, str] | None = None
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
def _run_git(args: list[str], *, allow_failure: bool = False) -> list[str]:
|
| 76 |
-
proc = subprocess.run(
|
| 77 |
-
["git", *args],
|
| 78 |
-
check=False,
|
| 79 |
-
capture_output=True,
|
| 80 |
-
text=True,
|
| 81 |
-
)
|
| 82 |
-
if proc.returncode != 0:
|
| 83 |
-
if allow_failure:
|
| 84 |
-
return []
|
| 85 |
-
raise RuntimeError(proc.stderr.strip() or proc.stdout.strip())
|
| 86 |
-
return [line.strip() for line in proc.stdout.splitlines() if line.strip()]
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
def changed_files(base_ref: str) -> list[str]:
|
| 90 |
-
merge_base = _run_git(["merge-base", base_ref, "HEAD"], allow_failure=True)
|
| 91 |
-
base = merge_base[0] if merge_base else base_ref
|
| 92 |
-
paths = set(_run_git(["diff", "--name-only", base, "HEAD"], allow_failure=True))
|
| 93 |
-
paths.update(_run_git(["diff", "--name-only"], allow_failure=True))
|
| 94 |
-
paths.update(_run_git(["diff", "--cached", "--name-only"], allow_failure=True))
|
| 95 |
-
paths.update(
|
| 96 |
-
_run_git(["ls-files", "--others", "--exclude-standard"], allow_failure=True)
|
| 97 |
-
)
|
| 98 |
-
return sorted(path.replace("\\", "/") for path in paths)
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
def select_checks(
|
| 102 |
-
*,
|
| 103 |
-
base_ref: str,
|
| 104 |
-
files: list[str],
|
| 105 |
-
profile: str,
|
| 106 |
-
python: str,
|
| 107 |
-
) -> tuple[list[Check], list[str]]:
|
| 108 |
-
flags = classify_paths(files)
|
| 109 |
-
checks: list[Check] = [
|
| 110 |
-
Check("whitespace", ("git", "diff", "--check")),
|
| 111 |
-
Check("repo stats", (python, "src/update_repo_stats.py", "--check")),
|
| 112 |
-
]
|
| 113 |
-
notes = [
|
| 114 |
-
"GitHub still runs Windows/macOS matrix jobs; local preflight covers the "
|
| 115 |
-
"same contracts on this host."
|
| 116 |
-
]
|
| 117 |
-
|
| 118 |
-
source_required = profile == "full" or (
|
| 119 |
-
not flags["docs_only"] and not flags["graph_only"]
|
| 120 |
-
)
|
| 121 |
-
if source_required:
|
| 122 |
-
checks.extend(
|
| 123 |
-
[
|
| 124 |
-
Check("ruff", (python, "-m", "ruff", "check", "src", "hooks", "scripts")),
|
| 125 |
-
Check("mypy", (python, "-m", "mypy", "src")),
|
| 126 |
-
Check("pip check", (python, "-m", "pip", "check")),
|
| 127 |
-
Check(
|
| 128 |
-
"unit-linux equivalent",
|
| 129 |
-
(
|
| 130 |
-
python,
|
| 131 |
-
"-m",
|
| 132 |
-
"pytest",
|
| 133 |
-
"-q",
|
| 134 |
-
"-m",
|
| 135 |
-
"not browser and not integration",
|
| 136 |
-
"--cov=src",
|
| 137 |
-
"--cov-report=term-missing",
|
| 138 |
-
"--cov-fail-under=40",
|
| 139 |
-
),
|
| 140 |
-
),
|
| 141 |
-
Check(
|
| 142 |
-
"A-Z canary",
|
| 143 |
-
(
|
| 144 |
-
python,
|
| 145 |
-
"-m",
|
| 146 |
-
"pytest",
|
| 147 |
-
"-q",
|
| 148 |
-
"--no-cov",
|
| 149 |
-
"src/tests/test_alive_loop_e2e.py",
|
| 150 |
-
"src/tests/test_fuzz_yaml_rendering.py",
|
| 151 |
-
),
|
| 152 |
-
),
|
| 153 |
-
Check(
|
| 154 |
-
"contract compatibility local",
|
| 155 |
-
(
|
| 156 |
-
python,
|
| 157 |
-
"-m",
|
| 158 |
-
"pytest",
|
| 159 |
-
"-q",
|
| 160 |
-
"--no-cov",
|
| 161 |
-
"src/tests/test_clean_host_contract.py",
|
| 162 |
-
"src/tests/test_package_scaffold.py",
|
| 163 |
-
),
|
| 164 |
-
),
|
| 165 |
-
Check(
|
| 166 |
-
"clean host contract",
|
| 167 |
-
(python, "scripts/clean_host_contract.py", "--fast"),
|
| 168 |
-
),
|
| 169 |
-
]
|
| 170 |
-
)
|
| 171 |
-
|
| 172 |
-
if flags["docs_changed"]:
|
| 173 |
-
checks.append(
|
| 174 |
-
Check("docs strict build", (python, "-m", "mkdocs", "build", "--strict"))
|
| 175 |
-
)
|
| 176 |
-
|
| 177 |
-
if flags["graph_artifact_changed"]:
|
| 178 |
-
checks.append(Check("graph artifact validation", (python, *GRAPH_VALIDATE_ARGS)))
|
| 179 |
-
|
| 180 |
-
if source_required and flags["similarity_changed"]:
|
| 181 |
-
checks.append(
|
| 182 |
-
Check(
|
| 183 |
-
"similarity precision/recall",
|
| 184 |
-
(
|
| 185 |
-
python,
|
| 186 |
-
"-m",
|
| 187 |
-
"pytest",
|
| 188 |
-
"-q",
|
| 189 |
-
"--no-cov",
|
| 190 |
-
"-m",
|
| 191 |
-
"integration",
|
| 192 |
-
"src/tests/test_similarity_precision_recall.py",
|
| 193 |
-
),
|
| 194 |
-
env={"CTX_REQUIRE_SIMILARITY_EVAL": "1"},
|
| 195 |
-
)
|
| 196 |
-
)
|
| 197 |
-
|
| 198 |
-
if source_required and flags["browser_changed"]:
|
| 199 |
-
checks.append(
|
| 200 |
-
Check(
|
| 201 |
-
"browser monitor security",
|
| 202 |
-
(
|
| 203 |
-
python,
|
| 204 |
-
"-m",
|
| 205 |
-
"pytest",
|
| 206 |
-
"-q",
|
| 207 |
-
"--no-cov",
|
| 208 |
-
"-m",
|
| 209 |
-
"browser",
|
| 210 |
-
"src/tests/test_ctx_monitor_browser.py",
|
| 211 |
-
),
|
| 212 |
-
)
|
| 213 |
-
)
|
| 214 |
-
|
| 215 |
-
if source_required:
|
| 216 |
-
out_dir = ".ci-preflight-dist"
|
| 217 |
-
twine_script = (
|
| 218 |
-
"import glob, subprocess, sys; "
|
| 219 |
-
f"files=glob.glob({str(out_dir + '/*')!r}); "
|
| 220 |
-
"sys.exit(2 if not files else subprocess.call("
|
| 221 |
-
"[sys.executable, '-m', 'twine', 'check', *files]))"
|
| 222 |
-
)
|
| 223 |
-
checks.extend(
|
| 224 |
-
[
|
| 225 |
-
Check(
|
| 226 |
-
"clean preflight dist",
|
| 227 |
-
(
|
| 228 |
-
python,
|
| 229 |
-
"-c",
|
| 230 |
-
f"import shutil; shutil.rmtree({out_dir!r}, ignore_errors=True)",
|
| 231 |
-
),
|
| 232 |
-
),
|
| 233 |
-
Check("build wheel", (python, "-m", "build", "--outdir", out_dir)),
|
| 234 |
-
Check("twine check", (python, "-c", twine_script)),
|
| 235 |
-
]
|
| 236 |
-
)
|
| 237 |
-
|
| 238 |
-
if files:
|
| 239 |
-
notes.insert(0, f"Changed files vs {base_ref}: {len(files)}")
|
| 240 |
-
else:
|
| 241 |
-
notes.insert(0, "No changed files detected; running baseline cheap checks only.")
|
| 242 |
-
|
| 243 |
-
return checks, notes
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
def run_checks(checks: list[Check], *, dry_run: bool) -> int:
|
| 247 |
-
for index, check in enumerate(checks, start=1):
|
| 248 |
-
print(f"[{index}/{len(checks)}] {check.name}: {' '.join(check.argv)}", flush=True)
|
| 249 |
-
if dry_run:
|
| 250 |
-
continue
|
| 251 |
-
env = os.environ.copy()
|
| 252 |
-
if check.env:
|
| 253 |
-
env.update(check.env)
|
| 254 |
-
start = time.monotonic()
|
| 255 |
-
proc = subprocess.run(check.argv, check=False, env=env)
|
| 256 |
-
elapsed = time.monotonic() - start
|
| 257 |
-
if proc.returncode != 0:
|
| 258 |
-
print(
|
| 259 |
-
f"[fail] {check.name} exited {proc.returncode} after {elapsed:.1f}s",
|
| 260 |
-
file=sys.stderr,
|
| 261 |
-
)
|
| 262 |
-
return proc.returncode
|
| 263 |
-
print(f"[pass] {check.name} in {elapsed:.1f}s", flush=True)
|
| 264 |
-
return 0
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
def main(argv: list[str] | None = None) -> int:
|
| 268 |
-
parser = argparse.ArgumentParser(description=__doc__)
|
| 269 |
-
parser.add_argument(
|
| 270 |
-
"--base",
|
| 271 |
-
default="origin/main",
|
| 272 |
-
help="base ref for changed-file detection",
|
| 273 |
-
)
|
| 274 |
-
parser.add_argument(
|
| 275 |
-
"--profile",
|
| 276 |
-
choices=("pr", "full"),
|
| 277 |
-
default="pr",
|
| 278 |
-
help="pr mirrors required PR checks; full forces source gates for any change set",
|
| 279 |
-
)
|
| 280 |
-
parser.add_argument(
|
| 281 |
-
"--python",
|
| 282 |
-
default=sys.executable,
|
| 283 |
-
help="Python executable to run checks with",
|
| 284 |
-
)
|
| 285 |
-
parser.add_argument(
|
| 286 |
-
"--dry-run",
|
| 287 |
-
action="store_true",
|
| 288 |
-
help="print selected checks without running them",
|
| 289 |
-
)
|
| 290 |
-
args = parser.parse_args(argv)
|
| 291 |
-
|
| 292 |
-
if not shutil.which("git"):
|
| 293 |
-
raise SystemExit("git is required for ci_preflight")
|
| 294 |
-
|
| 295 |
-
files = changed_files(args.base)
|
| 296 |
-
checks, notes = select_checks(
|
| 297 |
-
base_ref=args.base,
|
| 298 |
-
files=files,
|
| 299 |
-
profile=args.profile,
|
| 300 |
-
python=args.python,
|
| 301 |
-
)
|
| 302 |
-
for note in notes:
|
| 303 |
-
print(f"[note] {note}")
|
| 304 |
-
return run_checks(checks, dry_run=args.dry_run)
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
if __name__ == "__main__":
|
| 308 |
-
raise SystemExit(main())
|
|
|
|
| 1 |
+
"""Run local checks that mirror the required GitHub PR gates.
|
| 2 |
+
|
| 3 |
+
This is intentionally conservative: it uses the same path classifier as
|
| 4 |
+
`.github/workflows/test.yml`, runs the local equivalents of required jobs, and
|
| 5 |
+
prints any CI-only coverage that cannot be reproduced on the current OS.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
from dataclasses import dataclass
|
| 12 |
+
import os
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
import shutil
|
| 15 |
+
import subprocess
|
| 16 |
+
import sys
|
| 17 |
+
import time
|
| 18 |
+
|
| 19 |
+
REPO_ROOT = Path(__file__).resolve().parents[1]
|
| 20 |
+
if str(REPO_ROOT) not in sys.path:
|
| 21 |
+
sys.path.insert(0, str(REPO_ROOT))
|
| 22 |
+
|
| 23 |
+
from scripts.ci_classifier import classify_paths # noqa: E402
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
GRAPH_VALIDATE_ARGS = (
|
| 27 |
+
"src/validate_graph_artifacts.py",
|
| 28 |
+
"--graph-dir",
|
| 29 |
+
"graph",
|
| 30 |
+
"--deep",
|
| 31 |
+
"--min-nodes",
|
| 32 |
+
"100000",
|
| 33 |
+
"--min-edges",
|
| 34 |
+
"2000000",
|
| 35 |
+
"--min-skills-sh-nodes",
|
| 36 |
+
"89000",
|
| 37 |
+
"--min-semantic-edges",
|
| 38 |
+
"1000000",
|
| 39 |
+
"--expected-nodes",
|
| 40 |
+
"102928",
|
| 41 |
+
"--expected-edges",
|
| 42 |
+
"2913960",
|
| 43 |
+
"--expected-semantic-edges",
|
| 44 |
+
"1683193",
|
| 45 |
+
"--expected-harness-nodes",
|
| 46 |
+
"207",
|
| 47 |
+
"--expected-skills-sh-nodes",
|
| 48 |
+
"89471",
|
| 49 |
+
"--expected-skills-sh-catalog-entries",
|
| 50 |
+
"89465",
|
| 51 |
+
"--expected-skills-sh-converted",
|
| 52 |
+
"89465",
|
| 53 |
+
"--expected-skill-pages",
|
| 54 |
+
"91464",
|
| 55 |
+
"--expected-agent-pages",
|
| 56 |
+
"467",
|
| 57 |
+
"--expected-mcp-pages",
|
| 58 |
+
"10790",
|
| 59 |
+
"--expected-harness-pages",
|
| 60 |
+
"207",
|
| 61 |
+
"--line-threshold",
|
| 62 |
+
"180",
|
| 63 |
+
"--max-stage-lines",
|
| 64 |
+
"40",
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@dataclass(frozen=True)
|
| 69 |
+
class Check:
|
| 70 |
+
name: str
|
| 71 |
+
argv: tuple[str, ...]
|
| 72 |
+
env: dict[str, str] | None = None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _run_git(args: list[str], *, allow_failure: bool = False) -> list[str]:
|
| 76 |
+
proc = subprocess.run(
|
| 77 |
+
["git", *args],
|
| 78 |
+
check=False,
|
| 79 |
+
capture_output=True,
|
| 80 |
+
text=True,
|
| 81 |
+
)
|
| 82 |
+
if proc.returncode != 0:
|
| 83 |
+
if allow_failure:
|
| 84 |
+
return []
|
| 85 |
+
raise RuntimeError(proc.stderr.strip() or proc.stdout.strip())
|
| 86 |
+
return [line.strip() for line in proc.stdout.splitlines() if line.strip()]
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def changed_files(base_ref: str) -> list[str]:
|
| 90 |
+
merge_base = _run_git(["merge-base", base_ref, "HEAD"], allow_failure=True)
|
| 91 |
+
base = merge_base[0] if merge_base else base_ref
|
| 92 |
+
paths = set(_run_git(["diff", "--name-only", base, "HEAD"], allow_failure=True))
|
| 93 |
+
paths.update(_run_git(["diff", "--name-only"], allow_failure=True))
|
| 94 |
+
paths.update(_run_git(["diff", "--cached", "--name-only"], allow_failure=True))
|
| 95 |
+
paths.update(
|
| 96 |
+
_run_git(["ls-files", "--others", "--exclude-standard"], allow_failure=True)
|
| 97 |
+
)
|
| 98 |
+
return sorted(path.replace("\\", "/") for path in paths)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def select_checks(
|
| 102 |
+
*,
|
| 103 |
+
base_ref: str,
|
| 104 |
+
files: list[str],
|
| 105 |
+
profile: str,
|
| 106 |
+
python: str,
|
| 107 |
+
) -> tuple[list[Check], list[str]]:
|
| 108 |
+
flags = classify_paths(files)
|
| 109 |
+
checks: list[Check] = [
|
| 110 |
+
Check("whitespace", ("git", "diff", "--check")),
|
| 111 |
+
Check("repo stats", (python, "src/update_repo_stats.py", "--check")),
|
| 112 |
+
]
|
| 113 |
+
notes = [
|
| 114 |
+
"GitHub still runs Windows/macOS matrix jobs; local preflight covers the "
|
| 115 |
+
"same contracts on this host."
|
| 116 |
+
]
|
| 117 |
+
|
| 118 |
+
source_required = profile == "full" or (
|
| 119 |
+
not flags["docs_only"] and not flags["graph_only"]
|
| 120 |
+
)
|
| 121 |
+
if source_required:
|
| 122 |
+
checks.extend(
|
| 123 |
+
[
|
| 124 |
+
Check("ruff", (python, "-m", "ruff", "check", "src", "hooks", "scripts")),
|
| 125 |
+
Check("mypy", (python, "-m", "mypy", "src")),
|
| 126 |
+
Check("pip check", (python, "-m", "pip", "check")),
|
| 127 |
+
Check(
|
| 128 |
+
"unit-linux equivalent",
|
| 129 |
+
(
|
| 130 |
+
python,
|
| 131 |
+
"-m",
|
| 132 |
+
"pytest",
|
| 133 |
+
"-q",
|
| 134 |
+
"-m",
|
| 135 |
+
"not browser and not integration",
|
| 136 |
+
"--cov=src",
|
| 137 |
+
"--cov-report=term-missing",
|
| 138 |
+
"--cov-fail-under=40",
|
| 139 |
+
),
|
| 140 |
+
),
|
| 141 |
+
Check(
|
| 142 |
+
"A-Z canary",
|
| 143 |
+
(
|
| 144 |
+
python,
|
| 145 |
+
"-m",
|
| 146 |
+
"pytest",
|
| 147 |
+
"-q",
|
| 148 |
+
"--no-cov",
|
| 149 |
+
"src/tests/test_alive_loop_e2e.py",
|
| 150 |
+
"src/tests/test_fuzz_yaml_rendering.py",
|
| 151 |
+
),
|
| 152 |
+
),
|
| 153 |
+
Check(
|
| 154 |
+
"contract compatibility local",
|
| 155 |
+
(
|
| 156 |
+
python,
|
| 157 |
+
"-m",
|
| 158 |
+
"pytest",
|
| 159 |
+
"-q",
|
| 160 |
+
"--no-cov",
|
| 161 |
+
"src/tests/test_clean_host_contract.py",
|
| 162 |
+
"src/tests/test_package_scaffold.py",
|
| 163 |
+
),
|
| 164 |
+
),
|
| 165 |
+
Check(
|
| 166 |
+
"clean host contract",
|
| 167 |
+
(python, "scripts/clean_host_contract.py", "--fast"),
|
| 168 |
+
),
|
| 169 |
+
]
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
if flags["docs_changed"]:
|
| 173 |
+
checks.append(
|
| 174 |
+
Check("docs strict build", (python, "-m", "mkdocs", "build", "--strict"))
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
if flags["graph_artifact_changed"]:
|
| 178 |
+
checks.append(Check("graph artifact validation", (python, *GRAPH_VALIDATE_ARGS)))
|
| 179 |
+
|
| 180 |
+
if source_required and flags["similarity_changed"]:
|
| 181 |
+
checks.append(
|
| 182 |
+
Check(
|
| 183 |
+
"similarity precision/recall",
|
| 184 |
+
(
|
| 185 |
+
python,
|
| 186 |
+
"-m",
|
| 187 |
+
"pytest",
|
| 188 |
+
"-q",
|
| 189 |
+
"--no-cov",
|
| 190 |
+
"-m",
|
| 191 |
+
"integration",
|
| 192 |
+
"src/tests/test_similarity_precision_recall.py",
|
| 193 |
+
),
|
| 194 |
+
env={"CTX_REQUIRE_SIMILARITY_EVAL": "1"},
|
| 195 |
+
)
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
if source_required and flags["browser_changed"]:
|
| 199 |
+
checks.append(
|
| 200 |
+
Check(
|
| 201 |
+
"browser monitor security",
|
| 202 |
+
(
|
| 203 |
+
python,
|
| 204 |
+
"-m",
|
| 205 |
+
"pytest",
|
| 206 |
+
"-q",
|
| 207 |
+
"--no-cov",
|
| 208 |
+
"-m",
|
| 209 |
+
"browser",
|
| 210 |
+
"src/tests/test_ctx_monitor_browser.py",
|
| 211 |
+
),
|
| 212 |
+
)
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
if source_required:
|
| 216 |
+
out_dir = ".ci-preflight-dist"
|
| 217 |
+
twine_script = (
|
| 218 |
+
"import glob, subprocess, sys; "
|
| 219 |
+
f"files=glob.glob({str(out_dir + '/*')!r}); "
|
| 220 |
+
"sys.exit(2 if not files else subprocess.call("
|
| 221 |
+
"[sys.executable, '-m', 'twine', 'check', *files]))"
|
| 222 |
+
)
|
| 223 |
+
checks.extend(
|
| 224 |
+
[
|
| 225 |
+
Check(
|
| 226 |
+
"clean preflight dist",
|
| 227 |
+
(
|
| 228 |
+
python,
|
| 229 |
+
"-c",
|
| 230 |
+
f"import shutil; shutil.rmtree({out_dir!r}, ignore_errors=True)",
|
| 231 |
+
),
|
| 232 |
+
),
|
| 233 |
+
Check("build wheel", (python, "-m", "build", "--outdir", out_dir)),
|
| 234 |
+
Check("twine check", (python, "-c", twine_script)),
|
| 235 |
+
]
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
if files:
|
| 239 |
+
notes.insert(0, f"Changed files vs {base_ref}: {len(files)}")
|
| 240 |
+
else:
|
| 241 |
+
notes.insert(0, "No changed files detected; running baseline cheap checks only.")
|
| 242 |
+
|
| 243 |
+
return checks, notes
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def run_checks(checks: list[Check], *, dry_run: bool) -> int:
|
| 247 |
+
for index, check in enumerate(checks, start=1):
|
| 248 |
+
print(f"[{index}/{len(checks)}] {check.name}: {' '.join(check.argv)}", flush=True)
|
| 249 |
+
if dry_run:
|
| 250 |
+
continue
|
| 251 |
+
env = os.environ.copy()
|
| 252 |
+
if check.env:
|
| 253 |
+
env.update(check.env)
|
| 254 |
+
start = time.monotonic()
|
| 255 |
+
proc = subprocess.run(check.argv, check=False, env=env)
|
| 256 |
+
elapsed = time.monotonic() - start
|
| 257 |
+
if proc.returncode != 0:
|
| 258 |
+
print(
|
| 259 |
+
f"[fail] {check.name} exited {proc.returncode} after {elapsed:.1f}s",
|
| 260 |
+
file=sys.stderr,
|
| 261 |
+
)
|
| 262 |
+
return proc.returncode
|
| 263 |
+
print(f"[pass] {check.name} in {elapsed:.1f}s", flush=True)
|
| 264 |
+
return 0
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def main(argv: list[str] | None = None) -> int:
|
| 268 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 269 |
+
parser.add_argument(
|
| 270 |
+
"--base",
|
| 271 |
+
default="origin/main",
|
| 272 |
+
help="base ref for changed-file detection",
|
| 273 |
+
)
|
| 274 |
+
parser.add_argument(
|
| 275 |
+
"--profile",
|
| 276 |
+
choices=("pr", "full"),
|
| 277 |
+
default="pr",
|
| 278 |
+
help="pr mirrors required PR checks; full forces source gates for any change set",
|
| 279 |
+
)
|
| 280 |
+
parser.add_argument(
|
| 281 |
+
"--python",
|
| 282 |
+
default=sys.executable,
|
| 283 |
+
help="Python executable to run checks with",
|
| 284 |
+
)
|
| 285 |
+
parser.add_argument(
|
| 286 |
+
"--dry-run",
|
| 287 |
+
action="store_true",
|
| 288 |
+
help="print selected checks without running them",
|
| 289 |
+
)
|
| 290 |
+
args = parser.parse_args(argv)
|
| 291 |
+
|
| 292 |
+
if not shutil.which("git"):
|
| 293 |
+
raise SystemExit("git is required for ci_preflight")
|
| 294 |
+
|
| 295 |
+
files = changed_files(args.base)
|
| 296 |
+
checks, notes = select_checks(
|
| 297 |
+
base_ref=args.base,
|
| 298 |
+
files=files,
|
| 299 |
+
profile=args.profile,
|
| 300 |
+
python=args.python,
|
| 301 |
+
)
|
| 302 |
+
for note in notes:
|
| 303 |
+
print(f"[note] {note}")
|
| 304 |
+
return run_checks(checks, dry_run=args.dry_run)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
if __name__ == "__main__":
|
| 308 |
+
raise SystemExit(main())
|
scripts/ci_required.py
CHANGED
|
@@ -1,146 +1,146 @@
|
|
| 1 |
-
"""Validate GitHub Actions dependency results for the stable CI check."""
|
| 2 |
-
|
| 3 |
-
from __future__ import annotations
|
| 4 |
-
|
| 5 |
-
import json
|
| 6 |
-
import os
|
| 7 |
-
from typing import Any
|
| 8 |
-
|
| 9 |
-
CHEAP_PR_SKIPPABLE_JOBS = {
|
| 10 |
-
"clean-host-contract",
|
| 11 |
-
"contract-compat",
|
| 12 |
-
"e2e-canary",
|
| 13 |
-
"no-test-no-merge",
|
| 14 |
-
"package-build",
|
| 15 |
-
"package-smoke",
|
| 16 |
-
"similarity-integration",
|
| 17 |
-
"static",
|
| 18 |
-
"unit-linux",
|
| 19 |
-
}
|
| 20 |
-
REQUIRED_JOBS = {
|
| 21 |
-
"browser-security",
|
| 22 |
-
"classify",
|
| 23 |
-
"clean-host-contract",
|
| 24 |
-
"contract-compat",
|
| 25 |
-
"docs-check",
|
| 26 |
-
"e2e-canary",
|
| 27 |
-
"graph-check",
|
| 28 |
-
"no-test-no-merge",
|
| 29 |
-
"package-build",
|
| 30 |
-
"package-smoke",
|
| 31 |
-
"similarity-integration",
|
| 32 |
-
"static",
|
| 33 |
-
"test",
|
| 34 |
-
"unit-linux",
|
| 35 |
-
}
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
def _job_output(
|
| 39 |
-
needs: dict[str, dict[str, Any]],
|
| 40 |
-
job_name: str,
|
| 41 |
-
output_name: str,
|
| 42 |
-
) -> str | None:
|
| 43 |
-
outputs = needs.get(job_name, {}).get("outputs", {})
|
| 44 |
-
if not isinstance(outputs, dict):
|
| 45 |
-
return None
|
| 46 |
-
output = outputs.get(output_name)
|
| 47 |
-
return output if isinstance(output, str) else None
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
def failed_required_jobs(
|
| 51 |
-
needs: dict[str, dict[str, Any]],
|
| 52 |
-
*,
|
| 53 |
-
event_name: str,
|
| 54 |
-
) -> dict[str, str | None]:
|
| 55 |
-
failures: dict[str, str | None] = {}
|
| 56 |
-
for name in sorted(REQUIRED_JOBS - set(needs)):
|
| 57 |
-
failures[name] = "missing"
|
| 58 |
-
docs_only_pr = (
|
| 59 |
-
event_name == "pull_request"
|
| 60 |
-
and _job_output(needs, "classify", "docs_only") == "true"
|
| 61 |
-
)
|
| 62 |
-
docs_changed_pr = (
|
| 63 |
-
event_name == "pull_request"
|
| 64 |
-
and _job_output(needs, "classify", "docs_changed") == "true"
|
| 65 |
-
)
|
| 66 |
-
graph_only_pr = (
|
| 67 |
-
event_name == "pull_request"
|
| 68 |
-
and _job_output(needs, "classify", "graph_only") == "true"
|
| 69 |
-
)
|
| 70 |
-
graph_artifact_changed_pr = (
|
| 71 |
-
event_name == "pull_request"
|
| 72 |
-
and _job_output(needs, "classify", "graph_artifact_changed") == "true"
|
| 73 |
-
)
|
| 74 |
-
similarity_changed_pr = (
|
| 75 |
-
event_name == "pull_request"
|
| 76 |
-
and _job_output(needs, "classify", "similarity_changed") == "true"
|
| 77 |
-
)
|
| 78 |
-
cheap_pr = docs_only_pr or graph_only_pr
|
| 79 |
-
for name, details in sorted(needs.items()):
|
| 80 |
-
result = details.get("result")
|
| 81 |
-
if result == "success":
|
| 82 |
-
continue
|
| 83 |
-
if (
|
| 84 |
-
event_name != "pull_request"
|
| 85 |
-
and name in {"docs-check", "graph-check", "no-test-no-merge"}
|
| 86 |
-
and result == "skipped"
|
| 87 |
-
):
|
| 88 |
-
continue
|
| 89 |
-
if (
|
| 90 |
-
cheap_pr
|
| 91 |
-
and name in CHEAP_PR_SKIPPABLE_JOBS
|
| 92 |
-
and not (name == "similarity-integration" and similarity_changed_pr)
|
| 93 |
-
and result == "skipped"
|
| 94 |
-
):
|
| 95 |
-
continue
|
| 96 |
-
if (
|
| 97 |
-
event_name == "pull_request"
|
| 98 |
-
and name == "docs-check"
|
| 99 |
-
and result == "skipped"
|
| 100 |
-
and not docs_changed_pr
|
| 101 |
-
):
|
| 102 |
-
continue
|
| 103 |
-
if (
|
| 104 |
-
event_name == "pull_request"
|
| 105 |
-
and name == "graph-check"
|
| 106 |
-
and result == "skipped"
|
| 107 |
-
and not graph_artifact_changed_pr
|
| 108 |
-
):
|
| 109 |
-
continue
|
| 110 |
-
if (
|
| 111 |
-
event_name == "pull_request"
|
| 112 |
-
and name == "browser-security"
|
| 113 |
-
and result == "skipped"
|
| 114 |
-
and _job_output(needs, "classify", "browser_changed") == "false"
|
| 115 |
-
):
|
| 116 |
-
continue
|
| 117 |
-
if (
|
| 118 |
-
event_name == "pull_request"
|
| 119 |
-
and name == "similarity-integration"
|
| 120 |
-
and result == "skipped"
|
| 121 |
-
and _job_output(needs, "classify", "similarity_changed") == "false"
|
| 122 |
-
):
|
| 123 |
-
continue
|
| 124 |
-
if event_name == "pull_request" and name == "test" and result == "skipped":
|
| 125 |
-
continue
|
| 126 |
-
failures[name] = result
|
| 127 |
-
return failures
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
def main() -> int:
|
| 131 |
-
event_name = os.environ["EVENT_NAME"]
|
| 132 |
-
needs = json.loads(os.environ["NEEDS_JSON"])
|
| 133 |
-
bad = failed_required_jobs(needs, event_name=event_name)
|
| 134 |
-
|
| 135 |
-
for name, details in sorted(needs.items()):
|
| 136 |
-
print(f"{name}: {details.get('result')}")
|
| 137 |
-
|
| 138 |
-
if bad:
|
| 139 |
-
for name, result in bad.items():
|
| 140 |
-
print(f"::error::{name} finished with {result}")
|
| 141 |
-
return 1
|
| 142 |
-
return 0
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
if __name__ == "__main__":
|
| 146 |
-
raise SystemExit(main())
|
|
|
|
| 1 |
+
"""Validate GitHub Actions dependency results for the stable CI check."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
CHEAP_PR_SKIPPABLE_JOBS = {
|
| 10 |
+
"clean-host-contract",
|
| 11 |
+
"contract-compat",
|
| 12 |
+
"e2e-canary",
|
| 13 |
+
"no-test-no-merge",
|
| 14 |
+
"package-build",
|
| 15 |
+
"package-smoke",
|
| 16 |
+
"similarity-integration",
|
| 17 |
+
"static",
|
| 18 |
+
"unit-linux",
|
| 19 |
+
}
|
| 20 |
+
REQUIRED_JOBS = {
|
| 21 |
+
"browser-security",
|
| 22 |
+
"classify",
|
| 23 |
+
"clean-host-contract",
|
| 24 |
+
"contract-compat",
|
| 25 |
+
"docs-check",
|
| 26 |
+
"e2e-canary",
|
| 27 |
+
"graph-check",
|
| 28 |
+
"no-test-no-merge",
|
| 29 |
+
"package-build",
|
| 30 |
+
"package-smoke",
|
| 31 |
+
"similarity-integration",
|
| 32 |
+
"static",
|
| 33 |
+
"test",
|
| 34 |
+
"unit-linux",
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _job_output(
|
| 39 |
+
needs: dict[str, dict[str, Any]],
|
| 40 |
+
job_name: str,
|
| 41 |
+
output_name: str,
|
| 42 |
+
) -> str | None:
|
| 43 |
+
outputs = needs.get(job_name, {}).get("outputs", {})
|
| 44 |
+
if not isinstance(outputs, dict):
|
| 45 |
+
return None
|
| 46 |
+
output = outputs.get(output_name)
|
| 47 |
+
return output if isinstance(output, str) else None
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def failed_required_jobs(
|
| 51 |
+
needs: dict[str, dict[str, Any]],
|
| 52 |
+
*,
|
| 53 |
+
event_name: str,
|
| 54 |
+
) -> dict[str, str | None]:
|
| 55 |
+
failures: dict[str, str | None] = {}
|
| 56 |
+
for name in sorted(REQUIRED_JOBS - set(needs)):
|
| 57 |
+
failures[name] = "missing"
|
| 58 |
+
docs_only_pr = (
|
| 59 |
+
event_name == "pull_request"
|
| 60 |
+
and _job_output(needs, "classify", "docs_only") == "true"
|
| 61 |
+
)
|
| 62 |
+
docs_changed_pr = (
|
| 63 |
+
event_name == "pull_request"
|
| 64 |
+
and _job_output(needs, "classify", "docs_changed") == "true"
|
| 65 |
+
)
|
| 66 |
+
graph_only_pr = (
|
| 67 |
+
event_name == "pull_request"
|
| 68 |
+
and _job_output(needs, "classify", "graph_only") == "true"
|
| 69 |
+
)
|
| 70 |
+
graph_artifact_changed_pr = (
|
| 71 |
+
event_name == "pull_request"
|
| 72 |
+
and _job_output(needs, "classify", "graph_artifact_changed") == "true"
|
| 73 |
+
)
|
| 74 |
+
similarity_changed_pr = (
|
| 75 |
+
event_name == "pull_request"
|
| 76 |
+
and _job_output(needs, "classify", "similarity_changed") == "true"
|
| 77 |
+
)
|
| 78 |
+
cheap_pr = docs_only_pr or graph_only_pr
|
| 79 |
+
for name, details in sorted(needs.items()):
|
| 80 |
+
result = details.get("result")
|
| 81 |
+
if result == "success":
|
| 82 |
+
continue
|
| 83 |
+
if (
|
| 84 |
+
event_name != "pull_request"
|
| 85 |
+
and name in {"docs-check", "graph-check", "no-test-no-merge"}
|
| 86 |
+
and result == "skipped"
|
| 87 |
+
):
|
| 88 |
+
continue
|
| 89 |
+
if (
|
| 90 |
+
cheap_pr
|
| 91 |
+
and name in CHEAP_PR_SKIPPABLE_JOBS
|
| 92 |
+
and not (name == "similarity-integration" and similarity_changed_pr)
|
| 93 |
+
and result == "skipped"
|
| 94 |
+
):
|
| 95 |
+
continue
|
| 96 |
+
if (
|
| 97 |
+
event_name == "pull_request"
|
| 98 |
+
and name == "docs-check"
|
| 99 |
+
and result == "skipped"
|
| 100 |
+
and not docs_changed_pr
|
| 101 |
+
):
|
| 102 |
+
continue
|
| 103 |
+
if (
|
| 104 |
+
event_name == "pull_request"
|
| 105 |
+
and name == "graph-check"
|
| 106 |
+
and result == "skipped"
|
| 107 |
+
and not graph_artifact_changed_pr
|
| 108 |
+
):
|
| 109 |
+
continue
|
| 110 |
+
if (
|
| 111 |
+
event_name == "pull_request"
|
| 112 |
+
and name == "browser-security"
|
| 113 |
+
and result == "skipped"
|
| 114 |
+
and _job_output(needs, "classify", "browser_changed") == "false"
|
| 115 |
+
):
|
| 116 |
+
continue
|
| 117 |
+
if (
|
| 118 |
+
event_name == "pull_request"
|
| 119 |
+
and name == "similarity-integration"
|
| 120 |
+
and result == "skipped"
|
| 121 |
+
and _job_output(needs, "classify", "similarity_changed") == "false"
|
| 122 |
+
):
|
| 123 |
+
continue
|
| 124 |
+
if event_name == "pull_request" and name == "test" and result == "skipped":
|
| 125 |
+
continue
|
| 126 |
+
failures[name] = result
|
| 127 |
+
return failures
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def main() -> int:
|
| 131 |
+
event_name = os.environ["EVENT_NAME"]
|
| 132 |
+
needs = json.loads(os.environ["NEEDS_JSON"])
|
| 133 |
+
bad = failed_required_jobs(needs, event_name=event_name)
|
| 134 |
+
|
| 135 |
+
for name, details in sorted(needs.items()):
|
| 136 |
+
print(f"{name}: {details.get('result')}")
|
| 137 |
+
|
| 138 |
+
if bad:
|
| 139 |
+
for name, result in bad.items():
|
| 140 |
+
print(f"::error::{name} finished with {result}")
|
| 141 |
+
return 1
|
| 142 |
+
return 0
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
if __name__ == "__main__":
|
| 146 |
+
raise SystemExit(main())
|
scripts/clean_host_contract.py
CHANGED
|
@@ -1,57 +1,57 @@
|
|
| 1 |
-
"""Clean-host contract runner for ctx release hardening.
|
| 2 |
-
|
| 3 |
-
The contract builds the current tree into a wheel, installs it into a
|
| 4 |
-
fresh virtualenv, points all user-state environment variables at a temp
|
| 5 |
-
root, then drives real console scripts. It is intentionally not a public
|
| 6 |
-
entrypoint yet; this is release infrastructure.
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
from __future__ import annotations
|
| 10 |
-
|
| 11 |
-
import argparse
|
| 12 |
-
import json
|
| 13 |
-
import os
|
| 14 |
-
import shlex
|
| 15 |
-
import shutil
|
| 16 |
-
import subprocess
|
| 17 |
-
import sys
|
| 18 |
-
import tempfile
|
| 19 |
-
from dataclasses import dataclass
|
| 20 |
-
from pathlib import Path
|
| 21 |
-
from typing import Any, Mapping, Sequence
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
LIVE_CLAUDE_ACK_ENV = "CTX_LIVE_CLAUDE_ACK"
|
| 25 |
-
LIVE_CLAUDE_ACK_VALUE = "uses_quota"
|
| 26 |
-
LIVE_CLAUDE_DEFAULT_BUDGET_USD = 0.05
|
| 27 |
-
LIVE_CLAUDE_MAX_BUDGET_USD = 1.0
|
| 28 |
-
LIVE_CLAUDE_PROMPT_TIMEOUT_SECONDS = 180.0
|
| 29 |
-
LIVE_CLAUDE_PREFLIGHT_TIMEOUT_SECONDS = 30.0
|
| 30 |
-
|
| 31 |
-
_LIVE_CLAUDE_AUTH_EXACT_ENV = {
|
| 32 |
-
"ANTHROPIC_API_KEY",
|
| 33 |
-
"ANTHROPIC_AUTH_TOKEN",
|
| 34 |
-
"ANTHROPIC_BASE_URL",
|
| 35 |
-
"ANTHROPIC_BETA_HEADERS",
|
| 36 |
-
"CLAUDE_CODE_USE_BEDROCK",
|
| 37 |
-
"CLAUDE_CODE_USE_VERTEX",
|
| 38 |
-
"CLAUDE_CODE_USE_FOUNDRY",
|
| 39 |
-
}
|
| 40 |
-
_LIVE_CLAUDE_AUTH_PREFIX_ENV = (
|
| 41 |
-
"AWS_",
|
| 42 |
-
"GOOGLE_",
|
| 43 |
-
"GCLOUD_",
|
| 44 |
-
"VERTEXAI_",
|
| 45 |
-
"ANTHROPIC_",
|
| 46 |
-
)
|
| 47 |
_LIVE_CLAUDE_PLATFORM_ENV = {
|
| 48 |
"PATH",
|
| 49 |
"Path",
|
| 50 |
"PATHEXT",
|
| 51 |
"SYSTEMROOT",
|
| 52 |
-
"SystemRoot",
|
| 53 |
-
"WINDIR",
|
| 54 |
-
"COMSPEC",
|
| 55 |
"TEMP",
|
| 56 |
"TMP",
|
| 57 |
}
|
|
@@ -61,110 +61,110 @@ _CLEAN_HOST_PLATFORM_ENV = _LIVE_CLAUDE_PLATFORM_ENV | {
|
|
| 61 |
"TZ",
|
| 62 |
}
|
| 63 |
_EXPECTED_LIVE_CLAUDE_EVENTS = ("PostToolUse", "Stop")
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
@dataclass(frozen=True)
|
| 67 |
-
class ContractPaths:
|
| 68 |
-
root: Path
|
| 69 |
-
home: Path
|
| 70 |
-
appdata: Path
|
| 71 |
-
localappdata: Path
|
| 72 |
-
xdg_config: Path
|
| 73 |
-
xdg_cache: Path
|
| 74 |
-
pip_cache: Path
|
| 75 |
-
dist: Path
|
| 76 |
-
venv: Path
|
| 77 |
-
fake_modules: Path
|
| 78 |
-
tiny_repo: Path
|
| 79 |
-
sessions: Path
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
@dataclass(frozen=True)
|
| 83 |
-
class CompletedCommand:
|
| 84 |
-
args: tuple[str, ...]
|
| 85 |
-
cwd: Path
|
| 86 |
-
returncode: int
|
| 87 |
-
stdout: str
|
| 88 |
-
stderr: str
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
class CommandRunner:
|
| 92 |
-
def run(
|
| 93 |
-
self,
|
| 94 |
-
args: Sequence[str],
|
| 95 |
-
*,
|
| 96 |
-
cwd: Path,
|
| 97 |
-
env: Mapping[str, str],
|
| 98 |
-
check: bool = True,
|
| 99 |
-
timeout_seconds: float | None = None,
|
| 100 |
-
) -> CompletedCommand:
|
| 101 |
-
print("+ " + " ".join(args), flush=True)
|
| 102 |
-
try:
|
| 103 |
-
result = subprocess.run(
|
| 104 |
-
list(args),
|
| 105 |
-
cwd=cwd,
|
| 106 |
-
env=dict(env),
|
| 107 |
-
text=True,
|
| 108 |
-
capture_output=True,
|
| 109 |
-
check=False,
|
| 110 |
-
timeout=timeout_seconds,
|
| 111 |
-
)
|
| 112 |
-
except subprocess.TimeoutExpired as exc:
|
| 113 |
-
raise SystemExit(
|
| 114 |
-
f"command timed out after {timeout_seconds}s: {' '.join(args)}"
|
| 115 |
-
) from exc
|
| 116 |
-
if result.stdout.strip():
|
| 117 |
-
print(result.stdout.rstrip())
|
| 118 |
-
if result.stderr.strip():
|
| 119 |
-
print(result.stderr.rstrip(), file=sys.stderr)
|
| 120 |
-
completed = CompletedCommand(
|
| 121 |
-
args=tuple(args),
|
| 122 |
-
cwd=cwd,
|
| 123 |
-
returncode=result.returncode,
|
| 124 |
-
stdout=result.stdout,
|
| 125 |
-
stderr=result.stderr,
|
| 126 |
-
)
|
| 127 |
-
if check and result.returncode != 0:
|
| 128 |
-
raise SystemExit(
|
| 129 |
-
f"command failed with exit {result.returncode}: {' '.join(args)}"
|
| 130 |
-
)
|
| 131 |
-
return completed
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
def repo_root() -> Path:
|
| 135 |
-
return Path(__file__).resolve().parents[1]
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
def make_paths(root: Path) -> ContractPaths:
|
| 139 |
-
return ContractPaths(
|
| 140 |
-
root=root,
|
| 141 |
-
home=root / "home",
|
| 142 |
-
appdata=root / "appdata",
|
| 143 |
-
localappdata=root / "localappdata",
|
| 144 |
-
xdg_config=root / "xdg-config",
|
| 145 |
-
xdg_cache=root / "xdg-cache",
|
| 146 |
-
pip_cache=root / "pip-cache",
|
| 147 |
-
dist=root / "dist",
|
| 148 |
-
venv=root / "venv",
|
| 149 |
-
fake_modules=root / "fake-modules",
|
| 150 |
-
tiny_repo=root / "tiny-fastapi-repo",
|
| 151 |
-
sessions=root / "sessions",
|
| 152 |
-
)
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
def _is_relative_to(path: Path, root: Path) -> bool:
|
| 156 |
-
try:
|
| 157 |
-
path.resolve().relative_to(root.resolve())
|
| 158 |
-
except ValueError:
|
| 159 |
-
return False
|
| 160 |
-
return True
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
def assert_inside(path: Path, root: Path) -> None:
|
| 164 |
-
if not _is_relative_to(path, root):
|
| 165 |
-
raise AssertionError(f"path escaped temp root: {path} not under {root}")
|
| 166 |
-
|
| 167 |
-
|
| 168 |
def isolated_env(paths: ContractPaths, *, extra_pythonpath: Path | None = None) -> dict[str, str]:
|
| 169 |
env = {
|
| 170 |
key: value
|
|
@@ -175,167 +175,167 @@ def isolated_env(paths: ContractPaths, *, extra_pythonpath: Path | None = None)
|
|
| 175 |
"HOME": str(paths.home),
|
| 176 |
"USERPROFILE": str(paths.home),
|
| 177 |
"APPDATA": str(paths.appdata),
|
| 178 |
-
"LOCALAPPDATA": str(paths.localappdata),
|
| 179 |
-
"XDG_CONFIG_HOME": str(paths.xdg_config),
|
| 180 |
-
"XDG_CACHE_HOME": str(paths.xdg_cache),
|
| 181 |
"PIP_CACHE_DIR": str(paths.pip_cache),
|
| 182 |
"PYTHONUTF8": "1",
|
| 183 |
})
|
| 184 |
if extra_pythonpath is not None:
|
| 185 |
env["PYTHONPATH"] = str(extra_pythonpath)
|
| 186 |
return env
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
def live_claude_env(paths: ContractPaths) -> dict[str, str]:
|
| 190 |
-
"""Build a narrow env for opt-in live Claude checks.
|
| 191 |
-
|
| 192 |
-
The fake contract can inherit the parent env because it never calls a
|
| 193 |
-
hosted model. The live gate is different: it should keep auth and platform
|
| 194 |
-
plumbing, but not point Claude back at the user's real home/config tree.
|
| 195 |
-
"""
|
| 196 |
-
env: dict[str, str] = {}
|
| 197 |
-
for key, value in os.environ.items():
|
| 198 |
-
if (
|
| 199 |
-
key in _LIVE_CLAUDE_PLATFORM_ENV
|
| 200 |
-
or key in _LIVE_CLAUDE_AUTH_EXACT_ENV
|
| 201 |
-
or key.startswith(_LIVE_CLAUDE_AUTH_PREFIX_ENV)
|
| 202 |
-
):
|
| 203 |
-
env[key] = value
|
| 204 |
-
env.update({
|
| 205 |
-
"HOME": str(paths.home),
|
| 206 |
-
"USERPROFILE": str(paths.home),
|
| 207 |
-
"APPDATA": str(paths.appdata),
|
| 208 |
-
"LOCALAPPDATA": str(paths.localappdata),
|
| 209 |
-
"XDG_CONFIG_HOME": str(paths.xdg_config),
|
| 210 |
-
"XDG_CACHE_HOME": str(paths.xdg_cache),
|
| 211 |
-
"PYTHONUTF8": "1",
|
| 212 |
-
})
|
| 213 |
-
env.pop("CLAUDE_HOME", None)
|
| 214 |
-
return env
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
def venv_python(venv: Path) -> Path:
|
| 218 |
-
if os.name == "nt":
|
| 219 |
-
return venv / "Scripts" / "python.exe"
|
| 220 |
-
return venv / "bin" / "python"
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
def venv_script(venv: Path, name: str) -> Path:
|
| 224 |
-
candidates = (
|
| 225 |
-
[venv / "Scripts" / f"{name}.exe", venv / "Scripts" / name]
|
| 226 |
-
if os.name == "nt"
|
| 227 |
-
else [venv / "bin" / name]
|
| 228 |
-
)
|
| 229 |
-
for candidate in candidates:
|
| 230 |
-
if candidate.exists():
|
| 231 |
-
return candidate
|
| 232 |
-
return candidates[0]
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
def write_fake_litellm(fake_modules: Path) -> Path:
|
| 236 |
-
fake_modules.mkdir(parents=True, exist_ok=True)
|
| 237 |
-
path = fake_modules / "litellm.py"
|
| 238 |
-
path.write_text(
|
| 239 |
-
'''"""Process-local fake LiteLLM for clean-host contract runs."""\n'''
|
| 240 |
-
"from __future__ import annotations\n\n"
|
| 241 |
-
"import json\n"
|
| 242 |
-
"import os\n\n"
|
| 243 |
-
"def completion(**kwargs):\n"
|
| 244 |
-
" tool_name = os.environ.get('CTX_FAKE_LITELLM_TOOL_CALL')\n"
|
| 245 |
-
" if tool_name:\n"
|
| 246 |
-
" return {\n"
|
| 247 |
-
" 'choices': [{\n"
|
| 248 |
-
" 'message': {\n"
|
| 249 |
-
" 'content': '',\n"
|
| 250 |
-
" 'tool_calls': [{\n"
|
| 251 |
-
" 'id': 'clean-host-call-1',\n"
|
| 252 |
-
" 'type': 'function',\n"
|
| 253 |
-
" 'function': {\n"
|
| 254 |
-
" 'name': tool_name,\n"
|
| 255 |
-
" 'arguments': json.dumps({'slug': 'python-patterns'}),\n"
|
| 256 |
-
" },\n"
|
| 257 |
-
" }],\n"
|
| 258 |
-
" },\n"
|
| 259 |
-
" 'finish_reason': 'tool_calls',\n"
|
| 260 |
-
" }],\n"
|
| 261 |
-
" 'usage': {'prompt_tokens': 5, 'completion_tokens': 1},\n"
|
| 262 |
-
" }\n"
|
| 263 |
-
" return {\n"
|
| 264 |
-
" 'choices': [{\n"
|
| 265 |
-
" 'message': {'content': 'clean host contract response', 'tool_calls': None},\n"
|
| 266 |
-
" 'finish_reason': 'stop',\n"
|
| 267 |
-
" }],\n"
|
| 268 |
-
" 'usage': {'prompt_tokens': 5, 'completion_tokens': 3},\n"
|
| 269 |
-
" }\n",
|
| 270 |
-
encoding="utf-8",
|
| 271 |
-
)
|
| 272 |
-
return path
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
def write_fake_claude_cli(fake_modules: Path) -> Path:
|
| 276 |
-
"""Write a tiny Claude-Code-like host that executes generated hooks.
|
| 277 |
-
|
| 278 |
-
This does not call Anthropic APIs. It reads the isolated settings.json
|
| 279 |
-
produced by ctx-init and invokes the configured hook command strings with
|
| 280 |
-
representative stdin payloads, which catches broken module paths and hook
|
| 281 |
-
schema drift from the installed wheel.
|
| 282 |
-
"""
|
| 283 |
-
fake_modules.mkdir(parents=True, exist_ok=True)
|
| 284 |
-
path = fake_modules / "fake_claude.py"
|
| 285 |
-
path.write_text(
|
| 286 |
-
'''"""Deterministic Claude Code hook smoke host for clean-host tests."""\n'''
|
| 287 |
-
"from __future__ import annotations\n\n"
|
| 288 |
-
"import argparse\n"
|
| 289 |
-
"import json\n"
|
| 290 |
-
"import os\n"
|
| 291 |
-
"import re\n"
|
| 292 |
"import subprocess\n"
|
| 293 |
-
"import sys\n"
|
| 294 |
-
"from pathlib import Path\n\n"
|
| 295 |
-
"PAYLOADS = {\n"
|
| 296 |
-
" 'PostToolUse': {\n"
|
| 297 |
-
" 'hook_event_name': 'PostToolUse',\n"
|
| 298 |
-
" 'tool_name': 'Bash',\n"
|
| 299 |
-
" 'tool_input': {'command': 'pip install fastapi pytest'},\n"
|
| 300 |
-
" },\n"
|
| 301 |
-
" 'Stop': {\n"
|
| 302 |
-
" 'hook_event_name': 'Stop',\n"
|
| 303 |
-
" 'session_id': 'clean-host-fake-claude',\n"
|
| 304 |
-
" },\n"
|
| 305 |
-
"}\n\n"
|
| 306 |
-
"def _settings_path(raw: str) -> Path:\n"
|
| 307 |
-
" if raw:\n"
|
| 308 |
-
" return Path(raw)\n"
|
| 309 |
-
" return Path(os.path.expanduser('~/.claude/settings.json'))\n\n"
|
| 310 |
-
"def _commands(settings: dict, event: str) -> list[str]:\n"
|
| 311 |
-
" payload = PAYLOADS[event]\n"
|
| 312 |
-
" tool_name = str(payload.get('tool_name') or '')\n"
|
| 313 |
-
" out: list[str] = []\n"
|
| 314 |
-
" for entry in settings.get('hooks', {}).get(event, []):\n"
|
| 315 |
-
" if not isinstance(entry, dict):\n"
|
| 316 |
-
" continue\n"
|
| 317 |
-
" matcher = str(entry.get('matcher') or '.*')\n"
|
| 318 |
-
" if event == 'PostToolUse' and not re.search(matcher, tool_name):\n"
|
| 319 |
-
" continue\n"
|
| 320 |
-
" for hook in entry.get('hooks', []):\n"
|
| 321 |
-
" if isinstance(hook, dict) and hook.get('type') == 'command':\n"
|
| 322 |
-
" command = hook.get('command')\n"
|
| 323 |
-
" if isinstance(command, str) and command.strip():\n"
|
| 324 |
-
" out.append(command)\n"
|
| 325 |
-
" return out\n\n"
|
| 326 |
-
"def main() -> int:\n"
|
| 327 |
-
" parser = argparse.ArgumentParser()\n"
|
| 328 |
-
" parser.add_argument('--settings', default='')\n"
|
| 329 |
-
" parser.add_argument('--cwd', default='')\n"
|
| 330 |
-
" parser.add_argument('-p', '--print', action='store_true')\n"
|
| 331 |
-
" parser.add_argument('prompt', nargs='*')\n"
|
| 332 |
-
" args = parser.parse_args()\n"
|
| 333 |
-
" settings = json.loads(_settings_path(args.settings).read_text(encoding='utf-8'))\n"
|
| 334 |
-
" cwd = args.cwd or os.getcwd()\n"
|
| 335 |
-
" records = []\n"
|
| 336 |
-
" for event in ('PostToolUse', 'Stop'):\n"
|
| 337 |
-
" payload = json.dumps(PAYLOADS[event])\n"
|
| 338 |
-
" for command in _commands(settings, event):\n"
|
| 339 |
" result = subprocess.run(\n"
|
| 340 |
" command,\n"
|
| 341 |
" cwd=cwd,\n"
|
|
@@ -346,551 +346,551 @@ def write_fake_claude_cli(fake_modules: Path) -> Path:
|
|
| 346 |
" check=False,\n"
|
| 347 |
" shell=True,\n"
|
| 348 |
" )\n"
|
| 349 |
-
" records.append({\n"
|
| 350 |
-
" 'event': event,\n"
|
| 351 |
-
" 'command': command,\n"
|
| 352 |
-
" 'returncode': result.returncode,\n"
|
| 353 |
-
" 'stdout': result.stdout[-500:],\n"
|
| 354 |
-
" 'stderr': result.stderr[-500:],\n"
|
| 355 |
-
" })\n"
|
| 356 |
-
" failed = [r for r in records if r['returncode'] != 0]\n"
|
| 357 |
-
" print(json.dumps({'hook_commands': len(records), 'failed': len(failed), 'commands': records}))\n"
|
| 358 |
-
" return 1 if failed else 0\n\n"
|
| 359 |
-
"if __name__ == '__main__':\n"
|
| 360 |
-
" raise SystemExit(main())\n",
|
| 361 |
-
encoding="utf-8",
|
| 362 |
-
)
|
| 363 |
-
return path
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
def write_tiny_repo(path: Path) -> None:
|
| 367 |
-
(path / "app").mkdir(parents=True, exist_ok=True)
|
| 368 |
-
(path / "tests").mkdir(parents=True, exist_ok=True)
|
| 369 |
-
(path / "pyproject.toml").write_text(
|
| 370 |
-
"[project]\n"
|
| 371 |
-
"name = \"tiny-fastapi-contract\"\n"
|
| 372 |
-
"version = \"0.1.0\"\n"
|
| 373 |
-
"dependencies = [\"fastapi\", \"pytest\"]\n",
|
| 374 |
-
encoding="utf-8",
|
| 375 |
-
)
|
| 376 |
-
(path / "app" / "main.py").write_text(
|
| 377 |
-
"from fastapi import FastAPI\n\n"
|
| 378 |
-
"app = FastAPI()\n\n"
|
| 379 |
-
"@app.get('/health')\n"
|
| 380 |
-
"def health():\n"
|
| 381 |
-
" return {'ok': True}\n",
|
| 382 |
-
encoding="utf-8",
|
| 383 |
-
)
|
| 384 |
-
(path / "tests" / "test_health.py").write_text(
|
| 385 |
-
"def test_contract_fixture():\n"
|
| 386 |
-
" assert True\n",
|
| 387 |
-
encoding="utf-8",
|
| 388 |
-
)
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
def _single_wheel(dist: Path) -> Path:
|
| 392 |
-
wheels = sorted(dist.glob("*.whl"))
|
| 393 |
-
if len(wheels) != 1:
|
| 394 |
-
raise AssertionError(f"expected exactly one wheel in {dist}, found {len(wheels)}")
|
| 395 |
-
return wheels[0]
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
def _prepare_dirs(paths: ContractPaths) -> None:
|
| 399 |
-
for path in (
|
| 400 |
-
paths.home,
|
| 401 |
-
paths.appdata,
|
| 402 |
-
paths.localappdata,
|
| 403 |
-
paths.xdg_config,
|
| 404 |
-
paths.xdg_cache,
|
| 405 |
-
paths.pip_cache,
|
| 406 |
-
paths.dist,
|
| 407 |
-
paths.fake_modules,
|
| 408 |
-
paths.sessions,
|
| 409 |
-
):
|
| 410 |
-
path.mkdir(parents=True, exist_ok=True)
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
def _assert_fake_claude_hook_output(stdout: str) -> None:
|
| 414 |
-
try:
|
| 415 |
-
result = json.loads(stdout)
|
| 416 |
-
except json.JSONDecodeError as exc:
|
| 417 |
-
raise AssertionError(f"fake Claude hook smoke returned invalid JSON: {stdout!r}") from exc
|
| 418 |
-
if result.get("failed") != 0:
|
| 419 |
-
raise AssertionError(f"fake Claude hook smoke had failures: {stdout}")
|
| 420 |
-
hook_commands = int(result.get("hook_commands") or 0)
|
| 421 |
-
if hook_commands < 5:
|
| 422 |
-
raise AssertionError(f"expected at least 5 generated hook commands, got {hook_commands}")
|
| 423 |
-
rendered = "\n".join(
|
| 424 |
-
str(row.get("command", ""))
|
| 425 |
-
for row in result.get("commands", [])
|
| 426 |
-
if isinstance(row, dict)
|
| 427 |
-
)
|
| 428 |
-
for expected in (
|
| 429 |
-
"ctx.adapters.claude_code.hooks.context_monitor",
|
| 430 |
-
"skill_add_detector",
|
| 431 |
-
"ctx.adapters.claude_code.hooks.bundle_orchestrator",
|
| 432 |
-
"usage_tracker",
|
| 433 |
-
"ctx.adapters.claude_code.hooks.lifecycle_hooks",
|
| 434 |
-
):
|
| 435 |
-
if expected not in rendered:
|
| 436 |
-
raise AssertionError(f"fake Claude hook smoke did not run {expected}")
|
| 437 |
-
|
| 438 |
-
|
| 439 |
def _quote_command(parts: Sequence[str | Path]) -> str:
|
| 440 |
values = [str(part) for part in parts]
|
| 441 |
if os.name == "nt":
|
| 442 |
return subprocess.list2cmdline(values)
|
| 443 |
return " ".join(shlex.quote(part) for part in values)
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
def write_live_claude_sentinel_script(path: Path) -> None:
|
| 447 |
-
path.write_text(
|
| 448 |
-
'''"""Append Claude Code hook events to a clean-host sentinel file."""\n'''
|
| 449 |
-
"from __future__ import annotations\n\n"
|
| 450 |
-
"import argparse\n"
|
| 451 |
-
"import json\n"
|
| 452 |
-
"import os\n"
|
| 453 |
-
"import sys\n"
|
| 454 |
-
"from pathlib import Path\n\n"
|
| 455 |
-
"def main() -> int:\n"
|
| 456 |
-
" parser = argparse.ArgumentParser()\n"
|
| 457 |
-
" parser.add_argument('--event', required=True)\n"
|
| 458 |
-
" parser.add_argument('--out', required=True)\n"
|
| 459 |
-
" args = parser.parse_args()\n"
|
| 460 |
-
" raw = sys.stdin.read()\n"
|
| 461 |
-
" try:\n"
|
| 462 |
-
" payload = json.loads(raw) if raw.strip() else {}\n"
|
| 463 |
-
" except json.JSONDecodeError:\n"
|
| 464 |
-
" payload = {'invalid_json_prefix': raw[:200]}\n"
|
| 465 |
-
" out = Path(args.out)\n"
|
| 466 |
-
" out.parent.mkdir(parents=True, exist_ok=True)\n"
|
| 467 |
-
" record = {\n"
|
| 468 |
-
" 'event': args.event,\n"
|
| 469 |
-
" 'hook_event_name': payload.get('hook_event_name'),\n"
|
| 470 |
-
" 'tool_name': payload.get('tool_name'),\n"
|
| 471 |
-
" 'cwd': os.getcwd(),\n"
|
| 472 |
-
" 'argv': sys.argv[1:],\n"
|
| 473 |
-
" }\n"
|
| 474 |
-
" with out.open('a', encoding='utf-8') as handle:\n"
|
| 475 |
-
" handle.write(json.dumps(record, sort_keys=True) + '\\n')\n"
|
| 476 |
-
" return 0\n\n"
|
| 477 |
-
"if __name__ == '__main__':\n"
|
| 478 |
-
" raise SystemExit(main())\n",
|
| 479 |
-
encoding="utf-8",
|
| 480 |
-
)
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
def _append_live_claude_sentinel_hooks(
|
| 484 |
-
*,
|
| 485 |
-
settings_json: Path,
|
| 486 |
-
python_bin: Path,
|
| 487 |
-
sentinel_script: Path,
|
| 488 |
-
sentinel_jsonl: Path,
|
| 489 |
-
) -> None:
|
| 490 |
-
settings = json.loads(settings_json.read_text(encoding="utf-8"))
|
| 491 |
-
hooks = settings.setdefault("hooks", {})
|
| 492 |
-
post_command = _quote_command((
|
| 493 |
-
python_bin,
|
| 494 |
-
sentinel_script,
|
| 495 |
-
"--event",
|
| 496 |
-
"PostToolUse",
|
| 497 |
-
"--out",
|
| 498 |
-
sentinel_jsonl,
|
| 499 |
-
))
|
| 500 |
-
stop_command = _quote_command((
|
| 501 |
-
python_bin,
|
| 502 |
-
sentinel_script,
|
| 503 |
-
"--event",
|
| 504 |
-
"Stop",
|
| 505 |
-
"--out",
|
| 506 |
-
sentinel_jsonl,
|
| 507 |
-
))
|
| 508 |
-
hooks.setdefault("PostToolUse", []).append({
|
| 509 |
-
"matcher": ".*",
|
| 510 |
-
"hooks": [{"type": "command", "command": post_command}],
|
| 511 |
-
})
|
| 512 |
-
hooks.setdefault("Stop", []).append({
|
| 513 |
-
"hooks": [{"type": "command", "command": stop_command}],
|
| 514 |
-
})
|
| 515 |
-
tmp_path = settings_json.with_name(f"{settings_json.name}.live.tmp")
|
| 516 |
-
tmp_path.write_text(json.dumps(settings, indent=2) + "\n", encoding="utf-8")
|
| 517 |
-
os.replace(tmp_path, settings_json)
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
def _sentinel_records(path: Path) -> list[dict[str, Any]]:
|
| 521 |
-
if not path.exists():
|
| 522 |
-
raise AssertionError(f"live Claude sentinel was not written: {path}")
|
| 523 |
-
records: list[dict[str, Any]] = []
|
| 524 |
-
for line in path.read_text(encoding="utf-8").splitlines():
|
| 525 |
-
if not line.strip():
|
| 526 |
-
continue
|
| 527 |
-
try:
|
| 528 |
-
record = json.loads(line)
|
| 529 |
-
except json.JSONDecodeError as exc:
|
| 530 |
-
raise AssertionError(f"live Claude sentinel has invalid JSONL: {line}") from exc
|
| 531 |
-
if not isinstance(record, dict):
|
| 532 |
-
raise AssertionError(f"live Claude sentinel record is not an object: {line}")
|
| 533 |
-
records.append(record)
|
| 534 |
-
return records
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
def _assert_live_claude_sentinel(path: Path, *, expected_cwd: Path) -> None:
|
| 538 |
-
records = _sentinel_records(path)
|
| 539 |
-
events = {str(record.get("event") or "") for record in records}
|
| 540 |
-
for expected in _EXPECTED_LIVE_CLAUDE_EVENTS:
|
| 541 |
-
if expected not in events:
|
| 542 |
-
raise AssertionError(f"live Claude sentinel did not record {expected}")
|
| 543 |
-
expected_resolved = expected_cwd.resolve()
|
| 544 |
-
for record in records:
|
| 545 |
-
cwd = record.get("cwd")
|
| 546 |
-
if cwd is None or Path(str(cwd)).resolve() != expected_resolved:
|
| 547 |
-
raise AssertionError(
|
| 548 |
-
"live Claude sentinel recorded unexpected cwd: "
|
| 549 |
-
f"{cwd!r}, expected {expected_resolved}"
|
| 550 |
-
)
|
| 551 |
-
hook_event = record.get("hook_event_name")
|
| 552 |
-
event = record.get("event")
|
| 553 |
-
if hook_event not in (None, event):
|
| 554 |
-
raise AssertionError(
|
| 555 |
-
f"live Claude sentinel event mismatch: event={event!r}, "
|
| 556 |
-
f"hook_event_name={hook_event!r}"
|
| 557 |
-
)
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
def _require_live_claude_ack(max_budget_usd: float) -> None:
|
| 561 |
-
if os.environ.get(LIVE_CLAUDE_ACK_ENV) != LIVE_CLAUDE_ACK_VALUE:
|
| 562 |
-
raise AssertionError(
|
| 563 |
-
f"set {LIVE_CLAUDE_ACK_ENV}={LIVE_CLAUDE_ACK_VALUE} to run "
|
| 564 |
-
"the quota-consuming live Claude Code gate"
|
| 565 |
-
)
|
| 566 |
-
if max_budget_usd <= 0 or max_budget_usd > LIVE_CLAUDE_MAX_BUDGET_USD:
|
| 567 |
-
raise AssertionError(
|
| 568 |
-
"live Claude budget must be greater than 0 and no more than "
|
| 569 |
-
f"{LIVE_CLAUDE_MAX_BUDGET_USD} USD"
|
| 570 |
-
)
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
def _live_claude_command(
|
| 574 |
-
*,
|
| 575 |
-
claude_bin: Path,
|
| 576 |
-
settings_json: Path,
|
| 577 |
-
max_budget_usd: float,
|
| 578 |
-
) -> list[str]:
|
| 579 |
-
return [
|
| 580 |
-
str(claude_bin),
|
| 581 |
-
"--settings",
|
| 582 |
-
str(settings_json),
|
| 583 |
-
"--setting-sources",
|
| 584 |
-
"user",
|
| 585 |
-
"--output-format",
|
| 586 |
-
"stream-json",
|
| 587 |
-
"--include-hook-events",
|
| 588 |
-
"--no-session-persistence",
|
| 589 |
-
"--max-budget-usd",
|
| 590 |
-
str(max_budget_usd),
|
| 591 |
-
"--allowedTools",
|
| 592 |
-
"Bash(python --version)",
|
| 593 |
-
"-p",
|
| 594 |
-
"Use Bash to run exactly `python --version`, then stop.",
|
| 595 |
-
]
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
def _run_live_claude_gate(
|
| 599 |
-
*,
|
| 600 |
-
runner: CommandRunner,
|
| 601 |
-
paths: ContractPaths,
|
| 602 |
-
python_bin: Path,
|
| 603 |
-
settings_json: Path,
|
| 604 |
-
max_budget_usd: float,
|
| 605 |
-
claude_bin: Path | None,
|
| 606 |
-
) -> None:
|
| 607 |
-
_require_live_claude_ack(max_budget_usd)
|
| 608 |
-
resolved_claude = claude_bin if claude_bin is not None else None
|
| 609 |
-
if resolved_claude is None:
|
| 610 |
-
claude = shutil.which("claude")
|
| 611 |
-
resolved_claude = Path(claude) if claude is not None else None
|
| 612 |
-
if resolved_claude is None:
|
| 613 |
-
raise AssertionError("claude executable was not found on PATH")
|
| 614 |
-
live_env = live_claude_env(paths)
|
| 615 |
-
runner.run(
|
| 616 |
-
[str(resolved_claude), "--version"],
|
| 617 |
-
cwd=paths.tiny_repo,
|
| 618 |
-
env=live_env,
|
| 619 |
-
timeout_seconds=LIVE_CLAUDE_PREFLIGHT_TIMEOUT_SECONDS,
|
| 620 |
-
)
|
| 621 |
-
runner.run(
|
| 622 |
-
[str(resolved_claude), "auth", "status"],
|
| 623 |
-
cwd=paths.tiny_repo,
|
| 624 |
-
env=live_env,
|
| 625 |
-
timeout_seconds=LIVE_CLAUDE_PREFLIGHT_TIMEOUT_SECONDS,
|
| 626 |
-
)
|
| 627 |
-
sentinel_script = paths.root / "live-claude-hook-sentinel.py"
|
| 628 |
-
sentinel_jsonl = paths.root / "live-claude-hooks.jsonl"
|
| 629 |
-
write_live_claude_sentinel_script(sentinel_script)
|
| 630 |
-
_append_live_claude_sentinel_hooks(
|
| 631 |
-
settings_json=settings_json,
|
| 632 |
-
python_bin=python_bin,
|
| 633 |
-
sentinel_script=sentinel_script,
|
| 634 |
-
sentinel_jsonl=sentinel_jsonl,
|
| 635 |
-
)
|
| 636 |
-
runner.run(
|
| 637 |
-
_live_claude_command(
|
| 638 |
-
claude_bin=resolved_claude,
|
| 639 |
-
settings_json=settings_json,
|
| 640 |
-
max_budget_usd=max_budget_usd,
|
| 641 |
-
),
|
| 642 |
-
cwd=paths.tiny_repo,
|
| 643 |
-
env=live_env,
|
| 644 |
-
timeout_seconds=LIVE_CLAUDE_PROMPT_TIMEOUT_SECONDS,
|
| 645 |
-
)
|
| 646 |
-
_assert_live_claude_sentinel(sentinel_jsonl, expected_cwd=paths.tiny_repo)
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
def run_contract(
|
| 650 |
-
*,
|
| 651 |
-
project_root: Path,
|
| 652 |
-
temp_root: Path,
|
| 653 |
-
fast: bool,
|
| 654 |
-
runner: CommandRunner | None = None,
|
| 655 |
-
run_live_claude: bool = False,
|
| 656 |
-
live_claude_max_budget_usd: float = LIVE_CLAUDE_DEFAULT_BUDGET_USD,
|
| 657 |
-
live_claude_bin: Path | None = None,
|
| 658 |
-
) -> None:
|
| 659 |
-
runner = runner or CommandRunner()
|
| 660 |
-
paths = make_paths(temp_root)
|
| 661 |
-
_prepare_dirs(paths)
|
| 662 |
-
write_tiny_repo(paths.tiny_repo)
|
| 663 |
-
write_fake_litellm(paths.fake_modules)
|
| 664 |
-
fake_claude = write_fake_claude_cli(paths.fake_modules)
|
| 665 |
-
|
| 666 |
-
env = isolated_env(paths)
|
| 667 |
-
runner.run(
|
| 668 |
-
[
|
| 669 |
-
sys.executable,
|
| 670 |
-
"-m",
|
| 671 |
-
"pip",
|
| 672 |
-
"wheel",
|
| 673 |
-
"--no-deps",
|
| 674 |
-
"--wheel-dir",
|
| 675 |
-
str(paths.dist),
|
| 676 |
-
str(project_root),
|
| 677 |
-
],
|
| 678 |
-
cwd=project_root,
|
| 679 |
-
env=env,
|
| 680 |
-
)
|
| 681 |
-
runner.run([sys.executable, "-m", "venv", str(paths.venv)], cwd=project_root, env=env)
|
| 682 |
-
wheel = _single_wheel(paths.dist)
|
| 683 |
-
py = venv_python(paths.venv)
|
| 684 |
-
runner.run([str(py), "-m", "pip", "install", str(wheel)], cwd=project_root, env=env)
|
| 685 |
-
|
| 686 |
-
run_env = isolated_env(paths, extra_pythonpath=paths.fake_modules)
|
| 687 |
-
ctx_init = venv_script(paths.venv, "ctx-init")
|
| 688 |
-
ctx_scan_repo = venv_script(paths.venv, "ctx-scan-repo")
|
| 689 |
-
ctx = venv_script(paths.venv, "ctx")
|
| 690 |
-
|
| 691 |
-
runner.run([str(ctx_init), "--hooks"], cwd=paths.tiny_repo, env=run_env)
|
| 692 |
-
claude_dir = paths.home / ".claude"
|
| 693 |
-
assert_inside(claude_dir, paths.root)
|
| 694 |
-
if not (claude_dir / "settings.json").exists():
|
| 695 |
-
raise AssertionError("ctx-init --hooks did not write isolated settings.json")
|
| 696 |
-
fake_claude_result = runner.run(
|
| 697 |
-
[
|
| 698 |
-
str(py),
|
| 699 |
-
str(fake_claude),
|
| 700 |
-
"--settings",
|
| 701 |
-
str(claude_dir / "settings.json"),
|
| 702 |
-
"--cwd",
|
| 703 |
-
str(paths.tiny_repo),
|
| 704 |
-
"-p",
|
| 705 |
-
"trigger clean-host hook smoke",
|
| 706 |
-
],
|
| 707 |
-
cwd=paths.tiny_repo,
|
| 708 |
-
env=run_env,
|
| 709 |
-
)
|
| 710 |
-
_assert_fake_claude_hook_output(fake_claude_result.stdout)
|
| 711 |
-
if run_live_claude:
|
| 712 |
-
_run_live_claude_gate(
|
| 713 |
-
runner=runner,
|
| 714 |
-
paths=paths,
|
| 715 |
-
python_bin=py,
|
| 716 |
-
settings_json=claude_dir / "settings.json",
|
| 717 |
-
max_budget_usd=live_claude_max_budget_usd,
|
| 718 |
-
claude_bin=live_claude_bin,
|
| 719 |
-
)
|
| 720 |
-
|
| 721 |
-
stack_profile = paths.root / "stack-profile.json"
|
| 722 |
-
runner.run(
|
| 723 |
-
[
|
| 724 |
-
str(ctx_scan_repo),
|
| 725 |
-
"--repo",
|
| 726 |
-
str(paths.tiny_repo),
|
| 727 |
-
"--output",
|
| 728 |
-
str(stack_profile),
|
| 729 |
-
"--recommend",
|
| 730 |
-
],
|
| 731 |
-
cwd=paths.tiny_repo,
|
| 732 |
-
env=run_env,
|
| 733 |
-
)
|
| 734 |
-
if not stack_profile.exists():
|
| 735 |
-
raise AssertionError("ctx-scan-repo did not write stack profile")
|
| 736 |
-
|
| 737 |
-
runner.run(
|
| 738 |
-
[
|
| 739 |
-
str(ctx),
|
| 740 |
-
"run",
|
| 741 |
-
"--model",
|
| 742 |
-
"ollama/clean-host-fake",
|
| 743 |
-
"--task",
|
| 744 |
-
"Return a one-sentence clean-host contract response.",
|
| 745 |
-
"--no-ctx-tools",
|
| 746 |
-
"--sessions-dir",
|
| 747 |
-
str(paths.sessions),
|
| 748 |
-
"--session-id",
|
| 749 |
-
"clean-host-contract",
|
| 750 |
-
"--quiet",
|
| 751 |
-
],
|
| 752 |
-
cwd=paths.tiny_repo,
|
| 753 |
-
env=run_env,
|
| 754 |
-
)
|
| 755 |
-
runner.run(
|
| 756 |
-
[
|
| 757 |
-
str(ctx),
|
| 758 |
-
"resume",
|
| 759 |
-
"clean-host-contract",
|
| 760 |
-
"--task",
|
| 761 |
-
"Confirm resume works.",
|
| 762 |
-
"--sessions-dir",
|
| 763 |
-
str(paths.sessions),
|
| 764 |
-
"--quiet",
|
| 765 |
-
],
|
| 766 |
-
cwd=paths.tiny_repo,
|
| 767 |
-
env=run_env,
|
| 768 |
-
)
|
| 769 |
-
|
| 770 |
-
denied_env = dict(run_env)
|
| 771 |
-
denied_env["CTX_FAKE_LITELLM_TOOL_CALL"] = "ctx__wiki_get"
|
| 772 |
-
denied = runner.run(
|
| 773 |
-
[
|
| 774 |
-
str(ctx),
|
| 775 |
-
"run",
|
| 776 |
-
"--model",
|
| 777 |
-
"ollama/clean-host-fake",
|
| 778 |
-
"--task",
|
| 779 |
-
"Attempt the wiki tool so policy can deny it.",
|
| 780 |
-
"--sessions-dir",
|
| 781 |
-
str(paths.sessions),
|
| 782 |
-
"--session-id",
|
| 783 |
-
"clean-host-denied-tool",
|
| 784 |
-
"--deny-tool",
|
| 785 |
-
"ctx__wiki_get",
|
| 786 |
-
"--quiet",
|
| 787 |
-
"--json",
|
| 788 |
-
],
|
| 789 |
-
cwd=paths.tiny_repo,
|
| 790 |
-
env=denied_env,
|
| 791 |
-
check=False,
|
| 792 |
-
)
|
| 793 |
-
if denied.returncode != 2 or '"tool_denied"' not in denied.stdout:
|
| 794 |
-
raise AssertionError(
|
| 795 |
-
"expected denied tool run to exit 2 with tool_denied JSON; "
|
| 796 |
-
f"got rc={denied.returncode}"
|
| 797 |
-
)
|
| 798 |
-
|
| 799 |
-
if not fast:
|
| 800 |
-
runner.run([str(ctx_init), "--help"], cwd=paths.tiny_repo, env=run_env)
|
| 801 |
-
runner.run([str(ctx_scan_repo), "--help"], cwd=paths.tiny_repo, env=run_env)
|
| 802 |
-
runner.run([str(ctx), "--help"], cwd=paths.tiny_repo, env=run_env)
|
| 803 |
-
|
| 804 |
-
for expected in (paths.home, paths.appdata, paths.localappdata, paths.sessions):
|
| 805 |
-
assert_inside(expected, paths.root)
|
| 806 |
-
|
| 807 |
-
|
| 808 |
-
def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
|
| 809 |
-
parser = argparse.ArgumentParser(
|
| 810 |
-
description="Build/install ctx into a temp clean host and exercise core flows.",
|
| 811 |
-
)
|
| 812 |
-
parser.add_argument(
|
| 813 |
-
"--fast",
|
| 814 |
-
action="store_true",
|
| 815 |
-
help="Run the core contract only; skip extra help probes.",
|
| 816 |
-
)
|
| 817 |
-
parser.add_argument(
|
| 818 |
-
"--keep-temp",
|
| 819 |
-
action="store_true",
|
| 820 |
-
help="Keep the temp root after the run for debugging.",
|
| 821 |
-
)
|
| 822 |
-
parser.add_argument(
|
| 823 |
-
"--temp-root",
|
| 824 |
-
type=Path,
|
| 825 |
-
help="Use an explicit temp root. Must not already contain important data.",
|
| 826 |
-
)
|
| 827 |
-
parser.add_argument(
|
| 828 |
-
"--repo-root",
|
| 829 |
-
type=Path,
|
| 830 |
-
default=repo_root(),
|
| 831 |
-
help="Repository root to build. Default: inferred from this script.",
|
| 832 |
-
)
|
| 833 |
-
parser.add_argument(
|
| 834 |
-
"--run-live-claude",
|
| 835 |
-
action="store_true",
|
| 836 |
-
help=(
|
| 837 |
-
"Also run a real Claude Code host smoke. Requires "
|
| 838 |
-
f"{LIVE_CLAUDE_ACK_ENV}={LIVE_CLAUDE_ACK_VALUE} and can consume quota."
|
| 839 |
-
),
|
| 840 |
-
)
|
| 841 |
-
parser.add_argument(
|
| 842 |
-
"--live-claude-max-budget-usd",
|
| 843 |
-
type=float,
|
| 844 |
-
default=LIVE_CLAUDE_DEFAULT_BUDGET_USD,
|
| 845 |
-
help=(
|
| 846 |
-
"Maximum live Claude Code API budget for --run-live-claude. "
|
| 847 |
-
f"Default: {LIVE_CLAUDE_DEFAULT_BUDGET_USD}."
|
| 848 |
-
),
|
| 849 |
-
)
|
| 850 |
-
parser.add_argument(
|
| 851 |
-
"--claude-bin",
|
| 852 |
-
type=Path,
|
| 853 |
-
help="Explicit Claude Code executable path for --run-live-claude.",
|
| 854 |
-
)
|
| 855 |
-
return parser.parse_args(argv)
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
def main(argv: Sequence[str] | None = None) -> int:
|
| 859 |
-
args = parse_args(argv)
|
| 860 |
-
project_root = args.repo_root.resolve()
|
| 861 |
-
if args.temp_root is not None:
|
| 862 |
-
temp_root = args.temp_root.resolve()
|
| 863 |
-
temp_root.mkdir(parents=True, exist_ok=True)
|
| 864 |
-
run_contract(
|
| 865 |
-
project_root=project_root,
|
| 866 |
-
temp_root=temp_root,
|
| 867 |
-
fast=args.fast,
|
| 868 |
-
run_live_claude=args.run_live_claude,
|
| 869 |
-
live_claude_max_budget_usd=args.live_claude_max_budget_usd,
|
| 870 |
-
live_claude_bin=args.claude_bin,
|
| 871 |
-
)
|
| 872 |
-
print(f"clean-host contract passed; temp root kept at {temp_root}")
|
| 873 |
-
return 0
|
| 874 |
-
|
| 875 |
-
temp_dir = tempfile.mkdtemp(prefix="ctx-clean-host-")
|
| 876 |
-
temp_root = Path(temp_dir).resolve()
|
| 877 |
-
try:
|
| 878 |
-
run_contract(
|
| 879 |
-
project_root=project_root,
|
| 880 |
-
temp_root=temp_root,
|
| 881 |
-
fast=args.fast,
|
| 882 |
-
run_live_claude=args.run_live_claude,
|
| 883 |
-
live_claude_max_budget_usd=args.live_claude_max_budget_usd,
|
| 884 |
-
live_claude_bin=args.claude_bin,
|
| 885 |
-
)
|
| 886 |
-
print(f"clean-host contract passed under {temp_root}")
|
| 887 |
-
return 0
|
| 888 |
-
finally:
|
| 889 |
-
if args.keep_temp:
|
| 890 |
-
print(f"kept temp root: {temp_root}")
|
| 891 |
-
else:
|
| 892 |
-
shutil.rmtree(temp_root, ignore_errors=True)
|
| 893 |
-
|
| 894 |
-
|
| 895 |
-
if __name__ == "__main__":
|
| 896 |
-
raise SystemExit(main())
|
|
|
|
| 1 |
+
"""Clean-host contract runner for ctx release hardening.
|
| 2 |
+
|
| 3 |
+
The contract builds the current tree into a wheel, installs it into a
|
| 4 |
+
fresh virtualenv, points all user-state environment variables at a temp
|
| 5 |
+
root, then drives real console scripts. It is intentionally not a public
|
| 6 |
+
entrypoint yet; this is release infrastructure.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
import shlex
|
| 15 |
+
import shutil
|
| 16 |
+
import subprocess
|
| 17 |
+
import sys
|
| 18 |
+
import tempfile
|
| 19 |
+
from dataclasses import dataclass
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
from typing import Any, Mapping, Sequence
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
LIVE_CLAUDE_ACK_ENV = "CTX_LIVE_CLAUDE_ACK"
|
| 25 |
+
LIVE_CLAUDE_ACK_VALUE = "uses_quota"
|
| 26 |
+
LIVE_CLAUDE_DEFAULT_BUDGET_USD = 0.05
|
| 27 |
+
LIVE_CLAUDE_MAX_BUDGET_USD = 1.0
|
| 28 |
+
LIVE_CLAUDE_PROMPT_TIMEOUT_SECONDS = 180.0
|
| 29 |
+
LIVE_CLAUDE_PREFLIGHT_TIMEOUT_SECONDS = 30.0
|
| 30 |
+
|
| 31 |
+
_LIVE_CLAUDE_AUTH_EXACT_ENV = {
|
| 32 |
+
"ANTHROPIC_API_KEY",
|
| 33 |
+
"ANTHROPIC_AUTH_TOKEN",
|
| 34 |
+
"ANTHROPIC_BASE_URL",
|
| 35 |
+
"ANTHROPIC_BETA_HEADERS",
|
| 36 |
+
"CLAUDE_CODE_USE_BEDROCK",
|
| 37 |
+
"CLAUDE_CODE_USE_VERTEX",
|
| 38 |
+
"CLAUDE_CODE_USE_FOUNDRY",
|
| 39 |
+
}
|
| 40 |
+
_LIVE_CLAUDE_AUTH_PREFIX_ENV = (
|
| 41 |
+
"AWS_",
|
| 42 |
+
"GOOGLE_",
|
| 43 |
+
"GCLOUD_",
|
| 44 |
+
"VERTEXAI_",
|
| 45 |
+
"ANTHROPIC_",
|
| 46 |
+
)
|
| 47 |
_LIVE_CLAUDE_PLATFORM_ENV = {
|
| 48 |
"PATH",
|
| 49 |
"Path",
|
| 50 |
"PATHEXT",
|
| 51 |
"SYSTEMROOT",
|
| 52 |
+
"SystemRoot",
|
| 53 |
+
"WINDIR",
|
| 54 |
+
"COMSPEC",
|
| 55 |
"TEMP",
|
| 56 |
"TMP",
|
| 57 |
}
|
|
|
|
| 61 |
"TZ",
|
| 62 |
}
|
| 63 |
_EXPECTED_LIVE_CLAUDE_EVENTS = ("PostToolUse", "Stop")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@dataclass(frozen=True)
|
| 67 |
+
class ContractPaths:
|
| 68 |
+
root: Path
|
| 69 |
+
home: Path
|
| 70 |
+
appdata: Path
|
| 71 |
+
localappdata: Path
|
| 72 |
+
xdg_config: Path
|
| 73 |
+
xdg_cache: Path
|
| 74 |
+
pip_cache: Path
|
| 75 |
+
dist: Path
|
| 76 |
+
venv: Path
|
| 77 |
+
fake_modules: Path
|
| 78 |
+
tiny_repo: Path
|
| 79 |
+
sessions: Path
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@dataclass(frozen=True)
|
| 83 |
+
class CompletedCommand:
|
| 84 |
+
args: tuple[str, ...]
|
| 85 |
+
cwd: Path
|
| 86 |
+
returncode: int
|
| 87 |
+
stdout: str
|
| 88 |
+
stderr: str
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class CommandRunner:
|
| 92 |
+
def run(
|
| 93 |
+
self,
|
| 94 |
+
args: Sequence[str],
|
| 95 |
+
*,
|
| 96 |
+
cwd: Path,
|
| 97 |
+
env: Mapping[str, str],
|
| 98 |
+
check: bool = True,
|
| 99 |
+
timeout_seconds: float | None = None,
|
| 100 |
+
) -> CompletedCommand:
|
| 101 |
+
print("+ " + " ".join(args), flush=True)
|
| 102 |
+
try:
|
| 103 |
+
result = subprocess.run(
|
| 104 |
+
list(args),
|
| 105 |
+
cwd=cwd,
|
| 106 |
+
env=dict(env),
|
| 107 |
+
text=True,
|
| 108 |
+
capture_output=True,
|
| 109 |
+
check=False,
|
| 110 |
+
timeout=timeout_seconds,
|
| 111 |
+
)
|
| 112 |
+
except subprocess.TimeoutExpired as exc:
|
| 113 |
+
raise SystemExit(
|
| 114 |
+
f"command timed out after {timeout_seconds}s: {' '.join(args)}"
|
| 115 |
+
) from exc
|
| 116 |
+
if result.stdout.strip():
|
| 117 |
+
print(result.stdout.rstrip())
|
| 118 |
+
if result.stderr.strip():
|
| 119 |
+
print(result.stderr.rstrip(), file=sys.stderr)
|
| 120 |
+
completed = CompletedCommand(
|
| 121 |
+
args=tuple(args),
|
| 122 |
+
cwd=cwd,
|
| 123 |
+
returncode=result.returncode,
|
| 124 |
+
stdout=result.stdout,
|
| 125 |
+
stderr=result.stderr,
|
| 126 |
+
)
|
| 127 |
+
if check and result.returncode != 0:
|
| 128 |
+
raise SystemExit(
|
| 129 |
+
f"command failed with exit {result.returncode}: {' '.join(args)}"
|
| 130 |
+
)
|
| 131 |
+
return completed
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def repo_root() -> Path:
|
| 135 |
+
return Path(__file__).resolve().parents[1]
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def make_paths(root: Path) -> ContractPaths:
|
| 139 |
+
return ContractPaths(
|
| 140 |
+
root=root,
|
| 141 |
+
home=root / "home",
|
| 142 |
+
appdata=root / "appdata",
|
| 143 |
+
localappdata=root / "localappdata",
|
| 144 |
+
xdg_config=root / "xdg-config",
|
| 145 |
+
xdg_cache=root / "xdg-cache",
|
| 146 |
+
pip_cache=root / "pip-cache",
|
| 147 |
+
dist=root / "dist",
|
| 148 |
+
venv=root / "venv",
|
| 149 |
+
fake_modules=root / "fake-modules",
|
| 150 |
+
tiny_repo=root / "tiny-fastapi-repo",
|
| 151 |
+
sessions=root / "sessions",
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _is_relative_to(path: Path, root: Path) -> bool:
|
| 156 |
+
try:
|
| 157 |
+
path.resolve().relative_to(root.resolve())
|
| 158 |
+
except ValueError:
|
| 159 |
+
return False
|
| 160 |
+
return True
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def assert_inside(path: Path, root: Path) -> None:
|
| 164 |
+
if not _is_relative_to(path, root):
|
| 165 |
+
raise AssertionError(f"path escaped temp root: {path} not under {root}")
|
| 166 |
+
|
| 167 |
+
|
| 168 |
def isolated_env(paths: ContractPaths, *, extra_pythonpath: Path | None = None) -> dict[str, str]:
|
| 169 |
env = {
|
| 170 |
key: value
|
|
|
|
| 175 |
"HOME": str(paths.home),
|
| 176 |
"USERPROFILE": str(paths.home),
|
| 177 |
"APPDATA": str(paths.appdata),
|
| 178 |
+
"LOCALAPPDATA": str(paths.localappdata),
|
| 179 |
+
"XDG_CONFIG_HOME": str(paths.xdg_config),
|
| 180 |
+
"XDG_CACHE_HOME": str(paths.xdg_cache),
|
| 181 |
"PIP_CACHE_DIR": str(paths.pip_cache),
|
| 182 |
"PYTHONUTF8": "1",
|
| 183 |
})
|
| 184 |
if extra_pythonpath is not None:
|
| 185 |
env["PYTHONPATH"] = str(extra_pythonpath)
|
| 186 |
return env
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def live_claude_env(paths: ContractPaths) -> dict[str, str]:
|
| 190 |
+
"""Build a narrow env for opt-in live Claude checks.
|
| 191 |
+
|
| 192 |
+
The fake contract can inherit the parent env because it never calls a
|
| 193 |
+
hosted model. The live gate is different: it should keep auth and platform
|
| 194 |
+
plumbing, but not point Claude back at the user's real home/config tree.
|
| 195 |
+
"""
|
| 196 |
+
env: dict[str, str] = {}
|
| 197 |
+
for key, value in os.environ.items():
|
| 198 |
+
if (
|
| 199 |
+
key in _LIVE_CLAUDE_PLATFORM_ENV
|
| 200 |
+
or key in _LIVE_CLAUDE_AUTH_EXACT_ENV
|
| 201 |
+
or key.startswith(_LIVE_CLAUDE_AUTH_PREFIX_ENV)
|
| 202 |
+
):
|
| 203 |
+
env[key] = value
|
| 204 |
+
env.update({
|
| 205 |
+
"HOME": str(paths.home),
|
| 206 |
+
"USERPROFILE": str(paths.home),
|
| 207 |
+
"APPDATA": str(paths.appdata),
|
| 208 |
+
"LOCALAPPDATA": str(paths.localappdata),
|
| 209 |
+
"XDG_CONFIG_HOME": str(paths.xdg_config),
|
| 210 |
+
"XDG_CACHE_HOME": str(paths.xdg_cache),
|
| 211 |
+
"PYTHONUTF8": "1",
|
| 212 |
+
})
|
| 213 |
+
env.pop("CLAUDE_HOME", None)
|
| 214 |
+
return env
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def venv_python(venv: Path) -> Path:
|
| 218 |
+
if os.name == "nt":
|
| 219 |
+
return venv / "Scripts" / "python.exe"
|
| 220 |
+
return venv / "bin" / "python"
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def venv_script(venv: Path, name: str) -> Path:
|
| 224 |
+
candidates = (
|
| 225 |
+
[venv / "Scripts" / f"{name}.exe", venv / "Scripts" / name]
|
| 226 |
+
if os.name == "nt"
|
| 227 |
+
else [venv / "bin" / name]
|
| 228 |
+
)
|
| 229 |
+
for candidate in candidates:
|
| 230 |
+
if candidate.exists():
|
| 231 |
+
return candidate
|
| 232 |
+
return candidates[0]
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def write_fake_litellm(fake_modules: Path) -> Path:
|
| 236 |
+
fake_modules.mkdir(parents=True, exist_ok=True)
|
| 237 |
+
path = fake_modules / "litellm.py"
|
| 238 |
+
path.write_text(
|
| 239 |
+
'''"""Process-local fake LiteLLM for clean-host contract runs."""\n'''
|
| 240 |
+
"from __future__ import annotations\n\n"
|
| 241 |
+
"import json\n"
|
| 242 |
+
"import os\n\n"
|
| 243 |
+
"def completion(**kwargs):\n"
|
| 244 |
+
" tool_name = os.environ.get('CTX_FAKE_LITELLM_TOOL_CALL')\n"
|
| 245 |
+
" if tool_name:\n"
|
| 246 |
+
" return {\n"
|
| 247 |
+
" 'choices': [{\n"
|
| 248 |
+
" 'message': {\n"
|
| 249 |
+
" 'content': '',\n"
|
| 250 |
+
" 'tool_calls': [{\n"
|
| 251 |
+
" 'id': 'clean-host-call-1',\n"
|
| 252 |
+
" 'type': 'function',\n"
|
| 253 |
+
" 'function': {\n"
|
| 254 |
+
" 'name': tool_name,\n"
|
| 255 |
+
" 'arguments': json.dumps({'slug': 'python-patterns'}),\n"
|
| 256 |
+
" },\n"
|
| 257 |
+
" }],\n"
|
| 258 |
+
" },\n"
|
| 259 |
+
" 'finish_reason': 'tool_calls',\n"
|
| 260 |
+
" }],\n"
|
| 261 |
+
" 'usage': {'prompt_tokens': 5, 'completion_tokens': 1},\n"
|
| 262 |
+
" }\n"
|
| 263 |
+
" return {\n"
|
| 264 |
+
" 'choices': [{\n"
|
| 265 |
+
" 'message': {'content': 'clean host contract response', 'tool_calls': None},\n"
|
| 266 |
+
" 'finish_reason': 'stop',\n"
|
| 267 |
+
" }],\n"
|
| 268 |
+
" 'usage': {'prompt_tokens': 5, 'completion_tokens': 3},\n"
|
| 269 |
+
" }\n",
|
| 270 |
+
encoding="utf-8",
|
| 271 |
+
)
|
| 272 |
+
return path
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def write_fake_claude_cli(fake_modules: Path) -> Path:
|
| 276 |
+
"""Write a tiny Claude-Code-like host that executes generated hooks.
|
| 277 |
+
|
| 278 |
+
This does not call Anthropic APIs. It reads the isolated settings.json
|
| 279 |
+
produced by ctx-init and invokes the configured hook command strings with
|
| 280 |
+
representative stdin payloads, which catches broken module paths and hook
|
| 281 |
+
schema drift from the installed wheel.
|
| 282 |
+
"""
|
| 283 |
+
fake_modules.mkdir(parents=True, exist_ok=True)
|
| 284 |
+
path = fake_modules / "fake_claude.py"
|
| 285 |
+
path.write_text(
|
| 286 |
+
'''"""Deterministic Claude Code hook smoke host for clean-host tests."""\n'''
|
| 287 |
+
"from __future__ import annotations\n\n"
|
| 288 |
+
"import argparse\n"
|
| 289 |
+
"import json\n"
|
| 290 |
+
"import os\n"
|
| 291 |
+
"import re\n"
|
| 292 |
"import subprocess\n"
|
| 293 |
+
"import sys\n"
|
| 294 |
+
"from pathlib import Path\n\n"
|
| 295 |
+
"PAYLOADS = {\n"
|
| 296 |
+
" 'PostToolUse': {\n"
|
| 297 |
+
" 'hook_event_name': 'PostToolUse',\n"
|
| 298 |
+
" 'tool_name': 'Bash',\n"
|
| 299 |
+
" 'tool_input': {'command': 'pip install fastapi pytest'},\n"
|
| 300 |
+
" },\n"
|
| 301 |
+
" 'Stop': {\n"
|
| 302 |
+
" 'hook_event_name': 'Stop',\n"
|
| 303 |
+
" 'session_id': 'clean-host-fake-claude',\n"
|
| 304 |
+
" },\n"
|
| 305 |
+
"}\n\n"
|
| 306 |
+
"def _settings_path(raw: str) -> Path:\n"
|
| 307 |
+
" if raw:\n"
|
| 308 |
+
" return Path(raw)\n"
|
| 309 |
+
" return Path(os.path.expanduser('~/.claude/settings.json'))\n\n"
|
| 310 |
+
"def _commands(settings: dict, event: str) -> list[str]:\n"
|
| 311 |
+
" payload = PAYLOADS[event]\n"
|
| 312 |
+
" tool_name = str(payload.get('tool_name') or '')\n"
|
| 313 |
+
" out: list[str] = []\n"
|
| 314 |
+
" for entry in settings.get('hooks', {}).get(event, []):\n"
|
| 315 |
+
" if not isinstance(entry, dict):\n"
|
| 316 |
+
" continue\n"
|
| 317 |
+
" matcher = str(entry.get('matcher') or '.*')\n"
|
| 318 |
+
" if event == 'PostToolUse' and not re.search(matcher, tool_name):\n"
|
| 319 |
+
" continue\n"
|
| 320 |
+
" for hook in entry.get('hooks', []):\n"
|
| 321 |
+
" if isinstance(hook, dict) and hook.get('type') == 'command':\n"
|
| 322 |
+
" command = hook.get('command')\n"
|
| 323 |
+
" if isinstance(command, str) and command.strip():\n"
|
| 324 |
+
" out.append(command)\n"
|
| 325 |
+
" return out\n\n"
|
| 326 |
+
"def main() -> int:\n"
|
| 327 |
+
" parser = argparse.ArgumentParser()\n"
|
| 328 |
+
" parser.add_argument('--settings', default='')\n"
|
| 329 |
+
" parser.add_argument('--cwd', default='')\n"
|
| 330 |
+
" parser.add_argument('-p', '--print', action='store_true')\n"
|
| 331 |
+
" parser.add_argument('prompt', nargs='*')\n"
|
| 332 |
+
" args = parser.parse_args()\n"
|
| 333 |
+
" settings = json.loads(_settings_path(args.settings).read_text(encoding='utf-8'))\n"
|
| 334 |
+
" cwd = args.cwd or os.getcwd()\n"
|
| 335 |
+
" records = []\n"
|
| 336 |
+
" for event in ('PostToolUse', 'Stop'):\n"
|
| 337 |
+
" payload = json.dumps(PAYLOADS[event])\n"
|
| 338 |
+
" for command in _commands(settings, event):\n"
|
| 339 |
" result = subprocess.run(\n"
|
| 340 |
" command,\n"
|
| 341 |
" cwd=cwd,\n"
|
|
|
|
| 346 |
" check=False,\n"
|
| 347 |
" shell=True,\n"
|
| 348 |
" )\n"
|
| 349 |
+
" records.append({\n"
|
| 350 |
+
" 'event': event,\n"
|
| 351 |
+
" 'command': command,\n"
|
| 352 |
+
" 'returncode': result.returncode,\n"
|
| 353 |
+
" 'stdout': result.stdout[-500:],\n"
|
| 354 |
+
" 'stderr': result.stderr[-500:],\n"
|
| 355 |
+
" })\n"
|
| 356 |
+
" failed = [r for r in records if r['returncode'] != 0]\n"
|
| 357 |
+
" print(json.dumps({'hook_commands': len(records), 'failed': len(failed), 'commands': records}))\n"
|
| 358 |
+
" return 1 if failed else 0\n\n"
|
| 359 |
+
"if __name__ == '__main__':\n"
|
| 360 |
+
" raise SystemExit(main())\n",
|
| 361 |
+
encoding="utf-8",
|
| 362 |
+
)
|
| 363 |
+
return path
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def write_tiny_repo(path: Path) -> None:
|
| 367 |
+
(path / "app").mkdir(parents=True, exist_ok=True)
|
| 368 |
+
(path / "tests").mkdir(parents=True, exist_ok=True)
|
| 369 |
+
(path / "pyproject.toml").write_text(
|
| 370 |
+
"[project]\n"
|
| 371 |
+
"name = \"tiny-fastapi-contract\"\n"
|
| 372 |
+
"version = \"0.1.0\"\n"
|
| 373 |
+
"dependencies = [\"fastapi\", \"pytest\"]\n",
|
| 374 |
+
encoding="utf-8",
|
| 375 |
+
)
|
| 376 |
+
(path / "app" / "main.py").write_text(
|
| 377 |
+
"from fastapi import FastAPI\n\n"
|
| 378 |
+
"app = FastAPI()\n\n"
|
| 379 |
+
"@app.get('/health')\n"
|
| 380 |
+
"def health():\n"
|
| 381 |
+
" return {'ok': True}\n",
|
| 382 |
+
encoding="utf-8",
|
| 383 |
+
)
|
| 384 |
+
(path / "tests" / "test_health.py").write_text(
|
| 385 |
+
"def test_contract_fixture():\n"
|
| 386 |
+
" assert True\n",
|
| 387 |
+
encoding="utf-8",
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def _single_wheel(dist: Path) -> Path:
|
| 392 |
+
wheels = sorted(dist.glob("*.whl"))
|
| 393 |
+
if len(wheels) != 1:
|
| 394 |
+
raise AssertionError(f"expected exactly one wheel in {dist}, found {len(wheels)}")
|
| 395 |
+
return wheels[0]
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def _prepare_dirs(paths: ContractPaths) -> None:
|
| 399 |
+
for path in (
|
| 400 |
+
paths.home,
|
| 401 |
+
paths.appdata,
|
| 402 |
+
paths.localappdata,
|
| 403 |
+
paths.xdg_config,
|
| 404 |
+
paths.xdg_cache,
|
| 405 |
+
paths.pip_cache,
|
| 406 |
+
paths.dist,
|
| 407 |
+
paths.fake_modules,
|
| 408 |
+
paths.sessions,
|
| 409 |
+
):
|
| 410 |
+
path.mkdir(parents=True, exist_ok=True)
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def _assert_fake_claude_hook_output(stdout: str) -> None:
|
| 414 |
+
try:
|
| 415 |
+
result = json.loads(stdout)
|
| 416 |
+
except json.JSONDecodeError as exc:
|
| 417 |
+
raise AssertionError(f"fake Claude hook smoke returned invalid JSON: {stdout!r}") from exc
|
| 418 |
+
if result.get("failed") != 0:
|
| 419 |
+
raise AssertionError(f"fake Claude hook smoke had failures: {stdout}")
|
| 420 |
+
hook_commands = int(result.get("hook_commands") or 0)
|
| 421 |
+
if hook_commands < 5:
|
| 422 |
+
raise AssertionError(f"expected at least 5 generated hook commands, got {hook_commands}")
|
| 423 |
+
rendered = "\n".join(
|
| 424 |
+
str(row.get("command", ""))
|
| 425 |
+
for row in result.get("commands", [])
|
| 426 |
+
if isinstance(row, dict)
|
| 427 |
+
)
|
| 428 |
+
for expected in (
|
| 429 |
+
"ctx.adapters.claude_code.hooks.context_monitor",
|
| 430 |
+
"skill_add_detector",
|
| 431 |
+
"ctx.adapters.claude_code.hooks.bundle_orchestrator",
|
| 432 |
+
"usage_tracker",
|
| 433 |
+
"ctx.adapters.claude_code.hooks.lifecycle_hooks",
|
| 434 |
+
):
|
| 435 |
+
if expected not in rendered:
|
| 436 |
+
raise AssertionError(f"fake Claude hook smoke did not run {expected}")
|
| 437 |
+
|
| 438 |
+
|
| 439 |
def _quote_command(parts: Sequence[str | Path]) -> str:
|
| 440 |
values = [str(part) for part in parts]
|
| 441 |
if os.name == "nt":
|
| 442 |
return subprocess.list2cmdline(values)
|
| 443 |
return " ".join(shlex.quote(part) for part in values)
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def write_live_claude_sentinel_script(path: Path) -> None:
|
| 447 |
+
path.write_text(
|
| 448 |
+
'''"""Append Claude Code hook events to a clean-host sentinel file."""\n'''
|
| 449 |
+
"from __future__ import annotations\n\n"
|
| 450 |
+
"import argparse\n"
|
| 451 |
+
"import json\n"
|
| 452 |
+
"import os\n"
|
| 453 |
+
"import sys\n"
|
| 454 |
+
"from pathlib import Path\n\n"
|
| 455 |
+
"def main() -> int:\n"
|
| 456 |
+
" parser = argparse.ArgumentParser()\n"
|
| 457 |
+
" parser.add_argument('--event', required=True)\n"
|
| 458 |
+
" parser.add_argument('--out', required=True)\n"
|
| 459 |
+
" args = parser.parse_args()\n"
|
| 460 |
+
" raw = sys.stdin.read()\n"
|
| 461 |
+
" try:\n"
|
| 462 |
+
" payload = json.loads(raw) if raw.strip() else {}\n"
|
| 463 |
+
" except json.JSONDecodeError:\n"
|
| 464 |
+
" payload = {'invalid_json_prefix': raw[:200]}\n"
|
| 465 |
+
" out = Path(args.out)\n"
|
| 466 |
+
" out.parent.mkdir(parents=True, exist_ok=True)\n"
|
| 467 |
+
" record = {\n"
|
| 468 |
+
" 'event': args.event,\n"
|
| 469 |
+
" 'hook_event_name': payload.get('hook_event_name'),\n"
|
| 470 |
+
" 'tool_name': payload.get('tool_name'),\n"
|
| 471 |
+
" 'cwd': os.getcwd(),\n"
|
| 472 |
+
" 'argv': sys.argv[1:],\n"
|
| 473 |
+
" }\n"
|
| 474 |
+
" with out.open('a', encoding='utf-8') as handle:\n"
|
| 475 |
+
" handle.write(json.dumps(record, sort_keys=True) + '\\n')\n"
|
| 476 |
+
" return 0\n\n"
|
| 477 |
+
"if __name__ == '__main__':\n"
|
| 478 |
+
" raise SystemExit(main())\n",
|
| 479 |
+
encoding="utf-8",
|
| 480 |
+
)
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def _append_live_claude_sentinel_hooks(
|
| 484 |
+
*,
|
| 485 |
+
settings_json: Path,
|
| 486 |
+
python_bin: Path,
|
| 487 |
+
sentinel_script: Path,
|
| 488 |
+
sentinel_jsonl: Path,
|
| 489 |
+
) -> None:
|
| 490 |
+
settings = json.loads(settings_json.read_text(encoding="utf-8"))
|
| 491 |
+
hooks = settings.setdefault("hooks", {})
|
| 492 |
+
post_command = _quote_command((
|
| 493 |
+
python_bin,
|
| 494 |
+
sentinel_script,
|
| 495 |
+
"--event",
|
| 496 |
+
"PostToolUse",
|
| 497 |
+
"--out",
|
| 498 |
+
sentinel_jsonl,
|
| 499 |
+
))
|
| 500 |
+
stop_command = _quote_command((
|
| 501 |
+
python_bin,
|
| 502 |
+
sentinel_script,
|
| 503 |
+
"--event",
|
| 504 |
+
"Stop",
|
| 505 |
+
"--out",
|
| 506 |
+
sentinel_jsonl,
|
| 507 |
+
))
|
| 508 |
+
hooks.setdefault("PostToolUse", []).append({
|
| 509 |
+
"matcher": ".*",
|
| 510 |
+
"hooks": [{"type": "command", "command": post_command}],
|
| 511 |
+
})
|
| 512 |
+
hooks.setdefault("Stop", []).append({
|
| 513 |
+
"hooks": [{"type": "command", "command": stop_command}],
|
| 514 |
+
})
|
| 515 |
+
tmp_path = settings_json.with_name(f"{settings_json.name}.live.tmp")
|
| 516 |
+
tmp_path.write_text(json.dumps(settings, indent=2) + "\n", encoding="utf-8")
|
| 517 |
+
os.replace(tmp_path, settings_json)
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
def _sentinel_records(path: Path) -> list[dict[str, Any]]:
|
| 521 |
+
if not path.exists():
|
| 522 |
+
raise AssertionError(f"live Claude sentinel was not written: {path}")
|
| 523 |
+
records: list[dict[str, Any]] = []
|
| 524 |
+
for line in path.read_text(encoding="utf-8").splitlines():
|
| 525 |
+
if not line.strip():
|
| 526 |
+
continue
|
| 527 |
+
try:
|
| 528 |
+
record = json.loads(line)
|
| 529 |
+
except json.JSONDecodeError as exc:
|
| 530 |
+
raise AssertionError(f"live Claude sentinel has invalid JSONL: {line}") from exc
|
| 531 |
+
if not isinstance(record, dict):
|
| 532 |
+
raise AssertionError(f"live Claude sentinel record is not an object: {line}")
|
| 533 |
+
records.append(record)
|
| 534 |
+
return records
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def _assert_live_claude_sentinel(path: Path, *, expected_cwd: Path) -> None:
|
| 538 |
+
records = _sentinel_records(path)
|
| 539 |
+
events = {str(record.get("event") or "") for record in records}
|
| 540 |
+
for expected in _EXPECTED_LIVE_CLAUDE_EVENTS:
|
| 541 |
+
if expected not in events:
|
| 542 |
+
raise AssertionError(f"live Claude sentinel did not record {expected}")
|
| 543 |
+
expected_resolved = expected_cwd.resolve()
|
| 544 |
+
for record in records:
|
| 545 |
+
cwd = record.get("cwd")
|
| 546 |
+
if cwd is None or Path(str(cwd)).resolve() != expected_resolved:
|
| 547 |
+
raise AssertionError(
|
| 548 |
+
"live Claude sentinel recorded unexpected cwd: "
|
| 549 |
+
f"{cwd!r}, expected {expected_resolved}"
|
| 550 |
+
)
|
| 551 |
+
hook_event = record.get("hook_event_name")
|
| 552 |
+
event = record.get("event")
|
| 553 |
+
if hook_event not in (None, event):
|
| 554 |
+
raise AssertionError(
|
| 555 |
+
f"live Claude sentinel event mismatch: event={event!r}, "
|
| 556 |
+
f"hook_event_name={hook_event!r}"
|
| 557 |
+
)
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def _require_live_claude_ack(max_budget_usd: float) -> None:
|
| 561 |
+
if os.environ.get(LIVE_CLAUDE_ACK_ENV) != LIVE_CLAUDE_ACK_VALUE:
|
| 562 |
+
raise AssertionError(
|
| 563 |
+
f"set {LIVE_CLAUDE_ACK_ENV}={LIVE_CLAUDE_ACK_VALUE} to run "
|
| 564 |
+
"the quota-consuming live Claude Code gate"
|
| 565 |
+
)
|
| 566 |
+
if max_budget_usd <= 0 or max_budget_usd > LIVE_CLAUDE_MAX_BUDGET_USD:
|
| 567 |
+
raise AssertionError(
|
| 568 |
+
"live Claude budget must be greater than 0 and no more than "
|
| 569 |
+
f"{LIVE_CLAUDE_MAX_BUDGET_USD} USD"
|
| 570 |
+
)
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def _live_claude_command(
|
| 574 |
+
*,
|
| 575 |
+
claude_bin: Path,
|
| 576 |
+
settings_json: Path,
|
| 577 |
+
max_budget_usd: float,
|
| 578 |
+
) -> list[str]:
|
| 579 |
+
return [
|
| 580 |
+
str(claude_bin),
|
| 581 |
+
"--settings",
|
| 582 |
+
str(settings_json),
|
| 583 |
+
"--setting-sources",
|
| 584 |
+
"user",
|
| 585 |
+
"--output-format",
|
| 586 |
+
"stream-json",
|
| 587 |
+
"--include-hook-events",
|
| 588 |
+
"--no-session-persistence",
|
| 589 |
+
"--max-budget-usd",
|
| 590 |
+
str(max_budget_usd),
|
| 591 |
+
"--allowedTools",
|
| 592 |
+
"Bash(python --version)",
|
| 593 |
+
"-p",
|
| 594 |
+
"Use Bash to run exactly `python --version`, then stop.",
|
| 595 |
+
]
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
def _run_live_claude_gate(
|
| 599 |
+
*,
|
| 600 |
+
runner: CommandRunner,
|
| 601 |
+
paths: ContractPaths,
|
| 602 |
+
python_bin: Path,
|
| 603 |
+
settings_json: Path,
|
| 604 |
+
max_budget_usd: float,
|
| 605 |
+
claude_bin: Path | None,
|
| 606 |
+
) -> None:
|
| 607 |
+
_require_live_claude_ack(max_budget_usd)
|
| 608 |
+
resolved_claude = claude_bin if claude_bin is not None else None
|
| 609 |
+
if resolved_claude is None:
|
| 610 |
+
claude = shutil.which("claude")
|
| 611 |
+
resolved_claude = Path(claude) if claude is not None else None
|
| 612 |
+
if resolved_claude is None:
|
| 613 |
+
raise AssertionError("claude executable was not found on PATH")
|
| 614 |
+
live_env = live_claude_env(paths)
|
| 615 |
+
runner.run(
|
| 616 |
+
[str(resolved_claude), "--version"],
|
| 617 |
+
cwd=paths.tiny_repo,
|
| 618 |
+
env=live_env,
|
| 619 |
+
timeout_seconds=LIVE_CLAUDE_PREFLIGHT_TIMEOUT_SECONDS,
|
| 620 |
+
)
|
| 621 |
+
runner.run(
|
| 622 |
+
[str(resolved_claude), "auth", "status"],
|
| 623 |
+
cwd=paths.tiny_repo,
|
| 624 |
+
env=live_env,
|
| 625 |
+
timeout_seconds=LIVE_CLAUDE_PREFLIGHT_TIMEOUT_SECONDS,
|
| 626 |
+
)
|
| 627 |
+
sentinel_script = paths.root / "live-claude-hook-sentinel.py"
|
| 628 |
+
sentinel_jsonl = paths.root / "live-claude-hooks.jsonl"
|
| 629 |
+
write_live_claude_sentinel_script(sentinel_script)
|
| 630 |
+
_append_live_claude_sentinel_hooks(
|
| 631 |
+
settings_json=settings_json,
|
| 632 |
+
python_bin=python_bin,
|
| 633 |
+
sentinel_script=sentinel_script,
|
| 634 |
+
sentinel_jsonl=sentinel_jsonl,
|
| 635 |
+
)
|
| 636 |
+
runner.run(
|
| 637 |
+
_live_claude_command(
|
| 638 |
+
claude_bin=resolved_claude,
|
| 639 |
+
settings_json=settings_json,
|
| 640 |
+
max_budget_usd=max_budget_usd,
|
| 641 |
+
),
|
| 642 |
+
cwd=paths.tiny_repo,
|
| 643 |
+
env=live_env,
|
| 644 |
+
timeout_seconds=LIVE_CLAUDE_PROMPT_TIMEOUT_SECONDS,
|
| 645 |
+
)
|
| 646 |
+
_assert_live_claude_sentinel(sentinel_jsonl, expected_cwd=paths.tiny_repo)
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
def run_contract(
|
| 650 |
+
*,
|
| 651 |
+
project_root: Path,
|
| 652 |
+
temp_root: Path,
|
| 653 |
+
fast: bool,
|
| 654 |
+
runner: CommandRunner | None = None,
|
| 655 |
+
run_live_claude: bool = False,
|
| 656 |
+
live_claude_max_budget_usd: float = LIVE_CLAUDE_DEFAULT_BUDGET_USD,
|
| 657 |
+
live_claude_bin: Path | None = None,
|
| 658 |
+
) -> None:
|
| 659 |
+
runner = runner or CommandRunner()
|
| 660 |
+
paths = make_paths(temp_root)
|
| 661 |
+
_prepare_dirs(paths)
|
| 662 |
+
write_tiny_repo(paths.tiny_repo)
|
| 663 |
+
write_fake_litellm(paths.fake_modules)
|
| 664 |
+
fake_claude = write_fake_claude_cli(paths.fake_modules)
|
| 665 |
+
|
| 666 |
+
env = isolated_env(paths)
|
| 667 |
+
runner.run(
|
| 668 |
+
[
|
| 669 |
+
sys.executable,
|
| 670 |
+
"-m",
|
| 671 |
+
"pip",
|
| 672 |
+
"wheel",
|
| 673 |
+
"--no-deps",
|
| 674 |
+
"--wheel-dir",
|
| 675 |
+
str(paths.dist),
|
| 676 |
+
str(project_root),
|
| 677 |
+
],
|
| 678 |
+
cwd=project_root,
|
| 679 |
+
env=env,
|
| 680 |
+
)
|
| 681 |
+
runner.run([sys.executable, "-m", "venv", str(paths.venv)], cwd=project_root, env=env)
|
| 682 |
+
wheel = _single_wheel(paths.dist)
|
| 683 |
+
py = venv_python(paths.venv)
|
| 684 |
+
runner.run([str(py), "-m", "pip", "install", str(wheel)], cwd=project_root, env=env)
|
| 685 |
+
|
| 686 |
+
run_env = isolated_env(paths, extra_pythonpath=paths.fake_modules)
|
| 687 |
+
ctx_init = venv_script(paths.venv, "ctx-init")
|
| 688 |
+
ctx_scan_repo = venv_script(paths.venv, "ctx-scan-repo")
|
| 689 |
+
ctx = venv_script(paths.venv, "ctx")
|
| 690 |
+
|
| 691 |
+
runner.run([str(ctx_init), "--hooks"], cwd=paths.tiny_repo, env=run_env)
|
| 692 |
+
claude_dir = paths.home / ".claude"
|
| 693 |
+
assert_inside(claude_dir, paths.root)
|
| 694 |
+
if not (claude_dir / "settings.json").exists():
|
| 695 |
+
raise AssertionError("ctx-init --hooks did not write isolated settings.json")
|
| 696 |
+
fake_claude_result = runner.run(
|
| 697 |
+
[
|
| 698 |
+
str(py),
|
| 699 |
+
str(fake_claude),
|
| 700 |
+
"--settings",
|
| 701 |
+
str(claude_dir / "settings.json"),
|
| 702 |
+
"--cwd",
|
| 703 |
+
str(paths.tiny_repo),
|
| 704 |
+
"-p",
|
| 705 |
+
"trigger clean-host hook smoke",
|
| 706 |
+
],
|
| 707 |
+
cwd=paths.tiny_repo,
|
| 708 |
+
env=run_env,
|
| 709 |
+
)
|
| 710 |
+
_assert_fake_claude_hook_output(fake_claude_result.stdout)
|
| 711 |
+
if run_live_claude:
|
| 712 |
+
_run_live_claude_gate(
|
| 713 |
+
runner=runner,
|
| 714 |
+
paths=paths,
|
| 715 |
+
python_bin=py,
|
| 716 |
+
settings_json=claude_dir / "settings.json",
|
| 717 |
+
max_budget_usd=live_claude_max_budget_usd,
|
| 718 |
+
claude_bin=live_claude_bin,
|
| 719 |
+
)
|
| 720 |
+
|
| 721 |
+
stack_profile = paths.root / "stack-profile.json"
|
| 722 |
+
runner.run(
|
| 723 |
+
[
|
| 724 |
+
str(ctx_scan_repo),
|
| 725 |
+
"--repo",
|
| 726 |
+
str(paths.tiny_repo),
|
| 727 |
+
"--output",
|
| 728 |
+
str(stack_profile),
|
| 729 |
+
"--recommend",
|
| 730 |
+
],
|
| 731 |
+
cwd=paths.tiny_repo,
|
| 732 |
+
env=run_env,
|
| 733 |
+
)
|
| 734 |
+
if not stack_profile.exists():
|
| 735 |
+
raise AssertionError("ctx-scan-repo did not write stack profile")
|
| 736 |
+
|
| 737 |
+
runner.run(
|
| 738 |
+
[
|
| 739 |
+
str(ctx),
|
| 740 |
+
"run",
|
| 741 |
+
"--model",
|
| 742 |
+
"ollama/clean-host-fake",
|
| 743 |
+
"--task",
|
| 744 |
+
"Return a one-sentence clean-host contract response.",
|
| 745 |
+
"--no-ctx-tools",
|
| 746 |
+
"--sessions-dir",
|
| 747 |
+
str(paths.sessions),
|
| 748 |
+
"--session-id",
|
| 749 |
+
"clean-host-contract",
|
| 750 |
+
"--quiet",
|
| 751 |
+
],
|
| 752 |
+
cwd=paths.tiny_repo,
|
| 753 |
+
env=run_env,
|
| 754 |
+
)
|
| 755 |
+
runner.run(
|
| 756 |
+
[
|
| 757 |
+
str(ctx),
|
| 758 |
+
"resume",
|
| 759 |
+
"clean-host-contract",
|
| 760 |
+
"--task",
|
| 761 |
+
"Confirm resume works.",
|
| 762 |
+
"--sessions-dir",
|
| 763 |
+
str(paths.sessions),
|
| 764 |
+
"--quiet",
|
| 765 |
+
],
|
| 766 |
+
cwd=paths.tiny_repo,
|
| 767 |
+
env=run_env,
|
| 768 |
+
)
|
| 769 |
+
|
| 770 |
+
denied_env = dict(run_env)
|
| 771 |
+
denied_env["CTX_FAKE_LITELLM_TOOL_CALL"] = "ctx__wiki_get"
|
| 772 |
+
denied = runner.run(
|
| 773 |
+
[
|
| 774 |
+
str(ctx),
|
| 775 |
+
"run",
|
| 776 |
+
"--model",
|
| 777 |
+
"ollama/clean-host-fake",
|
| 778 |
+
"--task",
|
| 779 |
+
"Attempt the wiki tool so policy can deny it.",
|
| 780 |
+
"--sessions-dir",
|
| 781 |
+
str(paths.sessions),
|
| 782 |
+
"--session-id",
|
| 783 |
+
"clean-host-denied-tool",
|
| 784 |
+
"--deny-tool",
|
| 785 |
+
"ctx__wiki_get",
|
| 786 |
+
"--quiet",
|
| 787 |
+
"--json",
|
| 788 |
+
],
|
| 789 |
+
cwd=paths.tiny_repo,
|
| 790 |
+
env=denied_env,
|
| 791 |
+
check=False,
|
| 792 |
+
)
|
| 793 |
+
if denied.returncode != 2 or '"tool_denied"' not in denied.stdout:
|
| 794 |
+
raise AssertionError(
|
| 795 |
+
"expected denied tool run to exit 2 with tool_denied JSON; "
|
| 796 |
+
f"got rc={denied.returncode}"
|
| 797 |
+
)
|
| 798 |
+
|
| 799 |
+
if not fast:
|
| 800 |
+
runner.run([str(ctx_init), "--help"], cwd=paths.tiny_repo, env=run_env)
|
| 801 |
+
runner.run([str(ctx_scan_repo), "--help"], cwd=paths.tiny_repo, env=run_env)
|
| 802 |
+
runner.run([str(ctx), "--help"], cwd=paths.tiny_repo, env=run_env)
|
| 803 |
+
|
| 804 |
+
for expected in (paths.home, paths.appdata, paths.localappdata, paths.sessions):
|
| 805 |
+
assert_inside(expected, paths.root)
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
|
| 809 |
+
parser = argparse.ArgumentParser(
|
| 810 |
+
description="Build/install ctx into a temp clean host and exercise core flows.",
|
| 811 |
+
)
|
| 812 |
+
parser.add_argument(
|
| 813 |
+
"--fast",
|
| 814 |
+
action="store_true",
|
| 815 |
+
help="Run the core contract only; skip extra help probes.",
|
| 816 |
+
)
|
| 817 |
+
parser.add_argument(
|
| 818 |
+
"--keep-temp",
|
| 819 |
+
action="store_true",
|
| 820 |
+
help="Keep the temp root after the run for debugging.",
|
| 821 |
+
)
|
| 822 |
+
parser.add_argument(
|
| 823 |
+
"--temp-root",
|
| 824 |
+
type=Path,
|
| 825 |
+
help="Use an explicit temp root. Must not already contain important data.",
|
| 826 |
+
)
|
| 827 |
+
parser.add_argument(
|
| 828 |
+
"--repo-root",
|
| 829 |
+
type=Path,
|
| 830 |
+
default=repo_root(),
|
| 831 |
+
help="Repository root to build. Default: inferred from this script.",
|
| 832 |
+
)
|
| 833 |
+
parser.add_argument(
|
| 834 |
+
"--run-live-claude",
|
| 835 |
+
action="store_true",
|
| 836 |
+
help=(
|
| 837 |
+
"Also run a real Claude Code host smoke. Requires "
|
| 838 |
+
f"{LIVE_CLAUDE_ACK_ENV}={LIVE_CLAUDE_ACK_VALUE} and can consume quota."
|
| 839 |
+
),
|
| 840 |
+
)
|
| 841 |
+
parser.add_argument(
|
| 842 |
+
"--live-claude-max-budget-usd",
|
| 843 |
+
type=float,
|
| 844 |
+
default=LIVE_CLAUDE_DEFAULT_BUDGET_USD,
|
| 845 |
+
help=(
|
| 846 |
+
"Maximum live Claude Code API budget for --run-live-claude. "
|
| 847 |
+
f"Default: {LIVE_CLAUDE_DEFAULT_BUDGET_USD}."
|
| 848 |
+
),
|
| 849 |
+
)
|
| 850 |
+
parser.add_argument(
|
| 851 |
+
"--claude-bin",
|
| 852 |
+
type=Path,
|
| 853 |
+
help="Explicit Claude Code executable path for --run-live-claude.",
|
| 854 |
+
)
|
| 855 |
+
return parser.parse_args(argv)
|
| 856 |
+
|
| 857 |
+
|
| 858 |
+
def main(argv: Sequence[str] | None = None) -> int:
|
| 859 |
+
args = parse_args(argv)
|
| 860 |
+
project_root = args.repo_root.resolve()
|
| 861 |
+
if args.temp_root is not None:
|
| 862 |
+
temp_root = args.temp_root.resolve()
|
| 863 |
+
temp_root.mkdir(parents=True, exist_ok=True)
|
| 864 |
+
run_contract(
|
| 865 |
+
project_root=project_root,
|
| 866 |
+
temp_root=temp_root,
|
| 867 |
+
fast=args.fast,
|
| 868 |
+
run_live_claude=args.run_live_claude,
|
| 869 |
+
live_claude_max_budget_usd=args.live_claude_max_budget_usd,
|
| 870 |
+
live_claude_bin=args.claude_bin,
|
| 871 |
+
)
|
| 872 |
+
print(f"clean-host contract passed; temp root kept at {temp_root}")
|
| 873 |
+
return 0
|
| 874 |
+
|
| 875 |
+
temp_dir = tempfile.mkdtemp(prefix="ctx-clean-host-")
|
| 876 |
+
temp_root = Path(temp_dir).resolve()
|
| 877 |
+
try:
|
| 878 |
+
run_contract(
|
| 879 |
+
project_root=project_root,
|
| 880 |
+
temp_root=temp_root,
|
| 881 |
+
fast=args.fast,
|
| 882 |
+
run_live_claude=args.run_live_claude,
|
| 883 |
+
live_claude_max_budget_usd=args.live_claude_max_budget_usd,
|
| 884 |
+
live_claude_bin=args.claude_bin,
|
| 885 |
+
)
|
| 886 |
+
print(f"clean-host contract passed under {temp_root}")
|
| 887 |
+
return 0
|
| 888 |
+
finally:
|
| 889 |
+
if args.keep_temp:
|
| 890 |
+
print(f"kept temp root: {temp_root}")
|
| 891 |
+
else:
|
| 892 |
+
shutil.rmtree(temp_root, ignore_errors=True)
|
| 893 |
+
|
| 894 |
+
|
| 895 |
+
if __name__ == "__main__":
|
| 896 |
+
raise SystemExit(main())
|
scripts/graph_artifact_guard.py
CHANGED
|
@@ -1,196 +1,196 @@
|
|
| 1 |
-
from __future__ import annotations
|
| 2 |
-
|
| 3 |
-
import argparse
|
| 4 |
-
import subprocess
|
| 5 |
-
import sys
|
| 6 |
-
from pathlib import Path
|
| 7 |
-
from typing import Iterable
|
| 8 |
-
|
| 9 |
-
DEFAULT_ARTIFACTS = (
|
| 10 |
-
"graph/wiki-graph.tar.gz",
|
| 11 |
-
"graph/wiki-graph-runtime.tar.gz",
|
| 12 |
-
"graph/skills-sh-catalog.json.gz",
|
| 13 |
-
"graph/communities.json",
|
| 14 |
-
"graph/entity-overlays.jsonl",
|
| 15 |
-
)
|
| 16 |
-
|
| 17 |
-
STALE_GRAPH_PATTERNS = (
|
| 18 |
-
"*.staged",
|
| 19 |
-
"*.partial",
|
| 20 |
-
"*.lock",
|
| 21 |
-
"*.tmp",
|
| 22 |
-
)
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
def _run_git(
|
| 26 |
-
repo: Path,
|
| 27 |
-
args: Iterable[str],
|
| 28 |
-
*,
|
| 29 |
-
check: bool = True,
|
| 30 |
-
capture: bool = False,
|
| 31 |
-
) -> subprocess.CompletedProcess[str]:
|
| 32 |
-
return subprocess.run(
|
| 33 |
-
["git", *args],
|
| 34 |
-
cwd=repo,
|
| 35 |
-
check=check,
|
| 36 |
-
text=True,
|
| 37 |
-
stdout=subprocess.PIPE if capture else None,
|
| 38 |
-
stderr=subprocess.PIPE if capture else None,
|
| 39 |
-
)
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
def _repo_root(path: Path) -> Path:
|
| 43 |
-
result = _run_git(path, ["rev-parse", "--show-toplevel"], capture=True)
|
| 44 |
-
return Path(result.stdout.strip()).resolve()
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
def _tracked_artifacts(repo: Path, artifacts: Iterable[str]) -> list[str]:
|
| 48 |
-
tracked: list[str] = []
|
| 49 |
-
for artifact in artifacts:
|
| 50 |
-
result = _run_git(
|
| 51 |
-
repo,
|
| 52 |
-
["ls-files", "--error-unmatch", artifact],
|
| 53 |
-
check=False,
|
| 54 |
-
capture=True,
|
| 55 |
-
)
|
| 56 |
-
if result.returncode == 0:
|
| 57 |
-
tracked.append(artifact)
|
| 58 |
-
return tracked
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
def _set_skip_worktree(repo: Path, artifacts: list[str], *, enabled: bool) -> None:
|
| 62 |
-
if not artifacts:
|
| 63 |
-
print("No tracked graph artifacts matched.")
|
| 64 |
-
return
|
| 65 |
-
flag = "--skip-worktree" if enabled else "--no-skip-worktree"
|
| 66 |
-
_run_git(repo, ["update-index", flag, *artifacts])
|
| 67 |
-
action = "parked" if enabled else "unparked"
|
| 68 |
-
for artifact in artifacts:
|
| 69 |
-
print(f"{action}: {artifact}")
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
def _print_status(repo: Path, artifacts: list[str]) -> None:
|
| 73 |
-
if not artifacts:
|
| 74 |
-
print("No tracked graph artifacts matched.")
|
| 75 |
-
return
|
| 76 |
-
result = _run_git(repo, ["ls-files", "-v", *artifacts], capture=True)
|
| 77 |
-
for line in result.stdout.splitlines():
|
| 78 |
-
state = "parked" if line.startswith("S ") else "active"
|
| 79 |
-
print(f"{state}: {line[2:]}")
|
| 80 |
-
print()
|
| 81 |
-
sys.stdout.flush()
|
| 82 |
-
_run_git(repo, ["count-objects", "-vH"])
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
def _prune(repo: Path, *, include_lfs: bool, include_git_prune: bool) -> None:
|
| 86 |
-
if include_git_prune:
|
| 87 |
-
_run_git(repo, ["prune", "--expire=now", "--verbose"])
|
| 88 |
-
if include_lfs:
|
| 89 |
-
result = _run_git(repo, ["lfs", "prune", "--verbose"], check=False)
|
| 90 |
-
if result.returncode != 0:
|
| 91 |
-
raise SystemExit(result.returncode)
|
| 92 |
-
if not include_lfs and not include_git_prune:
|
| 93 |
-
print("No prune action selected.")
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
def _clean_stale_graph_files(repo: Path, *, dry_run: bool) -> None:
|
| 97 |
-
graph_dir = (repo / "graph").resolve()
|
| 98 |
-
repo = repo.resolve()
|
| 99 |
-
if not graph_dir.is_dir():
|
| 100 |
-
print("No graph directory found.")
|
| 101 |
-
return
|
| 102 |
-
|
| 103 |
-
stale_files: list[Path] = []
|
| 104 |
-
for pattern in STALE_GRAPH_PATTERNS:
|
| 105 |
-
stale_files.extend(
|
| 106 |
-
path.resolve()
|
| 107 |
-
for path in graph_dir.glob(pattern)
|
| 108 |
-
if path.is_file() and path.resolve().is_relative_to(graph_dir)
|
| 109 |
-
)
|
| 110 |
-
|
| 111 |
-
for path in sorted(set(stale_files)):
|
| 112 |
-
rel = path.relative_to(repo).as_posix()
|
| 113 |
-
if dry_run:
|
| 114 |
-
print(f"would remove: {rel}")
|
| 115 |
-
else:
|
| 116 |
-
path.unlink()
|
| 117 |
-
print(f"removed: {rel}")
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
def _parser() -> argparse.ArgumentParser:
|
| 121 |
-
parser = argparse.ArgumentParser(
|
| 122 |
-
description=(
|
| 123 |
-
"Park or unpark heavyweight generated graph artifacts so background "
|
| 124 |
-
"Git integrations do not repeatedly LFS-clean them while they are dirty."
|
| 125 |
-
)
|
| 126 |
-
)
|
| 127 |
-
parser.add_argument(
|
| 128 |
-
"command",
|
| 129 |
-
choices=("status", "park", "unpark", "prune", "clean-stale"),
|
| 130 |
-
help=(
|
| 131 |
-
"status shows skip-worktree state; park hides generated archives from "
|
| 132 |
-
"normal Git status/stage scans; unpark re-enables release staging; "
|
| 133 |
-
"prune removes prunable local LFS cache entries; clean-stale "
|
| 134 |
-
"removes interrupted graph promotion leftovers."
|
| 135 |
-
),
|
| 136 |
-
)
|
| 137 |
-
parser.add_argument(
|
| 138 |
-
"--repo",
|
| 139 |
-
type=Path,
|
| 140 |
-
default=Path.cwd(),
|
| 141 |
-
help="Repository path. Defaults to the current directory.",
|
| 142 |
-
)
|
| 143 |
-
parser.add_argument(
|
| 144 |
-
"--artifact",
|
| 145 |
-
action="append",
|
| 146 |
-
dest="artifacts",
|
| 147 |
-
help=(
|
| 148 |
-
"Artifact path to manage. May be passed more than once. Defaults to "
|
| 149 |
-
"the shipped graph tarballs and Skills.sh catalog gzip."
|
| 150 |
-
),
|
| 151 |
-
)
|
| 152 |
-
parser.add_argument(
|
| 153 |
-
"--skip-lfs",
|
| 154 |
-
action="store_true",
|
| 155 |
-
help="For prune only: skip git lfs prune.",
|
| 156 |
-
)
|
| 157 |
-
parser.add_argument(
|
| 158 |
-
"--include-git-prune",
|
| 159 |
-
action="store_true",
|
| 160 |
-
help=(
|
| 161 |
-
"For prune only: also run repo-wide git prune --expire=now. "
|
| 162 |
-
"This can discard unrelated dangling recovery objects."
|
| 163 |
-
),
|
| 164 |
-
)
|
| 165 |
-
parser.add_argument(
|
| 166 |
-
"--dry-run",
|
| 167 |
-
action="store_true",
|
| 168 |
-
help="For clean-stale only: print stale files without deleting them.",
|
| 169 |
-
)
|
| 170 |
-
return parser
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
def main(argv: list[str] | None = None) -> int:
|
| 174 |
-
args = _parser().parse_args(argv)
|
| 175 |
-
repo = _repo_root(args.repo)
|
| 176 |
-
artifacts = _tracked_artifacts(repo, args.artifacts or DEFAULT_ARTIFACTS)
|
| 177 |
-
|
| 178 |
-
if args.command == "status":
|
| 179 |
-
_print_status(repo, artifacts)
|
| 180 |
-
elif args.command == "park":
|
| 181 |
-
_set_skip_worktree(repo, artifacts, enabled=True)
|
| 182 |
-
elif args.command == "unpark":
|
| 183 |
-
_set_skip_worktree(repo, artifacts, enabled=False)
|
| 184 |
-
elif args.command == "prune":
|
| 185 |
-
_prune(
|
| 186 |
-
repo,
|
| 187 |
-
include_lfs=not args.skip_lfs,
|
| 188 |
-
include_git_prune=args.include_git_prune,
|
| 189 |
-
)
|
| 190 |
-
elif args.command == "clean-stale":
|
| 191 |
-
_clean_stale_graph_files(repo, dry_run=args.dry_run)
|
| 192 |
-
return 0
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
if __name__ == "__main__":
|
| 196 |
-
raise SystemExit(main(sys.argv[1:]))
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import subprocess
|
| 5 |
+
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Iterable
|
| 8 |
+
|
| 9 |
+
DEFAULT_ARTIFACTS = (
|
| 10 |
+
"graph/wiki-graph.tar.gz",
|
| 11 |
+
"graph/wiki-graph-runtime.tar.gz",
|
| 12 |
+
"graph/skills-sh-catalog.json.gz",
|
| 13 |
+
"graph/communities.json",
|
| 14 |
+
"graph/entity-overlays.jsonl",
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
STALE_GRAPH_PATTERNS = (
|
| 18 |
+
"*.staged",
|
| 19 |
+
"*.partial",
|
| 20 |
+
"*.lock",
|
| 21 |
+
"*.tmp",
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _run_git(
|
| 26 |
+
repo: Path,
|
| 27 |
+
args: Iterable[str],
|
| 28 |
+
*,
|
| 29 |
+
check: bool = True,
|
| 30 |
+
capture: bool = False,
|
| 31 |
+
) -> subprocess.CompletedProcess[str]:
|
| 32 |
+
return subprocess.run(
|
| 33 |
+
["git", *args],
|
| 34 |
+
cwd=repo,
|
| 35 |
+
check=check,
|
| 36 |
+
text=True,
|
| 37 |
+
stdout=subprocess.PIPE if capture else None,
|
| 38 |
+
stderr=subprocess.PIPE if capture else None,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _repo_root(path: Path) -> Path:
|
| 43 |
+
result = _run_git(path, ["rev-parse", "--show-toplevel"], capture=True)
|
| 44 |
+
return Path(result.stdout.strip()).resolve()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _tracked_artifacts(repo: Path, artifacts: Iterable[str]) -> list[str]:
|
| 48 |
+
tracked: list[str] = []
|
| 49 |
+
for artifact in artifacts:
|
| 50 |
+
result = _run_git(
|
| 51 |
+
repo,
|
| 52 |
+
["ls-files", "--error-unmatch", artifact],
|
| 53 |
+
check=False,
|
| 54 |
+
capture=True,
|
| 55 |
+
)
|
| 56 |
+
if result.returncode == 0:
|
| 57 |
+
tracked.append(artifact)
|
| 58 |
+
return tracked
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _set_skip_worktree(repo: Path, artifacts: list[str], *, enabled: bool) -> None:
|
| 62 |
+
if not artifacts:
|
| 63 |
+
print("No tracked graph artifacts matched.")
|
| 64 |
+
return
|
| 65 |
+
flag = "--skip-worktree" if enabled else "--no-skip-worktree"
|
| 66 |
+
_run_git(repo, ["update-index", flag, *artifacts])
|
| 67 |
+
action = "parked" if enabled else "unparked"
|
| 68 |
+
for artifact in artifacts:
|
| 69 |
+
print(f"{action}: {artifact}")
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _print_status(repo: Path, artifacts: list[str]) -> None:
|
| 73 |
+
if not artifacts:
|
| 74 |
+
print("No tracked graph artifacts matched.")
|
| 75 |
+
return
|
| 76 |
+
result = _run_git(repo, ["ls-files", "-v", *artifacts], capture=True)
|
| 77 |
+
for line in result.stdout.splitlines():
|
| 78 |
+
state = "parked" if line.startswith("S ") else "active"
|
| 79 |
+
print(f"{state}: {line[2:]}")
|
| 80 |
+
print()
|
| 81 |
+
sys.stdout.flush()
|
| 82 |
+
_run_git(repo, ["count-objects", "-vH"])
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _prune(repo: Path, *, include_lfs: bool, include_git_prune: bool) -> None:
|
| 86 |
+
if include_git_prune:
|
| 87 |
+
_run_git(repo, ["prune", "--expire=now", "--verbose"])
|
| 88 |
+
if include_lfs:
|
| 89 |
+
result = _run_git(repo, ["lfs", "prune", "--verbose"], check=False)
|
| 90 |
+
if result.returncode != 0:
|
| 91 |
+
raise SystemExit(result.returncode)
|
| 92 |
+
if not include_lfs and not include_git_prune:
|
| 93 |
+
print("No prune action selected.")
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _clean_stale_graph_files(repo: Path, *, dry_run: bool) -> None:
|
| 97 |
+
graph_dir = (repo / "graph").resolve()
|
| 98 |
+
repo = repo.resolve()
|
| 99 |
+
if not graph_dir.is_dir():
|
| 100 |
+
print("No graph directory found.")
|
| 101 |
+
return
|
| 102 |
+
|
| 103 |
+
stale_files: list[Path] = []
|
| 104 |
+
for pattern in STALE_GRAPH_PATTERNS:
|
| 105 |
+
stale_files.extend(
|
| 106 |
+
path.resolve()
|
| 107 |
+
for path in graph_dir.glob(pattern)
|
| 108 |
+
if path.is_file() and path.resolve().is_relative_to(graph_dir)
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
for path in sorted(set(stale_files)):
|
| 112 |
+
rel = path.relative_to(repo).as_posix()
|
| 113 |
+
if dry_run:
|
| 114 |
+
print(f"would remove: {rel}")
|
| 115 |
+
else:
|
| 116 |
+
path.unlink()
|
| 117 |
+
print(f"removed: {rel}")
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _parser() -> argparse.ArgumentParser:
|
| 121 |
+
parser = argparse.ArgumentParser(
|
| 122 |
+
description=(
|
| 123 |
+
"Park or unpark heavyweight generated graph artifacts so background "
|
| 124 |
+
"Git integrations do not repeatedly LFS-clean them while they are dirty."
|
| 125 |
+
)
|
| 126 |
+
)
|
| 127 |
+
parser.add_argument(
|
| 128 |
+
"command",
|
| 129 |
+
choices=("status", "park", "unpark", "prune", "clean-stale"),
|
| 130 |
+
help=(
|
| 131 |
+
"status shows skip-worktree state; park hides generated archives from "
|
| 132 |
+
"normal Git status/stage scans; unpark re-enables release staging; "
|
| 133 |
+
"prune removes prunable local LFS cache entries; clean-stale "
|
| 134 |
+
"removes interrupted graph promotion leftovers."
|
| 135 |
+
),
|
| 136 |
+
)
|
| 137 |
+
parser.add_argument(
|
| 138 |
+
"--repo",
|
| 139 |
+
type=Path,
|
| 140 |
+
default=Path.cwd(),
|
| 141 |
+
help="Repository path. Defaults to the current directory.",
|
| 142 |
+
)
|
| 143 |
+
parser.add_argument(
|
| 144 |
+
"--artifact",
|
| 145 |
+
action="append",
|
| 146 |
+
dest="artifacts",
|
| 147 |
+
help=(
|
| 148 |
+
"Artifact path to manage. May be passed more than once. Defaults to "
|
| 149 |
+
"the shipped graph tarballs and Skills.sh catalog gzip."
|
| 150 |
+
),
|
| 151 |
+
)
|
| 152 |
+
parser.add_argument(
|
| 153 |
+
"--skip-lfs",
|
| 154 |
+
action="store_true",
|
| 155 |
+
help="For prune only: skip git lfs prune.",
|
| 156 |
+
)
|
| 157 |
+
parser.add_argument(
|
| 158 |
+
"--include-git-prune",
|
| 159 |
+
action="store_true",
|
| 160 |
+
help=(
|
| 161 |
+
"For prune only: also run repo-wide git prune --expire=now. "
|
| 162 |
+
"This can discard unrelated dangling recovery objects."
|
| 163 |
+
),
|
| 164 |
+
)
|
| 165 |
+
parser.add_argument(
|
| 166 |
+
"--dry-run",
|
| 167 |
+
action="store_true",
|
| 168 |
+
help="For clean-stale only: print stale files without deleting them.",
|
| 169 |
+
)
|
| 170 |
+
return parser
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def main(argv: list[str] | None = None) -> int:
|
| 174 |
+
args = _parser().parse_args(argv)
|
| 175 |
+
repo = _repo_root(args.repo)
|
| 176 |
+
artifacts = _tracked_artifacts(repo, args.artifacts or DEFAULT_ARTIFACTS)
|
| 177 |
+
|
| 178 |
+
if args.command == "status":
|
| 179 |
+
_print_status(repo, artifacts)
|
| 180 |
+
elif args.command == "park":
|
| 181 |
+
_set_skip_worktree(repo, artifacts, enabled=True)
|
| 182 |
+
elif args.command == "unpark":
|
| 183 |
+
_set_skip_worktree(repo, artifacts, enabled=False)
|
| 184 |
+
elif args.command == "prune":
|
| 185 |
+
_prune(
|
| 186 |
+
repo,
|
| 187 |
+
include_lfs=not args.skip_lfs,
|
| 188 |
+
include_git_prune=args.include_git_prune,
|
| 189 |
+
)
|
| 190 |
+
elif args.command == "clean-stale":
|
| 191 |
+
_clean_stale_graph_files(repo, dry_run=args.dry_run)
|
| 192 |
+
return 0
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
if __name__ == "__main__":
|
| 196 |
+
raise SystemExit(main(sys.argv[1:]))
|
scripts/overlay_wiki_entities.py
CHANGED
|
@@ -1,540 +1,540 @@
|
|
| 1 |
-
"""Overlay explicit local wiki entities onto shipped graph tarballs.
|
| 2 |
-
|
| 3 |
-
This is a narrow release-maintenance tool. It starts from the current shipped
|
| 4 |
-
tarball, copies every existing member except graph export files and explicit
|
| 5 |
-
page replacements, then appends selected nodes/pages from a local wiki graph.
|
| 6 |
-
It deliberately does not rebuild Skills.sh semantic topology.
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
from __future__ import annotations
|
| 10 |
-
|
| 11 |
-
import argparse
|
| 12 |
-
import json
|
| 13 |
-
import sys
|
| 14 |
-
import tarfile
|
| 15 |
-
import tempfile
|
| 16 |
-
from collections import Counter
|
| 17 |
-
from dataclasses import dataclass
|
| 18 |
-
from datetime import datetime, timezone
|
| 19 |
-
from pathlib import Path
|
| 20 |
-
from typing import Any
|
| 21 |
-
|
| 22 |
-
REPO_ROOT = Path(__file__).resolve().parent.parent
|
| 23 |
-
if str(REPO_ROOT) not in sys.path:
|
| 24 |
-
sys.path.insert(0, str(REPO_ROOT))
|
| 25 |
-
|
| 26 |
-
from ctx.core.wiki.artifact_promotion import promote_staged_artifact # noqa: E402
|
| 27 |
-
from ctx.utils._fs_utils import atomic_write_text, reject_symlink_path # noqa: E402
|
| 28 |
-
from scripts.build_dashboard_graph_index import build_dashboard_index # noqa: E402
|
| 29 |
-
|
| 30 |
-
GRAPH_EXPORT_NAMES = {
|
| 31 |
-
"graphify-out/graph.json",
|
| 32 |
-
"graphify-out/graph-delta.json",
|
| 33 |
-
"graphify-out/communities.json",
|
| 34 |
-
"graphify-out/graph-report.md",
|
| 35 |
-
"graphify-out/graph-export-manifest.json",
|
| 36 |
-
}
|
| 37 |
-
OVERLAY_GZIP_COMPRESSLEVEL = 3
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
@dataclass(frozen=True)
|
| 41 |
-
class OverlayStats:
|
| 42 |
-
node_count: int
|
| 43 |
-
edge_count: int
|
| 44 |
-
added_nodes: int
|
| 45 |
-
added_edges: int
|
| 46 |
-
export_id: str
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
def overlay_entities(
|
| 50 |
-
*,
|
| 51 |
-
source_wiki: Path,
|
| 52 |
-
tarball: Path,
|
| 53 |
-
entity_ids: list[str],
|
| 54 |
-
skills_root: Path | None = None,
|
| 55 |
-
root_communities: Path | None = None,
|
| 56 |
-
runtime: bool = False,
|
| 57 |
-
now: datetime | None = None,
|
| 58 |
-
) -> OverlayStats:
|
| 59 |
-
if not entity_ids:
|
| 60 |
-
raise ValueError("at least one entity id is required")
|
| 61 |
-
source_graph = _read_json(source_wiki / "graphify-out" / "graph.json")
|
| 62 |
-
source_nodes = _nodes_by_id(source_graph)
|
| 63 |
-
selected = list(dict.fromkeys(entity_ids))
|
| 64 |
-
missing = [node_id for node_id in selected if node_id not in source_nodes]
|
| 65 |
-
if missing:
|
| 66 |
-
raise ValueError(f"source graph is missing selected nodes: {missing}")
|
| 67 |
-
|
| 68 |
-
graph, communities = _read_tar_graph_artifacts(tarball)
|
| 69 |
-
graph, added_nodes, added_edges = _merge_graph(graph, source_graph, selected)
|
| 70 |
-
timestamp = _timestamp(now)
|
| 71 |
-
export_id = f"ctx-graph-overlay-{timestamp}-{len(graph['nodes'])}-{len(graph['edges'])}"
|
| 72 |
-
graph.setdefault("graph", {})["export_id"] = export_id
|
| 73 |
-
graph["graph"]["generated"] = timestamp
|
| 74 |
-
graph["graph"]["overlay_entities"] = selected
|
| 75 |
-
communities = _merge_communities(
|
| 76 |
-
communities,
|
| 77 |
-
graph=graph,
|
| 78 |
-
selected=selected,
|
| 79 |
-
export_id=export_id,
|
| 80 |
-
generated=timestamp,
|
| 81 |
-
)
|
| 82 |
-
if root_communities is not None:
|
| 83 |
-
atomic_write_text(root_communities, json.dumps(communities, indent=2) + "\n")
|
| 84 |
-
|
| 85 |
-
replacements = _collect_replacements(
|
| 86 |
-
source_wiki=source_wiki,
|
| 87 |
-
entity_ids=selected,
|
| 88 |
-
skills_root=skills_root,
|
| 89 |
-
runtime=runtime,
|
| 90 |
-
)
|
| 91 |
-
replacements.update({
|
| 92 |
-
"graphify-out/graph.json": _json_bytes(graph, compact=True),
|
| 93 |
-
"graphify-out/dashboard-neighborhoods.sqlite3": _dashboard_index_bytes(graph),
|
| 94 |
-
"graphify-out/graph-delta.json": _json_bytes(
|
| 95 |
-
_render_delta(graph, selected, export_id=export_id, generated=timestamp),
|
| 96 |
-
compact=False,
|
| 97 |
-
),
|
| 98 |
-
"graphify-out/communities.json": _json_bytes(communities, compact=False),
|
| 99 |
-
"graphify-out/graph-report.md": _render_report(
|
| 100 |
-
graph,
|
| 101 |
-
communities,
|
| 102 |
-
selected=selected,
|
| 103 |
-
export_id=export_id,
|
| 104 |
-
generated=timestamp,
|
| 105 |
-
).encode("utf-8"),
|
| 106 |
-
"graphify-out/graph-export-manifest.json": _json_bytes(
|
| 107 |
-
_render_manifest(graph, communities, export_id=export_id, generated=timestamp),
|
| 108 |
-
compact=False,
|
| 109 |
-
),
|
| 110 |
-
})
|
| 111 |
-
_rewrite_tarball(tarball, replacements)
|
| 112 |
-
return OverlayStats(
|
| 113 |
-
node_count=len(graph["nodes"]),
|
| 114 |
-
edge_count=len(graph["edges"]),
|
| 115 |
-
added_nodes=added_nodes,
|
| 116 |
-
added_edges=added_edges,
|
| 117 |
-
export_id=export_id,
|
| 118 |
-
)
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
def _merge_graph(
|
| 122 |
-
graph: dict[str, Any],
|
| 123 |
-
source_graph: dict[str, Any],
|
| 124 |
-
selected: list[str],
|
| 125 |
-
) -> tuple[dict[str, Any], int, int]:
|
| 126 |
-
nodes = _list_field(graph, "nodes")
|
| 127 |
-
edges = _list_field(graph, "edges")
|
| 128 |
-
source_nodes = _nodes_by_id(source_graph)
|
| 129 |
-
dest_ids = {str(node.get("id")) for node in nodes if isinstance(node, dict)}
|
| 130 |
-
by_id = {
|
| 131 |
-
str(node.get("id")): index
|
| 132 |
-
for index, node in enumerate(nodes)
|
| 133 |
-
if isinstance(node, dict) and node.get("id")
|
| 134 |
-
}
|
| 135 |
-
added_nodes = 0
|
| 136 |
-
for node_id in selected:
|
| 137 |
-
node = dict(source_nodes[node_id])
|
| 138 |
-
if node_id in by_id:
|
| 139 |
-
nodes[by_id[node_id]] = node
|
| 140 |
-
else:
|
| 141 |
-
nodes.append(node)
|
| 142 |
-
dest_ids.add(node_id)
|
| 143 |
-
added_nodes += 1
|
| 144 |
-
|
| 145 |
-
edge_keys = {_edge_key(edge) for edge in edges if isinstance(edge, dict)}
|
| 146 |
-
added_edges = 0
|
| 147 |
-
for edge in _list_field(source_graph, "edges"):
|
| 148 |
-
if not isinstance(edge, dict):
|
| 149 |
-
continue
|
| 150 |
-
source = str(edge.get("source") or "")
|
| 151 |
-
target = str(edge.get("target") or "")
|
| 152 |
-
if source not in selected and target not in selected:
|
| 153 |
-
continue
|
| 154 |
-
if source not in dest_ids or target not in dest_ids:
|
| 155 |
-
continue
|
| 156 |
-
key = _edge_key(edge)
|
| 157 |
-
if key in edge_keys:
|
| 158 |
-
continue
|
| 159 |
-
edges.append(dict(edge))
|
| 160 |
-
edge_keys.add(key)
|
| 161 |
-
added_edges += 1
|
| 162 |
-
graph["nodes"] = nodes
|
| 163 |
-
graph["edges"] = edges
|
| 164 |
-
return graph, added_nodes, added_edges
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
def _merge_communities(
|
| 168 |
-
communities: dict[str, Any],
|
| 169 |
-
*,
|
| 170 |
-
graph: dict[str, Any],
|
| 171 |
-
selected: list[str],
|
| 172 |
-
export_id: str,
|
| 173 |
-
generated: str,
|
| 174 |
-
) -> dict[str, Any]:
|
| 175 |
-
raw = communities.get("communities")
|
| 176 |
-
if not isinstance(raw, dict) or not raw:
|
| 177 |
-
raw = {"0": {"label": "Overlay", "members": []}}
|
| 178 |
-
node_to_community: dict[str, str] = {}
|
| 179 |
-
for cid, payload in raw.items():
|
| 180 |
-
members = payload.get("members") if isinstance(payload, dict) else []
|
| 181 |
-
if not isinstance(members, list):
|
| 182 |
-
continue
|
| 183 |
-
for member in members:
|
| 184 |
-
node_to_community[str(member)] = str(cid)
|
| 185 |
-
edge_pairs = [
|
| 186 |
-
(str(edge.get("source") or ""), str(edge.get("target") or ""))
|
| 187 |
-
for edge in _list_field(graph, "edges")
|
| 188 |
-
if isinstance(edge, dict)
|
| 189 |
-
]
|
| 190 |
-
for node_id in selected:
|
| 191 |
-
if node_id in node_to_community:
|
| 192 |
-
continue
|
| 193 |
-
counts: Counter[str] = Counter()
|
| 194 |
-
for source, target in edge_pairs:
|
| 195 |
-
other = target if source == node_id else source if target == node_id else ""
|
| 196 |
-
if other and other in node_to_community:
|
| 197 |
-
counts[node_to_community[other]] += 1
|
| 198 |
-
cid = counts.most_common(1)[0][0] if counts else sorted(raw)[0]
|
| 199 |
-
payload = raw.setdefault(cid, {"label": "Overlay", "members": []})
|
| 200 |
-
members = payload.setdefault("members", [])
|
| 201 |
-
if isinstance(members, list):
|
| 202 |
-
members.append(node_id)
|
| 203 |
-
node_to_community[node_id] = cid
|
| 204 |
-
communities["export_id"] = export_id
|
| 205 |
-
communities["generated"] = generated
|
| 206 |
-
communities["total_communities"] = len(raw)
|
| 207 |
-
communities["communities"] = raw
|
| 208 |
-
return communities
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
def _collect_replacements(
|
| 212 |
-
*,
|
| 213 |
-
source_wiki: Path,
|
| 214 |
-
entity_ids: list[str],
|
| 215 |
-
skills_root: Path | None,
|
| 216 |
-
runtime: bool,
|
| 217 |
-
) -> dict[str, bytes]:
|
| 218 |
-
replacements: dict[str, bytes] = {}
|
| 219 |
-
for node_id in entity_ids:
|
| 220 |
-
entity_type, slug = _split_node_id(node_id)
|
| 221 |
-
page = _entity_page(source_wiki, entity_type, slug)
|
| 222 |
-
if page is not None and (not runtime or entity_type == "harness"):
|
| 223 |
-
replacements[page.relative_to(source_wiki).as_posix()] = _read_safe_bytes(page)
|
| 224 |
-
if not runtime and entity_type == "skill":
|
| 225 |
-
replacements.update(_skill_replacements(source_wiki, slug, skills_root=skills_root))
|
| 226 |
-
return replacements
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
def _dashboard_index_bytes(graph: dict[str, Any]) -> bytes:
|
| 230 |
-
with tempfile.TemporaryDirectory(prefix="ctx-overlay-index-") as tmp:
|
| 231 |
-
tmp_path = Path(tmp)
|
| 232 |
-
graph_path = tmp_path / "graph.json"
|
| 233 |
-
index_path = tmp_path / "dashboard-neighborhoods.sqlite3"
|
| 234 |
-
graph_path.write_bytes(_json_bytes(graph, compact=True))
|
| 235 |
-
build_dashboard_index(graph_path, index_path)
|
| 236 |
-
return index_path.read_bytes()
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
def _entity_page(source_wiki: Path, entity_type: str, slug: str) -> Path | None:
|
| 240 |
-
candidates = {
|
| 241 |
-
"skill": [source_wiki / "entities" / "skills" / f"{slug}.md"],
|
| 242 |
-
"agent": [source_wiki / "entities" / "agents" / f"{slug}.md"],
|
| 243 |
-
"harness": [source_wiki / "entities" / "harnesses" / f"{slug}.md"],
|
| 244 |
-
"mcp-server": [
|
| 245 |
-
source_wiki / "entities" / "mcp-servers" / slug[:1].lower() / f"{slug}.md",
|
| 246 |
-
],
|
| 247 |
-
}.get(entity_type, [])
|
| 248 |
-
for candidate in candidates:
|
| 249 |
-
if _is_safe_file(candidate):
|
| 250 |
-
return candidate
|
| 251 |
-
if entity_type == "mcp-server":
|
| 252 |
-
matches = list((source_wiki / "entities" / "mcp-servers").rglob(f"{slug}.md"))
|
| 253 |
-
for match in matches:
|
| 254 |
-
if _is_safe_file(match):
|
| 255 |
-
return match
|
| 256 |
-
return None
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
def _skill_replacements(source_wiki: Path, slug: str, *, skills_root: Path | None) -> dict[str, bytes]:
|
| 260 |
-
root = skills_root or Path.home() / ".claude" / "skills"
|
| 261 |
-
candidates = [
|
| 262 |
-
source_wiki / "converted" / slug / "SKILL.md",
|
| 263 |
-
root / slug / "SKILL.md",
|
| 264 |
-
]
|
| 265 |
-
for candidate in candidates:
|
| 266 |
-
if _is_safe_file(candidate):
|
| 267 |
-
skill_dir = candidate.parent
|
| 268 |
-
return {
|
| 269 |
-
f"converted/{slug}/{path.relative_to(skill_dir).as_posix()}": _read_safe_bytes(path)
|
| 270 |
-
for path in sorted(skill_dir.rglob("*"))
|
| 271 |
-
if _is_safe_file(path) and not path.name.endswith((".original", ".lock"))
|
| 272 |
-
}
|
| 273 |
-
return {}
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
def _is_safe_file(path: Path) -> bool:
|
| 277 |
-
reject_symlink_path(path)
|
| 278 |
-
return path.is_file()
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
def _read_safe_bytes(path: Path) -> bytes:
|
| 282 |
-
reject_symlink_path(path)
|
| 283 |
-
return path.read_bytes()
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
def _rewrite_tarball(tarball: Path, replacements: dict[str, bytes]) -> None:
|
| 287 |
-
reject_symlink_path(tarball)
|
| 288 |
-
staged = tarball.with_name(f"{tarball.name}.staged")
|
| 289 |
-
reject_symlink_path(staged)
|
| 290 |
-
skip_names = set(replacements)
|
| 291 |
-
with tarfile.open(tarball, "r:gz") as src, tarfile.open(
|
| 292 |
-
staged,
|
| 293 |
-
"w:gz",
|
| 294 |
-
compresslevel=OVERLAY_GZIP_COMPRESSLEVEL,
|
| 295 |
-
) as dst:
|
| 296 |
-
for member in src:
|
| 297 |
-
safe_name = _safe_tar_name(member.name)
|
| 298 |
-
if safe_name is None:
|
| 299 |
-
continue
|
| 300 |
-
if safe_name in GRAPH_EXPORT_NAMES or safe_name in skip_names:
|
| 301 |
-
continue
|
| 302 |
-
if safe_name.endswith(".original") or safe_name.endswith(".lock"):
|
| 303 |
-
continue
|
| 304 |
-
if member.isfile():
|
| 305 |
-
f = src.extractfile(member)
|
| 306 |
-
if f is not None:
|
| 307 |
-
dst.addfile(member, f)
|
| 308 |
-
elif member.isdir():
|
| 309 |
-
dst.addfile(member)
|
| 310 |
-
for name, payload in sorted(replacements.items()):
|
| 311 |
-
_add_bytes(dst, name=f"./{name}", payload=payload)
|
| 312 |
-
promote_staged_artifact(staged, tarball, validate=_validate_tarball)
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
def _validate_tarball(candidate: Path) -> None:
|
| 316 |
-
seen: set[str] = set()
|
| 317 |
-
with tarfile.open(candidate, "r:gz") as tf:
|
| 318 |
-
for member in tf:
|
| 319 |
-
safe_name = _safe_tar_name(member.name)
|
| 320 |
-
if safe_name is None:
|
| 321 |
-
raise ValueError(f"unsafe tar member: {member.name}")
|
| 322 |
-
if safe_name.endswith(".original") or safe_name.endswith(".lock"):
|
| 323 |
-
raise ValueError(f"transient member leaked: {safe_name}")
|
| 324 |
-
seen.add(safe_name)
|
| 325 |
-
missing = sorted(GRAPH_EXPORT_NAMES - seen)
|
| 326 |
-
if missing:
|
| 327 |
-
raise ValueError(f"candidate tarball missing graph exports: {missing}")
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
def _read_tar_graph_artifacts(tarball: Path) -> tuple[dict[str, Any], dict[str, Any]]:
|
| 331 |
-
graph: dict[str, Any] | None = None
|
| 332 |
-
communities: dict[str, Any] | None = None
|
| 333 |
-
with tarfile.open(tarball, "r:gz") as tf:
|
| 334 |
-
for member in tf:
|
| 335 |
-
safe_name = _safe_tar_name(member.name)
|
| 336 |
-
if safe_name not in {"graphify-out/graph.json", "graphify-out/communities.json"}:
|
| 337 |
-
continue
|
| 338 |
-
f = tf.extractfile(member)
|
| 339 |
-
if f is None:
|
| 340 |
-
continue
|
| 341 |
-
data = json.loads(f.read().decode("utf-8"))
|
| 342 |
-
if safe_name.endswith("graph.json"):
|
| 343 |
-
graph = data
|
| 344 |
-
else:
|
| 345 |
-
communities = data
|
| 346 |
-
if graph is None or communities is None:
|
| 347 |
-
raise ValueError("tarball is missing graph.json or communities.json")
|
| 348 |
-
return graph, communities
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
def _render_delta(
|
| 352 |
-
graph: dict[str, Any],
|
| 353 |
-
selected: list[str],
|
| 354 |
-
*,
|
| 355 |
-
export_id: str,
|
| 356 |
-
generated: str,
|
| 357 |
-
) -> dict[str, Any]:
|
| 358 |
-
selected_set = set(selected)
|
| 359 |
-
nodes = [
|
| 360 |
-
node for node in _list_field(graph, "nodes")
|
| 361 |
-
if isinstance(node, dict) and node.get("id") in selected_set
|
| 362 |
-
]
|
| 363 |
-
edges = [
|
| 364 |
-
edge for edge in _list_field(graph, "edges")
|
| 365 |
-
if isinstance(edge, dict)
|
| 366 |
-
and (edge.get("source") in selected_set or edge.get("target") in selected_set)
|
| 367 |
-
]
|
| 368 |
-
return {
|
| 369 |
-
"version": 1,
|
| 370 |
-
"full_rebuild": False,
|
| 371 |
-
"export_id": export_id,
|
| 372 |
-
"generated": generated,
|
| 373 |
-
"node_count": len(graph["nodes"]),
|
| 374 |
-
"edge_count": len(graph["edges"]),
|
| 375 |
-
"delta_node_count": len(nodes),
|
| 376 |
-
"delta_edge_count": len(edges),
|
| 377 |
-
"nodes": nodes,
|
| 378 |
-
"edges": edges,
|
| 379 |
-
}
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
def _render_manifest(
|
| 383 |
-
graph: dict[str, Any],
|
| 384 |
-
communities: dict[str, Any],
|
| 385 |
-
*,
|
| 386 |
-
export_id: str,
|
| 387 |
-
generated: str,
|
| 388 |
-
) -> dict[str, Any]:
|
| 389 |
-
return {
|
| 390 |
-
"version": 1,
|
| 391 |
-
"export_id": export_id,
|
| 392 |
-
"generated": generated,
|
| 393 |
-
"artifacts": {
|
| 394 |
-
"graph": "graph.json",
|
| 395 |
-
"delta": "graph-delta.json",
|
| 396 |
-
"communities": "communities.json",
|
| 397 |
-
"report": "graph-report.md",
|
| 398 |
-
},
|
| 399 |
-
"counts": {
|
| 400 |
-
"nodes": len(graph["nodes"]),
|
| 401 |
-
"edges": len(graph["edges"]),
|
| 402 |
-
"communities": communities.get("total_communities", 0),
|
| 403 |
-
},
|
| 404 |
-
}
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
def _render_report(
|
| 408 |
-
graph: dict[str, Any],
|
| 409 |
-
communities: dict[str, Any],
|
| 410 |
-
*,
|
| 411 |
-
selected: list[str],
|
| 412 |
-
export_id: str,
|
| 413 |
-
generated: str,
|
| 414 |
-
) -> str:
|
| 415 |
-
degree: Counter[str] = Counter()
|
| 416 |
-
for edge in _list_field(graph, "edges"):
|
| 417 |
-
if not isinstance(edge, dict):
|
| 418 |
-
continue
|
| 419 |
-
degree[str(edge.get("source") or "")] += 1
|
| 420 |
-
degree[str(edge.get("target") or "")] += 1
|
| 421 |
-
node_by_id = _nodes_by_id(graph)
|
| 422 |
-
lines = [
|
| 423 |
-
"# Graph Report",
|
| 424 |
-
"",
|
| 425 |
-
f"> Generated: {generated}",
|
| 426 |
-
f"> Export ID: {export_id}",
|
| 427 |
-
(
|
| 428 |
-
f"> Nodes: {len(graph['nodes'])} | Edges: {len(graph['edges'])} | "
|
| 429 |
-
f"Communities: {communities.get('total_communities', 0)}"
|
| 430 |
-
),
|
| 431 |
-
"",
|
| 432 |
-
"## Overlay Entities",
|
| 433 |
-
"",
|
| 434 |
-
]
|
| 435 |
-
for node_id in selected:
|
| 436 |
-
node = node_by_id.get(node_id, {})
|
| 437 |
-
lines.append(f"- **{node.get('label', node_id)}** ({node_id})")
|
| 438 |
-
lines.extend(["", "## Most Connected Nodes", ""])
|
| 439 |
-
for node_id, count in degree.most_common(20):
|
| 440 |
-
if not node_id:
|
| 441 |
-
continue
|
| 442 |
-
node = node_by_id.get(node_id, {})
|
| 443 |
-
lines.append(f"- **{node.get('label', node_id)}** ({count} connections)")
|
| 444 |
-
return "\n".join(lines) + "\n"
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
def _read_json(path: Path) -> dict[str, Any]:
|
| 448 |
-
data = json.loads(path.read_text(encoding="utf-8"))
|
| 449 |
-
if not isinstance(data, dict):
|
| 450 |
-
raise ValueError(f"{path} must contain a JSON object")
|
| 451 |
-
return data
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
def _nodes_by_id(graph: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
| 455 |
-
return {
|
| 456 |
-
str(node.get("id")): node
|
| 457 |
-
for node in _list_field(graph, "nodes")
|
| 458 |
-
if isinstance(node, dict) and node.get("id")
|
| 459 |
-
}
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
def _list_field(data: dict[str, Any], key: str) -> list[Any]:
|
| 463 |
-
value = data.get(key)
|
| 464 |
-
if not isinstance(value, list):
|
| 465 |
-
raise ValueError(f"graph field {key!r} must be a list")
|
| 466 |
-
return value
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
def _edge_key(edge: dict[str, Any]) -> tuple[str, str]:
|
| 470 |
-
source = str(edge.get("source") or "")
|
| 471 |
-
target = str(edge.get("target") or "")
|
| 472 |
-
return (source, target) if source <= target else (target, source)
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
def _split_node_id(node_id: str) -> tuple[str, str]:
|
| 476 |
-
if ":" not in node_id:
|
| 477 |
-
raise ValueError(f"invalid node id: {node_id}")
|
| 478 |
-
entity_type, slug = node_id.split(":", 1)
|
| 479 |
-
return entity_type, slug
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
def _safe_tar_name(name: str) -> str | None:
|
| 483 |
-
normalized = name.replace("\\", "/")
|
| 484 |
-
while normalized.startswith("./"):
|
| 485 |
-
normalized = normalized[2:]
|
| 486 |
-
if not normalized or normalized.startswith("/") or normalized.startswith("../"):
|
| 487 |
-
return None
|
| 488 |
-
if "/../" in normalized or normalized == "..":
|
| 489 |
-
return None
|
| 490 |
-
return normalized
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
def _add_bytes(
|
| 494 |
-
tf: tarfile.TarFile,
|
| 495 |
-
*,
|
| 496 |
-
name: str,
|
| 497 |
-
payload: bytes,
|
| 498 |
-
mode: int = 0o644,
|
| 499 |
-
) -> None:
|
| 500 |
-
import io
|
| 501 |
-
|
| 502 |
-
info = tarfile.TarInfo(name)
|
| 503 |
-
info.size = len(payload)
|
| 504 |
-
info.mode = mode
|
| 505 |
-
info.mtime = 0
|
| 506 |
-
tf.addfile(info, io.BytesIO(payload))
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
def _json_bytes(data: dict[str, Any], *, compact: bool) -> bytes:
|
| 510 |
-
if compact:
|
| 511 |
-
return json.dumps(data, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
| 512 |
-
return (json.dumps(data, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
def _timestamp(now: datetime | None = None) -> str:
|
| 516 |
-
value = now or datetime.now(timezone.utc)
|
| 517 |
-
return value.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
def main() -> None:
|
| 521 |
-
parser = argparse.ArgumentParser(description=__doc__)
|
| 522 |
-
parser.add_argument("--source-wiki", type=Path, default=Path.home() / ".claude" / "skill-wiki")
|
| 523 |
-
parser.add_argument("--tarball", type=Path, required=True)
|
| 524 |
-
parser.add_argument("--entity", action="append", required=True, help="Node id, e.g. skill:foo")
|
| 525 |
-
parser.add_argument("--root-communities", type=Path)
|
| 526 |
-
parser.add_argument("--runtime", action="store_true")
|
| 527 |
-
args = parser.parse_args()
|
| 528 |
-
stats = overlay_entities(
|
| 529 |
-
source_wiki=args.source_wiki,
|
| 530 |
-
tarball=args.tarball,
|
| 531 |
-
entity_ids=args.entity,
|
| 532 |
-
skills_root=Path.home() / ".claude" / "skills",
|
| 533 |
-
root_communities=args.root_communities,
|
| 534 |
-
runtime=args.runtime,
|
| 535 |
-
)
|
| 536 |
-
print(json.dumps(stats.__dict__, indent=2))
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
if __name__ == "__main__":
|
| 540 |
-
main()
|
|
|
|
| 1 |
+
"""Overlay explicit local wiki entities onto shipped graph tarballs.
|
| 2 |
+
|
| 3 |
+
This is a narrow release-maintenance tool. It starts from the current shipped
|
| 4 |
+
tarball, copies every existing member except graph export files and explicit
|
| 5 |
+
page replacements, then appends selected nodes/pages from a local wiki graph.
|
| 6 |
+
It deliberately does not rebuild Skills.sh semantic topology.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import json
|
| 13 |
+
import sys
|
| 14 |
+
import tarfile
|
| 15 |
+
import tempfile
|
| 16 |
+
from collections import Counter
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from datetime import datetime, timezone
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Any
|
| 21 |
+
|
| 22 |
+
REPO_ROOT = Path(__file__).resolve().parent.parent
|
| 23 |
+
if str(REPO_ROOT) not in sys.path:
|
| 24 |
+
sys.path.insert(0, str(REPO_ROOT))
|
| 25 |
+
|
| 26 |
+
from ctx.core.wiki.artifact_promotion import promote_staged_artifact # noqa: E402
|
| 27 |
+
from ctx.utils._fs_utils import atomic_write_text, reject_symlink_path # noqa: E402
|
| 28 |
+
from scripts.build_dashboard_graph_index import build_dashboard_index # noqa: E402
|
| 29 |
+
|
| 30 |
+
GRAPH_EXPORT_NAMES = {
|
| 31 |
+
"graphify-out/graph.json",
|
| 32 |
+
"graphify-out/graph-delta.json",
|
| 33 |
+
"graphify-out/communities.json",
|
| 34 |
+
"graphify-out/graph-report.md",
|
| 35 |
+
"graphify-out/graph-export-manifest.json",
|
| 36 |
+
}
|
| 37 |
+
OVERLAY_GZIP_COMPRESSLEVEL = 3
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@dataclass(frozen=True)
|
| 41 |
+
class OverlayStats:
|
| 42 |
+
node_count: int
|
| 43 |
+
edge_count: int
|
| 44 |
+
added_nodes: int
|
| 45 |
+
added_edges: int
|
| 46 |
+
export_id: str
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def overlay_entities(
|
| 50 |
+
*,
|
| 51 |
+
source_wiki: Path,
|
| 52 |
+
tarball: Path,
|
| 53 |
+
entity_ids: list[str],
|
| 54 |
+
skills_root: Path | None = None,
|
| 55 |
+
root_communities: Path | None = None,
|
| 56 |
+
runtime: bool = False,
|
| 57 |
+
now: datetime | None = None,
|
| 58 |
+
) -> OverlayStats:
|
| 59 |
+
if not entity_ids:
|
| 60 |
+
raise ValueError("at least one entity id is required")
|
| 61 |
+
source_graph = _read_json(source_wiki / "graphify-out" / "graph.json")
|
| 62 |
+
source_nodes = _nodes_by_id(source_graph)
|
| 63 |
+
selected = list(dict.fromkeys(entity_ids))
|
| 64 |
+
missing = [node_id for node_id in selected if node_id not in source_nodes]
|
| 65 |
+
if missing:
|
| 66 |
+
raise ValueError(f"source graph is missing selected nodes: {missing}")
|
| 67 |
+
|
| 68 |
+
graph, communities = _read_tar_graph_artifacts(tarball)
|
| 69 |
+
graph, added_nodes, added_edges = _merge_graph(graph, source_graph, selected)
|
| 70 |
+
timestamp = _timestamp(now)
|
| 71 |
+
export_id = f"ctx-graph-overlay-{timestamp}-{len(graph['nodes'])}-{len(graph['edges'])}"
|
| 72 |
+
graph.setdefault("graph", {})["export_id"] = export_id
|
| 73 |
+
graph["graph"]["generated"] = timestamp
|
| 74 |
+
graph["graph"]["overlay_entities"] = selected
|
| 75 |
+
communities = _merge_communities(
|
| 76 |
+
communities,
|
| 77 |
+
graph=graph,
|
| 78 |
+
selected=selected,
|
| 79 |
+
export_id=export_id,
|
| 80 |
+
generated=timestamp,
|
| 81 |
+
)
|
| 82 |
+
if root_communities is not None:
|
| 83 |
+
atomic_write_text(root_communities, json.dumps(communities, indent=2) + "\n")
|
| 84 |
+
|
| 85 |
+
replacements = _collect_replacements(
|
| 86 |
+
source_wiki=source_wiki,
|
| 87 |
+
entity_ids=selected,
|
| 88 |
+
skills_root=skills_root,
|
| 89 |
+
runtime=runtime,
|
| 90 |
+
)
|
| 91 |
+
replacements.update({
|
| 92 |
+
"graphify-out/graph.json": _json_bytes(graph, compact=True),
|
| 93 |
+
"graphify-out/dashboard-neighborhoods.sqlite3": _dashboard_index_bytes(graph),
|
| 94 |
+
"graphify-out/graph-delta.json": _json_bytes(
|
| 95 |
+
_render_delta(graph, selected, export_id=export_id, generated=timestamp),
|
| 96 |
+
compact=False,
|
| 97 |
+
),
|
| 98 |
+
"graphify-out/communities.json": _json_bytes(communities, compact=False),
|
| 99 |
+
"graphify-out/graph-report.md": _render_report(
|
| 100 |
+
graph,
|
| 101 |
+
communities,
|
| 102 |
+
selected=selected,
|
| 103 |
+
export_id=export_id,
|
| 104 |
+
generated=timestamp,
|
| 105 |
+
).encode("utf-8"),
|
| 106 |
+
"graphify-out/graph-export-manifest.json": _json_bytes(
|
| 107 |
+
_render_manifest(graph, communities, export_id=export_id, generated=timestamp),
|
| 108 |
+
compact=False,
|
| 109 |
+
),
|
| 110 |
+
})
|
| 111 |
+
_rewrite_tarball(tarball, replacements)
|
| 112 |
+
return OverlayStats(
|
| 113 |
+
node_count=len(graph["nodes"]),
|
| 114 |
+
edge_count=len(graph["edges"]),
|
| 115 |
+
added_nodes=added_nodes,
|
| 116 |
+
added_edges=added_edges,
|
| 117 |
+
export_id=export_id,
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _merge_graph(
|
| 122 |
+
graph: dict[str, Any],
|
| 123 |
+
source_graph: dict[str, Any],
|
| 124 |
+
selected: list[str],
|
| 125 |
+
) -> tuple[dict[str, Any], int, int]:
|
| 126 |
+
nodes = _list_field(graph, "nodes")
|
| 127 |
+
edges = _list_field(graph, "edges")
|
| 128 |
+
source_nodes = _nodes_by_id(source_graph)
|
| 129 |
+
dest_ids = {str(node.get("id")) for node in nodes if isinstance(node, dict)}
|
| 130 |
+
by_id = {
|
| 131 |
+
str(node.get("id")): index
|
| 132 |
+
for index, node in enumerate(nodes)
|
| 133 |
+
if isinstance(node, dict) and node.get("id")
|
| 134 |
+
}
|
| 135 |
+
added_nodes = 0
|
| 136 |
+
for node_id in selected:
|
| 137 |
+
node = dict(source_nodes[node_id])
|
| 138 |
+
if node_id in by_id:
|
| 139 |
+
nodes[by_id[node_id]] = node
|
| 140 |
+
else:
|
| 141 |
+
nodes.append(node)
|
| 142 |
+
dest_ids.add(node_id)
|
| 143 |
+
added_nodes += 1
|
| 144 |
+
|
| 145 |
+
edge_keys = {_edge_key(edge) for edge in edges if isinstance(edge, dict)}
|
| 146 |
+
added_edges = 0
|
| 147 |
+
for edge in _list_field(source_graph, "edges"):
|
| 148 |
+
if not isinstance(edge, dict):
|
| 149 |
+
continue
|
| 150 |
+
source = str(edge.get("source") or "")
|
| 151 |
+
target = str(edge.get("target") or "")
|
| 152 |
+
if source not in selected and target not in selected:
|
| 153 |
+
continue
|
| 154 |
+
if source not in dest_ids or target not in dest_ids:
|
| 155 |
+
continue
|
| 156 |
+
key = _edge_key(edge)
|
| 157 |
+
if key in edge_keys:
|
| 158 |
+
continue
|
| 159 |
+
edges.append(dict(edge))
|
| 160 |
+
edge_keys.add(key)
|
| 161 |
+
added_edges += 1
|
| 162 |
+
graph["nodes"] = nodes
|
| 163 |
+
graph["edges"] = edges
|
| 164 |
+
return graph, added_nodes, added_edges
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def _merge_communities(
|
| 168 |
+
communities: dict[str, Any],
|
| 169 |
+
*,
|
| 170 |
+
graph: dict[str, Any],
|
| 171 |
+
selected: list[str],
|
| 172 |
+
export_id: str,
|
| 173 |
+
generated: str,
|
| 174 |
+
) -> dict[str, Any]:
|
| 175 |
+
raw = communities.get("communities")
|
| 176 |
+
if not isinstance(raw, dict) or not raw:
|
| 177 |
+
raw = {"0": {"label": "Overlay", "members": []}}
|
| 178 |
+
node_to_community: dict[str, str] = {}
|
| 179 |
+
for cid, payload in raw.items():
|
| 180 |
+
members = payload.get("members") if isinstance(payload, dict) else []
|
| 181 |
+
if not isinstance(members, list):
|
| 182 |
+
continue
|
| 183 |
+
for member in members:
|
| 184 |
+
node_to_community[str(member)] = str(cid)
|
| 185 |
+
edge_pairs = [
|
| 186 |
+
(str(edge.get("source") or ""), str(edge.get("target") or ""))
|
| 187 |
+
for edge in _list_field(graph, "edges")
|
| 188 |
+
if isinstance(edge, dict)
|
| 189 |
+
]
|
| 190 |
+
for node_id in selected:
|
| 191 |
+
if node_id in node_to_community:
|
| 192 |
+
continue
|
| 193 |
+
counts: Counter[str] = Counter()
|
| 194 |
+
for source, target in edge_pairs:
|
| 195 |
+
other = target if source == node_id else source if target == node_id else ""
|
| 196 |
+
if other and other in node_to_community:
|
| 197 |
+
counts[node_to_community[other]] += 1
|
| 198 |
+
cid = counts.most_common(1)[0][0] if counts else sorted(raw)[0]
|
| 199 |
+
payload = raw.setdefault(cid, {"label": "Overlay", "members": []})
|
| 200 |
+
members = payload.setdefault("members", [])
|
| 201 |
+
if isinstance(members, list):
|
| 202 |
+
members.append(node_id)
|
| 203 |
+
node_to_community[node_id] = cid
|
| 204 |
+
communities["export_id"] = export_id
|
| 205 |
+
communities["generated"] = generated
|
| 206 |
+
communities["total_communities"] = len(raw)
|
| 207 |
+
communities["communities"] = raw
|
| 208 |
+
return communities
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def _collect_replacements(
|
| 212 |
+
*,
|
| 213 |
+
source_wiki: Path,
|
| 214 |
+
entity_ids: list[str],
|
| 215 |
+
skills_root: Path | None,
|
| 216 |
+
runtime: bool,
|
| 217 |
+
) -> dict[str, bytes]:
|
| 218 |
+
replacements: dict[str, bytes] = {}
|
| 219 |
+
for node_id in entity_ids:
|
| 220 |
+
entity_type, slug = _split_node_id(node_id)
|
| 221 |
+
page = _entity_page(source_wiki, entity_type, slug)
|
| 222 |
+
if page is not None and (not runtime or entity_type == "harness"):
|
| 223 |
+
replacements[page.relative_to(source_wiki).as_posix()] = _read_safe_bytes(page)
|
| 224 |
+
if not runtime and entity_type == "skill":
|
| 225 |
+
replacements.update(_skill_replacements(source_wiki, slug, skills_root=skills_root))
|
| 226 |
+
return replacements
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def _dashboard_index_bytes(graph: dict[str, Any]) -> bytes:
|
| 230 |
+
with tempfile.TemporaryDirectory(prefix="ctx-overlay-index-") as tmp:
|
| 231 |
+
tmp_path = Path(tmp)
|
| 232 |
+
graph_path = tmp_path / "graph.json"
|
| 233 |
+
index_path = tmp_path / "dashboard-neighborhoods.sqlite3"
|
| 234 |
+
graph_path.write_bytes(_json_bytes(graph, compact=True))
|
| 235 |
+
build_dashboard_index(graph_path, index_path)
|
| 236 |
+
return index_path.read_bytes()
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _entity_page(source_wiki: Path, entity_type: str, slug: str) -> Path | None:
|
| 240 |
+
candidates = {
|
| 241 |
+
"skill": [source_wiki / "entities" / "skills" / f"{slug}.md"],
|
| 242 |
+
"agent": [source_wiki / "entities" / "agents" / f"{slug}.md"],
|
| 243 |
+
"harness": [source_wiki / "entities" / "harnesses" / f"{slug}.md"],
|
| 244 |
+
"mcp-server": [
|
| 245 |
+
source_wiki / "entities" / "mcp-servers" / slug[:1].lower() / f"{slug}.md",
|
| 246 |
+
],
|
| 247 |
+
}.get(entity_type, [])
|
| 248 |
+
for candidate in candidates:
|
| 249 |
+
if _is_safe_file(candidate):
|
| 250 |
+
return candidate
|
| 251 |
+
if entity_type == "mcp-server":
|
| 252 |
+
matches = list((source_wiki / "entities" / "mcp-servers").rglob(f"{slug}.md"))
|
| 253 |
+
for match in matches:
|
| 254 |
+
if _is_safe_file(match):
|
| 255 |
+
return match
|
| 256 |
+
return None
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def _skill_replacements(source_wiki: Path, slug: str, *, skills_root: Path | None) -> dict[str, bytes]:
|
| 260 |
+
root = skills_root or Path.home() / ".claude" / "skills"
|
| 261 |
+
candidates = [
|
| 262 |
+
source_wiki / "converted" / slug / "SKILL.md",
|
| 263 |
+
root / slug / "SKILL.md",
|
| 264 |
+
]
|
| 265 |
+
for candidate in candidates:
|
| 266 |
+
if _is_safe_file(candidate):
|
| 267 |
+
skill_dir = candidate.parent
|
| 268 |
+
return {
|
| 269 |
+
f"converted/{slug}/{path.relative_to(skill_dir).as_posix()}": _read_safe_bytes(path)
|
| 270 |
+
for path in sorted(skill_dir.rglob("*"))
|
| 271 |
+
if _is_safe_file(path) and not path.name.endswith((".original", ".lock"))
|
| 272 |
+
}
|
| 273 |
+
return {}
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def _is_safe_file(path: Path) -> bool:
|
| 277 |
+
reject_symlink_path(path)
|
| 278 |
+
return path.is_file()
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def _read_safe_bytes(path: Path) -> bytes:
|
| 282 |
+
reject_symlink_path(path)
|
| 283 |
+
return path.read_bytes()
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def _rewrite_tarball(tarball: Path, replacements: dict[str, bytes]) -> None:
|
| 287 |
+
reject_symlink_path(tarball)
|
| 288 |
+
staged = tarball.with_name(f"{tarball.name}.staged")
|
| 289 |
+
reject_symlink_path(staged)
|
| 290 |
+
skip_names = set(replacements)
|
| 291 |
+
with tarfile.open(tarball, "r:gz") as src, tarfile.open(
|
| 292 |
+
staged,
|
| 293 |
+
"w:gz",
|
| 294 |
+
compresslevel=OVERLAY_GZIP_COMPRESSLEVEL,
|
| 295 |
+
) as dst:
|
| 296 |
+
for member in src:
|
| 297 |
+
safe_name = _safe_tar_name(member.name)
|
| 298 |
+
if safe_name is None:
|
| 299 |
+
continue
|
| 300 |
+
if safe_name in GRAPH_EXPORT_NAMES or safe_name in skip_names:
|
| 301 |
+
continue
|
| 302 |
+
if safe_name.endswith(".original") or safe_name.endswith(".lock"):
|
| 303 |
+
continue
|
| 304 |
+
if member.isfile():
|
| 305 |
+
f = src.extractfile(member)
|
| 306 |
+
if f is not None:
|
| 307 |
+
dst.addfile(member, f)
|
| 308 |
+
elif member.isdir():
|
| 309 |
+
dst.addfile(member)
|
| 310 |
+
for name, payload in sorted(replacements.items()):
|
| 311 |
+
_add_bytes(dst, name=f"./{name}", payload=payload)
|
| 312 |
+
promote_staged_artifact(staged, tarball, validate=_validate_tarball)
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def _validate_tarball(candidate: Path) -> None:
|
| 316 |
+
seen: set[str] = set()
|
| 317 |
+
with tarfile.open(candidate, "r:gz") as tf:
|
| 318 |
+
for member in tf:
|
| 319 |
+
safe_name = _safe_tar_name(member.name)
|
| 320 |
+
if safe_name is None:
|
| 321 |
+
raise ValueError(f"unsafe tar member: {member.name}")
|
| 322 |
+
if safe_name.endswith(".original") or safe_name.endswith(".lock"):
|
| 323 |
+
raise ValueError(f"transient member leaked: {safe_name}")
|
| 324 |
+
seen.add(safe_name)
|
| 325 |
+
missing = sorted(GRAPH_EXPORT_NAMES - seen)
|
| 326 |
+
if missing:
|
| 327 |
+
raise ValueError(f"candidate tarball missing graph exports: {missing}")
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def _read_tar_graph_artifacts(tarball: Path) -> tuple[dict[str, Any], dict[str, Any]]:
|
| 331 |
+
graph: dict[str, Any] | None = None
|
| 332 |
+
communities: dict[str, Any] | None = None
|
| 333 |
+
with tarfile.open(tarball, "r:gz") as tf:
|
| 334 |
+
for member in tf:
|
| 335 |
+
safe_name = _safe_tar_name(member.name)
|
| 336 |
+
if safe_name not in {"graphify-out/graph.json", "graphify-out/communities.json"}:
|
| 337 |
+
continue
|
| 338 |
+
f = tf.extractfile(member)
|
| 339 |
+
if f is None:
|
| 340 |
+
continue
|
| 341 |
+
data = json.loads(f.read().decode("utf-8"))
|
| 342 |
+
if safe_name.endswith("graph.json"):
|
| 343 |
+
graph = data
|
| 344 |
+
else:
|
| 345 |
+
communities = data
|
| 346 |
+
if graph is None or communities is None:
|
| 347 |
+
raise ValueError("tarball is missing graph.json or communities.json")
|
| 348 |
+
return graph, communities
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def _render_delta(
|
| 352 |
+
graph: dict[str, Any],
|
| 353 |
+
selected: list[str],
|
| 354 |
+
*,
|
| 355 |
+
export_id: str,
|
| 356 |
+
generated: str,
|
| 357 |
+
) -> dict[str, Any]:
|
| 358 |
+
selected_set = set(selected)
|
| 359 |
+
nodes = [
|
| 360 |
+
node for node in _list_field(graph, "nodes")
|
| 361 |
+
if isinstance(node, dict) and node.get("id") in selected_set
|
| 362 |
+
]
|
| 363 |
+
edges = [
|
| 364 |
+
edge for edge in _list_field(graph, "edges")
|
| 365 |
+
if isinstance(edge, dict)
|
| 366 |
+
and (edge.get("source") in selected_set or edge.get("target") in selected_set)
|
| 367 |
+
]
|
| 368 |
+
return {
|
| 369 |
+
"version": 1,
|
| 370 |
+
"full_rebuild": False,
|
| 371 |
+
"export_id": export_id,
|
| 372 |
+
"generated": generated,
|
| 373 |
+
"node_count": len(graph["nodes"]),
|
| 374 |
+
"edge_count": len(graph["edges"]),
|
| 375 |
+
"delta_node_count": len(nodes),
|
| 376 |
+
"delta_edge_count": len(edges),
|
| 377 |
+
"nodes": nodes,
|
| 378 |
+
"edges": edges,
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def _render_manifest(
|
| 383 |
+
graph: dict[str, Any],
|
| 384 |
+
communities: dict[str, Any],
|
| 385 |
+
*,
|
| 386 |
+
export_id: str,
|
| 387 |
+
generated: str,
|
| 388 |
+
) -> dict[str, Any]:
|
| 389 |
+
return {
|
| 390 |
+
"version": 1,
|
| 391 |
+
"export_id": export_id,
|
| 392 |
+
"generated": generated,
|
| 393 |
+
"artifacts": {
|
| 394 |
+
"graph": "graph.json",
|
| 395 |
+
"delta": "graph-delta.json",
|
| 396 |
+
"communities": "communities.json",
|
| 397 |
+
"report": "graph-report.md",
|
| 398 |
+
},
|
| 399 |
+
"counts": {
|
| 400 |
+
"nodes": len(graph["nodes"]),
|
| 401 |
+
"edges": len(graph["edges"]),
|
| 402 |
+
"communities": communities.get("total_communities", 0),
|
| 403 |
+
},
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def _render_report(
|
| 408 |
+
graph: dict[str, Any],
|
| 409 |
+
communities: dict[str, Any],
|
| 410 |
+
*,
|
| 411 |
+
selected: list[str],
|
| 412 |
+
export_id: str,
|
| 413 |
+
generated: str,
|
| 414 |
+
) -> str:
|
| 415 |
+
degree: Counter[str] = Counter()
|
| 416 |
+
for edge in _list_field(graph, "edges"):
|
| 417 |
+
if not isinstance(edge, dict):
|
| 418 |
+
continue
|
| 419 |
+
degree[str(edge.get("source") or "")] += 1
|
| 420 |
+
degree[str(edge.get("target") or "")] += 1
|
| 421 |
+
node_by_id = _nodes_by_id(graph)
|
| 422 |
+
lines = [
|
| 423 |
+
"# Graph Report",
|
| 424 |
+
"",
|
| 425 |
+
f"> Generated: {generated}",
|
| 426 |
+
f"> Export ID: {export_id}",
|
| 427 |
+
(
|
| 428 |
+
f"> Nodes: {len(graph['nodes'])} | Edges: {len(graph['edges'])} | "
|
| 429 |
+
f"Communities: {communities.get('total_communities', 0)}"
|
| 430 |
+
),
|
| 431 |
+
"",
|
| 432 |
+
"## Overlay Entities",
|
| 433 |
+
"",
|
| 434 |
+
]
|
| 435 |
+
for node_id in selected:
|
| 436 |
+
node = node_by_id.get(node_id, {})
|
| 437 |
+
lines.append(f"- **{node.get('label', node_id)}** ({node_id})")
|
| 438 |
+
lines.extend(["", "## Most Connected Nodes", ""])
|
| 439 |
+
for node_id, count in degree.most_common(20):
|
| 440 |
+
if not node_id:
|
| 441 |
+
continue
|
| 442 |
+
node = node_by_id.get(node_id, {})
|
| 443 |
+
lines.append(f"- **{node.get('label', node_id)}** ({count} connections)")
|
| 444 |
+
return "\n".join(lines) + "\n"
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def _read_json(path: Path) -> dict[str, Any]:
|
| 448 |
+
data = json.loads(path.read_text(encoding="utf-8"))
|
| 449 |
+
if not isinstance(data, dict):
|
| 450 |
+
raise ValueError(f"{path} must contain a JSON object")
|
| 451 |
+
return data
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
def _nodes_by_id(graph: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
| 455 |
+
return {
|
| 456 |
+
str(node.get("id")): node
|
| 457 |
+
for node in _list_field(graph, "nodes")
|
| 458 |
+
if isinstance(node, dict) and node.get("id")
|
| 459 |
+
}
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def _list_field(data: dict[str, Any], key: str) -> list[Any]:
|
| 463 |
+
value = data.get(key)
|
| 464 |
+
if not isinstance(value, list):
|
| 465 |
+
raise ValueError(f"graph field {key!r} must be a list")
|
| 466 |
+
return value
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def _edge_key(edge: dict[str, Any]) -> tuple[str, str]:
|
| 470 |
+
source = str(edge.get("source") or "")
|
| 471 |
+
target = str(edge.get("target") or "")
|
| 472 |
+
return (source, target) if source <= target else (target, source)
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
def _split_node_id(node_id: str) -> tuple[str, str]:
|
| 476 |
+
if ":" not in node_id:
|
| 477 |
+
raise ValueError(f"invalid node id: {node_id}")
|
| 478 |
+
entity_type, slug = node_id.split(":", 1)
|
| 479 |
+
return entity_type, slug
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def _safe_tar_name(name: str) -> str | None:
|
| 483 |
+
normalized = name.replace("\\", "/")
|
| 484 |
+
while normalized.startswith("./"):
|
| 485 |
+
normalized = normalized[2:]
|
| 486 |
+
if not normalized or normalized.startswith("/") or normalized.startswith("../"):
|
| 487 |
+
return None
|
| 488 |
+
if "/../" in normalized or normalized == "..":
|
| 489 |
+
return None
|
| 490 |
+
return normalized
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
def _add_bytes(
|
| 494 |
+
tf: tarfile.TarFile,
|
| 495 |
+
*,
|
| 496 |
+
name: str,
|
| 497 |
+
payload: bytes,
|
| 498 |
+
mode: int = 0o644,
|
| 499 |
+
) -> None:
|
| 500 |
+
import io
|
| 501 |
+
|
| 502 |
+
info = tarfile.TarInfo(name)
|
| 503 |
+
info.size = len(payload)
|
| 504 |
+
info.mode = mode
|
| 505 |
+
info.mtime = 0
|
| 506 |
+
tf.addfile(info, io.BytesIO(payload))
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def _json_bytes(data: dict[str, Any], *, compact: bool) -> bytes:
|
| 510 |
+
if compact:
|
| 511 |
+
return json.dumps(data, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
| 512 |
+
return (json.dumps(data, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
def _timestamp(now: datetime | None = None) -> str:
|
| 516 |
+
value = now or datetime.now(timezone.utc)
|
| 517 |
+
return value.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
def main() -> None:
|
| 521 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 522 |
+
parser.add_argument("--source-wiki", type=Path, default=Path.home() / ".claude" / "skill-wiki")
|
| 523 |
+
parser.add_argument("--tarball", type=Path, required=True)
|
| 524 |
+
parser.add_argument("--entity", action="append", required=True, help="Node id, e.g. skill:foo")
|
| 525 |
+
parser.add_argument("--root-communities", type=Path)
|
| 526 |
+
parser.add_argument("--runtime", action="store_true")
|
| 527 |
+
args = parser.parse_args()
|
| 528 |
+
stats = overlay_entities(
|
| 529 |
+
source_wiki=args.source_wiki,
|
| 530 |
+
tarball=args.tarball,
|
| 531 |
+
entity_ids=args.entity,
|
| 532 |
+
skills_root=Path.home() / ".claude" / "skills",
|
| 533 |
+
root_communities=args.root_communities,
|
| 534 |
+
runtime=args.runtime,
|
| 535 |
+
)
|
| 536 |
+
print(json.dumps(stats.__dict__, indent=2))
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
if __name__ == "__main__":
|
| 540 |
+
main()
|
scripts/sync_huggingface.py
CHANGED
|
@@ -1,282 +1,309 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""Sync the current git tree to Hugging Face with HF-only card metadata."""
|
| 3 |
-
|
| 4 |
-
from __future__ import annotations
|
| 5 |
-
|
| 6 |
-
import argparse
|
| 7 |
-
import os
|
| 8 |
-
import shutil
|
| 9 |
-
import subprocess
|
| 10 |
-
import sys
|
| 11 |
-
import tempfile
|
| 12 |
-
from pathlib import Path
|
| 13 |
-
from typing import Any
|
| 14 |
-
|
| 15 |
-
DEFAULT_REPO_ID = "Stevesolun/ctx"
|
| 16 |
-
DEFAULT_REPO_TYPE = "dataset"
|
| 17 |
-
|
| 18 |
-
HF_CARD_METADATA = """---
|
| 19 |
-
license: mit
|
| 20 |
-
pretty_name: ctx
|
| 21 |
-
tags:
|
| 22 |
-
- agents
|
| 23 |
-
- mcp
|
| 24 |
-
- skills
|
| 25 |
-
- knowledge-graph
|
| 26 |
-
- llm-wiki
|
| 27 |
-
- recommendation-system
|
| 28 |
-
- harness
|
| 29 |
-
- codex
|
| 30 |
-
- claude-code
|
| 31 |
-
---
|
| 32 |
-
|
| 33 |
-
"""
|
| 34 |
-
|
| 35 |
-
LFS_POINTER_PREFIX = b"version https://git-lfs.github.com/spec/v1"
|
| 36 |
-
HYDRATED_ARTIFACT_MIN_BYTES = {
|
| 37 |
-
Path("graph/wiki-graph.tar.gz"): 100_000_000,
|
| 38 |
-
Path("graph/wiki-graph-runtime.tar.gz"): 10_000_000,
|
| 39 |
-
Path("graph/skills-sh-catalog.json.gz"): 1_000_000,
|
| 40 |
-
}
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
def with_hf_repo_card_metadata(readme_text: str) -> str:
|
| 44 |
-
"""Return README text with Hugging Face repo-card metadata prepended."""
|
| 45 |
-
return HF_CARD_METADATA + _strip_leading_yaml_frontmatter(readme_text)
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
def _strip_leading_yaml_frontmatter(text: str) -> str:
|
| 49 |
-
if not text.startswith("---\n"):
|
| 50 |
-
return text
|
| 51 |
-
end = text.find("\n---\n", 4)
|
| 52 |
-
if end == -1:
|
| 53 |
-
return text
|
| 54 |
-
return text[end + len("\n---\n") :].lstrip("\n")
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
def _git(repo: Path, *args: str) -> str:
|
| 58 |
-
return subprocess.check_output(["git", *args], cwd=repo, text=True).strip()
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
def _git_bytes(repo: Path, *args: str) -> bytes:
|
| 62 |
-
return subprocess.check_output(["git", *args], cwd=repo)
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
def _iter_tracked_files(repo: Path) -> list[Path]:
|
| 66 |
-
output = _git_bytes(repo, "ls-files", "-z")
|
| 67 |
-
files: list[Path] = []
|
| 68 |
-
for raw in output.split(b"\0"):
|
| 69 |
-
if not raw:
|
| 70 |
-
continue
|
| 71 |
-
rel = Path(raw.decode("utf-8"))
|
| 72 |
-
if rel.is_absolute() or ".." in rel.parts:
|
| 73 |
-
raise ValueError(f"unsafe git path: {rel}")
|
| 74 |
-
files.append(rel)
|
| 75 |
-
return files
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
def _assert_hydrated_artifacts(repo: Path) -> None:
|
| 79 |
-
for rel, min_bytes in HYDRATED_ARTIFACT_MIN_BYTES.items():
|
| 80 |
-
artifact = repo / rel
|
| 81 |
-
if not artifact.is_file():
|
| 82 |
-
raise FileNotFoundError(
|
| 83 |
-
f"{rel.as_posix()} is required before Hugging Face sync"
|
| 84 |
-
)
|
| 85 |
-
size = artifact.stat().st_size
|
| 86 |
-
if size < min_bytes:
|
| 87 |
-
raise RuntimeError(
|
| 88 |
-
f"{rel.as_posix()} is {size:,} bytes; expected at least "
|
| 89 |
-
f"{min_bytes:,}.
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
def
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Sync the current git tree to Hugging Face with HF-only card metadata."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import os
|
| 8 |
+
import shutil
|
| 9 |
+
import subprocess
|
| 10 |
+
import sys
|
| 11 |
+
import tempfile
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Any
|
| 14 |
+
|
| 15 |
+
DEFAULT_REPO_ID = "Stevesolun/ctx"
|
| 16 |
+
DEFAULT_REPO_TYPE = "dataset"
|
| 17 |
+
|
| 18 |
+
HF_CARD_METADATA = """---
|
| 19 |
+
license: mit
|
| 20 |
+
pretty_name: ctx
|
| 21 |
+
tags:
|
| 22 |
+
- agents
|
| 23 |
+
- mcp
|
| 24 |
+
- skills
|
| 25 |
+
- knowledge-graph
|
| 26 |
+
- llm-wiki
|
| 27 |
+
- recommendation-system
|
| 28 |
+
- harness
|
| 29 |
+
- codex
|
| 30 |
+
- claude-code
|
| 31 |
+
---
|
| 32 |
+
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
LFS_POINTER_PREFIX = b"version https://git-lfs.github.com/spec/v1"
|
| 36 |
+
HYDRATED_ARTIFACT_MIN_BYTES = {
|
| 37 |
+
Path("graph/wiki-graph.tar.gz"): 100_000_000,
|
| 38 |
+
Path("graph/wiki-graph-runtime.tar.gz"): 10_000_000,
|
| 39 |
+
Path("graph/skills-sh-catalog.json.gz"): 1_000_000,
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def with_hf_repo_card_metadata(readme_text: str) -> str:
|
| 44 |
+
"""Return README text with Hugging Face repo-card metadata prepended."""
|
| 45 |
+
return HF_CARD_METADATA + _strip_leading_yaml_frontmatter(readme_text)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _strip_leading_yaml_frontmatter(text: str) -> str:
|
| 49 |
+
if not text.startswith("---\n"):
|
| 50 |
+
return text
|
| 51 |
+
end = text.find("\n---\n", 4)
|
| 52 |
+
if end == -1:
|
| 53 |
+
return text
|
| 54 |
+
return text[end + len("\n---\n") :].lstrip("\n")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _git(repo: Path, *args: str) -> str:
|
| 58 |
+
return subprocess.check_output(["git", *args], cwd=repo, text=True).strip()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _git_bytes(repo: Path, *args: str) -> bytes:
|
| 62 |
+
return subprocess.check_output(["git", *args], cwd=repo)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _iter_tracked_files(repo: Path) -> list[Path]:
|
| 66 |
+
output = _git_bytes(repo, "ls-files", "-z")
|
| 67 |
+
files: list[Path] = []
|
| 68 |
+
for raw in output.split(b"\0"):
|
| 69 |
+
if not raw:
|
| 70 |
+
continue
|
| 71 |
+
rel = Path(raw.decode("utf-8"))
|
| 72 |
+
if rel.is_absolute() or ".." in rel.parts:
|
| 73 |
+
raise ValueError(f"unsafe git path: {rel}")
|
| 74 |
+
files.append(rel)
|
| 75 |
+
return files
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _assert_hydrated_artifacts(repo: Path) -> None:
|
| 79 |
+
for rel, min_bytes in HYDRATED_ARTIFACT_MIN_BYTES.items():
|
| 80 |
+
artifact = repo / rel
|
| 81 |
+
if not artifact.is_file():
|
| 82 |
+
raise FileNotFoundError(
|
| 83 |
+
f"{rel.as_posix()} is required before Hugging Face sync"
|
| 84 |
+
)
|
| 85 |
+
size = artifact.stat().st_size
|
| 86 |
+
if size < min_bytes:
|
| 87 |
+
raise RuntimeError(
|
| 88 |
+
f"{rel.as_posix()} is {size:,} bytes; expected at least "
|
| 89 |
+
f"{min_bytes:,}. Download or rebuild graph release artifacts "
|
| 90 |
+
"before publishing."
|
| 91 |
+
)
|
| 92 |
+
with artifact.open("rb") as fh:
|
| 93 |
+
prefix = fh.read(len(LFS_POINTER_PREFIX))
|
| 94 |
+
if prefix == LFS_POINTER_PREFIX:
|
| 95 |
+
raise RuntimeError(
|
| 96 |
+
f"{rel.as_posix()} is a Git LFS pointer, not the hydrated artifact"
|
| 97 |
+
)
|
| 98 |
+
_validate_graph_artifact_integrity(repo)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _validate_graph_artifact_integrity(repo: Path) -> None:
|
| 102 |
+
src_dir = repo / "src"
|
| 103 |
+
if str(src_dir) not in sys.path:
|
| 104 |
+
sys.path.insert(0, str(src_dir))
|
| 105 |
+
try:
|
| 106 |
+
from validate_graph_artifacts import validate_graph_artifacts
|
| 107 |
+
|
| 108 |
+
validate_graph_artifacts(repo / "graph")
|
| 109 |
+
except Exception as exc: # noqa: BLE001
|
| 110 |
+
raise RuntimeError(
|
| 111 |
+
"graph artifact integrity validation failed before Hugging Face sync: "
|
| 112 |
+
f"{exc}"
|
| 113 |
+
) from exc
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _assert_repo_stats_current(repo: Path) -> None:
|
| 117 |
+
updater = repo / "src" / "update_repo_stats.py"
|
| 118 |
+
if not updater.is_file():
|
| 119 |
+
raise FileNotFoundError("src/update_repo_stats.py is required before Hugging Face sync")
|
| 120 |
+
subprocess.run(
|
| 121 |
+
[sys.executable, str(updater), "--check"],
|
| 122 |
+
cwd=repo,
|
| 123 |
+
check=True,
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _export_tracked_tree(repo: Path, export_dir: Path) -> None:
|
| 128 |
+
_assert_repo_stats_current(repo)
|
| 129 |
+
_assert_hydrated_artifacts(repo)
|
| 130 |
+
repo_root = repo.resolve()
|
| 131 |
+
export_root = export_dir.resolve()
|
| 132 |
+
for rel in _iter_tracked_files(repo):
|
| 133 |
+
source = (repo_root / rel).resolve()
|
| 134 |
+
if source != repo_root and not source.is_relative_to(repo_root):
|
| 135 |
+
raise ValueError(f"unsafe source path: {rel}")
|
| 136 |
+
if source.is_symlink():
|
| 137 |
+
raise ValueError(f"refusing to follow symlink during HF sync: {rel}")
|
| 138 |
+
if not source.is_file():
|
| 139 |
+
continue
|
| 140 |
+
target = (export_root / rel).resolve()
|
| 141 |
+
if target != export_root and not target.is_relative_to(export_root):
|
| 142 |
+
raise ValueError(f"unsafe export path: {rel}")
|
| 143 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 144 |
+
shutil.copy2(source, target)
|
| 145 |
+
_copy_hydrated_artifacts(repo_root, export_root)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def _copy_hydrated_artifacts(repo_root: Path, export_root: Path) -> None:
|
| 149 |
+
"""Copy required graph artifacts even when they are intentionally untracked."""
|
| 150 |
+
for rel in HYDRATED_ARTIFACT_MIN_BYTES:
|
| 151 |
+
source = (repo_root / rel).resolve()
|
| 152 |
+
if source != repo_root and not source.is_relative_to(repo_root):
|
| 153 |
+
raise ValueError(f"unsafe artifact source path: {rel}")
|
| 154 |
+
target = (export_root / rel).resolve()
|
| 155 |
+
if target != export_root and not target.is_relative_to(export_root):
|
| 156 |
+
raise ValueError(f"unsafe artifact export path: {rel}")
|
| 157 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 158 |
+
shutil.copy2(source, target)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _patch_export_readme(export_dir: Path) -> None:
|
| 162 |
+
readme = export_dir / "README.md"
|
| 163 |
+
readme.write_text(
|
| 164 |
+
with_hf_repo_card_metadata(readme.read_text(encoding="utf-8")),
|
| 165 |
+
encoding="utf-8",
|
| 166 |
+
newline="\n",
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _iter_export_file_names(export_dir: Path) -> set[str]:
|
| 171 |
+
names: set[str] = set()
|
| 172 |
+
for path in export_dir.rglob("*"):
|
| 173 |
+
if not path.is_file():
|
| 174 |
+
continue
|
| 175 |
+
rel = path.relative_to(export_dir).as_posix()
|
| 176 |
+
if rel == ".cache" or rel.startswith(".cache/"):
|
| 177 |
+
continue
|
| 178 |
+
names.add(rel)
|
| 179 |
+
return names
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def _repo_url(*, repo_id: str, repo_type: str) -> str:
|
| 183 |
+
prefix = {"dataset": "datasets", "space": "spaces"}.get(repo_type)
|
| 184 |
+
repo_path = f"{prefix}/{repo_id}" if prefix else repo_id
|
| 185 |
+
return f"https://huggingface.co/{repo_path}"
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def _repo_commit_url(*, repo_id: str, repo_type: str, sha: str) -> str:
|
| 189 |
+
return f"{_repo_url(repo_id=repo_id, repo_type=repo_type)}/commit/{sha}"
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _remote_has_no_stale_paths(
|
| 193 |
+
*,
|
| 194 |
+
api: Any,
|
| 195 |
+
export_dir: Path,
|
| 196 |
+
repo_id: str,
|
| 197 |
+
repo_type: str,
|
| 198 |
+
) -> bool:
|
| 199 |
+
try:
|
| 200 |
+
remote_files = set(api.list_repo_files(repo_id=repo_id, repo_type=repo_type))
|
| 201 |
+
except Exception:
|
| 202 |
+
return False
|
| 203 |
+
return remote_files <= _iter_export_file_names(export_dir)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def _upload_export(
|
| 207 |
+
*,
|
| 208 |
+
api: Any,
|
| 209 |
+
export_dir: Path,
|
| 210 |
+
repo_id: str,
|
| 211 |
+
repo_type: str,
|
| 212 |
+
head: str,
|
| 213 |
+
prefer_large_upload: bool,
|
| 214 |
+
) -> str:
|
| 215 |
+
if (
|
| 216 |
+
prefer_large_upload
|
| 217 |
+
and hasattr(api, "upload_large_folder")
|
| 218 |
+
and _remote_has_no_stale_paths(
|
| 219 |
+
api=api,
|
| 220 |
+
export_dir=export_dir,
|
| 221 |
+
repo_id=repo_id,
|
| 222 |
+
repo_type=repo_type,
|
| 223 |
+
)
|
| 224 |
+
):
|
| 225 |
+
api.upload_large_folder(
|
| 226 |
+
repo_id=repo_id,
|
| 227 |
+
repo_type=repo_type,
|
| 228 |
+
folder_path=str(export_dir),
|
| 229 |
+
print_report=True,
|
| 230 |
+
)
|
| 231 |
+
info = api.repo_info(repo_id=repo_id, repo_type=repo_type)
|
| 232 |
+
sha = getattr(info, "sha", None)
|
| 233 |
+
if sha:
|
| 234 |
+
return _repo_commit_url(repo_id=repo_id, repo_type=repo_type, sha=str(sha))
|
| 235 |
+
return _repo_url(repo_id=repo_id, repo_type=repo_type)
|
| 236 |
+
|
| 237 |
+
info = api.upload_folder(
|
| 238 |
+
repo_id=repo_id,
|
| 239 |
+
repo_type=repo_type,
|
| 240 |
+
folder_path=str(export_dir),
|
| 241 |
+
commit_message=f"Sync ctx {head[:7]}",
|
| 242 |
+
commit_description=f"GitHub commit: {head}",
|
| 243 |
+
delete_patterns="*",
|
| 244 |
+
)
|
| 245 |
+
return str(getattr(info, "commit_url", info))
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def sync_to_huggingface(
|
| 249 |
+
*,
|
| 250 |
+
repo: Path,
|
| 251 |
+
repo_id: str,
|
| 252 |
+
repo_type: str,
|
| 253 |
+
token: str,
|
| 254 |
+
) -> str:
|
| 255 |
+
"""Upload HEAD to Hugging Face and return the commit URL."""
|
| 256 |
+
from huggingface_hub import HfApi
|
| 257 |
+
|
| 258 |
+
head = _git(repo, "rev-parse", "HEAD")
|
| 259 |
+
workspace = Path(tempfile.mkdtemp(prefix="ctx-hf-upload-"))
|
| 260 |
+
export_dir = workspace / "export"
|
| 261 |
+
try:
|
| 262 |
+
export_dir.mkdir()
|
| 263 |
+
_export_tracked_tree(repo, export_dir)
|
| 264 |
+
_patch_export_readme(export_dir)
|
| 265 |
+
api = HfApi(token=token)
|
| 266 |
+
api.create_repo(repo_id, repo_type=repo_type, exist_ok=True)
|
| 267 |
+
return _upload_export(
|
| 268 |
+
api=api,
|
| 269 |
+
repo_id=repo_id,
|
| 270 |
+
repo_type=repo_type,
|
| 271 |
+
export_dir=export_dir,
|
| 272 |
+
head=head,
|
| 273 |
+
prefer_large_upload=True,
|
| 274 |
+
)
|
| 275 |
+
finally:
|
| 276 |
+
shutil.rmtree(workspace, ignore_errors=True)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def main() -> None:
|
| 280 |
+
parser = argparse.ArgumentParser(
|
| 281 |
+
description="Upload this git checkout to Hugging Face with repo-card metadata"
|
| 282 |
+
)
|
| 283 |
+
parser.add_argument("--repo", default=".", help="Git checkout path")
|
| 284 |
+
parser.add_argument(
|
| 285 |
+
"--repo-id",
|
| 286 |
+
default=os.environ.get("HF_REPO_ID", DEFAULT_REPO_ID),
|
| 287 |
+
help="Hugging Face repo ID",
|
| 288 |
+
)
|
| 289 |
+
parser.add_argument(
|
| 290 |
+
"--repo-type",
|
| 291 |
+
default=os.environ.get("HF_REPO_TYPE", DEFAULT_REPO_TYPE),
|
| 292 |
+
help="Hugging Face repo type",
|
| 293 |
+
)
|
| 294 |
+
args = parser.parse_args()
|
| 295 |
+
token = os.environ.get("HF_TOKEN")
|
| 296 |
+
if not token:
|
| 297 |
+
raise SystemExit("HF_TOKEN is required")
|
| 298 |
+
print(
|
| 299 |
+
sync_to_huggingface(
|
| 300 |
+
repo=Path(args.repo).resolve(),
|
| 301 |
+
repo_id=args.repo_id,
|
| 302 |
+
repo_type=args.repo_type,
|
| 303 |
+
token=token,
|
| 304 |
+
)
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
if __name__ == "__main__":
|
| 309 |
+
main()
|
src/tests/fixtures/fake_mcp_server.py
CHANGED
|
@@ -1,224 +1,224 @@
|
|
| 1 |
-
"""fake_mcp_server.py — minimal MCP server stub used by test_mcp_router.
|
| 2 |
-
|
| 3 |
-
Runs as a standalone subprocess launched by the tests. Reads JSON-RPC
|
| 4 |
-
lines on stdin, writes responses on stdout. Designed to be small and
|
| 5 |
-
scriptable: its behaviour is configurable via env vars so a single
|
| 6 |
-
script covers initialize + tools/list + tools/call + failure modes.
|
| 7 |
-
|
| 8 |
-
Env vars (all optional):
|
| 9 |
-
FAKE_MCP_FAIL_INIT=1 - respond with an error to initialize
|
| 10 |
-
FAKE_MCP_CRASH_ON_TOOL=1 - crash (exit 1) on any tools/call
|
| 11 |
-
FAKE_MCP_TOOL_ERROR=1 - return isError=True on any tools/call
|
| 12 |
-
FAKE_MCP_IGNORE_TOOL=1 - accept tools/call but never answer
|
| 13 |
-
FAKE_MCP_NOISY_STDERR=1 - write a warning line to stderr on startup
|
| 14 |
-
FAKE_MCP_STDERR_LINE=<text> - write this exact line to stderr on startup
|
| 15 |
-
FAKE_MCP_EMIT_NOTIFICATION=1 - emit a progress notification before each
|
| 16 |
-
tools/call response
|
| 17 |
-
FAKE_MCP_EXTRA_TOOL=<name> - add a second tool with this name (for
|
| 18 |
-
testing multi-tool list_tools)
|
| 19 |
-
|
| 20 |
-
Tool catalog:
|
| 21 |
-
echo(text: str) -> str
|
| 22 |
-
returns the input text verbatim. Used to confirm args round-trip.
|
| 23 |
-
add(a: int, b: int) -> str
|
| 24 |
-
returns str(a+b). Integer-args coverage.
|
| 25 |
-
"""
|
| 26 |
-
|
| 27 |
-
from __future__ import annotations
|
| 28 |
-
|
| 29 |
-
import json
|
| 30 |
-
import os
|
| 31 |
-
import sys
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
_PROTOCOL_VERSION = "2024-11-05"
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
def _echo_tool(args: dict) -> dict:
|
| 38 |
-
text = str(args.get("text", ""))
|
| 39 |
-
return {
|
| 40 |
-
"content": [{"type": "text", "text": text}],
|
| 41 |
-
"isError": False,
|
| 42 |
-
}
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
def _add_tool(args: dict) -> dict:
|
| 46 |
-
a = int(args.get("a", 0))
|
| 47 |
-
b = int(args.get("b", 0))
|
| 48 |
-
return {
|
| 49 |
-
"content": [{"type": "text", "text": str(a + b)}],
|
| 50 |
-
"isError": False,
|
| 51 |
-
}
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
def _env_tool(args: dict) -> dict:
|
| 55 |
-
name = str(args.get("name", ""))
|
| 56 |
-
return {
|
| 57 |
-
"content": [{"type": "text", "text": os.environ.get(name, "")}],
|
| 58 |
-
"isError": False,
|
| 59 |
-
}
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
TOOLS = {"echo": _echo_tool, "add": _add_tool, "echo_env": _env_tool}
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
def _tool_defs() -> list[dict]:
|
| 66 |
-
defs = [
|
| 67 |
-
{
|
| 68 |
-
"name": "echo",
|
| 69 |
-
"description": "Echo the input text verbatim.",
|
| 70 |
-
"inputSchema": {
|
| 71 |
-
"type": "object",
|
| 72 |
-
"properties": {"text": {"type": "string"}},
|
| 73 |
-
"required": ["text"],
|
| 74 |
-
},
|
| 75 |
-
},
|
| 76 |
-
{
|
| 77 |
-
"name": "add",
|
| 78 |
-
"description": "Return the sum of two integers.",
|
| 79 |
-
"inputSchema": {
|
| 80 |
-
"type": "object",
|
| 81 |
-
"properties": {
|
| 82 |
-
"a": {"type": "integer"},
|
| 83 |
-
"b": {"type": "integer"},
|
| 84 |
-
},
|
| 85 |
-
"required": ["a", "b"],
|
| 86 |
-
},
|
| 87 |
-
},
|
| 88 |
-
{
|
| 89 |
-
"name": "echo_env",
|
| 90 |
-
"description": "Return the value of an environment variable.",
|
| 91 |
-
"inputSchema": {
|
| 92 |
-
"type": "object",
|
| 93 |
-
"properties": {"name": {"type": "string"}},
|
| 94 |
-
"required": ["name"],
|
| 95 |
-
},
|
| 96 |
-
},
|
| 97 |
-
]
|
| 98 |
-
extra = os.environ.get("FAKE_MCP_EXTRA_TOOL")
|
| 99 |
-
if extra:
|
| 100 |
-
defs.append(
|
| 101 |
-
{
|
| 102 |
-
"name": extra,
|
| 103 |
-
"description": f"Extra tool {extra} (test-only).",
|
| 104 |
-
"inputSchema": {"type": "object", "properties": {}},
|
| 105 |
-
}
|
| 106 |
-
)
|
| 107 |
-
return defs
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
def _emit(frame: dict) -> None:
|
| 111 |
-
sys.stdout.write(json.dumps(frame) + "\n")
|
| 112 |
-
sys.stdout.flush()
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
def main() -> None:
|
| 116 |
-
if os.environ.get("FAKE_MCP_NOISY_STDERR") == "1":
|
| 117 |
-
sys.stderr.write("fake-mcp-server: starting up\n")
|
| 118 |
-
sys.stderr.flush()
|
| 119 |
-
stderr_line = os.environ.get("FAKE_MCP_STDERR_LINE")
|
| 120 |
-
if stderr_line:
|
| 121 |
-
sys.stderr.write(stderr_line + "\n")
|
| 122 |
-
sys.stderr.flush()
|
| 123 |
-
|
| 124 |
-
while True:
|
| 125 |
-
line = sys.stdin.readline()
|
| 126 |
-
if not line:
|
| 127 |
-
return
|
| 128 |
-
line = line.strip()
|
| 129 |
-
if not line:
|
| 130 |
-
continue
|
| 131 |
-
try:
|
| 132 |
-
req = json.loads(line)
|
| 133 |
-
except json.JSONDecodeError:
|
| 134 |
-
continue
|
| 135 |
-
|
| 136 |
-
method = req.get("method", "")
|
| 137 |
-
req_id = req.get("id")
|
| 138 |
-
params = req.get("params") or {}
|
| 139 |
-
|
| 140 |
-
if method == "initialize":
|
| 141 |
-
if os.environ.get("FAKE_MCP_FAIL_INIT") == "1":
|
| 142 |
-
_emit({
|
| 143 |
-
"jsonrpc": "2.0",
|
| 144 |
-
"id": req_id,
|
| 145 |
-
"error": {"code": -32603, "message": "init-forbidden"},
|
| 146 |
-
})
|
| 147 |
-
continue
|
| 148 |
-
_emit({
|
| 149 |
-
"jsonrpc": "2.0",
|
| 150 |
-
"id": req_id,
|
| 151 |
-
"result": {
|
| 152 |
-
"protocolVersion": _PROTOCOL_VERSION,
|
| 153 |
-
"capabilities": {"tools": {}},
|
| 154 |
-
"serverInfo": {"name": "fake-mcp", "version": "0.1"},
|
| 155 |
-
},
|
| 156 |
-
})
|
| 157 |
-
continue
|
| 158 |
-
|
| 159 |
-
if method == "notifications/initialized":
|
| 160 |
-
continue
|
| 161 |
-
|
| 162 |
-
if method == "tools/list":
|
| 163 |
-
_emit({
|
| 164 |
-
"jsonrpc": "2.0",
|
| 165 |
-
"id": req_id,
|
| 166 |
-
"result": {"tools": _tool_defs()},
|
| 167 |
-
})
|
| 168 |
-
continue
|
| 169 |
-
|
| 170 |
-
if method == "tools/call":
|
| 171 |
-
if os.environ.get("FAKE_MCP_CRASH_ON_TOOL") == "1":
|
| 172 |
-
sys.exit(1)
|
| 173 |
-
if os.environ.get("FAKE_MCP_IGNORE_TOOL") == "1":
|
| 174 |
-
continue
|
| 175 |
-
|
| 176 |
-
name = params.get("name", "")
|
| 177 |
-
args = params.get("arguments") or {}
|
| 178 |
-
|
| 179 |
-
if os.environ.get("FAKE_MCP_EMIT_NOTIFICATION") == "1":
|
| 180 |
-
_emit({
|
| 181 |
-
"jsonrpc": "2.0",
|
| 182 |
-
"method": "notifications/progress",
|
| 183 |
-
"params": {"progress": 0.5},
|
| 184 |
-
})
|
| 185 |
-
|
| 186 |
-
if os.environ.get("FAKE_MCP_TOOL_ERROR") == "1":
|
| 187 |
-
_emit({
|
| 188 |
-
"jsonrpc": "2.0",
|
| 189 |
-
"id": req_id,
|
| 190 |
-
"result": {
|
| 191 |
-
"content": [{"type": "text", "text": "forced error"}],
|
| 192 |
-
"isError": True,
|
| 193 |
-
},
|
| 194 |
-
})
|
| 195 |
-
continue
|
| 196 |
-
|
| 197 |
-
handler = TOOLS.get(name)
|
| 198 |
-
if handler is None:
|
| 199 |
-
_emit({
|
| 200 |
-
"jsonrpc": "2.0",
|
| 201 |
-
"id": req_id,
|
| 202 |
-
"error": {
|
| 203 |
-
"code": -32601,
|
| 204 |
-
"message": f"unknown tool {name!r}",
|
| 205 |
-
},
|
| 206 |
-
})
|
| 207 |
-
continue
|
| 208 |
-
_emit({
|
| 209 |
-
"jsonrpc": "2.0",
|
| 210 |
-
"id": req_id,
|
| 211 |
-
"result": handler(args),
|
| 212 |
-
})
|
| 213 |
-
continue
|
| 214 |
-
|
| 215 |
-
# Unknown method.
|
| 216 |
-
_emit({
|
| 217 |
-
"jsonrpc": "2.0",
|
| 218 |
-
"id": req_id,
|
| 219 |
-
"error": {"code": -32601, "message": f"method not found: {method}"},
|
| 220 |
-
})
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
if __name__ == "__main__":
|
| 224 |
-
main()
|
|
|
|
| 1 |
+
"""fake_mcp_server.py — minimal MCP server stub used by test_mcp_router.
|
| 2 |
+
|
| 3 |
+
Runs as a standalone subprocess launched by the tests. Reads JSON-RPC
|
| 4 |
+
lines on stdin, writes responses on stdout. Designed to be small and
|
| 5 |
+
scriptable: its behaviour is configurable via env vars so a single
|
| 6 |
+
script covers initialize + tools/list + tools/call + failure modes.
|
| 7 |
+
|
| 8 |
+
Env vars (all optional):
|
| 9 |
+
FAKE_MCP_FAIL_INIT=1 - respond with an error to initialize
|
| 10 |
+
FAKE_MCP_CRASH_ON_TOOL=1 - crash (exit 1) on any tools/call
|
| 11 |
+
FAKE_MCP_TOOL_ERROR=1 - return isError=True on any tools/call
|
| 12 |
+
FAKE_MCP_IGNORE_TOOL=1 - accept tools/call but never answer
|
| 13 |
+
FAKE_MCP_NOISY_STDERR=1 - write a warning line to stderr on startup
|
| 14 |
+
FAKE_MCP_STDERR_LINE=<text> - write this exact line to stderr on startup
|
| 15 |
+
FAKE_MCP_EMIT_NOTIFICATION=1 - emit a progress notification before each
|
| 16 |
+
tools/call response
|
| 17 |
+
FAKE_MCP_EXTRA_TOOL=<name> - add a second tool with this name (for
|
| 18 |
+
testing multi-tool list_tools)
|
| 19 |
+
|
| 20 |
+
Tool catalog:
|
| 21 |
+
echo(text: str) -> str
|
| 22 |
+
returns the input text verbatim. Used to confirm args round-trip.
|
| 23 |
+
add(a: int, b: int) -> str
|
| 24 |
+
returns str(a+b). Integer-args coverage.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
from __future__ import annotations
|
| 28 |
+
|
| 29 |
+
import json
|
| 30 |
+
import os
|
| 31 |
+
import sys
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
_PROTOCOL_VERSION = "2024-11-05"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _echo_tool(args: dict) -> dict:
|
| 38 |
+
text = str(args.get("text", ""))
|
| 39 |
+
return {
|
| 40 |
+
"content": [{"type": "text", "text": text}],
|
| 41 |
+
"isError": False,
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _add_tool(args: dict) -> dict:
|
| 46 |
+
a = int(args.get("a", 0))
|
| 47 |
+
b = int(args.get("b", 0))
|
| 48 |
+
return {
|
| 49 |
+
"content": [{"type": "text", "text": str(a + b)}],
|
| 50 |
+
"isError": False,
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _env_tool(args: dict) -> dict:
|
| 55 |
+
name = str(args.get("name", ""))
|
| 56 |
+
return {
|
| 57 |
+
"content": [{"type": "text", "text": os.environ.get(name, "")}],
|
| 58 |
+
"isError": False,
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
TOOLS = {"echo": _echo_tool, "add": _add_tool, "echo_env": _env_tool}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _tool_defs() -> list[dict]:
|
| 66 |
+
defs = [
|
| 67 |
+
{
|
| 68 |
+
"name": "echo",
|
| 69 |
+
"description": "Echo the input text verbatim.",
|
| 70 |
+
"inputSchema": {
|
| 71 |
+
"type": "object",
|
| 72 |
+
"properties": {"text": {"type": "string"}},
|
| 73 |
+
"required": ["text"],
|
| 74 |
+
},
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"name": "add",
|
| 78 |
+
"description": "Return the sum of two integers.",
|
| 79 |
+
"inputSchema": {
|
| 80 |
+
"type": "object",
|
| 81 |
+
"properties": {
|
| 82 |
+
"a": {"type": "integer"},
|
| 83 |
+
"b": {"type": "integer"},
|
| 84 |
+
},
|
| 85 |
+
"required": ["a", "b"],
|
| 86 |
+
},
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"name": "echo_env",
|
| 90 |
+
"description": "Return the value of an environment variable.",
|
| 91 |
+
"inputSchema": {
|
| 92 |
+
"type": "object",
|
| 93 |
+
"properties": {"name": {"type": "string"}},
|
| 94 |
+
"required": ["name"],
|
| 95 |
+
},
|
| 96 |
+
},
|
| 97 |
+
]
|
| 98 |
+
extra = os.environ.get("FAKE_MCP_EXTRA_TOOL")
|
| 99 |
+
if extra:
|
| 100 |
+
defs.append(
|
| 101 |
+
{
|
| 102 |
+
"name": extra,
|
| 103 |
+
"description": f"Extra tool {extra} (test-only).",
|
| 104 |
+
"inputSchema": {"type": "object", "properties": {}},
|
| 105 |
+
}
|
| 106 |
+
)
|
| 107 |
+
return defs
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _emit(frame: dict) -> None:
|
| 111 |
+
sys.stdout.write(json.dumps(frame) + "\n")
|
| 112 |
+
sys.stdout.flush()
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def main() -> None:
|
| 116 |
+
if os.environ.get("FAKE_MCP_NOISY_STDERR") == "1":
|
| 117 |
+
sys.stderr.write("fake-mcp-server: starting up\n")
|
| 118 |
+
sys.stderr.flush()
|
| 119 |
+
stderr_line = os.environ.get("FAKE_MCP_STDERR_LINE")
|
| 120 |
+
if stderr_line:
|
| 121 |
+
sys.stderr.write(stderr_line + "\n")
|
| 122 |
+
sys.stderr.flush()
|
| 123 |
+
|
| 124 |
+
while True:
|
| 125 |
+
line = sys.stdin.readline()
|
| 126 |
+
if not line:
|
| 127 |
+
return
|
| 128 |
+
line = line.strip()
|
| 129 |
+
if not line:
|
| 130 |
+
continue
|
| 131 |
+
try:
|
| 132 |
+
req = json.loads(line)
|
| 133 |
+
except json.JSONDecodeError:
|
| 134 |
+
continue
|
| 135 |
+
|
| 136 |
+
method = req.get("method", "")
|
| 137 |
+
req_id = req.get("id")
|
| 138 |
+
params = req.get("params") or {}
|
| 139 |
+
|
| 140 |
+
if method == "initialize":
|
| 141 |
+
if os.environ.get("FAKE_MCP_FAIL_INIT") == "1":
|
| 142 |
+
_emit({
|
| 143 |
+
"jsonrpc": "2.0",
|
| 144 |
+
"id": req_id,
|
| 145 |
+
"error": {"code": -32603, "message": "init-forbidden"},
|
| 146 |
+
})
|
| 147 |
+
continue
|
| 148 |
+
_emit({
|
| 149 |
+
"jsonrpc": "2.0",
|
| 150 |
+
"id": req_id,
|
| 151 |
+
"result": {
|
| 152 |
+
"protocolVersion": _PROTOCOL_VERSION,
|
| 153 |
+
"capabilities": {"tools": {}},
|
| 154 |
+
"serverInfo": {"name": "fake-mcp", "version": "0.1"},
|
| 155 |
+
},
|
| 156 |
+
})
|
| 157 |
+
continue
|
| 158 |
+
|
| 159 |
+
if method == "notifications/initialized":
|
| 160 |
+
continue
|
| 161 |
+
|
| 162 |
+
if method == "tools/list":
|
| 163 |
+
_emit({
|
| 164 |
+
"jsonrpc": "2.0",
|
| 165 |
+
"id": req_id,
|
| 166 |
+
"result": {"tools": _tool_defs()},
|
| 167 |
+
})
|
| 168 |
+
continue
|
| 169 |
+
|
| 170 |
+
if method == "tools/call":
|
| 171 |
+
if os.environ.get("FAKE_MCP_CRASH_ON_TOOL") == "1":
|
| 172 |
+
sys.exit(1)
|
| 173 |
+
if os.environ.get("FAKE_MCP_IGNORE_TOOL") == "1":
|
| 174 |
+
continue
|
| 175 |
+
|
| 176 |
+
name = params.get("name", "")
|
| 177 |
+
args = params.get("arguments") or {}
|
| 178 |
+
|
| 179 |
+
if os.environ.get("FAKE_MCP_EMIT_NOTIFICATION") == "1":
|
| 180 |
+
_emit({
|
| 181 |
+
"jsonrpc": "2.0",
|
| 182 |
+
"method": "notifications/progress",
|
| 183 |
+
"params": {"progress": 0.5},
|
| 184 |
+
})
|
| 185 |
+
|
| 186 |
+
if os.environ.get("FAKE_MCP_TOOL_ERROR") == "1":
|
| 187 |
+
_emit({
|
| 188 |
+
"jsonrpc": "2.0",
|
| 189 |
+
"id": req_id,
|
| 190 |
+
"result": {
|
| 191 |
+
"content": [{"type": "text", "text": "forced error"}],
|
| 192 |
+
"isError": True,
|
| 193 |
+
},
|
| 194 |
+
})
|
| 195 |
+
continue
|
| 196 |
+
|
| 197 |
+
handler = TOOLS.get(name)
|
| 198 |
+
if handler is None:
|
| 199 |
+
_emit({
|
| 200 |
+
"jsonrpc": "2.0",
|
| 201 |
+
"id": req_id,
|
| 202 |
+
"error": {
|
| 203 |
+
"code": -32601,
|
| 204 |
+
"message": f"unknown tool {name!r}",
|
| 205 |
+
},
|
| 206 |
+
})
|
| 207 |
+
continue
|
| 208 |
+
_emit({
|
| 209 |
+
"jsonrpc": "2.0",
|
| 210 |
+
"id": req_id,
|
| 211 |
+
"result": handler(args),
|
| 212 |
+
})
|
| 213 |
+
continue
|
| 214 |
+
|
| 215 |
+
# Unknown method.
|
| 216 |
+
_emit({
|
| 217 |
+
"jsonrpc": "2.0",
|
| 218 |
+
"id": req_id,
|
| 219 |
+
"error": {"code": -32601, "message": f"method not found: {method}"},
|
| 220 |
+
})
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
if __name__ == "__main__":
|
| 224 |
+
main()
|
src/tests/fixtures/pulsemcp_listing_excerpt.html
CHANGED
|
@@ -1,170 +1,170 @@
|
|
| 1 |
-
<div class="servers-listing">
|
| 2 |
-
<a href="/servers/microsoft-playwright">
|
| 3 |
-
<div class="relative flex flex-col rounded border border-pulse-gray-border h-full hover:border-pulse-purple hover:shadow-lg transition-all duration-300 bg-white" data-test-id="mcp-server-card-microsoft-playwright">
|
| 4 |
-
|
| 5 |
-
<div class="flex flex-col h-full p-6">
|
| 6 |
-
<!-- Header section -->
|
| 7 |
-
<div class="flex-grow">
|
| 8 |
-
<div class="flex items-center gap-3 mb-2">
|
| 9 |
-
<h3 class="text-20 text-pulse-black font-sans font-normal leading-tight">
|
| 10 |
-
Playwright Browser Automation
|
| 11 |
-
</h3>
|
| 12 |
-
</div>
|
| 13 |
-
|
| 14 |
-
<p class="text-14 text-gray-500 mb-3">Microsoft</p>
|
| 15 |
-
|
| 16 |
-
<p class="text-15 text-pulse-black leading-relaxed">
|
| 17 |
-
Enables web browser control for navigating websites, capturing page snapshots, interacting with elements, and taking...
|
| 18 |
-
</p>
|
| 19 |
-
</div>
|
| 20 |
-
|
| 21 |
-
<!-- Bottom stats section -->
|
| 22 |
-
<div class="mt-6 pt-4 border-t border-gray-200">
|
| 23 |
-
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
|
| 24 |
-
<!-- Classification -->
|
| 25 |
-
<div>
|
| 26 |
-
<p class="text-12 font-semibold text-pulse-black uppercase tracking-wide mb-1">Classification</p>
|
| 27 |
-
<div class="flex items-center gap-2">
|
| 28 |
-
<div class="w-4 h-4 flex-shrink-0">
|
| 29 |
-
<img class="w-4 h-4" alt="Official repository icon" src="https://storage.googleapis.com/pulse_public/static/official-repo-icon.svg" />
|
| 30 |
-
</div>
|
| 31 |
-
<p class="text-14 capitalize text-pulse-black">official</p>
|
| 32 |
-
</div>
|
| 33 |
-
</div>
|
| 34 |
-
|
| 35 |
-
<!-- Visitors -->
|
| 36 |
-
<div>
|
| 37 |
-
<p class="text-12 font-semibold text-pulse-black uppercase tracking-wide mb-1">
|
| 38 |
-
Est Visitors (Week)
|
| 39 |
-
</p>
|
| 40 |
-
<p class="text-14 text-pulse-black">
|
| 41 |
-
2.5m
|
| 42 |
-
</p>
|
| 43 |
-
</div>
|
| 44 |
-
|
| 45 |
-
<!-- Release Date -->
|
| 46 |
-
<div>
|
| 47 |
-
<p class="text-12 font-semibold text-pulse-black uppercase tracking-wide mb-1">Release Date</p>
|
| 48 |
-
<p class="text-14 text-pulse-black">
|
| 49 |
-
Mar 22, 2025
|
| 50 |
-
</p>
|
| 51 |
-
</div>
|
| 52 |
-
</div>
|
| 53 |
-
</div>
|
| 54 |
-
</div>
|
| 55 |
-
</div>
|
| 56 |
-
|
| 57 |
-
</a>
|
| 58 |
-
<a href="/servers/ktanaka101-duckdb">
|
| 59 |
-
<div class="relative flex flex-col rounded border border-pulse-gray-border h-full hover:border-pulse-purple hover:shadow-lg transition-all duration-300 bg-white" data-test-id="mcp-server-card-ktanaka101-duckdb">
|
| 60 |
-
|
| 61 |
-
<div class="flex flex-col h-full p-6">
|
| 62 |
-
<!-- Header section -->
|
| 63 |
-
<div class="flex-grow">
|
| 64 |
-
<div class="flex items-center gap-3 mb-2">
|
| 65 |
-
<h3 class="text-20 text-pulse-black font-sans font-normal leading-tight">
|
| 66 |
-
DuckDB
|
| 67 |
-
</h3>
|
| 68 |
-
</div>
|
| 69 |
-
|
| 70 |
-
<p class="text-14 text-gray-500 mb-3">ktanaka101</p>
|
| 71 |
-
|
| 72 |
-
<p class="text-15 text-pulse-black leading-relaxed">
|
| 73 |
-
Execute SQL queries and analyze data in DuckDB databases.
|
| 74 |
-
</p>
|
| 75 |
-
</div>
|
| 76 |
-
|
| 77 |
-
<!-- Bottom stats section -->
|
| 78 |
-
<div class="mt-6 pt-4 border-t border-gray-200">
|
| 79 |
-
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
|
| 80 |
-
<!-- Classification -->
|
| 81 |
-
<div>
|
| 82 |
-
<p class="text-12 font-semibold text-pulse-black uppercase tracking-wide mb-1">Classification</p>
|
| 83 |
-
<div class="flex items-center gap-2">
|
| 84 |
-
<div class="w-4 h-4 flex-shrink-0">
|
| 85 |
-
<img class="w-4 h-4" alt="Community icon" src="https://storage.googleapis.com/pulse_public/static/community-icon.svg" />
|
| 86 |
-
</div>
|
| 87 |
-
<p class="text-14 capitalize text-pulse-black">community</p>
|
| 88 |
-
</div>
|
| 89 |
-
</div>
|
| 90 |
-
|
| 91 |
-
<!-- Visitors -->
|
| 92 |
-
<div>
|
| 93 |
-
<p class="text-12 font-semibold text-pulse-black uppercase tracking-wide mb-1">
|
| 94 |
-
Est Visitors (Week)
|
| 95 |
-
</p>
|
| 96 |
-
<p class="text-14 text-pulse-black">
|
| 97 |
-
1.7m
|
| 98 |
-
</p>
|
| 99 |
-
</div>
|
| 100 |
-
|
| 101 |
-
<!-- Release Date -->
|
| 102 |
-
<div>
|
| 103 |
-
<p class="text-12 font-semibold text-pulse-black uppercase tracking-wide mb-1">Release Date</p>
|
| 104 |
-
<p class="text-14 text-pulse-black">
|
| 105 |
-
Nov 30, 2024
|
| 106 |
-
</p>
|
| 107 |
-
</div>
|
| 108 |
-
</div>
|
| 109 |
-
</div>
|
| 110 |
-
</div>
|
| 111 |
-
</div>
|
| 112 |
-
|
| 113 |
-
</a>
|
| 114 |
-
<a href="/servers/haris-musa-excel">
|
| 115 |
-
<div class="relative flex flex-col rounded border border-pulse-gray-border h-full hover:border-pulse-purple hover:shadow-lg transition-all duration-300 bg-white" data-test-id="mcp-server-card-haris-musa-excel">
|
| 116 |
-
|
| 117 |
-
<div class="flex flex-col h-full p-6">
|
| 118 |
-
<!-- Header section -->
|
| 119 |
-
<div class="flex-grow">
|
| 120 |
-
<div class="flex items-center gap-3 mb-2">
|
| 121 |
-
<h3 class="text-20 text-pulse-black font-sans font-normal leading-tight">
|
| 122 |
-
Excel File Manipulation
|
| 123 |
-
</h3>
|
| 124 |
-
</div>
|
| 125 |
-
|
| 126 |
-
<p class="text-14 text-gray-500 mb-3">Haris Musa</p>
|
| 127 |
-
|
| 128 |
-
<p class="text-15 text-pulse-black leading-relaxed">
|
| 129 |
-
Enables Excel file manipulation without Microsoft Excel installation using openpyxl, providing workbook operations,...
|
| 130 |
-
</p>
|
| 131 |
-
</div>
|
| 132 |
-
|
| 133 |
-
<!-- Bottom stats section -->
|
| 134 |
-
<div class="mt-6 pt-4 border-t border-gray-200">
|
| 135 |
-
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
|
| 136 |
-
<!-- Classification -->
|
| 137 |
-
<div>
|
| 138 |
-
<p class="text-12 font-semibold text-pulse-black uppercase tracking-wide mb-1">Classification</p>
|
| 139 |
-
<div class="flex items-center gap-2">
|
| 140 |
-
<div class="w-4 h-4 flex-shrink-0">
|
| 141 |
-
<img class="w-4 h-4" alt="Community icon" src="https://storage.googleapis.com/pulse_public/static/community-icon.svg" />
|
| 142 |
-
</div>
|
| 143 |
-
<p class="text-14 capitalize text-pulse-black">community</p>
|
| 144 |
-
</div>
|
| 145 |
-
</div>
|
| 146 |
-
|
| 147 |
-
<!-- Visitors -->
|
| 148 |
-
<div>
|
| 149 |
-
<p class="text-12 font-semibold text-pulse-black uppercase tracking-wide mb-1">
|
| 150 |
-
Est Visitors (Week)
|
| 151 |
-
</p>
|
| 152 |
-
<p class="text-14 text-pulse-black">
|
| 153 |
-
1.6m
|
| 154 |
-
</p>
|
| 155 |
-
</div>
|
| 156 |
-
|
| 157 |
-
<!-- Release Date -->
|
| 158 |
-
<div>
|
| 159 |
-
<p class="text-12 font-semibold text-pulse-black uppercase tracking-wide mb-1">Release Date</p>
|
| 160 |
-
<p class="text-14 text-pulse-black">
|
| 161 |
-
Feb 12, 2025
|
| 162 |
-
</p>
|
| 163 |
-
</div>
|
| 164 |
-
</div>
|
| 165 |
-
</div>
|
| 166 |
-
</div>
|
| 167 |
-
</div>
|
| 168 |
-
|
| 169 |
-
</a>
|
| 170 |
-
</div>
|
|
|
|
| 1 |
+
<div class="servers-listing">
|
| 2 |
+
<a href="/servers/microsoft-playwright">
|
| 3 |
+
<div class="relative flex flex-col rounded border border-pulse-gray-border h-full hover:border-pulse-purple hover:shadow-lg transition-all duration-300 bg-white" data-test-id="mcp-server-card-microsoft-playwright">
|
| 4 |
+
|
| 5 |
+
<div class="flex flex-col h-full p-6">
|
| 6 |
+
<!-- Header section -->
|
| 7 |
+
<div class="flex-grow">
|
| 8 |
+
<div class="flex items-center gap-3 mb-2">
|
| 9 |
+
<h3 class="text-20 text-pulse-black font-sans font-normal leading-tight">
|
| 10 |
+
Playwright Browser Automation
|
| 11 |
+
</h3>
|
| 12 |
+
</div>
|
| 13 |
+
|
| 14 |
+
<p class="text-14 text-gray-500 mb-3">Microsoft</p>
|
| 15 |
+
|
| 16 |
+
<p class="text-15 text-pulse-black leading-relaxed">
|
| 17 |
+
Enables web browser control for navigating websites, capturing page snapshots, interacting with elements, and taking...
|
| 18 |
+
</p>
|
| 19 |
+
</div>
|
| 20 |
+
|
| 21 |
+
<!-- Bottom stats section -->
|
| 22 |
+
<div class="mt-6 pt-4 border-t border-gray-200">
|
| 23 |
+
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
|
| 24 |
+
<!-- Classification -->
|
| 25 |
+
<div>
|
| 26 |
+
<p class="text-12 font-semibold text-pulse-black uppercase tracking-wide mb-1">Classification</p>
|
| 27 |
+
<div class="flex items-center gap-2">
|
| 28 |
+
<div class="w-4 h-4 flex-shrink-0">
|
| 29 |
+
<img class="w-4 h-4" alt="Official repository icon" src="https://storage.googleapis.com/pulse_public/static/official-repo-icon.svg" />
|
| 30 |
+
</div>
|
| 31 |
+
<p class="text-14 capitalize text-pulse-black">official</p>
|
| 32 |
+
</div>
|
| 33 |
+
</div>
|
| 34 |
+
|
| 35 |
+
<!-- Visitors -->
|
| 36 |
+
<div>
|
| 37 |
+
<p class="text-12 font-semibold text-pulse-black uppercase tracking-wide mb-1">
|
| 38 |
+
Est Visitors (Week)
|
| 39 |
+
</p>
|
| 40 |
+
<p class="text-14 text-pulse-black">
|
| 41 |
+
2.5m
|
| 42 |
+
</p>
|
| 43 |
+
</div>
|
| 44 |
+
|
| 45 |
+
<!-- Release Date -->
|
| 46 |
+
<div>
|
| 47 |
+
<p class="text-12 font-semibold text-pulse-black uppercase tracking-wide mb-1">Release Date</p>
|
| 48 |
+
<p class="text-14 text-pulse-black">
|
| 49 |
+
Mar 22, 2025
|
| 50 |
+
</p>
|
| 51 |
+
</div>
|
| 52 |
+
</div>
|
| 53 |
+
</div>
|
| 54 |
+
</div>
|
| 55 |
+
</div>
|
| 56 |
+
|
| 57 |
+
</a>
|
| 58 |
+
<a href="/servers/ktanaka101-duckdb">
|
| 59 |
+
<div class="relative flex flex-col rounded border border-pulse-gray-border h-full hover:border-pulse-purple hover:shadow-lg transition-all duration-300 bg-white" data-test-id="mcp-server-card-ktanaka101-duckdb">
|
| 60 |
+
|
| 61 |
+
<div class="flex flex-col h-full p-6">
|
| 62 |
+
<!-- Header section -->
|
| 63 |
+
<div class="flex-grow">
|
| 64 |
+
<div class="flex items-center gap-3 mb-2">
|
| 65 |
+
<h3 class="text-20 text-pulse-black font-sans font-normal leading-tight">
|
| 66 |
+
DuckDB
|
| 67 |
+
</h3>
|
| 68 |
+
</div>
|
| 69 |
+
|
| 70 |
+
<p class="text-14 text-gray-500 mb-3">ktanaka101</p>
|
| 71 |
+
|
| 72 |
+
<p class="text-15 text-pulse-black leading-relaxed">
|
| 73 |
+
Execute SQL queries and analyze data in DuckDB databases.
|
| 74 |
+
</p>
|
| 75 |
+
</div>
|
| 76 |
+
|
| 77 |
+
<!-- Bottom stats section -->
|
| 78 |
+
<div class="mt-6 pt-4 border-t border-gray-200">
|
| 79 |
+
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
|
| 80 |
+
<!-- Classification -->
|
| 81 |
+
<div>
|
| 82 |
+
<p class="text-12 font-semibold text-pulse-black uppercase tracking-wide mb-1">Classification</p>
|
| 83 |
+
<div class="flex items-center gap-2">
|
| 84 |
+
<div class="w-4 h-4 flex-shrink-0">
|
| 85 |
+
<img class="w-4 h-4" alt="Community icon" src="https://storage.googleapis.com/pulse_public/static/community-icon.svg" />
|
| 86 |
+
</div>
|
| 87 |
+
<p class="text-14 capitalize text-pulse-black">community</p>
|
| 88 |
+
</div>
|
| 89 |
+
</div>
|
| 90 |
+
|
| 91 |
+
<!-- Visitors -->
|
| 92 |
+
<div>
|
| 93 |
+
<p class="text-12 font-semibold text-pulse-black uppercase tracking-wide mb-1">
|
| 94 |
+
Est Visitors (Week)
|
| 95 |
+
</p>
|
| 96 |
+
<p class="text-14 text-pulse-black">
|
| 97 |
+
1.7m
|
| 98 |
+
</p>
|
| 99 |
+
</div>
|
| 100 |
+
|
| 101 |
+
<!-- Release Date -->
|
| 102 |
+
<div>
|
| 103 |
+
<p class="text-12 font-semibold text-pulse-black uppercase tracking-wide mb-1">Release Date</p>
|
| 104 |
+
<p class="text-14 text-pulse-black">
|
| 105 |
+
Nov 30, 2024
|
| 106 |
+
</p>
|
| 107 |
+
</div>
|
| 108 |
+
</div>
|
| 109 |
+
</div>
|
| 110 |
+
</div>
|
| 111 |
+
</div>
|
| 112 |
+
|
| 113 |
+
</a>
|
| 114 |
+
<a href="/servers/haris-musa-excel">
|
| 115 |
+
<div class="relative flex flex-col rounded border border-pulse-gray-border h-full hover:border-pulse-purple hover:shadow-lg transition-all duration-300 bg-white" data-test-id="mcp-server-card-haris-musa-excel">
|
| 116 |
+
|
| 117 |
+
<div class="flex flex-col h-full p-6">
|
| 118 |
+
<!-- Header section -->
|
| 119 |
+
<div class="flex-grow">
|
| 120 |
+
<div class="flex items-center gap-3 mb-2">
|
| 121 |
+
<h3 class="text-20 text-pulse-black font-sans font-normal leading-tight">
|
| 122 |
+
Excel File Manipulation
|
| 123 |
+
</h3>
|
| 124 |
+
</div>
|
| 125 |
+
|
| 126 |
+
<p class="text-14 text-gray-500 mb-3">Haris Musa</p>
|
| 127 |
+
|
| 128 |
+
<p class="text-15 text-pulse-black leading-relaxed">
|
| 129 |
+
Enables Excel file manipulation without Microsoft Excel installation using openpyxl, providing workbook operations,...
|
| 130 |
+
</p>
|
| 131 |
+
</div>
|
| 132 |
+
|
| 133 |
+
<!-- Bottom stats section -->
|
| 134 |
+
<div class="mt-6 pt-4 border-t border-gray-200">
|
| 135 |
+
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
|
| 136 |
+
<!-- Classification -->
|
| 137 |
+
<div>
|
| 138 |
+
<p class="text-12 font-semibold text-pulse-black uppercase tracking-wide mb-1">Classification</p>
|
| 139 |
+
<div class="flex items-center gap-2">
|
| 140 |
+
<div class="w-4 h-4 flex-shrink-0">
|
| 141 |
+
<img class="w-4 h-4" alt="Community icon" src="https://storage.googleapis.com/pulse_public/static/community-icon.svg" />
|
| 142 |
+
</div>
|
| 143 |
+
<p class="text-14 capitalize text-pulse-black">community</p>
|
| 144 |
+
</div>
|
| 145 |
+
</div>
|
| 146 |
+
|
| 147 |
+
<!-- Visitors -->
|
| 148 |
+
<div>
|
| 149 |
+
<p class="text-12 font-semibold text-pulse-black uppercase tracking-wide mb-1">
|
| 150 |
+
Est Visitors (Week)
|
| 151 |
+
</p>
|
| 152 |
+
<p class="text-14 text-pulse-black">
|
| 153 |
+
1.6m
|
| 154 |
+
</p>
|
| 155 |
+
</div>
|
| 156 |
+
|
| 157 |
+
<!-- Release Date -->
|
| 158 |
+
<div>
|
| 159 |
+
<p class="text-12 font-semibold text-pulse-black uppercase tracking-wide mb-1">Release Date</p>
|
| 160 |
+
<p class="text-14 text-pulse-black">
|
| 161 |
+
Feb 12, 2025
|
| 162 |
+
</p>
|
| 163 |
+
</div>
|
| 164 |
+
</div>
|
| 165 |
+
</div>
|
| 166 |
+
</div>
|
| 167 |
+
</div>
|
| 168 |
+
|
| 169 |
+
</a>
|
| 170 |
+
</div>
|
src/tests/test_agent_add.py
CHANGED
|
@@ -1,217 +1,217 @@
|
|
| 1 |
-
"""Tests for agent_add existing-update review behavior."""
|
| 2 |
-
|
| 3 |
-
from __future__ import annotations
|
| 4 |
-
|
| 5 |
-
import sys
|
| 6 |
-
from pathlib import Path
|
| 7 |
-
from typing import Any
|
| 8 |
-
from unittest.mock import MagicMock
|
| 9 |
-
|
| 10 |
-
SRC_DIR = Path(__file__).resolve().parents[1]
|
| 11 |
-
if str(SRC_DIR) not in sys.path:
|
| 12 |
-
sys.path.insert(0, str(SRC_DIR))
|
| 13 |
-
|
| 14 |
-
import agent_add # noqa: E402
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
class _Decision:
|
| 18 |
-
allow = True
|
| 19 |
-
warnings: tuple[Any, ...] = ()
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
def _agent_text(
|
| 23 |
-
*,
|
| 24 |
-
description: str = "Agent that reviews code changes with clear findings.",
|
| 25 |
-
model: str = "inherit",
|
| 26 |
-
body: str | None = None,
|
| 27 |
-
) -> str:
|
| 28 |
-
body = body or (
|
| 29 |
-
"This agent reviews code and reports concrete risks.\n\n"
|
| 30 |
-
"## Review Process\n\n"
|
| 31 |
-
"Read the diff, identify regressions, and return prioritized findings."
|
| 32 |
-
)
|
| 33 |
-
return "\n".join(
|
| 34 |
-
[
|
| 35 |
-
"---",
|
| 36 |
-
"name: reviewer-agent",
|
| 37 |
-
f"description: {description}",
|
| 38 |
-
f"model: {model}",
|
| 39 |
-
"---",
|
| 40 |
-
"# reviewer-agent",
|
| 41 |
-
"",
|
| 42 |
-
body,
|
| 43 |
-
]
|
| 44 |
-
)
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
def _setup_paths(tmp_path: Path) -> tuple[Path, Path, Path]:
|
| 48 |
-
wiki = tmp_path / "wiki"
|
| 49 |
-
agents_dir = tmp_path / "agents"
|
| 50 |
-
source = tmp_path / "reviewer-agent.md"
|
| 51 |
-
(wiki / "entities" / "agents").mkdir(parents=True)
|
| 52 |
-
agents_dir.mkdir(parents=True)
|
| 53 |
-
return wiki, agents_dir, source
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
def _patch_side_effects(monkeypatch: Any) -> MagicMock:
|
| 57 |
-
check = MagicMock(return_value=_Decision())
|
| 58 |
-
monkeypatch.setattr(agent_add, "check_intake", check)
|
| 59 |
-
monkeypatch.setattr(agent_add, "record_embedding", MagicMock())
|
| 60 |
-
monkeypatch.setattr(agent_add, "update_index", MagicMock())
|
| 61 |
-
monkeypatch.setattr(agent_add, "append_log", MagicMock())
|
| 62 |
-
monkeypatch.setattr(agent_add, "ensure_wiki", MagicMock())
|
| 63 |
-
return check
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
def test_existing_agent_review_skips_without_mutating_files(
|
| 67 |
-
tmp_path: Path,
|
| 68 |
-
monkeypatch: Any,
|
| 69 |
-
) -> None:
|
| 70 |
-
wiki, agents_dir, source = _setup_paths(tmp_path)
|
| 71 |
-
installed = agents_dir / "reviewer-agent.md"
|
| 72 |
-
existing_text = _agent_text(
|
| 73 |
-
description="Detailed agent with a conservative review process.",
|
| 74 |
-
model="sonnet",
|
| 75 |
-
)
|
| 76 |
-
installed.write_text(existing_text, encoding="utf-8")
|
| 77 |
-
entity = wiki / "entities" / "agents" / "reviewer-agent.md"
|
| 78 |
-
entity.write_text(
|
| 79 |
-
agent_add.generate_agent_page("reviewer-agent", installed),
|
| 80 |
-
encoding="utf-8",
|
| 81 |
-
)
|
| 82 |
-
entity_text = entity.read_text(encoding="utf-8")
|
| 83 |
-
source.write_text(
|
| 84 |
-
_agent_text(description="Short agent.", model="haiku"),
|
| 85 |
-
encoding="utf-8",
|
| 86 |
-
)
|
| 87 |
-
check = _patch_side_effects(monkeypatch)
|
| 88 |
-
|
| 89 |
-
result = agent_add.add_agent(
|
| 90 |
-
source_path=source,
|
| 91 |
-
name="reviewer-agent",
|
| 92 |
-
wiki_path=wiki,
|
| 93 |
-
agents_dir=agents_dir,
|
| 94 |
-
review_existing=True,
|
| 95 |
-
)
|
| 96 |
-
|
| 97 |
-
assert result["skipped"] is True
|
| 98 |
-
assert result["update_required"] is True
|
| 99 |
-
assert "Existing agent already exists: reviewer-agent" in result["update_review"]
|
| 100 |
-
assert "Changed frontmatter fields:" in result["update_review"]
|
| 101 |
-
assert "model" in result["update_review"]
|
| 102 |
-
assert installed.read_text(encoding="utf-8") == existing_text
|
| 103 |
-
assert entity.read_text(encoding="utf-8") == entity_text
|
| 104 |
-
check.assert_not_called()
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
def test_existing_agent_update_existing_applies_change(
|
| 108 |
-
tmp_path: Path,
|
| 109 |
-
monkeypatch: Any,
|
| 110 |
-
) -> None:
|
| 111 |
-
wiki, agents_dir, source = _setup_paths(tmp_path)
|
| 112 |
-
installed = agents_dir / "reviewer-agent.md"
|
| 113 |
-
installed.write_text(_agent_text(), encoding="utf-8")
|
| 114 |
-
entity = wiki / "entities" / "agents" / "reviewer-agent.md"
|
| 115 |
-
entity.write_text("# existing entity\n", encoding="utf-8")
|
| 116 |
-
updated_text = _agent_text(
|
| 117 |
-
description="Updated agent with stronger review coverage.",
|
| 118 |
-
model="opus",
|
| 119 |
-
)
|
| 120 |
-
source.write_text(updated_text, encoding="utf-8")
|
| 121 |
-
_patch_side_effects(monkeypatch)
|
| 122 |
-
|
| 123 |
-
result = agent_add.add_agent(
|
| 124 |
-
source_path=source,
|
| 125 |
-
name="reviewer-agent",
|
| 126 |
-
wiki_path=wiki,
|
| 127 |
-
agents_dir=agents_dir,
|
| 128 |
-
review_existing=True,
|
| 129 |
-
update_existing=True,
|
| 130 |
-
)
|
| 131 |
-
|
| 132 |
-
assert result["skipped"] is False
|
| 133 |
-
assert result["update_required"] is False
|
| 134 |
-
assert result["is_new_page"] is False
|
| 135 |
-
assert installed.read_text(encoding="utf-8") == updated_text
|
| 136 |
-
assert "Updated agent with stronger review coverage" in entity.read_text(
|
| 137 |
-
encoding="utf-8"
|
| 138 |
-
)
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
def test_new_agent_add_writes_converted_agent_mirror(
|
| 142 |
-
tmp_path: Path,
|
| 143 |
-
monkeypatch: Any,
|
| 144 |
-
) -> None:
|
| 145 |
-
wiki, agents_dir, source = _setup_paths(tmp_path)
|
| 146 |
-
source_text = _agent_text(description="Installable mirrored agent.")
|
| 147 |
-
source.write_text(source_text, encoding="utf-8")
|
| 148 |
-
_patch_side_effects(monkeypatch)
|
| 149 |
-
|
| 150 |
-
result = agent_add.add_agent(
|
| 151 |
-
source_path=source,
|
| 152 |
-
name="reviewer-agent",
|
| 153 |
-
wiki_path=wiki,
|
| 154 |
-
agents_dir=agents_dir,
|
| 155 |
-
)
|
| 156 |
-
|
| 157 |
-
mirror = wiki / "converted-agents" / "reviewer-agent.md"
|
| 158 |
-
assert result["is_new_page"] is True
|
| 159 |
-
assert mirror.read_text(encoding="utf-8") == source_text
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
def test_existing_agent_update_refreshes_converted_agent_mirror(
|
| 163 |
-
tmp_path: Path,
|
| 164 |
-
monkeypatch: Any,
|
| 165 |
-
) -> None:
|
| 166 |
-
wiki, agents_dir, source = _setup_paths(tmp_path)
|
| 167 |
-
installed = agents_dir / "reviewer-agent.md"
|
| 168 |
-
installed.write_text(_agent_text(), encoding="utf-8")
|
| 169 |
-
mirror = wiki / "converted-agents" / "reviewer-agent.md"
|
| 170 |
-
mirror.parent.mkdir(parents=True)
|
| 171 |
-
mirror.write_text("old mirror\n", encoding="utf-8")
|
| 172 |
-
entity = wiki / "entities" / "agents" / "reviewer-agent.md"
|
| 173 |
-
entity.write_text("# existing entity\n", encoding="utf-8")
|
| 174 |
-
updated_text = _agent_text(description="Updated mirrored agent.")
|
| 175 |
-
source.write_text(updated_text, encoding="utf-8")
|
| 176 |
-
_patch_side_effects(monkeypatch)
|
| 177 |
-
|
| 178 |
-
result = agent_add.add_agent(
|
| 179 |
-
source_path=source,
|
| 180 |
-
name="reviewer-agent",
|
| 181 |
-
wiki_path=wiki,
|
| 182 |
-
agents_dir=agents_dir,
|
| 183 |
-
review_existing=True,
|
| 184 |
-
update_existing=True,
|
| 185 |
-
)
|
| 186 |
-
|
| 187 |
-
assert result["is_new_page"] is False
|
| 188 |
-
assert mirror.read_text(encoding="utf-8") == updated_text
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
def test_main_existing_agent_prints_update_review(
|
| 192 |
-
tmp_path: Path,
|
| 193 |
-
monkeypatch: Any,
|
| 194 |
-
capsys: Any,
|
| 195 |
-
) -> None:
|
| 196 |
-
wiki, agents_dir, source = _setup_paths(tmp_path)
|
| 197 |
-
installed = agents_dir / "reviewer-agent.md"
|
| 198 |
-
installed.write_text(_agent_text(), encoding="utf-8")
|
| 199 |
-
source.write_text(
|
| 200 |
-
_agent_text(description="Replacement agent."),
|
| 201 |
-
encoding="utf-8",
|
| 202 |
-
)
|
| 203 |
-
_patch_side_effects(monkeypatch)
|
| 204 |
-
monkeypatch.setattr(sys, "argv", [
|
| 205 |
-
"agent_add.py",
|
| 206 |
-
"--agent-path", str(source),
|
| 207 |
-
"--name", "reviewer-agent",
|
| 208 |
-
"--wiki", str(wiki),
|
| 209 |
-
"--agents-dir", str(agents_dir),
|
| 210 |
-
])
|
| 211 |
-
|
| 212 |
-
agent_add.main()
|
| 213 |
-
|
| 214 |
-
out = capsys.readouterr().out
|
| 215 |
-
assert "Existing agent already exists: reviewer-agent" in out
|
| 216 |
-
assert "Use the explicit update flag" in out
|
| 217 |
-
assert "Replacement agent." not in installed.read_text(encoding="utf-8")
|
|
|
|
| 1 |
+
"""Tests for agent_add existing-update review behavior."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any
|
| 8 |
+
from unittest.mock import MagicMock
|
| 9 |
+
|
| 10 |
+
SRC_DIR = Path(__file__).resolve().parents[1]
|
| 11 |
+
if str(SRC_DIR) not in sys.path:
|
| 12 |
+
sys.path.insert(0, str(SRC_DIR))
|
| 13 |
+
|
| 14 |
+
import agent_add # noqa: E402
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class _Decision:
|
| 18 |
+
allow = True
|
| 19 |
+
warnings: tuple[Any, ...] = ()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _agent_text(
|
| 23 |
+
*,
|
| 24 |
+
description: str = "Agent that reviews code changes with clear findings.",
|
| 25 |
+
model: str = "inherit",
|
| 26 |
+
body: str | None = None,
|
| 27 |
+
) -> str:
|
| 28 |
+
body = body or (
|
| 29 |
+
"This agent reviews code and reports concrete risks.\n\n"
|
| 30 |
+
"## Review Process\n\n"
|
| 31 |
+
"Read the diff, identify regressions, and return prioritized findings."
|
| 32 |
+
)
|
| 33 |
+
return "\n".join(
|
| 34 |
+
[
|
| 35 |
+
"---",
|
| 36 |
+
"name: reviewer-agent",
|
| 37 |
+
f"description: {description}",
|
| 38 |
+
f"model: {model}",
|
| 39 |
+
"---",
|
| 40 |
+
"# reviewer-agent",
|
| 41 |
+
"",
|
| 42 |
+
body,
|
| 43 |
+
]
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _setup_paths(tmp_path: Path) -> tuple[Path, Path, Path]:
|
| 48 |
+
wiki = tmp_path / "wiki"
|
| 49 |
+
agents_dir = tmp_path / "agents"
|
| 50 |
+
source = tmp_path / "reviewer-agent.md"
|
| 51 |
+
(wiki / "entities" / "agents").mkdir(parents=True)
|
| 52 |
+
agents_dir.mkdir(parents=True)
|
| 53 |
+
return wiki, agents_dir, source
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _patch_side_effects(monkeypatch: Any) -> MagicMock:
|
| 57 |
+
check = MagicMock(return_value=_Decision())
|
| 58 |
+
monkeypatch.setattr(agent_add, "check_intake", check)
|
| 59 |
+
monkeypatch.setattr(agent_add, "record_embedding", MagicMock())
|
| 60 |
+
monkeypatch.setattr(agent_add, "update_index", MagicMock())
|
| 61 |
+
monkeypatch.setattr(agent_add, "append_log", MagicMock())
|
| 62 |
+
monkeypatch.setattr(agent_add, "ensure_wiki", MagicMock())
|
| 63 |
+
return check
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_existing_agent_review_skips_without_mutating_files(
|
| 67 |
+
tmp_path: Path,
|
| 68 |
+
monkeypatch: Any,
|
| 69 |
+
) -> None:
|
| 70 |
+
wiki, agents_dir, source = _setup_paths(tmp_path)
|
| 71 |
+
installed = agents_dir / "reviewer-agent.md"
|
| 72 |
+
existing_text = _agent_text(
|
| 73 |
+
description="Detailed agent with a conservative review process.",
|
| 74 |
+
model="sonnet",
|
| 75 |
+
)
|
| 76 |
+
installed.write_text(existing_text, encoding="utf-8")
|
| 77 |
+
entity = wiki / "entities" / "agents" / "reviewer-agent.md"
|
| 78 |
+
entity.write_text(
|
| 79 |
+
agent_add.generate_agent_page("reviewer-agent", installed),
|
| 80 |
+
encoding="utf-8",
|
| 81 |
+
)
|
| 82 |
+
entity_text = entity.read_text(encoding="utf-8")
|
| 83 |
+
source.write_text(
|
| 84 |
+
_agent_text(description="Short agent.", model="haiku"),
|
| 85 |
+
encoding="utf-8",
|
| 86 |
+
)
|
| 87 |
+
check = _patch_side_effects(monkeypatch)
|
| 88 |
+
|
| 89 |
+
result = agent_add.add_agent(
|
| 90 |
+
source_path=source,
|
| 91 |
+
name="reviewer-agent",
|
| 92 |
+
wiki_path=wiki,
|
| 93 |
+
agents_dir=agents_dir,
|
| 94 |
+
review_existing=True,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
assert result["skipped"] is True
|
| 98 |
+
assert result["update_required"] is True
|
| 99 |
+
assert "Existing agent already exists: reviewer-agent" in result["update_review"]
|
| 100 |
+
assert "Changed frontmatter fields:" in result["update_review"]
|
| 101 |
+
assert "model" in result["update_review"]
|
| 102 |
+
assert installed.read_text(encoding="utf-8") == existing_text
|
| 103 |
+
assert entity.read_text(encoding="utf-8") == entity_text
|
| 104 |
+
check.assert_not_called()
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def test_existing_agent_update_existing_applies_change(
|
| 108 |
+
tmp_path: Path,
|
| 109 |
+
monkeypatch: Any,
|
| 110 |
+
) -> None:
|
| 111 |
+
wiki, agents_dir, source = _setup_paths(tmp_path)
|
| 112 |
+
installed = agents_dir / "reviewer-agent.md"
|
| 113 |
+
installed.write_text(_agent_text(), encoding="utf-8")
|
| 114 |
+
entity = wiki / "entities" / "agents" / "reviewer-agent.md"
|
| 115 |
+
entity.write_text("# existing entity\n", encoding="utf-8")
|
| 116 |
+
updated_text = _agent_text(
|
| 117 |
+
description="Updated agent with stronger review coverage.",
|
| 118 |
+
model="opus",
|
| 119 |
+
)
|
| 120 |
+
source.write_text(updated_text, encoding="utf-8")
|
| 121 |
+
_patch_side_effects(monkeypatch)
|
| 122 |
+
|
| 123 |
+
result = agent_add.add_agent(
|
| 124 |
+
source_path=source,
|
| 125 |
+
name="reviewer-agent",
|
| 126 |
+
wiki_path=wiki,
|
| 127 |
+
agents_dir=agents_dir,
|
| 128 |
+
review_existing=True,
|
| 129 |
+
update_existing=True,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
assert result["skipped"] is False
|
| 133 |
+
assert result["update_required"] is False
|
| 134 |
+
assert result["is_new_page"] is False
|
| 135 |
+
assert installed.read_text(encoding="utf-8") == updated_text
|
| 136 |
+
assert "Updated agent with stronger review coverage" in entity.read_text(
|
| 137 |
+
encoding="utf-8"
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def test_new_agent_add_writes_converted_agent_mirror(
|
| 142 |
+
tmp_path: Path,
|
| 143 |
+
monkeypatch: Any,
|
| 144 |
+
) -> None:
|
| 145 |
+
wiki, agents_dir, source = _setup_paths(tmp_path)
|
| 146 |
+
source_text = _agent_text(description="Installable mirrored agent.")
|
| 147 |
+
source.write_text(source_text, encoding="utf-8")
|
| 148 |
+
_patch_side_effects(monkeypatch)
|
| 149 |
+
|
| 150 |
+
result = agent_add.add_agent(
|
| 151 |
+
source_path=source,
|
| 152 |
+
name="reviewer-agent",
|
| 153 |
+
wiki_path=wiki,
|
| 154 |
+
agents_dir=agents_dir,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
mirror = wiki / "converted-agents" / "reviewer-agent.md"
|
| 158 |
+
assert result["is_new_page"] is True
|
| 159 |
+
assert mirror.read_text(encoding="utf-8") == source_text
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def test_existing_agent_update_refreshes_converted_agent_mirror(
|
| 163 |
+
tmp_path: Path,
|
| 164 |
+
monkeypatch: Any,
|
| 165 |
+
) -> None:
|
| 166 |
+
wiki, agents_dir, source = _setup_paths(tmp_path)
|
| 167 |
+
installed = agents_dir / "reviewer-agent.md"
|
| 168 |
+
installed.write_text(_agent_text(), encoding="utf-8")
|
| 169 |
+
mirror = wiki / "converted-agents" / "reviewer-agent.md"
|
| 170 |
+
mirror.parent.mkdir(parents=True)
|
| 171 |
+
mirror.write_text("old mirror\n", encoding="utf-8")
|
| 172 |
+
entity = wiki / "entities" / "agents" / "reviewer-agent.md"
|
| 173 |
+
entity.write_text("# existing entity\n", encoding="utf-8")
|
| 174 |
+
updated_text = _agent_text(description="Updated mirrored agent.")
|
| 175 |
+
source.write_text(updated_text, encoding="utf-8")
|
| 176 |
+
_patch_side_effects(monkeypatch)
|
| 177 |
+
|
| 178 |
+
result = agent_add.add_agent(
|
| 179 |
+
source_path=source,
|
| 180 |
+
name="reviewer-agent",
|
| 181 |
+
wiki_path=wiki,
|
| 182 |
+
agents_dir=agents_dir,
|
| 183 |
+
review_existing=True,
|
| 184 |
+
update_existing=True,
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
assert result["is_new_page"] is False
|
| 188 |
+
assert mirror.read_text(encoding="utf-8") == updated_text
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def test_main_existing_agent_prints_update_review(
|
| 192 |
+
tmp_path: Path,
|
| 193 |
+
monkeypatch: Any,
|
| 194 |
+
capsys: Any,
|
| 195 |
+
) -> None:
|
| 196 |
+
wiki, agents_dir, source = _setup_paths(tmp_path)
|
| 197 |
+
installed = agents_dir / "reviewer-agent.md"
|
| 198 |
+
installed.write_text(_agent_text(), encoding="utf-8")
|
| 199 |
+
source.write_text(
|
| 200 |
+
_agent_text(description="Replacement agent."),
|
| 201 |
+
encoding="utf-8",
|
| 202 |
+
)
|
| 203 |
+
_patch_side_effects(monkeypatch)
|
| 204 |
+
monkeypatch.setattr(sys, "argv", [
|
| 205 |
+
"agent_add.py",
|
| 206 |
+
"--agent-path", str(source),
|
| 207 |
+
"--name", "reviewer-agent",
|
| 208 |
+
"--wiki", str(wiki),
|
| 209 |
+
"--agents-dir", str(agents_dir),
|
| 210 |
+
])
|
| 211 |
+
|
| 212 |
+
agent_add.main()
|
| 213 |
+
|
| 214 |
+
out = capsys.readouterr().out
|
| 215 |
+
assert "Existing agent already exists: reviewer-agent" in out
|
| 216 |
+
assert "Use the explicit update flag" in out
|
| 217 |
+
assert "Replacement agent." not in installed.read_text(encoding="utf-8")
|
src/tests/test_artifact_promotion.py
CHANGED
|
@@ -1,143 +1,143 @@
|
|
| 1 |
-
from __future__ import annotations
|
| 2 |
-
|
| 3 |
-
import gzip
|
| 4 |
-
import json
|
| 5 |
-
from datetime import datetime, timezone
|
| 6 |
-
from pathlib import Path
|
| 7 |
-
|
| 8 |
-
import pytest
|
| 9 |
-
|
| 10 |
-
from ctx.core.wiki import artifact_promotion
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
def test_promote_staged_artifact_validates_replaces_and_records_metadata(
|
| 14 |
-
tmp_path: Path,
|
| 15 |
-
) -> None:
|
| 16 |
-
target = tmp_path / "artifact.txt"
|
| 17 |
-
staged = tmp_path / "candidate.txt"
|
| 18 |
-
target.write_bytes(b"old\n")
|
| 19 |
-
staged.write_bytes(b"new\n")
|
| 20 |
-
validated: list[Path] = []
|
| 21 |
-
|
| 22 |
-
result = artifact_promotion.promote_staged_artifact(
|
| 23 |
-
staged,
|
| 24 |
-
target,
|
| 25 |
-
validate=lambda path: validated.append(path),
|
| 26 |
-
now=datetime(2026, 5, 4, tzinfo=timezone.utc),
|
| 27 |
-
)
|
| 28 |
-
|
| 29 |
-
metadata = json.loads(result.metadata_path.read_text(encoding="utf-8"))
|
| 30 |
-
assert validated == [staged]
|
| 31 |
-
assert target.read_bytes() == b"new\n"
|
| 32 |
-
assert not staged.exists()
|
| 33 |
-
assert metadata["status"] == "promoted"
|
| 34 |
-
assert metadata["previous"]["exists"] is True
|
| 35 |
-
assert metadata["previous"]["size"] == 4
|
| 36 |
-
assert metadata["candidate"]["size"] == 4
|
| 37 |
-
assert metadata["current"]["sha256"] == metadata["candidate"]["sha256"]
|
| 38 |
-
assert metadata["last_good"] == metadata["previous"]
|
| 39 |
-
assert metadata["rollback"]["available"] is True
|
| 40 |
-
assert metadata["rollback"]["sha256"] == metadata["previous"]["sha256"]
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
def test_promote_staged_artifact_validation_failure_preserves_target(
|
| 44 |
-
tmp_path: Path,
|
| 45 |
-
) -> None:
|
| 46 |
-
target = tmp_path / "artifact.txt"
|
| 47 |
-
staged = tmp_path / "candidate.txt"
|
| 48 |
-
target.write_bytes(b"old\n")
|
| 49 |
-
staged.write_bytes(b"new\n")
|
| 50 |
-
|
| 51 |
-
def fail_validation(_path: Path) -> None:
|
| 52 |
-
raise ValueError("candidate failed validation")
|
| 53 |
-
|
| 54 |
-
with pytest.raises(ValueError, match="candidate failed validation"):
|
| 55 |
-
artifact_promotion.promote_staged_artifact(
|
| 56 |
-
staged,
|
| 57 |
-
target,
|
| 58 |
-
validate=fail_validation,
|
| 59 |
-
)
|
| 60 |
-
|
| 61 |
-
assert target.read_bytes() == b"old\n"
|
| 62 |
-
assert staged.exists()
|
| 63 |
-
assert not target.with_name("artifact.txt.promotion.json").exists()
|
| 64 |
-
|
| 65 |
-
malformed_json = tmp_path / "broken.json"
|
| 66 |
-
malformed_json.write_text("{", encoding="utf-8")
|
| 67 |
-
with pytest.raises(ValueError, match="invalid JSON artifact"):
|
| 68 |
-
artifact_promotion.validate_json_artifact(malformed_json)
|
| 69 |
-
|
| 70 |
-
truncated_gzip = tmp_path / "broken.json.gz"
|
| 71 |
-
truncated_gzip.write_bytes(b"\x1f\x8b")
|
| 72 |
-
with pytest.raises(ValueError, match="invalid gzip JSON artifact"):
|
| 73 |
-
artifact_promotion.validate_gzip_json_artifact(truncated_gzip)
|
| 74 |
-
|
| 75 |
-
valid_gzip = tmp_path / "catalog.json.gz"
|
| 76 |
-
with gzip.open(valid_gzip, "wt", encoding="utf-8") as fh:
|
| 77 |
-
json.dump({"skills": []}, fh)
|
| 78 |
-
artifact_promotion.validate_gzip_json_artifact(valid_gzip, required_keys=("skills",))
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
def test_promote_staged_artifact_replace_failure_preserves_target_and_last_good(
|
| 82 |
-
tmp_path: Path,
|
| 83 |
-
monkeypatch: pytest.MonkeyPatch,
|
| 84 |
-
) -> None:
|
| 85 |
-
target = tmp_path / "artifact.txt"
|
| 86 |
-
staged = tmp_path / "candidate.txt"
|
| 87 |
-
target.write_bytes(b"old\n")
|
| 88 |
-
staged.write_bytes(b"new\n")
|
| 89 |
-
|
| 90 |
-
def locked_replace(_src: Path, _dst: Path) -> None:
|
| 91 |
-
raise PermissionError("locked")
|
| 92 |
-
|
| 93 |
-
monkeypatch.setattr(artifact_promotion, "_replace_with_retry", locked_replace)
|
| 94 |
-
|
| 95 |
-
with pytest.raises(PermissionError, match="locked"):
|
| 96 |
-
artifact_promotion.promote_staged_artifact(staged, target)
|
| 97 |
-
|
| 98 |
-
metadata = json.loads(
|
| 99 |
-
target.with_name("artifact.txt.promotion.json").read_text(encoding="utf-8")
|
| 100 |
-
)
|
| 101 |
-
assert target.read_bytes() == b"old\n"
|
| 102 |
-
assert staged.exists()
|
| 103 |
-
assert metadata["status"] == "staged"
|
| 104 |
-
assert metadata["previous"]["sha256"] != metadata["candidate"]["sha256"]
|
| 105 |
-
assert metadata["last_good"] == metadata["previous"]
|
| 106 |
-
assert metadata["rollback"]["available"] is True
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
def test_promote_staged_artifact_recovers_after_post_replace_crash(
|
| 110 |
-
tmp_path: Path,
|
| 111 |
-
) -> None:
|
| 112 |
-
target = tmp_path / "artifact.txt"
|
| 113 |
-
staged = tmp_path / "candidate.txt"
|
| 114 |
-
metadata_path = target.with_name("artifact.txt.promotion.json")
|
| 115 |
-
target.write_bytes(b"new\n")
|
| 116 |
-
candidate = artifact_promotion._snapshot(target)
|
| 117 |
-
previous = {
|
| 118 |
-
"path": str(target),
|
| 119 |
-
"exists": True,
|
| 120 |
-
"size": 4,
|
| 121 |
-
"sha256": "old-sha",
|
| 122 |
-
"mtime_ns": 1,
|
| 123 |
-
}
|
| 124 |
-
metadata_path.write_text(
|
| 125 |
-
json.dumps({
|
| 126 |
-
"schema_version": 1,
|
| 127 |
-
"status": "staged",
|
| 128 |
-
"target": str(target),
|
| 129 |
-
"started_at": "2026-05-04T00:00:00+00:00",
|
| 130 |
-
"previous": previous,
|
| 131 |
-
"candidate": candidate,
|
| 132 |
-
}),
|
| 133 |
-
encoding="utf-8",
|
| 134 |
-
)
|
| 135 |
-
|
| 136 |
-
result = artifact_promotion.promote_staged_artifact(staged, target)
|
| 137 |
-
|
| 138 |
-
metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
|
| 139 |
-
assert result.current["sha256"] == candidate["sha256"]
|
| 140 |
-
assert metadata["status"] == "promoted"
|
| 141 |
-
assert metadata["previous"] == previous
|
| 142 |
-
assert metadata["candidate"]["sha256"] == candidate["sha256"]
|
| 143 |
-
assert metadata["current"]["sha256"] == candidate["sha256"]
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import gzip
|
| 4 |
+
import json
|
| 5 |
+
from datetime import datetime, timezone
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
from ctx.core.wiki import artifact_promotion
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def test_promote_staged_artifact_validates_replaces_and_records_metadata(
|
| 14 |
+
tmp_path: Path,
|
| 15 |
+
) -> None:
|
| 16 |
+
target = tmp_path / "artifact.txt"
|
| 17 |
+
staged = tmp_path / "candidate.txt"
|
| 18 |
+
target.write_bytes(b"old\n")
|
| 19 |
+
staged.write_bytes(b"new\n")
|
| 20 |
+
validated: list[Path] = []
|
| 21 |
+
|
| 22 |
+
result = artifact_promotion.promote_staged_artifact(
|
| 23 |
+
staged,
|
| 24 |
+
target,
|
| 25 |
+
validate=lambda path: validated.append(path),
|
| 26 |
+
now=datetime(2026, 5, 4, tzinfo=timezone.utc),
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
metadata = json.loads(result.metadata_path.read_text(encoding="utf-8"))
|
| 30 |
+
assert validated == [staged]
|
| 31 |
+
assert target.read_bytes() == b"new\n"
|
| 32 |
+
assert not staged.exists()
|
| 33 |
+
assert metadata["status"] == "promoted"
|
| 34 |
+
assert metadata["previous"]["exists"] is True
|
| 35 |
+
assert metadata["previous"]["size"] == 4
|
| 36 |
+
assert metadata["candidate"]["size"] == 4
|
| 37 |
+
assert metadata["current"]["sha256"] == metadata["candidate"]["sha256"]
|
| 38 |
+
assert metadata["last_good"] == metadata["previous"]
|
| 39 |
+
assert metadata["rollback"]["available"] is True
|
| 40 |
+
assert metadata["rollback"]["sha256"] == metadata["previous"]["sha256"]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_promote_staged_artifact_validation_failure_preserves_target(
|
| 44 |
+
tmp_path: Path,
|
| 45 |
+
) -> None:
|
| 46 |
+
target = tmp_path / "artifact.txt"
|
| 47 |
+
staged = tmp_path / "candidate.txt"
|
| 48 |
+
target.write_bytes(b"old\n")
|
| 49 |
+
staged.write_bytes(b"new\n")
|
| 50 |
+
|
| 51 |
+
def fail_validation(_path: Path) -> None:
|
| 52 |
+
raise ValueError("candidate failed validation")
|
| 53 |
+
|
| 54 |
+
with pytest.raises(ValueError, match="candidate failed validation"):
|
| 55 |
+
artifact_promotion.promote_staged_artifact(
|
| 56 |
+
staged,
|
| 57 |
+
target,
|
| 58 |
+
validate=fail_validation,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
assert target.read_bytes() == b"old\n"
|
| 62 |
+
assert staged.exists()
|
| 63 |
+
assert not target.with_name("artifact.txt.promotion.json").exists()
|
| 64 |
+
|
| 65 |
+
malformed_json = tmp_path / "broken.json"
|
| 66 |
+
malformed_json.write_text("{", encoding="utf-8")
|
| 67 |
+
with pytest.raises(ValueError, match="invalid JSON artifact"):
|
| 68 |
+
artifact_promotion.validate_json_artifact(malformed_json)
|
| 69 |
+
|
| 70 |
+
truncated_gzip = tmp_path / "broken.json.gz"
|
| 71 |
+
truncated_gzip.write_bytes(b"\x1f\x8b")
|
| 72 |
+
with pytest.raises(ValueError, match="invalid gzip JSON artifact"):
|
| 73 |
+
artifact_promotion.validate_gzip_json_artifact(truncated_gzip)
|
| 74 |
+
|
| 75 |
+
valid_gzip = tmp_path / "catalog.json.gz"
|
| 76 |
+
with gzip.open(valid_gzip, "wt", encoding="utf-8") as fh:
|
| 77 |
+
json.dump({"skills": []}, fh)
|
| 78 |
+
artifact_promotion.validate_gzip_json_artifact(valid_gzip, required_keys=("skills",))
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def test_promote_staged_artifact_replace_failure_preserves_target_and_last_good(
|
| 82 |
+
tmp_path: Path,
|
| 83 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 84 |
+
) -> None:
|
| 85 |
+
target = tmp_path / "artifact.txt"
|
| 86 |
+
staged = tmp_path / "candidate.txt"
|
| 87 |
+
target.write_bytes(b"old\n")
|
| 88 |
+
staged.write_bytes(b"new\n")
|
| 89 |
+
|
| 90 |
+
def locked_replace(_src: Path, _dst: Path) -> None:
|
| 91 |
+
raise PermissionError("locked")
|
| 92 |
+
|
| 93 |
+
monkeypatch.setattr(artifact_promotion, "_replace_with_retry", locked_replace)
|
| 94 |
+
|
| 95 |
+
with pytest.raises(PermissionError, match="locked"):
|
| 96 |
+
artifact_promotion.promote_staged_artifact(staged, target)
|
| 97 |
+
|
| 98 |
+
metadata = json.loads(
|
| 99 |
+
target.with_name("artifact.txt.promotion.json").read_text(encoding="utf-8")
|
| 100 |
+
)
|
| 101 |
+
assert target.read_bytes() == b"old\n"
|
| 102 |
+
assert staged.exists()
|
| 103 |
+
assert metadata["status"] == "staged"
|
| 104 |
+
assert metadata["previous"]["sha256"] != metadata["candidate"]["sha256"]
|
| 105 |
+
assert metadata["last_good"] == metadata["previous"]
|
| 106 |
+
assert metadata["rollback"]["available"] is True
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def test_promote_staged_artifact_recovers_after_post_replace_crash(
|
| 110 |
+
tmp_path: Path,
|
| 111 |
+
) -> None:
|
| 112 |
+
target = tmp_path / "artifact.txt"
|
| 113 |
+
staged = tmp_path / "candidate.txt"
|
| 114 |
+
metadata_path = target.with_name("artifact.txt.promotion.json")
|
| 115 |
+
target.write_bytes(b"new\n")
|
| 116 |
+
candidate = artifact_promotion._snapshot(target)
|
| 117 |
+
previous = {
|
| 118 |
+
"path": str(target),
|
| 119 |
+
"exists": True,
|
| 120 |
+
"size": 4,
|
| 121 |
+
"sha256": "old-sha",
|
| 122 |
+
"mtime_ns": 1,
|
| 123 |
+
}
|
| 124 |
+
metadata_path.write_text(
|
| 125 |
+
json.dumps({
|
| 126 |
+
"schema_version": 1,
|
| 127 |
+
"status": "staged",
|
| 128 |
+
"target": str(target),
|
| 129 |
+
"started_at": "2026-05-04T00:00:00+00:00",
|
| 130 |
+
"previous": previous,
|
| 131 |
+
"candidate": candidate,
|
| 132 |
+
}),
|
| 133 |
+
encoding="utf-8",
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
result = artifact_promotion.promote_staged_artifact(staged, target)
|
| 137 |
+
|
| 138 |
+
metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
|
| 139 |
+
assert result.current["sha256"] == candidate["sha256"]
|
| 140 |
+
assert metadata["status"] == "promoted"
|
| 141 |
+
assert metadata["previous"] == previous
|
| 142 |
+
assert metadata["candidate"]["sha256"] == candidate["sha256"]
|
| 143 |
+
assert metadata["current"]["sha256"] == candidate["sha256"]
|
src/tests/test_bundle_orchestrator.py
CHANGED
|
@@ -1,42 +1,42 @@
|
|
| 1 |
-
"""
|
| 2 |
-
test_bundle_orchestrator.py -- pins the cross-type bundle contract.
|
| 3 |
-
|
| 4 |
Covers:
|
| 5 |
- categorise_bundle: top-K across all types (not per-type), preserves
|
| 6 |
graph-score order within each type, supports all-one-type and mixed.
|
| 7 |
-
- render_bundle_message: categorised output with install-cli hints,
|
| 8 |
-
omits empty type sections, includes unmatched signals + unload block.
|
| 9 |
-
- main(): reads pending-skills.json, caps at cfg.recommendation_top_k,
|
| 10 |
-
emits the Claude Code hook JSON envelope.
|
| 11 |
-
- Backward compat: skill_suggest.py shim still calls the new main().
|
| 12 |
-
"""
|
| 13 |
-
|
| 14 |
-
from __future__ import annotations
|
| 15 |
-
|
| 16 |
-
import json
|
| 17 |
-
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]))
|
| 24 |
-
|
| 25 |
-
from ctx.adapters.claude_code.hooks import bundle_orchestrator as _bo
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
# ────────────────────────────────────────────────────────────────────
|
| 29 |
-
# categorise_bundle — top-K is TOTAL, not per-type
|
| 30 |
-
# ────────────────────────────────────────────────────────────────────
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
class TestCategoriseBundle:
|
| 34 |
-
def _sug(self, *entries) -> list[dict]:
|
| 35 |
-
return [
|
| 36 |
-
{"name": n, "type": t, "score": s, "matching_tags": ["x"]}
|
| 37 |
-
for n, t, s in entries
|
| 38 |
-
]
|
| 39 |
-
|
| 40 |
def test_bundle_excludes_harnesses_from_execution_bundle(self):
|
| 41 |
"""Harnesses are recommended by model onboarding, not hook bundles."""
|
| 42 |
sugs = self._sug(
|
|
@@ -51,58 +51,58 @@ class TestCategoriseBundle:
|
|
| 51 |
assert len(grouped["agent"]) == 1
|
| 52 |
assert len(grouped["mcp-server"]) == 1
|
| 53 |
assert "harness" not in grouped
|
| 54 |
-
|
| 55 |
-
def test_bundle_can_be_single_type(self):
|
| 56 |
-
"""If the top-K entries are all skills, the bundle contains only
|
| 57 |
-
skills — agents/MCPs lists are empty (caller omits their headers)."""
|
| 58 |
-
sugs = self._sug(
|
| 59 |
-
("python-a", "skill", 90),
|
| 60 |
-
("python-b", "skill", 85),
|
| 61 |
-
("python-c", "skill", 80),
|
| 62 |
-
)
|
| 63 |
grouped = _bo.categorise_bundle(sugs, top_k=5)
|
| 64 |
assert len(grouped["skill"]) == 3
|
| 65 |
assert grouped["agent"] == []
|
| 66 |
assert grouped["mcp-server"] == []
|
| 67 |
-
|
| 68 |
-
def test_top_k_is_total_not_per_type(self):
|
| 69 |
-
"""top_k=5 with 10 skills available returns 5 skills TOTAL,
|
| 70 |
-
not 5 per type. User ask: 'don't show a lot of options'."""
|
| 71 |
-
sugs = self._sug(*[(f"skill-{i}", "skill", 100 - i) for i in range(10)])
|
| 72 |
-
grouped = _bo.categorise_bundle(sugs, top_k=5)
|
| 73 |
-
assert sum(len(v) for v in grouped.values()) == 5
|
| 74 |
-
|
| 75 |
-
def test_input_order_preserved_within_type(self):
|
| 76 |
-
"""Graph-score order from context_monitor.graph_suggest is
|
| 77 |
-
authoritative. categorise_bundle must not re-sort."""
|
| 78 |
-
sugs = self._sug(
|
| 79 |
-
("alpha", "skill", 99),
|
| 80 |
-
("beta", "skill", 50),
|
| 81 |
-
("gamma", "skill", 70),
|
| 82 |
-
)
|
| 83 |
-
grouped = _bo.categorise_bundle(sugs, top_k=5)
|
| 84 |
-
names = [e["name"] for e in grouped["skill"]]
|
| 85 |
-
# Called input order: alpha, beta, gamma -- caller has already
|
| 86 |
-
# sorted by score. categorise_bundle preserves that order.
|
| 87 |
-
assert names == ["alpha", "beta", "gamma"]
|
| 88 |
-
|
| 89 |
-
def test_top_k_one(self):
|
| 90 |
-
"""Edge case: top_k=1 returns one entry total."""
|
| 91 |
-
sugs = self._sug(
|
| 92 |
-
("skill-a", "skill", 90),
|
| 93 |
-
("agent-a", "agent", 85),
|
| 94 |
-
)
|
| 95 |
-
grouped = _bo.categorise_bundle(sugs, top_k=1)
|
| 96 |
-
assert sum(len(v) for v in grouped.values()) == 1
|
| 97 |
-
|
| 98 |
-
def test_empty_input(self):
|
| 99 |
grouped = _bo.categorise_bundle([], top_k=5)
|
| 100 |
assert grouped == {
|
| 101 |
"skill": [],
|
| 102 |
"agent": [],
|
| 103 |
"mcp-server": [],
|
| 104 |
}
|
| 105 |
-
|
| 106 |
def test_unknown_type_is_ignored(self):
|
| 107 |
"""A suggestion with an unexpected ``type`` value doesn't crash
|
| 108 |
the categoriser; it is skipped. Defensive — the
|
|
@@ -112,21 +112,21 @@ class TestCategoriseBundle:
|
|
| 112 |
grouped = _bo.categorise_bundle(sugs, top_k=5)
|
| 113 |
assert "future-type" not in grouped
|
| 114 |
assert sum(len(v) for v in grouped.values()) == 0
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
# ────────────────────────────────────────────────────────────────────
|
| 118 |
-
# render_bundle_message — user-facing layout
|
| 119 |
-
# ────────────────────────────────────────────────────────────────────
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
class TestRenderBundleMessage:
|
| 123 |
-
def _sug(self, *entries) -> list[dict]:
|
| 124 |
-
return [
|
| 125 |
-
{"name": n, "type": t, "score": s, "matching_tags": ["stack-x"]}
|
| 126 |
-
for n, t, s in entries
|
| 127 |
-
]
|
| 128 |
-
|
| 129 |
-
def test_categorised_headers_only_for_types_with_entries(self):
|
| 130 |
"""Skills/Agents/MCPs headers appear ONLY when that type has
|
| 131 |
entries in the bundle. Empty sections are omitted so the user
|
| 132 |
doesn't see dead headers."""
|
|
@@ -154,69 +154,69 @@ class TestRenderBundleMessage:
|
|
| 154 |
msg = _bo.render_bundle_message(sugs, [], [], top_k=5)
|
| 155 |
assert "Suggested bundle" not in msg
|
| 156 |
assert "langgraph" not in msg
|
| 157 |
-
|
| 158 |
-
def test_unmatched_signals_surfaced(self):
|
| 159 |
-
msg = _bo.render_bundle_message([], ["fastapi", "docker"], [], top_k=5)
|
| 160 |
-
assert "Unmatched signals" in msg
|
| 161 |
-
assert "fastapi" in msg
|
| 162 |
-
assert "docker" in msg
|
| 163 |
-
|
| 164 |
-
def test_unload_block_separate_from_bundle(self):
|
| 165 |
-
unload = [{"name": "old-skill", "reason": "unused for 30 days"}]
|
| 166 |
-
msg = _bo.render_bundle_message([], [], unload, top_k=5)
|
| 167 |
-
assert "loaded but never used" in msg
|
| 168 |
-
assert "old-skill" in msg
|
| 169 |
-
|
| 170 |
-
def test_empty_everything_yields_empty_message(self):
|
| 171 |
-
assert _bo.render_bundle_message([], [], [], top_k=5).strip() == ""
|
| 172 |
-
|
| 173 |
-
def test_top_k_enforced_in_render(self):
|
| 174 |
-
"""If input has 10 suggestions but top_k=3, only 3 show."""
|
| 175 |
-
sugs = self._sug(*[(f"s-{i}", "skill", 100 - i) for i in range(10)])
|
| 176 |
-
msg = _bo.render_bundle_message(sugs, [], [], top_k=3)
|
| 177 |
-
# Count the bullet lines that start with "- " (our bundle-item marker).
|
| 178 |
-
item_lines = [line for line in msg.splitlines() if line.strip().startswith("- ")]
|
| 179 |
-
assert len(item_lines) == 3
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
# ────────────────────────────────────────────────────────────────────
|
| 183 |
-
# main() — reads pending files, emits Claude-Code hook payload
|
| 184 |
-
# ────────────────────────────────────────────────────────────────────
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
class TestMainEndToEnd:
|
| 188 |
-
def _setup_paths(self, tmp_path, monkeypatch):
|
| 189 |
-
monkeypatch.setattr(_bo, "CLAUDE_DIR", tmp_path)
|
| 190 |
-
monkeypatch.setattr(_bo, "PENDING_SKILLS", tmp_path / "pending-skills.json")
|
| 191 |
-
monkeypatch.setattr(_bo, "PENDING_UNLOAD", tmp_path / "pending-unload.json")
|
| 192 |
-
monkeypatch.setattr(_bo, "SHOWN_FLAG", tmp_path / ".bundle-shown")
|
| 193 |
-
|
| 194 |
-
def test_no_pending_exits_0(self, tmp_path, monkeypatch):
|
| 195 |
-
self._setup_paths(tmp_path, monkeypatch)
|
| 196 |
-
with pytest.raises(SystemExit) as exc:
|
| 197 |
-
_bo.main()
|
| 198 |
-
assert exc.value.code == 0
|
| 199 |
-
|
| 200 |
def test_pending_with_bundle_emits_hook_json(
|
| 201 |
self, tmp_path, monkeypatch, capsys,
|
| 202 |
):
|
| 203 |
-
self._setup_paths(tmp_path, monkeypatch)
|
| 204 |
-
pending = {
|
| 205 |
-
"generated_at": datetime.now(timezone.utc).isoformat(),
|
| 206 |
-
"unmatched_signals": ["fastapi"],
|
| 207 |
-
"graph_suggestions": [
|
| 208 |
-
{"name": "fastapi-pro", "type": "skill", "score": 90,
|
| 209 |
-
"matching_tags": ["fastapi"]},
|
| 210 |
{"name": "anthropic-python-sdk", "type": "mcp-server",
|
| 211 |
"score": 75, "matching_tags": []},
|
| 212 |
],
|
| 213 |
}
|
| 214 |
-
(tmp_path / "pending-skills.json").write_text(json.dumps(pending))
|
| 215 |
-
|
| 216 |
-
_bo.main()
|
| 217 |
-
out = capsys.readouterr().out.strip()
|
| 218 |
-
payload = json.loads(out)
|
| 219 |
-
assert payload["hookSpecificOutput"]["hookEventName"] == "PostToolUse"
|
| 220 |
msg = payload["hookSpecificOutput"]["additionalContext"]
|
| 221 |
assert "fastapi-pro" in msg
|
| 222 |
assert "anthropic-python-sdk" in msg
|
|
@@ -245,69 +245,69 @@ class TestMainEndToEnd:
|
|
| 245 |
|
| 246 |
def test_already_shown_suppresses_output(
|
| 247 |
self, tmp_path, monkeypatch, capsys,
|
| 248 |
-
):
|
| 249 |
-
"""Second invocation in the same session doesn't re-emit."""
|
| 250 |
-
self._setup_paths(tmp_path, monkeypatch)
|
| 251 |
-
pending_at = datetime.now(timezone.utc).isoformat()
|
| 252 |
-
(tmp_path / "pending-skills.json").write_text(json.dumps({
|
| 253 |
-
"generated_at": pending_at,
|
| 254 |
-
"unmatched_signals": ["x"],
|
| 255 |
-
"graph_suggestions": [
|
| 256 |
-
{"name": "a", "type": "skill", "score": 50, "matching_tags": []},
|
| 257 |
-
],
|
| 258 |
-
}))
|
| 259 |
-
# Pre-mark shown with a timestamp AFTER pending_at so the guard trips.
|
| 260 |
-
later = datetime.now(timezone.utc).isoformat()
|
| 261 |
-
(tmp_path / ".bundle-shown").write_text(json.dumps({"shown_at": later}))
|
| 262 |
-
|
| 263 |
-
with pytest.raises(SystemExit) as exc:
|
| 264 |
-
_bo.main()
|
| 265 |
-
assert exc.value.code == 0
|
| 266 |
-
assert capsys.readouterr().out == ""
|
| 267 |
-
|
| 268 |
-
def test_top_k_from_config(self, tmp_path, monkeypatch, capsys):
|
| 269 |
-
"""A user override of recommendation_top_k in config propagates."""
|
| 270 |
-
self._setup_paths(tmp_path, monkeypatch)
|
| 271 |
-
|
| 272 |
-
# Monkey-patch the lazy ctx_config import path used inside _top_k.
|
| 273 |
-
import ctx_config as _cfg_mod
|
| 274 |
-
monkeypatch.setattr(_cfg_mod.cfg, "recommendation_top_k", 2)
|
| 275 |
-
|
| 276 |
-
pending = {
|
| 277 |
-
"generated_at": datetime.now(timezone.utc).isoformat(),
|
| 278 |
-
"unmatched_signals": [],
|
| 279 |
-
"graph_suggestions": [
|
| 280 |
-
{"name": f"s-{i}", "type": "skill", "score": 100 - i, "matching_tags": []}
|
| 281 |
-
for i in range(10)
|
| 282 |
-
],
|
| 283 |
-
}
|
| 284 |
-
(tmp_path / "pending-skills.json").write_text(json.dumps(pending))
|
| 285 |
-
|
| 286 |
-
_bo.main()
|
| 287 |
-
out = capsys.readouterr().out
|
| 288 |
-
payload = json.loads(out.strip())
|
| 289 |
-
msg = payload["hookSpecificOutput"]["additionalContext"]
|
| 290 |
-
item_lines = [line for line in msg.splitlines() if line.strip().startswith("- ")]
|
| 291 |
-
assert len(item_lines) == 2, f"expected top_k=2 cap, got {len(item_lines)}"
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
# ────────────────────────────────────────────────────────────────────
|
| 295 |
-
# Backward-compat: skill_suggest shim
|
| 296 |
-
# ────────────────────────────────────────────────────────────────────
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
class TestSkillSuggestShim:
|
| 300 |
-
"""skill_suggest.py must remain importable and call through to
|
| 301 |
-
bundle_orchestrator.main — otherwise existing ~/.claude/settings.json
|
| 302 |
-
hook configs that invoke ``python skill_suggest.py`` break silently."""
|
| 303 |
-
|
| 304 |
-
def test_shim_re_exports_main(self):
|
| 305 |
-
from ctx.adapters.claude_code.hooks import skill_suggest
|
| 306 |
-
# The shim re-imports main from bundle_orchestrator. The function
|
| 307 |
-
# object must be the SAME instance to guarantee behavioural parity.
|
| 308 |
-
assert skill_suggest.main is _bo.main
|
| 309 |
-
|
| 310 |
-
def test_shim_re_exports_constants(self):
|
| 311 |
-
from ctx.adapters.claude_code.hooks import skill_suggest
|
| 312 |
-
assert skill_suggest.PENDING_SKILLS == _bo.PENDING_SKILLS
|
| 313 |
-
assert skill_suggest.PENDING_UNLOAD == _bo.PENDING_UNLOAD
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_bundle_orchestrator.py -- pins the cross-type bundle contract.
|
| 3 |
+
|
| 4 |
Covers:
|
| 5 |
- categorise_bundle: top-K across all types (not per-type), preserves
|
| 6 |
graph-score order within each type, supports all-one-type and mixed.
|
| 7 |
+
- render_bundle_message: categorised output with install-cli hints,
|
| 8 |
+
omits empty type sections, includes unmatched signals + unload block.
|
| 9 |
+
- main(): reads pending-skills.json, caps at cfg.recommendation_top_k,
|
| 10 |
+
emits the Claude Code hook JSON envelope.
|
| 11 |
+
- Backward compat: skill_suggest.py shim still calls the new main().
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
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]))
|
| 24 |
+
|
| 25 |
+
from ctx.adapters.claude_code.hooks import bundle_orchestrator as _bo
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# ────────────────────────────────────────────────────────────────────
|
| 29 |
+
# categorise_bundle — top-K is TOTAL, not per-type
|
| 30 |
+
# ────────────────────────────────────────────────────────────────────
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class TestCategoriseBundle:
|
| 34 |
+
def _sug(self, *entries) -> list[dict]:
|
| 35 |
+
return [
|
| 36 |
+
{"name": n, "type": t, "score": s, "matching_tags": ["x"]}
|
| 37 |
+
for n, t, s in entries
|
| 38 |
+
]
|
| 39 |
+
|
| 40 |
def test_bundle_excludes_harnesses_from_execution_bundle(self):
|
| 41 |
"""Harnesses are recommended by model onboarding, not hook bundles."""
|
| 42 |
sugs = self._sug(
|
|
|
|
| 51 |
assert len(grouped["agent"]) == 1
|
| 52 |
assert len(grouped["mcp-server"]) == 1
|
| 53 |
assert "harness" not in grouped
|
| 54 |
+
|
| 55 |
+
def test_bundle_can_be_single_type(self):
|
| 56 |
+
"""If the top-K entries are all skills, the bundle contains only
|
| 57 |
+
skills — agents/MCPs lists are empty (caller omits their headers)."""
|
| 58 |
+
sugs = self._sug(
|
| 59 |
+
("python-a", "skill", 90),
|
| 60 |
+
("python-b", "skill", 85),
|
| 61 |
+
("python-c", "skill", 80),
|
| 62 |
+
)
|
| 63 |
grouped = _bo.categorise_bundle(sugs, top_k=5)
|
| 64 |
assert len(grouped["skill"]) == 3
|
| 65 |
assert grouped["agent"] == []
|
| 66 |
assert grouped["mcp-server"] == []
|
| 67 |
+
|
| 68 |
+
def test_top_k_is_total_not_per_type(self):
|
| 69 |
+
"""top_k=5 with 10 skills available returns 5 skills TOTAL,
|
| 70 |
+
not 5 per type. User ask: 'don't show a lot of options'."""
|
| 71 |
+
sugs = self._sug(*[(f"skill-{i}", "skill", 100 - i) for i in range(10)])
|
| 72 |
+
grouped = _bo.categorise_bundle(sugs, top_k=5)
|
| 73 |
+
assert sum(len(v) for v in grouped.values()) == 5
|
| 74 |
+
|
| 75 |
+
def test_input_order_preserved_within_type(self):
|
| 76 |
+
"""Graph-score order from context_monitor.graph_suggest is
|
| 77 |
+
authoritative. categorise_bundle must not re-sort."""
|
| 78 |
+
sugs = self._sug(
|
| 79 |
+
("alpha", "skill", 99),
|
| 80 |
+
("beta", "skill", 50),
|
| 81 |
+
("gamma", "skill", 70),
|
| 82 |
+
)
|
| 83 |
+
grouped = _bo.categorise_bundle(sugs, top_k=5)
|
| 84 |
+
names = [e["name"] for e in grouped["skill"]]
|
| 85 |
+
# Called input order: alpha, beta, gamma -- caller has already
|
| 86 |
+
# sorted by score. categorise_bundle preserves that order.
|
| 87 |
+
assert names == ["alpha", "beta", "gamma"]
|
| 88 |
+
|
| 89 |
+
def test_top_k_one(self):
|
| 90 |
+
"""Edge case: top_k=1 returns one entry total."""
|
| 91 |
+
sugs = self._sug(
|
| 92 |
+
("skill-a", "skill", 90),
|
| 93 |
+
("agent-a", "agent", 85),
|
| 94 |
+
)
|
| 95 |
+
grouped = _bo.categorise_bundle(sugs, top_k=1)
|
| 96 |
+
assert sum(len(v) for v in grouped.values()) == 1
|
| 97 |
+
|
| 98 |
+
def test_empty_input(self):
|
| 99 |
grouped = _bo.categorise_bundle([], top_k=5)
|
| 100 |
assert grouped == {
|
| 101 |
"skill": [],
|
| 102 |
"agent": [],
|
| 103 |
"mcp-server": [],
|
| 104 |
}
|
| 105 |
+
|
| 106 |
def test_unknown_type_is_ignored(self):
|
| 107 |
"""A suggestion with an unexpected ``type`` value doesn't crash
|
| 108 |
the categoriser; it is skipped. Defensive — the
|
|
|
|
| 112 |
grouped = _bo.categorise_bundle(sugs, top_k=5)
|
| 113 |
assert "future-type" not in grouped
|
| 114 |
assert sum(len(v) for v in grouped.values()) == 0
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
# ────────────────────────────────────────────────────────────────────
|
| 118 |
+
# render_bundle_message — user-facing layout
|
| 119 |
+
# ────────────────────────────────────────────────────────────────────
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class TestRenderBundleMessage:
|
| 123 |
+
def _sug(self, *entries) -> list[dict]:
|
| 124 |
+
return [
|
| 125 |
+
{"name": n, "type": t, "score": s, "matching_tags": ["stack-x"]}
|
| 126 |
+
for n, t, s in entries
|
| 127 |
+
]
|
| 128 |
+
|
| 129 |
+
def test_categorised_headers_only_for_types_with_entries(self):
|
| 130 |
"""Skills/Agents/MCPs headers appear ONLY when that type has
|
| 131 |
entries in the bundle. Empty sections are omitted so the user
|
| 132 |
doesn't see dead headers."""
|
|
|
|
| 154 |
msg = _bo.render_bundle_message(sugs, [], [], top_k=5)
|
| 155 |
assert "Suggested bundle" not in msg
|
| 156 |
assert "langgraph" not in msg
|
| 157 |
+
|
| 158 |
+
def test_unmatched_signals_surfaced(self):
|
| 159 |
+
msg = _bo.render_bundle_message([], ["fastapi", "docker"], [], top_k=5)
|
| 160 |
+
assert "Unmatched signals" in msg
|
| 161 |
+
assert "fastapi" in msg
|
| 162 |
+
assert "docker" in msg
|
| 163 |
+
|
| 164 |
+
def test_unload_block_separate_from_bundle(self):
|
| 165 |
+
unload = [{"name": "old-skill", "reason": "unused for 30 days"}]
|
| 166 |
+
msg = _bo.render_bundle_message([], [], unload, top_k=5)
|
| 167 |
+
assert "loaded but never used" in msg
|
| 168 |
+
assert "old-skill" in msg
|
| 169 |
+
|
| 170 |
+
def test_empty_everything_yields_empty_message(self):
|
| 171 |
+
assert _bo.render_bundle_message([], [], [], top_k=5).strip() == ""
|
| 172 |
+
|
| 173 |
+
def test_top_k_enforced_in_render(self):
|
| 174 |
+
"""If input has 10 suggestions but top_k=3, only 3 show."""
|
| 175 |
+
sugs = self._sug(*[(f"s-{i}", "skill", 100 - i) for i in range(10)])
|
| 176 |
+
msg = _bo.render_bundle_message(sugs, [], [], top_k=3)
|
| 177 |
+
# Count the bullet lines that start with "- " (our bundle-item marker).
|
| 178 |
+
item_lines = [line for line in msg.splitlines() if line.strip().startswith("- ")]
|
| 179 |
+
assert len(item_lines) == 3
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
# ────────────────────────────────────────────────────────────────────
|
| 183 |
+
# main() — reads pending files, emits Claude-Code hook payload
|
| 184 |
+
# ────────────────────────────────────────────────────────────────────
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class TestMainEndToEnd:
|
| 188 |
+
def _setup_paths(self, tmp_path, monkeypatch):
|
| 189 |
+
monkeypatch.setattr(_bo, "CLAUDE_DIR", tmp_path)
|
| 190 |
+
monkeypatch.setattr(_bo, "PENDING_SKILLS", tmp_path / "pending-skills.json")
|
| 191 |
+
monkeypatch.setattr(_bo, "PENDING_UNLOAD", tmp_path / "pending-unload.json")
|
| 192 |
+
monkeypatch.setattr(_bo, "SHOWN_FLAG", tmp_path / ".bundle-shown")
|
| 193 |
+
|
| 194 |
+
def test_no_pending_exits_0(self, tmp_path, monkeypatch):
|
| 195 |
+
self._setup_paths(tmp_path, monkeypatch)
|
| 196 |
+
with pytest.raises(SystemExit) as exc:
|
| 197 |
+
_bo.main()
|
| 198 |
+
assert exc.value.code == 0
|
| 199 |
+
|
| 200 |
def test_pending_with_bundle_emits_hook_json(
|
| 201 |
self, tmp_path, monkeypatch, capsys,
|
| 202 |
):
|
| 203 |
+
self._setup_paths(tmp_path, monkeypatch)
|
| 204 |
+
pending = {
|
| 205 |
+
"generated_at": datetime.now(timezone.utc).isoformat(),
|
| 206 |
+
"unmatched_signals": ["fastapi"],
|
| 207 |
+
"graph_suggestions": [
|
| 208 |
+
{"name": "fastapi-pro", "type": "skill", "score": 90,
|
| 209 |
+
"matching_tags": ["fastapi"]},
|
| 210 |
{"name": "anthropic-python-sdk", "type": "mcp-server",
|
| 211 |
"score": 75, "matching_tags": []},
|
| 212 |
],
|
| 213 |
}
|
| 214 |
+
(tmp_path / "pending-skills.json").write_text(json.dumps(pending))
|
| 215 |
+
|
| 216 |
+
_bo.main()
|
| 217 |
+
out = capsys.readouterr().out.strip()
|
| 218 |
+
payload = json.loads(out)
|
| 219 |
+
assert payload["hookSpecificOutput"]["hookEventName"] == "PostToolUse"
|
| 220 |
msg = payload["hookSpecificOutput"]["additionalContext"]
|
| 221 |
assert "fastapi-pro" in msg
|
| 222 |
assert "anthropic-python-sdk" in msg
|
|
|
|
| 245 |
|
| 246 |
def test_already_shown_suppresses_output(
|
| 247 |
self, tmp_path, monkeypatch, capsys,
|
| 248 |
+
):
|
| 249 |
+
"""Second invocation in the same session doesn't re-emit."""
|
| 250 |
+
self._setup_paths(tmp_path, monkeypatch)
|
| 251 |
+
pending_at = datetime.now(timezone.utc).isoformat()
|
| 252 |
+
(tmp_path / "pending-skills.json").write_text(json.dumps({
|
| 253 |
+
"generated_at": pending_at,
|
| 254 |
+
"unmatched_signals": ["x"],
|
| 255 |
+
"graph_suggestions": [
|
| 256 |
+
{"name": "a", "type": "skill", "score": 50, "matching_tags": []},
|
| 257 |
+
],
|
| 258 |
+
}))
|
| 259 |
+
# Pre-mark shown with a timestamp AFTER pending_at so the guard trips.
|
| 260 |
+
later = datetime.now(timezone.utc).isoformat()
|
| 261 |
+
(tmp_path / ".bundle-shown").write_text(json.dumps({"shown_at": later}))
|
| 262 |
+
|
| 263 |
+
with pytest.raises(SystemExit) as exc:
|
| 264 |
+
_bo.main()
|
| 265 |
+
assert exc.value.code == 0
|
| 266 |
+
assert capsys.readouterr().out == ""
|
| 267 |
+
|
| 268 |
+
def test_top_k_from_config(self, tmp_path, monkeypatch, capsys):
|
| 269 |
+
"""A user override of recommendation_top_k in config propagates."""
|
| 270 |
+
self._setup_paths(tmp_path, monkeypatch)
|
| 271 |
+
|
| 272 |
+
# Monkey-patch the lazy ctx_config import path used inside _top_k.
|
| 273 |
+
import ctx_config as _cfg_mod
|
| 274 |
+
monkeypatch.setattr(_cfg_mod.cfg, "recommendation_top_k", 2)
|
| 275 |
+
|
| 276 |
+
pending = {
|
| 277 |
+
"generated_at": datetime.now(timezone.utc).isoformat(),
|
| 278 |
+
"unmatched_signals": [],
|
| 279 |
+
"graph_suggestions": [
|
| 280 |
+
{"name": f"s-{i}", "type": "skill", "score": 100 - i, "matching_tags": []}
|
| 281 |
+
for i in range(10)
|
| 282 |
+
],
|
| 283 |
+
}
|
| 284 |
+
(tmp_path / "pending-skills.json").write_text(json.dumps(pending))
|
| 285 |
+
|
| 286 |
+
_bo.main()
|
| 287 |
+
out = capsys.readouterr().out
|
| 288 |
+
payload = json.loads(out.strip())
|
| 289 |
+
msg = payload["hookSpecificOutput"]["additionalContext"]
|
| 290 |
+
item_lines = [line for line in msg.splitlines() if line.strip().startswith("- ")]
|
| 291 |
+
assert len(item_lines) == 2, f"expected top_k=2 cap, got {len(item_lines)}"
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
# ────────────────────────────────────────────────────────────────────
|
| 295 |
+
# Backward-compat: skill_suggest shim
|
| 296 |
+
# ────────────────────────────────────────────────────────────────────
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
class TestSkillSuggestShim:
|
| 300 |
+
"""skill_suggest.py must remain importable and call through to
|
| 301 |
+
bundle_orchestrator.main — otherwise existing ~/.claude/settings.json
|
| 302 |
+
hook configs that invoke ``python skill_suggest.py`` break silently."""
|
| 303 |
+
|
| 304 |
+
def test_shim_re_exports_main(self):
|
| 305 |
+
from ctx.adapters.claude_code.hooks import skill_suggest
|
| 306 |
+
# The shim re-imports main from bundle_orchestrator. The function
|
| 307 |
+
# object must be the SAME instance to guarantee behavioural parity.
|
| 308 |
+
assert skill_suggest.main is _bo.main
|
| 309 |
+
|
| 310 |
+
def test_shim_re_exports_constants(self):
|
| 311 |
+
from ctx.adapters.claude_code.hooks import skill_suggest
|
| 312 |
+
assert skill_suggest.PENDING_SKILLS == _bo.PENDING_SKILLS
|
| 313 |
+
assert skill_suggest.PENDING_UNLOAD == _bo.PENDING_UNLOAD
|
src/tests/test_catalog_builder.py
CHANGED
|
@@ -1,917 +1,917 @@
|
|
| 1 |
-
"""
|
| 2 |
-
test_catalog_builder.py -- Coverage for catalog_builder.py (226 LOC).
|
| 3 |
-
|
| 4 |
-
catalog_builder scans skills and agents directories, builds catalog.md,
|
| 5 |
-
and optionally updates index.md and log.md inside the wiki. A regression
|
| 6 |
-
in any of the four public functions silently corrupts the master index
|
| 7 |
-
used by every downstream router call, so each branch is explicitly covered.
|
| 8 |
-
"""
|
| 9 |
-
|
| 10 |
-
from __future__ import annotations
|
| 11 |
-
|
| 12 |
-
import re
|
| 13 |
-
from pathlib import Path
|
| 14 |
-
from typing import Any
|
| 15 |
-
from unittest.mock import MagicMock
|
| 16 |
-
|
| 17 |
-
import pytest
|
| 18 |
-
|
| 19 |
-
import catalog_builder
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
# ── Helpers ───────────────────────────────────────────────────────────────────
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
def _make_skill(base: Path, name: str, line_count: int) -> Path:
|
| 26 |
-
"""Create skills_dir/<name>/SKILL.md with the requested number of lines."""
|
| 27 |
-
d = base / name
|
| 28 |
-
d.mkdir(parents=True, exist_ok=True)
|
| 29 |
-
content = "\n".join(f"# line {i}" for i in range(line_count))
|
| 30 |
-
(d / "SKILL.md").write_text(content, encoding="utf-8")
|
| 31 |
-
return d
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
def _make_agent(base: Path, name: str, line_count: int) -> Path:
|
| 35 |
-
"""Create agents_dir/<name>.md with the requested number of lines."""
|
| 36 |
-
base.mkdir(parents=True, exist_ok=True)
|
| 37 |
-
content = "\n".join(f"# line {i}" for i in range(line_count))
|
| 38 |
-
p = base / f"{name}.md"
|
| 39 |
-
p.write_text(content, encoding="utf-8")
|
| 40 |
-
return p
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
def _patched_cfg(monkeypatch: pytest.MonkeyPatch, threshold: int = 180) -> MagicMock:
|
| 44 |
-
"""Return a mock cfg with a configurable line_threshold."""
|
| 45 |
-
fake = MagicMock()
|
| 46 |
-
fake.line_threshold = threshold
|
| 47 |
-
monkeypatch.setattr(catalog_builder, "cfg", fake)
|
| 48 |
-
return fake
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
# ── scan_skills_dir ───────────────────────────────────────────────────────────
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
class TestScanSkillsDir:
|
| 55 |
-
def test_nonexistent_dir_returns_empty(
|
| 56 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 57 |
-
) -> None:
|
| 58 |
-
_patched_cfg(monkeypatch)
|
| 59 |
-
result = catalog_builder.scan_skills_dir(tmp_path / "does-not-exist")
|
| 60 |
-
assert result == []
|
| 61 |
-
|
| 62 |
-
def test_empty_dir_returns_empty(
|
| 63 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 64 |
-
) -> None:
|
| 65 |
-
_patched_cfg(monkeypatch)
|
| 66 |
-
skills_dir = tmp_path / "skills"
|
| 67 |
-
skills_dir.mkdir()
|
| 68 |
-
assert catalog_builder.scan_skills_dir(skills_dir) == []
|
| 69 |
-
|
| 70 |
-
def test_dir_without_skill_md_skipped(
|
| 71 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 72 |
-
) -> None:
|
| 73 |
-
_patched_cfg(monkeypatch)
|
| 74 |
-
skills_dir = tmp_path / "skills"
|
| 75 |
-
(skills_dir / "no-skill-md").mkdir(parents=True)
|
| 76 |
-
# directory exists but has no SKILL.md
|
| 77 |
-
assert catalog_builder.scan_skills_dir(skills_dir) == []
|
| 78 |
-
|
| 79 |
-
def test_flat_file_in_skills_dir_skipped(
|
| 80 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 81 |
-
) -> None:
|
| 82 |
-
"""Regular .md files at the top level of skills_dir are not skills."""
|
| 83 |
-
_patched_cfg(monkeypatch)
|
| 84 |
-
skills_dir = tmp_path / "skills"
|
| 85 |
-
skills_dir.mkdir()
|
| 86 |
-
(skills_dir / "flat.md").write_text("# flat", encoding="utf-8")
|
| 87 |
-
assert catalog_builder.scan_skills_dir(skills_dir) == []
|
| 88 |
-
|
| 89 |
-
def test_single_skill_parsed(
|
| 90 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 91 |
-
) -> None:
|
| 92 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 93 |
-
skills_dir = tmp_path / "skills"
|
| 94 |
-
_make_skill(skills_dir, "my-skill", 10)
|
| 95 |
-
result = catalog_builder.scan_skills_dir(skills_dir)
|
| 96 |
-
assert len(result) == 1
|
| 97 |
-
r = result[0]
|
| 98 |
-
assert r["name"] == "my-skill"
|
| 99 |
-
assert r["type"] == "skill"
|
| 100 |
-
assert r["lines"] == 10
|
| 101 |
-
assert r["over_180"] is False
|
| 102 |
-
assert "SKILL.md" in r["path"]
|
| 103 |
-
|
| 104 |
-
def test_over_threshold_flag(
|
| 105 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 106 |
-
) -> None:
|
| 107 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 108 |
-
skills_dir = tmp_path / "skills"
|
| 109 |
-
_make_skill(skills_dir, "fat-skill", 200)
|
| 110 |
-
result = catalog_builder.scan_skills_dir(skills_dir)
|
| 111 |
-
assert result[0]["over_180"] is True
|
| 112 |
-
|
| 113 |
-
def test_exactly_at_threshold_not_over(
|
| 114 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 115 |
-
) -> None:
|
| 116 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 117 |
-
skills_dir = tmp_path / "skills"
|
| 118 |
-
_make_skill(skills_dir, "boundary-skill", 180)
|
| 119 |
-
result = catalog_builder.scan_skills_dir(skills_dir)
|
| 120 |
-
assert result[0]["over_180"] is False
|
| 121 |
-
|
| 122 |
-
def test_one_above_threshold_is_over(
|
| 123 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 124 |
-
) -> None:
|
| 125 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 126 |
-
skills_dir = tmp_path / "skills"
|
| 127 |
-
_make_skill(skills_dir, "just-over", 181)
|
| 128 |
-
result = catalog_builder.scan_skills_dir(skills_dir)
|
| 129 |
-
assert result[0]["over_180"] is True
|
| 130 |
-
|
| 131 |
-
def test_multiple_skills_sorted(
|
| 132 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 133 |
-
) -> None:
|
| 134 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 135 |
-
skills_dir = tmp_path / "skills"
|
| 136 |
-
_make_skill(skills_dir, "zebra", 5)
|
| 137 |
-
_make_skill(skills_dir, "alpha", 5)
|
| 138 |
-
_make_skill(skills_dir, "middle", 5)
|
| 139 |
-
result = catalog_builder.scan_skills_dir(skills_dir)
|
| 140 |
-
names = [r["name"] for r in result]
|
| 141 |
-
assert names == sorted(names)
|
| 142 |
-
|
| 143 |
-
def test_empty_skill_md_yields_zero_lines(
|
| 144 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 145 |
-
) -> None:
|
| 146 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 147 |
-
skills_dir = tmp_path / "skills"
|
| 148 |
-
d = skills_dir / "empty-skill"
|
| 149 |
-
d.mkdir(parents=True)
|
| 150 |
-
(d / "SKILL.md").write_text("", encoding="utf-8")
|
| 151 |
-
result = catalog_builder.scan_skills_dir(skills_dir)
|
| 152 |
-
assert result[0]["lines"] == 0
|
| 153 |
-
|
| 154 |
-
def test_unicode_content_handled(
|
| 155 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 156 |
-
) -> None:
|
| 157 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 158 |
-
skills_dir = tmp_path / "skills"
|
| 159 |
-
d = skills_dir / "unicode-skill"
|
| 160 |
-
d.mkdir(parents=True)
|
| 161 |
-
content = "# 日本語\n# Ärger\n# emoji 🐍\n"
|
| 162 |
-
(d / "SKILL.md").write_text(content, encoding="utf-8")
|
| 163 |
-
result = catalog_builder.scan_skills_dir(skills_dir)
|
| 164 |
-
assert result[0]["lines"] == 3
|
| 165 |
-
|
| 166 |
-
def test_unreadable_skill_warns_and_uses_zero(
|
| 167 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
| 168 |
-
) -> None:
|
| 169 |
-
"""When read_text raises, lines falls back to 0 and a warning goes to stderr."""
|
| 170 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 171 |
-
skills_dir = tmp_path / "skills"
|
| 172 |
-
d = skills_dir / "bad-skill"
|
| 173 |
-
d.mkdir(parents=True)
|
| 174 |
-
skill_md = d / "SKILL.md"
|
| 175 |
-
skill_md.write_text("content", encoding="utf-8")
|
| 176 |
-
|
| 177 |
-
original_read = Path.read_text
|
| 178 |
-
|
| 179 |
-
def _boom(self: Path, **kwargs: Any) -> str: # type: ignore[override]
|
| 180 |
-
if self.name == "SKILL.md":
|
| 181 |
-
raise OSError("permission denied")
|
| 182 |
-
return original_read(self, **kwargs)
|
| 183 |
-
|
| 184 |
-
monkeypatch.setattr(Path, "read_text", _boom)
|
| 185 |
-
result = catalog_builder.scan_skills_dir(skills_dir)
|
| 186 |
-
assert result[0]["lines"] == 0
|
| 187 |
-
err = capsys.readouterr().err
|
| 188 |
-
assert "Warning" in err
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
# ── scan_agents_dir ───────────────────────────────────────────────────────────
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
class TestScanAgentsDir:
|
| 195 |
-
def test_nonexistent_dir_returns_empty(
|
| 196 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 197 |
-
) -> None:
|
| 198 |
-
_patched_cfg(monkeypatch)
|
| 199 |
-
result = catalog_builder.scan_agents_dir(tmp_path / "no-agents")
|
| 200 |
-
assert result == []
|
| 201 |
-
|
| 202 |
-
def test_empty_dir_returns_empty(
|
| 203 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 204 |
-
) -> None:
|
| 205 |
-
_patched_cfg(monkeypatch)
|
| 206 |
-
agents_dir = tmp_path / "agents"
|
| 207 |
-
agents_dir.mkdir()
|
| 208 |
-
assert catalog_builder.scan_agents_dir(agents_dir) == []
|
| 209 |
-
|
| 210 |
-
def test_non_md_files_ignored(
|
| 211 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 212 |
-
) -> None:
|
| 213 |
-
_patched_cfg(monkeypatch)
|
| 214 |
-
agents_dir = tmp_path / "agents"
|
| 215 |
-
agents_dir.mkdir()
|
| 216 |
-
(agents_dir / "script.py").write_text("x=1", encoding="utf-8")
|
| 217 |
-
(agents_dir / "data.json").write_text("{}", encoding="utf-8")
|
| 218 |
-
assert catalog_builder.scan_agents_dir(agents_dir) == []
|
| 219 |
-
|
| 220 |
-
def test_single_agent_parsed(
|
| 221 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 222 |
-
) -> None:
|
| 223 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 224 |
-
agents_dir = tmp_path / "agents"
|
| 225 |
-
_make_agent(agents_dir, "my-agent", 50)
|
| 226 |
-
result = catalog_builder.scan_agents_dir(agents_dir)
|
| 227 |
-
assert len(result) == 1
|
| 228 |
-
r = result[0]
|
| 229 |
-
assert r["name"] == "my-agent"
|
| 230 |
-
assert r["type"] == "agent"
|
| 231 |
-
assert r["lines"] == 50
|
| 232 |
-
assert r["over_180"] is False
|
| 233 |
-
assert r["path"].endswith("my-agent.md")
|
| 234 |
-
|
| 235 |
-
def test_over_threshold_flag(
|
| 236 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 237 |
-
) -> None:
|
| 238 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 239 |
-
agents_dir = tmp_path / "agents"
|
| 240 |
-
_make_agent(agents_dir, "fat-agent", 200)
|
| 241 |
-
result = catalog_builder.scan_agents_dir(agents_dir)
|
| 242 |
-
assert result[0]["over_180"] is True
|
| 243 |
-
|
| 244 |
-
def test_exactly_at_threshold_not_over(
|
| 245 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 246 |
-
) -> None:
|
| 247 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 248 |
-
agents_dir = tmp_path / "agents"
|
| 249 |
-
_make_agent(agents_dir, "boundary", 180)
|
| 250 |
-
result = catalog_builder.scan_agents_dir(agents_dir)
|
| 251 |
-
assert result[0]["over_180"] is False
|
| 252 |
-
|
| 253 |
-
def test_stem_used_as_name(
|
| 254 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 255 |
-
) -> None:
|
| 256 |
-
"""Agent name should be the stem (filename without .md extension)."""
|
| 257 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 258 |
-
agents_dir = tmp_path / "agents"
|
| 259 |
-
_make_agent(agents_dir, "code-reviewer", 10)
|
| 260 |
-
result = catalog_builder.scan_agents_dir(agents_dir)
|
| 261 |
-
assert result[0]["name"] == "code-reviewer"
|
| 262 |
-
|
| 263 |
-
def test_multiple_agents_sorted(
|
| 264 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 265 |
-
) -> None:
|
| 266 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 267 |
-
agents_dir = tmp_path / "agents"
|
| 268 |
-
for name in ("zzz", "aaa", "mmm"):
|
| 269 |
-
_make_agent(agents_dir, name, 5)
|
| 270 |
-
result = catalog_builder.scan_agents_dir(agents_dir)
|
| 271 |
-
names = [r["name"] for r in result]
|
| 272 |
-
assert names == sorted(names)
|
| 273 |
-
|
| 274 |
-
def test_unreadable_agent_warns_and_uses_zero(
|
| 275 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
| 276 |
-
) -> None:
|
| 277 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 278 |
-
agents_dir = tmp_path / "agents"
|
| 279 |
-
_make_agent(agents_dir, "broken-agent", 10)
|
| 280 |
-
|
| 281 |
-
original_read = Path.read_text
|
| 282 |
-
|
| 283 |
-
def _boom(self: Path, **kwargs: Any) -> str: # type: ignore[override]
|
| 284 |
-
if self.suffix == ".md":
|
| 285 |
-
raise OSError("permission denied")
|
| 286 |
-
return original_read(self, **kwargs)
|
| 287 |
-
|
| 288 |
-
monkeypatch.setattr(Path, "read_text", _boom)
|
| 289 |
-
result = catalog_builder.scan_agents_dir(agents_dir)
|
| 290 |
-
assert result[0]["lines"] == 0
|
| 291 |
-
err = capsys.readouterr().err
|
| 292 |
-
assert "Warning" in err
|
| 293 |
-
|
| 294 |
-
def test_unicode_agent_content(
|
| 295 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 296 |
-
) -> None:
|
| 297 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 298 |
-
agents_dir = tmp_path / "agents"
|
| 299 |
-
agents_dir.mkdir()
|
| 300 |
-
content = "# αβγδ\n# 中文\n# emoji 🤖\n"
|
| 301 |
-
(agents_dir / "unicode-agent.md").write_text(content, encoding="utf-8")
|
| 302 |
-
result = catalog_builder.scan_agents_dir(agents_dir)
|
| 303 |
-
assert result[0]["lines"] == 3
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
# ── build_catalog ─────────────────────────────────────────────────────────────
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
class TestBuildCatalog:
|
| 310 |
-
def test_empty_dirs_catalog_written(
|
| 311 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 312 |
-
) -> None:
|
| 313 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 314 |
-
wiki_dir = tmp_path / "wiki"
|
| 315 |
-
wiki_dir.mkdir()
|
| 316 |
-
skills_dir = tmp_path / "skills"
|
| 317 |
-
agents_dir = tmp_path / "agents"
|
| 318 |
-
|
| 319 |
-
stats = catalog_builder.build_catalog(wiki_dir, skills_dir, agents_dir, [])
|
| 320 |
-
|
| 321 |
-
catalog_path = wiki_dir / "catalog.md"
|
| 322 |
-
assert catalog_path.exists()
|
| 323 |
-
assert stats["total"] == 0
|
| 324 |
-
assert stats["skills"] == 0
|
| 325 |
-
assert stats["agents"] == 0
|
| 326 |
-
assert stats["over_180"] == 0
|
| 327 |
-
assert stats["catalog_path"] == str(catalog_path)
|
| 328 |
-
|
| 329 |
-
def test_catalog_md_header_present(
|
| 330 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 331 |
-
) -> None:
|
| 332 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 333 |
-
wiki_dir = tmp_path / "wiki"
|
| 334 |
-
wiki_dir.mkdir()
|
| 335 |
-
|
| 336 |
-
catalog_builder.build_catalog(wiki_dir, tmp_path / "s", tmp_path / "a", [])
|
| 337 |
-
|
| 338 |
-
content = (wiki_dir / "catalog.md").read_text(encoding="utf-8")
|
| 339 |
-
assert "# Skill Catalog" in content
|
| 340 |
-
assert "## Summary" in content
|
| 341 |
-
assert "## All Skills" in content
|
| 342 |
-
|
| 343 |
-
def test_stats_counts_skills_and_agents(
|
| 344 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 345 |
-
) -> None:
|
| 346 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 347 |
-
wiki_dir = tmp_path / "wiki"
|
| 348 |
-
wiki_dir.mkdir()
|
| 349 |
-
skills_dir = tmp_path / "skills"
|
| 350 |
-
agents_dir = tmp_path / "agents"
|
| 351 |
-
_make_skill(skills_dir, "skill-a", 10)
|
| 352 |
-
_make_skill(skills_dir, "skill-b", 10)
|
| 353 |
-
_make_agent(agents_dir, "agent-x", 5)
|
| 354 |
-
|
| 355 |
-
stats = catalog_builder.build_catalog(wiki_dir, skills_dir, agents_dir, [])
|
| 356 |
-
assert stats["total"] == 3
|
| 357 |
-
assert stats["skills"] == 2
|
| 358 |
-
assert stats["agents"] == 1
|
| 359 |
-
|
| 360 |
-
def test_over_180_count_correct(
|
| 361 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 362 |
-
) -> None:
|
| 363 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 364 |
-
wiki_dir = tmp_path / "wiki"
|
| 365 |
-
wiki_dir.mkdir()
|
| 366 |
-
skills_dir = tmp_path / "skills"
|
| 367 |
-
agents_dir = tmp_path / "agents"
|
| 368 |
-
_make_skill(skills_dir, "short-skill", 10)
|
| 369 |
-
_make_skill(skills_dir, "long-skill", 200)
|
| 370 |
-
_make_agent(agents_dir, "fat-agent", 250)
|
| 371 |
-
|
| 372 |
-
stats = catalog_builder.build_catalog(wiki_dir, skills_dir, agents_dir, [])
|
| 373 |
-
assert stats["over_180"] == 2
|
| 374 |
-
|
| 375 |
-
def test_catalog_table_rows_present(
|
| 376 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 377 |
-
) -> None:
|
| 378 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 379 |
-
wiki_dir = tmp_path / "wiki"
|
| 380 |
-
wiki_dir.mkdir()
|
| 381 |
-
skills_dir = tmp_path / "skills"
|
| 382 |
-
agents_dir = tmp_path / "agents"
|
| 383 |
-
_make_skill(skills_dir, "my-skill", 10)
|
| 384 |
-
_make_agent(agents_dir, "my-agent", 5)
|
| 385 |
-
|
| 386 |
-
catalog_builder.build_catalog(wiki_dir, skills_dir, agents_dir, [])
|
| 387 |
-
content = (wiki_dir / "catalog.md").read_text(encoding="utf-8")
|
| 388 |
-
assert "my-skill" in content
|
| 389 |
-
assert "my-agent" in content
|
| 390 |
-
|
| 391 |
-
def test_over_180_flag_in_table(
|
| 392 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 393 |
-
) -> None:
|
| 394 |
-
"""The warning character should appear for over-threshold items."""
|
| 395 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 396 |
-
wiki_dir = tmp_path / "wiki"
|
| 397 |
-
wiki_dir.mkdir()
|
| 398 |
-
skills_dir = tmp_path / "skills"
|
| 399 |
-
_make_skill(skills_dir, "fat-skill", 200)
|
| 400 |
-
|
| 401 |
-
catalog_builder.build_catalog(wiki_dir, skills_dir, tmp_path / "a", [])
|
| 402 |
-
content = (wiki_dir / "catalog.md").read_text(encoding="utf-8")
|
| 403 |
-
# The warning flag character should be present somewhere in the row
|
| 404 |
-
assert "⚠" in content # ⚠
|
| 405 |
-
|
| 406 |
-
def test_under_threshold_no_flag(
|
| 407 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 408 |
-
) -> None:
|
| 409 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 410 |
-
wiki_dir = tmp_path / "wiki"
|
| 411 |
-
wiki_dir.mkdir()
|
| 412 |
-
skills_dir = tmp_path / "skills"
|
| 413 |
-
_make_skill(skills_dir, "short", 10)
|
| 414 |
-
|
| 415 |
-
catalog_builder.build_catalog(wiki_dir, skills_dir, tmp_path / "a", [])
|
| 416 |
-
content = (wiki_dir / "catalog.md").read_text(encoding="utf-8")
|
| 417 |
-
assert "⚠" not in content
|
| 418 |
-
|
| 419 |
-
def test_extra_dirs_skills_pattern(
|
| 420 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 421 |
-
) -> None:
|
| 422 |
-
"""Extra dir with SKILL.md subdirs should be treated as skills."""
|
| 423 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 424 |
-
wiki_dir = tmp_path / "wiki"
|
| 425 |
-
wiki_dir.mkdir()
|
| 426 |
-
extra = tmp_path / "extra-skills"
|
| 427 |
-
_make_skill(extra, "extra-skill", 10)
|
| 428 |
-
|
| 429 |
-
stats = catalog_builder.build_catalog(
|
| 430 |
-
wiki_dir, tmp_path / "s", tmp_path / "a", [extra]
|
| 431 |
-
)
|
| 432 |
-
assert stats["total"] == 1
|
| 433 |
-
assert stats["skills"] == 1
|
| 434 |
-
|
| 435 |
-
def test_extra_dirs_agents_pattern(
|
| 436 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 437 |
-
) -> None:
|
| 438 |
-
"""Extra dir with flat .md files (no SKILL.md subdirs) treated as agents."""
|
| 439 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 440 |
-
wiki_dir = tmp_path / "wiki"
|
| 441 |
-
wiki_dir.mkdir()
|
| 442 |
-
extra = tmp_path / "extra-agents"
|
| 443 |
-
_make_agent(extra, "extra-agent", 10)
|
| 444 |
-
|
| 445 |
-
stats = catalog_builder.build_catalog(
|
| 446 |
-
wiki_dir, tmp_path / "s", tmp_path / "a", [extra]
|
| 447 |
-
)
|
| 448 |
-
assert stats["total"] == 1
|
| 449 |
-
assert stats["agents"] == 1
|
| 450 |
-
|
| 451 |
-
def test_extra_dir_nonexistent_skipped(
|
| 452 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 453 |
-
) -> None:
|
| 454 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 455 |
-
wiki_dir = tmp_path / "wiki"
|
| 456 |
-
wiki_dir.mkdir()
|
| 457 |
-
|
| 458 |
-
stats = catalog_builder.build_catalog(
|
| 459 |
-
wiki_dir, tmp_path / "s", tmp_path / "a",
|
| 460 |
-
[tmp_path / "ghost-dir"]
|
| 461 |
-
)
|
| 462 |
-
assert stats["total"] == 0
|
| 463 |
-
|
| 464 |
-
def test_catalog_overwrites_existing(
|
| 465 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 466 |
-
) -> None:
|
| 467 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 468 |
-
wiki_dir = tmp_path / "wiki"
|
| 469 |
-
wiki_dir.mkdir()
|
| 470 |
-
catalog_path = wiki_dir / "catalog.md"
|
| 471 |
-
catalog_path.write_text("OLD CONTENT", encoding="utf-8")
|
| 472 |
-
|
| 473 |
-
catalog_builder.build_catalog(wiki_dir, tmp_path / "s", tmp_path / "a", [])
|
| 474 |
-
content = catalog_path.read_text(encoding="utf-8")
|
| 475 |
-
assert "OLD CONTENT" not in content
|
| 476 |
-
assert "# Skill Catalog" in content
|
| 477 |
-
|
| 478 |
-
def test_summary_table_total_row(
|
| 479 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 480 |
-
) -> None:
|
| 481 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 482 |
-
wiki_dir = tmp_path / "wiki"
|
| 483 |
-
wiki_dir.mkdir()
|
| 484 |
-
skills_dir = tmp_path / "skills"
|
| 485 |
-
_make_skill(skills_dir, "sk", 10)
|
| 486 |
-
|
| 487 |
-
catalog_builder.build_catalog(wiki_dir, skills_dir, tmp_path / "a", [])
|
| 488 |
-
content = (wiki_dir / "catalog.md").read_text(encoding="utf-8")
|
| 489 |
-
assert "Total items" in content
|
| 490 |
-
assert "| 1 |" in content
|
| 491 |
-
|
| 492 |
-
def test_catalog_path_in_stats(
|
| 493 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 494 |
-
) -> None:
|
| 495 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 496 |
-
wiki_dir = tmp_path / "wiki"
|
| 497 |
-
wiki_dir.mkdir()
|
| 498 |
-
|
| 499 |
-
stats = catalog_builder.build_catalog(wiki_dir, tmp_path / "s", tmp_path / "a", [])
|
| 500 |
-
assert stats["catalog_path"] == str(wiki_dir / "catalog.md")
|
| 501 |
-
|
| 502 |
-
def test_many_items_all_appear_in_table(
|
| 503 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 504 |
-
) -> None:
|
| 505 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 506 |
-
wiki_dir = tmp_path / "wiki"
|
| 507 |
-
wiki_dir.mkdir()
|
| 508 |
-
skills_dir = tmp_path / "skills"
|
| 509 |
-
agents_dir = tmp_path / "agents"
|
| 510 |
-
for i in range(5):
|
| 511 |
-
_make_skill(skills_dir, f"skill-{i}", 10 + i)
|
| 512 |
-
for i in range(3):
|
| 513 |
-
_make_agent(agents_dir, f"agent-{i}", 5 + i)
|
| 514 |
-
|
| 515 |
-
stats = catalog_builder.build_catalog(wiki_dir, skills_dir, agents_dir, [])
|
| 516 |
-
assert stats["total"] == 8
|
| 517 |
-
content = (wiki_dir / "catalog.md").read_text(encoding="utf-8")
|
| 518 |
-
for i in range(5):
|
| 519 |
-
assert f"skill-{i}" in content
|
| 520 |
-
for i in range(3):
|
| 521 |
-
assert f"agent-{i}" in content
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
# ── update_wiki_index ─────────────────────────────────────────────────────────
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
class TestUpdateWikiIndex:
|
| 528 |
-
def _stats(self, total: int = 5) -> dict:
|
| 529 |
-
return {
|
| 530 |
-
"total": total,
|
| 531 |
-
"skills": 3,
|
| 532 |
-
"agents": 2,
|
| 533 |
-
"over_180": 1,
|
| 534 |
-
"catalog_path": "/tmp/catalog.md",
|
| 535 |
-
}
|
| 536 |
-
|
| 537 |
-
def test_no_index_md_is_noop(
|
| 538 |
-
self, tmp_path: Path
|
| 539 |
-
) -> None:
|
| 540 |
-
"""If index.md doesn't exist, function returns without error."""
|
| 541 |
-
wiki_dir = tmp_path / "wiki"
|
| 542 |
-
wiki_dir.mkdir()
|
| 543 |
-
# no index.md created — should be a silent no-op
|
| 544 |
-
catalog_builder.update_wiki_index(wiki_dir, self._stats())
|
| 545 |
-
assert not (wiki_dir / "index.md").exists()
|
| 546 |
-
|
| 547 |
-
def test_catalog_ref_inserted_once(
|
| 548 |
-
self, tmp_path: Path
|
| 549 |
-
) -> None:
|
| 550 |
-
wiki_dir = tmp_path / "wiki"
|
| 551 |
-
wiki_dir.mkdir()
|
| 552 |
-
index_path = wiki_dir / "index.md"
|
| 553 |
-
index_path.write_text("# Index\n\n## Skills\n\nSome content\n", encoding="utf-8")
|
| 554 |
-
|
| 555 |
-
catalog_builder.update_wiki_index(wiki_dir, self._stats())
|
| 556 |
-
content = index_path.read_text(encoding="utf-8")
|
| 557 |
-
assert content.count("[[catalog]]") == 1
|
| 558 |
-
|
| 559 |
-
def test_catalog_ref_not_duplicated_on_second_call(
|
| 560 |
-
self, tmp_path: Path
|
| 561 |
-
) -> None:
|
| 562 |
-
wiki_dir = tmp_path / "wiki"
|
| 563 |
-
wiki_dir.mkdir()
|
| 564 |
-
index_path = wiki_dir / "index.md"
|
| 565 |
-
index_path.write_text("# Index\n\n## Skills\n\n", encoding="utf-8")
|
| 566 |
-
|
| 567 |
-
catalog_builder.update_wiki_index(wiki_dir, self._stats())
|
| 568 |
-
catalog_builder.update_wiki_index(wiki_dir, self._stats())
|
| 569 |
-
content = index_path.read_text(encoding="utf-8")
|
| 570 |
-
assert content.count("[[catalog]]") == 1
|
| 571 |
-
|
| 572 |
-
def test_catalog_ref_inserted_under_skills_section(
|
| 573 |
-
self, tmp_path: Path
|
| 574 |
-
) -> None:
|
| 575 |
-
wiki_dir = tmp_path / "wiki"
|
| 576 |
-
wiki_dir.mkdir()
|
| 577 |
-
index_path = wiki_dir / "index.md"
|
| 578 |
-
index_path.write_text("# Index\n\n## Skills\n\n## Other\n", encoding="utf-8")
|
| 579 |
-
|
| 580 |
-
catalog_builder.update_wiki_index(wiki_dir, self._stats())
|
| 581 |
-
content = index_path.read_text(encoding="utf-8")
|
| 582 |
-
lines = content.split("\n")
|
| 583 |
-
skills_idx = next(i for i, line in enumerate(lines) if line.strip() == "## Skills")
|
| 584 |
-
catalog_idx = next(i for i, line in enumerate(lines) if "[[catalog]]" in line)
|
| 585 |
-
assert catalog_idx == skills_idx + 1
|
| 586 |
-
|
| 587 |
-
def test_catalog_ref_appended_when_no_skills_section(
|
| 588 |
-
self, tmp_path: Path
|
| 589 |
-
) -> None:
|
| 590 |
-
wiki_dir = tmp_path / "wiki"
|
| 591 |
-
wiki_dir.mkdir()
|
| 592 |
-
index_path = wiki_dir / "index.md"
|
| 593 |
-
index_path.write_text("# Index\n\nNo skills section here.\n", encoding="utf-8")
|
| 594 |
-
|
| 595 |
-
catalog_builder.update_wiki_index(wiki_dir, self._stats())
|
| 596 |
-
content = index_path.read_text(encoding="utf-8")
|
| 597 |
-
assert "[[catalog]]" in content
|
| 598 |
-
|
| 599 |
-
def test_total_pages_updated(
|
| 600 |
-
self, tmp_path: Path
|
| 601 |
-
) -> None:
|
| 602 |
-
wiki_dir = tmp_path / "wiki"
|
| 603 |
-
wiki_dir.mkdir()
|
| 604 |
-
index_path = wiki_dir / "index.md"
|
| 605 |
-
index_path.write_text(
|
| 606 |
-
"# Index\n\nTotal pages: 0\n\nLast updated: 2020-01-01\n",
|
| 607 |
-
encoding="utf-8",
|
| 608 |
-
)
|
| 609 |
-
|
| 610 |
-
catalog_builder.update_wiki_index(wiki_dir, self._stats(total=42))
|
| 611 |
-
content = index_path.read_text(encoding="utf-8")
|
| 612 |
-
assert "Total pages: 42" in content
|
| 613 |
-
assert "Total pages: 0" not in content
|
| 614 |
-
|
| 615 |
-
def test_last_updated_replaced(
|
| 616 |
-
self, tmp_path: Path
|
| 617 |
-
) -> None:
|
| 618 |
-
wiki_dir = tmp_path / "wiki"
|
| 619 |
-
wiki_dir.mkdir()
|
| 620 |
-
index_path = wiki_dir / "index.md"
|
| 621 |
-
index_path.write_text(
|
| 622 |
-
"# Index\n\nLast updated: 1999-12-31\n",
|
| 623 |
-
encoding="utf-8",
|
| 624 |
-
)
|
| 625 |
-
|
| 626 |
-
catalog_builder.update_wiki_index(wiki_dir, self._stats())
|
| 627 |
-
content = index_path.read_text(encoding="utf-8")
|
| 628 |
-
assert "Last updated: 1999-12-31" not in content
|
| 629 |
-
# The new date should match YYYY-MM-DD pattern
|
| 630 |
-
assert re.search(r"Last updated: \d{4}-\d{2}-\d{2}", content)
|
| 631 |
-
|
| 632 |
-
def test_index_with_existing_catalog_ref_updates_counts(
|
| 633 |
-
self, tmp_path: Path
|
| 634 |
-
) -> None:
|
| 635 |
-
"""Already-present [[catalog]] should not be duplicated; total should update."""
|
| 636 |
-
wiki_dir = tmp_path / "wiki"
|
| 637 |
-
wiki_dir.mkdir()
|
| 638 |
-
index_path = wiki_dir / "index.md"
|
| 639 |
-
index_path.write_text(
|
| 640 |
-
"# Index\n\n[[catalog]]\n\nTotal pages: 1\n",
|
| 641 |
-
encoding="utf-8",
|
| 642 |
-
)
|
| 643 |
-
|
| 644 |
-
catalog_builder.update_wiki_index(wiki_dir, self._stats(total=99))
|
| 645 |
-
content = index_path.read_text(encoding="utf-8")
|
| 646 |
-
assert content.count("[[catalog]]") == 1
|
| 647 |
-
assert "Total pages: 99" in content
|
| 648 |
-
|
| 649 |
-
def test_empty_index_md(
|
| 650 |
-
self, tmp_path: Path
|
| 651 |
-
) -> None:
|
| 652 |
-
"""Empty index.md should not raise; catalog ref is appended."""
|
| 653 |
-
wiki_dir = tmp_path / "wiki"
|
| 654 |
-
wiki_dir.mkdir()
|
| 655 |
-
index_path = wiki_dir / "index.md"
|
| 656 |
-
index_path.write_text("", encoding="utf-8")
|
| 657 |
-
|
| 658 |
-
catalog_builder.update_wiki_index(wiki_dir, self._stats())
|
| 659 |
-
content = index_path.read_text(encoding="utf-8")
|
| 660 |
-
assert "[[catalog]]" in content
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
# ── append_log ────────────────────────────────────────────────────────────────
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
class TestAppendLog:
|
| 667 |
-
def _stats(self) -> dict:
|
| 668 |
-
return {
|
| 669 |
-
"total": 7,
|
| 670 |
-
"skills": 4,
|
| 671 |
-
"agents": 3,
|
| 672 |
-
"over_180": 2,
|
| 673 |
-
"catalog_path": "/tmp/wiki/catalog.md",
|
| 674 |
-
}
|
| 675 |
-
|
| 676 |
-
def test_no_log_md_is_noop(
|
| 677 |
-
self, tmp_path: Path
|
| 678 |
-
) -> None:
|
| 679 |
-
wiki_dir = tmp_path / "wiki"
|
| 680 |
-
wiki_dir.mkdir()
|
| 681 |
-
# log.md does not exist — must not raise
|
| 682 |
-
catalog_builder.append_log(wiki_dir, self._stats())
|
| 683 |
-
assert not (wiki_dir / "log.md").exists()
|
| 684 |
-
|
| 685 |
-
def test_entry_appended_to_existing_log(
|
| 686 |
-
self, tmp_path: Path
|
| 687 |
-
) -> None:
|
| 688 |
-
wiki_dir = tmp_path / "wiki"
|
| 689 |
-
wiki_dir.mkdir()
|
| 690 |
-
log_path = wiki_dir / "log.md"
|
| 691 |
-
log_path.write_text("# Log\n\nOld entry.\n", encoding="utf-8")
|
| 692 |
-
|
| 693 |
-
catalog_builder.append_log(wiki_dir, self._stats())
|
| 694 |
-
content = log_path.read_text(encoding="utf-8")
|
| 695 |
-
assert "Old entry." in content
|
| 696 |
-
assert "catalog-build" in content
|
| 697 |
-
|
| 698 |
-
def test_log_contains_counts(
|
| 699 |
-
self, tmp_path: Path
|
| 700 |
-
) -> None:
|
| 701 |
-
wiki_dir = tmp_path / "wiki"
|
| 702 |
-
wiki_dir.mkdir()
|
| 703 |
-
log_path = wiki_dir / "log.md"
|
| 704 |
-
log_path.write_text("", encoding="utf-8")
|
| 705 |
-
|
| 706 |
-
catalog_builder.append_log(wiki_dir, self._stats())
|
| 707 |
-
content = log_path.read_text(encoding="utf-8")
|
| 708 |
-
assert "7" in content # total
|
| 709 |
-
assert "4" in content # skills
|
| 710 |
-
assert "3" in content # agents
|
| 711 |
-
assert "2" in content # over_180
|
| 712 |
-
|
| 713 |
-
def test_log_contains_catalog_path(
|
| 714 |
-
self, tmp_path: Path
|
| 715 |
-
) -> None:
|
| 716 |
-
wiki_dir = tmp_path / "wiki"
|
| 717 |
-
wiki_dir.mkdir()
|
| 718 |
-
(wiki_dir / "log.md").write_text("", encoding="utf-8")
|
| 719 |
-
|
| 720 |
-
catalog_builder.append_log(wiki_dir, self._stats())
|
| 721 |
-
content = (wiki_dir / "log.md").read_text(encoding="utf-8")
|
| 722 |
-
assert "/tmp/wiki/catalog.md" in content
|
| 723 |
-
|
| 724 |
-
def test_log_contains_date(
|
| 725 |
-
self, tmp_path: Path
|
| 726 |
-
) -> None:
|
| 727 |
-
wiki_dir = tmp_path / "wiki"
|
| 728 |
-
wiki_dir.mkdir()
|
| 729 |
-
(wiki_dir / "log.md").write_text("", encoding="utf-8")
|
| 730 |
-
|
| 731 |
-
catalog_builder.append_log(wiki_dir, self._stats())
|
| 732 |
-
content = (wiki_dir / "log.md").read_text(encoding="utf-8")
|
| 733 |
-
assert re.search(r"\d{4}-\d{2}-\d{2}", content)
|
| 734 |
-
|
| 735 |
-
def test_multiple_appends_accumulate(
|
| 736 |
-
self, tmp_path: Path
|
| 737 |
-
) -> None:
|
| 738 |
-
wiki_dir = tmp_path / "wiki"
|
| 739 |
-
wiki_dir.mkdir()
|
| 740 |
-
log_path = wiki_dir / "log.md"
|
| 741 |
-
log_path.write_text("", encoding="utf-8")
|
| 742 |
-
|
| 743 |
-
catalog_builder.append_log(wiki_dir, self._stats())
|
| 744 |
-
catalog_builder.append_log(wiki_dir, self._stats())
|
| 745 |
-
content = log_path.read_text(encoding="utf-8")
|
| 746 |
-
assert content.count("catalog-build") == 2
|
| 747 |
-
|
| 748 |
-
def test_empty_log_md_gets_entry(
|
| 749 |
-
self, tmp_path: Path
|
| 750 |
-
) -> None:
|
| 751 |
-
wiki_dir = tmp_path / "wiki"
|
| 752 |
-
wiki_dir.mkdir()
|
| 753 |
-
(wiki_dir / "log.md").write_text("", encoding="utf-8")
|
| 754 |
-
|
| 755 |
-
catalog_builder.append_log(wiki_dir, self._stats())
|
| 756 |
-
content = (wiki_dir / "log.md").read_text(encoding="utf-8")
|
| 757 |
-
assert len(content) > 0
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
# ── Parametric edge-case coverage ───────────────────────────────────────────
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
class TestScanSkillsDirParametric:
|
| 764 |
-
@pytest.mark.parametrize("line_count", [0, 1, 179, 180, 181, 500])
|
| 765 |
-
def test_over_threshold_boundary(
|
| 766 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, line_count: int
|
| 767 |
-
) -> None:
|
| 768 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 769 |
-
skills_dir = tmp_path / "skills"
|
| 770 |
-
_make_skill(skills_dir, "skill", line_count)
|
| 771 |
-
result = catalog_builder.scan_skills_dir(skills_dir)
|
| 772 |
-
assert result[0]["over_180"] == (line_count > 180)
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
class TestScanAgentsDirParametric:
|
| 776 |
-
@pytest.mark.parametrize("line_count", [0, 1, 179, 180, 181, 500])
|
| 777 |
-
def test_over_threshold_boundary(
|
| 778 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, line_count: int
|
| 779 |
-
) -> None:
|
| 780 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 781 |
-
agents_dir = tmp_path / "agents"
|
| 782 |
-
_make_agent(agents_dir, "agent", line_count)
|
| 783 |
-
result = catalog_builder.scan_agents_dir(agents_dir)
|
| 784 |
-
assert result[0]["over_180"] == (line_count > 180)
|
| 785 |
-
|
| 786 |
-
|
| 787 |
-
class TestBuildCatalogParametric:
|
| 788 |
-
@pytest.mark.parametrize(
|
| 789 |
-
"n_skills,n_agents,expected_total",
|
| 790 |
-
[
|
| 791 |
-
(0, 0, 0),
|
| 792 |
-
(1, 0, 1),
|
| 793 |
-
(0, 1, 1),
|
| 794 |
-
(3, 3, 6),
|
| 795 |
-
(10, 5, 15),
|
| 796 |
-
],
|
| 797 |
-
)
|
| 798 |
-
def test_total_count(
|
| 799 |
-
self,
|
| 800 |
-
tmp_path: Path,
|
| 801 |
-
monkeypatch: pytest.MonkeyPatch,
|
| 802 |
-
n_skills: int,
|
| 803 |
-
n_agents: int,
|
| 804 |
-
expected_total: int,
|
| 805 |
-
) -> None:
|
| 806 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 807 |
-
wiki_dir = tmp_path / "wiki"
|
| 808 |
-
wiki_dir.mkdir()
|
| 809 |
-
skills_dir = tmp_path / "skills"
|
| 810 |
-
agents_dir = tmp_path / "agents"
|
| 811 |
-
for i in range(n_skills):
|
| 812 |
-
_make_skill(skills_dir, f"skill-{i}", 10)
|
| 813 |
-
for i in range(n_agents):
|
| 814 |
-
_make_agent(agents_dir, f"agent-{i}", 10)
|
| 815 |
-
stats = catalog_builder.build_catalog(wiki_dir, skills_dir, agents_dir, [])
|
| 816 |
-
assert stats["total"] == expected_total
|
| 817 |
-
|
| 818 |
-
|
| 819 |
-
# ── main() CLI entrypoint ────────────────────────────────────────────────────
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
class TestMain:
|
| 823 |
-
"""Exercise the argparse entrypoint without touching real ~/.claude paths."""
|
| 824 |
-
|
| 825 |
-
def test_missing_wiki_exits_1(
|
| 826 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
| 827 |
-
) -> None:
|
| 828 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 829 |
-
wiki_dir = tmp_path / "wiki-missing"
|
| 830 |
-
# wiki_dir intentionally not created
|
| 831 |
-
monkeypatch.setattr(
|
| 832 |
-
"sys.argv",
|
| 833 |
-
[
|
| 834 |
-
"catalog_builder",
|
| 835 |
-
"--wiki", str(wiki_dir),
|
| 836 |
-
"--skills-dir", str(tmp_path / "skills"),
|
| 837 |
-
"--agents-dir", str(tmp_path / "agents"),
|
| 838 |
-
],
|
| 839 |
-
)
|
| 840 |
-
with pytest.raises(SystemExit) as exc_info:
|
| 841 |
-
catalog_builder.main()
|
| 842 |
-
assert exc_info.value.code == 1
|
| 843 |
-
err = capsys.readouterr().err
|
| 844 |
-
assert "Wiki not initialized" in err
|
| 845 |
-
|
| 846 |
-
def test_happy_path_prints_summary(
|
| 847 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
| 848 |
-
) -> None:
|
| 849 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 850 |
-
wiki_dir = tmp_path / "wiki"
|
| 851 |
-
wiki_dir.mkdir()
|
| 852 |
-
skills_dir = tmp_path / "skills"
|
| 853 |
-
agents_dir = tmp_path / "agents"
|
| 854 |
-
_make_skill(skills_dir, "demo-skill", 10)
|
| 855 |
-
_make_agent(agents_dir, "demo-agent", 5)
|
| 856 |
-
|
| 857 |
-
monkeypatch.setattr(
|
| 858 |
-
"sys.argv",
|
| 859 |
-
[
|
| 860 |
-
"catalog_builder",
|
| 861 |
-
"--wiki", str(wiki_dir),
|
| 862 |
-
"--skills-dir", str(skills_dir),
|
| 863 |
-
"--agents-dir", str(agents_dir),
|
| 864 |
-
],
|
| 865 |
-
)
|
| 866 |
-
catalog_builder.main()
|
| 867 |
-
out = capsys.readouterr().out
|
| 868 |
-
assert "Catalog built:" in out
|
| 869 |
-
assert "Written to:" in out
|
| 870 |
-
|
| 871 |
-
def test_extra_dirs_passed_through(
|
| 872 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
| 873 |
-
) -> None:
|
| 874 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 875 |
-
wiki_dir = tmp_path / "wiki"
|
| 876 |
-
wiki_dir.mkdir()
|
| 877 |
-
extra = tmp_path / "extra"
|
| 878 |
-
_make_skill(extra, "extra-skill", 10)
|
| 879 |
-
|
| 880 |
-
monkeypatch.setattr(
|
| 881 |
-
"sys.argv",
|
| 882 |
-
[
|
| 883 |
-
"catalog_builder",
|
| 884 |
-
"--wiki", str(wiki_dir),
|
| 885 |
-
"--skills-dir", str(tmp_path / "skills"),
|
| 886 |
-
"--agents-dir", str(tmp_path / "agents"),
|
| 887 |
-
"--extra-dirs", str(extra),
|
| 888 |
-
],
|
| 889 |
-
)
|
| 890 |
-
catalog_builder.main()
|
| 891 |
-
# catalog.md should exist and reference the extra skill
|
| 892 |
-
content = (wiki_dir / "catalog.md").read_text(encoding="utf-8")
|
| 893 |
-
assert "extra-skill" in content
|
| 894 |
-
|
| 895 |
-
def test_catalog_and_log_written_by_main(
|
| 896 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
| 897 |
-
) -> None:
|
| 898 |
-
_patched_cfg(monkeypatch, threshold=180)
|
| 899 |
-
wiki_dir = tmp_path / "wiki"
|
| 900 |
-
wiki_dir.mkdir()
|
| 901 |
-
# Pre-create log.md and index.md so update_wiki_index/append_log have targets
|
| 902 |
-
(wiki_dir / "log.md").write_text("", encoding="utf-8")
|
| 903 |
-
(wiki_dir / "index.md").write_text("# Index\n\nTotal pages: 0\n", encoding="utf-8")
|
| 904 |
-
|
| 905 |
-
monkeypatch.setattr(
|
| 906 |
-
"sys.argv",
|
| 907 |
-
[
|
| 908 |
-
"catalog_builder",
|
| 909 |
-
"--wiki", str(wiki_dir),
|
| 910 |
-
"--skills-dir", str(tmp_path / "skills"),
|
| 911 |
-
"--agents-dir", str(tmp_path / "agents"),
|
| 912 |
-
],
|
| 913 |
-
)
|
| 914 |
-
catalog_builder.main()
|
| 915 |
-
assert (wiki_dir / "catalog.md").exists()
|
| 916 |
-
log_content = (wiki_dir / "log.md").read_text(encoding="utf-8")
|
| 917 |
-
assert "catalog-build" in log_content
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_catalog_builder.py -- Coverage for catalog_builder.py (226 LOC).
|
| 3 |
+
|
| 4 |
+
catalog_builder scans skills and agents directories, builds catalog.md,
|
| 5 |
+
and optionally updates index.md and log.md inside the wiki. A regression
|
| 6 |
+
in any of the four public functions silently corrupts the master index
|
| 7 |
+
used by every downstream router call, so each branch is explicitly covered.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import re
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from typing import Any
|
| 15 |
+
from unittest.mock import MagicMock
|
| 16 |
+
|
| 17 |
+
import pytest
|
| 18 |
+
|
| 19 |
+
import catalog_builder
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# ── Helpers ───────────────────────────────────────────────────────────────────
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _make_skill(base: Path, name: str, line_count: int) -> Path:
|
| 26 |
+
"""Create skills_dir/<name>/SKILL.md with the requested number of lines."""
|
| 27 |
+
d = base / name
|
| 28 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 29 |
+
content = "\n".join(f"# line {i}" for i in range(line_count))
|
| 30 |
+
(d / "SKILL.md").write_text(content, encoding="utf-8")
|
| 31 |
+
return d
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _make_agent(base: Path, name: str, line_count: int) -> Path:
|
| 35 |
+
"""Create agents_dir/<name>.md with the requested number of lines."""
|
| 36 |
+
base.mkdir(parents=True, exist_ok=True)
|
| 37 |
+
content = "\n".join(f"# line {i}" for i in range(line_count))
|
| 38 |
+
p = base / f"{name}.md"
|
| 39 |
+
p.write_text(content, encoding="utf-8")
|
| 40 |
+
return p
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _patched_cfg(monkeypatch: pytest.MonkeyPatch, threshold: int = 180) -> MagicMock:
|
| 44 |
+
"""Return a mock cfg with a configurable line_threshold."""
|
| 45 |
+
fake = MagicMock()
|
| 46 |
+
fake.line_threshold = threshold
|
| 47 |
+
monkeypatch.setattr(catalog_builder, "cfg", fake)
|
| 48 |
+
return fake
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# ── scan_skills_dir ───────────────────────────────────────────────────────────
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class TestScanSkillsDir:
|
| 55 |
+
def test_nonexistent_dir_returns_empty(
|
| 56 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 57 |
+
) -> None:
|
| 58 |
+
_patched_cfg(monkeypatch)
|
| 59 |
+
result = catalog_builder.scan_skills_dir(tmp_path / "does-not-exist")
|
| 60 |
+
assert result == []
|
| 61 |
+
|
| 62 |
+
def test_empty_dir_returns_empty(
|
| 63 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 64 |
+
) -> None:
|
| 65 |
+
_patched_cfg(monkeypatch)
|
| 66 |
+
skills_dir = tmp_path / "skills"
|
| 67 |
+
skills_dir.mkdir()
|
| 68 |
+
assert catalog_builder.scan_skills_dir(skills_dir) == []
|
| 69 |
+
|
| 70 |
+
def test_dir_without_skill_md_skipped(
|
| 71 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 72 |
+
) -> None:
|
| 73 |
+
_patched_cfg(monkeypatch)
|
| 74 |
+
skills_dir = tmp_path / "skills"
|
| 75 |
+
(skills_dir / "no-skill-md").mkdir(parents=True)
|
| 76 |
+
# directory exists but has no SKILL.md
|
| 77 |
+
assert catalog_builder.scan_skills_dir(skills_dir) == []
|
| 78 |
+
|
| 79 |
+
def test_flat_file_in_skills_dir_skipped(
|
| 80 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 81 |
+
) -> None:
|
| 82 |
+
"""Regular .md files at the top level of skills_dir are not skills."""
|
| 83 |
+
_patched_cfg(monkeypatch)
|
| 84 |
+
skills_dir = tmp_path / "skills"
|
| 85 |
+
skills_dir.mkdir()
|
| 86 |
+
(skills_dir / "flat.md").write_text("# flat", encoding="utf-8")
|
| 87 |
+
assert catalog_builder.scan_skills_dir(skills_dir) == []
|
| 88 |
+
|
| 89 |
+
def test_single_skill_parsed(
|
| 90 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 91 |
+
) -> None:
|
| 92 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 93 |
+
skills_dir = tmp_path / "skills"
|
| 94 |
+
_make_skill(skills_dir, "my-skill", 10)
|
| 95 |
+
result = catalog_builder.scan_skills_dir(skills_dir)
|
| 96 |
+
assert len(result) == 1
|
| 97 |
+
r = result[0]
|
| 98 |
+
assert r["name"] == "my-skill"
|
| 99 |
+
assert r["type"] == "skill"
|
| 100 |
+
assert r["lines"] == 10
|
| 101 |
+
assert r["over_180"] is False
|
| 102 |
+
assert "SKILL.md" in r["path"]
|
| 103 |
+
|
| 104 |
+
def test_over_threshold_flag(
|
| 105 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 106 |
+
) -> None:
|
| 107 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 108 |
+
skills_dir = tmp_path / "skills"
|
| 109 |
+
_make_skill(skills_dir, "fat-skill", 200)
|
| 110 |
+
result = catalog_builder.scan_skills_dir(skills_dir)
|
| 111 |
+
assert result[0]["over_180"] is True
|
| 112 |
+
|
| 113 |
+
def test_exactly_at_threshold_not_over(
|
| 114 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 115 |
+
) -> None:
|
| 116 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 117 |
+
skills_dir = tmp_path / "skills"
|
| 118 |
+
_make_skill(skills_dir, "boundary-skill", 180)
|
| 119 |
+
result = catalog_builder.scan_skills_dir(skills_dir)
|
| 120 |
+
assert result[0]["over_180"] is False
|
| 121 |
+
|
| 122 |
+
def test_one_above_threshold_is_over(
|
| 123 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 124 |
+
) -> None:
|
| 125 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 126 |
+
skills_dir = tmp_path / "skills"
|
| 127 |
+
_make_skill(skills_dir, "just-over", 181)
|
| 128 |
+
result = catalog_builder.scan_skills_dir(skills_dir)
|
| 129 |
+
assert result[0]["over_180"] is True
|
| 130 |
+
|
| 131 |
+
def test_multiple_skills_sorted(
|
| 132 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 133 |
+
) -> None:
|
| 134 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 135 |
+
skills_dir = tmp_path / "skills"
|
| 136 |
+
_make_skill(skills_dir, "zebra", 5)
|
| 137 |
+
_make_skill(skills_dir, "alpha", 5)
|
| 138 |
+
_make_skill(skills_dir, "middle", 5)
|
| 139 |
+
result = catalog_builder.scan_skills_dir(skills_dir)
|
| 140 |
+
names = [r["name"] for r in result]
|
| 141 |
+
assert names == sorted(names)
|
| 142 |
+
|
| 143 |
+
def test_empty_skill_md_yields_zero_lines(
|
| 144 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 145 |
+
) -> None:
|
| 146 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 147 |
+
skills_dir = tmp_path / "skills"
|
| 148 |
+
d = skills_dir / "empty-skill"
|
| 149 |
+
d.mkdir(parents=True)
|
| 150 |
+
(d / "SKILL.md").write_text("", encoding="utf-8")
|
| 151 |
+
result = catalog_builder.scan_skills_dir(skills_dir)
|
| 152 |
+
assert result[0]["lines"] == 0
|
| 153 |
+
|
| 154 |
+
def test_unicode_content_handled(
|
| 155 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 156 |
+
) -> None:
|
| 157 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 158 |
+
skills_dir = tmp_path / "skills"
|
| 159 |
+
d = skills_dir / "unicode-skill"
|
| 160 |
+
d.mkdir(parents=True)
|
| 161 |
+
content = "# 日本語\n# Ärger\n# emoji 🐍\n"
|
| 162 |
+
(d / "SKILL.md").write_text(content, encoding="utf-8")
|
| 163 |
+
result = catalog_builder.scan_skills_dir(skills_dir)
|
| 164 |
+
assert result[0]["lines"] == 3
|
| 165 |
+
|
| 166 |
+
def test_unreadable_skill_warns_and_uses_zero(
|
| 167 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
| 168 |
+
) -> None:
|
| 169 |
+
"""When read_text raises, lines falls back to 0 and a warning goes to stderr."""
|
| 170 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 171 |
+
skills_dir = tmp_path / "skills"
|
| 172 |
+
d = skills_dir / "bad-skill"
|
| 173 |
+
d.mkdir(parents=True)
|
| 174 |
+
skill_md = d / "SKILL.md"
|
| 175 |
+
skill_md.write_text("content", encoding="utf-8")
|
| 176 |
+
|
| 177 |
+
original_read = Path.read_text
|
| 178 |
+
|
| 179 |
+
def _boom(self: Path, **kwargs: Any) -> str: # type: ignore[override]
|
| 180 |
+
if self.name == "SKILL.md":
|
| 181 |
+
raise OSError("permission denied")
|
| 182 |
+
return original_read(self, **kwargs)
|
| 183 |
+
|
| 184 |
+
monkeypatch.setattr(Path, "read_text", _boom)
|
| 185 |
+
result = catalog_builder.scan_skills_dir(skills_dir)
|
| 186 |
+
assert result[0]["lines"] == 0
|
| 187 |
+
err = capsys.readouterr().err
|
| 188 |
+
assert "Warning" in err
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
# ── scan_agents_dir ───────────────────────────────────────────────────────────
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class TestScanAgentsDir:
|
| 195 |
+
def test_nonexistent_dir_returns_empty(
|
| 196 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 197 |
+
) -> None:
|
| 198 |
+
_patched_cfg(monkeypatch)
|
| 199 |
+
result = catalog_builder.scan_agents_dir(tmp_path / "no-agents")
|
| 200 |
+
assert result == []
|
| 201 |
+
|
| 202 |
+
def test_empty_dir_returns_empty(
|
| 203 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 204 |
+
) -> None:
|
| 205 |
+
_patched_cfg(monkeypatch)
|
| 206 |
+
agents_dir = tmp_path / "agents"
|
| 207 |
+
agents_dir.mkdir()
|
| 208 |
+
assert catalog_builder.scan_agents_dir(agents_dir) == []
|
| 209 |
+
|
| 210 |
+
def test_non_md_files_ignored(
|
| 211 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 212 |
+
) -> None:
|
| 213 |
+
_patched_cfg(monkeypatch)
|
| 214 |
+
agents_dir = tmp_path / "agents"
|
| 215 |
+
agents_dir.mkdir()
|
| 216 |
+
(agents_dir / "script.py").write_text("x=1", encoding="utf-8")
|
| 217 |
+
(agents_dir / "data.json").write_text("{}", encoding="utf-8")
|
| 218 |
+
assert catalog_builder.scan_agents_dir(agents_dir) == []
|
| 219 |
+
|
| 220 |
+
def test_single_agent_parsed(
|
| 221 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 222 |
+
) -> None:
|
| 223 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 224 |
+
agents_dir = tmp_path / "agents"
|
| 225 |
+
_make_agent(agents_dir, "my-agent", 50)
|
| 226 |
+
result = catalog_builder.scan_agents_dir(agents_dir)
|
| 227 |
+
assert len(result) == 1
|
| 228 |
+
r = result[0]
|
| 229 |
+
assert r["name"] == "my-agent"
|
| 230 |
+
assert r["type"] == "agent"
|
| 231 |
+
assert r["lines"] == 50
|
| 232 |
+
assert r["over_180"] is False
|
| 233 |
+
assert r["path"].endswith("my-agent.md")
|
| 234 |
+
|
| 235 |
+
def test_over_threshold_flag(
|
| 236 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 237 |
+
) -> None:
|
| 238 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 239 |
+
agents_dir = tmp_path / "agents"
|
| 240 |
+
_make_agent(agents_dir, "fat-agent", 200)
|
| 241 |
+
result = catalog_builder.scan_agents_dir(agents_dir)
|
| 242 |
+
assert result[0]["over_180"] is True
|
| 243 |
+
|
| 244 |
+
def test_exactly_at_threshold_not_over(
|
| 245 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 246 |
+
) -> None:
|
| 247 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 248 |
+
agents_dir = tmp_path / "agents"
|
| 249 |
+
_make_agent(agents_dir, "boundary", 180)
|
| 250 |
+
result = catalog_builder.scan_agents_dir(agents_dir)
|
| 251 |
+
assert result[0]["over_180"] is False
|
| 252 |
+
|
| 253 |
+
def test_stem_used_as_name(
|
| 254 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 255 |
+
) -> None:
|
| 256 |
+
"""Agent name should be the stem (filename without .md extension)."""
|
| 257 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 258 |
+
agents_dir = tmp_path / "agents"
|
| 259 |
+
_make_agent(agents_dir, "code-reviewer", 10)
|
| 260 |
+
result = catalog_builder.scan_agents_dir(agents_dir)
|
| 261 |
+
assert result[0]["name"] == "code-reviewer"
|
| 262 |
+
|
| 263 |
+
def test_multiple_agents_sorted(
|
| 264 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 265 |
+
) -> None:
|
| 266 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 267 |
+
agents_dir = tmp_path / "agents"
|
| 268 |
+
for name in ("zzz", "aaa", "mmm"):
|
| 269 |
+
_make_agent(agents_dir, name, 5)
|
| 270 |
+
result = catalog_builder.scan_agents_dir(agents_dir)
|
| 271 |
+
names = [r["name"] for r in result]
|
| 272 |
+
assert names == sorted(names)
|
| 273 |
+
|
| 274 |
+
def test_unreadable_agent_warns_and_uses_zero(
|
| 275 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
| 276 |
+
) -> None:
|
| 277 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 278 |
+
agents_dir = tmp_path / "agents"
|
| 279 |
+
_make_agent(agents_dir, "broken-agent", 10)
|
| 280 |
+
|
| 281 |
+
original_read = Path.read_text
|
| 282 |
+
|
| 283 |
+
def _boom(self: Path, **kwargs: Any) -> str: # type: ignore[override]
|
| 284 |
+
if self.suffix == ".md":
|
| 285 |
+
raise OSError("permission denied")
|
| 286 |
+
return original_read(self, **kwargs)
|
| 287 |
+
|
| 288 |
+
monkeypatch.setattr(Path, "read_text", _boom)
|
| 289 |
+
result = catalog_builder.scan_agents_dir(agents_dir)
|
| 290 |
+
assert result[0]["lines"] == 0
|
| 291 |
+
err = capsys.readouterr().err
|
| 292 |
+
assert "Warning" in err
|
| 293 |
+
|
| 294 |
+
def test_unicode_agent_content(
|
| 295 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 296 |
+
) -> None:
|
| 297 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 298 |
+
agents_dir = tmp_path / "agents"
|
| 299 |
+
agents_dir.mkdir()
|
| 300 |
+
content = "# αβγδ\n# 中文\n# emoji 🤖\n"
|
| 301 |
+
(agents_dir / "unicode-agent.md").write_text(content, encoding="utf-8")
|
| 302 |
+
result = catalog_builder.scan_agents_dir(agents_dir)
|
| 303 |
+
assert result[0]["lines"] == 3
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
# ── build_catalog ─────────────────────────────────────────────────────────────
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
class TestBuildCatalog:
|
| 310 |
+
def test_empty_dirs_catalog_written(
|
| 311 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 312 |
+
) -> None:
|
| 313 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 314 |
+
wiki_dir = tmp_path / "wiki"
|
| 315 |
+
wiki_dir.mkdir()
|
| 316 |
+
skills_dir = tmp_path / "skills"
|
| 317 |
+
agents_dir = tmp_path / "agents"
|
| 318 |
+
|
| 319 |
+
stats = catalog_builder.build_catalog(wiki_dir, skills_dir, agents_dir, [])
|
| 320 |
+
|
| 321 |
+
catalog_path = wiki_dir / "catalog.md"
|
| 322 |
+
assert catalog_path.exists()
|
| 323 |
+
assert stats["total"] == 0
|
| 324 |
+
assert stats["skills"] == 0
|
| 325 |
+
assert stats["agents"] == 0
|
| 326 |
+
assert stats["over_180"] == 0
|
| 327 |
+
assert stats["catalog_path"] == str(catalog_path)
|
| 328 |
+
|
| 329 |
+
def test_catalog_md_header_present(
|
| 330 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 331 |
+
) -> None:
|
| 332 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 333 |
+
wiki_dir = tmp_path / "wiki"
|
| 334 |
+
wiki_dir.mkdir()
|
| 335 |
+
|
| 336 |
+
catalog_builder.build_catalog(wiki_dir, tmp_path / "s", tmp_path / "a", [])
|
| 337 |
+
|
| 338 |
+
content = (wiki_dir / "catalog.md").read_text(encoding="utf-8")
|
| 339 |
+
assert "# Skill Catalog" in content
|
| 340 |
+
assert "## Summary" in content
|
| 341 |
+
assert "## All Skills" in content
|
| 342 |
+
|
| 343 |
+
def test_stats_counts_skills_and_agents(
|
| 344 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 345 |
+
) -> None:
|
| 346 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 347 |
+
wiki_dir = tmp_path / "wiki"
|
| 348 |
+
wiki_dir.mkdir()
|
| 349 |
+
skills_dir = tmp_path / "skills"
|
| 350 |
+
agents_dir = tmp_path / "agents"
|
| 351 |
+
_make_skill(skills_dir, "skill-a", 10)
|
| 352 |
+
_make_skill(skills_dir, "skill-b", 10)
|
| 353 |
+
_make_agent(agents_dir, "agent-x", 5)
|
| 354 |
+
|
| 355 |
+
stats = catalog_builder.build_catalog(wiki_dir, skills_dir, agents_dir, [])
|
| 356 |
+
assert stats["total"] == 3
|
| 357 |
+
assert stats["skills"] == 2
|
| 358 |
+
assert stats["agents"] == 1
|
| 359 |
+
|
| 360 |
+
def test_over_180_count_correct(
|
| 361 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 362 |
+
) -> None:
|
| 363 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 364 |
+
wiki_dir = tmp_path / "wiki"
|
| 365 |
+
wiki_dir.mkdir()
|
| 366 |
+
skills_dir = tmp_path / "skills"
|
| 367 |
+
agents_dir = tmp_path / "agents"
|
| 368 |
+
_make_skill(skills_dir, "short-skill", 10)
|
| 369 |
+
_make_skill(skills_dir, "long-skill", 200)
|
| 370 |
+
_make_agent(agents_dir, "fat-agent", 250)
|
| 371 |
+
|
| 372 |
+
stats = catalog_builder.build_catalog(wiki_dir, skills_dir, agents_dir, [])
|
| 373 |
+
assert stats["over_180"] == 2
|
| 374 |
+
|
| 375 |
+
def test_catalog_table_rows_present(
|
| 376 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 377 |
+
) -> None:
|
| 378 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 379 |
+
wiki_dir = tmp_path / "wiki"
|
| 380 |
+
wiki_dir.mkdir()
|
| 381 |
+
skills_dir = tmp_path / "skills"
|
| 382 |
+
agents_dir = tmp_path / "agents"
|
| 383 |
+
_make_skill(skills_dir, "my-skill", 10)
|
| 384 |
+
_make_agent(agents_dir, "my-agent", 5)
|
| 385 |
+
|
| 386 |
+
catalog_builder.build_catalog(wiki_dir, skills_dir, agents_dir, [])
|
| 387 |
+
content = (wiki_dir / "catalog.md").read_text(encoding="utf-8")
|
| 388 |
+
assert "my-skill" in content
|
| 389 |
+
assert "my-agent" in content
|
| 390 |
+
|
| 391 |
+
def test_over_180_flag_in_table(
|
| 392 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 393 |
+
) -> None:
|
| 394 |
+
"""The warning character should appear for over-threshold items."""
|
| 395 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 396 |
+
wiki_dir = tmp_path / "wiki"
|
| 397 |
+
wiki_dir.mkdir()
|
| 398 |
+
skills_dir = tmp_path / "skills"
|
| 399 |
+
_make_skill(skills_dir, "fat-skill", 200)
|
| 400 |
+
|
| 401 |
+
catalog_builder.build_catalog(wiki_dir, skills_dir, tmp_path / "a", [])
|
| 402 |
+
content = (wiki_dir / "catalog.md").read_text(encoding="utf-8")
|
| 403 |
+
# The warning flag character should be present somewhere in the row
|
| 404 |
+
assert "⚠" in content # ⚠
|
| 405 |
+
|
| 406 |
+
def test_under_threshold_no_flag(
|
| 407 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 408 |
+
) -> None:
|
| 409 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 410 |
+
wiki_dir = tmp_path / "wiki"
|
| 411 |
+
wiki_dir.mkdir()
|
| 412 |
+
skills_dir = tmp_path / "skills"
|
| 413 |
+
_make_skill(skills_dir, "short", 10)
|
| 414 |
+
|
| 415 |
+
catalog_builder.build_catalog(wiki_dir, skills_dir, tmp_path / "a", [])
|
| 416 |
+
content = (wiki_dir / "catalog.md").read_text(encoding="utf-8")
|
| 417 |
+
assert "⚠" not in content
|
| 418 |
+
|
| 419 |
+
def test_extra_dirs_skills_pattern(
|
| 420 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 421 |
+
) -> None:
|
| 422 |
+
"""Extra dir with SKILL.md subdirs should be treated as skills."""
|
| 423 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 424 |
+
wiki_dir = tmp_path / "wiki"
|
| 425 |
+
wiki_dir.mkdir()
|
| 426 |
+
extra = tmp_path / "extra-skills"
|
| 427 |
+
_make_skill(extra, "extra-skill", 10)
|
| 428 |
+
|
| 429 |
+
stats = catalog_builder.build_catalog(
|
| 430 |
+
wiki_dir, tmp_path / "s", tmp_path / "a", [extra]
|
| 431 |
+
)
|
| 432 |
+
assert stats["total"] == 1
|
| 433 |
+
assert stats["skills"] == 1
|
| 434 |
+
|
| 435 |
+
def test_extra_dirs_agents_pattern(
|
| 436 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 437 |
+
) -> None:
|
| 438 |
+
"""Extra dir with flat .md files (no SKILL.md subdirs) treated as agents."""
|
| 439 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 440 |
+
wiki_dir = tmp_path / "wiki"
|
| 441 |
+
wiki_dir.mkdir()
|
| 442 |
+
extra = tmp_path / "extra-agents"
|
| 443 |
+
_make_agent(extra, "extra-agent", 10)
|
| 444 |
+
|
| 445 |
+
stats = catalog_builder.build_catalog(
|
| 446 |
+
wiki_dir, tmp_path / "s", tmp_path / "a", [extra]
|
| 447 |
+
)
|
| 448 |
+
assert stats["total"] == 1
|
| 449 |
+
assert stats["agents"] == 1
|
| 450 |
+
|
| 451 |
+
def test_extra_dir_nonexistent_skipped(
|
| 452 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 453 |
+
) -> None:
|
| 454 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 455 |
+
wiki_dir = tmp_path / "wiki"
|
| 456 |
+
wiki_dir.mkdir()
|
| 457 |
+
|
| 458 |
+
stats = catalog_builder.build_catalog(
|
| 459 |
+
wiki_dir, tmp_path / "s", tmp_path / "a",
|
| 460 |
+
[tmp_path / "ghost-dir"]
|
| 461 |
+
)
|
| 462 |
+
assert stats["total"] == 0
|
| 463 |
+
|
| 464 |
+
def test_catalog_overwrites_existing(
|
| 465 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 466 |
+
) -> None:
|
| 467 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 468 |
+
wiki_dir = tmp_path / "wiki"
|
| 469 |
+
wiki_dir.mkdir()
|
| 470 |
+
catalog_path = wiki_dir / "catalog.md"
|
| 471 |
+
catalog_path.write_text("OLD CONTENT", encoding="utf-8")
|
| 472 |
+
|
| 473 |
+
catalog_builder.build_catalog(wiki_dir, tmp_path / "s", tmp_path / "a", [])
|
| 474 |
+
content = catalog_path.read_text(encoding="utf-8")
|
| 475 |
+
assert "OLD CONTENT" not in content
|
| 476 |
+
assert "# Skill Catalog" in content
|
| 477 |
+
|
| 478 |
+
def test_summary_table_total_row(
|
| 479 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 480 |
+
) -> None:
|
| 481 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 482 |
+
wiki_dir = tmp_path / "wiki"
|
| 483 |
+
wiki_dir.mkdir()
|
| 484 |
+
skills_dir = tmp_path / "skills"
|
| 485 |
+
_make_skill(skills_dir, "sk", 10)
|
| 486 |
+
|
| 487 |
+
catalog_builder.build_catalog(wiki_dir, skills_dir, tmp_path / "a", [])
|
| 488 |
+
content = (wiki_dir / "catalog.md").read_text(encoding="utf-8")
|
| 489 |
+
assert "Total items" in content
|
| 490 |
+
assert "| 1 |" in content
|
| 491 |
+
|
| 492 |
+
def test_catalog_path_in_stats(
|
| 493 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 494 |
+
) -> None:
|
| 495 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 496 |
+
wiki_dir = tmp_path / "wiki"
|
| 497 |
+
wiki_dir.mkdir()
|
| 498 |
+
|
| 499 |
+
stats = catalog_builder.build_catalog(wiki_dir, tmp_path / "s", tmp_path / "a", [])
|
| 500 |
+
assert stats["catalog_path"] == str(wiki_dir / "catalog.md")
|
| 501 |
+
|
| 502 |
+
def test_many_items_all_appear_in_table(
|
| 503 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 504 |
+
) -> None:
|
| 505 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 506 |
+
wiki_dir = tmp_path / "wiki"
|
| 507 |
+
wiki_dir.mkdir()
|
| 508 |
+
skills_dir = tmp_path / "skills"
|
| 509 |
+
agents_dir = tmp_path / "agents"
|
| 510 |
+
for i in range(5):
|
| 511 |
+
_make_skill(skills_dir, f"skill-{i}", 10 + i)
|
| 512 |
+
for i in range(3):
|
| 513 |
+
_make_agent(agents_dir, f"agent-{i}", 5 + i)
|
| 514 |
+
|
| 515 |
+
stats = catalog_builder.build_catalog(wiki_dir, skills_dir, agents_dir, [])
|
| 516 |
+
assert stats["total"] == 8
|
| 517 |
+
content = (wiki_dir / "catalog.md").read_text(encoding="utf-8")
|
| 518 |
+
for i in range(5):
|
| 519 |
+
assert f"skill-{i}" in content
|
| 520 |
+
for i in range(3):
|
| 521 |
+
assert f"agent-{i}" in content
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
# ── update_wiki_index ─────────────────────────────────────────────────────────
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
class TestUpdateWikiIndex:
|
| 528 |
+
def _stats(self, total: int = 5) -> dict:
|
| 529 |
+
return {
|
| 530 |
+
"total": total,
|
| 531 |
+
"skills": 3,
|
| 532 |
+
"agents": 2,
|
| 533 |
+
"over_180": 1,
|
| 534 |
+
"catalog_path": "/tmp/catalog.md",
|
| 535 |
+
}
|
| 536 |
+
|
| 537 |
+
def test_no_index_md_is_noop(
|
| 538 |
+
self, tmp_path: Path
|
| 539 |
+
) -> None:
|
| 540 |
+
"""If index.md doesn't exist, function returns without error."""
|
| 541 |
+
wiki_dir = tmp_path / "wiki"
|
| 542 |
+
wiki_dir.mkdir()
|
| 543 |
+
# no index.md created — should be a silent no-op
|
| 544 |
+
catalog_builder.update_wiki_index(wiki_dir, self._stats())
|
| 545 |
+
assert not (wiki_dir / "index.md").exists()
|
| 546 |
+
|
| 547 |
+
def test_catalog_ref_inserted_once(
|
| 548 |
+
self, tmp_path: Path
|
| 549 |
+
) -> None:
|
| 550 |
+
wiki_dir = tmp_path / "wiki"
|
| 551 |
+
wiki_dir.mkdir()
|
| 552 |
+
index_path = wiki_dir / "index.md"
|
| 553 |
+
index_path.write_text("# Index\n\n## Skills\n\nSome content\n", encoding="utf-8")
|
| 554 |
+
|
| 555 |
+
catalog_builder.update_wiki_index(wiki_dir, self._stats())
|
| 556 |
+
content = index_path.read_text(encoding="utf-8")
|
| 557 |
+
assert content.count("[[catalog]]") == 1
|
| 558 |
+
|
| 559 |
+
def test_catalog_ref_not_duplicated_on_second_call(
|
| 560 |
+
self, tmp_path: Path
|
| 561 |
+
) -> None:
|
| 562 |
+
wiki_dir = tmp_path / "wiki"
|
| 563 |
+
wiki_dir.mkdir()
|
| 564 |
+
index_path = wiki_dir / "index.md"
|
| 565 |
+
index_path.write_text("# Index\n\n## Skills\n\n", encoding="utf-8")
|
| 566 |
+
|
| 567 |
+
catalog_builder.update_wiki_index(wiki_dir, self._stats())
|
| 568 |
+
catalog_builder.update_wiki_index(wiki_dir, self._stats())
|
| 569 |
+
content = index_path.read_text(encoding="utf-8")
|
| 570 |
+
assert content.count("[[catalog]]") == 1
|
| 571 |
+
|
| 572 |
+
def test_catalog_ref_inserted_under_skills_section(
|
| 573 |
+
self, tmp_path: Path
|
| 574 |
+
) -> None:
|
| 575 |
+
wiki_dir = tmp_path / "wiki"
|
| 576 |
+
wiki_dir.mkdir()
|
| 577 |
+
index_path = wiki_dir / "index.md"
|
| 578 |
+
index_path.write_text("# Index\n\n## Skills\n\n## Other\n", encoding="utf-8")
|
| 579 |
+
|
| 580 |
+
catalog_builder.update_wiki_index(wiki_dir, self._stats())
|
| 581 |
+
content = index_path.read_text(encoding="utf-8")
|
| 582 |
+
lines = content.split("\n")
|
| 583 |
+
skills_idx = next(i for i, line in enumerate(lines) if line.strip() == "## Skills")
|
| 584 |
+
catalog_idx = next(i for i, line in enumerate(lines) if "[[catalog]]" in line)
|
| 585 |
+
assert catalog_idx == skills_idx + 1
|
| 586 |
+
|
| 587 |
+
def test_catalog_ref_appended_when_no_skills_section(
|
| 588 |
+
self, tmp_path: Path
|
| 589 |
+
) -> None:
|
| 590 |
+
wiki_dir = tmp_path / "wiki"
|
| 591 |
+
wiki_dir.mkdir()
|
| 592 |
+
index_path = wiki_dir / "index.md"
|
| 593 |
+
index_path.write_text("# Index\n\nNo skills section here.\n", encoding="utf-8")
|
| 594 |
+
|
| 595 |
+
catalog_builder.update_wiki_index(wiki_dir, self._stats())
|
| 596 |
+
content = index_path.read_text(encoding="utf-8")
|
| 597 |
+
assert "[[catalog]]" in content
|
| 598 |
+
|
| 599 |
+
def test_total_pages_updated(
|
| 600 |
+
self, tmp_path: Path
|
| 601 |
+
) -> None:
|
| 602 |
+
wiki_dir = tmp_path / "wiki"
|
| 603 |
+
wiki_dir.mkdir()
|
| 604 |
+
index_path = wiki_dir / "index.md"
|
| 605 |
+
index_path.write_text(
|
| 606 |
+
"# Index\n\nTotal pages: 0\n\nLast updated: 2020-01-01\n",
|
| 607 |
+
encoding="utf-8",
|
| 608 |
+
)
|
| 609 |
+
|
| 610 |
+
catalog_builder.update_wiki_index(wiki_dir, self._stats(total=42))
|
| 611 |
+
content = index_path.read_text(encoding="utf-8")
|
| 612 |
+
assert "Total pages: 42" in content
|
| 613 |
+
assert "Total pages: 0" not in content
|
| 614 |
+
|
| 615 |
+
def test_last_updated_replaced(
|
| 616 |
+
self, tmp_path: Path
|
| 617 |
+
) -> None:
|
| 618 |
+
wiki_dir = tmp_path / "wiki"
|
| 619 |
+
wiki_dir.mkdir()
|
| 620 |
+
index_path = wiki_dir / "index.md"
|
| 621 |
+
index_path.write_text(
|
| 622 |
+
"# Index\n\nLast updated: 1999-12-31\n",
|
| 623 |
+
encoding="utf-8",
|
| 624 |
+
)
|
| 625 |
+
|
| 626 |
+
catalog_builder.update_wiki_index(wiki_dir, self._stats())
|
| 627 |
+
content = index_path.read_text(encoding="utf-8")
|
| 628 |
+
assert "Last updated: 1999-12-31" not in content
|
| 629 |
+
# The new date should match YYYY-MM-DD pattern
|
| 630 |
+
assert re.search(r"Last updated: \d{4}-\d{2}-\d{2}", content)
|
| 631 |
+
|
| 632 |
+
def test_index_with_existing_catalog_ref_updates_counts(
|
| 633 |
+
self, tmp_path: Path
|
| 634 |
+
) -> None:
|
| 635 |
+
"""Already-present [[catalog]] should not be duplicated; total should update."""
|
| 636 |
+
wiki_dir = tmp_path / "wiki"
|
| 637 |
+
wiki_dir.mkdir()
|
| 638 |
+
index_path = wiki_dir / "index.md"
|
| 639 |
+
index_path.write_text(
|
| 640 |
+
"# Index\n\n[[catalog]]\n\nTotal pages: 1\n",
|
| 641 |
+
encoding="utf-8",
|
| 642 |
+
)
|
| 643 |
+
|
| 644 |
+
catalog_builder.update_wiki_index(wiki_dir, self._stats(total=99))
|
| 645 |
+
content = index_path.read_text(encoding="utf-8")
|
| 646 |
+
assert content.count("[[catalog]]") == 1
|
| 647 |
+
assert "Total pages: 99" in content
|
| 648 |
+
|
| 649 |
+
def test_empty_index_md(
|
| 650 |
+
self, tmp_path: Path
|
| 651 |
+
) -> None:
|
| 652 |
+
"""Empty index.md should not raise; catalog ref is appended."""
|
| 653 |
+
wiki_dir = tmp_path / "wiki"
|
| 654 |
+
wiki_dir.mkdir()
|
| 655 |
+
index_path = wiki_dir / "index.md"
|
| 656 |
+
index_path.write_text("", encoding="utf-8")
|
| 657 |
+
|
| 658 |
+
catalog_builder.update_wiki_index(wiki_dir, self._stats())
|
| 659 |
+
content = index_path.read_text(encoding="utf-8")
|
| 660 |
+
assert "[[catalog]]" in content
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
# ── append_log ────────────────────────────────────────────────────────────────
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
class TestAppendLog:
|
| 667 |
+
def _stats(self) -> dict:
|
| 668 |
+
return {
|
| 669 |
+
"total": 7,
|
| 670 |
+
"skills": 4,
|
| 671 |
+
"agents": 3,
|
| 672 |
+
"over_180": 2,
|
| 673 |
+
"catalog_path": "/tmp/wiki/catalog.md",
|
| 674 |
+
}
|
| 675 |
+
|
| 676 |
+
def test_no_log_md_is_noop(
|
| 677 |
+
self, tmp_path: Path
|
| 678 |
+
) -> None:
|
| 679 |
+
wiki_dir = tmp_path / "wiki"
|
| 680 |
+
wiki_dir.mkdir()
|
| 681 |
+
# log.md does not exist — must not raise
|
| 682 |
+
catalog_builder.append_log(wiki_dir, self._stats())
|
| 683 |
+
assert not (wiki_dir / "log.md").exists()
|
| 684 |
+
|
| 685 |
+
def test_entry_appended_to_existing_log(
|
| 686 |
+
self, tmp_path: Path
|
| 687 |
+
) -> None:
|
| 688 |
+
wiki_dir = tmp_path / "wiki"
|
| 689 |
+
wiki_dir.mkdir()
|
| 690 |
+
log_path = wiki_dir / "log.md"
|
| 691 |
+
log_path.write_text("# Log\n\nOld entry.\n", encoding="utf-8")
|
| 692 |
+
|
| 693 |
+
catalog_builder.append_log(wiki_dir, self._stats())
|
| 694 |
+
content = log_path.read_text(encoding="utf-8")
|
| 695 |
+
assert "Old entry." in content
|
| 696 |
+
assert "catalog-build" in content
|
| 697 |
+
|
| 698 |
+
def test_log_contains_counts(
|
| 699 |
+
self, tmp_path: Path
|
| 700 |
+
) -> None:
|
| 701 |
+
wiki_dir = tmp_path / "wiki"
|
| 702 |
+
wiki_dir.mkdir()
|
| 703 |
+
log_path = wiki_dir / "log.md"
|
| 704 |
+
log_path.write_text("", encoding="utf-8")
|
| 705 |
+
|
| 706 |
+
catalog_builder.append_log(wiki_dir, self._stats())
|
| 707 |
+
content = log_path.read_text(encoding="utf-8")
|
| 708 |
+
assert "7" in content # total
|
| 709 |
+
assert "4" in content # skills
|
| 710 |
+
assert "3" in content # agents
|
| 711 |
+
assert "2" in content # over_180
|
| 712 |
+
|
| 713 |
+
def test_log_contains_catalog_path(
|
| 714 |
+
self, tmp_path: Path
|
| 715 |
+
) -> None:
|
| 716 |
+
wiki_dir = tmp_path / "wiki"
|
| 717 |
+
wiki_dir.mkdir()
|
| 718 |
+
(wiki_dir / "log.md").write_text("", encoding="utf-8")
|
| 719 |
+
|
| 720 |
+
catalog_builder.append_log(wiki_dir, self._stats())
|
| 721 |
+
content = (wiki_dir / "log.md").read_text(encoding="utf-8")
|
| 722 |
+
assert "/tmp/wiki/catalog.md" in content
|
| 723 |
+
|
| 724 |
+
def test_log_contains_date(
|
| 725 |
+
self, tmp_path: Path
|
| 726 |
+
) -> None:
|
| 727 |
+
wiki_dir = tmp_path / "wiki"
|
| 728 |
+
wiki_dir.mkdir()
|
| 729 |
+
(wiki_dir / "log.md").write_text("", encoding="utf-8")
|
| 730 |
+
|
| 731 |
+
catalog_builder.append_log(wiki_dir, self._stats())
|
| 732 |
+
content = (wiki_dir / "log.md").read_text(encoding="utf-8")
|
| 733 |
+
assert re.search(r"\d{4}-\d{2}-\d{2}", content)
|
| 734 |
+
|
| 735 |
+
def test_multiple_appends_accumulate(
|
| 736 |
+
self, tmp_path: Path
|
| 737 |
+
) -> None:
|
| 738 |
+
wiki_dir = tmp_path / "wiki"
|
| 739 |
+
wiki_dir.mkdir()
|
| 740 |
+
log_path = wiki_dir / "log.md"
|
| 741 |
+
log_path.write_text("", encoding="utf-8")
|
| 742 |
+
|
| 743 |
+
catalog_builder.append_log(wiki_dir, self._stats())
|
| 744 |
+
catalog_builder.append_log(wiki_dir, self._stats())
|
| 745 |
+
content = log_path.read_text(encoding="utf-8")
|
| 746 |
+
assert content.count("catalog-build") == 2
|
| 747 |
+
|
| 748 |
+
def test_empty_log_md_gets_entry(
|
| 749 |
+
self, tmp_path: Path
|
| 750 |
+
) -> None:
|
| 751 |
+
wiki_dir = tmp_path / "wiki"
|
| 752 |
+
wiki_dir.mkdir()
|
| 753 |
+
(wiki_dir / "log.md").write_text("", encoding="utf-8")
|
| 754 |
+
|
| 755 |
+
catalog_builder.append_log(wiki_dir, self._stats())
|
| 756 |
+
content = (wiki_dir / "log.md").read_text(encoding="utf-8")
|
| 757 |
+
assert len(content) > 0
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
# ── Parametric edge-case coverage ──────────────────────────────────────────��─
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
class TestScanSkillsDirParametric:
|
| 764 |
+
@pytest.mark.parametrize("line_count", [0, 1, 179, 180, 181, 500])
|
| 765 |
+
def test_over_threshold_boundary(
|
| 766 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, line_count: int
|
| 767 |
+
) -> None:
|
| 768 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 769 |
+
skills_dir = tmp_path / "skills"
|
| 770 |
+
_make_skill(skills_dir, "skill", line_count)
|
| 771 |
+
result = catalog_builder.scan_skills_dir(skills_dir)
|
| 772 |
+
assert result[0]["over_180"] == (line_count > 180)
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
class TestScanAgentsDirParametric:
|
| 776 |
+
@pytest.mark.parametrize("line_count", [0, 1, 179, 180, 181, 500])
|
| 777 |
+
def test_over_threshold_boundary(
|
| 778 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, line_count: int
|
| 779 |
+
) -> None:
|
| 780 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 781 |
+
agents_dir = tmp_path / "agents"
|
| 782 |
+
_make_agent(agents_dir, "agent", line_count)
|
| 783 |
+
result = catalog_builder.scan_agents_dir(agents_dir)
|
| 784 |
+
assert result[0]["over_180"] == (line_count > 180)
|
| 785 |
+
|
| 786 |
+
|
| 787 |
+
class TestBuildCatalogParametric:
|
| 788 |
+
@pytest.mark.parametrize(
|
| 789 |
+
"n_skills,n_agents,expected_total",
|
| 790 |
+
[
|
| 791 |
+
(0, 0, 0),
|
| 792 |
+
(1, 0, 1),
|
| 793 |
+
(0, 1, 1),
|
| 794 |
+
(3, 3, 6),
|
| 795 |
+
(10, 5, 15),
|
| 796 |
+
],
|
| 797 |
+
)
|
| 798 |
+
def test_total_count(
|
| 799 |
+
self,
|
| 800 |
+
tmp_path: Path,
|
| 801 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 802 |
+
n_skills: int,
|
| 803 |
+
n_agents: int,
|
| 804 |
+
expected_total: int,
|
| 805 |
+
) -> None:
|
| 806 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 807 |
+
wiki_dir = tmp_path / "wiki"
|
| 808 |
+
wiki_dir.mkdir()
|
| 809 |
+
skills_dir = tmp_path / "skills"
|
| 810 |
+
agents_dir = tmp_path / "agents"
|
| 811 |
+
for i in range(n_skills):
|
| 812 |
+
_make_skill(skills_dir, f"skill-{i}", 10)
|
| 813 |
+
for i in range(n_agents):
|
| 814 |
+
_make_agent(agents_dir, f"agent-{i}", 10)
|
| 815 |
+
stats = catalog_builder.build_catalog(wiki_dir, skills_dir, agents_dir, [])
|
| 816 |
+
assert stats["total"] == expected_total
|
| 817 |
+
|
| 818 |
+
|
| 819 |
+
# ── main() CLI entrypoint ────────────────────────────────────────────────────
|
| 820 |
+
|
| 821 |
+
|
| 822 |
+
class TestMain:
|
| 823 |
+
"""Exercise the argparse entrypoint without touching real ~/.claude paths."""
|
| 824 |
+
|
| 825 |
+
def test_missing_wiki_exits_1(
|
| 826 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
| 827 |
+
) -> None:
|
| 828 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 829 |
+
wiki_dir = tmp_path / "wiki-missing"
|
| 830 |
+
# wiki_dir intentionally not created
|
| 831 |
+
monkeypatch.setattr(
|
| 832 |
+
"sys.argv",
|
| 833 |
+
[
|
| 834 |
+
"catalog_builder",
|
| 835 |
+
"--wiki", str(wiki_dir),
|
| 836 |
+
"--skills-dir", str(tmp_path / "skills"),
|
| 837 |
+
"--agents-dir", str(tmp_path / "agents"),
|
| 838 |
+
],
|
| 839 |
+
)
|
| 840 |
+
with pytest.raises(SystemExit) as exc_info:
|
| 841 |
+
catalog_builder.main()
|
| 842 |
+
assert exc_info.value.code == 1
|
| 843 |
+
err = capsys.readouterr().err
|
| 844 |
+
assert "Wiki not initialized" in err
|
| 845 |
+
|
| 846 |
+
def test_happy_path_prints_summary(
|
| 847 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
| 848 |
+
) -> None:
|
| 849 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 850 |
+
wiki_dir = tmp_path / "wiki"
|
| 851 |
+
wiki_dir.mkdir()
|
| 852 |
+
skills_dir = tmp_path / "skills"
|
| 853 |
+
agents_dir = tmp_path / "agents"
|
| 854 |
+
_make_skill(skills_dir, "demo-skill", 10)
|
| 855 |
+
_make_agent(agents_dir, "demo-agent", 5)
|
| 856 |
+
|
| 857 |
+
monkeypatch.setattr(
|
| 858 |
+
"sys.argv",
|
| 859 |
+
[
|
| 860 |
+
"catalog_builder",
|
| 861 |
+
"--wiki", str(wiki_dir),
|
| 862 |
+
"--skills-dir", str(skills_dir),
|
| 863 |
+
"--agents-dir", str(agents_dir),
|
| 864 |
+
],
|
| 865 |
+
)
|
| 866 |
+
catalog_builder.main()
|
| 867 |
+
out = capsys.readouterr().out
|
| 868 |
+
assert "Catalog built:" in out
|
| 869 |
+
assert "Written to:" in out
|
| 870 |
+
|
| 871 |
+
def test_extra_dirs_passed_through(
|
| 872 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
| 873 |
+
) -> None:
|
| 874 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 875 |
+
wiki_dir = tmp_path / "wiki"
|
| 876 |
+
wiki_dir.mkdir()
|
| 877 |
+
extra = tmp_path / "extra"
|
| 878 |
+
_make_skill(extra, "extra-skill", 10)
|
| 879 |
+
|
| 880 |
+
monkeypatch.setattr(
|
| 881 |
+
"sys.argv",
|
| 882 |
+
[
|
| 883 |
+
"catalog_builder",
|
| 884 |
+
"--wiki", str(wiki_dir),
|
| 885 |
+
"--skills-dir", str(tmp_path / "skills"),
|
| 886 |
+
"--agents-dir", str(tmp_path / "agents"),
|
| 887 |
+
"--extra-dirs", str(extra),
|
| 888 |
+
],
|
| 889 |
+
)
|
| 890 |
+
catalog_builder.main()
|
| 891 |
+
# catalog.md should exist and reference the extra skill
|
| 892 |
+
content = (wiki_dir / "catalog.md").read_text(encoding="utf-8")
|
| 893 |
+
assert "extra-skill" in content
|
| 894 |
+
|
| 895 |
+
def test_catalog_and_log_written_by_main(
|
| 896 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
| 897 |
+
) -> None:
|
| 898 |
+
_patched_cfg(monkeypatch, threshold=180)
|
| 899 |
+
wiki_dir = tmp_path / "wiki"
|
| 900 |
+
wiki_dir.mkdir()
|
| 901 |
+
# Pre-create log.md and index.md so update_wiki_index/append_log have targets
|
| 902 |
+
(wiki_dir / "log.md").write_text("", encoding="utf-8")
|
| 903 |
+
(wiki_dir / "index.md").write_text("# Index\n\nTotal pages: 0\n", encoding="utf-8")
|
| 904 |
+
|
| 905 |
+
monkeypatch.setattr(
|
| 906 |
+
"sys.argv",
|
| 907 |
+
[
|
| 908 |
+
"catalog_builder",
|
| 909 |
+
"--wiki", str(wiki_dir),
|
| 910 |
+
"--skills-dir", str(tmp_path / "skills"),
|
| 911 |
+
"--agents-dir", str(tmp_path / "agents"),
|
| 912 |
+
],
|
| 913 |
+
)
|
| 914 |
+
catalog_builder.main()
|
| 915 |
+
assert (wiki_dir / "catalog.md").exists()
|
| 916 |
+
log_content = (wiki_dir / "log.md").read_text(encoding="utf-8")
|
| 917 |
+
assert "catalog-build" in log_content
|
src/tests/test_change_detector.py
CHANGED
|
@@ -1,869 +1,869 @@
|
|
| 1 |
-
"""
|
| 2 |
-
test_change_detector.py -- Coverage sprint for change_detector.py.
|
| 3 |
-
|
| 4 |
-
change_detector is a pure-function diff engine: it hashes live files,
|
| 5 |
-
loads a manifest from the last snapshot directory, and returns a
|
| 6 |
-
ChangeReport dataclass. No filesystem writes, no subprocess calls.
|
| 7 |
-
|
| 8 |
-
Tests are grouped by the internal helper they exercise so regressions
|
| 9 |
-
surface at the exact layer where they occur.
|
| 10 |
-
"""
|
| 11 |
-
|
| 12 |
-
from __future__ import annotations
|
| 13 |
-
|
| 14 |
-
import hashlib
|
| 15 |
-
import json
|
| 16 |
-
from pathlib import Path
|
| 17 |
-
from typing import Any
|
| 18 |
-
|
| 19 |
-
import pytest
|
| 20 |
-
|
| 21 |
-
import change_detector
|
| 22 |
-
from backup_config import BackupConfig, BackupTree
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
# ── Helpers ──────────────────────────────────────────────────────────────────
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
def _default_cfg(**kwargs: Any) -> BackupConfig:
|
| 29 |
-
"""Return a BackupConfig with trees=() and memory_glob=False by default."""
|
| 30 |
-
base = {
|
| 31 |
-
"top_files": (),
|
| 32 |
-
"trees": (),
|
| 33 |
-
"memory_glob": False,
|
| 34 |
-
}
|
| 35 |
-
base.update(kwargs)
|
| 36 |
-
return BackupConfig(**base) # type: ignore[arg-type]
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
def _manifest_json(
|
| 40 |
-
entries: list[dict[str, Any]],
|
| 41 |
-
snapshot_id: str = "snap-001",
|
| 42 |
-
) -> str:
|
| 43 |
-
return json.dumps({"snapshot_id": snapshot_id, "entries": entries})
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
# ── TestChangeReport ─────────────────────────────────────────────────────────
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
class TestChangeReport:
|
| 50 |
-
"""Unit tests for the ChangeReport dataclass properties and methods."""
|
| 51 |
-
|
| 52 |
-
def test_has_changes_false_when_all_empty(self) -> None:
|
| 53 |
-
r = change_detector.ChangeReport(
|
| 54 |
-
new=(), changed=(), removed=(), unchanged=5, baseline_snapshot="x"
|
| 55 |
-
)
|
| 56 |
-
assert r.has_changes is False
|
| 57 |
-
|
| 58 |
-
def test_has_changes_true_when_new(self) -> None:
|
| 59 |
-
r = change_detector.ChangeReport(
|
| 60 |
-
new=("a.txt",), changed=(), removed=(), unchanged=0, baseline_snapshot=None
|
| 61 |
-
)
|
| 62 |
-
assert r.has_changes is True
|
| 63 |
-
|
| 64 |
-
def test_has_changes_true_when_changed(self) -> None:
|
| 65 |
-
r = change_detector.ChangeReport(
|
| 66 |
-
new=(), changed=("b.txt",), removed=(), unchanged=3, baseline_snapshot="x"
|
| 67 |
-
)
|
| 68 |
-
assert r.has_changes is True
|
| 69 |
-
|
| 70 |
-
def test_has_changes_true_when_removed(self) -> None:
|
| 71 |
-
r = change_detector.ChangeReport(
|
| 72 |
-
new=(), changed=(), removed=("c.txt",), unchanged=2, baseline_snapshot="x"
|
| 73 |
-
)
|
| 74 |
-
assert r.has_changes is True
|
| 75 |
-
|
| 76 |
-
def test_total_current_sums_new_changed_unchanged(self) -> None:
|
| 77 |
-
r = change_detector.ChangeReport(
|
| 78 |
-
new=("a",), changed=("b", "c"), removed=("z",), unchanged=7, baseline_snapshot="x"
|
| 79 |
-
)
|
| 80 |
-
# removed does NOT count toward total_current
|
| 81 |
-
assert r.total_current == 1 + 2 + 7
|
| 82 |
-
|
| 83 |
-
def test_total_current_zero_when_nothing_tracked(self) -> None:
|
| 84 |
-
r = change_detector.ChangeReport(
|
| 85 |
-
new=(), changed=(), removed=(), unchanged=0, baseline_snapshot=None
|
| 86 |
-
)
|
| 87 |
-
assert r.total_current == 0
|
| 88 |
-
|
| 89 |
-
def test_to_dict_includes_computed_properties(self) -> None:
|
| 90 |
-
r = change_detector.ChangeReport(
|
| 91 |
-
new=("f",), changed=(), removed=(), unchanged=2, baseline_snapshot="s1"
|
| 92 |
-
)
|
| 93 |
-
d = r.to_dict()
|
| 94 |
-
assert d["has_changes"] is True
|
| 95 |
-
assert d["total_current"] == 3
|
| 96 |
-
assert d["new"] == ("f",)
|
| 97 |
-
assert d["baseline_snapshot"] == "s1"
|
| 98 |
-
|
| 99 |
-
def test_to_dict_has_changes_false_path(self) -> None:
|
| 100 |
-
r = change_detector.ChangeReport(
|
| 101 |
-
new=(), changed=(), removed=(), unchanged=1, baseline_snapshot="s1"
|
| 102 |
-
)
|
| 103 |
-
d = r.to_dict()
|
| 104 |
-
assert d["has_changes"] is False
|
| 105 |
-
assert d["total_current"] == 1
|
| 106 |
-
|
| 107 |
-
def test_report_is_frozen_dataclass(self) -> None:
|
| 108 |
-
r = change_detector.ChangeReport(
|
| 109 |
-
new=(), changed=(), removed=(), unchanged=0, baseline_snapshot=None
|
| 110 |
-
)
|
| 111 |
-
with pytest.raises((AttributeError, TypeError)):
|
| 112 |
-
r.unchanged = 99 # type: ignore[misc]
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
# ── TestSha256File ────────────────────────────────────────────────────────────
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
class TestSha256File:
|
| 119 |
-
"""Tests for the internal _sha256_file helper."""
|
| 120 |
-
|
| 121 |
-
def test_known_content_matches_expected_digest(self, tmp_path: Path) -> None:
|
| 122 |
-
f = tmp_path / "known.txt"
|
| 123 |
-
f.write_bytes(b"hello world")
|
| 124 |
-
expected = hashlib.sha256(b"hello world").hexdigest()
|
| 125 |
-
assert change_detector._sha256_file(f) == expected
|
| 126 |
-
|
| 127 |
-
def test_empty_file_has_stable_digest(self, tmp_path: Path) -> None:
|
| 128 |
-
f = tmp_path / "empty.bin"
|
| 129 |
-
f.write_bytes(b"")
|
| 130 |
-
digest = change_detector._sha256_file(f)
|
| 131 |
-
assert digest == hashlib.sha256(b"").hexdigest()
|
| 132 |
-
|
| 133 |
-
def test_same_content_same_digest(self, tmp_path: Path) -> None:
|
| 134 |
-
f1 = tmp_path / "a.txt"
|
| 135 |
-
f2 = tmp_path / "b.txt"
|
| 136 |
-
f1.write_bytes(b"content")
|
| 137 |
-
f2.write_bytes(b"content")
|
| 138 |
-
assert change_detector._sha256_file(f1) == change_detector._sha256_file(f2)
|
| 139 |
-
|
| 140 |
-
def test_different_content_different_digest(self, tmp_path: Path) -> None:
|
| 141 |
-
f1 = tmp_path / "a.txt"
|
| 142 |
-
f2 = tmp_path / "b.txt"
|
| 143 |
-
f1.write_bytes(b"content-A")
|
| 144 |
-
f2.write_bytes(b"content-B")
|
| 145 |
-
assert change_detector._sha256_file(f1) != change_detector._sha256_file(f2)
|
| 146 |
-
|
| 147 |
-
def test_single_byte_change_changes_digest(self, tmp_path: Path) -> None:
|
| 148 |
-
f = tmp_path / "data.bin"
|
| 149 |
-
f.write_bytes(b"abcdefgh")
|
| 150 |
-
d1 = change_detector._sha256_file(f)
|
| 151 |
-
f.write_bytes(b"abcdefgX")
|
| 152 |
-
d2 = change_detector._sha256_file(f)
|
| 153 |
-
assert d1 != d2
|
| 154 |
-
|
| 155 |
-
def test_symlink_returns_none(self, tmp_path: Path) -> None:
|
| 156 |
-
target = tmp_path / "real.txt"
|
| 157 |
-
target.write_bytes(b"data")
|
| 158 |
-
link = tmp_path / "link.txt"
|
| 159 |
-
try:
|
| 160 |
-
link.symlink_to(target)
|
| 161 |
-
except (OSError, NotImplementedError):
|
| 162 |
-
pytest.skip("symlinks not supported on this platform")
|
| 163 |
-
assert change_detector._sha256_file(link) is None
|
| 164 |
-
|
| 165 |
-
def test_missing_file_returns_none(self, tmp_path: Path) -> None:
|
| 166 |
-
assert change_detector._sha256_file(tmp_path / "ghost.txt") is None
|
| 167 |
-
|
| 168 |
-
def test_returns_lowercase_hex_string(self, tmp_path: Path) -> None:
|
| 169 |
-
f = tmp_path / "f.bin"
|
| 170 |
-
f.write_bytes(b"\xff\xfe")
|
| 171 |
-
digest = change_detector._sha256_file(f)
|
| 172 |
-
assert digest is not None
|
| 173 |
-
assert digest == digest.lower()
|
| 174 |
-
assert len(digest) == 64
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
# ── TestIterTopFiles ──────────────────────────────────────────────────────────
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
class TestIterTopFiles:
|
| 181 |
-
"""Tests for _iter_top_files."""
|
| 182 |
-
|
| 183 |
-
def test_yields_existing_regular_files(self, tmp_path: Path) -> None:
|
| 184 |
-
(tmp_path / "settings.json").write_text("{}", encoding="utf-8")
|
| 185 |
-
cfg = _default_cfg(top_files=("settings.json",))
|
| 186 |
-
results = list(change_detector._iter_top_files(cfg, tmp_path))
|
| 187 |
-
assert len(results) == 1
|
| 188 |
-
name, path = results[0]
|
| 189 |
-
assert name == "settings.json"
|
| 190 |
-
assert path == tmp_path / "settings.json"
|
| 191 |
-
|
| 192 |
-
def test_missing_file_not_yielded(self, tmp_path: Path) -> None:
|
| 193 |
-
cfg = _default_cfg(top_files=("missing.json",))
|
| 194 |
-
assert list(change_detector._iter_top_files(cfg, tmp_path)) == []
|
| 195 |
-
|
| 196 |
-
def test_symlink_not_yielded(self, tmp_path: Path) -> None:
|
| 197 |
-
target = tmp_path / "real.json"
|
| 198 |
-
target.write_text("{}", encoding="utf-8")
|
| 199 |
-
link = tmp_path / "link.json"
|
| 200 |
-
try:
|
| 201 |
-
link.symlink_to(target)
|
| 202 |
-
except (OSError, NotImplementedError):
|
| 203 |
-
pytest.skip("symlinks not supported on this platform")
|
| 204 |
-
cfg = _default_cfg(top_files=("link.json",))
|
| 205 |
-
assert list(change_detector._iter_top_files(cfg, tmp_path)) == []
|
| 206 |
-
|
| 207 |
-
def test_empty_top_files_yields_nothing(self, tmp_path: Path) -> None:
|
| 208 |
-
cfg = _default_cfg(top_files=())
|
| 209 |
-
assert list(change_detector._iter_top_files(cfg, tmp_path)) == []
|
| 210 |
-
|
| 211 |
-
def test_multiple_files_all_yielded(self, tmp_path: Path) -> None:
|
| 212 |
-
for name in ("a.json", "b.md", "c.json"):
|
| 213 |
-
(tmp_path / name).write_text("x", encoding="utf-8")
|
| 214 |
-
cfg = _default_cfg(top_files=("a.json", "b.md", "c.json"))
|
| 215 |
-
names = [n for n, _ in change_detector._iter_top_files(cfg, tmp_path)]
|
| 216 |
-
assert sorted(names) == ["a.json", "b.md", "c.json"]
|
| 217 |
-
|
| 218 |
-
def test_directory_not_yielded(self, tmp_path: Path) -> None:
|
| 219 |
-
(tmp_path / "notafile").mkdir()
|
| 220 |
-
cfg = _default_cfg(top_files=("notafile",))
|
| 221 |
-
assert list(change_detector._iter_top_files(cfg, tmp_path)) == []
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
# ── TestIterTreeFiles ─────────────────────────────────────────────────────────
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
class TestIterTreeFiles:
|
| 228 |
-
"""Tests for _iter_tree_files."""
|
| 229 |
-
|
| 230 |
-
def _make_tree(self, base: Path, subpath: str, content: bytes = b"data") -> Path:
|
| 231 |
-
p = base / subpath
|
| 232 |
-
p.parent.mkdir(parents=True, exist_ok=True)
|
| 233 |
-
p.write_bytes(content)
|
| 234 |
-
return p
|
| 235 |
-
|
| 236 |
-
def test_yields_files_under_tree(self, tmp_path: Path) -> None:
|
| 237 |
-
self._make_tree(tmp_path, "skills/python/SKILL.md")
|
| 238 |
-
cfg = _default_cfg(trees=(BackupTree(src="skills", dest="skills"),))
|
| 239 |
-
results = list(change_detector._iter_tree_files(cfg, tmp_path))
|
| 240 |
-
dest_rels = [d for d, _ in results]
|
| 241 |
-
assert "skills/python/SKILL.md" in dest_rels
|
| 242 |
-
|
| 243 |
-
def test_missing_tree_root_yields_nothing(self, tmp_path: Path) -> None:
|
| 244 |
-
cfg = _default_cfg(trees=(BackupTree(src="nonexistent", dest="nonexistent"),))
|
| 245 |
-
assert list(change_detector._iter_tree_files(cfg, tmp_path)) == []
|
| 246 |
-
|
| 247 |
-
def test_file_exceeding_max_bytes_skipped(self, tmp_path: Path) -> None:
|
| 248 |
-
big = tmp_path / "agents" / "big.md"
|
| 249 |
-
big.parent.mkdir(parents=True)
|
| 250 |
-
big.write_bytes(b"x" * 100)
|
| 251 |
-
cfg = _default_cfg(
|
| 252 |
-
trees=(BackupTree(src="agents", dest="agents"),),
|
| 253 |
-
max_file_bytes=50,
|
| 254 |
-
)
|
| 255 |
-
assert list(change_detector._iter_tree_files(cfg, tmp_path)) == []
|
| 256 |
-
|
| 257 |
-
def test_file_exactly_at_max_bytes_included(self, tmp_path: Path) -> None:
|
| 258 |
-
f = tmp_path / "agents" / "exact.md"
|
| 259 |
-
f.parent.mkdir(parents=True)
|
| 260 |
-
f.write_bytes(b"x" * 50)
|
| 261 |
-
cfg = _default_cfg(
|
| 262 |
-
trees=(BackupTree(src="agents", dest="agents"),),
|
| 263 |
-
max_file_bytes=50,
|
| 264 |
-
)
|
| 265 |
-
results = list(change_detector._iter_tree_files(cfg, tmp_path))
|
| 266 |
-
assert len(results) == 1
|
| 267 |
-
|
| 268 |
-
def test_symlink_file_skipped(self, tmp_path: Path) -> None:
|
| 269 |
-
target = tmp_path / "agents" / "real.md"
|
| 270 |
-
target.parent.mkdir(parents=True)
|
| 271 |
-
target.write_bytes(b"content")
|
| 272 |
-
link = tmp_path / "agents" / "link.md"
|
| 273 |
-
try:
|
| 274 |
-
link.symlink_to(target)
|
| 275 |
-
except (OSError, NotImplementedError):
|
| 276 |
-
pytest.skip("symlinks not supported on this platform")
|
| 277 |
-
cfg = _default_cfg(trees=(BackupTree(src="agents", dest="agents"),))
|
| 278 |
-
# Only the real file should appear, not the symlink.
|
| 279 |
-
results = list(change_detector._iter_tree_files(cfg, tmp_path))
|
| 280 |
-
dest_rels = [d for d, _ in results]
|
| 281 |
-
assert "agents/link.md" not in dest_rels
|
| 282 |
-
assert "agents/real.md" in dest_rels
|
| 283 |
-
|
| 284 |
-
def test_dest_rel_uses_tree_dest_prefix(self, tmp_path: Path) -> None:
|
| 285 |
-
self._make_tree(tmp_path, "raw_agents/subdir/file.md")
|
| 286 |
-
cfg = _default_cfg(trees=(BackupTree(src="raw_agents", dest="my_agents"),))
|
| 287 |
-
results = list(change_detector._iter_tree_files(cfg, tmp_path))
|
| 288 |
-
dest_rels = [d for d, _ in results]
|
| 289 |
-
assert "my_agents/subdir/file.md" in dest_rels
|
| 290 |
-
|
| 291 |
-
def test_empty_trees_yields_nothing(self, tmp_path: Path) -> None:
|
| 292 |
-
cfg = _default_cfg(trees=())
|
| 293 |
-
assert list(change_detector._iter_tree_files(cfg, tmp_path)) == []
|
| 294 |
-
|
| 295 |
-
def test_nested_subdirectories_walked(self, tmp_path: Path) -> None:
|
| 296 |
-
for subpath in ("skills/a/b/c/deep.md", "skills/top.md"):
|
| 297 |
-
self._make_tree(tmp_path, subpath)
|
| 298 |
-
cfg = _default_cfg(trees=(BackupTree(src="skills", dest="skills"),))
|
| 299 |
-
results = list(change_detector._iter_tree_files(cfg, tmp_path))
|
| 300 |
-
dest_rels = [d for d, _ in results]
|
| 301 |
-
assert "skills/a/b/c/deep.md" in dest_rels
|
| 302 |
-
assert "skills/top.md" in dest_rels
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
# ── TestIterMemoryFiles ───────────────────────────────────────────────────────
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
class TestIterMemoryFiles:
|
| 309 |
-
"""Tests for _iter_memory_files."""
|
| 310 |
-
|
| 311 |
-
def _make_memory_file(
|
| 312 |
-
self, base: Path, slug: str, filename: str, content: bytes = b"mem"
|
| 313 |
-
) -> Path:
|
| 314 |
-
p = base / "projects" / slug / "memory" / filename
|
| 315 |
-
p.parent.mkdir(parents=True, exist_ok=True)
|
| 316 |
-
p.write_bytes(content)
|
| 317 |
-
return p
|
| 318 |
-
|
| 319 |
-
def test_memory_glob_false_yields_nothing(self, tmp_path: Path) -> None:
|
| 320 |
-
self._make_memory_file(tmp_path, "proj-slug", "MEMORY.md")
|
| 321 |
-
cfg = _default_cfg(memory_glob=False)
|
| 322 |
-
assert list(change_detector._iter_memory_files(cfg, tmp_path)) == []
|
| 323 |
-
|
| 324 |
-
def test_missing_projects_dir_yields_nothing(self, tmp_path: Path) -> None:
|
| 325 |
-
cfg = _default_cfg(memory_glob=True)
|
| 326 |
-
assert list(change_detector._iter_memory_files(cfg, tmp_path)) == []
|
| 327 |
-
|
| 328 |
-
def test_yields_memory_files_under_projects(self, tmp_path: Path) -> None:
|
| 329 |
-
self._make_memory_file(tmp_path, "my-proj", "NOTE.md")
|
| 330 |
-
cfg = _default_cfg(memory_glob=True)
|
| 331 |
-
results = list(change_detector._iter_memory_files(cfg, tmp_path))
|
| 332 |
-
dest_rels = [d for d, _ in results]
|
| 333 |
-
assert "memory/my-proj/NOTE.md" in dest_rels
|
| 334 |
-
|
| 335 |
-
def test_dest_rel_includes_slug_and_filename(self, tmp_path: Path) -> None:
|
| 336 |
-
self._make_memory_file(tmp_path, "alpha", "a.md")
|
| 337 |
-
self._make_memory_file(tmp_path, "beta", "b.md")
|
| 338 |
-
cfg = _default_cfg(memory_glob=True)
|
| 339 |
-
results = list(change_detector._iter_memory_files(cfg, tmp_path))
|
| 340 |
-
dest_rels = {d for d, _ in results}
|
| 341 |
-
assert "memory/alpha/a.md" in dest_rels
|
| 342 |
-
assert "memory/beta/b.md" in dest_rels
|
| 343 |
-
|
| 344 |
-
def test_file_exceeding_max_bytes_skipped(self, tmp_path: Path) -> None:
|
| 345 |
-
self._make_memory_file(tmp_path, "proj", "big.md", content=b"x" * 200)
|
| 346 |
-
cfg = _default_cfg(memory_glob=True, max_file_bytes=100)
|
| 347 |
-
assert list(change_detector._iter_memory_files(cfg, tmp_path)) == []
|
| 348 |
-
|
| 349 |
-
def test_symlink_memory_file_skipped(self, tmp_path: Path) -> None:
|
| 350 |
-
target = self._make_memory_file(tmp_path, "proj", "real.md")
|
| 351 |
-
link = tmp_path / "projects" / "proj" / "memory" / "link.md"
|
| 352 |
-
try:
|
| 353 |
-
link.symlink_to(target)
|
| 354 |
-
except (OSError, NotImplementedError):
|
| 355 |
-
pytest.skip("symlinks not supported on this platform")
|
| 356 |
-
cfg = _default_cfg(memory_glob=True)
|
| 357 |
-
results = list(change_detector._iter_memory_files(cfg, tmp_path))
|
| 358 |
-
dest_rels = [d for d, _ in results]
|
| 359 |
-
assert "memory/proj/link.md" not in dest_rels
|
| 360 |
-
assert "memory/proj/real.md" in dest_rels
|
| 361 |
-
|
| 362 |
-
def test_project_file_not_dir_ignored(self, tmp_path: Path) -> None:
|
| 363 |
-
"""A file directly inside projects/ (not a dir) must be skipped."""
|
| 364 |
-
projects = tmp_path / "projects"
|
| 365 |
-
projects.mkdir(parents=True)
|
| 366 |
-
(projects / "stray-file.txt").write_text("x", encoding="utf-8")
|
| 367 |
-
cfg = _default_cfg(memory_glob=True)
|
| 368 |
-
assert list(change_detector._iter_memory_files(cfg, tmp_path)) == []
|
| 369 |
-
|
| 370 |
-
def test_slug_without_memory_subdir_skipped(self, tmp_path: Path) -> None:
|
| 371 |
-
slug_dir = tmp_path / "projects" / "no-memory"
|
| 372 |
-
slug_dir.mkdir(parents=True)
|
| 373 |
-
cfg = _default_cfg(memory_glob=True)
|
| 374 |
-
assert list(change_detector._iter_memory_files(cfg, tmp_path)) == []
|
| 375 |
-
|
| 376 |
-
def test_nested_memory_path_dest_rel(self, tmp_path: Path) -> None:
|
| 377 |
-
nested = tmp_path / "projects" / "proj" / "memory" / "sub" / "deep.md"
|
| 378 |
-
nested.parent.mkdir(parents=True, exist_ok=True)
|
| 379 |
-
nested.write_bytes(b"content")
|
| 380 |
-
cfg = _default_cfg(memory_glob=True)
|
| 381 |
-
results = list(change_detector._iter_memory_files(cfg, tmp_path))
|
| 382 |
-
dest_rels = [d for d, _ in results]
|
| 383 |
-
assert "memory/proj/sub/deep.md" in dest_rels
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
# ── TestLoadSnapshotHashes ────────────────────────────────────────────────────
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
class TestLoadSnapshotHashes:
|
| 390 |
-
"""Tests for the internal _load_snapshot_hashes helper."""
|
| 391 |
-
|
| 392 |
-
def test_missing_manifest_returns_empty(self, tmp_path: Path) -> None:
|
| 393 |
-
snap = tmp_path / "snap"
|
| 394 |
-
snap.mkdir()
|
| 395 |
-
assert change_detector._load_snapshot_hashes(snap) == {}
|
| 396 |
-
|
| 397 |
-
def test_corrupt_json_returns_empty(self, tmp_path: Path) -> None:
|
| 398 |
-
snap = tmp_path / "snap"
|
| 399 |
-
snap.mkdir()
|
| 400 |
-
(snap / "manifest.json").write_text("{NOT JSON", encoding="utf-8")
|
| 401 |
-
assert change_detector._load_snapshot_hashes(snap) == {}
|
| 402 |
-
|
| 403 |
-
def test_valid_manifest_returns_mapping(self, tmp_path: Path) -> None:
|
| 404 |
-
snap = tmp_path / "snap"
|
| 405 |
-
snap.mkdir()
|
| 406 |
-
(snap / "manifest.json").write_text(
|
| 407 |
-
_manifest_json([{"dest": "settings.json", "sha256": "abc123"}]),
|
| 408 |
-
encoding="utf-8",
|
| 409 |
-
)
|
| 410 |
-
result = change_detector._load_snapshot_hashes(snap)
|
| 411 |
-
assert result == {"settings.json": "abc123"}
|
| 412 |
-
|
| 413 |
-
def test_entries_missing_dest_skipped(self, tmp_path: Path) -> None:
|
| 414 |
-
snap = tmp_path / "snap"
|
| 415 |
-
snap.mkdir()
|
| 416 |
-
(snap / "manifest.json").write_text(
|
| 417 |
-
_manifest_json([{"sha256": "abc"}, {"dest": "ok.md", "sha256": "def"}]),
|
| 418 |
-
encoding="utf-8",
|
| 419 |
-
)
|
| 420 |
-
result = change_detector._load_snapshot_hashes(snap)
|
| 421 |
-
assert "ok.md" in result
|
| 422 |
-
assert len(result) == 1
|
| 423 |
-
|
| 424 |
-
def test_entries_missing_sha256_skipped(self, tmp_path: Path) -> None:
|
| 425 |
-
snap = tmp_path / "snap"
|
| 426 |
-
snap.mkdir()
|
| 427 |
-
(snap / "manifest.json").write_text(
|
| 428 |
-
_manifest_json([{"dest": "x.md"}, {"dest": "y.md", "sha256": "hash"}]),
|
| 429 |
-
encoding="utf-8",
|
| 430 |
-
)
|
| 431 |
-
result = change_detector._load_snapshot_hashes(snap)
|
| 432 |
-
assert result == {"y.md": "hash"}
|
| 433 |
-
|
| 434 |
-
def test_entries_null_values_skipped(self, tmp_path: Path) -> None:
|
| 435 |
-
snap = tmp_path / "snap"
|
| 436 |
-
snap.mkdir()
|
| 437 |
-
(snap / "manifest.json").write_text(
|
| 438 |
-
_manifest_json([{"dest": None, "sha256": "x"}, {"dest": "z.md", "sha256": "y"}]),
|
| 439 |
-
encoding="utf-8",
|
| 440 |
-
)
|
| 441 |
-
result = change_detector._load_snapshot_hashes(snap)
|
| 442 |
-
assert result == {"z.md": "y"}
|
| 443 |
-
|
| 444 |
-
def test_empty_entries_returns_empty(self, tmp_path: Path) -> None:
|
| 445 |
-
snap = tmp_path / "snap"
|
| 446 |
-
snap.mkdir()
|
| 447 |
-
(snap / "manifest.json").write_text(
|
| 448 |
-
json.dumps({"snapshot_id": "s", "entries": []}),
|
| 449 |
-
encoding="utf-8",
|
| 450 |
-
)
|
| 451 |
-
assert change_detector._load_snapshot_hashes(snap) == {}
|
| 452 |
-
|
| 453 |
-
def test_manifest_without_entries_key_returns_empty(self, tmp_path: Path) -> None:
|
| 454 |
-
snap = tmp_path / "snap"
|
| 455 |
-
snap.mkdir()
|
| 456 |
-
(snap / "manifest.json").write_text(
|
| 457 |
-
json.dumps({"snapshot_id": "s"}),
|
| 458 |
-
encoding="utf-8",
|
| 459 |
-
)
|
| 460 |
-
assert change_detector._load_snapshot_hashes(snap) == {}
|
| 461 |
-
|
| 462 |
-
def test_multiple_entries_all_loaded(self, tmp_path: Path) -> None:
|
| 463 |
-
snap = tmp_path / "snap"
|
| 464 |
-
snap.mkdir()
|
| 465 |
-
entries = [
|
| 466 |
-
{"dest": "a.md", "sha256": "hash-a"},
|
| 467 |
-
{"dest": "b.md", "sha256": "hash-b"},
|
| 468 |
-
{"dest": "c.md", "sha256": "hash-c"},
|
| 469 |
-
]
|
| 470 |
-
(snap / "manifest.json").write_text(
|
| 471 |
-
_manifest_json(entries), encoding="utf-8"
|
| 472 |
-
)
|
| 473 |
-
result = change_detector._load_snapshot_hashes(snap)
|
| 474 |
-
assert len(result) == 3
|
| 475 |
-
assert result["b.md"] == "hash-b"
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
# ── TestSnapshotId ────────────────────────────────────────────────────────────
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
class TestSnapshotId:
|
| 482 |
-
"""Tests for the internal _snapshot_id helper."""
|
| 483 |
-
|
| 484 |
-
def test_reads_snapshot_id_from_manifest(self, tmp_path: Path) -> None:
|
| 485 |
-
snap = tmp_path / "20240101T120000Z"
|
| 486 |
-
snap.mkdir()
|
| 487 |
-
(snap / "manifest.json").write_text(
|
| 488 |
-
json.dumps({"snapshot_id": "custom-id-42", "entries": []}),
|
| 489 |
-
encoding="utf-8",
|
| 490 |
-
)
|
| 491 |
-
assert change_detector._snapshot_id(snap) == "custom-id-42"
|
| 492 |
-
|
| 493 |
-
def test_falls_back_to_dir_name_on_missing_manifest(self, tmp_path: Path) -> None:
|
| 494 |
-
snap = tmp_path / "fallback-name"
|
| 495 |
-
snap.mkdir()
|
| 496 |
-
assert change_detector._snapshot_id(snap) == "fallback-name"
|
| 497 |
-
|
| 498 |
-
def test_falls_back_to_dir_name_on_corrupt_json(self, tmp_path: Path) -> None:
|
| 499 |
-
snap = tmp_path / "fallback-corrupt"
|
| 500 |
-
snap.mkdir()
|
| 501 |
-
(snap / "manifest.json").write_text("{BAD JSON", encoding="utf-8")
|
| 502 |
-
assert change_detector._snapshot_id(snap) == "fallback-corrupt"
|
| 503 |
-
|
| 504 |
-
def test_falls_back_to_dir_name_when_snapshot_id_absent(self, tmp_path: Path) -> None:
|
| 505 |
-
snap = tmp_path / "dir-name-fallback"
|
| 506 |
-
snap.mkdir()
|
| 507 |
-
(snap / "manifest.json").write_text(
|
| 508 |
-
json.dumps({"entries": []}), encoding="utf-8"
|
| 509 |
-
)
|
| 510 |
-
assert change_detector._snapshot_id(snap) == "dir-name-fallback"
|
| 511 |
-
|
| 512 |
-
def test_snapshot_id_none_falls_back_to_dir_name(self, tmp_path: Path) -> None:
|
| 513 |
-
snap = tmp_path / "none-id-fallback"
|
| 514 |
-
snap.mkdir()
|
| 515 |
-
(snap / "manifest.json").write_text(
|
| 516 |
-
json.dumps({"snapshot_id": None, "entries": []}),
|
| 517 |
-
encoding="utf-8",
|
| 518 |
-
)
|
| 519 |
-
# None -> falsy -> falls back to snap.name
|
| 520 |
-
assert change_detector._snapshot_id(snap) == "none-id-fallback"
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
# ── TestDetectChanges ─────────────────────────────────────────────────────────
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
class TestDetectChanges:
|
| 527 |
-
"""Integration tests for the public detect_changes function."""
|
| 528 |
-
|
| 529 |
-
def _write_file(self, path: Path, content: bytes = b"content") -> None:
|
| 530 |
-
path.parent.mkdir(parents=True, exist_ok=True)
|
| 531 |
-
path.write_bytes(content)
|
| 532 |
-
|
| 533 |
-
def _write_manifest(
|
| 534 |
-
self,
|
| 535 |
-
snap: Path,
|
| 536 |
-
entries: list[dict[str, Any]],
|
| 537 |
-
snapshot_id: str = "baseline-snap",
|
| 538 |
-
) -> None:
|
| 539 |
-
snap.mkdir(parents=True, exist_ok=True)
|
| 540 |
-
(snap / "manifest.json").write_text(
|
| 541 |
-
_manifest_json(entries, snapshot_id), encoding="utf-8"
|
| 542 |
-
)
|
| 543 |
-
|
| 544 |
-
# -- No baseline --
|
| 545 |
-
|
| 546 |
-
def test_no_baseline_all_files_are_new(self, tmp_path: Path) -> None:
|
| 547 |
-
claude_home = tmp_path / "home"
|
| 548 |
-
claude_home.mkdir()
|
| 549 |
-
(claude_home / "settings.json").write_text("{}", encoding="utf-8")
|
| 550 |
-
cfg = _default_cfg(top_files=("settings.json",))
|
| 551 |
-
report = change_detector.detect_changes(cfg, claude_home, last_snapshot=None)
|
| 552 |
-
assert "settings.json" in report.new
|
| 553 |
-
assert report.changed == ()
|
| 554 |
-
assert report.removed == ()
|
| 555 |
-
assert report.unchanged == 0
|
| 556 |
-
assert report.baseline_snapshot is None
|
| 557 |
-
|
| 558 |
-
def test_none_snapshot_no_tracked_files(self, tmp_path: Path) -> None:
|
| 559 |
-
cfg = _default_cfg()
|
| 560 |
-
report = change_detector.detect_changes(cfg, tmp_path, last_snapshot=None)
|
| 561 |
-
assert report.new == ()
|
| 562 |
-
assert report.has_changes is False
|
| 563 |
-
assert report.baseline_snapshot is None
|
| 564 |
-
|
| 565 |
-
def test_nonexistent_snapshot_dir_treated_as_no_baseline(
|
| 566 |
-
self, tmp_path: Path
|
| 567 |
-
) -> None:
|
| 568 |
-
claude_home = tmp_path / "home"
|
| 569 |
-
claude_home.mkdir()
|
| 570 |
-
(claude_home / "CLAUDE.md").write_text("hi", encoding="utf-8")
|
| 571 |
-
cfg = _default_cfg(top_files=("CLAUDE.md",))
|
| 572 |
-
ghost_snap = tmp_path / "nonexistent-snap"
|
| 573 |
-
report = change_detector.detect_changes(cfg, claude_home, ghost_snap)
|
| 574 |
-
assert "CLAUDE.md" in report.new
|
| 575 |
-
assert report.baseline_snapshot is None
|
| 576 |
-
|
| 577 |
-
# -- All unchanged --
|
| 578 |
-
|
| 579 |
-
def test_all_files_unchanged(self, tmp_path: Path) -> None:
|
| 580 |
-
claude_home = tmp_path / "home"
|
| 581 |
-
claude_home.mkdir()
|
| 582 |
-
f = claude_home / "settings.json"
|
| 583 |
-
f.write_bytes(b"same")
|
| 584 |
-
digest = hashlib.sha256(b"same").hexdigest()
|
| 585 |
-
snap = tmp_path / "snap"
|
| 586 |
-
self._write_manifest(snap, [{"dest": "settings.json", "sha256": digest}])
|
| 587 |
-
cfg = _default_cfg(top_files=("settings.json",))
|
| 588 |
-
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 589 |
-
assert report.new == ()
|
| 590 |
-
assert report.changed == ()
|
| 591 |
-
assert report.removed == ()
|
| 592 |
-
assert report.unchanged == 1
|
| 593 |
-
assert report.has_changes is False
|
| 594 |
-
|
| 595 |
-
# -- New files --
|
| 596 |
-
|
| 597 |
-
def test_file_absent_from_baseline_is_new(self, tmp_path: Path) -> None:
|
| 598 |
-
claude_home = tmp_path / "home"
|
| 599 |
-
claude_home.mkdir()
|
| 600 |
-
(claude_home / "new.json").write_bytes(b"new content")
|
| 601 |
-
snap = tmp_path / "snap"
|
| 602 |
-
self._write_manifest(snap, []) # empty baseline
|
| 603 |
-
cfg = _default_cfg(top_files=("new.json",))
|
| 604 |
-
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 605 |
-
assert "new.json" in report.new
|
| 606 |
-
assert report.changed == ()
|
| 607 |
-
assert report.removed == ()
|
| 608 |
-
|
| 609 |
-
# -- Changed files --
|
| 610 |
-
|
| 611 |
-
def test_file_with_different_hash_is_changed(self, tmp_path: Path) -> None:
|
| 612 |
-
claude_home = tmp_path / "home"
|
| 613 |
-
claude_home.mkdir()
|
| 614 |
-
f = claude_home / "CLAUDE.md"
|
| 615 |
-
f.write_bytes(b"new-content")
|
| 616 |
-
snap = tmp_path / "snap"
|
| 617 |
-
self._write_manifest(snap, [{"dest": "CLAUDE.md", "sha256": "old-stale-hash"}])
|
| 618 |
-
cfg = _default_cfg(top_files=("CLAUDE.md",))
|
| 619 |
-
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 620 |
-
assert "CLAUDE.md" in report.changed
|
| 621 |
-
assert report.new == ()
|
| 622 |
-
assert report.removed == ()
|
| 623 |
-
|
| 624 |
-
# -- Removed files --
|
| 625 |
-
|
| 626 |
-
def test_file_in_baseline_not_on_disk_is_removed(self, tmp_path: Path) -> None:
|
| 627 |
-
claude_home = tmp_path / "home"
|
| 628 |
-
claude_home.mkdir()
|
| 629 |
-
snap = tmp_path / "snap"
|
| 630 |
-
self._write_manifest(snap, [{"dest": "gone.json", "sha256": "dead"}])
|
| 631 |
-
cfg = _default_cfg(top_files=("gone.json",))
|
| 632 |
-
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 633 |
-
assert "gone.json" in report.removed
|
| 634 |
-
assert report.new == ()
|
| 635 |
-
assert report.changed == ()
|
| 636 |
-
|
| 637 |
-
# -- Combined --
|
| 638 |
-
|
| 639 |
-
def test_mixed_new_changed_removed_unchanged(self, tmp_path: Path) -> None:
|
| 640 |
-
claude_home = tmp_path / "home"
|
| 641 |
-
claude_home.mkdir()
|
| 642 |
-
|
| 643 |
-
# new — present now, absent in baseline
|
| 644 |
-
(claude_home / "new.json").write_bytes(b"fresh")
|
| 645 |
-
# changed — present now, different hash in baseline
|
| 646 |
-
(claude_home / "changed.json").write_bytes(b"modified")
|
| 647 |
-
hashlib.sha256(b"modified").hexdigest()
|
| 648 |
-
# unchanged — present now, same hash
|
| 649 |
-
(claude_home / "same.json").write_bytes(b"identical")
|
| 650 |
-
same_digest = hashlib.sha256(b"identical").hexdigest()
|
| 651 |
-
# removed — in baseline, not on disk
|
| 652 |
-
|
| 653 |
-
snap = tmp_path / "snap"
|
| 654 |
-
self._write_manifest(snap, [
|
| 655 |
-
{"dest": "changed.json", "sha256": "stale-hash"},
|
| 656 |
-
{"dest": "same.json", "sha256": same_digest},
|
| 657 |
-
{"dest": "removed.json", "sha256": "any-hash"},
|
| 658 |
-
])
|
| 659 |
-
cfg = _default_cfg(top_files=("new.json", "changed.json", "same.json", "removed.json"))
|
| 660 |
-
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 661 |
-
|
| 662 |
-
assert "new.json" in report.new
|
| 663 |
-
assert "changed.json" in report.changed
|
| 664 |
-
assert "removed.json" in report.removed
|
| 665 |
-
assert report.unchanged == 1
|
| 666 |
-
assert report.has_changes is True
|
| 667 |
-
assert report.baseline_snapshot == "baseline-snap"
|
| 668 |
-
|
| 669 |
-
# -- Snapshot ID propagation --
|
| 670 |
-
|
| 671 |
-
def test_baseline_snapshot_id_propagated(self, tmp_path: Path) -> None:
|
| 672 |
-
claude_home = tmp_path / "home"
|
| 673 |
-
claude_home.mkdir()
|
| 674 |
-
snap = tmp_path / "snap"
|
| 675 |
-
self._write_manifest(snap, [], snapshot_id="my-snap-xyz")
|
| 676 |
-
cfg = _default_cfg()
|
| 677 |
-
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 678 |
-
assert report.baseline_snapshot == "my-snap-xyz"
|
| 679 |
-
|
| 680 |
-
# -- Trees integration --
|
| 681 |
-
|
| 682 |
-
def test_tree_files_compared_against_baseline(self, tmp_path: Path) -> None:
|
| 683 |
-
claude_home = tmp_path / "home"
|
| 684 |
-
skill_file = claude_home / "skills" / "py" / "SKILL.md"
|
| 685 |
-
skill_file.parent.mkdir(parents=True)
|
| 686 |
-
skill_file.write_bytes(b"skill content")
|
| 687 |
-
digest = hashlib.sha256(b"skill content").hexdigest()
|
| 688 |
-
|
| 689 |
-
snap = tmp_path / "snap"
|
| 690 |
-
self._write_manifest(snap, [{"dest": "skills/py/SKILL.md", "sha256": digest}])
|
| 691 |
-
cfg = BackupConfig(
|
| 692 |
-
top_files=(),
|
| 693 |
-
trees=(BackupTree(src="skills", dest="skills"),),
|
| 694 |
-
memory_glob=False,
|
| 695 |
-
)
|
| 696 |
-
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 697 |
-
assert report.unchanged == 1
|
| 698 |
-
assert report.has_changes is False
|
| 699 |
-
|
| 700 |
-
# -- Memory files integration --
|
| 701 |
-
|
| 702 |
-
def test_memory_files_detected_as_new(self, tmp_path: Path) -> None:
|
| 703 |
-
claude_home = tmp_path / "home"
|
| 704 |
-
mem_file = claude_home / "projects" / "proj-x" / "memory" / "MEMORY.md"
|
| 705 |
-
mem_file.parent.mkdir(parents=True)
|
| 706 |
-
mem_file.write_bytes(b"mem data")
|
| 707 |
-
|
| 708 |
-
snap = tmp_path / "snap"
|
| 709 |
-
self._write_manifest(snap, []) # empty baseline
|
| 710 |
-
cfg = _default_cfg(memory_glob=True)
|
| 711 |
-
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 712 |
-
assert any("memory/proj-x" in d for d in report.new)
|
| 713 |
-
|
| 714 |
-
# -- Sorted output --
|
| 715 |
-
|
| 716 |
-
def test_new_files_are_sorted(self, tmp_path: Path) -> None:
|
| 717 |
-
claude_home = tmp_path / "home"
|
| 718 |
-
claude_home.mkdir()
|
| 719 |
-
for name in ("z.json", "a.json", "m.json"):
|
| 720 |
-
(claude_home / name).write_bytes(b"x")
|
| 721 |
-
cfg = _default_cfg(top_files=("z.json", "a.json", "m.json"))
|
| 722 |
-
report = change_detector.detect_changes(cfg, claude_home, last_snapshot=None)
|
| 723 |
-
assert list(report.new) == sorted(report.new)
|
| 724 |
-
|
| 725 |
-
def test_changed_files_are_sorted(self, tmp_path: Path) -> None:
|
| 726 |
-
claude_home = tmp_path / "home"
|
| 727 |
-
claude_home.mkdir()
|
| 728 |
-
files = ["z.json", "a.json", "m.json"]
|
| 729 |
-
for name in files:
|
| 730 |
-
(claude_home / name).write_bytes(b"current")
|
| 731 |
-
snap = tmp_path / "snap"
|
| 732 |
-
self._write_manifest(snap, [{"dest": n, "sha256": "old"} for n in files])
|
| 733 |
-
cfg = _default_cfg(top_files=tuple(files))
|
| 734 |
-
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 735 |
-
assert list(report.changed) == sorted(report.changed)
|
| 736 |
-
|
| 737 |
-
# -- Symlink in tracked path --
|
| 738 |
-
|
| 739 |
-
def test_symlink_top_file_not_counted(self, tmp_path: Path) -> None:
|
| 740 |
-
claude_home = tmp_path / "home"
|
| 741 |
-
claude_home.mkdir()
|
| 742 |
-
target = claude_home / "real.json"
|
| 743 |
-
target.write_bytes(b"content")
|
| 744 |
-
link = claude_home / "settings.json"
|
| 745 |
-
try:
|
| 746 |
-
link.symlink_to(target)
|
| 747 |
-
except (OSError, NotImplementedError):
|
| 748 |
-
pytest.skip("symlinks not supported on this platform")
|
| 749 |
-
snap = tmp_path / "snap"
|
| 750 |
-
self._write_manifest(snap, [])
|
| 751 |
-
cfg = _default_cfg(top_files=("settings.json",))
|
| 752 |
-
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 753 |
-
# _iter_top_files skips the symlink → nothing in current state
|
| 754 |
-
assert report.new == ()
|
| 755 |
-
|
| 756 |
-
# -- Large file skipped by max_file_bytes --
|
| 757 |
-
|
| 758 |
-
def test_oversized_tree_file_never_counted_as_new(self, tmp_path: Path) -> None:
|
| 759 |
-
claude_home = tmp_path / "home"
|
| 760 |
-
big = claude_home / "agents" / "huge.md"
|
| 761 |
-
big.parent.mkdir(parents=True)
|
| 762 |
-
big.write_bytes(b"x" * 1000)
|
| 763 |
-
snap = tmp_path / "snap"
|
| 764 |
-
self._write_manifest(snap, [])
|
| 765 |
-
cfg = BackupConfig(
|
| 766 |
-
top_files=(),
|
| 767 |
-
trees=(BackupTree(src="agents", dest="agents"),),
|
| 768 |
-
memory_glob=False,
|
| 769 |
-
max_file_bytes=500,
|
| 770 |
-
)
|
| 771 |
-
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 772 |
-
assert report.new == ()
|
| 773 |
-
|
| 774 |
-
# -- Parametrized: baseline_snapshot vs no baseline --
|
| 775 |
-
|
| 776 |
-
@pytest.mark.parametrize(
|
| 777 |
-
"last_snapshot_is_none,expected_baseline",
|
| 778 |
-
[
|
| 779 |
-
(True, None),
|
| 780 |
-
(False, "snap-id"),
|
| 781 |
-
],
|
| 782 |
-
)
|
| 783 |
-
def test_baseline_snapshot_field(
|
| 784 |
-
self,
|
| 785 |
-
tmp_path: Path,
|
| 786 |
-
last_snapshot_is_none: bool,
|
| 787 |
-
expected_baseline: str | None,
|
| 788 |
-
) -> None:
|
| 789 |
-
claude_home = tmp_path / "home"
|
| 790 |
-
claude_home.mkdir()
|
| 791 |
-
if last_snapshot_is_none:
|
| 792 |
-
snap = None
|
| 793 |
-
else:
|
| 794 |
-
snap = tmp_path / "snap"
|
| 795 |
-
self._write_manifest(snap, [], snapshot_id="snap-id")
|
| 796 |
-
cfg = _default_cfg()
|
| 797 |
-
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 798 |
-
assert report.baseline_snapshot == expected_baseline
|
| 799 |
-
|
| 800 |
-
# -- Parametrized: has_changes conditions --
|
| 801 |
-
|
| 802 |
-
@pytest.mark.parametrize(
|
| 803 |
-
"new,changed,removed,unchanged,expect_changes",
|
| 804 |
-
[
|
| 805 |
-
((), (), (), 0, False),
|
| 806 |
-
(("a",), (), (), 0, True),
|
| 807 |
-
((), ("b",), (), 0, True),
|
| 808 |
-
((), (), ("c",), 0, True),
|
| 809 |
-
((), (), (), 5, False),
|
| 810 |
-
(("a",), ("b",), ("c",), 2, True),
|
| 811 |
-
],
|
| 812 |
-
)
|
| 813 |
-
def test_has_changes_parametrized(
|
| 814 |
-
self,
|
| 815 |
-
new: tuple[str, ...],
|
| 816 |
-
changed: tuple[str, ...],
|
| 817 |
-
removed: tuple[str, ...],
|
| 818 |
-
unchanged: int,
|
| 819 |
-
expect_changes: bool,
|
| 820 |
-
) -> None:
|
| 821 |
-
r = change_detector.ChangeReport(
|
| 822 |
-
new=new,
|
| 823 |
-
changed=changed,
|
| 824 |
-
removed=removed,
|
| 825 |
-
unchanged=unchanged,
|
| 826 |
-
baseline_snapshot=None,
|
| 827 |
-
)
|
| 828 |
-
assert r.has_changes is expect_changes
|
| 829 |
-
|
| 830 |
-
# -- Corrupt manifest in snapshot dir --
|
| 831 |
-
|
| 832 |
-
def test_corrupt_manifest_treats_all_current_as_new(self, tmp_path: Path) -> None:
|
| 833 |
-
claude_home = tmp_path / "home"
|
| 834 |
-
claude_home.mkdir()
|
| 835 |
-
(claude_home / "settings.json").write_bytes(b"data")
|
| 836 |
-
snap = tmp_path / "snap"
|
| 837 |
-
snap.mkdir()
|
| 838 |
-
(snap / "manifest.json").write_text("{INVALID", encoding="utf-8")
|
| 839 |
-
cfg = _default_cfg(top_files=("settings.json",))
|
| 840 |
-
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 841 |
-
# Corrupt manifest → empty baseline → settings.json treated as new
|
| 842 |
-
assert "settings.json" in report.new
|
| 843 |
-
assert report.removed == ()
|
| 844 |
-
|
| 845 |
-
# -- total_current property via detect_changes --
|
| 846 |
-
|
| 847 |
-
def test_total_current_counts_new_changed_unchanged_not_removed(
|
| 848 |
-
self, tmp_path: Path
|
| 849 |
-
) -> None:
|
| 850 |
-
claude_home = tmp_path / "home"
|
| 851 |
-
claude_home.mkdir()
|
| 852 |
-
# 2 new files
|
| 853 |
-
(claude_home / "a.json").write_bytes(b"a")
|
| 854 |
-
(claude_home / "b.json").write_bytes(b"b")
|
| 855 |
-
# 1 unchanged
|
| 856 |
-
(claude_home / "c.json").write_bytes(b"same")
|
| 857 |
-
same_d = hashlib.sha256(b"same").hexdigest()
|
| 858 |
-
# 1 changed
|
| 859 |
-
(claude_home / "d.json").write_bytes(b"new")
|
| 860 |
-
snap = tmp_path / "snap"
|
| 861 |
-
self._write_manifest(snap, [
|
| 862 |
-
{"dest": "c.json", "sha256": same_d},
|
| 863 |
-
{"dest": "d.json", "sha256": "old-hash"},
|
| 864 |
-
{"dest": "removed.json", "sha256": "r-hash"},
|
| 865 |
-
])
|
| 866 |
-
cfg = _default_cfg(top_files=("a.json", "b.json", "c.json", "d.json"))
|
| 867 |
-
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 868 |
-
# new=2, changed=1, unchanged=1 → total_current=4
|
| 869 |
-
assert report.total_current == 4
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_change_detector.py -- Coverage sprint for change_detector.py.
|
| 3 |
+
|
| 4 |
+
change_detector is a pure-function diff engine: it hashes live files,
|
| 5 |
+
loads a manifest from the last snapshot directory, and returns a
|
| 6 |
+
ChangeReport dataclass. No filesystem writes, no subprocess calls.
|
| 7 |
+
|
| 8 |
+
Tests are grouped by the internal helper they exercise so regressions
|
| 9 |
+
surface at the exact layer where they occur.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import hashlib
|
| 15 |
+
import json
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from typing import Any
|
| 18 |
+
|
| 19 |
+
import pytest
|
| 20 |
+
|
| 21 |
+
import change_detector
|
| 22 |
+
from backup_config import BackupConfig, BackupTree
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# ── Helpers ──────────────────────────────────────────────────────────────────
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _default_cfg(**kwargs: Any) -> BackupConfig:
|
| 29 |
+
"""Return a BackupConfig with trees=() and memory_glob=False by default."""
|
| 30 |
+
base = {
|
| 31 |
+
"top_files": (),
|
| 32 |
+
"trees": (),
|
| 33 |
+
"memory_glob": False,
|
| 34 |
+
}
|
| 35 |
+
base.update(kwargs)
|
| 36 |
+
return BackupConfig(**base) # type: ignore[arg-type]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _manifest_json(
|
| 40 |
+
entries: list[dict[str, Any]],
|
| 41 |
+
snapshot_id: str = "snap-001",
|
| 42 |
+
) -> str:
|
| 43 |
+
return json.dumps({"snapshot_id": snapshot_id, "entries": entries})
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# ── TestChangeReport ─────────────────────────────────────────────────────────
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class TestChangeReport:
|
| 50 |
+
"""Unit tests for the ChangeReport dataclass properties and methods."""
|
| 51 |
+
|
| 52 |
+
def test_has_changes_false_when_all_empty(self) -> None:
|
| 53 |
+
r = change_detector.ChangeReport(
|
| 54 |
+
new=(), changed=(), removed=(), unchanged=5, baseline_snapshot="x"
|
| 55 |
+
)
|
| 56 |
+
assert r.has_changes is False
|
| 57 |
+
|
| 58 |
+
def test_has_changes_true_when_new(self) -> None:
|
| 59 |
+
r = change_detector.ChangeReport(
|
| 60 |
+
new=("a.txt",), changed=(), removed=(), unchanged=0, baseline_snapshot=None
|
| 61 |
+
)
|
| 62 |
+
assert r.has_changes is True
|
| 63 |
+
|
| 64 |
+
def test_has_changes_true_when_changed(self) -> None:
|
| 65 |
+
r = change_detector.ChangeReport(
|
| 66 |
+
new=(), changed=("b.txt",), removed=(), unchanged=3, baseline_snapshot="x"
|
| 67 |
+
)
|
| 68 |
+
assert r.has_changes is True
|
| 69 |
+
|
| 70 |
+
def test_has_changes_true_when_removed(self) -> None:
|
| 71 |
+
r = change_detector.ChangeReport(
|
| 72 |
+
new=(), changed=(), removed=("c.txt",), unchanged=2, baseline_snapshot="x"
|
| 73 |
+
)
|
| 74 |
+
assert r.has_changes is True
|
| 75 |
+
|
| 76 |
+
def test_total_current_sums_new_changed_unchanged(self) -> None:
|
| 77 |
+
r = change_detector.ChangeReport(
|
| 78 |
+
new=("a",), changed=("b", "c"), removed=("z",), unchanged=7, baseline_snapshot="x"
|
| 79 |
+
)
|
| 80 |
+
# removed does NOT count toward total_current
|
| 81 |
+
assert r.total_current == 1 + 2 + 7
|
| 82 |
+
|
| 83 |
+
def test_total_current_zero_when_nothing_tracked(self) -> None:
|
| 84 |
+
r = change_detector.ChangeReport(
|
| 85 |
+
new=(), changed=(), removed=(), unchanged=0, baseline_snapshot=None
|
| 86 |
+
)
|
| 87 |
+
assert r.total_current == 0
|
| 88 |
+
|
| 89 |
+
def test_to_dict_includes_computed_properties(self) -> None:
|
| 90 |
+
r = change_detector.ChangeReport(
|
| 91 |
+
new=("f",), changed=(), removed=(), unchanged=2, baseline_snapshot="s1"
|
| 92 |
+
)
|
| 93 |
+
d = r.to_dict()
|
| 94 |
+
assert d["has_changes"] is True
|
| 95 |
+
assert d["total_current"] == 3
|
| 96 |
+
assert d["new"] == ("f",)
|
| 97 |
+
assert d["baseline_snapshot"] == "s1"
|
| 98 |
+
|
| 99 |
+
def test_to_dict_has_changes_false_path(self) -> None:
|
| 100 |
+
r = change_detector.ChangeReport(
|
| 101 |
+
new=(), changed=(), removed=(), unchanged=1, baseline_snapshot="s1"
|
| 102 |
+
)
|
| 103 |
+
d = r.to_dict()
|
| 104 |
+
assert d["has_changes"] is False
|
| 105 |
+
assert d["total_current"] == 1
|
| 106 |
+
|
| 107 |
+
def test_report_is_frozen_dataclass(self) -> None:
|
| 108 |
+
r = change_detector.ChangeReport(
|
| 109 |
+
new=(), changed=(), removed=(), unchanged=0, baseline_snapshot=None
|
| 110 |
+
)
|
| 111 |
+
with pytest.raises((AttributeError, TypeError)):
|
| 112 |
+
r.unchanged = 99 # type: ignore[misc]
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# ── TestSha256File ────────────────────────────────────────────────────────────
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class TestSha256File:
|
| 119 |
+
"""Tests for the internal _sha256_file helper."""
|
| 120 |
+
|
| 121 |
+
def test_known_content_matches_expected_digest(self, tmp_path: Path) -> None:
|
| 122 |
+
f = tmp_path / "known.txt"
|
| 123 |
+
f.write_bytes(b"hello world")
|
| 124 |
+
expected = hashlib.sha256(b"hello world").hexdigest()
|
| 125 |
+
assert change_detector._sha256_file(f) == expected
|
| 126 |
+
|
| 127 |
+
def test_empty_file_has_stable_digest(self, tmp_path: Path) -> None:
|
| 128 |
+
f = tmp_path / "empty.bin"
|
| 129 |
+
f.write_bytes(b"")
|
| 130 |
+
digest = change_detector._sha256_file(f)
|
| 131 |
+
assert digest == hashlib.sha256(b"").hexdigest()
|
| 132 |
+
|
| 133 |
+
def test_same_content_same_digest(self, tmp_path: Path) -> None:
|
| 134 |
+
f1 = tmp_path / "a.txt"
|
| 135 |
+
f2 = tmp_path / "b.txt"
|
| 136 |
+
f1.write_bytes(b"content")
|
| 137 |
+
f2.write_bytes(b"content")
|
| 138 |
+
assert change_detector._sha256_file(f1) == change_detector._sha256_file(f2)
|
| 139 |
+
|
| 140 |
+
def test_different_content_different_digest(self, tmp_path: Path) -> None:
|
| 141 |
+
f1 = tmp_path / "a.txt"
|
| 142 |
+
f2 = tmp_path / "b.txt"
|
| 143 |
+
f1.write_bytes(b"content-A")
|
| 144 |
+
f2.write_bytes(b"content-B")
|
| 145 |
+
assert change_detector._sha256_file(f1) != change_detector._sha256_file(f2)
|
| 146 |
+
|
| 147 |
+
def test_single_byte_change_changes_digest(self, tmp_path: Path) -> None:
|
| 148 |
+
f = tmp_path / "data.bin"
|
| 149 |
+
f.write_bytes(b"abcdefgh")
|
| 150 |
+
d1 = change_detector._sha256_file(f)
|
| 151 |
+
f.write_bytes(b"abcdefgX")
|
| 152 |
+
d2 = change_detector._sha256_file(f)
|
| 153 |
+
assert d1 != d2
|
| 154 |
+
|
| 155 |
+
def test_symlink_returns_none(self, tmp_path: Path) -> None:
|
| 156 |
+
target = tmp_path / "real.txt"
|
| 157 |
+
target.write_bytes(b"data")
|
| 158 |
+
link = tmp_path / "link.txt"
|
| 159 |
+
try:
|
| 160 |
+
link.symlink_to(target)
|
| 161 |
+
except (OSError, NotImplementedError):
|
| 162 |
+
pytest.skip("symlinks not supported on this platform")
|
| 163 |
+
assert change_detector._sha256_file(link) is None
|
| 164 |
+
|
| 165 |
+
def test_missing_file_returns_none(self, tmp_path: Path) -> None:
|
| 166 |
+
assert change_detector._sha256_file(tmp_path / "ghost.txt") is None
|
| 167 |
+
|
| 168 |
+
def test_returns_lowercase_hex_string(self, tmp_path: Path) -> None:
|
| 169 |
+
f = tmp_path / "f.bin"
|
| 170 |
+
f.write_bytes(b"\xff\xfe")
|
| 171 |
+
digest = change_detector._sha256_file(f)
|
| 172 |
+
assert digest is not None
|
| 173 |
+
assert digest == digest.lower()
|
| 174 |
+
assert len(digest) == 64
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
# ── TestIterTopFiles ──────────────────────────────────────────────────────────
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class TestIterTopFiles:
|
| 181 |
+
"""Tests for _iter_top_files."""
|
| 182 |
+
|
| 183 |
+
def test_yields_existing_regular_files(self, tmp_path: Path) -> None:
|
| 184 |
+
(tmp_path / "settings.json").write_text("{}", encoding="utf-8")
|
| 185 |
+
cfg = _default_cfg(top_files=("settings.json",))
|
| 186 |
+
results = list(change_detector._iter_top_files(cfg, tmp_path))
|
| 187 |
+
assert len(results) == 1
|
| 188 |
+
name, path = results[0]
|
| 189 |
+
assert name == "settings.json"
|
| 190 |
+
assert path == tmp_path / "settings.json"
|
| 191 |
+
|
| 192 |
+
def test_missing_file_not_yielded(self, tmp_path: Path) -> None:
|
| 193 |
+
cfg = _default_cfg(top_files=("missing.json",))
|
| 194 |
+
assert list(change_detector._iter_top_files(cfg, tmp_path)) == []
|
| 195 |
+
|
| 196 |
+
def test_symlink_not_yielded(self, tmp_path: Path) -> None:
|
| 197 |
+
target = tmp_path / "real.json"
|
| 198 |
+
target.write_text("{}", encoding="utf-8")
|
| 199 |
+
link = tmp_path / "link.json"
|
| 200 |
+
try:
|
| 201 |
+
link.symlink_to(target)
|
| 202 |
+
except (OSError, NotImplementedError):
|
| 203 |
+
pytest.skip("symlinks not supported on this platform")
|
| 204 |
+
cfg = _default_cfg(top_files=("link.json",))
|
| 205 |
+
assert list(change_detector._iter_top_files(cfg, tmp_path)) == []
|
| 206 |
+
|
| 207 |
+
def test_empty_top_files_yields_nothing(self, tmp_path: Path) -> None:
|
| 208 |
+
cfg = _default_cfg(top_files=())
|
| 209 |
+
assert list(change_detector._iter_top_files(cfg, tmp_path)) == []
|
| 210 |
+
|
| 211 |
+
def test_multiple_files_all_yielded(self, tmp_path: Path) -> None:
|
| 212 |
+
for name in ("a.json", "b.md", "c.json"):
|
| 213 |
+
(tmp_path / name).write_text("x", encoding="utf-8")
|
| 214 |
+
cfg = _default_cfg(top_files=("a.json", "b.md", "c.json"))
|
| 215 |
+
names = [n for n, _ in change_detector._iter_top_files(cfg, tmp_path)]
|
| 216 |
+
assert sorted(names) == ["a.json", "b.md", "c.json"]
|
| 217 |
+
|
| 218 |
+
def test_directory_not_yielded(self, tmp_path: Path) -> None:
|
| 219 |
+
(tmp_path / "notafile").mkdir()
|
| 220 |
+
cfg = _default_cfg(top_files=("notafile",))
|
| 221 |
+
assert list(change_detector._iter_top_files(cfg, tmp_path)) == []
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
# ── TestIterTreeFiles ─────────────────────────────────────────────────────────
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
class TestIterTreeFiles:
|
| 228 |
+
"""Tests for _iter_tree_files."""
|
| 229 |
+
|
| 230 |
+
def _make_tree(self, base: Path, subpath: str, content: bytes = b"data") -> Path:
|
| 231 |
+
p = base / subpath
|
| 232 |
+
p.parent.mkdir(parents=True, exist_ok=True)
|
| 233 |
+
p.write_bytes(content)
|
| 234 |
+
return p
|
| 235 |
+
|
| 236 |
+
def test_yields_files_under_tree(self, tmp_path: Path) -> None:
|
| 237 |
+
self._make_tree(tmp_path, "skills/python/SKILL.md")
|
| 238 |
+
cfg = _default_cfg(trees=(BackupTree(src="skills", dest="skills"),))
|
| 239 |
+
results = list(change_detector._iter_tree_files(cfg, tmp_path))
|
| 240 |
+
dest_rels = [d for d, _ in results]
|
| 241 |
+
assert "skills/python/SKILL.md" in dest_rels
|
| 242 |
+
|
| 243 |
+
def test_missing_tree_root_yields_nothing(self, tmp_path: Path) -> None:
|
| 244 |
+
cfg = _default_cfg(trees=(BackupTree(src="nonexistent", dest="nonexistent"),))
|
| 245 |
+
assert list(change_detector._iter_tree_files(cfg, tmp_path)) == []
|
| 246 |
+
|
| 247 |
+
def test_file_exceeding_max_bytes_skipped(self, tmp_path: Path) -> None:
|
| 248 |
+
big = tmp_path / "agents" / "big.md"
|
| 249 |
+
big.parent.mkdir(parents=True)
|
| 250 |
+
big.write_bytes(b"x" * 100)
|
| 251 |
+
cfg = _default_cfg(
|
| 252 |
+
trees=(BackupTree(src="agents", dest="agents"),),
|
| 253 |
+
max_file_bytes=50,
|
| 254 |
+
)
|
| 255 |
+
assert list(change_detector._iter_tree_files(cfg, tmp_path)) == []
|
| 256 |
+
|
| 257 |
+
def test_file_exactly_at_max_bytes_included(self, tmp_path: Path) -> None:
|
| 258 |
+
f = tmp_path / "agents" / "exact.md"
|
| 259 |
+
f.parent.mkdir(parents=True)
|
| 260 |
+
f.write_bytes(b"x" * 50)
|
| 261 |
+
cfg = _default_cfg(
|
| 262 |
+
trees=(BackupTree(src="agents", dest="agents"),),
|
| 263 |
+
max_file_bytes=50,
|
| 264 |
+
)
|
| 265 |
+
results = list(change_detector._iter_tree_files(cfg, tmp_path))
|
| 266 |
+
assert len(results) == 1
|
| 267 |
+
|
| 268 |
+
def test_symlink_file_skipped(self, tmp_path: Path) -> None:
|
| 269 |
+
target = tmp_path / "agents" / "real.md"
|
| 270 |
+
target.parent.mkdir(parents=True)
|
| 271 |
+
target.write_bytes(b"content")
|
| 272 |
+
link = tmp_path / "agents" / "link.md"
|
| 273 |
+
try:
|
| 274 |
+
link.symlink_to(target)
|
| 275 |
+
except (OSError, NotImplementedError):
|
| 276 |
+
pytest.skip("symlinks not supported on this platform")
|
| 277 |
+
cfg = _default_cfg(trees=(BackupTree(src="agents", dest="agents"),))
|
| 278 |
+
# Only the real file should appear, not the symlink.
|
| 279 |
+
results = list(change_detector._iter_tree_files(cfg, tmp_path))
|
| 280 |
+
dest_rels = [d for d, _ in results]
|
| 281 |
+
assert "agents/link.md" not in dest_rels
|
| 282 |
+
assert "agents/real.md" in dest_rels
|
| 283 |
+
|
| 284 |
+
def test_dest_rel_uses_tree_dest_prefix(self, tmp_path: Path) -> None:
|
| 285 |
+
self._make_tree(tmp_path, "raw_agents/subdir/file.md")
|
| 286 |
+
cfg = _default_cfg(trees=(BackupTree(src="raw_agents", dest="my_agents"),))
|
| 287 |
+
results = list(change_detector._iter_tree_files(cfg, tmp_path))
|
| 288 |
+
dest_rels = [d for d, _ in results]
|
| 289 |
+
assert "my_agents/subdir/file.md" in dest_rels
|
| 290 |
+
|
| 291 |
+
def test_empty_trees_yields_nothing(self, tmp_path: Path) -> None:
|
| 292 |
+
cfg = _default_cfg(trees=())
|
| 293 |
+
assert list(change_detector._iter_tree_files(cfg, tmp_path)) == []
|
| 294 |
+
|
| 295 |
+
def test_nested_subdirectories_walked(self, tmp_path: Path) -> None:
|
| 296 |
+
for subpath in ("skills/a/b/c/deep.md", "skills/top.md"):
|
| 297 |
+
self._make_tree(tmp_path, subpath)
|
| 298 |
+
cfg = _default_cfg(trees=(BackupTree(src="skills", dest="skills"),))
|
| 299 |
+
results = list(change_detector._iter_tree_files(cfg, tmp_path))
|
| 300 |
+
dest_rels = [d for d, _ in results]
|
| 301 |
+
assert "skills/a/b/c/deep.md" in dest_rels
|
| 302 |
+
assert "skills/top.md" in dest_rels
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
# ── TestIterMemoryFiles ───────────────────────────────────────────────────────
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
class TestIterMemoryFiles:
|
| 309 |
+
"""Tests for _iter_memory_files."""
|
| 310 |
+
|
| 311 |
+
def _make_memory_file(
|
| 312 |
+
self, base: Path, slug: str, filename: str, content: bytes = b"mem"
|
| 313 |
+
) -> Path:
|
| 314 |
+
p = base / "projects" / slug / "memory" / filename
|
| 315 |
+
p.parent.mkdir(parents=True, exist_ok=True)
|
| 316 |
+
p.write_bytes(content)
|
| 317 |
+
return p
|
| 318 |
+
|
| 319 |
+
def test_memory_glob_false_yields_nothing(self, tmp_path: Path) -> None:
|
| 320 |
+
self._make_memory_file(tmp_path, "proj-slug", "MEMORY.md")
|
| 321 |
+
cfg = _default_cfg(memory_glob=False)
|
| 322 |
+
assert list(change_detector._iter_memory_files(cfg, tmp_path)) == []
|
| 323 |
+
|
| 324 |
+
def test_missing_projects_dir_yields_nothing(self, tmp_path: Path) -> None:
|
| 325 |
+
cfg = _default_cfg(memory_glob=True)
|
| 326 |
+
assert list(change_detector._iter_memory_files(cfg, tmp_path)) == []
|
| 327 |
+
|
| 328 |
+
def test_yields_memory_files_under_projects(self, tmp_path: Path) -> None:
|
| 329 |
+
self._make_memory_file(tmp_path, "my-proj", "NOTE.md")
|
| 330 |
+
cfg = _default_cfg(memory_glob=True)
|
| 331 |
+
results = list(change_detector._iter_memory_files(cfg, tmp_path))
|
| 332 |
+
dest_rels = [d for d, _ in results]
|
| 333 |
+
assert "memory/my-proj/NOTE.md" in dest_rels
|
| 334 |
+
|
| 335 |
+
def test_dest_rel_includes_slug_and_filename(self, tmp_path: Path) -> None:
|
| 336 |
+
self._make_memory_file(tmp_path, "alpha", "a.md")
|
| 337 |
+
self._make_memory_file(tmp_path, "beta", "b.md")
|
| 338 |
+
cfg = _default_cfg(memory_glob=True)
|
| 339 |
+
results = list(change_detector._iter_memory_files(cfg, tmp_path))
|
| 340 |
+
dest_rels = {d for d, _ in results}
|
| 341 |
+
assert "memory/alpha/a.md" in dest_rels
|
| 342 |
+
assert "memory/beta/b.md" in dest_rels
|
| 343 |
+
|
| 344 |
+
def test_file_exceeding_max_bytes_skipped(self, tmp_path: Path) -> None:
|
| 345 |
+
self._make_memory_file(tmp_path, "proj", "big.md", content=b"x" * 200)
|
| 346 |
+
cfg = _default_cfg(memory_glob=True, max_file_bytes=100)
|
| 347 |
+
assert list(change_detector._iter_memory_files(cfg, tmp_path)) == []
|
| 348 |
+
|
| 349 |
+
def test_symlink_memory_file_skipped(self, tmp_path: Path) -> None:
|
| 350 |
+
target = self._make_memory_file(tmp_path, "proj", "real.md")
|
| 351 |
+
link = tmp_path / "projects" / "proj" / "memory" / "link.md"
|
| 352 |
+
try:
|
| 353 |
+
link.symlink_to(target)
|
| 354 |
+
except (OSError, NotImplementedError):
|
| 355 |
+
pytest.skip("symlinks not supported on this platform")
|
| 356 |
+
cfg = _default_cfg(memory_glob=True)
|
| 357 |
+
results = list(change_detector._iter_memory_files(cfg, tmp_path))
|
| 358 |
+
dest_rels = [d for d, _ in results]
|
| 359 |
+
assert "memory/proj/link.md" not in dest_rels
|
| 360 |
+
assert "memory/proj/real.md" in dest_rels
|
| 361 |
+
|
| 362 |
+
def test_project_file_not_dir_ignored(self, tmp_path: Path) -> None:
|
| 363 |
+
"""A file directly inside projects/ (not a dir) must be skipped."""
|
| 364 |
+
projects = tmp_path / "projects"
|
| 365 |
+
projects.mkdir(parents=True)
|
| 366 |
+
(projects / "stray-file.txt").write_text("x", encoding="utf-8")
|
| 367 |
+
cfg = _default_cfg(memory_glob=True)
|
| 368 |
+
assert list(change_detector._iter_memory_files(cfg, tmp_path)) == []
|
| 369 |
+
|
| 370 |
+
def test_slug_without_memory_subdir_skipped(self, tmp_path: Path) -> None:
|
| 371 |
+
slug_dir = tmp_path / "projects" / "no-memory"
|
| 372 |
+
slug_dir.mkdir(parents=True)
|
| 373 |
+
cfg = _default_cfg(memory_glob=True)
|
| 374 |
+
assert list(change_detector._iter_memory_files(cfg, tmp_path)) == []
|
| 375 |
+
|
| 376 |
+
def test_nested_memory_path_dest_rel(self, tmp_path: Path) -> None:
|
| 377 |
+
nested = tmp_path / "projects" / "proj" / "memory" / "sub" / "deep.md"
|
| 378 |
+
nested.parent.mkdir(parents=True, exist_ok=True)
|
| 379 |
+
nested.write_bytes(b"content")
|
| 380 |
+
cfg = _default_cfg(memory_glob=True)
|
| 381 |
+
results = list(change_detector._iter_memory_files(cfg, tmp_path))
|
| 382 |
+
dest_rels = [d for d, _ in results]
|
| 383 |
+
assert "memory/proj/sub/deep.md" in dest_rels
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
# ── TestLoadSnapshotHashes ────────────────────────────────────────────────────
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
class TestLoadSnapshotHashes:
|
| 390 |
+
"""Tests for the internal _load_snapshot_hashes helper."""
|
| 391 |
+
|
| 392 |
+
def test_missing_manifest_returns_empty(self, tmp_path: Path) -> None:
|
| 393 |
+
snap = tmp_path / "snap"
|
| 394 |
+
snap.mkdir()
|
| 395 |
+
assert change_detector._load_snapshot_hashes(snap) == {}
|
| 396 |
+
|
| 397 |
+
def test_corrupt_json_returns_empty(self, tmp_path: Path) -> None:
|
| 398 |
+
snap = tmp_path / "snap"
|
| 399 |
+
snap.mkdir()
|
| 400 |
+
(snap / "manifest.json").write_text("{NOT JSON", encoding="utf-8")
|
| 401 |
+
assert change_detector._load_snapshot_hashes(snap) == {}
|
| 402 |
+
|
| 403 |
+
def test_valid_manifest_returns_mapping(self, tmp_path: Path) -> None:
|
| 404 |
+
snap = tmp_path / "snap"
|
| 405 |
+
snap.mkdir()
|
| 406 |
+
(snap / "manifest.json").write_text(
|
| 407 |
+
_manifest_json([{"dest": "settings.json", "sha256": "abc123"}]),
|
| 408 |
+
encoding="utf-8",
|
| 409 |
+
)
|
| 410 |
+
result = change_detector._load_snapshot_hashes(snap)
|
| 411 |
+
assert result == {"settings.json": "abc123"}
|
| 412 |
+
|
| 413 |
+
def test_entries_missing_dest_skipped(self, tmp_path: Path) -> None:
|
| 414 |
+
snap = tmp_path / "snap"
|
| 415 |
+
snap.mkdir()
|
| 416 |
+
(snap / "manifest.json").write_text(
|
| 417 |
+
_manifest_json([{"sha256": "abc"}, {"dest": "ok.md", "sha256": "def"}]),
|
| 418 |
+
encoding="utf-8",
|
| 419 |
+
)
|
| 420 |
+
result = change_detector._load_snapshot_hashes(snap)
|
| 421 |
+
assert "ok.md" in result
|
| 422 |
+
assert len(result) == 1
|
| 423 |
+
|
| 424 |
+
def test_entries_missing_sha256_skipped(self, tmp_path: Path) -> None:
|
| 425 |
+
snap = tmp_path / "snap"
|
| 426 |
+
snap.mkdir()
|
| 427 |
+
(snap / "manifest.json").write_text(
|
| 428 |
+
_manifest_json([{"dest": "x.md"}, {"dest": "y.md", "sha256": "hash"}]),
|
| 429 |
+
encoding="utf-8",
|
| 430 |
+
)
|
| 431 |
+
result = change_detector._load_snapshot_hashes(snap)
|
| 432 |
+
assert result == {"y.md": "hash"}
|
| 433 |
+
|
| 434 |
+
def test_entries_null_values_skipped(self, tmp_path: Path) -> None:
|
| 435 |
+
snap = tmp_path / "snap"
|
| 436 |
+
snap.mkdir()
|
| 437 |
+
(snap / "manifest.json").write_text(
|
| 438 |
+
_manifest_json([{"dest": None, "sha256": "x"}, {"dest": "z.md", "sha256": "y"}]),
|
| 439 |
+
encoding="utf-8",
|
| 440 |
+
)
|
| 441 |
+
result = change_detector._load_snapshot_hashes(snap)
|
| 442 |
+
assert result == {"z.md": "y"}
|
| 443 |
+
|
| 444 |
+
def test_empty_entries_returns_empty(self, tmp_path: Path) -> None:
|
| 445 |
+
snap = tmp_path / "snap"
|
| 446 |
+
snap.mkdir()
|
| 447 |
+
(snap / "manifest.json").write_text(
|
| 448 |
+
json.dumps({"snapshot_id": "s", "entries": []}),
|
| 449 |
+
encoding="utf-8",
|
| 450 |
+
)
|
| 451 |
+
assert change_detector._load_snapshot_hashes(snap) == {}
|
| 452 |
+
|
| 453 |
+
def test_manifest_without_entries_key_returns_empty(self, tmp_path: Path) -> None:
|
| 454 |
+
snap = tmp_path / "snap"
|
| 455 |
+
snap.mkdir()
|
| 456 |
+
(snap / "manifest.json").write_text(
|
| 457 |
+
json.dumps({"snapshot_id": "s"}),
|
| 458 |
+
encoding="utf-8",
|
| 459 |
+
)
|
| 460 |
+
assert change_detector._load_snapshot_hashes(snap) == {}
|
| 461 |
+
|
| 462 |
+
def test_multiple_entries_all_loaded(self, tmp_path: Path) -> None:
|
| 463 |
+
snap = tmp_path / "snap"
|
| 464 |
+
snap.mkdir()
|
| 465 |
+
entries = [
|
| 466 |
+
{"dest": "a.md", "sha256": "hash-a"},
|
| 467 |
+
{"dest": "b.md", "sha256": "hash-b"},
|
| 468 |
+
{"dest": "c.md", "sha256": "hash-c"},
|
| 469 |
+
]
|
| 470 |
+
(snap / "manifest.json").write_text(
|
| 471 |
+
_manifest_json(entries), encoding="utf-8"
|
| 472 |
+
)
|
| 473 |
+
result = change_detector._load_snapshot_hashes(snap)
|
| 474 |
+
assert len(result) == 3
|
| 475 |
+
assert result["b.md"] == "hash-b"
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
# ── TestSnapshotId ────────────────────────────────────────────────────────────
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
class TestSnapshotId:
|
| 482 |
+
"""Tests for the internal _snapshot_id helper."""
|
| 483 |
+
|
| 484 |
+
def test_reads_snapshot_id_from_manifest(self, tmp_path: Path) -> None:
|
| 485 |
+
snap = tmp_path / "20240101T120000Z"
|
| 486 |
+
snap.mkdir()
|
| 487 |
+
(snap / "manifest.json").write_text(
|
| 488 |
+
json.dumps({"snapshot_id": "custom-id-42", "entries": []}),
|
| 489 |
+
encoding="utf-8",
|
| 490 |
+
)
|
| 491 |
+
assert change_detector._snapshot_id(snap) == "custom-id-42"
|
| 492 |
+
|
| 493 |
+
def test_falls_back_to_dir_name_on_missing_manifest(self, tmp_path: Path) -> None:
|
| 494 |
+
snap = tmp_path / "fallback-name"
|
| 495 |
+
snap.mkdir()
|
| 496 |
+
assert change_detector._snapshot_id(snap) == "fallback-name"
|
| 497 |
+
|
| 498 |
+
def test_falls_back_to_dir_name_on_corrupt_json(self, tmp_path: Path) -> None:
|
| 499 |
+
snap = tmp_path / "fallback-corrupt"
|
| 500 |
+
snap.mkdir()
|
| 501 |
+
(snap / "manifest.json").write_text("{BAD JSON", encoding="utf-8")
|
| 502 |
+
assert change_detector._snapshot_id(snap) == "fallback-corrupt"
|
| 503 |
+
|
| 504 |
+
def test_falls_back_to_dir_name_when_snapshot_id_absent(self, tmp_path: Path) -> None:
|
| 505 |
+
snap = tmp_path / "dir-name-fallback"
|
| 506 |
+
snap.mkdir()
|
| 507 |
+
(snap / "manifest.json").write_text(
|
| 508 |
+
json.dumps({"entries": []}), encoding="utf-8"
|
| 509 |
+
)
|
| 510 |
+
assert change_detector._snapshot_id(snap) == "dir-name-fallback"
|
| 511 |
+
|
| 512 |
+
def test_snapshot_id_none_falls_back_to_dir_name(self, tmp_path: Path) -> None:
|
| 513 |
+
snap = tmp_path / "none-id-fallback"
|
| 514 |
+
snap.mkdir()
|
| 515 |
+
(snap / "manifest.json").write_text(
|
| 516 |
+
json.dumps({"snapshot_id": None, "entries": []}),
|
| 517 |
+
encoding="utf-8",
|
| 518 |
+
)
|
| 519 |
+
# None -> falsy -> falls back to snap.name
|
| 520 |
+
assert change_detector._snapshot_id(snap) == "none-id-fallback"
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
# ── TestDetectChanges ─────────────────────────────────────────────────────────
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
class TestDetectChanges:
|
| 527 |
+
"""Integration tests for the public detect_changes function."""
|
| 528 |
+
|
| 529 |
+
def _write_file(self, path: Path, content: bytes = b"content") -> None:
|
| 530 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 531 |
+
path.write_bytes(content)
|
| 532 |
+
|
| 533 |
+
def _write_manifest(
|
| 534 |
+
self,
|
| 535 |
+
snap: Path,
|
| 536 |
+
entries: list[dict[str, Any]],
|
| 537 |
+
snapshot_id: str = "baseline-snap",
|
| 538 |
+
) -> None:
|
| 539 |
+
snap.mkdir(parents=True, exist_ok=True)
|
| 540 |
+
(snap / "manifest.json").write_text(
|
| 541 |
+
_manifest_json(entries, snapshot_id), encoding="utf-8"
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
# -- No baseline --
|
| 545 |
+
|
| 546 |
+
def test_no_baseline_all_files_are_new(self, tmp_path: Path) -> None:
|
| 547 |
+
claude_home = tmp_path / "home"
|
| 548 |
+
claude_home.mkdir()
|
| 549 |
+
(claude_home / "settings.json").write_text("{}", encoding="utf-8")
|
| 550 |
+
cfg = _default_cfg(top_files=("settings.json",))
|
| 551 |
+
report = change_detector.detect_changes(cfg, claude_home, last_snapshot=None)
|
| 552 |
+
assert "settings.json" in report.new
|
| 553 |
+
assert report.changed == ()
|
| 554 |
+
assert report.removed == ()
|
| 555 |
+
assert report.unchanged == 0
|
| 556 |
+
assert report.baseline_snapshot is None
|
| 557 |
+
|
| 558 |
+
def test_none_snapshot_no_tracked_files(self, tmp_path: Path) -> None:
|
| 559 |
+
cfg = _default_cfg()
|
| 560 |
+
report = change_detector.detect_changes(cfg, tmp_path, last_snapshot=None)
|
| 561 |
+
assert report.new == ()
|
| 562 |
+
assert report.has_changes is False
|
| 563 |
+
assert report.baseline_snapshot is None
|
| 564 |
+
|
| 565 |
+
def test_nonexistent_snapshot_dir_treated_as_no_baseline(
|
| 566 |
+
self, tmp_path: Path
|
| 567 |
+
) -> None:
|
| 568 |
+
claude_home = tmp_path / "home"
|
| 569 |
+
claude_home.mkdir()
|
| 570 |
+
(claude_home / "CLAUDE.md").write_text("hi", encoding="utf-8")
|
| 571 |
+
cfg = _default_cfg(top_files=("CLAUDE.md",))
|
| 572 |
+
ghost_snap = tmp_path / "nonexistent-snap"
|
| 573 |
+
report = change_detector.detect_changes(cfg, claude_home, ghost_snap)
|
| 574 |
+
assert "CLAUDE.md" in report.new
|
| 575 |
+
assert report.baseline_snapshot is None
|
| 576 |
+
|
| 577 |
+
# -- All unchanged --
|
| 578 |
+
|
| 579 |
+
def test_all_files_unchanged(self, tmp_path: Path) -> None:
|
| 580 |
+
claude_home = tmp_path / "home"
|
| 581 |
+
claude_home.mkdir()
|
| 582 |
+
f = claude_home / "settings.json"
|
| 583 |
+
f.write_bytes(b"same")
|
| 584 |
+
digest = hashlib.sha256(b"same").hexdigest()
|
| 585 |
+
snap = tmp_path / "snap"
|
| 586 |
+
self._write_manifest(snap, [{"dest": "settings.json", "sha256": digest}])
|
| 587 |
+
cfg = _default_cfg(top_files=("settings.json",))
|
| 588 |
+
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 589 |
+
assert report.new == ()
|
| 590 |
+
assert report.changed == ()
|
| 591 |
+
assert report.removed == ()
|
| 592 |
+
assert report.unchanged == 1
|
| 593 |
+
assert report.has_changes is False
|
| 594 |
+
|
| 595 |
+
# -- New files --
|
| 596 |
+
|
| 597 |
+
def test_file_absent_from_baseline_is_new(self, tmp_path: Path) -> None:
|
| 598 |
+
claude_home = tmp_path / "home"
|
| 599 |
+
claude_home.mkdir()
|
| 600 |
+
(claude_home / "new.json").write_bytes(b"new content")
|
| 601 |
+
snap = tmp_path / "snap"
|
| 602 |
+
self._write_manifest(snap, []) # empty baseline
|
| 603 |
+
cfg = _default_cfg(top_files=("new.json",))
|
| 604 |
+
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 605 |
+
assert "new.json" in report.new
|
| 606 |
+
assert report.changed == ()
|
| 607 |
+
assert report.removed == ()
|
| 608 |
+
|
| 609 |
+
# -- Changed files --
|
| 610 |
+
|
| 611 |
+
def test_file_with_different_hash_is_changed(self, tmp_path: Path) -> None:
|
| 612 |
+
claude_home = tmp_path / "home"
|
| 613 |
+
claude_home.mkdir()
|
| 614 |
+
f = claude_home / "CLAUDE.md"
|
| 615 |
+
f.write_bytes(b"new-content")
|
| 616 |
+
snap = tmp_path / "snap"
|
| 617 |
+
self._write_manifest(snap, [{"dest": "CLAUDE.md", "sha256": "old-stale-hash"}])
|
| 618 |
+
cfg = _default_cfg(top_files=("CLAUDE.md",))
|
| 619 |
+
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 620 |
+
assert "CLAUDE.md" in report.changed
|
| 621 |
+
assert report.new == ()
|
| 622 |
+
assert report.removed == ()
|
| 623 |
+
|
| 624 |
+
# -- Removed files --
|
| 625 |
+
|
| 626 |
+
def test_file_in_baseline_not_on_disk_is_removed(self, tmp_path: Path) -> None:
|
| 627 |
+
claude_home = tmp_path / "home"
|
| 628 |
+
claude_home.mkdir()
|
| 629 |
+
snap = tmp_path / "snap"
|
| 630 |
+
self._write_manifest(snap, [{"dest": "gone.json", "sha256": "dead"}])
|
| 631 |
+
cfg = _default_cfg(top_files=("gone.json",))
|
| 632 |
+
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 633 |
+
assert "gone.json" in report.removed
|
| 634 |
+
assert report.new == ()
|
| 635 |
+
assert report.changed == ()
|
| 636 |
+
|
| 637 |
+
# -- Combined --
|
| 638 |
+
|
| 639 |
+
def test_mixed_new_changed_removed_unchanged(self, tmp_path: Path) -> None:
|
| 640 |
+
claude_home = tmp_path / "home"
|
| 641 |
+
claude_home.mkdir()
|
| 642 |
+
|
| 643 |
+
# new — present now, absent in baseline
|
| 644 |
+
(claude_home / "new.json").write_bytes(b"fresh")
|
| 645 |
+
# changed — present now, different hash in baseline
|
| 646 |
+
(claude_home / "changed.json").write_bytes(b"modified")
|
| 647 |
+
hashlib.sha256(b"modified").hexdigest()
|
| 648 |
+
# unchanged — present now, same hash
|
| 649 |
+
(claude_home / "same.json").write_bytes(b"identical")
|
| 650 |
+
same_digest = hashlib.sha256(b"identical").hexdigest()
|
| 651 |
+
# removed — in baseline, not on disk
|
| 652 |
+
|
| 653 |
+
snap = tmp_path / "snap"
|
| 654 |
+
self._write_manifest(snap, [
|
| 655 |
+
{"dest": "changed.json", "sha256": "stale-hash"},
|
| 656 |
+
{"dest": "same.json", "sha256": same_digest},
|
| 657 |
+
{"dest": "removed.json", "sha256": "any-hash"},
|
| 658 |
+
])
|
| 659 |
+
cfg = _default_cfg(top_files=("new.json", "changed.json", "same.json", "removed.json"))
|
| 660 |
+
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 661 |
+
|
| 662 |
+
assert "new.json" in report.new
|
| 663 |
+
assert "changed.json" in report.changed
|
| 664 |
+
assert "removed.json" in report.removed
|
| 665 |
+
assert report.unchanged == 1
|
| 666 |
+
assert report.has_changes is True
|
| 667 |
+
assert report.baseline_snapshot == "baseline-snap"
|
| 668 |
+
|
| 669 |
+
# -- Snapshot ID propagation --
|
| 670 |
+
|
| 671 |
+
def test_baseline_snapshot_id_propagated(self, tmp_path: Path) -> None:
|
| 672 |
+
claude_home = tmp_path / "home"
|
| 673 |
+
claude_home.mkdir()
|
| 674 |
+
snap = tmp_path / "snap"
|
| 675 |
+
self._write_manifest(snap, [], snapshot_id="my-snap-xyz")
|
| 676 |
+
cfg = _default_cfg()
|
| 677 |
+
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 678 |
+
assert report.baseline_snapshot == "my-snap-xyz"
|
| 679 |
+
|
| 680 |
+
# -- Trees integration --
|
| 681 |
+
|
| 682 |
+
def test_tree_files_compared_against_baseline(self, tmp_path: Path) -> None:
|
| 683 |
+
claude_home = tmp_path / "home"
|
| 684 |
+
skill_file = claude_home / "skills" / "py" / "SKILL.md"
|
| 685 |
+
skill_file.parent.mkdir(parents=True)
|
| 686 |
+
skill_file.write_bytes(b"skill content")
|
| 687 |
+
digest = hashlib.sha256(b"skill content").hexdigest()
|
| 688 |
+
|
| 689 |
+
snap = tmp_path / "snap"
|
| 690 |
+
self._write_manifest(snap, [{"dest": "skills/py/SKILL.md", "sha256": digest}])
|
| 691 |
+
cfg = BackupConfig(
|
| 692 |
+
top_files=(),
|
| 693 |
+
trees=(BackupTree(src="skills", dest="skills"),),
|
| 694 |
+
memory_glob=False,
|
| 695 |
+
)
|
| 696 |
+
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 697 |
+
assert report.unchanged == 1
|
| 698 |
+
assert report.has_changes is False
|
| 699 |
+
|
| 700 |
+
# -- Memory files integration --
|
| 701 |
+
|
| 702 |
+
def test_memory_files_detected_as_new(self, tmp_path: Path) -> None:
|
| 703 |
+
claude_home = tmp_path / "home"
|
| 704 |
+
mem_file = claude_home / "projects" / "proj-x" / "memory" / "MEMORY.md"
|
| 705 |
+
mem_file.parent.mkdir(parents=True)
|
| 706 |
+
mem_file.write_bytes(b"mem data")
|
| 707 |
+
|
| 708 |
+
snap = tmp_path / "snap"
|
| 709 |
+
self._write_manifest(snap, []) # empty baseline
|
| 710 |
+
cfg = _default_cfg(memory_glob=True)
|
| 711 |
+
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 712 |
+
assert any("memory/proj-x" in d for d in report.new)
|
| 713 |
+
|
| 714 |
+
# -- Sorted output --
|
| 715 |
+
|
| 716 |
+
def test_new_files_are_sorted(self, tmp_path: Path) -> None:
|
| 717 |
+
claude_home = tmp_path / "home"
|
| 718 |
+
claude_home.mkdir()
|
| 719 |
+
for name in ("z.json", "a.json", "m.json"):
|
| 720 |
+
(claude_home / name).write_bytes(b"x")
|
| 721 |
+
cfg = _default_cfg(top_files=("z.json", "a.json", "m.json"))
|
| 722 |
+
report = change_detector.detect_changes(cfg, claude_home, last_snapshot=None)
|
| 723 |
+
assert list(report.new) == sorted(report.new)
|
| 724 |
+
|
| 725 |
+
def test_changed_files_are_sorted(self, tmp_path: Path) -> None:
|
| 726 |
+
claude_home = tmp_path / "home"
|
| 727 |
+
claude_home.mkdir()
|
| 728 |
+
files = ["z.json", "a.json", "m.json"]
|
| 729 |
+
for name in files:
|
| 730 |
+
(claude_home / name).write_bytes(b"current")
|
| 731 |
+
snap = tmp_path / "snap"
|
| 732 |
+
self._write_manifest(snap, [{"dest": n, "sha256": "old"} for n in files])
|
| 733 |
+
cfg = _default_cfg(top_files=tuple(files))
|
| 734 |
+
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 735 |
+
assert list(report.changed) == sorted(report.changed)
|
| 736 |
+
|
| 737 |
+
# -- Symlink in tracked path --
|
| 738 |
+
|
| 739 |
+
def test_symlink_top_file_not_counted(self, tmp_path: Path) -> None:
|
| 740 |
+
claude_home = tmp_path / "home"
|
| 741 |
+
claude_home.mkdir()
|
| 742 |
+
target = claude_home / "real.json"
|
| 743 |
+
target.write_bytes(b"content")
|
| 744 |
+
link = claude_home / "settings.json"
|
| 745 |
+
try:
|
| 746 |
+
link.symlink_to(target)
|
| 747 |
+
except (OSError, NotImplementedError):
|
| 748 |
+
pytest.skip("symlinks not supported on this platform")
|
| 749 |
+
snap = tmp_path / "snap"
|
| 750 |
+
self._write_manifest(snap, [])
|
| 751 |
+
cfg = _default_cfg(top_files=("settings.json",))
|
| 752 |
+
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 753 |
+
# _iter_top_files skips the symlink → nothing in current state
|
| 754 |
+
assert report.new == ()
|
| 755 |
+
|
| 756 |
+
# -- Large file skipped by max_file_bytes --
|
| 757 |
+
|
| 758 |
+
def test_oversized_tree_file_never_counted_as_new(self, tmp_path: Path) -> None:
|
| 759 |
+
claude_home = tmp_path / "home"
|
| 760 |
+
big = claude_home / "agents" / "huge.md"
|
| 761 |
+
big.parent.mkdir(parents=True)
|
| 762 |
+
big.write_bytes(b"x" * 1000)
|
| 763 |
+
snap = tmp_path / "snap"
|
| 764 |
+
self._write_manifest(snap, [])
|
| 765 |
+
cfg = BackupConfig(
|
| 766 |
+
top_files=(),
|
| 767 |
+
trees=(BackupTree(src="agents", dest="agents"),),
|
| 768 |
+
memory_glob=False,
|
| 769 |
+
max_file_bytes=500,
|
| 770 |
+
)
|
| 771 |
+
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 772 |
+
assert report.new == ()
|
| 773 |
+
|
| 774 |
+
# -- Parametrized: baseline_snapshot vs no baseline --
|
| 775 |
+
|
| 776 |
+
@pytest.mark.parametrize(
|
| 777 |
+
"last_snapshot_is_none,expected_baseline",
|
| 778 |
+
[
|
| 779 |
+
(True, None),
|
| 780 |
+
(False, "snap-id"),
|
| 781 |
+
],
|
| 782 |
+
)
|
| 783 |
+
def test_baseline_snapshot_field(
|
| 784 |
+
self,
|
| 785 |
+
tmp_path: Path,
|
| 786 |
+
last_snapshot_is_none: bool,
|
| 787 |
+
expected_baseline: str | None,
|
| 788 |
+
) -> None:
|
| 789 |
+
claude_home = tmp_path / "home"
|
| 790 |
+
claude_home.mkdir()
|
| 791 |
+
if last_snapshot_is_none:
|
| 792 |
+
snap = None
|
| 793 |
+
else:
|
| 794 |
+
snap = tmp_path / "snap"
|
| 795 |
+
self._write_manifest(snap, [], snapshot_id="snap-id")
|
| 796 |
+
cfg = _default_cfg()
|
| 797 |
+
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 798 |
+
assert report.baseline_snapshot == expected_baseline
|
| 799 |
+
|
| 800 |
+
# -- Parametrized: has_changes conditions --
|
| 801 |
+
|
| 802 |
+
@pytest.mark.parametrize(
|
| 803 |
+
"new,changed,removed,unchanged,expect_changes",
|
| 804 |
+
[
|
| 805 |
+
((), (), (), 0, False),
|
| 806 |
+
(("a",), (), (), 0, True),
|
| 807 |
+
((), ("b",), (), 0, True),
|
| 808 |
+
((), (), ("c",), 0, True),
|
| 809 |
+
((), (), (), 5, False),
|
| 810 |
+
(("a",), ("b",), ("c",), 2, True),
|
| 811 |
+
],
|
| 812 |
+
)
|
| 813 |
+
def test_has_changes_parametrized(
|
| 814 |
+
self,
|
| 815 |
+
new: tuple[str, ...],
|
| 816 |
+
changed: tuple[str, ...],
|
| 817 |
+
removed: tuple[str, ...],
|
| 818 |
+
unchanged: int,
|
| 819 |
+
expect_changes: bool,
|
| 820 |
+
) -> None:
|
| 821 |
+
r = change_detector.ChangeReport(
|
| 822 |
+
new=new,
|
| 823 |
+
changed=changed,
|
| 824 |
+
removed=removed,
|
| 825 |
+
unchanged=unchanged,
|
| 826 |
+
baseline_snapshot=None,
|
| 827 |
+
)
|
| 828 |
+
assert r.has_changes is expect_changes
|
| 829 |
+
|
| 830 |
+
# -- Corrupt manifest in snapshot dir --
|
| 831 |
+
|
| 832 |
+
def test_corrupt_manifest_treats_all_current_as_new(self, tmp_path: Path) -> None:
|
| 833 |
+
claude_home = tmp_path / "home"
|
| 834 |
+
claude_home.mkdir()
|
| 835 |
+
(claude_home / "settings.json").write_bytes(b"data")
|
| 836 |
+
snap = tmp_path / "snap"
|
| 837 |
+
snap.mkdir()
|
| 838 |
+
(snap / "manifest.json").write_text("{INVALID", encoding="utf-8")
|
| 839 |
+
cfg = _default_cfg(top_files=("settings.json",))
|
| 840 |
+
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 841 |
+
# Corrupt manifest → empty baseline → settings.json treated as new
|
| 842 |
+
assert "settings.json" in report.new
|
| 843 |
+
assert report.removed == ()
|
| 844 |
+
|
| 845 |
+
# -- total_current property via detect_changes --
|
| 846 |
+
|
| 847 |
+
def test_total_current_counts_new_changed_unchanged_not_removed(
|
| 848 |
+
self, tmp_path: Path
|
| 849 |
+
) -> None:
|
| 850 |
+
claude_home = tmp_path / "home"
|
| 851 |
+
claude_home.mkdir()
|
| 852 |
+
# 2 new files
|
| 853 |
+
(claude_home / "a.json").write_bytes(b"a")
|
| 854 |
+
(claude_home / "b.json").write_bytes(b"b")
|
| 855 |
+
# 1 unchanged
|
| 856 |
+
(claude_home / "c.json").write_bytes(b"same")
|
| 857 |
+
same_d = hashlib.sha256(b"same").hexdigest()
|
| 858 |
+
# 1 changed
|
| 859 |
+
(claude_home / "d.json").write_bytes(b"new")
|
| 860 |
+
snap = tmp_path / "snap"
|
| 861 |
+
self._write_manifest(snap, [
|
| 862 |
+
{"dest": "c.json", "sha256": same_d},
|
| 863 |
+
{"dest": "d.json", "sha256": "old-hash"},
|
| 864 |
+
{"dest": "removed.json", "sha256": "r-hash"},
|
| 865 |
+
])
|
| 866 |
+
cfg = _default_cfg(top_files=("a.json", "b.json", "c.json", "d.json"))
|
| 867 |
+
report = change_detector.detect_changes(cfg, claude_home, snap)
|
| 868 |
+
# new=2, changed=1, unchanged=1 → total_current=4
|
| 869 |
+
assert report.total_current == 4
|
src/tests/test_config.py
CHANGED
|
@@ -1,373 +1,373 @@
|
|
| 1 |
-
"""
|
| 2 |
-
test_config.py -- Tests for the ctx_config.Config system.
|
| 3 |
-
|
| 4 |
-
Covers:
|
| 5 |
-
- ctx_config.Config: attribute types, path expansion, reload, deep merge,
|
| 6 |
-
all_skill_dirs()
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
import sys
|
| 10 |
-
import tempfile
|
| 11 |
-
from pathlib import Path
|
| 12 |
-
from typing import Any
|
| 13 |
-
|
| 14 |
-
import pytest
|
| 15 |
-
|
| 16 |
-
# ---------------------------------------------------------------------------
|
| 17 |
-
# sys.path is already patched by conftest.py, but guard here too so the module
|
| 18 |
-
# can be run in isolation (e.g. `python -m pytest tests/test_config.py`).
|
| 19 |
-
# ---------------------------------------------------------------------------
|
| 20 |
-
_PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
| 21 |
-
if str(_PROJECT_ROOT) not in sys.path:
|
| 22 |
-
sys.path.insert(0, str(_PROJECT_ROOT))
|
| 23 |
-
|
| 24 |
-
import ctx_config # noqa: E402
|
| 25 |
-
from ctx_config import Config, _deep_merge # noqa: E402
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
# ===========================================================================
|
| 29 |
-
# Helper
|
| 30 |
-
# ===========================================================================
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
def _minimal_raw(overrides: dict[str, Any] | None = None) -> dict[str, Any]:
|
| 34 |
-
"""Return a minimal raw-config dict sufficient to construct a Config."""
|
| 35 |
-
raw: dict[str, Any] = {
|
| 36 |
-
"paths": {
|
| 37 |
-
"claude_dir": "~/.claude",
|
| 38 |
-
"wiki_dir": "~/.claude/skill-wiki",
|
| 39 |
-
"skills_dir": "~/.claude/skills",
|
| 40 |
-
"agents_dir": "~/.claude/agents",
|
| 41 |
-
"skill_manifest": "~/.claude/skill-manifest.json",
|
| 42 |
-
"intent_log": "~/.claude/intent-log.jsonl",
|
| 43 |
-
"pending_skills": "~/.claude/pending-skills.json",
|
| 44 |
-
"skill_registry": "~/.claude/skill-registry.json",
|
| 45 |
-
"stack_profile_tmp": "~/.claude/skill-stack-profile.json",
|
| 46 |
-
"catalog": "~/.claude/skill-wiki/catalog.md",
|
| 47 |
-
},
|
| 48 |
-
"resolver": {},
|
| 49 |
-
"context_monitor": {},
|
| 50 |
-
"usage_tracker": {},
|
| 51 |
-
"skill_transformer": {},
|
| 52 |
-
"skill_router": {},
|
| 53 |
-
"extra_skill_dirs": [],
|
| 54 |
-
"babysitter": {},
|
| 55 |
-
}
|
| 56 |
-
if overrides:
|
| 57 |
-
_deep_merge(raw, overrides)
|
| 58 |
-
return raw
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
# ===========================================================================
|
| 62 |
-
# Config tests
|
| 63 |
-
# ===========================================================================
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
class TestConfigLoadsDefaults:
|
| 67 |
-
"""test_config_loads_defaults -- expected attributes exist with correct defaults."""
|
| 68 |
-
|
| 69 |
-
def test_has_wiki_dir(self) -> None:
|
| 70 |
-
cfg = Config(_minimal_raw())
|
| 71 |
-
assert hasattr(cfg, "wiki_dir")
|
| 72 |
-
|
| 73 |
-
def test_has_skills_dir(self) -> None:
|
| 74 |
-
cfg = Config(_minimal_raw())
|
| 75 |
-
assert hasattr(cfg, "skills_dir")
|
| 76 |
-
|
| 77 |
-
def test_line_threshold_default(self) -> None:
|
| 78 |
-
cfg = Config(_minimal_raw())
|
| 79 |
-
assert cfg.line_threshold == 180
|
| 80 |
-
|
| 81 |
-
def test_line_threshold_accepts_user_value(self) -> None:
|
| 82 |
-
cfg = Config(_minimal_raw({"skill_transformer": {"line_threshold": 240}}))
|
| 83 |
-
assert cfg.line_threshold == 240
|
| 84 |
-
|
| 85 |
-
@pytest.mark.parametrize("value", [0, -1, "not-an-int", "240", True, False, 1.5])
|
| 86 |
-
def test_line_threshold_rejects_invalid_values(self, value: object) -> None:
|
| 87 |
-
with pytest.raises(ValueError, match="skill_transformer.line_threshold"):
|
| 88 |
-
Config(_minimal_raw({"skill_transformer": {"line_threshold": value}}))
|
| 89 |
-
|
| 90 |
-
def test_max_stage_lines_default(self) -> None:
|
| 91 |
-
cfg = Config(_minimal_raw())
|
| 92 |
-
assert cfg.max_stage_lines == 40
|
| 93 |
-
|
| 94 |
-
def test_max_skills_default(self) -> None:
|
| 95 |
-
cfg = Config(_minimal_raw())
|
| 96 |
-
assert cfg.max_skills == 15
|
| 97 |
-
|
| 98 |
-
def test_stage_count_default(self) -> None:
|
| 99 |
-
cfg = Config(_minimal_raw())
|
| 100 |
-
assert cfg.stage_count == 5
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
class TestConfigPathsArePathlib:
|
| 104 |
-
"""test_config_paths_are_pathlib -- all path attributes are Path objects."""
|
| 105 |
-
|
| 106 |
-
PATH_ATTRS = [
|
| 107 |
-
"claude_dir",
|
| 108 |
-
"wiki_dir",
|
| 109 |
-
"skills_dir",
|
| 110 |
-
"agents_dir",
|
| 111 |
-
"skill_manifest",
|
| 112 |
-
"intent_log",
|
| 113 |
-
"pending_skills",
|
| 114 |
-
"skill_registry",
|
| 115 |
-
"stack_profile_tmp",
|
| 116 |
-
"catalog",
|
| 117 |
-
]
|
| 118 |
-
|
| 119 |
-
@pytest.mark.parametrize("attr", PATH_ATTRS)
|
| 120 |
-
def test_attr_is_path(
|
| 121 |
-
self,
|
| 122 |
-
attr: str,
|
| 123 |
-
tmp_path: Path,
|
| 124 |
-
monkeypatch: pytest.MonkeyPatch,
|
| 125 |
-
) -> None:
|
| 126 |
-
cfg = Config(_minimal_raw())
|
| 127 |
-
assert isinstance(getattr(cfg, attr), Path), (
|
| 128 |
-
f"cfg.{attr} should be a Path, got {type(getattr(cfg, attr))}"
|
| 129 |
-
)
|
| 130 |
-
|
| 131 |
-
if attr == "stack_profile_tmp":
|
| 132 |
-
raw = _minimal_raw()
|
| 133 |
-
del raw["paths"]["stack_profile_tmp"]
|
| 134 |
-
monkeypatch.setattr(tempfile, "gettempdir", lambda: str(tmp_path))
|
| 135 |
-
|
| 136 |
-
cfg = Config(raw)
|
| 137 |
-
|
| 138 |
-
assert cfg.stack_profile_tmp == tmp_path / "skill-stack-profile.json"
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
class TestConfigExpandTilde:
|
| 142 |
-
"""test_config_expand_tilde -- paths with ~ are expanded to absolute paths."""
|
| 143 |
-
|
| 144 |
-
def test_wiki_dir_is_absolute(self) -> None:
|
| 145 |
-
cfg = Config(_minimal_raw())
|
| 146 |
-
assert cfg.wiki_dir.is_absolute(), (
|
| 147 |
-
f"wiki_dir should be absolute after ~ expansion, got: {cfg.wiki_dir}"
|
| 148 |
-
)
|
| 149 |
-
|
| 150 |
-
def test_skills_dir_is_absolute(self) -> None:
|
| 151 |
-
cfg = Config(_minimal_raw())
|
| 152 |
-
assert cfg.skills_dir.is_absolute()
|
| 153 |
-
|
| 154 |
-
def test_claude_dir_is_absolute(self) -> None:
|
| 155 |
-
cfg = Config(_minimal_raw())
|
| 156 |
-
assert cfg.claude_dir.is_absolute()
|
| 157 |
-
|
| 158 |
-
def test_custom_tilde_path_expanded(self) -> None:
|
| 159 |
-
raw = _minimal_raw({"paths": {"wiki_dir": "~/custom-wiki"}})
|
| 160 |
-
cfg = Config(raw)
|
| 161 |
-
assert "~" not in str(cfg.wiki_dir)
|
| 162 |
-
assert cfg.wiki_dir.is_absolute()
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
def test_claude_adapter_modules_use_cfg_paths() -> None:
|
| 166 |
-
from ctx.adapters.claude_code import skill_health, skill_loader
|
| 167 |
-
from ctx.adapters.claude_code.install import install_utils, skill_unload
|
| 168 |
-
|
| 169 |
-
assert install_utils.MANIFEST_PATH == ctx_config.cfg.skill_manifest
|
| 170 |
-
assert skill_loader.SKILLS_DIR == ctx_config.cfg.skills_dir
|
| 171 |
-
assert skill_loader.AGENTS_DIR == ctx_config.cfg.agents_dir
|
| 172 |
-
assert skill_loader.WIKI_DIR == ctx_config.cfg.wiki_dir
|
| 173 |
-
assert skill_loader.PENDING_SKILLS == ctx_config.cfg.pending_skills
|
| 174 |
-
assert skill_loader.MANIFEST_PATH == ctx_config.cfg.skill_manifest
|
| 175 |
-
assert skill_unload.CLAUDE_DIR == ctx_config.cfg.claude_dir
|
| 176 |
-
assert skill_unload.WIKI_DIR == ctx_config.cfg.wiki_dir
|
| 177 |
-
assert skill_unload.MANIFEST_PATH == ctx_config.cfg.skill_manifest
|
| 178 |
-
assert skill_health.SKILLS_DIR == ctx_config.cfg.skills_dir
|
| 179 |
-
assert skill_health.AGENTS_DIR == ctx_config.cfg.agents_dir
|
| 180 |
-
assert skill_health.PENDING_PATH == ctx_config.cfg.pending_skills
|
| 181 |
-
assert skill_health.MANIFEST_PATH == ctx_config.cfg.skill_manifest
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
class TestConfigReload:
|
| 185 |
-
"""test_config_reload -- reload() picks up changes to the raw config."""
|
| 186 |
-
|
| 187 |
-
def test_reload_updates_singleton(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
| 188 |
-
# Write a temporary default config with a custom line_threshold
|
| 189 |
-
custom_config = tmp_path / "config.json"
|
| 190 |
-
import json
|
| 191 |
-
|
| 192 |
-
custom_config.write_text(
|
| 193 |
-
json.dumps({"skill_transformer": {"line_threshold": 999}}),
|
| 194 |
-
encoding="utf-8",
|
| 195 |
-
)
|
| 196 |
-
|
| 197 |
-
# Patch the module-level constants so _load_raw reads our file
|
| 198 |
-
monkeypatch.setattr(ctx_config, "_DEFAULT_CONFIG", custom_config)
|
| 199 |
-
# Also suppress user config so it doesn't bleed in
|
| 200 |
-
monkeypatch.setattr(ctx_config, "_USER_CONFIG", tmp_path / "nonexistent.json")
|
| 201 |
-
|
| 202 |
-
ctx_config.reload()
|
| 203 |
-
assert ctx_config.cfg.line_threshold == 999
|
| 204 |
-
|
| 205 |
-
def test_reload_restores_after_monkeypatch(
|
| 206 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 207 |
-
) -> None:
|
| 208 |
-
"""After reload with empty config the attribute still exists (defaults apply)."""
|
| 209 |
-
empty_config = tmp_path / "empty.json"
|
| 210 |
-
empty_config.write_text("{}", encoding="utf-8")
|
| 211 |
-
|
| 212 |
-
monkeypatch.setattr(ctx_config, "_DEFAULT_CONFIG", empty_config)
|
| 213 |
-
monkeypatch.setattr(ctx_config, "_USER_CONFIG", tmp_path / "nonexistent.json")
|
| 214 |
-
|
| 215 |
-
ctx_config.reload()
|
| 216 |
-
# line_threshold should fall back to the packaged default 180
|
| 217 |
-
assert ctx_config.cfg.line_threshold == 180
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
class TestConfigAllSkillDirs:
|
| 221 |
-
"""test_config_all_skill_dirs -- all_skill_dirs() returns a list of existing dirs."""
|
| 222 |
-
|
| 223 |
-
def test_returns_list(self) -> None:
|
| 224 |
-
cfg = Config(_minimal_raw())
|
| 225 |
-
result = cfg.all_skill_dirs()
|
| 226 |
-
assert isinstance(result, list)
|
| 227 |
-
|
| 228 |
-
def test_contains_only_existing_dirs(self) -> None:
|
| 229 |
-
cfg = Config(_minimal_raw())
|
| 230 |
-
for d in cfg.all_skill_dirs():
|
| 231 |
-
assert d.exists() and d.is_dir(), f"{d} does not exist or is not a directory"
|
| 232 |
-
|
| 233 |
-
def test_extra_dirs_included_when_they_exist(self, tmp_path: Path) -> None:
|
| 234 |
-
extra = tmp_path / "extra-skills"
|
| 235 |
-
extra.mkdir()
|
| 236 |
-
raw = _minimal_raw({"extra_skill_dirs": [str(extra)]})
|
| 237 |
-
cfg = Config(raw)
|
| 238 |
-
assert extra in cfg.all_skill_dirs()
|
| 239 |
-
|
| 240 |
-
def test_nonexistent_extra_dirs_excluded(self, tmp_path: Path) -> None:
|
| 241 |
-
ghost = tmp_path / "ghost-skills"
|
| 242 |
-
# intentionally do NOT create it
|
| 243 |
-
raw = _minimal_raw({"extra_skill_dirs": [str(ghost)]})
|
| 244 |
-
cfg = Config(raw)
|
| 245 |
-
assert ghost not in cfg.all_skill_dirs()
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
class TestConfigDeepMerge:
|
| 249 |
-
"""test_config_deep_merge -- nested dicts merge correctly and override wins."""
|
| 250 |
-
|
| 251 |
-
def test_override_scalar_wins(self) -> None:
|
| 252 |
-
base: dict[str, Any] = {"a": 1, "b": 2}
|
| 253 |
-
override: dict[str, Any] = {"b": 99}
|
| 254 |
-
_deep_merge(base, override)
|
| 255 |
-
assert base["b"] == 99
|
| 256 |
-
assert base["a"] == 1 # untouched
|
| 257 |
-
|
| 258 |
-
def test_nested_dict_merged_not_replaced(self) -> None:
|
| 259 |
-
base: dict[str, Any] = {"paths": {"wiki_dir": "~/wiki", "skills_dir": "~/skills"}}
|
| 260 |
-
override: dict[str, Any] = {"paths": {"wiki_dir": "~/custom-wiki"}}
|
| 261 |
-
_deep_merge(base, override)
|
| 262 |
-
# wiki_dir is overridden
|
| 263 |
-
assert base["paths"]["wiki_dir"] == "~/custom-wiki"
|
| 264 |
-
# skills_dir is preserved from base
|
| 265 |
-
assert base["paths"]["skills_dir"] == "~/skills"
|
| 266 |
-
|
| 267 |
-
def test_new_key_added(self) -> None:
|
| 268 |
-
base: dict[str, Any] = {"x": 1}
|
| 269 |
-
override: dict[str, Any] = {"y": 2}
|
| 270 |
-
_deep_merge(base, override)
|
| 271 |
-
assert base["y"] == 2
|
| 272 |
-
|
| 273 |
-
def test_deeply_nested_override(self) -> None:
|
| 274 |
-
base: dict[str, Any] = {"a": {"b": {"c": 10, "d": 20}}}
|
| 275 |
-
override: dict[str, Any] = {"a": {"b": {"c": 99}}}
|
| 276 |
-
_deep_merge(base, override)
|
| 277 |
-
assert base["a"]["b"]["c"] == 99
|
| 278 |
-
assert base["a"]["b"]["d"] == 20
|
| 279 |
-
|
| 280 |
-
def test_override_replaces_non_dict_with_scalar(self) -> None:
|
| 281 |
-
base: dict[str, Any] = {"a": {"nested": True}}
|
| 282 |
-
override: dict[str, Any] = {"a": "flat"}
|
| 283 |
-
_deep_merge(base, override)
|
| 284 |
-
assert base["a"] == "flat"
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
class TestConfigIntake:
|
| 288 |
-
"""test_config_intake -- intake gate section is exposed with defaults."""
|
| 289 |
-
|
| 290 |
-
def test_intake_defaults(self) -> None:
|
| 291 |
-
cfg = Config(_minimal_raw())
|
| 292 |
-
assert cfg.intake_enabled is True
|
| 293 |
-
assert cfg.intake_dup_threshold == pytest.approx(0.93)
|
| 294 |
-
assert cfg.intake_near_dup_threshold == pytest.approx(0.80)
|
| 295 |
-
assert cfg.intake_min_neighbors == 0
|
| 296 |
-
assert cfg.intake_min_neighbor_score == pytest.approx(0.30)
|
| 297 |
-
assert cfg.intake_min_body_chars == 120
|
| 298 |
-
assert cfg.intake_backend == "sentence-transformers"
|
| 299 |
-
assert cfg.intake_model is None
|
| 300 |
-
assert cfg.intake_base_url is None
|
| 301 |
-
assert cfg.intake_allow_remote is False
|
| 302 |
-
assert isinstance(cfg.intake_cache_root, Path)
|
| 303 |
-
assert cfg.intake_cache_root.is_absolute()
|
| 304 |
-
|
| 305 |
-
def test_intake_overrides_applied(self) -> None:
|
| 306 |
-
raw = _minimal_raw({
|
| 307 |
-
"intake": {
|
| 308 |
-
"enabled": False,
|
| 309 |
-
"dup_threshold": 0.95,
|
| 310 |
-
"near_dup_threshold": 0.80,
|
| 311 |
-
"min_neighbors": 2,
|
| 312 |
-
"min_neighbor_score": 0.50,
|
| 313 |
-
"min_body_chars": 200,
|
| 314 |
-
"embedding": {
|
| 315 |
-
"backend": "ollama",
|
| 316 |
-
"model": "nomic-embed-text",
|
| 317 |
-
"allow_remote": True,
|
| 318 |
-
},
|
| 319 |
-
},
|
| 320 |
-
})
|
| 321 |
-
cfg = Config(raw)
|
| 322 |
-
assert cfg.intake_enabled is False
|
| 323 |
-
assert cfg.intake_dup_threshold == pytest.approx(0.95)
|
| 324 |
-
assert cfg.intake_near_dup_threshold == pytest.approx(0.80)
|
| 325 |
-
assert cfg.intake_min_neighbors == 2
|
| 326 |
-
assert cfg.intake_min_neighbor_score == pytest.approx(0.50)
|
| 327 |
-
assert cfg.intake_min_body_chars == 200
|
| 328 |
-
assert cfg.intake_backend == "ollama"
|
| 329 |
-
assert cfg.intake_model == "nomic-embed-text"
|
| 330 |
-
assert cfg.intake_allow_remote is True
|
| 331 |
-
|
| 332 |
-
def test_build_intake_config_returns_dataclass(self) -> None:
|
| 333 |
-
from intake_gate import IntakeConfig
|
| 334 |
-
|
| 335 |
-
cfg = Config(_minimal_raw())
|
| 336 |
-
ic = cfg.build_intake_config()
|
| 337 |
-
assert isinstance(ic, IntakeConfig)
|
| 338 |
-
assert ic.dup_threshold == pytest.approx(0.93)
|
| 339 |
-
assert ic.near_dup_threshold == pytest.approx(0.80)
|
| 340 |
-
assert ic.min_body_chars == 120
|
| 341 |
-
|
| 342 |
-
def test_build_intake_config_honours_overrides(self) -> None:
|
| 343 |
-
raw = _minimal_raw({
|
| 344 |
-
"intake": {"dup_threshold": 0.91, "near_dup_threshold": 0.75},
|
| 345 |
-
})
|
| 346 |
-
cfg = Config(raw)
|
| 347 |
-
ic = cfg.build_intake_config()
|
| 348 |
-
assert ic.dup_threshold == pytest.approx(0.91)
|
| 349 |
-
assert ic.near_dup_threshold == pytest.approx(0.75)
|
| 350 |
-
|
| 351 |
-
def test_build_intake_embedder_returns_sentence_transformer(self) -> None:
|
| 352 |
-
from embedding_backend import SentenceTransformerEmbedder
|
| 353 |
-
|
| 354 |
-
cfg = Config(_minimal_raw())
|
| 355 |
-
emb = cfg.build_intake_embedder()
|
| 356 |
-
assert isinstance(emb, SentenceTransformerEmbedder)
|
| 357 |
-
|
| 358 |
-
def test_build_intake_embedder_ollama_selection(self) -> None:
|
| 359 |
-
from embedding_backend import OllamaEmbedder
|
| 360 |
-
|
| 361 |
-
raw = _minimal_raw({
|
| 362 |
-
"intake": {"embedding": {"backend": "ollama"}},
|
| 363 |
-
})
|
| 364 |
-
cfg = Config(raw)
|
| 365 |
-
emb = cfg.build_intake_embedder()
|
| 366 |
-
assert isinstance(emb, OllamaEmbedder)
|
| 367 |
-
|
| 368 |
-
def test_non_string_model_falls_back_to_none(self) -> None:
|
| 369 |
-
raw = _minimal_raw({
|
| 370 |
-
"intake": {"embedding": {"model": 42}}, # wrong type
|
| 371 |
-
})
|
| 372 |
-
cfg = Config(raw)
|
| 373 |
-
assert cfg.intake_model is None
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_config.py -- Tests for the ctx_config.Config system.
|
| 3 |
+
|
| 4 |
+
Covers:
|
| 5 |
+
- ctx_config.Config: attribute types, path expansion, reload, deep merge,
|
| 6 |
+
all_skill_dirs()
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import sys
|
| 10 |
+
import tempfile
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any
|
| 13 |
+
|
| 14 |
+
import pytest
|
| 15 |
+
|
| 16 |
+
# ---------------------------------------------------------------------------
|
| 17 |
+
# sys.path is already patched by conftest.py, but guard here too so the module
|
| 18 |
+
# can be run in isolation (e.g. `python -m pytest tests/test_config.py`).
|
| 19 |
+
# ---------------------------------------------------------------------------
|
| 20 |
+
_PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
| 21 |
+
if str(_PROJECT_ROOT) not in sys.path:
|
| 22 |
+
sys.path.insert(0, str(_PROJECT_ROOT))
|
| 23 |
+
|
| 24 |
+
import ctx_config # noqa: E402
|
| 25 |
+
from ctx_config import Config, _deep_merge # noqa: E402
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# ===========================================================================
|
| 29 |
+
# Helper
|
| 30 |
+
# ===========================================================================
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _minimal_raw(overrides: dict[str, Any] | None = None) -> dict[str, Any]:
|
| 34 |
+
"""Return a minimal raw-config dict sufficient to construct a Config."""
|
| 35 |
+
raw: dict[str, Any] = {
|
| 36 |
+
"paths": {
|
| 37 |
+
"claude_dir": "~/.claude",
|
| 38 |
+
"wiki_dir": "~/.claude/skill-wiki",
|
| 39 |
+
"skills_dir": "~/.claude/skills",
|
| 40 |
+
"agents_dir": "~/.claude/agents",
|
| 41 |
+
"skill_manifest": "~/.claude/skill-manifest.json",
|
| 42 |
+
"intent_log": "~/.claude/intent-log.jsonl",
|
| 43 |
+
"pending_skills": "~/.claude/pending-skills.json",
|
| 44 |
+
"skill_registry": "~/.claude/skill-registry.json",
|
| 45 |
+
"stack_profile_tmp": "~/.claude/skill-stack-profile.json",
|
| 46 |
+
"catalog": "~/.claude/skill-wiki/catalog.md",
|
| 47 |
+
},
|
| 48 |
+
"resolver": {},
|
| 49 |
+
"context_monitor": {},
|
| 50 |
+
"usage_tracker": {},
|
| 51 |
+
"skill_transformer": {},
|
| 52 |
+
"skill_router": {},
|
| 53 |
+
"extra_skill_dirs": [],
|
| 54 |
+
"babysitter": {},
|
| 55 |
+
}
|
| 56 |
+
if overrides:
|
| 57 |
+
_deep_merge(raw, overrides)
|
| 58 |
+
return raw
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# ===========================================================================
|
| 62 |
+
# Config tests
|
| 63 |
+
# ===========================================================================
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class TestConfigLoadsDefaults:
|
| 67 |
+
"""test_config_loads_defaults -- expected attributes exist with correct defaults."""
|
| 68 |
+
|
| 69 |
+
def test_has_wiki_dir(self) -> None:
|
| 70 |
+
cfg = Config(_minimal_raw())
|
| 71 |
+
assert hasattr(cfg, "wiki_dir")
|
| 72 |
+
|
| 73 |
+
def test_has_skills_dir(self) -> None:
|
| 74 |
+
cfg = Config(_minimal_raw())
|
| 75 |
+
assert hasattr(cfg, "skills_dir")
|
| 76 |
+
|
| 77 |
+
def test_line_threshold_default(self) -> None:
|
| 78 |
+
cfg = Config(_minimal_raw())
|
| 79 |
+
assert cfg.line_threshold == 180
|
| 80 |
+
|
| 81 |
+
def test_line_threshold_accepts_user_value(self) -> None:
|
| 82 |
+
cfg = Config(_minimal_raw({"skill_transformer": {"line_threshold": 240}}))
|
| 83 |
+
assert cfg.line_threshold == 240
|
| 84 |
+
|
| 85 |
+
@pytest.mark.parametrize("value", [0, -1, "not-an-int", "240", True, False, 1.5])
|
| 86 |
+
def test_line_threshold_rejects_invalid_values(self, value: object) -> None:
|
| 87 |
+
with pytest.raises(ValueError, match="skill_transformer.line_threshold"):
|
| 88 |
+
Config(_minimal_raw({"skill_transformer": {"line_threshold": value}}))
|
| 89 |
+
|
| 90 |
+
def test_max_stage_lines_default(self) -> None:
|
| 91 |
+
cfg = Config(_minimal_raw())
|
| 92 |
+
assert cfg.max_stage_lines == 40
|
| 93 |
+
|
| 94 |
+
def test_max_skills_default(self) -> None:
|
| 95 |
+
cfg = Config(_minimal_raw())
|
| 96 |
+
assert cfg.max_skills == 15
|
| 97 |
+
|
| 98 |
+
def test_stage_count_default(self) -> None:
|
| 99 |
+
cfg = Config(_minimal_raw())
|
| 100 |
+
assert cfg.stage_count == 5
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class TestConfigPathsArePathlib:
|
| 104 |
+
"""test_config_paths_are_pathlib -- all path attributes are Path objects."""
|
| 105 |
+
|
| 106 |
+
PATH_ATTRS = [
|
| 107 |
+
"claude_dir",
|
| 108 |
+
"wiki_dir",
|
| 109 |
+
"skills_dir",
|
| 110 |
+
"agents_dir",
|
| 111 |
+
"skill_manifest",
|
| 112 |
+
"intent_log",
|
| 113 |
+
"pending_skills",
|
| 114 |
+
"skill_registry",
|
| 115 |
+
"stack_profile_tmp",
|
| 116 |
+
"catalog",
|
| 117 |
+
]
|
| 118 |
+
|
| 119 |
+
@pytest.mark.parametrize("attr", PATH_ATTRS)
|
| 120 |
+
def test_attr_is_path(
|
| 121 |
+
self,
|
| 122 |
+
attr: str,
|
| 123 |
+
tmp_path: Path,
|
| 124 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 125 |
+
) -> None:
|
| 126 |
+
cfg = Config(_minimal_raw())
|
| 127 |
+
assert isinstance(getattr(cfg, attr), Path), (
|
| 128 |
+
f"cfg.{attr} should be a Path, got {type(getattr(cfg, attr))}"
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
if attr == "stack_profile_tmp":
|
| 132 |
+
raw = _minimal_raw()
|
| 133 |
+
del raw["paths"]["stack_profile_tmp"]
|
| 134 |
+
monkeypatch.setattr(tempfile, "gettempdir", lambda: str(tmp_path))
|
| 135 |
+
|
| 136 |
+
cfg = Config(raw)
|
| 137 |
+
|
| 138 |
+
assert cfg.stack_profile_tmp == tmp_path / "skill-stack-profile.json"
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class TestConfigExpandTilde:
|
| 142 |
+
"""test_config_expand_tilde -- paths with ~ are expanded to absolute paths."""
|
| 143 |
+
|
| 144 |
+
def test_wiki_dir_is_absolute(self) -> None:
|
| 145 |
+
cfg = Config(_minimal_raw())
|
| 146 |
+
assert cfg.wiki_dir.is_absolute(), (
|
| 147 |
+
f"wiki_dir should be absolute after ~ expansion, got: {cfg.wiki_dir}"
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
def test_skills_dir_is_absolute(self) -> None:
|
| 151 |
+
cfg = Config(_minimal_raw())
|
| 152 |
+
assert cfg.skills_dir.is_absolute()
|
| 153 |
+
|
| 154 |
+
def test_claude_dir_is_absolute(self) -> None:
|
| 155 |
+
cfg = Config(_minimal_raw())
|
| 156 |
+
assert cfg.claude_dir.is_absolute()
|
| 157 |
+
|
| 158 |
+
def test_custom_tilde_path_expanded(self) -> None:
|
| 159 |
+
raw = _minimal_raw({"paths": {"wiki_dir": "~/custom-wiki"}})
|
| 160 |
+
cfg = Config(raw)
|
| 161 |
+
assert "~" not in str(cfg.wiki_dir)
|
| 162 |
+
assert cfg.wiki_dir.is_absolute()
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def test_claude_adapter_modules_use_cfg_paths() -> None:
|
| 166 |
+
from ctx.adapters.claude_code import skill_health, skill_loader
|
| 167 |
+
from ctx.adapters.claude_code.install import install_utils, skill_unload
|
| 168 |
+
|
| 169 |
+
assert install_utils.MANIFEST_PATH == ctx_config.cfg.skill_manifest
|
| 170 |
+
assert skill_loader.SKILLS_DIR == ctx_config.cfg.skills_dir
|
| 171 |
+
assert skill_loader.AGENTS_DIR == ctx_config.cfg.agents_dir
|
| 172 |
+
assert skill_loader.WIKI_DIR == ctx_config.cfg.wiki_dir
|
| 173 |
+
assert skill_loader.PENDING_SKILLS == ctx_config.cfg.pending_skills
|
| 174 |
+
assert skill_loader.MANIFEST_PATH == ctx_config.cfg.skill_manifest
|
| 175 |
+
assert skill_unload.CLAUDE_DIR == ctx_config.cfg.claude_dir
|
| 176 |
+
assert skill_unload.WIKI_DIR == ctx_config.cfg.wiki_dir
|
| 177 |
+
assert skill_unload.MANIFEST_PATH == ctx_config.cfg.skill_manifest
|
| 178 |
+
assert skill_health.SKILLS_DIR == ctx_config.cfg.skills_dir
|
| 179 |
+
assert skill_health.AGENTS_DIR == ctx_config.cfg.agents_dir
|
| 180 |
+
assert skill_health.PENDING_PATH == ctx_config.cfg.pending_skills
|
| 181 |
+
assert skill_health.MANIFEST_PATH == ctx_config.cfg.skill_manifest
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class TestConfigReload:
|
| 185 |
+
"""test_config_reload -- reload() picks up changes to the raw config."""
|
| 186 |
+
|
| 187 |
+
def test_reload_updates_singleton(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
| 188 |
+
# Write a temporary default config with a custom line_threshold
|
| 189 |
+
custom_config = tmp_path / "config.json"
|
| 190 |
+
import json
|
| 191 |
+
|
| 192 |
+
custom_config.write_text(
|
| 193 |
+
json.dumps({"skill_transformer": {"line_threshold": 999}}),
|
| 194 |
+
encoding="utf-8",
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
# Patch the module-level constants so _load_raw reads our file
|
| 198 |
+
monkeypatch.setattr(ctx_config, "_DEFAULT_CONFIG", custom_config)
|
| 199 |
+
# Also suppress user config so it doesn't bleed in
|
| 200 |
+
monkeypatch.setattr(ctx_config, "_USER_CONFIG", tmp_path / "nonexistent.json")
|
| 201 |
+
|
| 202 |
+
ctx_config.reload()
|
| 203 |
+
assert ctx_config.cfg.line_threshold == 999
|
| 204 |
+
|
| 205 |
+
def test_reload_restores_after_monkeypatch(
|
| 206 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 207 |
+
) -> None:
|
| 208 |
+
"""After reload with empty config the attribute still exists (defaults apply)."""
|
| 209 |
+
empty_config = tmp_path / "empty.json"
|
| 210 |
+
empty_config.write_text("{}", encoding="utf-8")
|
| 211 |
+
|
| 212 |
+
monkeypatch.setattr(ctx_config, "_DEFAULT_CONFIG", empty_config)
|
| 213 |
+
monkeypatch.setattr(ctx_config, "_USER_CONFIG", tmp_path / "nonexistent.json")
|
| 214 |
+
|
| 215 |
+
ctx_config.reload()
|
| 216 |
+
# line_threshold should fall back to the packaged default 180
|
| 217 |
+
assert ctx_config.cfg.line_threshold == 180
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class TestConfigAllSkillDirs:
|
| 221 |
+
"""test_config_all_skill_dirs -- all_skill_dirs() returns a list of existing dirs."""
|
| 222 |
+
|
| 223 |
+
def test_returns_list(self) -> None:
|
| 224 |
+
cfg = Config(_minimal_raw())
|
| 225 |
+
result = cfg.all_skill_dirs()
|
| 226 |
+
assert isinstance(result, list)
|
| 227 |
+
|
| 228 |
+
def test_contains_only_existing_dirs(self) -> None:
|
| 229 |
+
cfg = Config(_minimal_raw())
|
| 230 |
+
for d in cfg.all_skill_dirs():
|
| 231 |
+
assert d.exists() and d.is_dir(), f"{d} does not exist or is not a directory"
|
| 232 |
+
|
| 233 |
+
def test_extra_dirs_included_when_they_exist(self, tmp_path: Path) -> None:
|
| 234 |
+
extra = tmp_path / "extra-skills"
|
| 235 |
+
extra.mkdir()
|
| 236 |
+
raw = _minimal_raw({"extra_skill_dirs": [str(extra)]})
|
| 237 |
+
cfg = Config(raw)
|
| 238 |
+
assert extra in cfg.all_skill_dirs()
|
| 239 |
+
|
| 240 |
+
def test_nonexistent_extra_dirs_excluded(self, tmp_path: Path) -> None:
|
| 241 |
+
ghost = tmp_path / "ghost-skills"
|
| 242 |
+
# intentionally do NOT create it
|
| 243 |
+
raw = _minimal_raw({"extra_skill_dirs": [str(ghost)]})
|
| 244 |
+
cfg = Config(raw)
|
| 245 |
+
assert ghost not in cfg.all_skill_dirs()
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
class TestConfigDeepMerge:
|
| 249 |
+
"""test_config_deep_merge -- nested dicts merge correctly and override wins."""
|
| 250 |
+
|
| 251 |
+
def test_override_scalar_wins(self) -> None:
|
| 252 |
+
base: dict[str, Any] = {"a": 1, "b": 2}
|
| 253 |
+
override: dict[str, Any] = {"b": 99}
|
| 254 |
+
_deep_merge(base, override)
|
| 255 |
+
assert base["b"] == 99
|
| 256 |
+
assert base["a"] == 1 # untouched
|
| 257 |
+
|
| 258 |
+
def test_nested_dict_merged_not_replaced(self) -> None:
|
| 259 |
+
base: dict[str, Any] = {"paths": {"wiki_dir": "~/wiki", "skills_dir": "~/skills"}}
|
| 260 |
+
override: dict[str, Any] = {"paths": {"wiki_dir": "~/custom-wiki"}}
|
| 261 |
+
_deep_merge(base, override)
|
| 262 |
+
# wiki_dir is overridden
|
| 263 |
+
assert base["paths"]["wiki_dir"] == "~/custom-wiki"
|
| 264 |
+
# skills_dir is preserved from base
|
| 265 |
+
assert base["paths"]["skills_dir"] == "~/skills"
|
| 266 |
+
|
| 267 |
+
def test_new_key_added(self) -> None:
|
| 268 |
+
base: dict[str, Any] = {"x": 1}
|
| 269 |
+
override: dict[str, Any] = {"y": 2}
|
| 270 |
+
_deep_merge(base, override)
|
| 271 |
+
assert base["y"] == 2
|
| 272 |
+
|
| 273 |
+
def test_deeply_nested_override(self) -> None:
|
| 274 |
+
base: dict[str, Any] = {"a": {"b": {"c": 10, "d": 20}}}
|
| 275 |
+
override: dict[str, Any] = {"a": {"b": {"c": 99}}}
|
| 276 |
+
_deep_merge(base, override)
|
| 277 |
+
assert base["a"]["b"]["c"] == 99
|
| 278 |
+
assert base["a"]["b"]["d"] == 20
|
| 279 |
+
|
| 280 |
+
def test_override_replaces_non_dict_with_scalar(self) -> None:
|
| 281 |
+
base: dict[str, Any] = {"a": {"nested": True}}
|
| 282 |
+
override: dict[str, Any] = {"a": "flat"}
|
| 283 |
+
_deep_merge(base, override)
|
| 284 |
+
assert base["a"] == "flat"
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
class TestConfigIntake:
|
| 288 |
+
"""test_config_intake -- intake gate section is exposed with defaults."""
|
| 289 |
+
|
| 290 |
+
def test_intake_defaults(self) -> None:
|
| 291 |
+
cfg = Config(_minimal_raw())
|
| 292 |
+
assert cfg.intake_enabled is True
|
| 293 |
+
assert cfg.intake_dup_threshold == pytest.approx(0.93)
|
| 294 |
+
assert cfg.intake_near_dup_threshold == pytest.approx(0.80)
|
| 295 |
+
assert cfg.intake_min_neighbors == 0
|
| 296 |
+
assert cfg.intake_min_neighbor_score == pytest.approx(0.30)
|
| 297 |
+
assert cfg.intake_min_body_chars == 120
|
| 298 |
+
assert cfg.intake_backend == "sentence-transformers"
|
| 299 |
+
assert cfg.intake_model is None
|
| 300 |
+
assert cfg.intake_base_url is None
|
| 301 |
+
assert cfg.intake_allow_remote is False
|
| 302 |
+
assert isinstance(cfg.intake_cache_root, Path)
|
| 303 |
+
assert cfg.intake_cache_root.is_absolute()
|
| 304 |
+
|
| 305 |
+
def test_intake_overrides_applied(self) -> None:
|
| 306 |
+
raw = _minimal_raw({
|
| 307 |
+
"intake": {
|
| 308 |
+
"enabled": False,
|
| 309 |
+
"dup_threshold": 0.95,
|
| 310 |
+
"near_dup_threshold": 0.80,
|
| 311 |
+
"min_neighbors": 2,
|
| 312 |
+
"min_neighbor_score": 0.50,
|
| 313 |
+
"min_body_chars": 200,
|
| 314 |
+
"embedding": {
|
| 315 |
+
"backend": "ollama",
|
| 316 |
+
"model": "nomic-embed-text",
|
| 317 |
+
"allow_remote": True,
|
| 318 |
+
},
|
| 319 |
+
},
|
| 320 |
+
})
|
| 321 |
+
cfg = Config(raw)
|
| 322 |
+
assert cfg.intake_enabled is False
|
| 323 |
+
assert cfg.intake_dup_threshold == pytest.approx(0.95)
|
| 324 |
+
assert cfg.intake_near_dup_threshold == pytest.approx(0.80)
|
| 325 |
+
assert cfg.intake_min_neighbors == 2
|
| 326 |
+
assert cfg.intake_min_neighbor_score == pytest.approx(0.50)
|
| 327 |
+
assert cfg.intake_min_body_chars == 200
|
| 328 |
+
assert cfg.intake_backend == "ollama"
|
| 329 |
+
assert cfg.intake_model == "nomic-embed-text"
|
| 330 |
+
assert cfg.intake_allow_remote is True
|
| 331 |
+
|
| 332 |
+
def test_build_intake_config_returns_dataclass(self) -> None:
|
| 333 |
+
from intake_gate import IntakeConfig
|
| 334 |
+
|
| 335 |
+
cfg = Config(_minimal_raw())
|
| 336 |
+
ic = cfg.build_intake_config()
|
| 337 |
+
assert isinstance(ic, IntakeConfig)
|
| 338 |
+
assert ic.dup_threshold == pytest.approx(0.93)
|
| 339 |
+
assert ic.near_dup_threshold == pytest.approx(0.80)
|
| 340 |
+
assert ic.min_body_chars == 120
|
| 341 |
+
|
| 342 |
+
def test_build_intake_config_honours_overrides(self) -> None:
|
| 343 |
+
raw = _minimal_raw({
|
| 344 |
+
"intake": {"dup_threshold": 0.91, "near_dup_threshold": 0.75},
|
| 345 |
+
})
|
| 346 |
+
cfg = Config(raw)
|
| 347 |
+
ic = cfg.build_intake_config()
|
| 348 |
+
assert ic.dup_threshold == pytest.approx(0.91)
|
| 349 |
+
assert ic.near_dup_threshold == pytest.approx(0.75)
|
| 350 |
+
|
| 351 |
+
def test_build_intake_embedder_returns_sentence_transformer(self) -> None:
|
| 352 |
+
from embedding_backend import SentenceTransformerEmbedder
|
| 353 |
+
|
| 354 |
+
cfg = Config(_minimal_raw())
|
| 355 |
+
emb = cfg.build_intake_embedder()
|
| 356 |
+
assert isinstance(emb, SentenceTransformerEmbedder)
|
| 357 |
+
|
| 358 |
+
def test_build_intake_embedder_ollama_selection(self) -> None:
|
| 359 |
+
from embedding_backend import OllamaEmbedder
|
| 360 |
+
|
| 361 |
+
raw = _minimal_raw({
|
| 362 |
+
"intake": {"embedding": {"backend": "ollama"}},
|
| 363 |
+
})
|
| 364 |
+
cfg = Config(raw)
|
| 365 |
+
emb = cfg.build_intake_embedder()
|
| 366 |
+
assert isinstance(emb, OllamaEmbedder)
|
| 367 |
+
|
| 368 |
+
def test_non_string_model_falls_back_to_none(self) -> None:
|
| 369 |
+
raw = _minimal_raw({
|
| 370 |
+
"intake": {"embedding": {"model": 42}}, # wrong type
|
| 371 |
+
})
|
| 372 |
+
cfg = Config(raw)
|
| 373 |
+
assert cfg.intake_model is None
|
src/tests/test_context_monitor.py
CHANGED
|
@@ -1,529 +1,529 @@
|
|
| 1 |
-
"""
|
| 2 |
-
tests/test_context_monitor.py -- pytest suite for context_monitor module.
|
| 3 |
-
|
| 4 |
-
Covers:
|
| 5 |
-
- extract_signals (keyword match, extension match, Bash tool signals, empty input)
|
| 6 |
-
- load_manifest_skills (happy, missing file, bad json)
|
| 7 |
-
- append_intent_log (creates file, appends)
|
| 8 |
-
- count_recent_unmatched (matched vs unmatched)
|
| 9 |
-
- write_pending_skills (creates file, content)
|
| 10 |
-
- load_recent_unmatched_count (happy path, missing file, skips bad lines)
|
| 11 |
-
- _parse_stdin_payload (valid JSON, empty stdin, non-dict, bad JSON)
|
| 12 |
-
- main() (--tool/--input flags, --from-stdin flag, no signals exit-0)
|
| 13 |
-
"""
|
| 14 |
-
|
| 15 |
-
import io
|
| 16 |
-
import json
|
| 17 |
-
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]))
|
| 24 |
-
|
| 25 |
-
from ctx.adapters.claude_code.hooks import context_monitor as _cm
|
| 26 |
-
from ctx.adapters.claude_code.hooks.context_monitor import (
|
| 27 |
-
_parse_stdin_payload,
|
| 28 |
-
append_intent_log,
|
| 29 |
-
count_recent_unmatched,
|
| 30 |
-
extract_signals,
|
| 31 |
-
load_manifest_skills,
|
| 32 |
-
load_recent_unmatched_count,
|
| 33 |
-
write_pending_skills,
|
| 34 |
-
)
|
| 35 |
-
|
| 36 |
-
TODAY = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
# ---------------------------------------------------------------------------
|
| 40 |
-
# extract_signals
|
| 41 |
-
# ---------------------------------------------------------------------------
|
| 42 |
-
|
| 43 |
-
class TestExtractSignals:
|
| 44 |
-
def test_keyword_match_react(self):
|
| 45 |
-
signals = extract_signals("Read", {"file_path": "src/App.tsx"})
|
| 46 |
-
assert "react" in signals
|
| 47 |
-
|
| 48 |
-
def test_keyword_match_docker(self):
|
| 49 |
-
signals = extract_signals("Read", {"file_path": "Dockerfile"})
|
| 50 |
-
assert "docker" in signals
|
| 51 |
-
|
| 52 |
-
def test_extension_tsx_triggers_react(self):
|
| 53 |
-
signals = extract_signals("Read", {"file_path": "component.tsx"})
|
| 54 |
-
assert "react" in signals
|
| 55 |
-
|
| 56 |
-
def test_extension_tf_triggers_terraform(self):
|
| 57 |
-
signals = extract_signals("Write", {"file_path": "main.tf"})
|
| 58 |
-
assert "terraform" in signals
|
| 59 |
-
|
| 60 |
-
def test_bash_pip_install_triggers_python(self):
|
| 61 |
-
signals = extract_signals("Bash", {"command": "pip install fastapi"})
|
| 62 |
-
assert "python" in signals
|
| 63 |
-
|
| 64 |
-
def test_bash_npm_install_triggers_javascript(self):
|
| 65 |
-
signals = extract_signals("Bash", {"command": "npm install react"})
|
| 66 |
-
assert "javascript" in signals
|
| 67 |
-
|
| 68 |
-
def test_empty_input_returns_empty(self):
|
| 69 |
-
signals = extract_signals("Read", {})
|
| 70 |
-
assert signals == []
|
| 71 |
-
|
| 72 |
-
def test_no_match_returns_empty(self):
|
| 73 |
-
signals = extract_signals("Read", {"file_path": "README.md"})
|
| 74 |
-
assert signals == []
|
| 75 |
-
|
| 76 |
-
def test_multiple_signals_deduped(self):
|
| 77 |
-
signals = extract_signals("Read", {"content": "react jsx tsx"})
|
| 78 |
-
# react should appear only once despite 3 matching keywords
|
| 79 |
-
assert signals.count("react") == 1
|
| 80 |
-
|
| 81 |
-
def test_signals_sorted(self):
|
| 82 |
-
signals = extract_signals("Bash", {"command": "docker-compose up"})
|
| 83 |
-
assert signals == sorted(signals)
|
| 84 |
-
|
| 85 |
-
def test_anthropic_keyword_maps_to_sdk(self):
|
| 86 |
-
signals = extract_signals("Read", {"content": "from anthropic import Anthropic"})
|
| 87 |
-
assert "anthropic-sdk" in signals
|
| 88 |
-
|
| 89 |
-
def test_kubernetes_keyword_match(self):
|
| 90 |
-
signals = extract_signals("Bash", {"command": "kubectl apply -f deployment.yaml"})
|
| 91 |
-
assert "kubernetes" in signals
|
| 92 |
-
|
| 93 |
-
def test_case_insensitive_match(self):
|
| 94 |
-
signals = extract_signals("Read", {"content": "FASTAPI app = FastAPI()"})
|
| 95 |
-
assert "fastapi" in signals
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
# ---------------------------------------------------------------------------
|
| 99 |
-
# load_manifest_skills
|
| 100 |
-
# ---------------------------------------------------------------------------
|
| 101 |
-
|
| 102 |
-
class TestLoadManifestSkills:
|
| 103 |
-
def test_happy_path(self, tmp_path, monkeypatch):
|
| 104 |
-
manifest = {"load": [{"skill": "react"}, {"skill": "docker"}]}
|
| 105 |
-
mpath = tmp_path / "manifest.json"
|
| 106 |
-
mpath.write_text(json.dumps(manifest))
|
| 107 |
-
monkeypatch.setattr(_cm, "MANIFEST_PATH", mpath)
|
| 108 |
-
result = load_manifest_skills()
|
| 109 |
-
assert result == {"react", "docker"}
|
| 110 |
-
|
| 111 |
-
def test_missing_file_returns_empty_set(self, tmp_path, monkeypatch):
|
| 112 |
-
monkeypatch.setattr(_cm, "MANIFEST_PATH", tmp_path / "no-such.json")
|
| 113 |
-
assert load_manifest_skills() == set()
|
| 114 |
-
|
| 115 |
-
def test_bad_json_returns_empty_set(self, tmp_path, monkeypatch):
|
| 116 |
-
mpath = tmp_path / "manifest.json"
|
| 117 |
-
mpath.write_text("not-json")
|
| 118 |
-
monkeypatch.setattr(_cm, "MANIFEST_PATH", mpath)
|
| 119 |
-
assert load_manifest_skills() == set()
|
| 120 |
-
|
| 121 |
-
def test_empty_load_list(self, tmp_path, monkeypatch):
|
| 122 |
-
mpath = tmp_path / "manifest.json"
|
| 123 |
-
mpath.write_text(json.dumps({"load": []}))
|
| 124 |
-
monkeypatch.setattr(_cm, "MANIFEST_PATH", mpath)
|
| 125 |
-
assert load_manifest_skills() == set()
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
# ---------------------------------------------------------------------------
|
| 129 |
-
# append_intent_log
|
| 130 |
-
# ---------------------------------------------------------------------------
|
| 131 |
-
|
| 132 |
-
class TestAppendIntentLog:
|
| 133 |
-
def test_creates_file_and_appends(self, tmp_path, monkeypatch):
|
| 134 |
-
log = tmp_path / "intent.jsonl"
|
| 135 |
-
monkeypatch.setattr(_cm, "CLAUDE_DIR", tmp_path)
|
| 136 |
-
monkeypatch.setattr(_cm, "INTENT_LOG", log)
|
| 137 |
-
entry = {"date": TODAY, "signals": ["react"]}
|
| 138 |
-
append_intent_log(entry)
|
| 139 |
-
lines = [line for line in log.read_text().strip().split("\n") if line]
|
| 140 |
-
assert len(lines) == 1
|
| 141 |
-
assert json.loads(lines[0])["signals"] == ["react"]
|
| 142 |
-
|
| 143 |
-
def test_appends_multiple_entries(self, tmp_path, monkeypatch):
|
| 144 |
-
log = tmp_path / "intent.jsonl"
|
| 145 |
-
monkeypatch.setattr(_cm, "CLAUDE_DIR", tmp_path)
|
| 146 |
-
monkeypatch.setattr(_cm, "INTENT_LOG", log)
|
| 147 |
-
append_intent_log({"date": TODAY, "signals": ["react"]})
|
| 148 |
-
append_intent_log({"date": TODAY, "signals": ["docker"]})
|
| 149 |
-
lines = [line for line in log.read_text().strip().split("\n") if line]
|
| 150 |
-
assert len(lines) == 2
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
# ---------------------------------------------------------------------------
|
| 154 |
-
# count_recent_unmatched
|
| 155 |
-
# ---------------------------------------------------------------------------
|
| 156 |
-
|
| 157 |
-
class TestCountRecentUnmatched:
|
| 158 |
-
def test_all_matched(self):
|
| 159 |
-
unmatched = count_recent_unmatched(["react", "docker"], {"react", "docker"})
|
| 160 |
-
assert unmatched == []
|
| 161 |
-
|
| 162 |
-
def test_none_matched(self):
|
| 163 |
-
unmatched = count_recent_unmatched(["react", "docker"], set())
|
| 164 |
-
assert set(unmatched) == {"react", "docker"}
|
| 165 |
-
|
| 166 |
-
def test_partial_match(self):
|
| 167 |
-
unmatched = count_recent_unmatched(["react", "docker"], {"react"})
|
| 168 |
-
assert unmatched == ["docker"]
|
| 169 |
-
|
| 170 |
-
def test_empty_signals(self):
|
| 171 |
-
assert count_recent_unmatched([], {"react"}) == []
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
# ---------------------------------------------------------------------------
|
| 175 |
-
# write_pending_skills
|
| 176 |
-
# ---------------------------------------------------------------------------
|
| 177 |
-
|
| 178 |
-
class TestWritePendingSkills:
|
| 179 |
-
def test_writes_pending_skills_file(self, tmp_path, monkeypatch):
|
| 180 |
-
monkeypatch.setattr(_cm, "PENDING_SKILLS", tmp_path / "pending.json")
|
| 181 |
-
monkeypatch.setattr(_cm, "graph_suggest", lambda unmatched: [])
|
| 182 |
-
write_pending_skills(["react", "docker"])
|
| 183 |
-
pending = json.loads((tmp_path / "pending.json").read_text())
|
| 184 |
-
assert pending["unmatched_signals"] == ["react", "docker"]
|
| 185 |
-
assert "suggestion" in pending
|
| 186 |
-
|
| 187 |
-
def test_suggestion_mentions_signals(self, tmp_path, monkeypatch):
|
| 188 |
-
monkeypatch.setattr(_cm, "PENDING_SKILLS", tmp_path / "pending.json")
|
| 189 |
-
monkeypatch.setattr(_cm, "graph_suggest", lambda unmatched: [])
|
| 190 |
-
write_pending_skills(["fastapi"])
|
| 191 |
-
pending = json.loads((tmp_path / "pending.json").read_text())
|
| 192 |
-
assert "fastapi" in pending["suggestion"]
|
| 193 |
-
|
| 194 |
-
def test_empty_unmatched(self, tmp_path, monkeypatch):
|
| 195 |
-
monkeypatch.setattr(_cm, "PENDING_SKILLS", tmp_path / "pending.json")
|
| 196 |
-
monkeypatch.setattr(_cm, "graph_suggest", lambda unmatched: [])
|
| 197 |
-
write_pending_skills([])
|
| 198 |
-
pending = json.loads((tmp_path / "pending.json").read_text())
|
| 199 |
-
assert pending["unmatched_signals"] == []
|
| 200 |
-
|
| 201 |
-
def test_graph_suggestions_list_present(self, tmp_path, monkeypatch):
|
| 202 |
-
monkeypatch.setattr(_cm, "PENDING_SKILLS", tmp_path / "pending.json")
|
| 203 |
-
monkeypatch.setattr(
|
| 204 |
-
_cm,
|
| 205 |
-
"graph_suggest",
|
| 206 |
-
lambda unmatched: [{"name": "fastapi-pro", "type": "skill"}],
|
| 207 |
-
)
|
| 208 |
-
write_pending_skills(["unknown-signal"])
|
| 209 |
-
pending = json.loads((tmp_path / "pending.json").read_text())
|
| 210 |
-
assert pending["graph_suggestions"] == [{"name": "fastapi-pro", "type": "skill"}]
|
| 211 |
-
|
| 212 |
-
def test_graph_suggest_filters_to_execution_bundle_types(self, tmp_path, monkeypatch):
|
| 213 |
-
graph_path = tmp_path / "skill-wiki" / "graphify-out" / "graph.json"
|
| 214 |
-
graph_path.parent.mkdir(parents=True)
|
| 215 |
-
graph_path.write_text("{}", encoding="utf-8")
|
| 216 |
-
monkeypatch.setattr(_cm, "CLAUDE_DIR", tmp_path)
|
| 217 |
-
calls = {}
|
| 218 |
-
|
| 219 |
-
class FakeGraph:
|
| 220 |
-
def number_of_nodes(self):
|
| 221 |
-
return 1
|
| 222 |
-
|
| 223 |
-
fake_graph_module = type(
|
| 224 |
-
"FakeGraphModule",
|
| 225 |
-
(),
|
| 226 |
-
{"load_graph": staticmethod(lambda _path=None: FakeGraph())},
|
| 227 |
-
)
|
| 228 |
-
|
| 229 |
-
def fake_recommend_by_tags(graph, tags, **kwargs):
|
| 230 |
-
calls["entity_types"] = kwargs.get("entity_types")
|
| 231 |
-
return [{"name": "fastapi-pro", "type": "skill"}]
|
| 232 |
-
|
| 233 |
-
fake_recommend_module = type(
|
| 234 |
-
"FakeRecommendModule",
|
| 235 |
-
(),
|
| 236 |
-
{"recommend_by_tags": staticmethod(fake_recommend_by_tags)},
|
| 237 |
-
)
|
| 238 |
-
monkeypatch.setitem(sys.modules, "ctx.core.graph.resolve_graph", fake_graph_module)
|
| 239 |
-
monkeypatch.setitem(
|
| 240 |
-
sys.modules,
|
| 241 |
-
"ctx.core.resolve.recommendations",
|
| 242 |
-
fake_recommend_module,
|
| 243 |
-
)
|
| 244 |
-
|
| 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
|
| 251 |
-
# ---------------------------------------------------------------------------
|
| 252 |
-
|
| 253 |
-
class TestLoadRecentUnmatchedCount:
|
| 254 |
-
def _write_log(self, path: Path, entries: list[dict]) -> None:
|
| 255 |
-
path.write_text("\n".join(json.dumps(e) for e in entries) + "\n")
|
| 256 |
-
|
| 257 |
-
def test_happy_path_counts_distinct(self, tmp_path, monkeypatch):
|
| 258 |
-
log = tmp_path / "intent.jsonl"
|
| 259 |
-
self._write_log(log, [
|
| 260 |
-
{"date": TODAY, "unmatched": ["react", "docker"]},
|
| 261 |
-
{"date": TODAY, "unmatched": ["react"]}, # react already counted
|
| 262 |
-
])
|
| 263 |
-
monkeypatch.setattr(_cm, "INTENT_LOG", log)
|
| 264 |
-
count = load_recent_unmatched_count()
|
| 265 |
-
assert count == 2 # react + docker distinct
|
| 266 |
-
|
| 267 |
-
def test_missing_file_returns_0(self, tmp_path, monkeypatch):
|
| 268 |
-
monkeypatch.setattr(_cm, "INTENT_LOG", tmp_path / "nope.jsonl")
|
| 269 |
-
assert load_recent_unmatched_count() == 0
|
| 270 |
-
|
| 271 |
-
def test_skips_bad_lines(self, tmp_path, monkeypatch):
|
| 272 |
-
log = tmp_path / "intent.jsonl"
|
| 273 |
-
log.write_text(f'not-json\n{json.dumps({"date": TODAY, "unmatched": ["react"]})}\n')
|
| 274 |
-
monkeypatch.setattr(_cm, "INTENT_LOG", log)
|
| 275 |
-
assert load_recent_unmatched_count() == 1
|
| 276 |
-
|
| 277 |
-
def test_other_dates_not_counted(self, tmp_path, monkeypatch):
|
| 278 |
-
log = tmp_path / "intent.jsonl"
|
| 279 |
-
self._write_log(log, [{"date": "2000-01-01", "unmatched": ["react"]}])
|
| 280 |
-
monkeypatch.setattr(_cm, "INTENT_LOG", log)
|
| 281 |
-
assert load_recent_unmatched_count() == 0
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
# ---------------------------------------------------------------------------
|
| 285 |
-
# _parse_stdin_payload
|
| 286 |
-
# ---------------------------------------------------------------------------
|
| 287 |
-
|
| 288 |
-
class TestParseStdinPayload:
|
| 289 |
-
def test_valid_payload(self, monkeypatch):
|
| 290 |
-
payload = json.dumps({"tool_name": "Read", "tool_input": {"file_path": "foo.py"}})
|
| 291 |
-
monkeypatch.setattr(sys, "stdin", io.StringIO(payload))
|
| 292 |
-
tool_name, tool_input = _parse_stdin_payload()
|
| 293 |
-
assert tool_name == "Read"
|
| 294 |
-
assert tool_input == {"file_path": "foo.py"}
|
| 295 |
-
|
| 296 |
-
def test_empty_stdin(self, monkeypatch):
|
| 297 |
-
monkeypatch.setattr(sys, "stdin", io.StringIO(""))
|
| 298 |
-
tool_name, tool_input = _parse_stdin_payload()
|
| 299 |
-
assert tool_name == "unknown"
|
| 300 |
-
assert tool_input == {}
|
| 301 |
-
|
| 302 |
-
def test_non_dict_json(self, monkeypatch):
|
| 303 |
-
monkeypatch.setattr(sys, "stdin", io.StringIO(json.dumps([1, 2, 3])))
|
| 304 |
-
tool_name, tool_input = _parse_stdin_payload()
|
| 305 |
-
assert tool_name == "unknown"
|
| 306 |
-
|
| 307 |
-
def test_bad_json(self, monkeypatch):
|
| 308 |
-
monkeypatch.setattr(sys, "stdin", io.StringIO("not-json"))
|
| 309 |
-
tool_name, tool_input = _parse_stdin_payload()
|
| 310 |
-
assert tool_name == "unknown"
|
| 311 |
-
assert tool_input == {}
|
| 312 |
-
|
| 313 |
-
def test_missing_tool_input_defaults_to_empty(self, monkeypatch):
|
| 314 |
-
payload = json.dumps({"tool_name": "Bash"})
|
| 315 |
-
monkeypatch.setattr(sys, "stdin", io.StringIO(payload))
|
| 316 |
-
_, tool_input = _parse_stdin_payload()
|
| 317 |
-
assert tool_input == {}
|
| 318 |
-
|
| 319 |
-
def test_non_dict_tool_input_defaults_to_empty(self, monkeypatch):
|
| 320 |
-
payload = json.dumps({"tool_name": "Bash", "tool_input": "not-a-dict"})
|
| 321 |
-
monkeypatch.setattr(sys, "stdin", io.StringIO(payload))
|
| 322 |
-
_, tool_input = _parse_stdin_payload()
|
| 323 |
-
assert tool_input == {}
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
# ---------------------------------------------------------------------------
|
| 327 |
-
# main()
|
| 328 |
-
# ---------------------------------------------------------------------------
|
| 329 |
-
|
| 330 |
-
class TestMain:
|
| 331 |
-
def test_no_signals_exits_0(self, tmp_path, monkeypatch):
|
| 332 |
-
"""When tool input produces no signals, main exits 0."""
|
| 333 |
-
monkeypatch.setattr(_cm, "CLAUDE_DIR", tmp_path)
|
| 334 |
-
monkeypatch.setattr(_cm, "INTENT_LOG", tmp_path / "intent.jsonl")
|
| 335 |
-
monkeypatch.setattr(_cm, "MANIFEST_PATH", tmp_path / "manifest.json")
|
| 336 |
-
monkeypatch.setattr(_cm, "PENDING_SKILLS", tmp_path / "pending.json")
|
| 337 |
-
monkeypatch.setattr(sys, "argv", ["context_monitor.py", "--tool", "Read", "--input", "{}"])
|
| 338 |
-
with pytest.raises(SystemExit) as exc:
|
| 339 |
-
_cm.main()
|
| 340 |
-
assert exc.value.code == 0
|
| 341 |
-
|
| 342 |
-
def test_signals_appended_to_log(self, tmp_path, monkeypatch):
|
| 343 |
-
"""Signals from --input are written to the intent log."""
|
| 344 |
-
monkeypatch.setattr(_cm, "CLAUDE_DIR", tmp_path)
|
| 345 |
-
log = tmp_path / "intent.jsonl"
|
| 346 |
-
monkeypatch.setattr(_cm, "INTENT_LOG", log)
|
| 347 |
-
monkeypatch.setattr(_cm, "MANIFEST_PATH", tmp_path / "manifest.json")
|
| 348 |
-
monkeypatch.setattr(_cm, "PENDING_SKILLS", tmp_path / "pending.json")
|
| 349 |
-
monkeypatch.setattr(_cm, "_THRESHOLD", 999) # prevent pending write
|
| 350 |
-
tool_input = json.dumps({"file_path": "Dockerfile"})
|
| 351 |
-
monkeypatch.setattr(sys, "argv", ["context_monitor.py", "--tool", "Read", "--input", tool_input])
|
| 352 |
-
_cm.main()
|
| 353 |
-
lines = [line for line in log.read_text().strip().split("\n") if line]
|
| 354 |
-
assert len(lines) == 1
|
| 355 |
-
entry = json.loads(lines[0])
|
| 356 |
-
assert "docker" in entry["signals"]
|
| 357 |
-
|
| 358 |
-
def test_from_stdin_flag(self, tmp_path, monkeypatch):
|
| 359 |
-
"""--from-stdin reads tool payload from stdin."""
|
| 360 |
-
monkeypatch.setattr(_cm, "CLAUDE_DIR", tmp_path)
|
| 361 |
-
log = tmp_path / "intent.jsonl"
|
| 362 |
-
monkeypatch.setattr(_cm, "INTENT_LOG", log)
|
| 363 |
-
monkeypatch.setattr(_cm, "MANIFEST_PATH", tmp_path / "manifest.json")
|
| 364 |
-
monkeypatch.setattr(_cm, "PENDING_SKILLS", tmp_path / "pending.json")
|
| 365 |
-
monkeypatch.setattr(_cm, "_THRESHOLD", 999)
|
| 366 |
-
payload = json.dumps({"tool_name": "Read", "tool_input": {"file_path": "Dockerfile"}})
|
| 367 |
-
monkeypatch.setattr(sys, "stdin", io.StringIO(payload))
|
| 368 |
-
monkeypatch.setattr(sys, "argv", ["context_monitor.py", "--from-stdin"])
|
| 369 |
-
_cm.main()
|
| 370 |
-
lines = [line for line in log.read_text().strip().split("\n") if line]
|
| 371 |
-
assert len(lines) == 1
|
| 372 |
-
entry = json.loads(lines[0])
|
| 373 |
-
assert "docker" in entry["signals"]
|
| 374 |
-
|
| 375 |
-
def test_bad_json_input_falls_back_to_raw(self, tmp_path, monkeypatch):
|
| 376 |
-
"""Malformed --input falls back to {'raw': value} and may produce no signals."""
|
| 377 |
-
monkeypatch.setattr(_cm, "CLAUDE_DIR", tmp_path)
|
| 378 |
-
log = tmp_path / "intent.jsonl"
|
| 379 |
-
monkeypatch.setattr(_cm, "INTENT_LOG", log)
|
| 380 |
-
monkeypatch.setattr(_cm, "MANIFEST_PATH", tmp_path / "manifest.json")
|
| 381 |
-
monkeypatch.setattr(_cm, "PENDING_SKILLS", tmp_path / "pending.json")
|
| 382 |
-
monkeypatch.setattr(sys, "argv", ["context_monitor.py", "--tool", "Read", "--input", "not-json"])
|
| 383 |
-
# Should not crash
|
| 384 |
-
try:
|
| 385 |
-
_cm.main()
|
| 386 |
-
except SystemExit as e:
|
| 387 |
-
assert e.code == 0 # exits 0 when no signals
|
| 388 |
-
|
| 389 |
-
def test_threshold_triggers_pending_write(self, tmp_path, monkeypatch):
|
| 390 |
-
"""When unmatched count >= threshold, pending-skills.json is written."""
|
| 391 |
-
monkeypatch.setattr(_cm, "CLAUDE_DIR", tmp_path)
|
| 392 |
-
log = tmp_path / "intent.jsonl"
|
| 393 |
-
pending = tmp_path / "pending.json"
|
| 394 |
-
monkeypatch.setattr(_cm, "INTENT_LOG", log)
|
| 395 |
-
monkeypatch.setattr(_cm, "MANIFEST_PATH", tmp_path / "manifest.json")
|
| 396 |
-
monkeypatch.setattr(_cm, "PENDING_SKILLS", pending)
|
| 397 |
-
monkeypatch.setattr(_cm, "_THRESHOLD", 1) # trigger on 1 unmatched
|
| 398 |
-
tool_input = json.dumps({"file_path": "Dockerfile"})
|
| 399 |
-
monkeypatch.setattr(sys, "argv", ["context_monitor.py", "--tool", "Read", "--input", tool_input])
|
| 400 |
-
_cm.main()
|
| 401 |
-
assert pending.exists()
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
# ---------------------------------------------------------------------------
|
| 405 |
-
# Cumulative-threshold regression (code-reviewer finding BLOCKER)
|
| 406 |
-
# ---------------------------------------------------------------------------
|
| 407 |
-
#
|
| 408 |
-
# Prior impl used ``len(unmatched) >= THRESHOLD`` where ``unmatched`` is the
|
| 409 |
-
# per-invocation list. A single tool call almost never surfaces 3 unmatched
|
| 410 |
-
# signals alone, so the default threshold=3 meant pending-skills.json was
|
| 411 |
-
# essentially never written — silently killing the suggestion arm of the
|
| 412 |
-
# alive loop. The fix walks the intent log and checks the cumulative
|
| 413 |
-
# (per-day, across all invocations) unmatched count against the threshold.
|
| 414 |
-
|
| 415 |
-
class TestCumulativeThreshold:
|
| 416 |
-
"""The threshold must fire on cumulative unmatched across today's log,
|
| 417 |
-
not just on a single invocation's count.
|
| 418 |
-
"""
|
| 419 |
-
|
| 420 |
-
def _setup_paths(self, tmp_path, monkeypatch):
|
| 421 |
-
log = tmp_path / "intent.jsonl"
|
| 422 |
-
pending = tmp_path / "pending.json"
|
| 423 |
-
monkeypatch.setattr(_cm, "CLAUDE_DIR", tmp_path)
|
| 424 |
-
monkeypatch.setattr(_cm, "INTENT_LOG", log)
|
| 425 |
-
monkeypatch.setattr(_cm, "MANIFEST_PATH", tmp_path / "manifest.json")
|
| 426 |
-
monkeypatch.setattr(_cm, "PENDING_SKILLS", pending)
|
| 427 |
-
return log, pending
|
| 428 |
-
|
| 429 |
-
def _run_main(self, monkeypatch, tool_name: str, tool_input: dict):
|
| 430 |
-
monkeypatch.setattr(
|
| 431 |
-
sys, "argv",
|
| 432 |
-
["context_monitor.py", "--tool", tool_name, "--input", json.dumps(tool_input)],
|
| 433 |
-
)
|
| 434 |
-
_cm.main()
|
| 435 |
-
|
| 436 |
-
def test_fires_on_cumulative_across_three_invocations(
|
| 437 |
-
self, tmp_path, monkeypatch,
|
| 438 |
-
):
|
| 439 |
-
"""Three invocations each surfacing ONE unmatched signal should
|
| 440 |
-
trigger pending-skills write when THRESHOLD=3.
|
| 441 |
-
|
| 442 |
-
This is the case the old len(unmatched)>=THRESHOLD check missed.
|
| 443 |
-
The user types a react file, then opens a Dockerfile, then edits
|
| 444 |
-
terraform — three separate tool calls, three different unmatched
|
| 445 |
-
signals, cumulatively at threshold.
|
| 446 |
-
"""
|
| 447 |
-
_, pending = self._setup_paths(tmp_path, monkeypatch)
|
| 448 |
-
monkeypatch.setattr(_cm, "_THRESHOLD", 3)
|
| 449 |
-
|
| 450 |
-
# Three invocations, one unique unmatched signal each.
|
| 451 |
-
self._run_main(monkeypatch, "Read", {"file_path": "App.tsx"}) # react
|
| 452 |
-
assert not pending.exists(), "fired after 1 cumulative unmatched"
|
| 453 |
-
|
| 454 |
-
self._run_main(monkeypatch, "Read", {"file_path": "Dockerfile"}) # docker
|
| 455 |
-
assert not pending.exists(), "fired after 2 cumulative unmatched"
|
| 456 |
-
|
| 457 |
-
self._run_main(monkeypatch, "Read", {"file_path": "main.tf"}) # terraform
|
| 458 |
-
assert pending.exists(), (
|
| 459 |
-
"did NOT fire after 3 cumulative unmatched — "
|
| 460 |
-
"the per-invocation threshold bug regressed"
|
| 461 |
-
)
|
| 462 |
-
|
| 463 |
-
def test_does_not_fire_below_cumulative_threshold(
|
| 464 |
-
self, tmp_path, monkeypatch,
|
| 465 |
-
):
|
| 466 |
-
"""Below-threshold cumulative count must NOT trigger.
|
| 467 |
-
|
| 468 |
-
Otherwise every first-keystroke would spam pending-skills.json.
|
| 469 |
-
"""
|
| 470 |
-
_, pending = self._setup_paths(tmp_path, monkeypatch)
|
| 471 |
-
monkeypatch.setattr(_cm, "_THRESHOLD", 3)
|
| 472 |
-
|
| 473 |
-
self._run_main(monkeypatch, "Read", {"file_path": "App.tsx"})
|
| 474 |
-
self._run_main(monkeypatch, "Read", {"file_path": "Dockerfile"})
|
| 475 |
-
# Only 2 unique signals accumulated; THRESHOLD=3 => no write.
|
| 476 |
-
assert not pending.exists()
|
| 477 |
-
|
| 478 |
-
def test_fires_when_single_invocation_surfaces_multiple(
|
| 479 |
-
self, tmp_path, monkeypatch,
|
| 480 |
-
):
|
| 481 |
-
"""Backward-compat: a single invocation carrying threshold-worth of
|
| 482 |
-
new signals on its own still fires (the old happy path)."""
|
| 483 |
-
_, pending = self._setup_paths(tmp_path, monkeypatch)
|
| 484 |
-
monkeypatch.setattr(_cm, "_THRESHOLD", 2)
|
| 485 |
-
|
| 486 |
-
# A Bash pip install surfaces multiple signals in one invocation.
|
| 487 |
-
self._run_main(
|
| 488 |
-
monkeypatch, "Bash",
|
| 489 |
-
{"command": "pip install fastapi django"},
|
| 490 |
-
)
|
| 491 |
-
assert pending.exists()
|
| 492 |
-
|
| 493 |
-
def test_pending_contains_cumulative_union(
|
| 494 |
-
self, tmp_path, monkeypatch,
|
| 495 |
-
):
|
| 496 |
-
"""When the threshold fires, pending-skills.json lists ALL of today's
|
| 497 |
-
unmatched signals, not just the current invocation's."""
|
| 498 |
-
_, pending = self._setup_paths(tmp_path, monkeypatch)
|
| 499 |
-
monkeypatch.setattr(_cm, "_THRESHOLD", 2)
|
| 500 |
-
|
| 501 |
-
self._run_main(monkeypatch, "Read", {"file_path": "App.tsx"})
|
| 502 |
-
self._run_main(monkeypatch, "Read", {"file_path": "Dockerfile"})
|
| 503 |
-
|
| 504 |
-
assert pending.exists()
|
| 505 |
-
payload = json.loads(pending.read_text())
|
| 506 |
-
unmatched = set(payload.get("unmatched_signals", []))
|
| 507 |
-
# Both react (from App.tsx) and docker (from Dockerfile) must be
|
| 508 |
-
# present — a fix that only reports the current invocation's
|
| 509 |
-
# signals would miss react.
|
| 510 |
-
assert {"react", "docker"}.issubset(unmatched), (
|
| 511 |
-
f"pending does not include cumulative signals: {unmatched}"
|
| 512 |
-
)
|
| 513 |
-
|
| 514 |
-
def test_duplicate_signals_across_invocations_count_once(
|
| 515 |
-
self, tmp_path, monkeypatch,
|
| 516 |
-
):
|
| 517 |
-
"""Unique-set cumulative count — repeated signals don't inflate.
|
| 518 |
-
|
| 519 |
-
The same file edited twice should not double-count toward the
|
| 520 |
-
threshold; otherwise a tight edit-save-edit-save loop would
|
| 521 |
-
auto-trigger suggestions on a single concept.
|
| 522 |
-
"""
|
| 523 |
-
_, pending = self._setup_paths(tmp_path, monkeypatch)
|
| 524 |
-
monkeypatch.setattr(_cm, "_THRESHOLD", 2)
|
| 525 |
-
|
| 526 |
-
self._run_main(monkeypatch, "Read", {"file_path": "App.tsx"}) # react
|
| 527 |
-
self._run_main(monkeypatch, "Read", {"file_path": "index.tsx"}) # react (dup)
|
| 528 |
-
# Only 1 unique unmatched concept; THRESHOLD=2 => no write.
|
| 529 |
-
assert not pending.exists()
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
tests/test_context_monitor.py -- pytest suite for context_monitor module.
|
| 3 |
+
|
| 4 |
+
Covers:
|
| 5 |
+
- extract_signals (keyword match, extension match, Bash tool signals, empty input)
|
| 6 |
+
- load_manifest_skills (happy, missing file, bad json)
|
| 7 |
+
- append_intent_log (creates file, appends)
|
| 8 |
+
- count_recent_unmatched (matched vs unmatched)
|
| 9 |
+
- write_pending_skills (creates file, content)
|
| 10 |
+
- load_recent_unmatched_count (happy path, missing file, skips bad lines)
|
| 11 |
+
- _parse_stdin_payload (valid JSON, empty stdin, non-dict, bad JSON)
|
| 12 |
+
- main() (--tool/--input flags, --from-stdin flag, no signals exit-0)
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import io
|
| 16 |
+
import json
|
| 17 |
+
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]))
|
| 24 |
+
|
| 25 |
+
from ctx.adapters.claude_code.hooks import context_monitor as _cm
|
| 26 |
+
from ctx.adapters.claude_code.hooks.context_monitor import (
|
| 27 |
+
_parse_stdin_payload,
|
| 28 |
+
append_intent_log,
|
| 29 |
+
count_recent_unmatched,
|
| 30 |
+
extract_signals,
|
| 31 |
+
load_manifest_skills,
|
| 32 |
+
load_recent_unmatched_count,
|
| 33 |
+
write_pending_skills,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
TODAY = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# ---------------------------------------------------------------------------
|
| 40 |
+
# extract_signals
|
| 41 |
+
# ---------------------------------------------------------------------------
|
| 42 |
+
|
| 43 |
+
class TestExtractSignals:
|
| 44 |
+
def test_keyword_match_react(self):
|
| 45 |
+
signals = extract_signals("Read", {"file_path": "src/App.tsx"})
|
| 46 |
+
assert "react" in signals
|
| 47 |
+
|
| 48 |
+
def test_keyword_match_docker(self):
|
| 49 |
+
signals = extract_signals("Read", {"file_path": "Dockerfile"})
|
| 50 |
+
assert "docker" in signals
|
| 51 |
+
|
| 52 |
+
def test_extension_tsx_triggers_react(self):
|
| 53 |
+
signals = extract_signals("Read", {"file_path": "component.tsx"})
|
| 54 |
+
assert "react" in signals
|
| 55 |
+
|
| 56 |
+
def test_extension_tf_triggers_terraform(self):
|
| 57 |
+
signals = extract_signals("Write", {"file_path": "main.tf"})
|
| 58 |
+
assert "terraform" in signals
|
| 59 |
+
|
| 60 |
+
def test_bash_pip_install_triggers_python(self):
|
| 61 |
+
signals = extract_signals("Bash", {"command": "pip install fastapi"})
|
| 62 |
+
assert "python" in signals
|
| 63 |
+
|
| 64 |
+
def test_bash_npm_install_triggers_javascript(self):
|
| 65 |
+
signals = extract_signals("Bash", {"command": "npm install react"})
|
| 66 |
+
assert "javascript" in signals
|
| 67 |
+
|
| 68 |
+
def test_empty_input_returns_empty(self):
|
| 69 |
+
signals = extract_signals("Read", {})
|
| 70 |
+
assert signals == []
|
| 71 |
+
|
| 72 |
+
def test_no_match_returns_empty(self):
|
| 73 |
+
signals = extract_signals("Read", {"file_path": "README.md"})
|
| 74 |
+
assert signals == []
|
| 75 |
+
|
| 76 |
+
def test_multiple_signals_deduped(self):
|
| 77 |
+
signals = extract_signals("Read", {"content": "react jsx tsx"})
|
| 78 |
+
# react should appear only once despite 3 matching keywords
|
| 79 |
+
assert signals.count("react") == 1
|
| 80 |
+
|
| 81 |
+
def test_signals_sorted(self):
|
| 82 |
+
signals = extract_signals("Bash", {"command": "docker-compose up"})
|
| 83 |
+
assert signals == sorted(signals)
|
| 84 |
+
|
| 85 |
+
def test_anthropic_keyword_maps_to_sdk(self):
|
| 86 |
+
signals = extract_signals("Read", {"content": "from anthropic import Anthropic"})
|
| 87 |
+
assert "anthropic-sdk" in signals
|
| 88 |
+
|
| 89 |
+
def test_kubernetes_keyword_match(self):
|
| 90 |
+
signals = extract_signals("Bash", {"command": "kubectl apply -f deployment.yaml"})
|
| 91 |
+
assert "kubernetes" in signals
|
| 92 |
+
|
| 93 |
+
def test_case_insensitive_match(self):
|
| 94 |
+
signals = extract_signals("Read", {"content": "FASTAPI app = FastAPI()"})
|
| 95 |
+
assert "fastapi" in signals
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# ---------------------------------------------------------------------------
|
| 99 |
+
# load_manifest_skills
|
| 100 |
+
# ---------------------------------------------------------------------------
|
| 101 |
+
|
| 102 |
+
class TestLoadManifestSkills:
|
| 103 |
+
def test_happy_path(self, tmp_path, monkeypatch):
|
| 104 |
+
manifest = {"load": [{"skill": "react"}, {"skill": "docker"}]}
|
| 105 |
+
mpath = tmp_path / "manifest.json"
|
| 106 |
+
mpath.write_text(json.dumps(manifest))
|
| 107 |
+
monkeypatch.setattr(_cm, "MANIFEST_PATH", mpath)
|
| 108 |
+
result = load_manifest_skills()
|
| 109 |
+
assert result == {"react", "docker"}
|
| 110 |
+
|
| 111 |
+
def test_missing_file_returns_empty_set(self, tmp_path, monkeypatch):
|
| 112 |
+
monkeypatch.setattr(_cm, "MANIFEST_PATH", tmp_path / "no-such.json")
|
| 113 |
+
assert load_manifest_skills() == set()
|
| 114 |
+
|
| 115 |
+
def test_bad_json_returns_empty_set(self, tmp_path, monkeypatch):
|
| 116 |
+
mpath = tmp_path / "manifest.json"
|
| 117 |
+
mpath.write_text("not-json")
|
| 118 |
+
monkeypatch.setattr(_cm, "MANIFEST_PATH", mpath)
|
| 119 |
+
assert load_manifest_skills() == set()
|
| 120 |
+
|
| 121 |
+
def test_empty_load_list(self, tmp_path, monkeypatch):
|
| 122 |
+
mpath = tmp_path / "manifest.json"
|
| 123 |
+
mpath.write_text(json.dumps({"load": []}))
|
| 124 |
+
monkeypatch.setattr(_cm, "MANIFEST_PATH", mpath)
|
| 125 |
+
assert load_manifest_skills() == set()
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# ---------------------------------------------------------------------------
|
| 129 |
+
# append_intent_log
|
| 130 |
+
# ---------------------------------------------------------------------------
|
| 131 |
+
|
| 132 |
+
class TestAppendIntentLog:
|
| 133 |
+
def test_creates_file_and_appends(self, tmp_path, monkeypatch):
|
| 134 |
+
log = tmp_path / "intent.jsonl"
|
| 135 |
+
monkeypatch.setattr(_cm, "CLAUDE_DIR", tmp_path)
|
| 136 |
+
monkeypatch.setattr(_cm, "INTENT_LOG", log)
|
| 137 |
+
entry = {"date": TODAY, "signals": ["react"]}
|
| 138 |
+
append_intent_log(entry)
|
| 139 |
+
lines = [line for line in log.read_text().strip().split("\n") if line]
|
| 140 |
+
assert len(lines) == 1
|
| 141 |
+
assert json.loads(lines[0])["signals"] == ["react"]
|
| 142 |
+
|
| 143 |
+
def test_appends_multiple_entries(self, tmp_path, monkeypatch):
|
| 144 |
+
log = tmp_path / "intent.jsonl"
|
| 145 |
+
monkeypatch.setattr(_cm, "CLAUDE_DIR", tmp_path)
|
| 146 |
+
monkeypatch.setattr(_cm, "INTENT_LOG", log)
|
| 147 |
+
append_intent_log({"date": TODAY, "signals": ["react"]})
|
| 148 |
+
append_intent_log({"date": TODAY, "signals": ["docker"]})
|
| 149 |
+
lines = [line for line in log.read_text().strip().split("\n") if line]
|
| 150 |
+
assert len(lines) == 2
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# ---------------------------------------------------------------------------
|
| 154 |
+
# count_recent_unmatched
|
| 155 |
+
# ---------------------------------------------------------------------------
|
| 156 |
+
|
| 157 |
+
class TestCountRecentUnmatched:
|
| 158 |
+
def test_all_matched(self):
|
| 159 |
+
unmatched = count_recent_unmatched(["react", "docker"], {"react", "docker"})
|
| 160 |
+
assert unmatched == []
|
| 161 |
+
|
| 162 |
+
def test_none_matched(self):
|
| 163 |
+
unmatched = count_recent_unmatched(["react", "docker"], set())
|
| 164 |
+
assert set(unmatched) == {"react", "docker"}
|
| 165 |
+
|
| 166 |
+
def test_partial_match(self):
|
| 167 |
+
unmatched = count_recent_unmatched(["react", "docker"], {"react"})
|
| 168 |
+
assert unmatched == ["docker"]
|
| 169 |
+
|
| 170 |
+
def test_empty_signals(self):
|
| 171 |
+
assert count_recent_unmatched([], {"react"}) == []
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
# ---------------------------------------------------------------------------
|
| 175 |
+
# write_pending_skills
|
| 176 |
+
# ---------------------------------------------------------------------------
|
| 177 |
+
|
| 178 |
+
class TestWritePendingSkills:
|
| 179 |
+
def test_writes_pending_skills_file(self, tmp_path, monkeypatch):
|
| 180 |
+
monkeypatch.setattr(_cm, "PENDING_SKILLS", tmp_path / "pending.json")
|
| 181 |
+
monkeypatch.setattr(_cm, "graph_suggest", lambda unmatched: [])
|
| 182 |
+
write_pending_skills(["react", "docker"])
|
| 183 |
+
pending = json.loads((tmp_path / "pending.json").read_text())
|
| 184 |
+
assert pending["unmatched_signals"] == ["react", "docker"]
|
| 185 |
+
assert "suggestion" in pending
|
| 186 |
+
|
| 187 |
+
def test_suggestion_mentions_signals(self, tmp_path, monkeypatch):
|
| 188 |
+
monkeypatch.setattr(_cm, "PENDING_SKILLS", tmp_path / "pending.json")
|
| 189 |
+
monkeypatch.setattr(_cm, "graph_suggest", lambda unmatched: [])
|
| 190 |
+
write_pending_skills(["fastapi"])
|
| 191 |
+
pending = json.loads((tmp_path / "pending.json").read_text())
|
| 192 |
+
assert "fastapi" in pending["suggestion"]
|
| 193 |
+
|
| 194 |
+
def test_empty_unmatched(self, tmp_path, monkeypatch):
|
| 195 |
+
monkeypatch.setattr(_cm, "PENDING_SKILLS", tmp_path / "pending.json")
|
| 196 |
+
monkeypatch.setattr(_cm, "graph_suggest", lambda unmatched: [])
|
| 197 |
+
write_pending_skills([])
|
| 198 |
+
pending = json.loads((tmp_path / "pending.json").read_text())
|
| 199 |
+
assert pending["unmatched_signals"] == []
|
| 200 |
+
|
| 201 |
+
def test_graph_suggestions_list_present(self, tmp_path, monkeypatch):
|
| 202 |
+
monkeypatch.setattr(_cm, "PENDING_SKILLS", tmp_path / "pending.json")
|
| 203 |
+
monkeypatch.setattr(
|
| 204 |
+
_cm,
|
| 205 |
+
"graph_suggest",
|
| 206 |
+
lambda unmatched: [{"name": "fastapi-pro", "type": "skill"}],
|
| 207 |
+
)
|
| 208 |
+
write_pending_skills(["unknown-signal"])
|
| 209 |
+
pending = json.loads((tmp_path / "pending.json").read_text())
|
| 210 |
+
assert pending["graph_suggestions"] == [{"name": "fastapi-pro", "type": "skill"}]
|
| 211 |
+
|
| 212 |
+
def test_graph_suggest_filters_to_execution_bundle_types(self, tmp_path, monkeypatch):
|
| 213 |
+
graph_path = tmp_path / "skill-wiki" / "graphify-out" / "graph.json"
|
| 214 |
+
graph_path.parent.mkdir(parents=True)
|
| 215 |
+
graph_path.write_text("{}", encoding="utf-8")
|
| 216 |
+
monkeypatch.setattr(_cm, "CLAUDE_DIR", tmp_path)
|
| 217 |
+
calls = {}
|
| 218 |
+
|
| 219 |
+
class FakeGraph:
|
| 220 |
+
def number_of_nodes(self):
|
| 221 |
+
return 1
|
| 222 |
+
|
| 223 |
+
fake_graph_module = type(
|
| 224 |
+
"FakeGraphModule",
|
| 225 |
+
(),
|
| 226 |
+
{"load_graph": staticmethod(lambda _path=None: FakeGraph())},
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
def fake_recommend_by_tags(graph, tags, **kwargs):
|
| 230 |
+
calls["entity_types"] = kwargs.get("entity_types")
|
| 231 |
+
return [{"name": "fastapi-pro", "type": "skill"}]
|
| 232 |
+
|
| 233 |
+
fake_recommend_module = type(
|
| 234 |
+
"FakeRecommendModule",
|
| 235 |
+
(),
|
| 236 |
+
{"recommend_by_tags": staticmethod(fake_recommend_by_tags)},
|
| 237 |
+
)
|
| 238 |
+
monkeypatch.setitem(sys.modules, "ctx.core.graph.resolve_graph", fake_graph_module)
|
| 239 |
+
monkeypatch.setitem(
|
| 240 |
+
sys.modules,
|
| 241 |
+
"ctx.core.resolve.recommendations",
|
| 242 |
+
fake_recommend_module,
|
| 243 |
+
)
|
| 244 |
+
|
| 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
|
| 251 |
+
# ---------------------------------------------------------------------------
|
| 252 |
+
|
| 253 |
+
class TestLoadRecentUnmatchedCount:
|
| 254 |
+
def _write_log(self, path: Path, entries: list[dict]) -> None:
|
| 255 |
+
path.write_text("\n".join(json.dumps(e) for e in entries) + "\n")
|
| 256 |
+
|
| 257 |
+
def test_happy_path_counts_distinct(self, tmp_path, monkeypatch):
|
| 258 |
+
log = tmp_path / "intent.jsonl"
|
| 259 |
+
self._write_log(log, [
|
| 260 |
+
{"date": TODAY, "unmatched": ["react", "docker"]},
|
| 261 |
+
{"date": TODAY, "unmatched": ["react"]}, # react already counted
|
| 262 |
+
])
|
| 263 |
+
monkeypatch.setattr(_cm, "INTENT_LOG", log)
|
| 264 |
+
count = load_recent_unmatched_count()
|
| 265 |
+
assert count == 2 # react + docker distinct
|
| 266 |
+
|
| 267 |
+
def test_missing_file_returns_0(self, tmp_path, monkeypatch):
|
| 268 |
+
monkeypatch.setattr(_cm, "INTENT_LOG", tmp_path / "nope.jsonl")
|
| 269 |
+
assert load_recent_unmatched_count() == 0
|
| 270 |
+
|
| 271 |
+
def test_skips_bad_lines(self, tmp_path, monkeypatch):
|
| 272 |
+
log = tmp_path / "intent.jsonl"
|
| 273 |
+
log.write_text(f'not-json\n{json.dumps({"date": TODAY, "unmatched": ["react"]})}\n')
|
| 274 |
+
monkeypatch.setattr(_cm, "INTENT_LOG", log)
|
| 275 |
+
assert load_recent_unmatched_count() == 1
|
| 276 |
+
|
| 277 |
+
def test_other_dates_not_counted(self, tmp_path, monkeypatch):
|
| 278 |
+
log = tmp_path / "intent.jsonl"
|
| 279 |
+
self._write_log(log, [{"date": "2000-01-01", "unmatched": ["react"]}])
|
| 280 |
+
monkeypatch.setattr(_cm, "INTENT_LOG", log)
|
| 281 |
+
assert load_recent_unmatched_count() == 0
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
# ---------------------------------------------------------------------------
|
| 285 |
+
# _parse_stdin_payload
|
| 286 |
+
# ---------------------------------------------------------------------------
|
| 287 |
+
|
| 288 |
+
class TestParseStdinPayload:
|
| 289 |
+
def test_valid_payload(self, monkeypatch):
|
| 290 |
+
payload = json.dumps({"tool_name": "Read", "tool_input": {"file_path": "foo.py"}})
|
| 291 |
+
monkeypatch.setattr(sys, "stdin", io.StringIO(payload))
|
| 292 |
+
tool_name, tool_input = _parse_stdin_payload()
|
| 293 |
+
assert tool_name == "Read"
|
| 294 |
+
assert tool_input == {"file_path": "foo.py"}
|
| 295 |
+
|
| 296 |
+
def test_empty_stdin(self, monkeypatch):
|
| 297 |
+
monkeypatch.setattr(sys, "stdin", io.StringIO(""))
|
| 298 |
+
tool_name, tool_input = _parse_stdin_payload()
|
| 299 |
+
assert tool_name == "unknown"
|
| 300 |
+
assert tool_input == {}
|
| 301 |
+
|
| 302 |
+
def test_non_dict_json(self, monkeypatch):
|
| 303 |
+
monkeypatch.setattr(sys, "stdin", io.StringIO(json.dumps([1, 2, 3])))
|
| 304 |
+
tool_name, tool_input = _parse_stdin_payload()
|
| 305 |
+
assert tool_name == "unknown"
|
| 306 |
+
|
| 307 |
+
def test_bad_json(self, monkeypatch):
|
| 308 |
+
monkeypatch.setattr(sys, "stdin", io.StringIO("not-json"))
|
| 309 |
+
tool_name, tool_input = _parse_stdin_payload()
|
| 310 |
+
assert tool_name == "unknown"
|
| 311 |
+
assert tool_input == {}
|
| 312 |
+
|
| 313 |
+
def test_missing_tool_input_defaults_to_empty(self, monkeypatch):
|
| 314 |
+
payload = json.dumps({"tool_name": "Bash"})
|
| 315 |
+
monkeypatch.setattr(sys, "stdin", io.StringIO(payload))
|
| 316 |
+
_, tool_input = _parse_stdin_payload()
|
| 317 |
+
assert tool_input == {}
|
| 318 |
+
|
| 319 |
+
def test_non_dict_tool_input_defaults_to_empty(self, monkeypatch):
|
| 320 |
+
payload = json.dumps({"tool_name": "Bash", "tool_input": "not-a-dict"})
|
| 321 |
+
monkeypatch.setattr(sys, "stdin", io.StringIO(payload))
|
| 322 |
+
_, tool_input = _parse_stdin_payload()
|
| 323 |
+
assert tool_input == {}
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
# ---------------------------------------------------------------------------
|
| 327 |
+
# main()
|
| 328 |
+
# ---------------------------------------------------------------------------
|
| 329 |
+
|
| 330 |
+
class TestMain:
|
| 331 |
+
def test_no_signals_exits_0(self, tmp_path, monkeypatch):
|
| 332 |
+
"""When tool input produces no signals, main exits 0."""
|
| 333 |
+
monkeypatch.setattr(_cm, "CLAUDE_DIR", tmp_path)
|
| 334 |
+
monkeypatch.setattr(_cm, "INTENT_LOG", tmp_path / "intent.jsonl")
|
| 335 |
+
monkeypatch.setattr(_cm, "MANIFEST_PATH", tmp_path / "manifest.json")
|
| 336 |
+
monkeypatch.setattr(_cm, "PENDING_SKILLS", tmp_path / "pending.json")
|
| 337 |
+
monkeypatch.setattr(sys, "argv", ["context_monitor.py", "--tool", "Read", "--input", "{}"])
|
| 338 |
+
with pytest.raises(SystemExit) as exc:
|
| 339 |
+
_cm.main()
|
| 340 |
+
assert exc.value.code == 0
|
| 341 |
+
|
| 342 |
+
def test_signals_appended_to_log(self, tmp_path, monkeypatch):
|
| 343 |
+
"""Signals from --input are written to the intent log."""
|
| 344 |
+
monkeypatch.setattr(_cm, "CLAUDE_DIR", tmp_path)
|
| 345 |
+
log = tmp_path / "intent.jsonl"
|
| 346 |
+
monkeypatch.setattr(_cm, "INTENT_LOG", log)
|
| 347 |
+
monkeypatch.setattr(_cm, "MANIFEST_PATH", tmp_path / "manifest.json")
|
| 348 |
+
monkeypatch.setattr(_cm, "PENDING_SKILLS", tmp_path / "pending.json")
|
| 349 |
+
monkeypatch.setattr(_cm, "_THRESHOLD", 999) # prevent pending write
|
| 350 |
+
tool_input = json.dumps({"file_path": "Dockerfile"})
|
| 351 |
+
monkeypatch.setattr(sys, "argv", ["context_monitor.py", "--tool", "Read", "--input", tool_input])
|
| 352 |
+
_cm.main()
|
| 353 |
+
lines = [line for line in log.read_text().strip().split("\n") if line]
|
| 354 |
+
assert len(lines) == 1
|
| 355 |
+
entry = json.loads(lines[0])
|
| 356 |
+
assert "docker" in entry["signals"]
|
| 357 |
+
|
| 358 |
+
def test_from_stdin_flag(self, tmp_path, monkeypatch):
|
| 359 |
+
"""--from-stdin reads tool payload from stdin."""
|
| 360 |
+
monkeypatch.setattr(_cm, "CLAUDE_DIR", tmp_path)
|
| 361 |
+
log = tmp_path / "intent.jsonl"
|
| 362 |
+
monkeypatch.setattr(_cm, "INTENT_LOG", log)
|
| 363 |
+
monkeypatch.setattr(_cm, "MANIFEST_PATH", tmp_path / "manifest.json")
|
| 364 |
+
monkeypatch.setattr(_cm, "PENDING_SKILLS", tmp_path / "pending.json")
|
| 365 |
+
monkeypatch.setattr(_cm, "_THRESHOLD", 999)
|
| 366 |
+
payload = json.dumps({"tool_name": "Read", "tool_input": {"file_path": "Dockerfile"}})
|
| 367 |
+
monkeypatch.setattr(sys, "stdin", io.StringIO(payload))
|
| 368 |
+
monkeypatch.setattr(sys, "argv", ["context_monitor.py", "--from-stdin"])
|
| 369 |
+
_cm.main()
|
| 370 |
+
lines = [line for line in log.read_text().strip().split("\n") if line]
|
| 371 |
+
assert len(lines) == 1
|
| 372 |
+
entry = json.loads(lines[0])
|
| 373 |
+
assert "docker" in entry["signals"]
|
| 374 |
+
|
| 375 |
+
def test_bad_json_input_falls_back_to_raw(self, tmp_path, monkeypatch):
|
| 376 |
+
"""Malformed --input falls back to {'raw': value} and may produce no signals."""
|
| 377 |
+
monkeypatch.setattr(_cm, "CLAUDE_DIR", tmp_path)
|
| 378 |
+
log = tmp_path / "intent.jsonl"
|
| 379 |
+
monkeypatch.setattr(_cm, "INTENT_LOG", log)
|
| 380 |
+
monkeypatch.setattr(_cm, "MANIFEST_PATH", tmp_path / "manifest.json")
|
| 381 |
+
monkeypatch.setattr(_cm, "PENDING_SKILLS", tmp_path / "pending.json")
|
| 382 |
+
monkeypatch.setattr(sys, "argv", ["context_monitor.py", "--tool", "Read", "--input", "not-json"])
|
| 383 |
+
# Should not crash
|
| 384 |
+
try:
|
| 385 |
+
_cm.main()
|
| 386 |
+
except SystemExit as e:
|
| 387 |
+
assert e.code == 0 # exits 0 when no signals
|
| 388 |
+
|
| 389 |
+
def test_threshold_triggers_pending_write(self, tmp_path, monkeypatch):
|
| 390 |
+
"""When unmatched count >= threshold, pending-skills.json is written."""
|
| 391 |
+
monkeypatch.setattr(_cm, "CLAUDE_DIR", tmp_path)
|
| 392 |
+
log = tmp_path / "intent.jsonl"
|
| 393 |
+
pending = tmp_path / "pending.json"
|
| 394 |
+
monkeypatch.setattr(_cm, "INTENT_LOG", log)
|
| 395 |
+
monkeypatch.setattr(_cm, "MANIFEST_PATH", tmp_path / "manifest.json")
|
| 396 |
+
monkeypatch.setattr(_cm, "PENDING_SKILLS", pending)
|
| 397 |
+
monkeypatch.setattr(_cm, "_THRESHOLD", 1) # trigger on 1 unmatched
|
| 398 |
+
tool_input = json.dumps({"file_path": "Dockerfile"})
|
| 399 |
+
monkeypatch.setattr(sys, "argv", ["context_monitor.py", "--tool", "Read", "--input", tool_input])
|
| 400 |
+
_cm.main()
|
| 401 |
+
assert pending.exists()
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
# ---------------------------------------------------------------------------
|
| 405 |
+
# Cumulative-threshold regression (code-reviewer finding BLOCKER)
|
| 406 |
+
# ---------------------------------------------------------------------------
|
| 407 |
+
#
|
| 408 |
+
# Prior impl used ``len(unmatched) >= THRESHOLD`` where ``unmatched`` is the
|
| 409 |
+
# per-invocation list. A single tool call almost never surfaces 3 unmatched
|
| 410 |
+
# signals alone, so the default threshold=3 meant pending-skills.json was
|
| 411 |
+
# essentially never written — silently killing the suggestion arm of the
|
| 412 |
+
# alive loop. The fix walks the intent log and checks the cumulative
|
| 413 |
+
# (per-day, across all invocations) unmatched count against the threshold.
|
| 414 |
+
|
| 415 |
+
class TestCumulativeThreshold:
|
| 416 |
+
"""The threshold must fire on cumulative unmatched across today's log,
|
| 417 |
+
not just on a single invocation's count.
|
| 418 |
+
"""
|
| 419 |
+
|
| 420 |
+
def _setup_paths(self, tmp_path, monkeypatch):
|
| 421 |
+
log = tmp_path / "intent.jsonl"
|
| 422 |
+
pending = tmp_path / "pending.json"
|
| 423 |
+
monkeypatch.setattr(_cm, "CLAUDE_DIR", tmp_path)
|
| 424 |
+
monkeypatch.setattr(_cm, "INTENT_LOG", log)
|
| 425 |
+
monkeypatch.setattr(_cm, "MANIFEST_PATH", tmp_path / "manifest.json")
|
| 426 |
+
monkeypatch.setattr(_cm, "PENDING_SKILLS", pending)
|
| 427 |
+
return log, pending
|
| 428 |
+
|
| 429 |
+
def _run_main(self, monkeypatch, tool_name: str, tool_input: dict):
|
| 430 |
+
monkeypatch.setattr(
|
| 431 |
+
sys, "argv",
|
| 432 |
+
["context_monitor.py", "--tool", tool_name, "--input", json.dumps(tool_input)],
|
| 433 |
+
)
|
| 434 |
+
_cm.main()
|
| 435 |
+
|
| 436 |
+
def test_fires_on_cumulative_across_three_invocations(
|
| 437 |
+
self, tmp_path, monkeypatch,
|
| 438 |
+
):
|
| 439 |
+
"""Three invocations each surfacing ONE unmatched signal should
|
| 440 |
+
trigger pending-skills write when THRESHOLD=3.
|
| 441 |
+
|
| 442 |
+
This is the case the old len(unmatched)>=THRESHOLD check missed.
|
| 443 |
+
The user types a react file, then opens a Dockerfile, then edits
|
| 444 |
+
terraform — three separate tool calls, three different unmatched
|
| 445 |
+
signals, cumulatively at threshold.
|
| 446 |
+
"""
|
| 447 |
+
_, pending = self._setup_paths(tmp_path, monkeypatch)
|
| 448 |
+
monkeypatch.setattr(_cm, "_THRESHOLD", 3)
|
| 449 |
+
|
| 450 |
+
# Three invocations, one unique unmatched signal each.
|
| 451 |
+
self._run_main(monkeypatch, "Read", {"file_path": "App.tsx"}) # react
|
| 452 |
+
assert not pending.exists(), "fired after 1 cumulative unmatched"
|
| 453 |
+
|
| 454 |
+
self._run_main(monkeypatch, "Read", {"file_path": "Dockerfile"}) # docker
|
| 455 |
+
assert not pending.exists(), "fired after 2 cumulative unmatched"
|
| 456 |
+
|
| 457 |
+
self._run_main(monkeypatch, "Read", {"file_path": "main.tf"}) # terraform
|
| 458 |
+
assert pending.exists(), (
|
| 459 |
+
"did NOT fire after 3 cumulative unmatched — "
|
| 460 |
+
"the per-invocation threshold bug regressed"
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
def test_does_not_fire_below_cumulative_threshold(
|
| 464 |
+
self, tmp_path, monkeypatch,
|
| 465 |
+
):
|
| 466 |
+
"""Below-threshold cumulative count must NOT trigger.
|
| 467 |
+
|
| 468 |
+
Otherwise every first-keystroke would spam pending-skills.json.
|
| 469 |
+
"""
|
| 470 |
+
_, pending = self._setup_paths(tmp_path, monkeypatch)
|
| 471 |
+
monkeypatch.setattr(_cm, "_THRESHOLD", 3)
|
| 472 |
+
|
| 473 |
+
self._run_main(monkeypatch, "Read", {"file_path": "App.tsx"})
|
| 474 |
+
self._run_main(monkeypatch, "Read", {"file_path": "Dockerfile"})
|
| 475 |
+
# Only 2 unique signals accumulated; THRESHOLD=3 => no write.
|
| 476 |
+
assert not pending.exists()
|
| 477 |
+
|
| 478 |
+
def test_fires_when_single_invocation_surfaces_multiple(
|
| 479 |
+
self, tmp_path, monkeypatch,
|
| 480 |
+
):
|
| 481 |
+
"""Backward-compat: a single invocation carrying threshold-worth of
|
| 482 |
+
new signals on its own still fires (the old happy path)."""
|
| 483 |
+
_, pending = self._setup_paths(tmp_path, monkeypatch)
|
| 484 |
+
monkeypatch.setattr(_cm, "_THRESHOLD", 2)
|
| 485 |
+
|
| 486 |
+
# A Bash pip install surfaces multiple signals in one invocation.
|
| 487 |
+
self._run_main(
|
| 488 |
+
monkeypatch, "Bash",
|
| 489 |
+
{"command": "pip install fastapi django"},
|
| 490 |
+
)
|
| 491 |
+
assert pending.exists()
|
| 492 |
+
|
| 493 |
+
def test_pending_contains_cumulative_union(
|
| 494 |
+
self, tmp_path, monkeypatch,
|
| 495 |
+
):
|
| 496 |
+
"""When the threshold fires, pending-skills.json lists ALL of today's
|
| 497 |
+
unmatched signals, not just the current invocation's."""
|
| 498 |
+
_, pending = self._setup_paths(tmp_path, monkeypatch)
|
| 499 |
+
monkeypatch.setattr(_cm, "_THRESHOLD", 2)
|
| 500 |
+
|
| 501 |
+
self._run_main(monkeypatch, "Read", {"file_path": "App.tsx"})
|
| 502 |
+
self._run_main(monkeypatch, "Read", {"file_path": "Dockerfile"})
|
| 503 |
+
|
| 504 |
+
assert pending.exists()
|
| 505 |
+
payload = json.loads(pending.read_text())
|
| 506 |
+
unmatched = set(payload.get("unmatched_signals", []))
|
| 507 |
+
# Both react (from App.tsx) and docker (from Dockerfile) must be
|
| 508 |
+
# present — a fix that only reports the current invocation's
|
| 509 |
+
# signals would miss react.
|
| 510 |
+
assert {"react", "docker"}.issubset(unmatched), (
|
| 511 |
+
f"pending does not include cumulative signals: {unmatched}"
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
def test_duplicate_signals_across_invocations_count_once(
|
| 515 |
+
self, tmp_path, monkeypatch,
|
| 516 |
+
):
|
| 517 |
+
"""Unique-set cumulative count — repeated signals don't inflate.
|
| 518 |
+
|
| 519 |
+
The same file edited twice should not double-count toward the
|
| 520 |
+
threshold; otherwise a tight edit-save-edit-save loop would
|
| 521 |
+
auto-trigger suggestions on a single concept.
|
| 522 |
+
"""
|
| 523 |
+
_, pending = self._setup_paths(tmp_path, monkeypatch)
|
| 524 |
+
monkeypatch.setattr(_cm, "_THRESHOLD", 2)
|
| 525 |
+
|
| 526 |
+
self._run_main(monkeypatch, "Read", {"file_path": "App.tsx"}) # react
|
| 527 |
+
self._run_main(monkeypatch, "Read", {"file_path": "index.tsx"}) # react (dup)
|
| 528 |
+
# Only 1 unique unmatched concept; THRESHOLD=2 => no write.
|
| 529 |
+
assert not pending.exists()
|
src/tests/test_ctx_init.py
CHANGED
|
@@ -1,1348 +1,1368 @@
|
|
| 1 |
-
"""Tests for ctx_init — bootstrap ~/.claude/ scaffolding."""
|
| 2 |
-
|
| 3 |
-
from __future__ import annotations
|
| 4 |
-
|
| 5 |
-
import builtins
|
| 6 |
-
import hashlib
|
| 7 |
-
import io
|
| 8 |
-
import json
|
| 9 |
-
import sqlite3
|
| 10 |
-
import sys
|
| 11 |
-
import tarfile
|
| 12 |
-
import zlib
|
| 13 |
-
from pathlib import Path
|
| 14 |
-
from types import SimpleNamespace
|
| 15 |
-
|
| 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:
|
| 22 |
-
conn = sqlite3.connect(path)
|
| 23 |
-
try:
|
| 24 |
-
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
|
| 25 |
-
conn.execute(
|
| 26 |
-
"CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
|
| 27 |
-
"description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
|
| 28 |
-
)
|
| 29 |
-
conn.execute(
|
| 30 |
-
"CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
|
| 31 |
-
"PRIMARY KEY(slug,type,node_id))"
|
| 32 |
-
)
|
| 33 |
-
conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
|
| 34 |
-
conn.executemany(
|
| 35 |
-
"INSERT INTO meta VALUES(?,?)",
|
| 36 |
-
[
|
| 37 |
-
("export_id", json.dumps(export_id)),
|
| 38 |
-
("nodes_count", "1"),
|
| 39 |
-
("edges_count", "0"),
|
| 40 |
-
("max_degree", "1"),
|
| 41 |
-
("top_k", "40"),
|
| 42 |
-
],
|
| 43 |
-
)
|
| 44 |
-
conn.execute(
|
| 45 |
-
"INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
|
| 46 |
-
("skill:current", "current", "skill", "[]", "", None, None, 0),
|
| 47 |
-
)
|
| 48 |
-
conn.execute("INSERT INTO slug_index VALUES(?,?,?)", ("current", "skill", "skill:current"))
|
| 49 |
-
conn.execute("INSERT INTO neighbors VALUES(?,?)", ("skill:current", zlib.compress(b"[]")))
|
| 50 |
-
conn.commit()
|
| 51 |
-
finally:
|
| 52 |
-
conn.close()
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
def _artifact_sha256_or_lfs_oid(path: Path, *, normalize_text: bool = False) -> str:
|
| 56 |
-
data = path.read_bytes()
|
| 57 |
-
if data.startswith(b"version https://git-lfs.github.com/spec/v1\n"):
|
| 58 |
-
for line in data.decode("utf-8").splitlines():
|
| 59 |
-
if line.startswith("oid sha256:"):
|
| 60 |
-
return line.removeprefix("oid sha256:")
|
| 61 |
-
if normalize_text:
|
| 62 |
-
data = data.replace(b"\r\n", b"\n")
|
| 63 |
-
return hashlib.sha256(data).hexdigest()
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
def test_ensure_directories_creates_standard_tree(tmp_path: Path) -> None:
|
| 67 |
-
created = ci.ensure_directories(tmp_path)
|
| 68 |
-
# First call should create every standard subdir.
|
| 69 |
-
assert len(created) == len(ci._STANDARD_SUBDIRS)
|
| 70 |
-
for sub in ci._STANDARD_SUBDIRS:
|
| 71 |
-
assert (tmp_path / sub).is_dir(), f"missing {sub}"
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
def test_ensure_directories_is_idempotent(tmp_path: Path) -> None:
|
| 75 |
-
first = ci.ensure_directories(tmp_path)
|
| 76 |
-
assert len(first) > 0
|
| 77 |
-
second = ci.ensure_directories(tmp_path)
|
| 78 |
-
assert second == [], "second call should not recreate anything"
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
def test_seed_user_config_writes_once(tmp_path: Path) -> None:
|
| 82 |
-
tmp_path.mkdir(exist_ok=True)
|
| 83 |
-
first = ci.seed_user_config(tmp_path)
|
| 84 |
-
assert first is not None
|
| 85 |
-
assert first.exists()
|
| 86 |
-
body = first.read_text(encoding="utf-8")
|
| 87 |
-
assert "skill-system-config.json" in body
|
| 88 |
-
|
| 89 |
-
# Second call returns None (file already exists, force=False).
|
| 90 |
-
second = ci.seed_user_config(tmp_path)
|
| 91 |
-
assert second is None
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
def test_seed_user_config_respects_force(tmp_path: Path) -> None:
|
| 95 |
-
target = tmp_path / "skill-system-config.json"
|
| 96 |
-
target.write_text("user-custom-content", encoding="utf-8")
|
| 97 |
-
# Without force → don't touch.
|
| 98 |
-
assert ci.seed_user_config(tmp_path, force=False) is None
|
| 99 |
-
assert target.read_text() == "user-custom-content"
|
| 100 |
-
# With force → overwrite.
|
| 101 |
-
result = ci.seed_user_config(tmp_path, force=True)
|
| 102 |
-
assert result == target
|
| 103 |
-
assert "skill-system-config.json" in target.read_text()
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
def test_main_creates_everything_in_dry_mode(tmp_path: Path, monkeypatch,
|
| 107 |
-
capsys) -> None:
|
| 108 |
-
"""End-to-end: ``ctx-init`` (no flags) creates dirs + config + toolboxes
|
| 109 |
-
without touching hooks or graph."""
|
| 110 |
-
monkeypatch.setattr(ci, "_claude_dir", lambda: tmp_path)
|
| 111 |
-
|
| 112 |
-
# Short-circuit subprocess.run to avoid spawning a real toolbox/graph CLI
|
| 113 |
-
# in tests. Verify that main() doesn't call install_hooks or build_graph
|
| 114 |
-
# when those flags are absent.
|
| 115 |
-
calls: list[list[str]] = []
|
| 116 |
-
|
| 117 |
-
class _FakeResult:
|
| 118 |
-
returncode = 0
|
| 119 |
-
stdout = ""
|
| 120 |
-
stderr = ""
|
| 121 |
-
|
| 122 |
-
def fake_run(cmd, **kwargs):
|
| 123 |
-
calls.append(list(cmd))
|
| 124 |
-
return _FakeResult()
|
| 125 |
-
|
| 126 |
-
monkeypatch.setattr(ci.subprocess, "run", fake_run)
|
| 127 |
-
|
| 128 |
-
rc = ci.main([])
|
| 129 |
-
assert rc == 0
|
| 130 |
-
# toolbox init should have been invoked
|
| 131 |
-
toolbox_calls = [c for c in calls if "toolbox" in " ".join(c)]
|
| 132 |
-
assert toolbox_calls, "toolbox init not invoked"
|
| 133 |
-
# inject_hooks / wiki_graphify must NOT be invoked without flags
|
| 134 |
-
for c in calls:
|
| 135 |
-
assert "inject_hooks" not in " ".join(c)
|
| 136 |
-
assert "wiki_graphify" not in " ".join(c)
|
| 137 |
-
|
| 138 |
-
out = capsys.readouterr().out
|
| 139 |
-
assert "[ok]" in out
|
| 140 |
-
assert "[skip] hook injection" in out
|
| 141 |
-
assert "[skip] graph install" in out
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
def test_main_treats_existing_toolboxes_as_idempotent_skip(
|
| 145 |
-
tmp_path: Path,
|
| 146 |
-
monkeypatch,
|
| 147 |
-
capsys,
|
| 148 |
-
) -> None:
|
| 149 |
-
monkeypatch.setattr(ci, "_claude_dir", lambda: tmp_path)
|
| 150 |
-
|
| 151 |
-
class _FakeResult:
|
| 152 |
-
returncode = 1
|
| 153 |
-
stdout = ""
|
| 154 |
-
stderr = (
|
| 155 |
-
"Global config already has 5 toolbox(es). "
|
| 156 |
-
"Use --force to overwrite."
|
| 157 |
-
)
|
| 158 |
-
|
| 159 |
-
monkeypatch.setattr(ci.subprocess, "run", lambda *_args, **_kwargs: _FakeResult())
|
| 160 |
-
|
| 161 |
-
rc = ci.main(["--model-mode", "skip"])
|
| 162 |
-
captured = capsys.readouterr()
|
| 163 |
-
|
| 164 |
-
assert rc == 0
|
| 165 |
-
assert "starter toolboxes already present" in captured.out
|
| 166 |
-
assert "toolbox init returned" not in captured.err
|
| 167 |
-
assert "Global config already has" not in captured.err
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
def test_main_auto_wizard_in_terminal_configures_custom_model(
|
| 171 |
-
tmp_path: Path,
|
| 172 |
-
monkeypatch,
|
| 173 |
-
) -> None:
|
| 174 |
-
monkeypatch.setattr(ci, "_claude_dir", lambda: tmp_path)
|
| 175 |
-
monkeypatch.setattr(ci, "_stdio_is_interactive", lambda: True)
|
| 176 |
-
monkeypatch.setattr(
|
| 177 |
-
ci,
|
| 178 |
-
"recommend_harnesses",
|
| 179 |
-
lambda goal, top_k=5, model_provider=None, model=None: [],
|
| 180 |
-
)
|
| 181 |
-
|
| 182 |
-
answers = iter([
|
| 183 |
-
"y", # hooks
|
| 184 |
-
"enriched", # knowledge mode
|
| 185 |
-
"n", # graph
|
| 186 |
-
"custom", # model mode
|
| 187 |
-
"openai/gpt-5.5", # model
|
| 188 |
-
"", # provider default: openai
|
| 189 |
-
"", # api key env default: OPENAI_API_KEY
|
| 190 |
-
"", # base URL
|
| 191 |
-
"build CAD artifacts",
|
| 192 |
-
"windows python", # runtime / OS
|
| 193 |
-
"supervised", # autonomy
|
| 194 |
-
"filesystem shell", # allowed tools
|
| 195 |
-
"pytest ruff", # verification
|
| 196 |
-
"private repo", # privacy / network
|
| 197 |
-
"mcp", # attach mode
|
| 198 |
-
"n", # validate model
|
| 199 |
-
])
|
| 200 |
-
monkeypatch.setattr(builtins, "input", lambda _prompt: next(answers))
|
| 201 |
-
calls: list[list[str]] = []
|
| 202 |
-
|
| 203 |
-
class _FakeResult:
|
| 204 |
-
returncode = 0
|
| 205 |
-
stdout = ""
|
| 206 |
-
stderr = ""
|
| 207 |
-
|
| 208 |
-
def _fake_run(cmd: list[str], **_kwargs: object) -> _FakeResult:
|
| 209 |
-
calls.append(list(cmd))
|
| 210 |
-
return _FakeResult()
|
| 211 |
-
|
| 212 |
-
monkeypatch.setattr(ci.subprocess, "run", _fake_run)
|
| 213 |
-
|
| 214 |
-
rc = ci.main([])
|
| 215 |
-
|
| 216 |
-
assert rc == 0
|
| 217 |
-
assert any("ctx.adapters.claude_code.inject_hooks" in c for c in calls)
|
| 218 |
-
assert not any("ctx.core.wiki.wiki_graphify" in c for c in calls)
|
| 219 |
-
profile = json.loads((tmp_path / "ctx-model-profile.json").read_text())
|
| 220 |
-
assert profile["mode"] == "custom"
|
| 221 |
-
assert profile["provider"] == "openai"
|
| 222 |
-
assert profile["model"] == "openai/gpt-5.5"
|
| 223 |
-
assert profile["api_key_env"] == "OPENAI_API_KEY"
|
| 224 |
-
assert profile["goal"] == "build CAD artifacts"
|
| 225 |
-
assert profile["knowledge_mode"] == "enriched"
|
| 226 |
-
assert profile["harness_requirements"] == {
|
| 227 |
-
"runtime": "windows python",
|
| 228 |
-
"autonomy": "supervised",
|
| 229 |
-
"tools": "filesystem shell",
|
| 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"
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
def test_wizard_flag_prompts_without_tty(tmp_path: Path, monkeypatch) -> None:
|
| 239 |
-
monkeypatch.setattr(ci, "_claude_dir", lambda: tmp_path)
|
| 240 |
-
monkeypatch.setattr(ci, "_stdio_is_interactive", lambda: False)
|
| 241 |
-
monkeypatch.setattr(ci, "seed_toolboxes", lambda force=False: 0)
|
| 242 |
-
monkeypatch.setattr(
|
| 243 |
-
ci,
|
| 244 |
-
"recommend_harnesses",
|
| 245 |
-
lambda goal, top_k=5, model_provider=None, model=None: [],
|
| 246 |
-
)
|
| 247 |
-
|
| 248 |
-
answers = iter([
|
| 249 |
-
"n", # hooks
|
| 250 |
-
"local", # knowledge mode
|
| 251 |
-
"claude-code", # model mode
|
| 252 |
-
"maintain FastAPI services",
|
| 253 |
-
])
|
| 254 |
-
monkeypatch.setattr(builtins, "input", lambda _prompt: next(answers))
|
| 255 |
-
|
| 256 |
-
rc = ci.main(["--wizard"])
|
| 257 |
-
|
| 258 |
-
assert rc == 0
|
| 259 |
-
profile = json.loads((tmp_path / "ctx-model-profile.json").read_text())
|
| 260 |
-
assert profile["mode"] == "claude-code"
|
| 261 |
-
assert profile["goal"] == "maintain FastAPI services"
|
| 262 |
-
assert profile["knowledge_mode"] == "local"
|
| 263 |
-
user_config = json.loads((tmp_path / "skill-system-config.json").read_text())
|
| 264 |
-
assert user_config["knowledge"]["mode"] == "local"
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
def test_explicit_args_do_not_auto_wizard_in_terminal(
|
| 268 |
-
tmp_path: Path,
|
| 269 |
-
monkeypatch,
|
| 270 |
-
) -> None:
|
| 271 |
-
monkeypatch.setattr(ci, "_claude_dir", lambda: tmp_path)
|
| 272 |
-
monkeypatch.setattr(ci, "_stdio_is_interactive", lambda: True)
|
| 273 |
-
monkeypatch.setattr(ci, "seed_toolboxes", lambda force=False: 0)
|
| 274 |
-
monkeypatch.setattr(
|
| 275 |
-
builtins,
|
| 276 |
-
"input",
|
| 277 |
-
lambda _prompt: (_ for _ in ()).throw(AssertionError("unexpected prompt")),
|
| 278 |
-
)
|
| 279 |
-
|
| 280 |
-
assert ci.main(["--model-mode", "skip", "--knowledge-mode", "local"]) == 0
|
| 281 |
-
user_config = json.loads((tmp_path / "skill-system-config.json").read_text())
|
| 282 |
-
assert user_config["knowledge"]["mode"] == "local"
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
def test_main_with_hooks_flag_invokes_inject(tmp_path: Path, monkeypatch) -> None:
|
| 286 |
-
monkeypatch.setattr(ci, "_claude_dir", lambda: tmp_path)
|
| 287 |
-
calls: list[list[str]] = []
|
| 288 |
-
|
| 289 |
-
class _FakeResult:
|
| 290 |
-
returncode = 0
|
| 291 |
-
stdout = ""
|
| 292 |
-
stderr = ""
|
| 293 |
-
|
| 294 |
-
def _fake_run(cmd: list[str], **_kwargs: object) -> _FakeResult:
|
| 295 |
-
calls.append(list(cmd))
|
| 296 |
-
return _FakeResult()
|
| 297 |
-
|
| 298 |
-
monkeypatch.setattr(ci.subprocess, "run", _fake_run)
|
| 299 |
-
rc = ci.main(["--hooks"])
|
| 300 |
-
assert rc == 0
|
| 301 |
-
assert any("ctx.adapters.claude_code.inject_hooks" in c for c in calls)
|
| 302 |
-
assert not any(c == "inject_hooks" for call in calls for c in call)
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
def _write_graph_archive(tmp_path: Path) -> Path:
|
| 306 |
-
source = tmp_path / "archive-source"
|
| 307 |
-
graph_out = source / "graphify-out"
|
| 308 |
-
graph_out.mkdir(parents=True)
|
| 309 |
-
(graph_out / "graph.json").write_text(
|
| 310 |
-
json.dumps({"graph": {"export_id": "test-export"}, "nodes": [], "links": []}),
|
| 311 |
-
encoding="utf-8",
|
| 312 |
-
)
|
| 313 |
-
(graph_out / "graph-delta.json").write_text(
|
| 314 |
-
json.dumps({"export_id": "test-export", "nodes": [], "edges": []}),
|
| 315 |
-
encoding="utf-8",
|
| 316 |
-
)
|
| 317 |
-
(graph_out / "communities.json").write_text(
|
| 318 |
-
json.dumps({"export_id": "test-export", "total_communities": 0}),
|
| 319 |
-
encoding="utf-8",
|
| 320 |
-
)
|
| 321 |
-
(graph_out / "graph-report.md").write_text(
|
| 322 |
-
"# Graph Report\n\n> Export ID: test-export\n",
|
| 323 |
-
encoding="utf-8",
|
| 324 |
-
)
|
| 325 |
-
(graph_out / "graph-export-manifest.json").write_text(
|
| 326 |
-
json.dumps({
|
| 327 |
-
"version": 1,
|
| 328 |
-
"export_id": "test-export",
|
| 329 |
-
"artifacts": {
|
| 330 |
-
"graph": "graph.json",
|
| 331 |
-
"delta": "graph-delta.json",
|
| 332 |
-
"communities": "communities.json",
|
| 333 |
-
"report": "graph-report.md",
|
| 334 |
-
},
|
| 335 |
-
}),
|
| 336 |
-
encoding="utf-8",
|
| 337 |
-
)
|
| 338 |
-
_write_dashboard_index(graph_out / "dashboard-neighborhoods.sqlite3")
|
| 339 |
-
external = source / "external-catalogs" / "skills-sh"
|
| 340 |
-
external.mkdir(parents=True)
|
| 341 |
-
(external / "catalog.json").write_text("{}", encoding="utf-8")
|
| 342 |
-
entities = source / "entities" / "skills"
|
| 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("*")):
|
| 349 |
-
if path.is_file():
|
| 350 |
-
tf.add(path, arcname=path.relative_to(source).as_posix())
|
| 351 |
-
return archive
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
def _tar_text(tf: tarfile.TarFile, name: str, text: str) -> None:
|
| 355 |
-
payload = text.encode("utf-8")
|
| 356 |
-
info = tarfile.TarInfo(name)
|
| 357 |
-
info.size = len(payload)
|
| 358 |
-
tf.addfile(info, io.BytesIO(payload))
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
def _tar_bytes(tf: tarfile.TarFile, name: str, payload: bytes) -> None:
|
| 362 |
-
info = tarfile.TarInfo(name)
|
| 363 |
-
info.size = len(payload)
|
| 364 |
-
tf.addfile(info, io.BytesIO(payload))
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
def test_download_graph_archive_verifies_sha256(
|
| 368 |
-
tmp_path: Path,
|
| 369 |
-
monkeypatch,
|
| 370 |
-
) -> None:
|
| 371 |
-
payload = b"graph archive bytes"
|
| 372 |
-
|
| 373 |
-
class _Response(io.BytesIO):
|
| 374 |
-
def __enter__(self) -> "_Response":
|
| 375 |
-
return self
|
| 376 |
-
|
| 377 |
-
def __exit__(self, *_args: object) -> None:
|
| 378 |
-
return None
|
| 379 |
-
|
| 380 |
-
monkeypatch.setattr(
|
| 381 |
-
ci.urllib.request,
|
| 382 |
-
"urlopen",
|
| 383 |
-
lambda _url, timeout=120: _Response(payload),
|
| 384 |
-
)
|
| 385 |
-
|
| 386 |
-
destination = tmp_path / "wiki-graph.tar.gz"
|
| 387 |
-
ci._download_graph_archive(
|
| 388 |
-
destination,
|
| 389 |
-
url="https://example.invalid/wiki-graph.tar.gz",
|
| 390 |
-
expected_sha256=hashlib.sha256(payload).hexdigest(),
|
| 391 |
-
)
|
| 392 |
-
assert destination.read_bytes() == payload
|
| 393 |
-
|
| 394 |
-
bad_destination = tmp_path / "bad-wiki-graph.tar.gz"
|
| 395 |
-
with pytest.raises(ValueError, match="checksum mismatch"):
|
| 396 |
-
ci._download_graph_archive(
|
| 397 |
-
bad_destination,
|
| 398 |
-
url="https://example.invalid/wiki-graph.tar.gz",
|
| 399 |
-
expected_sha256="0" * 64,
|
| 400 |
-
)
|
| 401 |
-
assert not bad_destination.exists()
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
def test_graph_download_checksums_match_shipped_artifacts() -> None:
|
| 405 |
-
root = Path(__file__).resolve().parent.parent.parent
|
| 406 |
-
for mode, archive_name in ci._GRAPH_ARCHIVE_NAMES.items():
|
| 407 |
-
path = root / "graph" / archive_name
|
| 408 |
-
assert ci._GRAPH_ARCHIVE_SHA256[mode] == _artifact_sha256_or_lfs_oid(path)
|
| 409 |
-
|
| 410 |
-
overlay_path = root / "graph" / ci._GRAPH_ENTITY_OVERLAY_NAME
|
| 411 |
-
assert ci._GRAPH_ENTITY_OVERLAY_SHA256 == _artifact_sha256_or_lfs_oid(
|
| 412 |
-
overlay_path,
|
| 413 |
-
normalize_text=True,
|
| 414 |
-
)
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
def test_local_graph_archive_checksum_is_verified(tmp_path: Path) -> None:
|
| 418 |
-
archive = tmp_path / "wiki-graph-runtime.tar.gz"
|
| 419 |
-
archive.write_bytes(b"not the shipped runtime archive")
|
| 420 |
-
|
| 421 |
-
with pytest.raises(ValueError, match="local graph archive checksum mismatch"):
|
| 422 |
-
ci._verify_local_graph_archive(archive, requested_install_mode="runtime")
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
def
|
| 426 |
-
tmp_path: Path,
|
| 427 |
-
monkeypatch,
|
| 428 |
-
) -> None:
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
"
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
)
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
"
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
monkeypatch,
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
monkeypatch.setattr(ci
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
)
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
) ->
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
)
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
_tar_text(
|
| 652 |
-
tf,
|
| 653 |
-
"graphify-out/graph
|
| 654 |
-
json.dumps({
|
| 655 |
-
"
|
| 656 |
-
"
|
| 657 |
-
"
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
}),
|
| 664 |
-
)
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
"
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
|
| 720 |
-
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
|
| 734 |
-
)
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
|
| 738 |
-
|
| 739 |
-
|
| 740 |
-
|
| 741 |
-
|
| 742 |
-
|
| 743 |
-
|
| 744 |
-
|
| 745 |
-
|
| 746 |
-
|
| 747 |
-
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
|
| 753 |
-
|
| 754 |
-
)
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
|
| 777 |
-
|
| 778 |
-
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
|
| 783 |
-
|
| 784 |
-
|
| 785 |
-
|
| 786 |
-
|
| 787 |
-
)
|
| 788 |
-
|
| 789 |
-
|
| 790 |
-
|
| 791 |
-
(
|
| 792 |
-
|
| 793 |
-
|
| 794 |
-
|
| 795 |
-
|
| 796 |
-
|
| 797 |
-
|
| 798 |
-
|
| 799 |
-
|
| 800 |
-
|
| 801 |
-
|
| 802 |
-
|
| 803 |
-
|
| 804 |
-
|
| 805 |
-
|
| 806 |
-
|
| 807 |
-
|
| 808 |
-
|
| 809 |
-
|
| 810 |
-
|
| 811 |
-
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
|
| 815 |
-
|
| 816 |
-
"
|
| 817 |
-
|
| 818 |
-
)
|
| 819 |
-
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
|
| 823 |
-
|
| 824 |
-
|
| 825 |
-
|
| 826 |
-
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
|
| 830 |
-
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
monkeypatch,
|
| 834 |
-
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
|
| 844 |
-
|
| 845 |
-
"
|
| 846 |
-
|
| 847 |
-
)
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
|
| 851 |
-
|
| 852 |
-
|
| 853 |
-
|
| 854 |
-
|
| 855 |
-
|
| 856 |
-
|
| 857 |
-
)
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
|
| 865 |
-
|
| 866 |
-
|
| 867 |
-
|
| 868 |
-
|
| 869 |
-
|
| 870 |
-
|
| 871 |
-
|
| 872 |
-
|
| 873 |
-
|
| 874 |
-
|
| 875 |
-
|
| 876 |
-
|
| 877 |
-
|
| 878 |
-
monkeypatch,
|
| 879 |
-
|
| 880 |
-
|
| 881 |
-
|
| 882 |
-
|
| 883 |
-
|
| 884 |
-
|
| 885 |
-
|
| 886 |
-
def
|
| 887 |
-
|
| 888 |
-
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
|
| 892 |
-
|
| 893 |
-
|
| 894 |
-
|
| 895 |
-
|
| 896 |
-
|
| 897 |
-
|
| 898 |
-
|
| 899 |
-
|
| 900 |
-
|
| 901 |
-
|
| 902 |
-
|
| 903 |
-
|
| 904 |
-
|
| 905 |
-
|
| 906 |
-
|
| 907 |
-
|
| 908 |
-
|
| 909 |
-
|
| 910 |
-
|
| 911 |
-
|
| 912 |
-
|
| 913 |
-
|
| 914 |
-
|
| 915 |
-
|
| 916 |
-
|
| 917 |
-
|
| 918 |
-
|
| 919 |
-
|
| 920 |
-
|
| 921 |
-
|
| 922 |
-
|
| 923 |
-
|
| 924 |
-
|
| 925 |
-
|
| 926 |
-
|
| 927 |
-
|
| 928 |
-
|
| 929 |
-
|
| 930 |
-
|
| 931 |
-
|
| 932 |
-
|
| 933 |
-
|
| 934 |
-
|
| 935 |
-
|
| 936 |
-
|
| 937 |
-
|
| 938 |
-
|
| 939 |
-
|
| 940 |
-
|
| 941 |
-
|
| 942 |
-
|
| 943 |
-
|
| 944 |
-
|
| 945 |
-
monkeypatch
|
| 946 |
-
|
| 947 |
-
|
| 948 |
-
|
| 949 |
-
|
| 950 |
-
|
| 951 |
-
|
| 952 |
-
|
| 953 |
-
|
| 954 |
-
|
| 955 |
-
|
| 956 |
-
|
| 957 |
-
|
| 958 |
-
|
| 959 |
-
|
| 960 |
-
|
| 961 |
-
|
| 962 |
-
|
| 963 |
-
|
| 964 |
-
|
| 965 |
-
|
| 966 |
-
|
| 967 |
-
|
| 968 |
-
|
| 969 |
-
|
| 970 |
-
|
| 971 |
-
|
| 972 |
-
|
| 973 |
-
|
| 974 |
-
|
| 975 |
-
|
| 976 |
-
|
| 977 |
-
|
| 978 |
-
|
| 979 |
-
|
| 980 |
-
|
| 981 |
-
|
| 982 |
-
|
| 983 |
-
|
| 984 |
-
|
| 985 |
-
|
| 986 |
-
|
| 987 |
-
"
|
| 988 |
-
|
| 989 |
-
|
| 990 |
-
|
| 991 |
-
|
| 992 |
-
|
| 993 |
-
|
| 994 |
-
|
| 995 |
-
|
| 996 |
-
|
| 997 |
-
|
| 998 |
-
|
| 999 |
-
|
| 1000 |
-
|
| 1001 |
-
|
| 1002 |
-
|
| 1003 |
-
|
| 1004 |
-
|
| 1005 |
-
|
| 1006 |
-
|
| 1007 |
-
|
| 1008 |
-
|
| 1009 |
-
|
| 1010 |
-
|
| 1011 |
-
|
| 1012 |
-
|
| 1013 |
-
|
| 1014 |
-
|
| 1015 |
-
|
| 1016 |
-
|
| 1017 |
-
|
| 1018 |
-
|
| 1019 |
-
|
| 1020 |
-
|
| 1021 |
-
|
| 1022 |
-
|
| 1023 |
-
|
| 1024 |
-
|
| 1025 |
-
|
| 1026 |
-
|
| 1027 |
-
|
| 1028 |
-
|
| 1029 |
-
|
| 1030 |
-
|
| 1031 |
-
|
| 1032 |
-
|
| 1033 |
-
|
| 1034 |
-
|
| 1035 |
-
|
| 1036 |
-
|
| 1037 |
-
|
| 1038 |
-
|
| 1039 |
-
"
|
| 1040 |
-
|
| 1041 |
-
|
| 1042 |
-
|
| 1043 |
-
|
| 1044 |
-
|
| 1045 |
-
|
| 1046 |
-
|
| 1047 |
-
|
| 1048 |
-
|
| 1049 |
-
|
| 1050 |
-
|
| 1051 |
-
|
| 1052 |
-
|
| 1053 |
-
|
| 1054 |
-
|
| 1055 |
-
|
| 1056 |
-
)
|
| 1057 |
-
|
| 1058 |
-
|
| 1059 |
-
"
|
| 1060 |
-
|
| 1061 |
-
|
| 1062 |
-
|
| 1063 |
-
|
| 1064 |
-
|
| 1065 |
-
|
| 1066 |
-
|
| 1067 |
-
|
| 1068 |
-
|
| 1069 |
-
|
| 1070 |
-
|
| 1071 |
-
|
| 1072 |
-
|
| 1073 |
-
|
| 1074 |
-
|
| 1075 |
-
|
| 1076 |
-
)
|
| 1077 |
-
|
| 1078 |
-
|
| 1079 |
-
|
| 1080 |
-
|
| 1081 |
-
|
| 1082 |
-
|
| 1083 |
-
|
| 1084 |
-
|
| 1085 |
-
|
| 1086 |
-
|
| 1087 |
-
|
| 1088 |
-
|
| 1089 |
-
|
| 1090 |
-
|
| 1091 |
-
|
| 1092 |
-
|
| 1093 |
-
|
| 1094 |
-
|
| 1095 |
-
|
| 1096 |
-
|
| 1097 |
-
|
| 1098 |
-
|
| 1099 |
-
|
| 1100 |
-
|
| 1101 |
-
(
|
| 1102 |
-
|
| 1103 |
-
|
| 1104 |
-
|
| 1105 |
-
|
| 1106 |
-
|
| 1107 |
-
|
| 1108 |
-
|
| 1109 |
-
|
| 1110 |
-
|
| 1111 |
-
|
| 1112 |
-
|
| 1113 |
-
|
| 1114 |
-
|
| 1115 |
-
|
| 1116 |
-
|
| 1117 |
-
|
| 1118 |
-
""
|
| 1119 |
-
|
| 1120 |
-
)
|
| 1121 |
-
|
| 1122 |
-
|
| 1123 |
-
|
| 1124 |
-
|
| 1125 |
-
|
| 1126 |
-
|
| 1127 |
-
|
| 1128 |
-
|
| 1129 |
-
|
| 1130 |
-
|
| 1131 |
-
|
| 1132 |
-
|
| 1133 |
-
|
| 1134 |
-
|
| 1135 |
-
|
| 1136 |
-
|
| 1137 |
-
|
| 1138 |
-
|
| 1139 |
-
|
| 1140 |
-
|
| 1141 |
-
|
| 1142 |
-
|
| 1143 |
-
|
| 1144 |
-
|
| 1145 |
-
|
| 1146 |
-
|
| 1147 |
-
|
| 1148 |
-
|
| 1149 |
-
|
| 1150 |
-
|
| 1151 |
-
|
| 1152 |
-
|
| 1153 |
-
|
| 1154 |
-
|
| 1155 |
-
|
| 1156 |
-
|
| 1157 |
-
|
| 1158 |
-
|
| 1159 |
-
|
| 1160 |
-
|
| 1161 |
-
|
| 1162 |
-
|
| 1163 |
-
|
| 1164 |
-
|
| 1165 |
-
|
| 1166 |
-
|
| 1167 |
-
|
| 1168 |
-
|
| 1169 |
-
|
| 1170 |
-
|
| 1171 |
-
|
| 1172 |
-
|
| 1173 |
-
|
| 1174 |
-
|
| 1175 |
-
|
| 1176 |
-
|
| 1177 |
-
|
| 1178 |
-
""
|
| 1179 |
-
|
| 1180 |
-
|
| 1181 |
-
|
| 1182 |
-
|
| 1183 |
-
|
| 1184 |
-
|
| 1185 |
-
|
| 1186 |
-
|
| 1187 |
-
|
| 1188 |
-
|
| 1189 |
-
|
| 1190 |
-
|
| 1191 |
-
|
| 1192 |
-
|
| 1193 |
-
|
| 1194 |
-
|
| 1195 |
-
|
| 1196 |
-
|
| 1197 |
-
|
| 1198 |
-
|
| 1199 |
-
|
| 1200 |
-
|
| 1201 |
-
|
| 1202 |
-
-
|
| 1203 |
-
|
| 1204 |
-
-
|
| 1205 |
-
|
| 1206 |
-
|
| 1207 |
-
|
| 1208 |
-
|
| 1209 |
-
|
| 1210 |
-
|
| 1211 |
-
""
|
| 1212 |
-
|
| 1213 |
-
)
|
| 1214 |
-
|
| 1215 |
-
|
| 1216 |
-
|
| 1217 |
-
|
| 1218 |
-
|
| 1219 |
-
|
| 1220 |
-
|
| 1221 |
-
|
| 1222 |
-
|
| 1223 |
-
|
| 1224 |
-
|
| 1225 |
-
|
| 1226 |
-
|
| 1227 |
-
|
| 1228 |
-
|
| 1229 |
-
|
| 1230 |
-
|
| 1231 |
-
|
| 1232 |
-
|
| 1233 |
-
|
| 1234 |
-
|
| 1235 |
-
|
| 1236 |
-
|
| 1237 |
-
},
|
| 1238 |
-
|
| 1239 |
-
|
| 1240 |
-
|
| 1241 |
-
|
| 1242 |
-
|
| 1243 |
-
|
| 1244 |
-
|
| 1245 |
-
|
| 1246 |
-
|
| 1247 |
-
|
| 1248 |
-
|
| 1249 |
-
|
| 1250 |
-
|
| 1251 |
-
|
| 1252 |
-
|
| 1253 |
-
|
| 1254 |
-
|
| 1255 |
-
|
| 1256 |
-
|
| 1257 |
-
|
| 1258 |
-
)
|
| 1259 |
-
|
| 1260 |
-
|
| 1261 |
-
|
| 1262 |
-
|
| 1263 |
-
|
| 1264 |
-
|
| 1265 |
-
|
| 1266 |
-
|
| 1267 |
-
|
| 1268 |
-
|
| 1269 |
-
|
| 1270 |
-
|
| 1271 |
-
|
| 1272 |
-
|
| 1273 |
-
|
| 1274 |
-
|
| 1275 |
-
|
| 1276 |
-
|
| 1277 |
-
|
| 1278 |
-
|
| 1279 |
-
)
|
| 1280 |
-
|
| 1281 |
-
|
| 1282 |
-
|
| 1283 |
-
|
| 1284 |
-
|
| 1285 |
-
|
| 1286 |
-
|
| 1287 |
-
|
| 1288 |
-
|
| 1289 |
-
|
| 1290 |
-
|
| 1291 |
-
|
| 1292 |
-
|
| 1293 |
-
|
| 1294 |
-
|
| 1295 |
-
|
| 1296 |
-
|
| 1297 |
-
|
| 1298 |
-
|
| 1299 |
-
|
| 1300 |
-
|
| 1301 |
-
|
| 1302 |
-
|
| 1303 |
-
|
| 1304 |
-
|
| 1305 |
-
|
| 1306 |
-
|
| 1307 |
-
|
| 1308 |
-
|
| 1309 |
-
|
| 1310 |
-
|
| 1311 |
-
|
| 1312 |
-
|
| 1313 |
-
|
| 1314 |
-
|
| 1315 |
-
|
| 1316 |
-
|
| 1317 |
-
|
| 1318 |
-
|
| 1319 |
-
|
| 1320 |
-
|
| 1321 |
-
|
| 1322 |
-
|
| 1323 |
-
|
| 1324 |
-
|
| 1325 |
-
|
| 1326 |
-
|
| 1327 |
-
|
| 1328 |
-
|
| 1329 |
-
|
| 1330 |
-
|
| 1331 |
-
|
| 1332 |
-
|
| 1333 |
-
|
| 1334 |
-
|
| 1335 |
-
|
| 1336 |
-
|
| 1337 |
-
|
| 1338 |
-
|
| 1339 |
-
|
| 1340 |
-
|
| 1341 |
-
|
| 1342 |
-
|
| 1343 |
-
|
| 1344 |
-
|
| 1345 |
-
|
| 1346 |
-
"
|
| 1347 |
-
|
| 1348 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for ctx_init — bootstrap ~/.claude/ scaffolding."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import builtins
|
| 6 |
+
import hashlib
|
| 7 |
+
import io
|
| 8 |
+
import json
|
| 9 |
+
import sqlite3
|
| 10 |
+
import sys
|
| 11 |
+
import tarfile
|
| 12 |
+
import zlib
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from types import SimpleNamespace
|
| 15 |
+
|
| 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:
|
| 22 |
+
conn = sqlite3.connect(path)
|
| 23 |
+
try:
|
| 24 |
+
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
|
| 25 |
+
conn.execute(
|
| 26 |
+
"CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
|
| 27 |
+
"description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
|
| 28 |
+
)
|
| 29 |
+
conn.execute(
|
| 30 |
+
"CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
|
| 31 |
+
"PRIMARY KEY(slug,type,node_id))"
|
| 32 |
+
)
|
| 33 |
+
conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
|
| 34 |
+
conn.executemany(
|
| 35 |
+
"INSERT INTO meta VALUES(?,?)",
|
| 36 |
+
[
|
| 37 |
+
("export_id", json.dumps(export_id)),
|
| 38 |
+
("nodes_count", "1"),
|
| 39 |
+
("edges_count", "0"),
|
| 40 |
+
("max_degree", "1"),
|
| 41 |
+
("top_k", "40"),
|
| 42 |
+
],
|
| 43 |
+
)
|
| 44 |
+
conn.execute(
|
| 45 |
+
"INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
|
| 46 |
+
("skill:current", "current", "skill", "[]", "", None, None, 0),
|
| 47 |
+
)
|
| 48 |
+
conn.execute("INSERT INTO slug_index VALUES(?,?,?)", ("current", "skill", "skill:current"))
|
| 49 |
+
conn.execute("INSERT INTO neighbors VALUES(?,?)", ("skill:current", zlib.compress(b"[]")))
|
| 50 |
+
conn.commit()
|
| 51 |
+
finally:
|
| 52 |
+
conn.close()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _artifact_sha256_or_lfs_oid(path: Path, *, normalize_text: bool = False) -> str:
|
| 56 |
+
data = path.read_bytes()
|
| 57 |
+
if data.startswith(b"version https://git-lfs.github.com/spec/v1\n"):
|
| 58 |
+
for line in data.decode("utf-8").splitlines():
|
| 59 |
+
if line.startswith("oid sha256:"):
|
| 60 |
+
return line.removeprefix("oid sha256:")
|
| 61 |
+
if normalize_text:
|
| 62 |
+
data = data.replace(b"\r\n", b"\n")
|
| 63 |
+
return hashlib.sha256(data).hexdigest()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_ensure_directories_creates_standard_tree(tmp_path: Path) -> None:
|
| 67 |
+
created = ci.ensure_directories(tmp_path)
|
| 68 |
+
# First call should create every standard subdir.
|
| 69 |
+
assert len(created) == len(ci._STANDARD_SUBDIRS)
|
| 70 |
+
for sub in ci._STANDARD_SUBDIRS:
|
| 71 |
+
assert (tmp_path / sub).is_dir(), f"missing {sub}"
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_ensure_directories_is_idempotent(tmp_path: Path) -> None:
|
| 75 |
+
first = ci.ensure_directories(tmp_path)
|
| 76 |
+
assert len(first) > 0
|
| 77 |
+
second = ci.ensure_directories(tmp_path)
|
| 78 |
+
assert second == [], "second call should not recreate anything"
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def test_seed_user_config_writes_once(tmp_path: Path) -> None:
|
| 82 |
+
tmp_path.mkdir(exist_ok=True)
|
| 83 |
+
first = ci.seed_user_config(tmp_path)
|
| 84 |
+
assert first is not None
|
| 85 |
+
assert first.exists()
|
| 86 |
+
body = first.read_text(encoding="utf-8")
|
| 87 |
+
assert "skill-system-config.json" in body
|
| 88 |
+
|
| 89 |
+
# Second call returns None (file already exists, force=False).
|
| 90 |
+
second = ci.seed_user_config(tmp_path)
|
| 91 |
+
assert second is None
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def test_seed_user_config_respects_force(tmp_path: Path) -> None:
|
| 95 |
+
target = tmp_path / "skill-system-config.json"
|
| 96 |
+
target.write_text("user-custom-content", encoding="utf-8")
|
| 97 |
+
# Without force → don't touch.
|
| 98 |
+
assert ci.seed_user_config(tmp_path, force=False) is None
|
| 99 |
+
assert target.read_text() == "user-custom-content"
|
| 100 |
+
# With force → overwrite.
|
| 101 |
+
result = ci.seed_user_config(tmp_path, force=True)
|
| 102 |
+
assert result == target
|
| 103 |
+
assert "skill-system-config.json" in target.read_text()
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def test_main_creates_everything_in_dry_mode(tmp_path: Path, monkeypatch,
|
| 107 |
+
capsys) -> None:
|
| 108 |
+
"""End-to-end: ``ctx-init`` (no flags) creates dirs + config + toolboxes
|
| 109 |
+
without touching hooks or graph."""
|
| 110 |
+
monkeypatch.setattr(ci, "_claude_dir", lambda: tmp_path)
|
| 111 |
+
|
| 112 |
+
# Short-circuit subprocess.run to avoid spawning a real toolbox/graph CLI
|
| 113 |
+
# in tests. Verify that main() doesn't call install_hooks or build_graph
|
| 114 |
+
# when those flags are absent.
|
| 115 |
+
calls: list[list[str]] = []
|
| 116 |
+
|
| 117 |
+
class _FakeResult:
|
| 118 |
+
returncode = 0
|
| 119 |
+
stdout = ""
|
| 120 |
+
stderr = ""
|
| 121 |
+
|
| 122 |
+
def fake_run(cmd, **kwargs):
|
| 123 |
+
calls.append(list(cmd))
|
| 124 |
+
return _FakeResult()
|
| 125 |
+
|
| 126 |
+
monkeypatch.setattr(ci.subprocess, "run", fake_run)
|
| 127 |
+
|
| 128 |
+
rc = ci.main([])
|
| 129 |
+
assert rc == 0
|
| 130 |
+
# toolbox init should have been invoked
|
| 131 |
+
toolbox_calls = [c for c in calls if "toolbox" in " ".join(c)]
|
| 132 |
+
assert toolbox_calls, "toolbox init not invoked"
|
| 133 |
+
# inject_hooks / wiki_graphify must NOT be invoked without flags
|
| 134 |
+
for c in calls:
|
| 135 |
+
assert "inject_hooks" not in " ".join(c)
|
| 136 |
+
assert "wiki_graphify" not in " ".join(c)
|
| 137 |
+
|
| 138 |
+
out = capsys.readouterr().out
|
| 139 |
+
assert "[ok]" in out
|
| 140 |
+
assert "[skip] hook injection" in out
|
| 141 |
+
assert "[skip] graph install" in out
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def test_main_treats_existing_toolboxes_as_idempotent_skip(
|
| 145 |
+
tmp_path: Path,
|
| 146 |
+
monkeypatch,
|
| 147 |
+
capsys,
|
| 148 |
+
) -> None:
|
| 149 |
+
monkeypatch.setattr(ci, "_claude_dir", lambda: tmp_path)
|
| 150 |
+
|
| 151 |
+
class _FakeResult:
|
| 152 |
+
returncode = 1
|
| 153 |
+
stdout = ""
|
| 154 |
+
stderr = (
|
| 155 |
+
"Global config already has 5 toolbox(es). "
|
| 156 |
+
"Use --force to overwrite."
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
monkeypatch.setattr(ci.subprocess, "run", lambda *_args, **_kwargs: _FakeResult())
|
| 160 |
+
|
| 161 |
+
rc = ci.main(["--model-mode", "skip"])
|
| 162 |
+
captured = capsys.readouterr()
|
| 163 |
+
|
| 164 |
+
assert rc == 0
|
| 165 |
+
assert "starter toolboxes already present" in captured.out
|
| 166 |
+
assert "toolbox init returned" not in captured.err
|
| 167 |
+
assert "Global config already has" not in captured.err
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def test_main_auto_wizard_in_terminal_configures_custom_model(
|
| 171 |
+
tmp_path: Path,
|
| 172 |
+
monkeypatch,
|
| 173 |
+
) -> None:
|
| 174 |
+
monkeypatch.setattr(ci, "_claude_dir", lambda: tmp_path)
|
| 175 |
+
monkeypatch.setattr(ci, "_stdio_is_interactive", lambda: True)
|
| 176 |
+
monkeypatch.setattr(
|
| 177 |
+
ci,
|
| 178 |
+
"recommend_harnesses",
|
| 179 |
+
lambda goal, top_k=5, model_provider=None, model=None: [],
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
answers = iter([
|
| 183 |
+
"y", # hooks
|
| 184 |
+
"enriched", # knowledge mode
|
| 185 |
+
"n", # graph
|
| 186 |
+
"custom", # model mode
|
| 187 |
+
"openai/gpt-5.5", # model
|
| 188 |
+
"", # provider default: openai
|
| 189 |
+
"", # api key env default: OPENAI_API_KEY
|
| 190 |
+
"", # base URL
|
| 191 |
+
"build CAD artifacts",
|
| 192 |
+
"windows python", # runtime / OS
|
| 193 |
+
"supervised", # autonomy
|
| 194 |
+
"filesystem shell", # allowed tools
|
| 195 |
+
"pytest ruff", # verification
|
| 196 |
+
"private repo", # privacy / network
|
| 197 |
+
"mcp", # attach mode
|
| 198 |
+
"n", # validate model
|
| 199 |
+
])
|
| 200 |
+
monkeypatch.setattr(builtins, "input", lambda _prompt: next(answers))
|
| 201 |
+
calls: list[list[str]] = []
|
| 202 |
+
|
| 203 |
+
class _FakeResult:
|
| 204 |
+
returncode = 0
|
| 205 |
+
stdout = ""
|
| 206 |
+
stderr = ""
|
| 207 |
+
|
| 208 |
+
def _fake_run(cmd: list[str], **_kwargs: object) -> _FakeResult:
|
| 209 |
+
calls.append(list(cmd))
|
| 210 |
+
return _FakeResult()
|
| 211 |
+
|
| 212 |
+
monkeypatch.setattr(ci.subprocess, "run", _fake_run)
|
| 213 |
+
|
| 214 |
+
rc = ci.main([])
|
| 215 |
+
|
| 216 |
+
assert rc == 0
|
| 217 |
+
assert any("ctx.adapters.claude_code.inject_hooks" in c for c in calls)
|
| 218 |
+
assert not any("ctx.core.wiki.wiki_graphify" in c for c in calls)
|
| 219 |
+
profile = json.loads((tmp_path / "ctx-model-profile.json").read_text())
|
| 220 |
+
assert profile["mode"] == "custom"
|
| 221 |
+
assert profile["provider"] == "openai"
|
| 222 |
+
assert profile["model"] == "openai/gpt-5.5"
|
| 223 |
+
assert profile["api_key_env"] == "OPENAI_API_KEY"
|
| 224 |
+
assert profile["goal"] == "build CAD artifacts"
|
| 225 |
+
assert profile["knowledge_mode"] == "enriched"
|
| 226 |
+
assert profile["harness_requirements"] == {
|
| 227 |
+
"runtime": "windows python",
|
| 228 |
+
"autonomy": "supervised",
|
| 229 |
+
"tools": "filesystem shell",
|
| 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"
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def test_wizard_flag_prompts_without_tty(tmp_path: Path, monkeypatch) -> None:
|
| 239 |
+
monkeypatch.setattr(ci, "_claude_dir", lambda: tmp_path)
|
| 240 |
+
monkeypatch.setattr(ci, "_stdio_is_interactive", lambda: False)
|
| 241 |
+
monkeypatch.setattr(ci, "seed_toolboxes", lambda force=False: 0)
|
| 242 |
+
monkeypatch.setattr(
|
| 243 |
+
ci,
|
| 244 |
+
"recommend_harnesses",
|
| 245 |
+
lambda goal, top_k=5, model_provider=None, model=None: [],
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
answers = iter([
|
| 249 |
+
"n", # hooks
|
| 250 |
+
"local", # knowledge mode
|
| 251 |
+
"claude-code", # model mode
|
| 252 |
+
"maintain FastAPI services",
|
| 253 |
+
])
|
| 254 |
+
monkeypatch.setattr(builtins, "input", lambda _prompt: next(answers))
|
| 255 |
+
|
| 256 |
+
rc = ci.main(["--wizard"])
|
| 257 |
+
|
| 258 |
+
assert rc == 0
|
| 259 |
+
profile = json.loads((tmp_path / "ctx-model-profile.json").read_text())
|
| 260 |
+
assert profile["mode"] == "claude-code"
|
| 261 |
+
assert profile["goal"] == "maintain FastAPI services"
|
| 262 |
+
assert profile["knowledge_mode"] == "local"
|
| 263 |
+
user_config = json.loads((tmp_path / "skill-system-config.json").read_text())
|
| 264 |
+
assert user_config["knowledge"]["mode"] == "local"
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def test_explicit_args_do_not_auto_wizard_in_terminal(
|
| 268 |
+
tmp_path: Path,
|
| 269 |
+
monkeypatch,
|
| 270 |
+
) -> None:
|
| 271 |
+
monkeypatch.setattr(ci, "_claude_dir", lambda: tmp_path)
|
| 272 |
+
monkeypatch.setattr(ci, "_stdio_is_interactive", lambda: True)
|
| 273 |
+
monkeypatch.setattr(ci, "seed_toolboxes", lambda force=False: 0)
|
| 274 |
+
monkeypatch.setattr(
|
| 275 |
+
builtins,
|
| 276 |
+
"input",
|
| 277 |
+
lambda _prompt: (_ for _ in ()).throw(AssertionError("unexpected prompt")),
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
assert ci.main(["--model-mode", "skip", "--knowledge-mode", "local"]) == 0
|
| 281 |
+
user_config = json.loads((tmp_path / "skill-system-config.json").read_text())
|
| 282 |
+
assert user_config["knowledge"]["mode"] == "local"
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def test_main_with_hooks_flag_invokes_inject(tmp_path: Path, monkeypatch) -> None:
|
| 286 |
+
monkeypatch.setattr(ci, "_claude_dir", lambda: tmp_path)
|
| 287 |
+
calls: list[list[str]] = []
|
| 288 |
+
|
| 289 |
+
class _FakeResult:
|
| 290 |
+
returncode = 0
|
| 291 |
+
stdout = ""
|
| 292 |
+
stderr = ""
|
| 293 |
+
|
| 294 |
+
def _fake_run(cmd: list[str], **_kwargs: object) -> _FakeResult:
|
| 295 |
+
calls.append(list(cmd))
|
| 296 |
+
return _FakeResult()
|
| 297 |
+
|
| 298 |
+
monkeypatch.setattr(ci.subprocess, "run", _fake_run)
|
| 299 |
+
rc = ci.main(["--hooks"])
|
| 300 |
+
assert rc == 0
|
| 301 |
+
assert any("ctx.adapters.claude_code.inject_hooks" in c for c in calls)
|
| 302 |
+
assert not any(c == "inject_hooks" for call in calls for c in call)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def _write_graph_archive(tmp_path: Path) -> Path:
|
| 306 |
+
source = tmp_path / "archive-source"
|
| 307 |
+
graph_out = source / "graphify-out"
|
| 308 |
+
graph_out.mkdir(parents=True)
|
| 309 |
+
(graph_out / "graph.json").write_text(
|
| 310 |
+
json.dumps({"graph": {"export_id": "test-export"}, "nodes": [], "links": []}),
|
| 311 |
+
encoding="utf-8",
|
| 312 |
+
)
|
| 313 |
+
(graph_out / "graph-delta.json").write_text(
|
| 314 |
+
json.dumps({"export_id": "test-export", "nodes": [], "edges": []}),
|
| 315 |
+
encoding="utf-8",
|
| 316 |
+
)
|
| 317 |
+
(graph_out / "communities.json").write_text(
|
| 318 |
+
json.dumps({"export_id": "test-export", "total_communities": 0}),
|
| 319 |
+
encoding="utf-8",
|
| 320 |
+
)
|
| 321 |
+
(graph_out / "graph-report.md").write_text(
|
| 322 |
+
"# Graph Report\n\n> Export ID: test-export\n",
|
| 323 |
+
encoding="utf-8",
|
| 324 |
+
)
|
| 325 |
+
(graph_out / "graph-export-manifest.json").write_text(
|
| 326 |
+
json.dumps({
|
| 327 |
+
"version": 1,
|
| 328 |
+
"export_id": "test-export",
|
| 329 |
+
"artifacts": {
|
| 330 |
+
"graph": "graph.json",
|
| 331 |
+
"delta": "graph-delta.json",
|
| 332 |
+
"communities": "communities.json",
|
| 333 |
+
"report": "graph-report.md",
|
| 334 |
+
},
|
| 335 |
+
}),
|
| 336 |
+
encoding="utf-8",
|
| 337 |
+
)
|
| 338 |
+
_write_dashboard_index(graph_out / "dashboard-neighborhoods.sqlite3")
|
| 339 |
+
external = source / "external-catalogs" / "skills-sh"
|
| 340 |
+
external.mkdir(parents=True)
|
| 341 |
+
(external / "catalog.json").write_text("{}", encoding="utf-8")
|
| 342 |
+
entities = source / "entities" / "skills"
|
| 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("*")):
|
| 349 |
+
if path.is_file():
|
| 350 |
+
tf.add(path, arcname=path.relative_to(source).as_posix())
|
| 351 |
+
return archive
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def _tar_text(tf: tarfile.TarFile, name: str, text: str) -> None:
|
| 355 |
+
payload = text.encode("utf-8")
|
| 356 |
+
info = tarfile.TarInfo(name)
|
| 357 |
+
info.size = len(payload)
|
| 358 |
+
tf.addfile(info, io.BytesIO(payload))
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def _tar_bytes(tf: tarfile.TarFile, name: str, payload: bytes) -> None:
|
| 362 |
+
info = tarfile.TarInfo(name)
|
| 363 |
+
info.size = len(payload)
|
| 364 |
+
tf.addfile(info, io.BytesIO(payload))
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def test_download_graph_archive_verifies_sha256(
|
| 368 |
+
tmp_path: Path,
|
| 369 |
+
monkeypatch,
|
| 370 |
+
) -> None:
|
| 371 |
+
payload = b"graph archive bytes"
|
| 372 |
+
|
| 373 |
+
class _Response(io.BytesIO):
|
| 374 |
+
def __enter__(self) -> "_Response":
|
| 375 |
+
return self
|
| 376 |
+
|
| 377 |
+
def __exit__(self, *_args: object) -> None:
|
| 378 |
+
return None
|
| 379 |
+
|
| 380 |
+
monkeypatch.setattr(
|
| 381 |
+
ci.urllib.request,
|
| 382 |
+
"urlopen",
|
| 383 |
+
lambda _url, timeout=120: _Response(payload),
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
destination = tmp_path / "wiki-graph.tar.gz"
|
| 387 |
+
ci._download_graph_archive(
|
| 388 |
+
destination,
|
| 389 |
+
url="https://example.invalid/wiki-graph.tar.gz",
|
| 390 |
+
expected_sha256=hashlib.sha256(payload).hexdigest(),
|
| 391 |
+
)
|
| 392 |
+
assert destination.read_bytes() == payload
|
| 393 |
+
|
| 394 |
+
bad_destination = tmp_path / "bad-wiki-graph.tar.gz"
|
| 395 |
+
with pytest.raises(ValueError, match="checksum mismatch"):
|
| 396 |
+
ci._download_graph_archive(
|
| 397 |
+
bad_destination,
|
| 398 |
+
url="https://example.invalid/wiki-graph.tar.gz",
|
| 399 |
+
expected_sha256="0" * 64,
|
| 400 |
+
)
|
| 401 |
+
assert not bad_destination.exists()
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def test_graph_download_checksums_match_shipped_artifacts() -> None:
|
| 405 |
+
root = Path(__file__).resolve().parent.parent.parent
|
| 406 |
+
for mode, archive_name in ci._GRAPH_ARCHIVE_NAMES.items():
|
| 407 |
+
path = root / "graph" / archive_name
|
| 408 |
+
assert ci._GRAPH_ARCHIVE_SHA256[mode] == _artifact_sha256_or_lfs_oid(path)
|
| 409 |
+
|
| 410 |
+
overlay_path = root / "graph" / ci._GRAPH_ENTITY_OVERLAY_NAME
|
| 411 |
+
assert ci._GRAPH_ENTITY_OVERLAY_SHA256 == _artifact_sha256_or_lfs_oid(
|
| 412 |
+
overlay_path,
|
| 413 |
+
normalize_text=True,
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def test_local_graph_archive_checksum_is_verified(tmp_path: Path) -> None:
|
| 418 |
+
archive = tmp_path / "wiki-graph-runtime.tar.gz"
|
| 419 |
+
archive.write_bytes(b"not the shipped runtime archive")
|
| 420 |
+
|
| 421 |
+
with pytest.raises(ValueError, match="local graph archive checksum mismatch"):
|
| 422 |
+
ci._verify_local_graph_archive(archive, requested_install_mode="runtime")
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def test_lfs_pointer_graph_archive_is_ignored(
|
| 426 |
+
tmp_path: Path,
|
| 427 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 428 |
+
) -> None:
|
| 429 |
+
graph_dir = tmp_path / "graph"
|
| 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:334fb19bace3fd6e4b92087850f17297fb248032957d123f3f1432dfde2e36c0\n"
|
| 434 |
+
"size 175773376\n",
|
| 435 |
+
encoding="utf-8",
|
| 436 |
+
)
|
| 437 |
+
cwd = tmp_path / "cwd"
|
| 438 |
+
cwd.mkdir()
|
| 439 |
+
monkeypatch.chdir(cwd)
|
| 440 |
+
monkeypatch.setattr(ci, "__file__", str(tmp_path / "src" / "ctx_init.py"))
|
| 441 |
+
|
| 442 |
+
assert ci._find_local_graph_archive("runtime") is None
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def test_custom_graph_url_requires_checksum_or_explicit_opt_out(
|
| 446 |
+
tmp_path: Path,
|
| 447 |
+
monkeypatch,
|
| 448 |
+
) -> None:
|
| 449 |
+
monkeypatch.setattr(ci, "_find_local_graph_archive", lambda _mode: None)
|
| 450 |
+
monkeypatch.setattr(
|
| 451 |
+
ci,
|
| 452 |
+
"_download_graph_archive",
|
| 453 |
+
lambda *_args, **_kwargs: (_ for _ in ()).throw(
|
| 454 |
+
AssertionError("download should be blocked before network access")
|
| 455 |
+
),
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
rc = ci.build_graph(
|
| 459 |
+
tmp_path / "home",
|
| 460 |
+
graph_url="https://example.invalid/wiki-graph.tar.gz",
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
assert rc == 1
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
def test_custom_graph_url_bypasses_local_archive(
|
| 467 |
+
tmp_path: Path,
|
| 468 |
+
monkeypatch,
|
| 469 |
+
) -> None:
|
| 470 |
+
archive = _write_graph_archive(tmp_path)
|
| 471 |
+
archive_bytes = archive.read_bytes()
|
| 472 |
+
calls: list[dict[str, object]] = []
|
| 473 |
+
|
| 474 |
+
monkeypatch.setattr(
|
| 475 |
+
ci,
|
| 476 |
+
"_find_local_graph_archive",
|
| 477 |
+
lambda _mode: (_ for _ in ()).throw(
|
| 478 |
+
AssertionError("explicit graph_url must not use local archive")
|
| 479 |
+
),
|
| 480 |
+
)
|
| 481 |
+
|
| 482 |
+
def fake_download(destination: Path, **kwargs: object) -> None:
|
| 483 |
+
calls.append(dict(kwargs))
|
| 484 |
+
destination.write_bytes(archive_bytes)
|
| 485 |
+
|
| 486 |
+
monkeypatch.setattr(ci, "_download_graph_archive", fake_download)
|
| 487 |
+
monkeypatch.setattr(ci, "_install_graph_entity_overlay", lambda *_a, **_k: None)
|
| 488 |
+
|
| 489 |
+
rc = ci.build_graph(
|
| 490 |
+
tmp_path / "home",
|
| 491 |
+
graph_url="https://example.invalid/custom-wiki-graph.tar.gz",
|
| 492 |
+
graph_sha256=hashlib.sha256(archive_bytes).hexdigest(),
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
assert rc == 0
|
| 496 |
+
assert calls == [
|
| 497 |
+
{
|
| 498 |
+
"url": "https://example.invalid/custom-wiki-graph.tar.gz",
|
| 499 |
+
"expected_sha256": hashlib.sha256(archive_bytes).hexdigest(),
|
| 500 |
+
}
|
| 501 |
+
]
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def test_main_with_graph_flag_installs_prebuilt_graph(
|
| 505 |
+
tmp_path: Path,
|
| 506 |
+
monkeypatch,
|
| 507 |
+
) -> None:
|
| 508 |
+
claude = tmp_path / "home"
|
| 509 |
+
archive = _write_graph_archive(tmp_path)
|
| 510 |
+
monkeypatch.setattr(ci, "_claude_dir", lambda: claude)
|
| 511 |
+
monkeypatch.setattr(ci, "seed_toolboxes", lambda force=False: 0)
|
| 512 |
+
monkeypatch.setattr(
|
| 513 |
+
ci,
|
| 514 |
+
"_find_local_graph_archive",
|
| 515 |
+
lambda _install_mode="runtime": archive,
|
| 516 |
+
raising=False,
|
| 517 |
+
)
|
| 518 |
+
monkeypatch.setattr(ci, "_verify_local_graph_archive", lambda *_a, **_k: None)
|
| 519 |
+
monkeypatch.setattr(
|
| 520 |
+
ci,
|
| 521 |
+
"_download_graph_archive",
|
| 522 |
+
lambda _dest, **_kwargs: (_ for _ in ()).throw(
|
| 523 |
+
AssertionError("unexpected release download")
|
| 524 |
+
),
|
| 525 |
+
raising=False,
|
| 526 |
+
)
|
| 527 |
+
calls: list[list[str]] = []
|
| 528 |
+
|
| 529 |
+
class _FakeResult:
|
| 530 |
+
returncode = 0
|
| 531 |
+
stdout = ""
|
| 532 |
+
stderr = ""
|
| 533 |
+
|
| 534 |
+
def _fake_run(cmd: list[str], **_kwargs: object) -> _FakeResult:
|
| 535 |
+
calls.append(list(cmd))
|
| 536 |
+
return _FakeResult()
|
| 537 |
+
|
| 538 |
+
monkeypatch.setattr(ci.subprocess, "run", _fake_run)
|
| 539 |
+
rc = ci.main(["--graph", "--model-mode", "skip"])
|
| 540 |
+
assert rc == 0
|
| 541 |
+
graph_json = claude / "skill-wiki" / "graphify-out" / "graph.json"
|
| 542 |
+
graph_payload = json.loads(graph_json.read_text(encoding="utf-8"))
|
| 543 |
+
assert graph_payload["graph"]["export_id"] == "test-export"
|
| 544 |
+
assert not (
|
| 545 |
+
claude / "skill-wiki" / "entities" / "skills" / "current.md"
|
| 546 |
+
).exists()
|
| 547 |
+
assert not any("ctx.core.wiki.wiki_graphify" in c for c in calls)
|
| 548 |
+
assert not any(c == "wiki_graphify" for call in calls for c in call)
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
def test_graph_install_copies_local_entity_overlay(
|
| 552 |
+
tmp_path: Path,
|
| 553 |
+
monkeypatch,
|
| 554 |
+
) -> None:
|
| 555 |
+
claude = tmp_path / "home"
|
| 556 |
+
archive = _write_graph_archive(tmp_path)
|
| 557 |
+
overlay = tmp_path / "entity-overlays.jsonl"
|
| 558 |
+
overlay.write_text(
|
| 559 |
+
json.dumps({
|
| 560 |
+
"overlay_id": "test-overlay",
|
| 561 |
+
"nodes": [{"id": "harness:mirage", "type": "harness"}],
|
| 562 |
+
"edges": [
|
| 563 |
+
{
|
| 564 |
+
"source": "harness:mirage",
|
| 565 |
+
"target": "skill:codex-review",
|
| 566 |
+
"weight": 0.5,
|
| 567 |
+
"similarity_score": 0.5,
|
| 568 |
+
"method": "manual_direct_overlay_v1",
|
| 569 |
+
"rank": 1,
|
| 570 |
+
"provenance": "manual_overlay_v1",
|
| 571 |
+
}
|
| 572 |
+
],
|
| 573 |
+
})
|
| 574 |
+
+ "\n",
|
| 575 |
+
encoding="utf-8",
|
| 576 |
+
)
|
| 577 |
+
monkeypatch.setattr(
|
| 578 |
+
ci,
|
| 579 |
+
"_find_local_graph_archive",
|
| 580 |
+
lambda _install_mode="runtime": archive,
|
| 581 |
+
raising=False,
|
| 582 |
+
)
|
| 583 |
+
monkeypatch.setattr(ci, "_find_local_graph_entity_overlay", lambda: overlay)
|
| 584 |
+
monkeypatch.setattr(ci, "_verify_local_graph_archive", lambda *_a, **_k: None)
|
| 585 |
+
|
| 586 |
+
assert ci.build_graph(claude) == 0
|
| 587 |
+
|
| 588 |
+
installed = claude / "skill-wiki" / "graphify-out" / "entity-overlays.jsonl"
|
| 589 |
+
payload = json.loads(installed.read_text(encoding="utf-8"))
|
| 590 |
+
assert payload["overlay_id"] == "test-overlay"
|
| 591 |
+
assert payload["edges"][0]["method"] == "manual_direct_overlay_v1"
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
@pytest.mark.parametrize("field", ["semantic_sim", "tag_sim", "token_sim"])
|
| 595 |
+
def test_graph_overlay_validation_rejects_out_of_range_similarity_fields(
|
| 596 |
+
tmp_path: Path,
|
| 597 |
+
field: str,
|
| 598 |
+
) -> None:
|
| 599 |
+
overlay = tmp_path / "entity-overlays.jsonl"
|
| 600 |
+
overlay.write_text(
|
| 601 |
+
json.dumps({
|
| 602 |
+
"nodes": [{"id": "skill:a"}],
|
| 603 |
+
"edges": [
|
| 604 |
+
{
|
| 605 |
+
"source": "skill:a",
|
| 606 |
+
"target": "skill:b",
|
| 607 |
+
"weight": 0.5,
|
| 608 |
+
"final_weight": 0.5,
|
| 609 |
+
field: 2.0,
|
| 610 |
+
},
|
| 611 |
+
],
|
| 612 |
+
})
|
| 613 |
+
+ "\n",
|
| 614 |
+
encoding="utf-8",
|
| 615 |
+
)
|
| 616 |
+
|
| 617 |
+
with pytest.raises(ValueError, match=f"{field} must be 0..1"):
|
| 618 |
+
ci._validate_graph_entity_overlay(overlay)
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
def test_graph_overlay_validation_rejects_weight_final_weight_drift(
|
| 622 |
+
tmp_path: Path,
|
| 623 |
+
) -> None:
|
| 624 |
+
overlay = tmp_path / "entity-overlays.jsonl"
|
| 625 |
+
overlay.write_text(
|
| 626 |
+
json.dumps({
|
| 627 |
+
"nodes": [{"id": "skill:a"}],
|
| 628 |
+
"edges": [
|
| 629 |
+
{
|
| 630 |
+
"source": "skill:a",
|
| 631 |
+
"target": "skill:b",
|
| 632 |
+
"weight": 0.7,
|
| 633 |
+
"final_weight": 0.5,
|
| 634 |
+
},
|
| 635 |
+
],
|
| 636 |
+
})
|
| 637 |
+
+ "\n",
|
| 638 |
+
encoding="utf-8",
|
| 639 |
+
)
|
| 640 |
+
|
| 641 |
+
with pytest.raises(ValueError, match="weight must equal final_weight"):
|
| 642 |
+
ci._validate_graph_entity_overlay(overlay)
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
def test_runtime_graph_install_extracts_harness_pages_after_required_files(
|
| 646 |
+
tmp_path: Path,
|
| 647 |
+
monkeypatch,
|
| 648 |
+
) -> None:
|
| 649 |
+
archive = tmp_path / "ordered-runtime-wiki-graph.tar.gz"
|
| 650 |
+
with tarfile.open(archive, "w:gz") as tf:
|
| 651 |
+
_tar_text(
|
| 652 |
+
tf,
|
| 653 |
+
"graphify-out/graph.json",
|
| 654 |
+
json.dumps({
|
| 655 |
+
"graph": {"export_id": "test-export"},
|
| 656 |
+
"nodes": [{"id": "harness:text-to-cad", "type": "harness"}],
|
| 657 |
+
"links": [],
|
| 658 |
+
}),
|
| 659 |
+
)
|
| 660 |
+
_tar_text(
|
| 661 |
+
tf,
|
| 662 |
+
"graphify-out/graph-delta.json",
|
| 663 |
+
json.dumps({"export_id": "test-export", "nodes": [], "edges": []}),
|
| 664 |
+
)
|
| 665 |
+
_tar_text(
|
| 666 |
+
tf,
|
| 667 |
+
"graphify-out/communities.json",
|
| 668 |
+
json.dumps({"export_id": "test-export", "total_communities": 0}),
|
| 669 |
+
)
|
| 670 |
+
_tar_text(tf, "graphify-out/graph-report.md", "# Graph Report\n")
|
| 671 |
+
_tar_text(
|
| 672 |
+
tf,
|
| 673 |
+
"graphify-out/graph-export-manifest.json",
|
| 674 |
+
json.dumps({
|
| 675 |
+
"version": 1,
|
| 676 |
+
"export_id": "test-export",
|
| 677 |
+
"artifacts": {
|
| 678 |
+
"graph": "graph.json",
|
| 679 |
+
"delta": "graph-delta.json",
|
| 680 |
+
"communities": "communities.json",
|
| 681 |
+
"report": "graph-report.md",
|
| 682 |
+
},
|
| 683 |
+
}),
|
| 684 |
+
)
|
| 685 |
+
index_path = tmp_path / "runtime-dashboard-neighborhoods.sqlite3"
|
| 686 |
+
_write_dashboard_index(index_path)
|
| 687 |
+
_tar_bytes(
|
| 688 |
+
tf,
|
| 689 |
+
"graphify-out/dashboard-neighborhoods.sqlite3",
|
| 690 |
+
index_path.read_bytes(),
|
| 691 |
+
)
|
| 692 |
+
_tar_text(tf, "external-catalogs/skills-sh/catalog.json", "{}")
|
| 693 |
+
_tar_text(tf, "index.md", "# Wiki\n")
|
| 694 |
+
_tar_text(tf, "entities/harnesses/text-to-cad.md", "# Text to CAD\n")
|
| 695 |
+
_tar_text(tf, "entities/skills/not-runtime.md", "# Not runtime\n")
|
| 696 |
+
|
| 697 |
+
claude = tmp_path / "home"
|
| 698 |
+
monkeypatch.setattr(
|
| 699 |
+
ci,
|
| 700 |
+
"_find_local_graph_archive",
|
| 701 |
+
lambda _install_mode="runtime": archive,
|
| 702 |
+
)
|
| 703 |
+
monkeypatch.setattr(ci, "_verify_local_graph_archive", lambda *_a, **_k: None)
|
| 704 |
+
|
| 705 |
+
assert ci.build_graph(claude) == 0
|
| 706 |
+
assert (
|
| 707 |
+
claude / "skill-wiki" / "entities" / "harnesses" / "text-to-cad.md"
|
| 708 |
+
).is_file()
|
| 709 |
+
assert not (
|
| 710 |
+
claude / "skill-wiki" / "entities" / "skills" / "not-runtime.md"
|
| 711 |
+
).exists()
|
| 712 |
+
|
| 713 |
+
|
| 714 |
+
def test_runtime_graph_install_preserves_existing_non_harness_entities(
|
| 715 |
+
tmp_path: Path,
|
| 716 |
+
monkeypatch,
|
| 717 |
+
) -> None:
|
| 718 |
+
archive = _write_graph_archive(tmp_path)
|
| 719 |
+
claude = tmp_path / "home"
|
| 720 |
+
local_skill = claude / "skill-wiki" / "entities" / "skills" / "private.md"
|
| 721 |
+
local_agent = claude / "skill-wiki" / "entities" / "agents" / "private.md"
|
| 722 |
+
local_mcp = claude / "skill-wiki" / "entities" / "mcp-servers" / "p" / "private.md"
|
| 723 |
+
local_harness = claude / "skill-wiki" / "entities" / "harnesses" / "old.md"
|
| 724 |
+
for path in (local_skill, local_agent, local_mcp, local_harness):
|
| 725 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 726 |
+
path.write_text(f"# {path.stem}\n", encoding="utf-8")
|
| 727 |
+
|
| 728 |
+
monkeypatch.setattr(
|
| 729 |
+
ci,
|
| 730 |
+
"_find_local_graph_archive",
|
| 731 |
+
lambda _install_mode="runtime": archive,
|
| 732 |
+
)
|
| 733 |
+
monkeypatch.setattr(ci, "_verify_local_graph_archive", lambda *_a, **_k: None)
|
| 734 |
+
monkeypatch.setattr(ci, "_install_graph_entity_overlay", lambda *_a, **_k: None)
|
| 735 |
+
|
| 736 |
+
assert ci.build_graph(claude, force=True, install_mode="runtime") == 0
|
| 737 |
+
|
| 738 |
+
assert local_skill.is_file()
|
| 739 |
+
assert local_agent.is_file()
|
| 740 |
+
assert local_mcp.is_file()
|
| 741 |
+
assert not local_harness.exists()
|
| 742 |
+
|
| 743 |
+
|
| 744 |
+
def test_graph_install_rejects_incomplete_archive(
|
| 745 |
+
tmp_path: Path,
|
| 746 |
+
monkeypatch,
|
| 747 |
+
) -> None:
|
| 748 |
+
source = tmp_path / "incomplete-source"
|
| 749 |
+
graph_out = source / "graphify-out"
|
| 750 |
+
graph_out.mkdir(parents=True)
|
| 751 |
+
(graph_out / "graph.json").write_text(
|
| 752 |
+
json.dumps({"graph": {"export_id": "partial"}, "nodes": []}),
|
| 753 |
+
encoding="utf-8",
|
| 754 |
+
)
|
| 755 |
+
archive = tmp_path / "incomplete-wiki-graph.tar.gz"
|
| 756 |
+
with tarfile.open(archive, "w:gz") as tf:
|
| 757 |
+
tf.add(graph_out / "graph.json", arcname="graphify-out/graph.json")
|
| 758 |
+
|
| 759 |
+
claude = tmp_path / "home"
|
| 760 |
+
monkeypatch.setattr(
|
| 761 |
+
ci,
|
| 762 |
+
"_find_local_graph_archive",
|
| 763 |
+
lambda _install_mode="runtime": archive,
|
| 764 |
+
)
|
| 765 |
+
monkeypatch.setattr(ci, "_verify_local_graph_archive", lambda *_a, **_k: None)
|
| 766 |
+
|
| 767 |
+
assert ci.build_graph(claude) == 1
|
| 768 |
+
assert not (claude / "skill-wiki" / "graphify-out" / "graph.json").exists()
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
def test_graph_install_validation_does_not_parse_full_graph_json(
|
| 772 |
+
tmp_path: Path,
|
| 773 |
+
monkeypatch,
|
| 774 |
+
) -> None:
|
| 775 |
+
wiki = tmp_path / "wiki"
|
| 776 |
+
graph_out = wiki / "graphify-out"
|
| 777 |
+
graph_out.mkdir(parents=True)
|
| 778 |
+
(wiki / "index.md").write_text("# Wiki\n", encoding="utf-8")
|
| 779 |
+
(graph_out / "graph.json").write_text(
|
| 780 |
+
json.dumps({"graph": {"export_id": "test-export"}, "nodes": [], "links": []}),
|
| 781 |
+
encoding="utf-8",
|
| 782 |
+
)
|
| 783 |
+
(graph_out / "graph-delta.json").write_text(
|
| 784 |
+
json.dumps({"export_id": "test-export", "nodes": [], "edges": []}),
|
| 785 |
+
encoding="utf-8",
|
| 786 |
+
)
|
| 787 |
+
(graph_out / "communities.json").write_text(
|
| 788 |
+
json.dumps({"export_id": "test-export", "total_communities": 0}),
|
| 789 |
+
encoding="utf-8",
|
| 790 |
+
)
|
| 791 |
+
(graph_out / "graph-report.md").write_text(
|
| 792 |
+
"# Graph Report\n\n> Export ID: test-export\n",
|
| 793 |
+
encoding="utf-8",
|
| 794 |
+
)
|
| 795 |
+
(graph_out / "graph-export-manifest.json").write_text(
|
| 796 |
+
json.dumps({
|
| 797 |
+
"version": 1,
|
| 798 |
+
"export_id": "test-export",
|
| 799 |
+
"artifacts": {
|
| 800 |
+
"graph": "graph.json",
|
| 801 |
+
"delta": "graph-delta.json",
|
| 802 |
+
"communities": "communities.json",
|
| 803 |
+
"report": "graph-report.md",
|
| 804 |
+
},
|
| 805 |
+
}),
|
| 806 |
+
encoding="utf-8",
|
| 807 |
+
)
|
| 808 |
+
_write_dashboard_index(graph_out / "dashboard-neighborhoods.sqlite3")
|
| 809 |
+
external = wiki / "external-catalogs" / "skills-sh"
|
| 810 |
+
external.mkdir(parents=True)
|
| 811 |
+
(external / "catalog.json").write_text("{}", encoding="utf-8")
|
| 812 |
+
|
| 813 |
+
def guarded_read(path: Path) -> object:
|
| 814 |
+
if path.name == "graph.json":
|
| 815 |
+
raise AssertionError("install validation must not parse full graph.json")
|
| 816 |
+
return json.loads(path.read_text(encoding="utf-8"))
|
| 817 |
+
|
| 818 |
+
monkeypatch.setattr(ci, "_read_json_file", guarded_read)
|
| 819 |
+
|
| 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"
|
| 829 |
+
stale = claude / "skill-wiki" / "entities" / "skills" / "stale.md"
|
| 830 |
+
stale.parent.mkdir(parents=True)
|
| 831 |
+
stale.write_text("# Stale\n", encoding="utf-8")
|
| 832 |
+
monkeypatch.setattr(ci, "_claude_dir", lambda: claude)
|
| 833 |
+
monkeypatch.setattr(ci, "seed_toolboxes", lambda force=False: 0)
|
| 834 |
+
monkeypatch.setattr(
|
| 835 |
+
ci,
|
| 836 |
+
"_find_local_graph_archive",
|
| 837 |
+
lambda _install_mode="runtime": archive,
|
| 838 |
+
)
|
| 839 |
+
monkeypatch.setattr(ci, "_verify_local_graph_archive", lambda *_a, **_k: None)
|
| 840 |
+
|
| 841 |
+
assert ci.main([
|
| 842 |
+
"--graph",
|
| 843 |
+
"--graph-install-mode", "full",
|
| 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 |
+
|
| 850 |
+
|
| 851 |
+
def test_graph_install_rejects_path_traversal_archive(
|
| 852 |
+
tmp_path: Path,
|
| 853 |
+
monkeypatch,
|
| 854 |
+
) -> None:
|
| 855 |
+
archive = tmp_path / "malicious-wiki-graph.tar.gz"
|
| 856 |
+
payload = b"owned"
|
| 857 |
+
with tarfile.open(archive, "w:gz") as tf:
|
| 858 |
+
info = tarfile.TarInfo("../evil.txt")
|
| 859 |
+
info.size = len(payload)
|
| 860 |
+
tf.addfile(info, io.BytesIO(payload))
|
| 861 |
+
|
| 862 |
+
claude = tmp_path / "home"
|
| 863 |
+
monkeypatch.setattr(
|
| 864 |
+
ci,
|
| 865 |
+
"_find_local_graph_archive",
|
| 866 |
+
lambda _install_mode="runtime": archive,
|
| 867 |
+
)
|
| 868 |
+
monkeypatch.setattr(ci, "_verify_local_graph_archive", lambda *_a, **_k: None)
|
| 869 |
+
|
| 870 |
+
assert ci.build_graph(claude) == 1
|
| 871 |
+
assert not (tmp_path / "evil.txt").exists()
|
| 872 |
+
assert not (claude / "evil.txt").exists()
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
def test_main_with_requested_hook_failure_exits_nonzero(
|
| 876 |
+
tmp_path: Path, monkeypatch
|
| 877 |
+
) -> None:
|
| 878 |
+
monkeypatch.setattr(ci, "_claude_dir", lambda: tmp_path)
|
| 879 |
+
|
| 880 |
+
class _FakeResult:
|
| 881 |
+
def __init__(self, returncode: int) -> None:
|
| 882 |
+
self.returncode = returncode
|
| 883 |
+
self.stdout = ""
|
| 884 |
+
self.stderr = ""
|
| 885 |
+
|
| 886 |
+
def fake_run(cmd, **kwargs):
|
| 887 |
+
if "ctx.adapters.claude_code.inject_hooks" in cmd:
|
| 888 |
+
return _FakeResult(7)
|
| 889 |
+
return _FakeResult(0)
|
| 890 |
+
|
| 891 |
+
monkeypatch.setattr(ci.subprocess, "run", fake_run)
|
| 892 |
+
|
| 893 |
+
assert ci.main(["--hooks"]) == 7
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
def test_main_custom_model_writes_profile_and_recommends_harness(
|
| 897 |
+
tmp_path: Path,
|
| 898 |
+
monkeypatch,
|
| 899 |
+
capsys,
|
| 900 |
+
) -> None:
|
| 901 |
+
monkeypatch.setattr(ci, "_claude_dir", lambda: tmp_path)
|
| 902 |
+
monkeypatch.setattr(ci, "seed_toolboxes", lambda force=False: 0)
|
| 903 |
+
|
| 904 |
+
recommendation_calls: list[dict[str, object]] = []
|
| 905 |
+
|
| 906 |
+
def fake_recommend(
|
| 907 |
+
goal: str,
|
| 908 |
+
top_k: int = 5,
|
| 909 |
+
model_provider: str | None = None,
|
| 910 |
+
model: str | None = None,
|
| 911 |
+
) -> list[dict[str, object]]:
|
| 912 |
+
recommendation_calls.append({
|
| 913 |
+
"goal": goal,
|
| 914 |
+
"top_k": top_k,
|
| 915 |
+
"model_provider": model_provider,
|
| 916 |
+
"model": model,
|
| 917 |
+
})
|
| 918 |
+
return [{"name": "text-to-cad", "type": "harness", "score": 0.8}]
|
| 919 |
+
|
| 920 |
+
monkeypatch.setattr(
|
| 921 |
+
ci,
|
| 922 |
+
"recommend_harnesses",
|
| 923 |
+
fake_recommend,
|
| 924 |
+
)
|
| 925 |
+
|
| 926 |
+
rc = ci.main([
|
| 927 |
+
"--model-mode", "custom",
|
| 928 |
+
"--model", "openai/gpt-5.5",
|
| 929 |
+
"--goal", "turn text prompts into CAD",
|
| 930 |
+
])
|
| 931 |
+
|
| 932 |
+
assert rc == 0
|
| 933 |
+
profile = json.loads((tmp_path / "ctx-model-profile.json").read_text())
|
| 934 |
+
assert profile["mode"] == "custom"
|
| 935 |
+
assert profile["provider"] == "openai"
|
| 936 |
+
assert profile["model"] == "openai/gpt-5.5"
|
| 937 |
+
assert profile["api_key_env"] == "OPENAI_API_KEY"
|
| 938 |
+
assert recommendation_calls[0]["model_provider"] == "openai"
|
| 939 |
+
assert recommendation_calls[0]["model"] == "openai/gpt-5.5"
|
| 940 |
+
assert "text-to-cad" in capsys.readouterr().out
|
| 941 |
+
|
| 942 |
+
|
| 943 |
+
def test_main_custom_model_records_structured_harness_requirements(
|
| 944 |
+
tmp_path: Path,
|
| 945 |
+
monkeypatch,
|
| 946 |
+
) -> None:
|
| 947 |
+
monkeypatch.setattr(ci, "_claude_dir", lambda: tmp_path)
|
| 948 |
+
monkeypatch.setattr(ci, "seed_toolboxes", lambda force=False: 0)
|
| 949 |
+
recommendation_calls: list[dict[str, object]] = []
|
| 950 |
+
|
| 951 |
+
def fake_recommend(
|
| 952 |
+
goal: str,
|
| 953 |
+
top_k: int = 5,
|
| 954 |
+
model_provider: str | None = None,
|
| 955 |
+
model: str | None = None,
|
| 956 |
+
) -> list[dict[str, object]]:
|
| 957 |
+
recommendation_calls.append({
|
| 958 |
+
"goal": goal,
|
| 959 |
+
"top_k": top_k,
|
| 960 |
+
"model_provider": model_provider,
|
| 961 |
+
"model": model,
|
| 962 |
+
})
|
| 963 |
+
return []
|
| 964 |
+
|
| 965 |
+
monkeypatch.setattr(ci, "recommend_harnesses", fake_recommend)
|
| 966 |
+
|
| 967 |
+
rc = ci.main([
|
| 968 |
+
"--model-mode", "custom",
|
| 969 |
+
"--model", "openai/gpt-5.5",
|
| 970 |
+
"--goal", "build a code agent",
|
| 971 |
+
"--harness-runtime", "windows python",
|
| 972 |
+
"--harness-autonomy", "supervised",
|
| 973 |
+
"--harness-tools", "filesystem shell browser",
|
| 974 |
+
"--harness-verify", "pytest ruff",
|
| 975 |
+
"--harness-privacy", "private repo no secrets",
|
| 976 |
+
"--harness-attach-mode", "mcp",
|
| 977 |
+
])
|
| 978 |
+
|
| 979 |
+
assert rc == 0
|
| 980 |
+
profile = json.loads((tmp_path / "ctx-model-profile.json").read_text())
|
| 981 |
+
assert profile["harness_requirements"] == {
|
| 982 |
+
"runtime": "windows python",
|
| 983 |
+
"autonomy": "supervised",
|
| 984 |
+
"tools": "filesystem shell browser",
|
| 985 |
+
"verification": "pytest ruff",
|
| 986 |
+
"privacy": "private repo no secrets",
|
| 987 |
+
"attach_mode": "mcp",
|
| 988 |
+
}
|
| 989 |
+
query = str(recommendation_calls[0]["goal"])
|
| 990 |
+
assert "windows python" in query
|
| 991 |
+
assert "filesystem shell browser" in query
|
| 992 |
+
assert "pytest ruff" in query
|
| 993 |
+
assert "private repo no secrets" in query
|
| 994 |
+
assert "mcp" in query
|
| 995 |
+
|
| 996 |
+
|
| 997 |
+
def test_main_custom_model_no_fit_points_to_harness_plan(
|
| 998 |
+
tmp_path: Path,
|
| 999 |
+
monkeypatch,
|
| 1000 |
+
capsys,
|
| 1001 |
+
) -> None:
|
| 1002 |
+
monkeypatch.setattr(ci, "_claude_dir", lambda: tmp_path)
|
| 1003 |
+
monkeypatch.setattr(ci, "seed_toolboxes", lambda force=False: 0)
|
| 1004 |
+
monkeypatch.setattr(ci, "recommend_harnesses", lambda *args, **kwargs: [])
|
| 1005 |
+
|
| 1006 |
+
rc = ci.main([
|
| 1007 |
+
"--model-mode", "custom",
|
| 1008 |
+
"--model", "ollama/llama3.1",
|
| 1009 |
+
"--model-provider", "ollama",
|
| 1010 |
+
"--goal", "private local CAD workflow",
|
| 1011 |
+
"--harness-runtime", "linux server",
|
| 1012 |
+
"--harness-tools", "filesystem shell",
|
| 1013 |
+
"--harness-verify", "pytest",
|
| 1014 |
+
"--harness-privacy", "offline source code",
|
| 1015 |
+
"--harness-attach-mode", "mcp",
|
| 1016 |
+
])
|
| 1017 |
+
|
| 1018 |
+
assert rc == 0
|
| 1019 |
+
output = capsys.readouterr().out
|
| 1020 |
+
assert "no harness recommendations matched yet" in output
|
| 1021 |
+
assert "ctx-harness-install --recommend" in output
|
| 1022 |
+
assert "--model-provider \"ollama\"" in output
|
| 1023 |
+
assert "--harness-runtime \"linux server\"" in output
|
| 1024 |
+
assert "--harness-tools \"filesystem shell\"" in output
|
| 1025 |
+
assert "--harness-verify \"pytest\"" in output
|
| 1026 |
+
assert "--harness-privacy \"offline source code\"" in output
|
| 1027 |
+
assert "--harness-attach-mode \"mcp\"" in output
|
| 1028 |
+
assert "--plan-on-no-fit" in output
|
| 1029 |
+
|
| 1030 |
+
|
| 1031 |
+
def test_recommend_harnesses_uses_wiki_frontmatter_for_fit(
|
| 1032 |
+
tmp_path: Path,
|
| 1033 |
+
monkeypatch,
|
| 1034 |
+
) -> None:
|
| 1035 |
+
wiki = tmp_path / "wiki"
|
| 1036 |
+
page = wiki / "entities" / "harnesses" / "text-to-cad.md"
|
| 1037 |
+
page.parent.mkdir(parents=True)
|
| 1038 |
+
page.write_text(
|
| 1039 |
+
"""---
|
| 1040 |
+
title: Text to CAD
|
| 1041 |
+
type: harness
|
| 1042 |
+
tags:
|
| 1043 |
+
- cad
|
| 1044 |
+
runtimes:
|
| 1045 |
+
- python
|
| 1046 |
+
model_providers:
|
| 1047 |
+
- openai
|
| 1048 |
+
capabilities:
|
| 1049 |
+
- Generate CAD artifacts from natural language prompts
|
| 1050 |
+
with OpenSCAD and mesh validation
|
| 1051 |
+
repo_url: https://github.com/earthtojake/text-to-cad
|
| 1052 |
+
---
|
| 1053 |
+
# Text to CAD
|
| 1054 |
+
""",
|
| 1055 |
+
encoding="utf-8",
|
| 1056 |
+
)
|
| 1057 |
+
graph = nx.Graph()
|
| 1058 |
+
graph.add_node(
|
| 1059 |
+
"harness:text-to-cad",
|
| 1060 |
+
label="text-to-cad",
|
| 1061 |
+
type="harness",
|
| 1062 |
+
tags=["cad"],
|
| 1063 |
+
)
|
| 1064 |
+
monkeypatch.setattr(ci, "_load_recommendation_graph", lambda: graph)
|
| 1065 |
+
import ctx_config
|
| 1066 |
+
|
| 1067 |
+
monkeypatch.setattr(
|
| 1068 |
+
ctx_config,
|
| 1069 |
+
"cfg",
|
| 1070 |
+
SimpleNamespace(
|
| 1071 |
+
wiki_dir=wiki,
|
| 1072 |
+
claude_dir=tmp_path / ".claude",
|
| 1073 |
+
recommendation_top_k=5,
|
| 1074 |
+
harness_recommendation_min_fit_score=0.85,
|
| 1075 |
+
),
|
| 1076 |
+
)
|
| 1077 |
+
|
| 1078 |
+
results = ci.recommend_harnesses(
|
| 1079 |
+
"turn text prompts into CAD openscad openai gpt-5 harness",
|
| 1080 |
+
model_provider="openai",
|
| 1081 |
+
model="openai/gpt-5.5",
|
| 1082 |
+
)
|
| 1083 |
+
|
| 1084 |
+
assert results
|
| 1085 |
+
assert results[0]["name"] == "text-to-cad"
|
| 1086 |
+
assert results[0]["fit_score"] >= 0.85
|
| 1087 |
+
assert "openai" in results[0]["fit_signals"]
|
| 1088 |
+
assert "gpt-5" not in results[0]["fit_signals"]
|
| 1089 |
+
assert "gpt-5" not in results[0]["missing_signals"]
|
| 1090 |
+
assert "openscad" in results[0]["fit_signals"]
|
| 1091 |
+
|
| 1092 |
+
|
| 1093 |
+
def test_load_recommendation_graph_uses_configured_wiki_dir(
|
| 1094 |
+
tmp_path: Path,
|
| 1095 |
+
monkeypatch,
|
| 1096 |
+
) -> None:
|
| 1097 |
+
wiki = tmp_path / "custom-wiki"
|
| 1098 |
+
out = wiki / "graphify-out"
|
| 1099 |
+
out.mkdir(parents=True)
|
| 1100 |
+
graph = nx.Graph()
|
| 1101 |
+
graph.add_node("harness:custom", label="custom", type="harness")
|
| 1102 |
+
data = nx.node_link_data(graph)
|
| 1103 |
+
(out / "graph.json").write_text(json.dumps(data), encoding="utf-8")
|
| 1104 |
+
|
| 1105 |
+
import ctx_config
|
| 1106 |
+
|
| 1107 |
+
monkeypatch.setattr(ctx_config, "cfg", SimpleNamespace(wiki_dir=wiki))
|
| 1108 |
+
|
| 1109 |
+
loaded = ci._load_recommendation_graph()
|
| 1110 |
+
|
| 1111 |
+
assert "harness:custom" in loaded
|
| 1112 |
+
|
| 1113 |
+
|
| 1114 |
+
def test_recommend_harnesses_surfaces_reliability_rubric(
|
| 1115 |
+
tmp_path: Path,
|
| 1116 |
+
monkeypatch,
|
| 1117 |
+
) -> None:
|
| 1118 |
+
wiki = tmp_path / "wiki"
|
| 1119 |
+
harness_dir = wiki / "entities" / "harnesses"
|
| 1120 |
+
harness_dir.mkdir(parents=True)
|
| 1121 |
+
(harness_dir / "reliable-agent.md").write_text(
|
| 1122 |
+
"""---
|
| 1123 |
+
title: Reliable Agent
|
| 1124 |
+
type: harness
|
| 1125 |
+
tags:
|
| 1126 |
+
- agents
|
| 1127 |
+
model_providers:
|
| 1128 |
+
- openai
|
| 1129 |
+
capabilities:
|
| 1130 |
+
- Persistent project context and task state
|
| 1131 |
+
- Permission limits, sandbox rules, and policy checks
|
| 1132 |
+
- Automated tests, evals, retry loops, and validation gates
|
| 1133 |
+
verify_commands:
|
| 1134 |
+
- pytest
|
| 1135 |
+
repo_url: https://example.test/reliable-agent
|
| 1136 |
+
---
|
| 1137 |
+
# Reliable Agent
|
| 1138 |
+
""",
|
| 1139 |
+
encoding="utf-8",
|
| 1140 |
+
)
|
| 1141 |
+
graph = nx.Graph()
|
| 1142 |
+
graph.add_node(
|
| 1143 |
+
"harness:reliable-agent",
|
| 1144 |
+
label="reliable-agent",
|
| 1145 |
+
type="harness",
|
| 1146 |
+
tags=["agents"],
|
| 1147 |
+
)
|
| 1148 |
+
monkeypatch.setattr(ci, "_load_recommendation_graph", lambda: graph)
|
| 1149 |
+
import ctx_config
|
| 1150 |
+
|
| 1151 |
+
monkeypatch.setattr(
|
| 1152 |
+
ctx_config,
|
| 1153 |
+
"cfg",
|
| 1154 |
+
SimpleNamespace(
|
| 1155 |
+
wiki_dir=wiki,
|
| 1156 |
+
claude_dir=tmp_path / ".claude",
|
| 1157 |
+
recommendation_top_k=5,
|
| 1158 |
+
harness_recommendation_min_fit_score=0.20,
|
| 1159 |
+
harness_reliability_weights={
|
| 1160 |
+
"context": 0.34,
|
| 1161 |
+
"constraints": 0.33,
|
| 1162 |
+
"convergence": 0.33,
|
| 1163 |
+
},
|
| 1164 |
+
),
|
| 1165 |
+
)
|
| 1166 |
+
|
| 1167 |
+
results = ci.recommend_harnesses(
|
| 1168 |
+
"openai agent workflow with tests and sandbox",
|
| 1169 |
+
model_provider="openai",
|
| 1170 |
+
model="openai/gpt-5.5",
|
| 1171 |
+
)
|
| 1172 |
+
|
| 1173 |
+
assert results
|
| 1174 |
+
recommendation = results[0]
|
| 1175 |
+
assert recommendation["name"] == "reliable-agent"
|
| 1176 |
+
assert recommendation["reliability_score"] >= 0.90
|
| 1177 |
+
assert set(recommendation["reliability_dimensions"]) == {
|
| 1178 |
+
"context",
|
| 1179 |
+
"constraints",
|
| 1180 |
+
"convergence",
|
| 1181 |
+
}
|
| 1182 |
+
assert recommendation["reliability_dimensions"]["context"]["matched_terms"]
|
| 1183 |
+
assert recommendation["reliability_dimensions"]["constraints"]["matched_terms"]
|
| 1184 |
+
assert recommendation["reliability_dimensions"]["convergence"]["matched_terms"]
|
| 1185 |
+
assert "context" in recommendation["reliability_reason"]
|
| 1186 |
+
assert "constraints" in recommendation["reliability_reason"]
|
| 1187 |
+
assert "convergence" in recommendation["reliability_reason"]
|
| 1188 |
+
|
| 1189 |
+
|
| 1190 |
+
def test_recommend_harnesses_prefers_reliable_harness_when_fit_ties(
|
| 1191 |
+
tmp_path: Path,
|
| 1192 |
+
monkeypatch,
|
| 1193 |
+
) -> None:
|
| 1194 |
+
wiki = tmp_path / "wiki"
|
| 1195 |
+
harness_dir = wiki / "entities" / "harnesses"
|
| 1196 |
+
harness_dir.mkdir(parents=True)
|
| 1197 |
+
(harness_dir / "thin-agent.md").write_text(
|
| 1198 |
+
"""---
|
| 1199 |
+
title: Thin Agent
|
| 1200 |
+
type: harness
|
| 1201 |
+
tags:
|
| 1202 |
+
- agents
|
| 1203 |
+
model_providers:
|
| 1204 |
+
- openai
|
| 1205 |
+
capabilities:
|
| 1206 |
+
- Agent workflow orchestration
|
| 1207 |
+
repo_url: https://example.test/thin-agent
|
| 1208 |
+
---
|
| 1209 |
+
# Thin Agent
|
| 1210 |
+
""",
|
| 1211 |
+
encoding="utf-8",
|
| 1212 |
+
)
|
| 1213 |
+
(harness_dir / "reliable-agent.md").write_text(
|
| 1214 |
+
"""---
|
| 1215 |
+
title: Reliable Agent
|
| 1216 |
+
type: harness
|
| 1217 |
+
tags:
|
| 1218 |
+
- agents
|
| 1219 |
+
model_providers:
|
| 1220 |
+
- openai
|
| 1221 |
+
capabilities:
|
| 1222 |
+
- Agent workflow orchestration
|
| 1223 |
+
- Persistent context state and durable task documents
|
| 1224 |
+
- Permission limits, sandbox boundaries, and approval policies
|
| 1225 |
+
- Automated tests, evals, validation gates, and retry loops
|
| 1226 |
+
verify_commands:
|
| 1227 |
+
- pytest
|
| 1228 |
+
repo_url: https://example.test/reliable-agent
|
| 1229 |
+
---
|
| 1230 |
+
# Reliable Agent
|
| 1231 |
+
""",
|
| 1232 |
+
encoding="utf-8",
|
| 1233 |
+
)
|
| 1234 |
+
graph = nx.Graph()
|
| 1235 |
+
for slug in ("thin-agent", "reliable-agent"):
|
| 1236 |
+
graph.add_node(
|
| 1237 |
+
f"harness:{slug}",
|
| 1238 |
+
label=slug,
|
| 1239 |
+
type="harness",
|
| 1240 |
+
tags=["agents"],
|
| 1241 |
+
)
|
| 1242 |
+
monkeypatch.setattr(ci, "_load_recommendation_graph", lambda: graph)
|
| 1243 |
+
import ctx_config
|
| 1244 |
+
|
| 1245 |
+
monkeypatch.setattr(
|
| 1246 |
+
ctx_config,
|
| 1247 |
+
"cfg",
|
| 1248 |
+
SimpleNamespace(
|
| 1249 |
+
wiki_dir=wiki,
|
| 1250 |
+
claude_dir=tmp_path / ".claude",
|
| 1251 |
+
recommendation_top_k=5,
|
| 1252 |
+
harness_recommendation_min_fit_score=0.20,
|
| 1253 |
+
harness_reliability_weights={
|
| 1254 |
+
"context": 0.34,
|
| 1255 |
+
"constraints": 0.33,
|
| 1256 |
+
"convergence": 0.33,
|
| 1257 |
+
},
|
| 1258 |
+
),
|
| 1259 |
+
)
|
| 1260 |
+
|
| 1261 |
+
results = ci.recommend_harnesses(
|
| 1262 |
+
"openai agent workflow",
|
| 1263 |
+
model_provider="openai",
|
| 1264 |
+
model="openai/gpt-5.5",
|
| 1265 |
+
)
|
| 1266 |
+
|
| 1267 |
+
assert [row["name"] for row in results[:2]] == [
|
| 1268 |
+
"reliable-agent",
|
| 1269 |
+
"thin-agent",
|
| 1270 |
+
]
|
| 1271 |
+
assert results[0]["fit_score"] == results[1]["fit_score"]
|
| 1272 |
+
assert results[0]["reliability_score"] > results[1]["reliability_score"]
|
| 1273 |
+
|
| 1274 |
+
|
| 1275 |
+
def test_recommend_harnesses_avoids_semantic_model_load_by_default(
|
| 1276 |
+
tmp_path: Path,
|
| 1277 |
+
monkeypatch,
|
| 1278 |
+
) -> None:
|
| 1279 |
+
graph = nx.Graph()
|
| 1280 |
+
graph.add_node("harness:langgraph", label="langgraph", type="harness")
|
| 1281 |
+
monkeypatch.setattr(ci, "_load_recommendation_graph", lambda: graph)
|
| 1282 |
+
monkeypatch.setattr(ci, "_harness_supports_provider", lambda *args, **kwargs: True)
|
| 1283 |
+
monkeypatch.setattr(ci, "_installed_harness_slugs", lambda _path: set())
|
| 1284 |
+
monkeypatch.setattr(
|
| 1285 |
+
ci,
|
| 1286 |
+
"_annotate_harness_fit",
|
| 1287 |
+
lambda *_args, **_kwargs: {"fit_score": 0.99, "fit_signals": ["agent"]},
|
| 1288 |
+
)
|
| 1289 |
+
import ctx_config
|
| 1290 |
+
|
| 1291 |
+
monkeypatch.setattr(
|
| 1292 |
+
ctx_config,
|
| 1293 |
+
"cfg",
|
| 1294 |
+
SimpleNamespace(
|
| 1295 |
+
claude_dir=tmp_path / ".claude",
|
| 1296 |
+
recommendation_top_k=5,
|
| 1297 |
+
harness_recommendation_min_fit_score=0.85,
|
| 1298 |
+
),
|
| 1299 |
+
)
|
| 1300 |
+
calls: dict[str, object] = {}
|
| 1301 |
+
|
| 1302 |
+
def fake_recommend_by_tags(*_args, **kwargs):
|
| 1303 |
+
calls.update(kwargs)
|
| 1304 |
+
return [{"name": "langgraph", "type": "harness", "score": 1.0}]
|
| 1305 |
+
|
| 1306 |
+
monkeypatch.setitem(
|
| 1307 |
+
sys.modules,
|
| 1308 |
+
"ctx.core.resolve.recommendations",
|
| 1309 |
+
type(
|
| 1310 |
+
"FakeRecommendModule",
|
| 1311 |
+
(),
|
| 1312 |
+
{
|
| 1313 |
+
"query_to_tags": staticmethod(lambda _query: ["agent"]),
|
| 1314 |
+
"recommend_by_tags": staticmethod(fake_recommend_by_tags),
|
| 1315 |
+
},
|
| 1316 |
+
),
|
| 1317 |
+
)
|
| 1318 |
+
|
| 1319 |
+
results = ci.recommend_harnesses(
|
| 1320 |
+
"build an agent workflow",
|
| 1321 |
+
model_provider="openai",
|
| 1322 |
+
model="openai/gpt-5.5",
|
| 1323 |
+
)
|
| 1324 |
+
|
| 1325 |
+
assert results[0]["name"] == "langgraph"
|
| 1326 |
+
assert calls["query"] == "build an agent workflow"
|
| 1327 |
+
assert calls["entity_types"] == ("harness",)
|
| 1328 |
+
assert calls["use_semantic_query"] is False
|
| 1329 |
+
|
| 1330 |
+
|
| 1331 |
+
def test_main_custom_model_requires_model(tmp_path: Path, monkeypatch) -> None:
|
| 1332 |
+
monkeypatch.setattr(ci, "_claude_dir", lambda: tmp_path)
|
| 1333 |
+
monkeypatch.setattr(ci, "seed_toolboxes", lambda force=False: 0)
|
| 1334 |
+
|
| 1335 |
+
assert ci.main(["--model-mode", "custom"]) == 1
|
| 1336 |
+
|
| 1337 |
+
|
| 1338 |
+
def test_validate_model_flag_invokes_connection_check(
|
| 1339 |
+
tmp_path: Path,
|
| 1340 |
+
monkeypatch,
|
| 1341 |
+
) -> None:
|
| 1342 |
+
monkeypatch.setattr(ci, "_claude_dir", lambda: tmp_path)
|
| 1343 |
+
monkeypatch.setattr(ci, "seed_toolboxes", lambda force=False: 0)
|
| 1344 |
+
monkeypatch.setattr(
|
| 1345 |
+
ci,
|
| 1346 |
+
"recommend_harnesses",
|
| 1347 |
+
lambda goal, top_k=5, model_provider=None, model=None: [],
|
| 1348 |
+
)
|
| 1349 |
+
calls: list[dict] = []
|
| 1350 |
+
|
| 1351 |
+
def fake_validate(**kwargs):
|
| 1352 |
+
calls.append(kwargs)
|
| 1353 |
+
return 0
|
| 1354 |
+
|
| 1355 |
+
monkeypatch.setattr(ci, "validate_model_connection", fake_validate)
|
| 1356 |
+
|
| 1357 |
+
rc = ci.main([
|
| 1358 |
+
"--model-mode", "custom",
|
| 1359 |
+
"--model", "ollama/llama3.1",
|
| 1360 |
+
"--validate-model",
|
| 1361 |
+
])
|
| 1362 |
+
|
| 1363 |
+
assert rc == 0
|
| 1364 |
+
assert calls == [{
|
| 1365 |
+
"model": "ollama/llama3.1",
|
| 1366 |
+
"api_key_env": None,
|
| 1367 |
+
"base_url": None,
|
| 1368 |
+
}]
|
src/tests/test_dedup_check.py
CHANGED
|
@@ -1,286 +1,286 @@
|
|
| 1 |
-
"""test_dedup_check.py — unit tests for the dedup gate.
|
| 2 |
-
|
| 3 |
-
Covers:
|
| 4 |
-
- allowlist parsing (comments, malformed lines, slug ordering)
|
| 5 |
-
- state load/save (round-trip, version mismatch, threshold mismatch)
|
| 6 |
-
- find_high_similarity_pairs (chunking, threshold filtering, dedup)
|
| 7 |
-
- end-to-end orchestration on a synthetic fixture
|
| 8 |
-
- markdown + JSON report rendering
|
| 9 |
-
- exit code behavior
|
| 10 |
-
"""
|
| 11 |
-
|
| 12 |
-
from __future__ import annotations
|
| 13 |
-
|
| 14 |
-
import sys
|
| 15 |
-
from pathlib import Path
|
| 16 |
-
|
| 17 |
-
import numpy as np
|
| 18 |
-
|
| 19 |
-
SRC_DIR = Path(__file__).resolve().parents[1]
|
| 20 |
-
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 ──────────────────────────────────────────────────────────
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
def test_allowlist_parses_comments_and_blanks(tmp_path: Path) -> None:
|
| 30 |
-
p = tmp_path / "allow.txt"
|
| 31 |
-
p.write_text(
|
| 32 |
-
"\n".join([
|
| 33 |
-
"# header comment",
|
| 34 |
-
"",
|
| 35 |
-
"alpha beta # legitimate distinct",
|
| 36 |
-
" gamma delta",
|
| 37 |
-
"# trailing comment",
|
| 38 |
-
]),
|
| 39 |
-
encoding="utf-8",
|
| 40 |
-
)
|
| 41 |
-
assert dc.load_allowlist(p) == {("alpha", "beta"), ("delta", "gamma")}
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
def test_allowlist_canonicalises_slug_order(tmp_path: Path) -> None:
|
| 45 |
-
p = tmp_path / "allow.txt"
|
| 46 |
-
p.write_text("zebra apple\n", encoding="utf-8")
|
| 47 |
-
# Stored canonical (low, high) regardless of file order
|
| 48 |
-
assert dc.load_allowlist(p) == {("apple", "zebra")}
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
def test_allowlist_returns_empty_when_missing(tmp_path: Path) -> None:
|
| 52 |
-
assert dc.load_allowlist(tmp_path / "does-not-exist.txt") == set()
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
def test_allowlist_skips_malformed_lines(tmp_path: Path) -> None:
|
| 56 |
-
p = tmp_path / "allow.txt"
|
| 57 |
-
p.write_text("only-one-token\n", encoding="utf-8")
|
| 58 |
-
assert dc.load_allowlist(p) == set()
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
# ── State ──────────────────────────────────────────────────────────────
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
def test_state_round_trip(tmp_path: Path) -> None:
|
| 65 |
-
s = dc.DedupState(
|
| 66 |
-
version=dc.DEDUP_STATE_VERSION,
|
| 67 |
-
model_id="m1",
|
| 68 |
-
threshold=0.85,
|
| 69 |
-
entity_hashes={"skill:a": "h1"},
|
| 70 |
-
last_findings=[{"a": "skill:a", "b": "skill:b"}],
|
| 71 |
-
)
|
| 72 |
-
dc.save_state(tmp_path, s)
|
| 73 |
-
loaded = dc.load_state(tmp_path, model_id="m1", threshold=0.85)
|
| 74 |
-
assert loaded.entity_hashes == {"skill:a": "h1"}
|
| 75 |
-
assert loaded.threshold == 0.85
|
| 76 |
-
assert loaded.model_id == "m1"
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
def test_state_invalidates_on_model_change(tmp_path: Path) -> None:
|
| 80 |
-
s = dc.DedupState(
|
| 81 |
-
version=dc.DEDUP_STATE_VERSION,
|
| 82 |
-
model_id="m1", threshold=0.85,
|
| 83 |
-
entity_hashes={"skill:a": "h1"}, last_findings=[],
|
| 84 |
-
)
|
| 85 |
-
dc.save_state(tmp_path, s)
|
| 86 |
-
loaded = dc.load_state(tmp_path, model_id="m2", threshold=0.85)
|
| 87 |
-
assert loaded.entity_hashes == {}, "model change must invalidate state"
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
def test_state_invalidates_on_threshold_change(tmp_path: Path) -> None:
|
| 91 |
-
s = dc.DedupState(
|
| 92 |
-
version=dc.DEDUP_STATE_VERSION,
|
| 93 |
-
model_id="m1", threshold=0.85,
|
| 94 |
-
entity_hashes={"skill:a": "h1"}, last_findings=[],
|
| 95 |
-
)
|
| 96 |
-
dc.save_state(tmp_path, s)
|
| 97 |
-
loaded = dc.load_state(tmp_path, model_id="m1", threshold=0.90)
|
| 98 |
-
assert loaded.entity_hashes == {}, "threshold change must invalidate state"
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
def test_state_returns_empty_when_missing(tmp_path: Path) -> None:
|
| 102 |
-
out = dc.load_state(tmp_path, model_id="m1", threshold=0.85)
|
| 103 |
-
assert out.entity_hashes == {}
|
| 104 |
-
assert out.threshold == 0.85
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
# ── Pair finding ───────────────────────────────────────────────────────
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
def test_find_high_similarity_pairs_emits_each_pair_once() -> None:
|
| 111 |
-
"""A symmetric similarity matrix must produce N(N-1)/2 pairs at most,
|
| 112 |
-
not N² (no double-emission).
|
| 113 |
-
"""
|
| 114 |
-
# Three identical vectors → all three pairs are perfectly similar
|
| 115 |
-
vecs = np.array([
|
| 116 |
-
[1.0, 0.0, 0.0],
|
| 117 |
-
[1.0, 0.0, 0.0],
|
| 118 |
-
[1.0, 0.0, 0.0],
|
| 119 |
-
], dtype="float32")
|
| 120 |
-
# L2 already normalised
|
| 121 |
-
entities = [
|
| 122 |
-
dc.EntityRef(node_id=f"skill:{s}", type="skill", slug=s,
|
| 123 |
-
path=Path(f"/{s}.md"), description=s, tags=())
|
| 124 |
-
for s in ["a", "b", "c"]
|
| 125 |
-
]
|
| 126 |
-
pairs = dc.find_high_similarity_pairs(entities, vecs, threshold=0.99)
|
| 127 |
-
assert len(pairs) == 3, "expected exactly 3 pairs for 3 entities"
|
| 128 |
-
seen = {(i, j) for i, j, _ in pairs}
|
| 129 |
-
assert seen == {(0, 1), (0, 2), (1, 2)}
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
def test_find_high_similarity_pairs_threshold_filters() -> None:
|
| 133 |
-
"""Below-threshold pairs must not appear."""
|
| 134 |
-
# Two orthogonal vectors → cosine = 0
|
| 135 |
-
vecs = np.array([[1.0, 0.0], [0.0, 1.0]], dtype="float32")
|
| 136 |
-
entities = [
|
| 137 |
-
dc.EntityRef(node_id=f"skill:{s}", type="skill", slug=s,
|
| 138 |
-
path=Path(f"/{s}.md"), description=s, tags=())
|
| 139 |
-
for s in ["a", "b"]
|
| 140 |
-
]
|
| 141 |
-
pairs = dc.find_high_similarity_pairs(entities, vecs, threshold=0.50)
|
| 142 |
-
assert pairs == [], "orthogonal vectors must not produce a pair at any threshold > 0"
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
def test_find_high_similarity_pairs_chunking_consistent() -> None:
|
| 146 |
-
"""Different chunk sizes must produce the same result."""
|
| 147 |
-
rng = np.random.default_rng(42)
|
| 148 |
-
n = 50
|
| 149 |
-
raw = rng.standard_normal((n, 8)).astype("float32")
|
| 150 |
-
norms = np.linalg.norm(raw, axis=1, keepdims=True)
|
| 151 |
-
norms[norms == 0] = 1.0
|
| 152 |
-
vecs = raw / norms
|
| 153 |
-
entities = [
|
| 154 |
-
dc.EntityRef(node_id=f"skill:e{i}", type="skill", slug=f"e{i}",
|
| 155 |
-
path=Path(f"/e{i}.md"), description="", tags=())
|
| 156 |
-
for i in range(n)
|
| 157 |
-
]
|
| 158 |
-
a = sorted(dc.find_high_similarity_pairs(entities, vecs, threshold=0.5, chunk_size=8))
|
| 159 |
-
b = sorted(dc.find_high_similarity_pairs(entities, vecs, threshold=0.5, chunk_size=200))
|
| 160 |
-
assert [(i, j) for i, j, _ in a] == [(i, j) for i, j, _ in b], (
|
| 161 |
-
"chunked + unchunked runs must produce identical pair sets"
|
| 162 |
-
)
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
# ── Markdown rendering ────────────────────────────────────────────────
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
def test_render_markdown_with_no_findings() -> None:
|
| 169 |
-
rep = dc.DedupReport(
|
| 170 |
-
threshold=0.85, model_id="m1",
|
| 171 |
-
total_entities=10, pairs_evaluated=45,
|
| 172 |
-
)
|
| 173 |
-
md = dc.render_markdown(rep)
|
| 174 |
-
assert "No actionable findings" in md
|
| 175 |
-
assert "0.85" in md
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
def test_render_markdown_caps_at_top_n() -> None:
|
| 179 |
-
refs = [
|
| 180 |
-
dc.EntityRef(node_id=f"skill:e{i}", type="skill", slug=f"e{i}",
|
| 181 |
-
path=Path(f"/e{i}.md"), description=f"desc{i}", tags=())
|
| 182 |
-
for i in range(150)
|
| 183 |
-
]
|
| 184 |
-
pairs = [
|
| 185 |
-
dc.DedupPair(a=refs[i], b=refs[i + 1],
|
| 186 |
-
similarity=0.99 - i * 0.0001, shared_tags=())
|
| 187 |
-
for i in range(149)
|
| 188 |
-
]
|
| 189 |
-
rep = dc.DedupReport(
|
| 190 |
-
threshold=0.85, model_id="m1",
|
| 191 |
-
total_entities=150, pairs_evaluated=149,
|
| 192 |
-
findings=pairs,
|
| 193 |
-
)
|
| 194 |
-
md = dc.render_markdown(rep, top_n=10)
|
| 195 |
-
# Header acknowledges the cap
|
| 196 |
-
assert "Showing" in md and "top 10" in md
|
| 197 |
-
# Body has at most top_n ### headers
|
| 198 |
-
headers = [line for line in md.splitlines() if line.startswith("### ")]
|
| 199 |
-
assert len(headers) == 10, f"expected 10 finding headers, got {len(headers)}"
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
def test_incremental_skips_unchanged_pairs(tmp_path: Path) -> None:
|
| 203 |
-
"""First run: full pass, state saved. Second run with same hashes:
|
| 204 |
-
every prior finding carries forward without recomputation, and only
|
| 205 |
-
pairs touching changed/new entities are recomputed.
|
| 206 |
-
"""
|
| 207 |
-
import numpy as np
|
| 208 |
-
|
| 209 |
-
cache_dir = tmp_path / "cache"
|
| 210 |
-
cache_dir.mkdir()
|
| 211 |
-
# Build a tiny embeddings.npz + topk-state.json the loader can read.
|
| 212 |
-
refs = [
|
| 213 |
-
dc.EntityRef(
|
| 214 |
-
node_id=f"skill:e{i}", type="skill", slug=f"e{i}",
|
| 215 |
-
path=tmp_path / f"e{i}.md", description=f"d{i}", tags=("t",),
|
| 216 |
-
)
|
| 217 |
-
for i in range(3)
|
| 218 |
-
]
|
| 219 |
-
# Vectors: e0/e1 are nearly identical (cosine ~1.0); e2 is unrelated.
|
| 220 |
-
vecs = np.array([[1.0, 0.0], [0.999, 0.045], [0.0, 1.0]], dtype="float32")
|
| 221 |
-
|
| 222 |
-
# Save first state via run_dedup_check's normal save path: simulate a
|
| 223 |
-
# prior run by saving state directly with these hashes + finding.
|
| 224 |
-
hashes = {r.node_id: dc._entity_hash_for_state(r) for r in refs}
|
| 225 |
-
prior = dc.DedupState(
|
| 226 |
-
version=dc.DEDUP_STATE_VERSION,
|
| 227 |
-
model_id="test", threshold=0.85,
|
| 228 |
-
entity_hashes=hashes,
|
| 229 |
-
last_findings=[
|
| 230 |
-
{"a": "skill:e0", "b": "skill:e1", "similarity": 0.999},
|
| 231 |
-
],
|
| 232 |
-
)
|
| 233 |
-
dc.save_state(cache_dir, prior)
|
| 234 |
-
|
| 235 |
-
# All entities unchanged → unchanged_ids covers everyone → carry-forward
|
| 236 |
-
unchanged = {nid for nid, h in hashes.items() if prior.entity_hashes.get(nid) == h}
|
| 237 |
-
assert unchanged == {"skill:e0", "skill:e1", "skill:e2"}
|
| 238 |
-
|
| 239 |
-
# Verify _find_pairs_for_changed returns nothing when there are no
|
| 240 |
-
# changed entities (i.e. an incremental run with everything cached
|
| 241 |
-
# bypasses the expensive pairwise pass entirely).
|
| 242 |
-
pairs = dc._find_pairs_for_changed(refs, vecs, [], threshold=0.85)
|
| 243 |
-
assert pairs == []
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
def test_incremental_recomputes_when_entity_changed(tmp_path: Path) -> None:
|
| 247 |
-
"""When one entity's hash changes, pairs touching it must be
|
| 248 |
-
recomputed even if the prior state had carry-forward findings.
|
| 249 |
-
"""
|
| 250 |
-
import numpy as np
|
| 251 |
-
|
| 252 |
-
refs = [
|
| 253 |
-
dc.EntityRef(node_id=f"skill:e{i}", type="skill", slug=f"e{i}",
|
| 254 |
-
path=tmp_path / f"e{i}.md", description=f"d{i}", tags=())
|
| 255 |
-
for i in range(3)
|
| 256 |
-
]
|
| 257 |
-
vecs = np.array([[1.0, 0.0], [0.999, 0.045], [0.0, 1.0]], dtype="float32")
|
| 258 |
-
|
| 259 |
-
# Only e1 is "changed" (index 1); pairs computed only for rows
|
| 260 |
-
# involving index 1.
|
| 261 |
-
pairs = dc._find_pairs_for_changed(refs, vecs, [1], threshold=0.85)
|
| 262 |
-
pair_keys = {(i, j) for i, j, _ in pairs}
|
| 263 |
-
# e0-e1 pair (0,1) must be present; e1-e2 pair would exist if cosine
|
| 264 |
-
# were >= 0.85 but the vectors here put it well below.
|
| 265 |
-
assert (0, 1) in pair_keys
|
| 266 |
-
# No (0, 2) pair since neither endpoint is changed.
|
| 267 |
-
assert (0, 2) not in pair_keys
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
def test_render_markdown_includes_distribution_buckets() -> None:
|
| 271 |
-
refs = [
|
| 272 |
-
dc.EntityRef(node_id=f"skill:e{i}", type="skill", slug=f"e{i}",
|
| 273 |
-
path=Path(f"/e{i}.md"), description="", tags=())
|
| 274 |
-
for i in range(4)
|
| 275 |
-
]
|
| 276 |
-
pairs = [
|
| 277 |
-
dc.DedupPair(a=refs[0], b=refs[1], similarity=0.995, shared_tags=()),
|
| 278 |
-
dc.DedupPair(a=refs[0], b=refs[2], similarity=0.93, shared_tags=()),
|
| 279 |
-
dc.DedupPair(a=refs[0], b=refs[3], similarity=0.86, shared_tags=()),
|
| 280 |
-
]
|
| 281 |
-
rep = dc.DedupReport(
|
| 282 |
-
threshold=0.85, model_id="m1",
|
| 283 |
-
total_entities=4, pairs_evaluated=6, findings=pairs,
|
| 284 |
-
)
|
| 285 |
-
md = dc.render_markdown(rep)
|
| 286 |
-
assert "≥0.99" in md and "0.90-0.95" in md and "0.85-0.90" in md
|
|
|
|
| 1 |
+
"""test_dedup_check.py — unit tests for the dedup gate.
|
| 2 |
+
|
| 3 |
+
Covers:
|
| 4 |
+
- allowlist parsing (comments, malformed lines, slug ordering)
|
| 5 |
+
- state load/save (round-trip, version mismatch, threshold mismatch)
|
| 6 |
+
- find_high_similarity_pairs (chunking, threshold filtering, dedup)
|
| 7 |
+
- end-to-end orchestration on a synthetic fixture
|
| 8 |
+
- markdown + JSON report rendering
|
| 9 |
+
- exit code behavior
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import sys
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
SRC_DIR = Path(__file__).resolve().parents[1]
|
| 20 |
+
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 ──────────────────────────────────────────────────────────
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_allowlist_parses_comments_and_blanks(tmp_path: Path) -> None:
|
| 30 |
+
p = tmp_path / "allow.txt"
|
| 31 |
+
p.write_text(
|
| 32 |
+
"\n".join([
|
| 33 |
+
"# header comment",
|
| 34 |
+
"",
|
| 35 |
+
"alpha beta # legitimate distinct",
|
| 36 |
+
" gamma delta",
|
| 37 |
+
"# trailing comment",
|
| 38 |
+
]),
|
| 39 |
+
encoding="utf-8",
|
| 40 |
+
)
|
| 41 |
+
assert dc.load_allowlist(p) == {("alpha", "beta"), ("delta", "gamma")}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_allowlist_canonicalises_slug_order(tmp_path: Path) -> None:
|
| 45 |
+
p = tmp_path / "allow.txt"
|
| 46 |
+
p.write_text("zebra apple\n", encoding="utf-8")
|
| 47 |
+
# Stored canonical (low, high) regardless of file order
|
| 48 |
+
assert dc.load_allowlist(p) == {("apple", "zebra")}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_allowlist_returns_empty_when_missing(tmp_path: Path) -> None:
|
| 52 |
+
assert dc.load_allowlist(tmp_path / "does-not-exist.txt") == set()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def test_allowlist_skips_malformed_lines(tmp_path: Path) -> None:
|
| 56 |
+
p = tmp_path / "allow.txt"
|
| 57 |
+
p.write_text("only-one-token\n", encoding="utf-8")
|
| 58 |
+
assert dc.load_allowlist(p) == set()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# ── State ──────────────────────────────────────────────────────────────
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_state_round_trip(tmp_path: Path) -> None:
|
| 65 |
+
s = dc.DedupState(
|
| 66 |
+
version=dc.DEDUP_STATE_VERSION,
|
| 67 |
+
model_id="m1",
|
| 68 |
+
threshold=0.85,
|
| 69 |
+
entity_hashes={"skill:a": "h1"},
|
| 70 |
+
last_findings=[{"a": "skill:a", "b": "skill:b"}],
|
| 71 |
+
)
|
| 72 |
+
dc.save_state(tmp_path, s)
|
| 73 |
+
loaded = dc.load_state(tmp_path, model_id="m1", threshold=0.85)
|
| 74 |
+
assert loaded.entity_hashes == {"skill:a": "h1"}
|
| 75 |
+
assert loaded.threshold == 0.85
|
| 76 |
+
assert loaded.model_id == "m1"
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_state_invalidates_on_model_change(tmp_path: Path) -> None:
|
| 80 |
+
s = dc.DedupState(
|
| 81 |
+
version=dc.DEDUP_STATE_VERSION,
|
| 82 |
+
model_id="m1", threshold=0.85,
|
| 83 |
+
entity_hashes={"skill:a": "h1"}, last_findings=[],
|
| 84 |
+
)
|
| 85 |
+
dc.save_state(tmp_path, s)
|
| 86 |
+
loaded = dc.load_state(tmp_path, model_id="m2", threshold=0.85)
|
| 87 |
+
assert loaded.entity_hashes == {}, "model change must invalidate state"
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def test_state_invalidates_on_threshold_change(tmp_path: Path) -> None:
|
| 91 |
+
s = dc.DedupState(
|
| 92 |
+
version=dc.DEDUP_STATE_VERSION,
|
| 93 |
+
model_id="m1", threshold=0.85,
|
| 94 |
+
entity_hashes={"skill:a": "h1"}, last_findings=[],
|
| 95 |
+
)
|
| 96 |
+
dc.save_state(tmp_path, s)
|
| 97 |
+
loaded = dc.load_state(tmp_path, model_id="m1", threshold=0.90)
|
| 98 |
+
assert loaded.entity_hashes == {}, "threshold change must invalidate state"
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def test_state_returns_empty_when_missing(tmp_path: Path) -> None:
|
| 102 |
+
out = dc.load_state(tmp_path, model_id="m1", threshold=0.85)
|
| 103 |
+
assert out.entity_hashes == {}
|
| 104 |
+
assert out.threshold == 0.85
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
# ── Pair finding ───────────────────────────────────────────────────────
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def test_find_high_similarity_pairs_emits_each_pair_once() -> None:
|
| 111 |
+
"""A symmetric similarity matrix must produce N(N-1)/2 pairs at most,
|
| 112 |
+
not N² (no double-emission).
|
| 113 |
+
"""
|
| 114 |
+
# Three identical vectors → all three pairs are perfectly similar
|
| 115 |
+
vecs = np.array([
|
| 116 |
+
[1.0, 0.0, 0.0],
|
| 117 |
+
[1.0, 0.0, 0.0],
|
| 118 |
+
[1.0, 0.0, 0.0],
|
| 119 |
+
], dtype="float32")
|
| 120 |
+
# L2 already normalised
|
| 121 |
+
entities = [
|
| 122 |
+
dc.EntityRef(node_id=f"skill:{s}", type="skill", slug=s,
|
| 123 |
+
path=Path(f"/{s}.md"), description=s, tags=())
|
| 124 |
+
for s in ["a", "b", "c"]
|
| 125 |
+
]
|
| 126 |
+
pairs = dc.find_high_similarity_pairs(entities, vecs, threshold=0.99)
|
| 127 |
+
assert len(pairs) == 3, "expected exactly 3 pairs for 3 entities"
|
| 128 |
+
seen = {(i, j) for i, j, _ in pairs}
|
| 129 |
+
assert seen == {(0, 1), (0, 2), (1, 2)}
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def test_find_high_similarity_pairs_threshold_filters() -> None:
|
| 133 |
+
"""Below-threshold pairs must not appear."""
|
| 134 |
+
# Two orthogonal vectors → cosine = 0
|
| 135 |
+
vecs = np.array([[1.0, 0.0], [0.0, 1.0]], dtype="float32")
|
| 136 |
+
entities = [
|
| 137 |
+
dc.EntityRef(node_id=f"skill:{s}", type="skill", slug=s,
|
| 138 |
+
path=Path(f"/{s}.md"), description=s, tags=())
|
| 139 |
+
for s in ["a", "b"]
|
| 140 |
+
]
|
| 141 |
+
pairs = dc.find_high_similarity_pairs(entities, vecs, threshold=0.50)
|
| 142 |
+
assert pairs == [], "orthogonal vectors must not produce a pair at any threshold > 0"
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def test_find_high_similarity_pairs_chunking_consistent() -> None:
|
| 146 |
+
"""Different chunk sizes must produce the same result."""
|
| 147 |
+
rng = np.random.default_rng(42)
|
| 148 |
+
n = 50
|
| 149 |
+
raw = rng.standard_normal((n, 8)).astype("float32")
|
| 150 |
+
norms = np.linalg.norm(raw, axis=1, keepdims=True)
|
| 151 |
+
norms[norms == 0] = 1.0
|
| 152 |
+
vecs = raw / norms
|
| 153 |
+
entities = [
|
| 154 |
+
dc.EntityRef(node_id=f"skill:e{i}", type="skill", slug=f"e{i}",
|
| 155 |
+
path=Path(f"/e{i}.md"), description="", tags=())
|
| 156 |
+
for i in range(n)
|
| 157 |
+
]
|
| 158 |
+
a = sorted(dc.find_high_similarity_pairs(entities, vecs, threshold=0.5, chunk_size=8))
|
| 159 |
+
b = sorted(dc.find_high_similarity_pairs(entities, vecs, threshold=0.5, chunk_size=200))
|
| 160 |
+
assert [(i, j) for i, j, _ in a] == [(i, j) for i, j, _ in b], (
|
| 161 |
+
"chunked + unchunked runs must produce identical pair sets"
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
# ── Markdown rendering ────────────────────────────────────────────────
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def test_render_markdown_with_no_findings() -> None:
|
| 169 |
+
rep = dc.DedupReport(
|
| 170 |
+
threshold=0.85, model_id="m1",
|
| 171 |
+
total_entities=10, pairs_evaluated=45,
|
| 172 |
+
)
|
| 173 |
+
md = dc.render_markdown(rep)
|
| 174 |
+
assert "No actionable findings" in md
|
| 175 |
+
assert "0.85" in md
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def test_render_markdown_caps_at_top_n() -> None:
|
| 179 |
+
refs = [
|
| 180 |
+
dc.EntityRef(node_id=f"skill:e{i}", type="skill", slug=f"e{i}",
|
| 181 |
+
path=Path(f"/e{i}.md"), description=f"desc{i}", tags=())
|
| 182 |
+
for i in range(150)
|
| 183 |
+
]
|
| 184 |
+
pairs = [
|
| 185 |
+
dc.DedupPair(a=refs[i], b=refs[i + 1],
|
| 186 |
+
similarity=0.99 - i * 0.0001, shared_tags=())
|
| 187 |
+
for i in range(149)
|
| 188 |
+
]
|
| 189 |
+
rep = dc.DedupReport(
|
| 190 |
+
threshold=0.85, model_id="m1",
|
| 191 |
+
total_entities=150, pairs_evaluated=149,
|
| 192 |
+
findings=pairs,
|
| 193 |
+
)
|
| 194 |
+
md = dc.render_markdown(rep, top_n=10)
|
| 195 |
+
# Header acknowledges the cap
|
| 196 |
+
assert "Showing" in md and "top 10" in md
|
| 197 |
+
# Body has at most top_n ### headers
|
| 198 |
+
headers = [line for line in md.splitlines() if line.startswith("### ")]
|
| 199 |
+
assert len(headers) == 10, f"expected 10 finding headers, got {len(headers)}"
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def test_incremental_skips_unchanged_pairs(tmp_path: Path) -> None:
|
| 203 |
+
"""First run: full pass, state saved. Second run with same hashes:
|
| 204 |
+
every prior finding carries forward without recomputation, and only
|
| 205 |
+
pairs touching changed/new entities are recomputed.
|
| 206 |
+
"""
|
| 207 |
+
import numpy as np
|
| 208 |
+
|
| 209 |
+
cache_dir = tmp_path / "cache"
|
| 210 |
+
cache_dir.mkdir()
|
| 211 |
+
# Build a tiny embeddings.npz + topk-state.json the loader can read.
|
| 212 |
+
refs = [
|
| 213 |
+
dc.EntityRef(
|
| 214 |
+
node_id=f"skill:e{i}", type="skill", slug=f"e{i}",
|
| 215 |
+
path=tmp_path / f"e{i}.md", description=f"d{i}", tags=("t",),
|
| 216 |
+
)
|
| 217 |
+
for i in range(3)
|
| 218 |
+
]
|
| 219 |
+
# Vectors: e0/e1 are nearly identical (cosine ~1.0); e2 is unrelated.
|
| 220 |
+
vecs = np.array([[1.0, 0.0], [0.999, 0.045], [0.0, 1.0]], dtype="float32")
|
| 221 |
+
|
| 222 |
+
# Save first state via run_dedup_check's normal save path: simulate a
|
| 223 |
+
# prior run by saving state directly with these hashes + finding.
|
| 224 |
+
hashes = {r.node_id: dc._entity_hash_for_state(r) for r in refs}
|
| 225 |
+
prior = dc.DedupState(
|
| 226 |
+
version=dc.DEDUP_STATE_VERSION,
|
| 227 |
+
model_id="test", threshold=0.85,
|
| 228 |
+
entity_hashes=hashes,
|
| 229 |
+
last_findings=[
|
| 230 |
+
{"a": "skill:e0", "b": "skill:e1", "similarity": 0.999},
|
| 231 |
+
],
|
| 232 |
+
)
|
| 233 |
+
dc.save_state(cache_dir, prior)
|
| 234 |
+
|
| 235 |
+
# All entities unchanged → unchanged_ids covers everyone → carry-forward
|
| 236 |
+
unchanged = {nid for nid, h in hashes.items() if prior.entity_hashes.get(nid) == h}
|
| 237 |
+
assert unchanged == {"skill:e0", "skill:e1", "skill:e2"}
|
| 238 |
+
|
| 239 |
+
# Verify _find_pairs_for_changed returns nothing when there are no
|
| 240 |
+
# changed entities (i.e. an incremental run with everything cached
|
| 241 |
+
# bypasses the expensive pairwise pass entirely).
|
| 242 |
+
pairs = dc._find_pairs_for_changed(refs, vecs, [], threshold=0.85)
|
| 243 |
+
assert pairs == []
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def test_incremental_recomputes_when_entity_changed(tmp_path: Path) -> None:
|
| 247 |
+
"""When one entity's hash changes, pairs touching it must be
|
| 248 |
+
recomputed even if the prior state had carry-forward findings.
|
| 249 |
+
"""
|
| 250 |
+
import numpy as np
|
| 251 |
+
|
| 252 |
+
refs = [
|
| 253 |
+
dc.EntityRef(node_id=f"skill:e{i}", type="skill", slug=f"e{i}",
|
| 254 |
+
path=tmp_path / f"e{i}.md", description=f"d{i}", tags=())
|
| 255 |
+
for i in range(3)
|
| 256 |
+
]
|
| 257 |
+
vecs = np.array([[1.0, 0.0], [0.999, 0.045], [0.0, 1.0]], dtype="float32")
|
| 258 |
+
|
| 259 |
+
# Only e1 is "changed" (index 1); pairs computed only for rows
|
| 260 |
+
# involving index 1.
|
| 261 |
+
pairs = dc._find_pairs_for_changed(refs, vecs, [1], threshold=0.85)
|
| 262 |
+
pair_keys = {(i, j) for i, j, _ in pairs}
|
| 263 |
+
# e0-e1 pair (0,1) must be present; e1-e2 pair would exist if cosine
|
| 264 |
+
# were >= 0.85 but the vectors here put it well below.
|
| 265 |
+
assert (0, 1) in pair_keys
|
| 266 |
+
# No (0, 2) pair since neither endpoint is changed.
|
| 267 |
+
assert (0, 2) not in pair_keys
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def test_render_markdown_includes_distribution_buckets() -> None:
|
| 271 |
+
refs = [
|
| 272 |
+
dc.EntityRef(node_id=f"skill:e{i}", type="skill", slug=f"e{i}",
|
| 273 |
+
path=Path(f"/e{i}.md"), description="", tags=())
|
| 274 |
+
for i in range(4)
|
| 275 |
+
]
|
| 276 |
+
pairs = [
|
| 277 |
+
dc.DedupPair(a=refs[0], b=refs[1], similarity=0.995, shared_tags=()),
|
| 278 |
+
dc.DedupPair(a=refs[0], b=refs[2], similarity=0.93, shared_tags=()),
|
| 279 |
+
dc.DedupPair(a=refs[0], b=refs[3], similarity=0.86, shared_tags=()),
|
| 280 |
+
]
|
| 281 |
+
rep = dc.DedupReport(
|
| 282 |
+
threshold=0.85, model_id="m1",
|
| 283 |
+
total_entities=4, pairs_evaluated=6, findings=pairs,
|
| 284 |
+
)
|
| 285 |
+
md = dc.render_markdown(rep)
|
| 286 |
+
assert "≥0.99" in md and "0.90-0.95" in md and "0.85-0.90" in md
|
src/tests/test_fs_utils.py
CHANGED
|
@@ -1,207 +1,207 @@
|
|
| 1 |
-
"""
|
| 2 |
-
test_fs_utils.py -- Tests for the shared atomic file-write helpers.
|
| 3 |
-
"""
|
| 4 |
-
|
| 5 |
-
from __future__ import annotations
|
| 6 |
-
|
| 7 |
-
import json
|
| 8 |
-
import os
|
| 9 |
-
import sys
|
| 10 |
-
import threading
|
| 11 |
-
from pathlib import Path
|
| 12 |
-
from unittest.mock import patch
|
| 13 |
-
|
| 14 |
-
import pytest
|
| 15 |
-
|
| 16 |
-
# Ensure src/ is on sys.path
|
| 17 |
-
_SRC = Path(__file__).resolve().parent.parent
|
| 18 |
-
if str(_SRC) not in sys.path:
|
| 19 |
-
sys.path.insert(0, str(_SRC))
|
| 20 |
-
|
| 21 |
-
from ctx.utils import _fs_utils as fs_utils # noqa: E402
|
| 22 |
-
from ctx.utils._fs_utils import atomic_write_bytes, atomic_write_json, atomic_write_text # noqa: E402
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
# ── atomic_write_text ─────────────────────────────────────────────────────────
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
def test_write_text_happy_path(tmp_path: Path) -> None:
|
| 29 |
-
target = tmp_path / "out.txt"
|
| 30 |
-
atomic_write_text(target, "hello world")
|
| 31 |
-
assert target.read_text(encoding="utf-8") == "hello world"
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
def test_write_text_creates_parent_dirs(tmp_path: Path) -> None:
|
| 35 |
-
target = tmp_path / "a" / "b" / "c" / "out.txt"
|
| 36 |
-
atomic_write_text(target, "nested")
|
| 37 |
-
assert target.read_text(encoding="utf-8") == "nested"
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
def test_write_text_overwrites_existing(tmp_path: Path) -> None:
|
| 41 |
-
target = tmp_path / "out.txt"
|
| 42 |
-
target.write_text("old", encoding="utf-8")
|
| 43 |
-
atomic_write_text(target, "new")
|
| 44 |
-
assert target.read_text(encoding="utf-8") == "new"
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
def test_write_text_custom_encoding(tmp_path: Path) -> None:
|
| 48 |
-
target = tmp_path / "out.txt"
|
| 49 |
-
text = "caf\u00e9" # contains non-ASCII
|
| 50 |
-
atomic_write_text(target, text, encoding="utf-8")
|
| 51 |
-
assert target.read_text(encoding="utf-8") == text
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
def test_write_text_no_temp_file_left_on_success(tmp_path: Path) -> None:
|
| 55 |
-
target = tmp_path / "out.txt"
|
| 56 |
-
atomic_write_text(target, "data")
|
| 57 |
-
leftover = list(tmp_path.glob("out.txt.*"))
|
| 58 |
-
assert leftover == [], f"Unexpected temp files: {leftover}"
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
def test_write_text_no_temp_file_left_on_error(tmp_path: Path) -> None:
|
| 62 |
-
"""Temp file must be cleaned up even when os.replace raises."""
|
| 63 |
-
target = tmp_path / "out.txt"
|
| 64 |
-
with patch("ctx.utils._fs_utils._replace_with_retry", side_effect=OSError("boom")):
|
| 65 |
-
with pytest.raises(OSError, match="boom"):
|
| 66 |
-
atomic_write_text(target, "data")
|
| 67 |
-
leftover = list(tmp_path.glob("out.txt.*"))
|
| 68 |
-
assert leftover == [], f"Temp file leaked: {leftover}"
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
def test_write_text_fsyncs_temp_before_replace_and_parent_after(
|
| 72 |
-
tmp_path: Path,
|
| 73 |
-
monkeypatch: pytest.MonkeyPatch,
|
| 74 |
-
) -> None:
|
| 75 |
-
target = tmp_path / "out.txt"
|
| 76 |
-
events: list[str] = []
|
| 77 |
-
|
| 78 |
-
def record_fsync(_fd: int) -> None:
|
| 79 |
-
events.append("fsync")
|
| 80 |
-
|
| 81 |
-
def record_replace(
|
| 82 |
-
src: str,
|
| 83 |
-
dst: Path,
|
| 84 |
-
*,
|
| 85 |
-
attempts: int = 10,
|
| 86 |
-
delay: float = 0.05,
|
| 87 |
-
) -> None:
|
| 88 |
-
del attempts, delay
|
| 89 |
-
events.append("replace")
|
| 90 |
-
os.replace(src, dst)
|
| 91 |
-
|
| 92 |
-
def record_parent_fsync(path: Path) -> None:
|
| 93 |
-
assert path == target.parent
|
| 94 |
-
events.append("parent-fsync")
|
| 95 |
-
|
| 96 |
-
monkeypatch.setattr(fs_utils.os, "fsync", record_fsync)
|
| 97 |
-
monkeypatch.setattr(fs_utils, "_replace_with_retry", record_replace)
|
| 98 |
-
monkeypatch.setattr(fs_utils, "_fsync_parent_dir", record_parent_fsync, raising=False)
|
| 99 |
-
|
| 100 |
-
atomic_write_text(target, "durable")
|
| 101 |
-
|
| 102 |
-
assert events == ["fsync", "replace", "parent-fsync"]
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
# ── atomic_write_bytes ────────────────────────────────────────────────────────
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
def test_write_bytes_happy_path(tmp_path: Path) -> None:
|
| 109 |
-
target = tmp_path / "out.bin"
|
| 110 |
-
atomic_write_bytes(target, b"\x00\x01\x02\x03")
|
| 111 |
-
assert target.read_bytes() == b"\x00\x01\x02\x03"
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
def test_write_bytes_creates_parent_dirs(tmp_path: Path) -> None:
|
| 115 |
-
target = tmp_path / "deep" / "out.bin"
|
| 116 |
-
atomic_write_bytes(target, b"bytes")
|
| 117 |
-
assert target.read_bytes() == b"bytes"
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
# ── atomic_write_json ─────────────────────────────────────────────────────────
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
def test_write_json_happy_path(tmp_path: Path) -> None:
|
| 124 |
-
target = tmp_path / "data.json"
|
| 125 |
-
obj = {"key": "value", "num": 42}
|
| 126 |
-
atomic_write_json(target, obj)
|
| 127 |
-
loaded = json.loads(target.read_text(encoding="utf-8"))
|
| 128 |
-
assert loaded == obj
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
def test_write_json_trailing_newline(tmp_path: Path) -> None:
|
| 132 |
-
target = tmp_path / "data.json"
|
| 133 |
-
atomic_write_json(target, {"x": 1})
|
| 134 |
-
assert target.read_text(encoding="utf-8").endswith("\n")
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
def test_write_json_custom_indent(tmp_path: Path) -> None:
|
| 138 |
-
target = tmp_path / "data.json"
|
| 139 |
-
atomic_write_json(target, {"a": 1}, indent=4)
|
| 140 |
-
raw = target.read_text(encoding="utf-8")
|
| 141 |
-
assert ' "a"' in raw # 4-space indent present
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
def test_write_json_none_indent(tmp_path: Path) -> None:
|
| 145 |
-
target = tmp_path / "data.json"
|
| 146 |
-
atomic_write_json(target, {"a": 1}, indent=None)
|
| 147 |
-
raw = target.read_text(encoding="utf-8").strip()
|
| 148 |
-
assert raw == '{"a": 1}'
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
# ── Windows retry ─────────────────────────────────────────────────────────────
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
def test_replace_retries_on_permission_error(tmp_path: Path) -> None:
|
| 155 |
-
"""_replace_with_retry should succeed on the second attempt."""
|
| 156 |
-
target = tmp_path / "out.txt"
|
| 157 |
-
call_count = 0
|
| 158 |
-
real_replace = os.replace
|
| 159 |
-
|
| 160 |
-
def flaky_replace(src: str, dst: Path) -> None:
|
| 161 |
-
nonlocal call_count
|
| 162 |
-
call_count += 1
|
| 163 |
-
if call_count == 1:
|
| 164 |
-
raise PermissionError("locked")
|
| 165 |
-
real_replace(src, dst)
|
| 166 |
-
|
| 167 |
-
with patch("ctx.utils._fs_utils.os.replace", side_effect=flaky_replace):
|
| 168 |
-
with patch("ctx.utils._fs_utils.time.sleep"): # don't actually sleep
|
| 169 |
-
atomic_write_text(target, "retry-test")
|
| 170 |
-
|
| 171 |
-
assert call_count == 2
|
| 172 |
-
assert target.read_text(encoding="utf-8") == "retry-test"
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
def test_replace_raises_after_max_attempts(tmp_path: Path) -> None:
|
| 176 |
-
"""After exhausting retries, the PermissionError must propagate."""
|
| 177 |
-
target = tmp_path / "out.txt"
|
| 178 |
-
|
| 179 |
-
with patch("ctx.utils._fs_utils.os.replace", side_effect=PermissionError("always locked")):
|
| 180 |
-
with patch("ctx.utils._fs_utils.time.sleep"):
|
| 181 |
-
with pytest.raises(PermissionError, match="always locked"):
|
| 182 |
-
atomic_write_text(target, "data")
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
# ── Concurrency smoke test ────────────────────────────────────────────────────
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
def test_concurrent_writes_last_write_wins(tmp_path: Path) -> None:
|
| 189 |
-
"""Multiple threads writing to the same path must not leave corruption."""
|
| 190 |
-
target = tmp_path / "shared.txt"
|
| 191 |
-
errors: list[Exception] = []
|
| 192 |
-
|
| 193 |
-
def writer(content: str) -> None:
|
| 194 |
-
try:
|
| 195 |
-
atomic_write_text(target, content)
|
| 196 |
-
except Exception as exc:
|
| 197 |
-
errors.append(exc)
|
| 198 |
-
|
| 199 |
-
threads = [threading.Thread(target=writer, args=(f"thread-{i}",)) for i in range(8)]
|
| 200 |
-
for t in threads:
|
| 201 |
-
t.start()
|
| 202 |
-
for t in threads:
|
| 203 |
-
t.join()
|
| 204 |
-
|
| 205 |
-
assert errors == [], f"Writer threads raised: {errors}"
|
| 206 |
-
content = target.read_text(encoding="utf-8")
|
| 207 |
-
assert content.startswith("thread-")
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_fs_utils.py -- Tests for the shared atomic file-write helpers.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
import threading
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from unittest.mock import patch
|
| 13 |
+
|
| 14 |
+
import pytest
|
| 15 |
+
|
| 16 |
+
# Ensure src/ is on sys.path
|
| 17 |
+
_SRC = Path(__file__).resolve().parent.parent
|
| 18 |
+
if str(_SRC) not in sys.path:
|
| 19 |
+
sys.path.insert(0, str(_SRC))
|
| 20 |
+
|
| 21 |
+
from ctx.utils import _fs_utils as fs_utils # noqa: E402
|
| 22 |
+
from ctx.utils._fs_utils import atomic_write_bytes, atomic_write_json, atomic_write_text # noqa: E402
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# ── atomic_write_text ─────────────────────────────────────────────────────────
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_write_text_happy_path(tmp_path: Path) -> None:
|
| 29 |
+
target = tmp_path / "out.txt"
|
| 30 |
+
atomic_write_text(target, "hello world")
|
| 31 |
+
assert target.read_text(encoding="utf-8") == "hello world"
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_write_text_creates_parent_dirs(tmp_path: Path) -> None:
|
| 35 |
+
target = tmp_path / "a" / "b" / "c" / "out.txt"
|
| 36 |
+
atomic_write_text(target, "nested")
|
| 37 |
+
assert target.read_text(encoding="utf-8") == "nested"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_write_text_overwrites_existing(tmp_path: Path) -> None:
|
| 41 |
+
target = tmp_path / "out.txt"
|
| 42 |
+
target.write_text("old", encoding="utf-8")
|
| 43 |
+
atomic_write_text(target, "new")
|
| 44 |
+
assert target.read_text(encoding="utf-8") == "new"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def test_write_text_custom_encoding(tmp_path: Path) -> None:
|
| 48 |
+
target = tmp_path / "out.txt"
|
| 49 |
+
text = "caf\u00e9" # contains non-ASCII
|
| 50 |
+
atomic_write_text(target, text, encoding="utf-8")
|
| 51 |
+
assert target.read_text(encoding="utf-8") == text
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_write_text_no_temp_file_left_on_success(tmp_path: Path) -> None:
|
| 55 |
+
target = tmp_path / "out.txt"
|
| 56 |
+
atomic_write_text(target, "data")
|
| 57 |
+
leftover = list(tmp_path.glob("out.txt.*"))
|
| 58 |
+
assert leftover == [], f"Unexpected temp files: {leftover}"
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def test_write_text_no_temp_file_left_on_error(tmp_path: Path) -> None:
|
| 62 |
+
"""Temp file must be cleaned up even when os.replace raises."""
|
| 63 |
+
target = tmp_path / "out.txt"
|
| 64 |
+
with patch("ctx.utils._fs_utils._replace_with_retry", side_effect=OSError("boom")):
|
| 65 |
+
with pytest.raises(OSError, match="boom"):
|
| 66 |
+
atomic_write_text(target, "data")
|
| 67 |
+
leftover = list(tmp_path.glob("out.txt.*"))
|
| 68 |
+
assert leftover == [], f"Temp file leaked: {leftover}"
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def test_write_text_fsyncs_temp_before_replace_and_parent_after(
|
| 72 |
+
tmp_path: Path,
|
| 73 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 74 |
+
) -> None:
|
| 75 |
+
target = tmp_path / "out.txt"
|
| 76 |
+
events: list[str] = []
|
| 77 |
+
|
| 78 |
+
def record_fsync(_fd: int) -> None:
|
| 79 |
+
events.append("fsync")
|
| 80 |
+
|
| 81 |
+
def record_replace(
|
| 82 |
+
src: str,
|
| 83 |
+
dst: Path,
|
| 84 |
+
*,
|
| 85 |
+
attempts: int = 10,
|
| 86 |
+
delay: float = 0.05,
|
| 87 |
+
) -> None:
|
| 88 |
+
del attempts, delay
|
| 89 |
+
events.append("replace")
|
| 90 |
+
os.replace(src, dst)
|
| 91 |
+
|
| 92 |
+
def record_parent_fsync(path: Path) -> None:
|
| 93 |
+
assert path == target.parent
|
| 94 |
+
events.append("parent-fsync")
|
| 95 |
+
|
| 96 |
+
monkeypatch.setattr(fs_utils.os, "fsync", record_fsync)
|
| 97 |
+
monkeypatch.setattr(fs_utils, "_replace_with_retry", record_replace)
|
| 98 |
+
monkeypatch.setattr(fs_utils, "_fsync_parent_dir", record_parent_fsync, raising=False)
|
| 99 |
+
|
| 100 |
+
atomic_write_text(target, "durable")
|
| 101 |
+
|
| 102 |
+
assert events == ["fsync", "replace", "parent-fsync"]
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# ── atomic_write_bytes ────────────────────────────────────────────────────────
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def test_write_bytes_happy_path(tmp_path: Path) -> None:
|
| 109 |
+
target = tmp_path / "out.bin"
|
| 110 |
+
atomic_write_bytes(target, b"\x00\x01\x02\x03")
|
| 111 |
+
assert target.read_bytes() == b"\x00\x01\x02\x03"
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def test_write_bytes_creates_parent_dirs(tmp_path: Path) -> None:
|
| 115 |
+
target = tmp_path / "deep" / "out.bin"
|
| 116 |
+
atomic_write_bytes(target, b"bytes")
|
| 117 |
+
assert target.read_bytes() == b"bytes"
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# ── atomic_write_json ─────────────────────────────────────────────────────────
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def test_write_json_happy_path(tmp_path: Path) -> None:
|
| 124 |
+
target = tmp_path / "data.json"
|
| 125 |
+
obj = {"key": "value", "num": 42}
|
| 126 |
+
atomic_write_json(target, obj)
|
| 127 |
+
loaded = json.loads(target.read_text(encoding="utf-8"))
|
| 128 |
+
assert loaded == obj
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def test_write_json_trailing_newline(tmp_path: Path) -> None:
|
| 132 |
+
target = tmp_path / "data.json"
|
| 133 |
+
atomic_write_json(target, {"x": 1})
|
| 134 |
+
assert target.read_text(encoding="utf-8").endswith("\n")
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def test_write_json_custom_indent(tmp_path: Path) -> None:
|
| 138 |
+
target = tmp_path / "data.json"
|
| 139 |
+
atomic_write_json(target, {"a": 1}, indent=4)
|
| 140 |
+
raw = target.read_text(encoding="utf-8")
|
| 141 |
+
assert ' "a"' in raw # 4-space indent present
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def test_write_json_none_indent(tmp_path: Path) -> None:
|
| 145 |
+
target = tmp_path / "data.json"
|
| 146 |
+
atomic_write_json(target, {"a": 1}, indent=None)
|
| 147 |
+
raw = target.read_text(encoding="utf-8").strip()
|
| 148 |
+
assert raw == '{"a": 1}'
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# ── Windows retry ─────────────────────────────────────────────────────────────
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def test_replace_retries_on_permission_error(tmp_path: Path) -> None:
|
| 155 |
+
"""_replace_with_retry should succeed on the second attempt."""
|
| 156 |
+
target = tmp_path / "out.txt"
|
| 157 |
+
call_count = 0
|
| 158 |
+
real_replace = os.replace
|
| 159 |
+
|
| 160 |
+
def flaky_replace(src: str, dst: Path) -> None:
|
| 161 |
+
nonlocal call_count
|
| 162 |
+
call_count += 1
|
| 163 |
+
if call_count == 1:
|
| 164 |
+
raise PermissionError("locked")
|
| 165 |
+
real_replace(src, dst)
|
| 166 |
+
|
| 167 |
+
with patch("ctx.utils._fs_utils.os.replace", side_effect=flaky_replace):
|
| 168 |
+
with patch("ctx.utils._fs_utils.time.sleep"): # don't actually sleep
|
| 169 |
+
atomic_write_text(target, "retry-test")
|
| 170 |
+
|
| 171 |
+
assert call_count == 2
|
| 172 |
+
assert target.read_text(encoding="utf-8") == "retry-test"
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def test_replace_raises_after_max_attempts(tmp_path: Path) -> None:
|
| 176 |
+
"""After exhausting retries, the PermissionError must propagate."""
|
| 177 |
+
target = tmp_path / "out.txt"
|
| 178 |
+
|
| 179 |
+
with patch("ctx.utils._fs_utils.os.replace", side_effect=PermissionError("always locked")):
|
| 180 |
+
with patch("ctx.utils._fs_utils.time.sleep"):
|
| 181 |
+
with pytest.raises(PermissionError, match="always locked"):
|
| 182 |
+
atomic_write_text(target, "data")
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
# ── Concurrency smoke test ────────────────────────────────────────────────────
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def test_concurrent_writes_last_write_wins(tmp_path: Path) -> None:
|
| 189 |
+
"""Multiple threads writing to the same path must not leave corruption."""
|
| 190 |
+
target = tmp_path / "shared.txt"
|
| 191 |
+
errors: list[Exception] = []
|
| 192 |
+
|
| 193 |
+
def writer(content: str) -> None:
|
| 194 |
+
try:
|
| 195 |
+
atomic_write_text(target, content)
|
| 196 |
+
except Exception as exc:
|
| 197 |
+
errors.append(exc)
|
| 198 |
+
|
| 199 |
+
threads = [threading.Thread(target=writer, args=(f"thread-{i}",)) for i in range(8)]
|
| 200 |
+
for t in threads:
|
| 201 |
+
t.start()
|
| 202 |
+
for t in threads:
|
| 203 |
+
t.join()
|
| 204 |
+
|
| 205 |
+
assert errors == [], f"Writer threads raised: {errors}"
|
| 206 |
+
content = target.read_text(encoding="utf-8")
|
| 207 |
+
assert content.startswith("thread-")
|
src/tests/test_harness_contract.py
CHANGED
|
@@ -1,744 +1,744 @@
|
|
| 1 |
-
"""
|
| 2 |
-
test_harness_contract.py -- Contract + ContractBuilder + P/C/G/E flow.
|
| 3 |
-
|
| 4 |
-
Pins:
|
| 5 |
-
* ContractCriterion + Contract shapes, frozen, to_dict, to_markdown
|
| 6 |
-
* ContractCriterion.as_evaluator_criterion rendering with/without
|
| 7 |
-
metric + threshold
|
| 8 |
-
* ContractBuilder.build happy path, unstructured fallback, planner
|
| 9 |
-
injection into user turn, default temperature
|
| 10 |
-
* _parse_criteria_list: synth name fallback, drops non-dict items
|
| 11 |
-
* _safe_str_tuple: list / string-fallback / non-list
|
| 12 |
-
* run_with_evaluation with contract_builder: evaluator gets
|
| 13 |
-
refined criteria, system prompt uses contract markdown,
|
| 14 |
-
total_usage sums all four agents
|
| 15 |
-
* CLI: --contract requires --planner; --contract persists contract
|
| 16 |
-
event into JSONL; JSON output does NOT re-duplicate contract
|
| 17 |
-
(it's in the session file)
|
| 18 |
-
* augmented_system_prompt_with_contract formatting
|
| 19 |
-
"""
|
| 20 |
-
|
| 21 |
-
from __future__ import annotations
|
| 22 |
-
|
| 23 |
-
import json
|
| 24 |
-
import sys
|
| 25 |
-
import types
|
| 26 |
-
from dataclasses import dataclass, field
|
| 27 |
-
from pathlib import Path
|
| 28 |
-
from typing import Any
|
| 29 |
-
|
| 30 |
-
import pytest
|
| 31 |
-
|
| 32 |
-
from ctx.adapters.generic.contract import (
|
| 33 |
-
Contract,
|
| 34 |
-
ContractBuilder,
|
| 35 |
-
ContractCriterion,
|
| 36 |
-
_parse_criteria_list,
|
| 37 |
-
_safe_str_tuple,
|
| 38 |
-
augmented_system_prompt_with_contract,
|
| 39 |
-
)
|
| 40 |
-
from ctx.adapters.generic.evaluator import (
|
| 41 |
-
Evaluator,
|
| 42 |
-
run_with_evaluation,
|
| 43 |
-
)
|
| 44 |
-
from ctx.adapters.generic.planner import PlanArtifact, Planner
|
| 45 |
-
from ctx.adapters.generic.providers import (
|
| 46 |
-
CompletionResponse,
|
| 47 |
-
Message,
|
| 48 |
-
ModelProvider,
|
| 49 |
-
ToolDefinition,
|
| 50 |
-
Usage,
|
| 51 |
-
)
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
# ── Scripted provider ──────────────────────────────────────────────────────
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
@dataclass
|
| 58 |
-
class _Scripted(ModelProvider):
|
| 59 |
-
responses: list[CompletionResponse]
|
| 60 |
-
name: str = "scripted"
|
| 61 |
-
calls: list[dict[str, Any]] = field(default_factory=list)
|
| 62 |
-
|
| 63 |
-
def complete(
|
| 64 |
-
self,
|
| 65 |
-
messages: list[Message],
|
| 66 |
-
tools: list[ToolDefinition] | None = None,
|
| 67 |
-
*,
|
| 68 |
-
model: str | None = None,
|
| 69 |
-
temperature: float = 0.7,
|
| 70 |
-
max_tokens: int | None = None,
|
| 71 |
-
) -> CompletionResponse:
|
| 72 |
-
self.calls.append(
|
| 73 |
-
{
|
| 74 |
-
"messages": list(messages),
|
| 75 |
-
"model": model,
|
| 76 |
-
"temperature": temperature,
|
| 77 |
-
"max_tokens": max_tokens,
|
| 78 |
-
}
|
| 79 |
-
)
|
| 80 |
-
if not self.responses:
|
| 81 |
-
raise RuntimeError("scripted: ran out of responses")
|
| 82 |
-
return self.responses.pop(0)
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
def _resp(content: str) -> CompletionResponse:
|
| 86 |
-
return CompletionResponse(
|
| 87 |
-
content=content,
|
| 88 |
-
tool_calls=(),
|
| 89 |
-
finish_reason="stop",
|
| 90 |
-
usage=Usage(input_tokens=10, output_tokens=20),
|
| 91 |
-
provider="scripted",
|
| 92 |
-
model="x",
|
| 93 |
-
)
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
_VALID_CONTRACT_JSON = json.dumps({
|
| 97 |
-
"summary": "Ensure input validation on the submit endpoint.",
|
| 98 |
-
"criteria": [
|
| 99 |
-
{
|
| 100 |
-
"name": "empty-input-returns-422",
|
| 101 |
-
"description": "Empty input must not silently succeed.",
|
| 102 |
-
"pass_condition": "POST with empty body returns HTTP 422.",
|
| 103 |
-
"fail_condition": "POST with empty body returns anything other than 422.",
|
| 104 |
-
},
|
| 105 |
-
{
|
| 106 |
-
"name": "latency-under-200ms",
|
| 107 |
-
"description": "Happy path must stay under 200ms p95.",
|
| 108 |
-
"pass_condition": "p95 latency is under 200ms over 100 requests.",
|
| 109 |
-
"fail_condition": "p95 latency exceeds 200ms.",
|
| 110 |
-
"metric": "p95_latency_ms",
|
| 111 |
-
"threshold": "< 200",
|
| 112 |
-
},
|
| 113 |
-
],
|
| 114 |
-
"scope_in": ["POST /submit handler", "input validation layer"],
|
| 115 |
-
"scope_out": ["frontend forms", "unrelated endpoints"],
|
| 116 |
-
"approach": "Add a Pydantic validator at the entrypoint.",
|
| 117 |
-
})
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
_VALID_PLAN_JSON = json.dumps({
|
| 121 |
-
"summary": "Add validation to /submit",
|
| 122 |
-
"success_criteria": [
|
| 123 |
-
"Empty input should be rejected",
|
| 124 |
-
"Latency should stay reasonable",
|
| 125 |
-
],
|
| 126 |
-
"approach": "Add a validator",
|
| 127 |
-
"out_of_scope": [],
|
| 128 |
-
"risks": [],
|
| 129 |
-
})
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
# ── ContractCriterion ──────────────────────────────────────────────────────
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
class TestContractCriterion:
|
| 136 |
-
def test_frozen(self) -> None:
|
| 137 |
-
c = ContractCriterion(
|
| 138 |
-
name="n", description="d", pass_condition="p",
|
| 139 |
-
)
|
| 140 |
-
with pytest.raises(Exception):
|
| 141 |
-
c.name = "m" # type: ignore[misc]
|
| 142 |
-
|
| 143 |
-
def test_defaults(self) -> None:
|
| 144 |
-
c = ContractCriterion(
|
| 145 |
-
name="n", description="d", pass_condition="p",
|
| 146 |
-
)
|
| 147 |
-
assert c.fail_condition == ""
|
| 148 |
-
assert c.metric == ""
|
| 149 |
-
assert c.threshold == ""
|
| 150 |
-
|
| 151 |
-
def test_as_evaluator_criterion_basic(self) -> None:
|
| 152 |
-
c = ContractCriterion(
|
| 153 |
-
name="x", description="d", pass_condition="returns 422",
|
| 154 |
-
)
|
| 155 |
-
assert c.as_evaluator_criterion() == "returns 422"
|
| 156 |
-
|
| 157 |
-
def test_as_evaluator_criterion_with_metric(self) -> None:
|
| 158 |
-
c = ContractCriterion(
|
| 159 |
-
name="x", description="d",
|
| 160 |
-
pass_condition="p95 fast enough",
|
| 161 |
-
metric="p95_latency_ms",
|
| 162 |
-
)
|
| 163 |
-
out = c.as_evaluator_criterion()
|
| 164 |
-
assert "p95 fast enough" in out
|
| 165 |
-
assert "p95_latency_ms" in out
|
| 166 |
-
|
| 167 |
-
def test_as_evaluator_criterion_with_threshold(self) -> None:
|
| 168 |
-
c = ContractCriterion(
|
| 169 |
-
name="x", description="d",
|
| 170 |
-
pass_condition="fast",
|
| 171 |
-
metric="latency",
|
| 172 |
-
threshold="< 200",
|
| 173 |
-
)
|
| 174 |
-
out = c.as_evaluator_criterion()
|
| 175 |
-
assert "latency" in out
|
| 176 |
-
assert "< 200" in out
|
| 177 |
-
|
| 178 |
-
def test_as_evaluator_criterion_falls_back_to_description(self) -> None:
|
| 179 |
-
# Empty pass_condition → use description.
|
| 180 |
-
c = ContractCriterion(
|
| 181 |
-
name="x", description="desc-text", pass_condition="",
|
| 182 |
-
)
|
| 183 |
-
assert c.as_evaluator_criterion() == "desc-text"
|
| 184 |
-
|
| 185 |
-
def test_as_evaluator_criterion_falls_back_to_name(self) -> None:
|
| 186 |
-
c = ContractCriterion(name="the-name", description="", pass_condition="")
|
| 187 |
-
assert c.as_evaluator_criterion() == "the-name"
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
# ── Contract ───────────────────────────────────────────────────────────────
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
class TestContract:
|
| 194 |
-
def _mk(self) -> Contract:
|
| 195 |
-
return Contract(
|
| 196 |
-
task="t",
|
| 197 |
-
summary="s",
|
| 198 |
-
criteria=(
|
| 199 |
-
ContractCriterion(
|
| 200 |
-
name="a", description="d1", pass_condition="p1",
|
| 201 |
-
fail_condition="f1",
|
| 202 |
-
),
|
| 203 |
-
ContractCriterion(
|
| 204 |
-
name="b", description="d2", pass_condition="p2",
|
| 205 |
-
metric="m", threshold=">=0.8",
|
| 206 |
-
),
|
| 207 |
-
),
|
| 208 |
-
scope_in=("in1",),
|
| 209 |
-
scope_out=("out1",),
|
| 210 |
-
approach="do X",
|
| 211 |
-
usage=Usage(input_tokens=5, output_tokens=10),
|
| 212 |
-
raw_json="",
|
| 213 |
-
)
|
| 214 |
-
|
| 215 |
-
def test_frozen(self) -> None:
|
| 216 |
-
c = self._mk()
|
| 217 |
-
with pytest.raises(Exception):
|
| 218 |
-
c.summary = "other" # type: ignore[misc]
|
| 219 |
-
|
| 220 |
-
def test_as_evaluator_criteria(self) -> None:
|
| 221 |
-
crits = self._mk().as_evaluator_criteria()
|
| 222 |
-
assert crits[0] == "p1"
|
| 223 |
-
assert "p2" in crits[1]
|
| 224 |
-
assert "m" in crits[1]
|
| 225 |
-
assert ">=0.8" in crits[1]
|
| 226 |
-
|
| 227 |
-
def test_to_dict_shape(self) -> None:
|
| 228 |
-
d = self._mk().to_dict()
|
| 229 |
-
assert d["task"] == "t"
|
| 230 |
-
assert d["summary"] == "s"
|
| 231 |
-
assert len(d["criteria"]) == 2
|
| 232 |
-
assert d["criteria"][0]["name"] == "a"
|
| 233 |
-
assert d["scope_in"] == ["in1"]
|
| 234 |
-
assert d["scope_out"] == ["out1"]
|
| 235 |
-
assert d["parsed_ok"] is True
|
| 236 |
-
|
| 237 |
-
def test_to_markdown_shape(self) -> None:
|
| 238 |
-
md = self._mk().to_markdown()
|
| 239 |
-
assert "# Sprint Contract" in md
|
| 240 |
-
assert "**Task:** t" in md
|
| 241 |
-
assert "## Summary" in md
|
| 242 |
-
assert "### 1. a" in md
|
| 243 |
-
assert "### 2. b" in md
|
| 244 |
-
assert "**Pass:** p1" in md
|
| 245 |
-
assert "**Fail:** f1" in md
|
| 246 |
-
assert "**Metric:** m" in md
|
| 247 |
-
assert "threshold: >=0.8" in md
|
| 248 |
-
assert "## In scope" in md
|
| 249 |
-
assert "- in1" in md
|
| 250 |
-
assert "## Out of scope" in md
|
| 251 |
-
assert "- out1" in md
|
| 252 |
-
assert "## Approach" in md
|
| 253 |
-
|
| 254 |
-
def test_to_markdown_empty_sections(self) -> None:
|
| 255 |
-
c = Contract(
|
| 256 |
-
task="t", summary="", criteria=(),
|
| 257 |
-
scope_in=(), scope_out=(), approach="",
|
| 258 |
-
usage=Usage(), raw_json="",
|
| 259 |
-
)
|
| 260 |
-
md = c.to_markdown()
|
| 261 |
-
assert "_(no summary)_" in md
|
| 262 |
-
# Empty sections should not appear.
|
| 263 |
-
assert "## Criteria" not in md
|
| 264 |
-
assert "## In scope" not in md
|
| 265 |
-
assert "## Approach" not in md
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
# ── ContractBuilder ────────────────────────────────────────────────────────
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
class TestContractBuilder:
|
| 272 |
-
def test_happy_path_from_plan(self) -> None:
|
| 273 |
-
plan = PlanArtifact(
|
| 274 |
-
task="t",
|
| 275 |
-
summary="plan summary",
|
| 276 |
-
success_criteria=("empty input", "good perf"),
|
| 277 |
-
approach="approach",
|
| 278 |
-
out_of_scope=(),
|
| 279 |
-
risks=(),
|
| 280 |
-
usage=Usage(),
|
| 281 |
-
raw_json="",
|
| 282 |
-
)
|
| 283 |
-
provider = _Scripted([_resp(_VALID_CONTRACT_JSON)])
|
| 284 |
-
contract = ContractBuilder(provider).build("t", plan=plan)
|
| 285 |
-
assert contract.parsed_ok is True
|
| 286 |
-
assert len(contract.criteria) == 2
|
| 287 |
-
assert contract.criteria[0].name == "empty-input-returns-422"
|
| 288 |
-
assert contract.criteria[1].metric == "p95_latency_ms"
|
| 289 |
-
|
| 290 |
-
def test_happy_path_without_plan(self) -> None:
|
| 291 |
-
provider = _Scripted([_resp(_VALID_CONTRACT_JSON)])
|
| 292 |
-
contract = ContractBuilder(provider).build("task")
|
| 293 |
-
assert contract.parsed_ok is True
|
| 294 |
-
assert len(contract.criteria) == 2
|
| 295 |
-
|
| 296 |
-
def test_plan_markdown_embedded_in_user_turn(self) -> None:
|
| 297 |
-
plan = PlanArtifact(
|
| 298 |
-
task="t",
|
| 299 |
-
summary="plan-summary-marker",
|
| 300 |
-
success_criteria=(),
|
| 301 |
-
approach="",
|
| 302 |
-
out_of_scope=(),
|
| 303 |
-
risks=(),
|
| 304 |
-
usage=Usage(),
|
| 305 |
-
raw_json="",
|
| 306 |
-
)
|
| 307 |
-
provider = _Scripted([_resp(_VALID_CONTRACT_JSON)])
|
| 308 |
-
ContractBuilder(provider).build("task", plan=plan)
|
| 309 |
-
user_msg = next(
|
| 310 |
-
m for m in provider.calls[0]["messages"] if m.role == "user"
|
| 311 |
-
)
|
| 312 |
-
assert "plan-summary-marker" in user_msg.content
|
| 313 |
-
|
| 314 |
-
def test_unstructured_fallback(self) -> None:
|
| 315 |
-
provider = _Scripted([_resp("not JSON, just prose")])
|
| 316 |
-
contract = ContractBuilder(provider).build("t")
|
| 317 |
-
assert contract.parsed_ok is False
|
| 318 |
-
assert contract.criteria == ()
|
| 319 |
-
assert contract.summary == "not JSON, just prose"
|
| 320 |
-
|
| 321 |
-
def test_default_temperature_is_strict(self) -> None:
|
| 322 |
-
provider = _Scripted([_resp(_VALID_CONTRACT_JSON)])
|
| 323 |
-
ContractBuilder(provider).build("t")
|
| 324 |
-
# Default 0.2 — stricter than the planner (0.4) and generator (0.7).
|
| 325 |
-
assert provider.calls[0]["temperature"] == 0.2
|
| 326 |
-
|
| 327 |
-
def test_model_override(self) -> None:
|
| 328 |
-
provider = _Scripted([_resp(_VALID_CONTRACT_JSON)])
|
| 329 |
-
ContractBuilder(provider, model="contract-model").build("t")
|
| 330 |
-
assert provider.calls[0]["model"] == "contract-model"
|
| 331 |
-
|
| 332 |
-
def test_empty_response_produces_stub(self) -> None:
|
| 333 |
-
provider = _Scripted([_resp("")])
|
| 334 |
-
contract = ContractBuilder(provider).build("t")
|
| 335 |
-
assert contract.parsed_ok is False
|
| 336 |
-
# Empty response → summary carries the placeholder text
|
| 337 |
-
assert "empty" in contract.summary.lower()
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
# ── Parsers ────────────────────────────────────────────────────────────────
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
class TestParseCriteriaList:
|
| 344 |
-
def test_empty(self) -> None:
|
| 345 |
-
assert _parse_criteria_list([]) == ()
|
| 346 |
-
|
| 347 |
-
def test_non_list(self) -> None:
|
| 348 |
-
assert _parse_criteria_list({"a": 1}) == ()
|
| 349 |
-
assert _parse_criteria_list(None) == ()
|
| 350 |
-
|
| 351 |
-
def test_skips_non_dict_items(self) -> None:
|
| 352 |
-
out = _parse_criteria_list([
|
| 353 |
-
{"name": "a", "description": "d", "pass_condition": "p"},
|
| 354 |
-
"garbage",
|
| 355 |
-
42,
|
| 356 |
-
])
|
| 357 |
-
assert len(out) == 1
|
| 358 |
-
assert out[0].name == "a"
|
| 359 |
-
|
| 360 |
-
def test_synthesises_missing_name(self) -> None:
|
| 361 |
-
out = _parse_criteria_list([
|
| 362 |
-
{"description": "d", "pass_condition": "p"},
|
| 363 |
-
{"description": "d", "pass_condition": "p"},
|
| 364 |
-
])
|
| 365 |
-
assert out[0].name == "criterion-1"
|
| 366 |
-
assert out[1].name == "criterion-2"
|
| 367 |
-
|
| 368 |
-
def test_all_fields_preserved(self) -> None:
|
| 369 |
-
out = _parse_criteria_list([
|
| 370 |
-
{
|
| 371 |
-
"name": "n", "description": "d",
|
| 372 |
-
"pass_condition": "p", "fail_condition": "f",
|
| 373 |
-
"metric": "m", "threshold": "< 100",
|
| 374 |
-
}
|
| 375 |
-
])
|
| 376 |
-
c = out[0]
|
| 377 |
-
assert c.name == "n"
|
| 378 |
-
assert c.pass_condition == "p"
|
| 379 |
-
assert c.fail_condition == "f"
|
| 380 |
-
assert c.metric == "m"
|
| 381 |
-
assert c.threshold == "< 100"
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
class TestSafeStrTuple:
|
| 385 |
-
def test_none(self) -> None:
|
| 386 |
-
assert _safe_str_tuple(None) == ()
|
| 387 |
-
|
| 388 |
-
def test_list(self) -> None:
|
| 389 |
-
assert _safe_str_tuple(["a", "b"]) == ("a", "b")
|
| 390 |
-
|
| 391 |
-
def test_drops_empty(self) -> None:
|
| 392 |
-
assert _safe_str_tuple(["a", "", None, "b"]) == ("a", "b")
|
| 393 |
-
|
| 394 |
-
def test_string_fallback(self) -> None:
|
| 395 |
-
out = _safe_str_tuple("- first\n* second\nthird")
|
| 396 |
-
assert out == ("first", "second", "third")
|
| 397 |
-
|
| 398 |
-
def test_non_list_non_string(self) -> None:
|
| 399 |
-
assert _safe_str_tuple(42) == ()
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
# ── augmented_system_prompt_with_contract ────────────────────────────────
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
class TestAugmentedSystemPromptWithContract:
|
| 406 |
-
def test_contract_embedded(self) -> None:
|
| 407 |
-
contract = Contract(
|
| 408 |
-
task="t", summary="the contract summary",
|
| 409 |
-
criteria=(
|
| 410 |
-
ContractCriterion(
|
| 411 |
-
name="n", description="d",
|
| 412 |
-
pass_condition="MUST return 422",
|
| 413 |
-
),
|
| 414 |
-
),
|
| 415 |
-
scope_in=(), scope_out=(), approach="",
|
| 416 |
-
usage=Usage(), raw_json="",
|
| 417 |
-
)
|
| 418 |
-
out = augmented_system_prompt_with_contract("base", contract)
|
| 419 |
-
assert "base" in out
|
| 420 |
-
assert "# Sprint Contract" in out
|
| 421 |
-
assert "MUST return 422" in out
|
| 422 |
-
assert "the contract summary" in out
|
| 423 |
-
assert "non-negotiable" in out
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
# ── run_with_evaluation with contract_builder ─────────────────────────────
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
class TestRunWithContract:
|
| 430 |
-
def test_contract_criteria_used_by_evaluator(self) -> None:
|
| 431 |
-
# Response order: planner, contract, generator, evaluator
|
| 432 |
-
provider = _Scripted([
|
| 433 |
-
_resp(_VALID_PLAN_JSON),
|
| 434 |
-
_resp(_VALID_CONTRACT_JSON),
|
| 435 |
-
_resp("generator answer"),
|
| 436 |
-
_resp(json.dumps({
|
| 437 |
-
"verdict": "pass",
|
| 438 |
-
"overall_score": 1.0,
|
| 439 |
-
"criteria": [],
|
| 440 |
-
"summary_feedback": "good",
|
| 441 |
-
"revision_directive": "",
|
| 442 |
-
})),
|
| 443 |
-
])
|
| 444 |
-
outcome = run_with_evaluation(
|
| 445 |
-
provider=provider,
|
| 446 |
-
system_prompt="sys",
|
| 447 |
-
task="t",
|
| 448 |
-
evaluator=Evaluator(provider),
|
| 449 |
-
planner=Planner(provider),
|
| 450 |
-
contract_builder=ContractBuilder(provider),
|
| 451 |
-
max_rounds=1,
|
| 452 |
-
)
|
| 453 |
-
# Outcome carries plan + contract.
|
| 454 |
-
assert outcome.plan is not None
|
| 455 |
-
assert outcome.contract is not None
|
| 456 |
-
assert outcome.contract.summary.startswith("Ensure")
|
| 457 |
-
# Evaluator call (4th) should see contract-derived criteria.
|
| 458 |
-
evaluator_call = provider.calls[3]
|
| 459 |
-
user_content = next(
|
| 460 |
-
m.content for m in evaluator_call["messages"] if m.role == "user"
|
| 461 |
-
)
|
| 462 |
-
assert "POST with empty body returns HTTP 422" in user_content
|
| 463 |
-
|
| 464 |
-
def test_contract_prompt_injected_into_generator(self) -> None:
|
| 465 |
-
provider = _Scripted([
|
| 466 |
-
_resp(_VALID_PLAN_JSON),
|
| 467 |
-
_resp(_VALID_CONTRACT_JSON),
|
| 468 |
-
_resp("gen answer"),
|
| 469 |
-
_resp(json.dumps({
|
| 470 |
-
"verdict": "pass", "overall_score": 1.0, "criteria": [],
|
| 471 |
-
"summary_feedback": "", "revision_directive": "",
|
| 472 |
-
})),
|
| 473 |
-
])
|
| 474 |
-
run_with_evaluation(
|
| 475 |
-
provider=provider,
|
| 476 |
-
system_prompt="base-prompt",
|
| 477 |
-
task="t",
|
| 478 |
-
evaluator=Evaluator(provider),
|
| 479 |
-
planner=Planner(provider),
|
| 480 |
-
contract_builder=ContractBuilder(provider),
|
| 481 |
-
max_rounds=1,
|
| 482 |
-
)
|
| 483 |
-
# Generator call (3rd) should see contract markdown in system prompt.
|
| 484 |
-
generator_call = provider.calls[2]
|
| 485 |
-
sys_content = next(
|
| 486 |
-
m.content for m in generator_call["messages"] if m.role == "system"
|
| 487 |
-
)
|
| 488 |
-
assert "# Sprint Contract" in sys_content
|
| 489 |
-
assert "non-negotiable" in sys_content
|
| 490 |
-
# Plan's narrative still present too (base + contract embeds).
|
| 491 |
-
assert "base-prompt" in sys_content
|
| 492 |
-
|
| 493 |
-
def test_total_usage_includes_contract_cost(self) -> None:
|
| 494 |
-
# Each response reports 10 input + 20 output → 40 total input.
|
| 495 |
-
provider = _Scripted([
|
| 496 |
-
_resp(_VALID_PLAN_JSON), # planner
|
| 497 |
-
_resp(_VALID_CONTRACT_JSON), # contract
|
| 498 |
-
_resp("g"), # generator
|
| 499 |
-
_resp(json.dumps({
|
| 500 |
-
"verdict": "pass", "overall_score": 1.0, "criteria": [],
|
| 501 |
-
"summary_feedback": "", "revision_directive": "",
|
| 502 |
-
})), # evaluator
|
| 503 |
-
])
|
| 504 |
-
outcome = run_with_evaluation(
|
| 505 |
-
provider=provider,
|
| 506 |
-
system_prompt="s",
|
| 507 |
-
task="t",
|
| 508 |
-
evaluator=Evaluator(provider),
|
| 509 |
-
planner=Planner(provider),
|
| 510 |
-
contract_builder=ContractBuilder(provider),
|
| 511 |
-
max_rounds=1,
|
| 512 |
-
)
|
| 513 |
-
assert outcome.total_usage.input_tokens == 40
|
| 514 |
-
assert outcome.total_usage.output_tokens == 80
|
| 515 |
-
|
| 516 |
-
def test_contract_without_planner_also_works(self) -> None:
|
| 517 |
-
"""Contract can run without a plan — library escape hatch."""
|
| 518 |
-
provider = _Scripted([
|
| 519 |
-
_resp(_VALID_CONTRACT_JSON),
|
| 520 |
-
_resp("g"),
|
| 521 |
-
_resp(json.dumps({
|
| 522 |
-
"verdict": "pass", "overall_score": 1.0, "criteria": [],
|
| 523 |
-
"summary_feedback": "", "revision_directive": "",
|
| 524 |
-
})),
|
| 525 |
-
])
|
| 526 |
-
outcome = run_with_evaluation(
|
| 527 |
-
provider=provider,
|
| 528 |
-
system_prompt="s",
|
| 529 |
-
task="t",
|
| 530 |
-
evaluator=Evaluator(provider),
|
| 531 |
-
planner=None,
|
| 532 |
-
contract_builder=ContractBuilder(provider),
|
| 533 |
-
max_rounds=1,
|
| 534 |
-
)
|
| 535 |
-
assert outcome.plan is None
|
| 536 |
-
assert outcome.contract is not None
|
| 537 |
-
|
| 538 |
-
def test_empty_contract_criteria_falls_back_to_evaluator_defaults(
|
| 539 |
-
self,
|
| 540 |
-
) -> None:
|
| 541 |
-
"""When the contract builder produces no criteria (bad JSON),
|
| 542 |
-
the evaluator still runs with its default criteria set."""
|
| 543 |
-
empty_contract_json = json.dumps({
|
| 544 |
-
"summary": "stub", "criteria": [],
|
| 545 |
-
"scope_in": [], "scope_out": [], "approach": "",
|
| 546 |
-
})
|
| 547 |
-
provider = _Scripted([
|
| 548 |
-
_resp(_VALID_PLAN_JSON),
|
| 549 |
-
_resp(empty_contract_json),
|
| 550 |
-
_resp("g"),
|
| 551 |
-
_resp(json.dumps({
|
| 552 |
-
"verdict": "pass", "overall_score": 1.0, "criteria": [],
|
| 553 |
-
"summary_feedback": "", "revision_directive": "",
|
| 554 |
-
})),
|
| 555 |
-
])
|
| 556 |
-
outcome = run_with_evaluation(
|
| 557 |
-
provider=provider,
|
| 558 |
-
system_prompt="s",
|
| 559 |
-
task="t",
|
| 560 |
-
evaluator=Evaluator(provider),
|
| 561 |
-
planner=Planner(provider),
|
| 562 |
-
contract_builder=ContractBuilder(provider),
|
| 563 |
-
max_rounds=1,
|
| 564 |
-
)
|
| 565 |
-
# Contract captured but empty.
|
| 566 |
-
assert outcome.contract is not None
|
| 567 |
-
assert outcome.contract.criteria == ()
|
| 568 |
-
# Evaluator call saw the planner's success_criteria (since
|
| 569 |
-
# the contract had nothing to replace them with).
|
| 570 |
-
evaluator_call = provider.calls[3]
|
| 571 |
-
user_content = next(
|
| 572 |
-
m.content for m in evaluator_call["messages"] if m.role == "user"
|
| 573 |
-
)
|
| 574 |
-
# Planner criteria survive.
|
| 575 |
-
assert "Empty input should be rejected" in user_content
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
# ── CLI integration ───────────────────────────────────────────────────────
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
@pytest.fixture()
|
| 582 |
-
def fake_litellm_contract(monkeypatch: pytest.MonkeyPatch):
|
| 583 |
-
fake = types.ModuleType("litellm")
|
| 584 |
-
calls: list[dict[str, Any]] = []
|
| 585 |
-
|
| 586 |
-
def _mk(content: str) -> dict[str, Any]:
|
| 587 |
-
return {
|
| 588 |
-
"choices": [
|
| 589 |
-
{"message": {"content": content}, "finish_reason": "stop"}
|
| 590 |
-
],
|
| 591 |
-
"usage": {"prompt_tokens": 5, "completion_tokens": 10},
|
| 592 |
-
}
|
| 593 |
-
|
| 594 |
-
# Default queue: planner → contract → generator → evaluator(pass).
|
| 595 |
-
fake._responses = [ # type: ignore[attr-defined]
|
| 596 |
-
_mk(_VALID_PLAN_JSON),
|
| 597 |
-
_mk(_VALID_CONTRACT_JSON),
|
| 598 |
-
_mk("done"),
|
| 599 |
-
_mk(json.dumps({
|
| 600 |
-
"verdict": "pass", "overall_score": 1.0, "criteria": [],
|
| 601 |
-
"summary_feedback": "fine", "revision_directive": "",
|
| 602 |
-
})),
|
| 603 |
-
]
|
| 604 |
-
|
| 605 |
-
def completion(**kwargs):
|
| 606 |
-
calls.append(kwargs)
|
| 607 |
-
if not fake._responses: # type: ignore[attr-defined]
|
| 608 |
-
raise RuntimeError("fake: no more responses")
|
| 609 |
-
return fake._responses.pop(0) # type: ignore[attr-defined]
|
| 610 |
-
|
| 611 |
-
fake.completion = completion # type: ignore[attr-defined]
|
| 612 |
-
fake._calls = calls # type: ignore[attr-defined]
|
| 613 |
-
fake._mk = _mk # type: ignore[attr-defined]
|
| 614 |
-
monkeypatch.setitem(sys.modules, "litellm", fake)
|
| 615 |
-
return fake
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
class TestCliContract:
|
| 619 |
-
def test_contract_without_planner_rejected(self, tmp_path: Path) -> None:
|
| 620 |
-
from ctx.cli.run import main
|
| 621 |
-
|
| 622 |
-
with pytest.raises(SystemExit, match="--contract requires --planner"):
|
| 623 |
-
main(
|
| 624 |
-
[
|
| 625 |
-
"run",
|
| 626 |
-
"--model", "ollama/x",
|
| 627 |
-
"--task", "t",
|
| 628 |
-
"--sessions-dir", str(tmp_path),
|
| 629 |
-
"--evaluator",
|
| 630 |
-
"--contract",
|
| 631 |
-
"--no-ctx-tools",
|
| 632 |
-
"--quiet",
|
| 633 |
-
]
|
| 634 |
-
)
|
| 635 |
-
|
| 636 |
-
def test_contract_without_evaluator_rejected(
|
| 637 |
-
self, tmp_path: Path,
|
| 638 |
-
) -> None:
|
| 639 |
-
"""--contract is only meaningful with --evaluator + --planner."""
|
| 640 |
-
# Without --evaluator the contract flag is silently ignored
|
| 641 |
-
# (the solo path ignores it since run_with_evaluation isn't
|
| 642 |
-
# entered); that's acceptable behaviour — document but don't
|
| 643 |
-
# error. This test pins the current behaviour so a future
|
| 644 |
-
# change is explicit.
|
| 645 |
-
from ctx.cli.run import main
|
| 646 |
-
|
| 647 |
-
# Should not raise — --contract is silently ignored in the
|
| 648 |
-
# solo path (run_with_evaluation isn't entered). The solo
|
| 649 |
-
# path with --planner makes TWO provider calls: the planner
|
| 650 |
-
# call and the Generator's single iteration.
|
| 651 |
-
fake = types.ModuleType("litellm")
|
| 652 |
-
|
| 653 |
-
def _mk(content: str) -> dict[str, Any]:
|
| 654 |
-
return {
|
| 655 |
-
"choices": [
|
| 656 |
-
{"message": {"content": content}, "finish_reason": "stop"}
|
| 657 |
-
],
|
| 658 |
-
"usage": {"prompt_tokens": 1, "completion_tokens": 1},
|
| 659 |
-
}
|
| 660 |
-
|
| 661 |
-
fake._responses = [ # type: ignore[attr-defined]
|
| 662 |
-
_mk(_VALID_PLAN_JSON), # planner call
|
| 663 |
-
_mk("generator answer"), # generator
|
| 664 |
-
]
|
| 665 |
-
|
| 666 |
-
def completion(**kwargs):
|
| 667 |
-
return fake._responses.pop(0) # type: ignore[attr-defined]
|
| 668 |
-
|
| 669 |
-
fake.completion = completion # type: ignore[attr-defined]
|
| 670 |
-
import sys as _sys
|
| 671 |
-
_sys.modules["litellm"] = fake
|
| 672 |
-
exit_code = main(
|
| 673 |
-
[
|
| 674 |
-
"run",
|
| 675 |
-
"--model", "ollama/x",
|
| 676 |
-
"--task", "t",
|
| 677 |
-
"--sessions-dir", str(tmp_path),
|
| 678 |
-
"--planner", # planner enabled but evaluator isn't
|
| 679 |
-
"--contract", # contract solo path doesn't reach run_with_eval
|
| 680 |
-
"--no-ctx-tools",
|
| 681 |
-
"--quiet",
|
| 682 |
-
]
|
| 683 |
-
)
|
| 684 |
-
assert exit_code == 0
|
| 685 |
-
|
| 686 |
-
def test_contract_persisted_in_jsonl(
|
| 687 |
-
self, fake_litellm_contract: Any, tmp_path: Path,
|
| 688 |
-
) -> None:
|
| 689 |
-
from ctx.cli.run import main
|
| 690 |
-
|
| 691 |
-
main(
|
| 692 |
-
[
|
| 693 |
-
"run",
|
| 694 |
-
"--model", "ollama/x",
|
| 695 |
-
"--task", "add validation",
|
| 696 |
-
"--sessions-dir", str(tmp_path),
|
| 697 |
-
"--session-id", "cn-run",
|
| 698 |
-
"--planner",
|
| 699 |
-
"--evaluator",
|
| 700 |
-
"--contract",
|
| 701 |
-
"--no-ctx-tools",
|
| 702 |
-
"--quiet",
|
| 703 |
-
]
|
| 704 |
-
)
|
| 705 |
-
# JSONL should carry a 'contract' event with the refined criteria.
|
| 706 |
-
events = [
|
| 707 |
-
json.loads(line)
|
| 708 |
-
for line in (tmp_path / "cn-run.jsonl").read_text(encoding="utf-8").splitlines()
|
| 709 |
-
if line
|
| 710 |
-
]
|
| 711 |
-
contract_events = [e for e in events if e.get("type") == "contract"]
|
| 712 |
-
assert len(contract_events) == 1
|
| 713 |
-
ce = contract_events[0]
|
| 714 |
-
assert ce["summary"].startswith("Ensure")
|
| 715 |
-
assert len(ce["criteria"]) == 2
|
| 716 |
-
# session_start metadata contract_used True.
|
| 717 |
-
first = events[0]
|
| 718 |
-
assert first["type"] == "session_start"
|
| 719 |
-
assert first["contract_used"] is True
|
| 720 |
-
|
| 721 |
-
def test_contract_model_override(
|
| 722 |
-
self, fake_litellm_contract: Any, tmp_path: Path,
|
| 723 |
-
) -> None:
|
| 724 |
-
from ctx.cli.run import main
|
| 725 |
-
|
| 726 |
-
main(
|
| 727 |
-
[
|
| 728 |
-
"run",
|
| 729 |
-
"--model", "ollama/main",
|
| 730 |
-
"--contract-model", "ollama/contract",
|
| 731 |
-
"--task", "t",
|
| 732 |
-
"--sessions-dir", str(tmp_path),
|
| 733 |
-
"--session-id", "cn-override",
|
| 734 |
-
"--planner",
|
| 735 |
-
"--evaluator",
|
| 736 |
-
"--contract",
|
| 737 |
-
"--no-ctx-tools",
|
| 738 |
-
"--quiet",
|
| 739 |
-
]
|
| 740 |
-
)
|
| 741 |
-
calls = fake_litellm_contract._calls
|
| 742 |
-
# Order: planner → contract → generator → evaluator
|
| 743 |
-
contract_call = calls[1]
|
| 744 |
-
assert contract_call["model"] == "ollama/contract"
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_harness_contract.py -- Contract + ContractBuilder + P/C/G/E flow.
|
| 3 |
+
|
| 4 |
+
Pins:
|
| 5 |
+
* ContractCriterion + Contract shapes, frozen, to_dict, to_markdown
|
| 6 |
+
* ContractCriterion.as_evaluator_criterion rendering with/without
|
| 7 |
+
metric + threshold
|
| 8 |
+
* ContractBuilder.build happy path, unstructured fallback, planner
|
| 9 |
+
injection into user turn, default temperature
|
| 10 |
+
* _parse_criteria_list: synth name fallback, drops non-dict items
|
| 11 |
+
* _safe_str_tuple: list / string-fallback / non-list
|
| 12 |
+
* run_with_evaluation with contract_builder: evaluator gets
|
| 13 |
+
refined criteria, system prompt uses contract markdown,
|
| 14 |
+
total_usage sums all four agents
|
| 15 |
+
* CLI: --contract requires --planner; --contract persists contract
|
| 16 |
+
event into JSONL; JSON output does NOT re-duplicate contract
|
| 17 |
+
(it's in the session file)
|
| 18 |
+
* augmented_system_prompt_with_contract formatting
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import json
|
| 24 |
+
import sys
|
| 25 |
+
import types
|
| 26 |
+
from dataclasses import dataclass, field
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
from typing import Any
|
| 29 |
+
|
| 30 |
+
import pytest
|
| 31 |
+
|
| 32 |
+
from ctx.adapters.generic.contract import (
|
| 33 |
+
Contract,
|
| 34 |
+
ContractBuilder,
|
| 35 |
+
ContractCriterion,
|
| 36 |
+
_parse_criteria_list,
|
| 37 |
+
_safe_str_tuple,
|
| 38 |
+
augmented_system_prompt_with_contract,
|
| 39 |
+
)
|
| 40 |
+
from ctx.adapters.generic.evaluator import (
|
| 41 |
+
Evaluator,
|
| 42 |
+
run_with_evaluation,
|
| 43 |
+
)
|
| 44 |
+
from ctx.adapters.generic.planner import PlanArtifact, Planner
|
| 45 |
+
from ctx.adapters.generic.providers import (
|
| 46 |
+
CompletionResponse,
|
| 47 |
+
Message,
|
| 48 |
+
ModelProvider,
|
| 49 |
+
ToolDefinition,
|
| 50 |
+
Usage,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# ── Scripted provider ──────────────────────────────────────────────────────
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@dataclass
|
| 58 |
+
class _Scripted(ModelProvider):
|
| 59 |
+
responses: list[CompletionResponse]
|
| 60 |
+
name: str = "scripted"
|
| 61 |
+
calls: list[dict[str, Any]] = field(default_factory=list)
|
| 62 |
+
|
| 63 |
+
def complete(
|
| 64 |
+
self,
|
| 65 |
+
messages: list[Message],
|
| 66 |
+
tools: list[ToolDefinition] | None = None,
|
| 67 |
+
*,
|
| 68 |
+
model: str | None = None,
|
| 69 |
+
temperature: float = 0.7,
|
| 70 |
+
max_tokens: int | None = None,
|
| 71 |
+
) -> CompletionResponse:
|
| 72 |
+
self.calls.append(
|
| 73 |
+
{
|
| 74 |
+
"messages": list(messages),
|
| 75 |
+
"model": model,
|
| 76 |
+
"temperature": temperature,
|
| 77 |
+
"max_tokens": max_tokens,
|
| 78 |
+
}
|
| 79 |
+
)
|
| 80 |
+
if not self.responses:
|
| 81 |
+
raise RuntimeError("scripted: ran out of responses")
|
| 82 |
+
return self.responses.pop(0)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _resp(content: str) -> CompletionResponse:
|
| 86 |
+
return CompletionResponse(
|
| 87 |
+
content=content,
|
| 88 |
+
tool_calls=(),
|
| 89 |
+
finish_reason="stop",
|
| 90 |
+
usage=Usage(input_tokens=10, output_tokens=20),
|
| 91 |
+
provider="scripted",
|
| 92 |
+
model="x",
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
_VALID_CONTRACT_JSON = json.dumps({
|
| 97 |
+
"summary": "Ensure input validation on the submit endpoint.",
|
| 98 |
+
"criteria": [
|
| 99 |
+
{
|
| 100 |
+
"name": "empty-input-returns-422",
|
| 101 |
+
"description": "Empty input must not silently succeed.",
|
| 102 |
+
"pass_condition": "POST with empty body returns HTTP 422.",
|
| 103 |
+
"fail_condition": "POST with empty body returns anything other than 422.",
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"name": "latency-under-200ms",
|
| 107 |
+
"description": "Happy path must stay under 200ms p95.",
|
| 108 |
+
"pass_condition": "p95 latency is under 200ms over 100 requests.",
|
| 109 |
+
"fail_condition": "p95 latency exceeds 200ms.",
|
| 110 |
+
"metric": "p95_latency_ms",
|
| 111 |
+
"threshold": "< 200",
|
| 112 |
+
},
|
| 113 |
+
],
|
| 114 |
+
"scope_in": ["POST /submit handler", "input validation layer"],
|
| 115 |
+
"scope_out": ["frontend forms", "unrelated endpoints"],
|
| 116 |
+
"approach": "Add a Pydantic validator at the entrypoint.",
|
| 117 |
+
})
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
_VALID_PLAN_JSON = json.dumps({
|
| 121 |
+
"summary": "Add validation to /submit",
|
| 122 |
+
"success_criteria": [
|
| 123 |
+
"Empty input should be rejected",
|
| 124 |
+
"Latency should stay reasonable",
|
| 125 |
+
],
|
| 126 |
+
"approach": "Add a validator",
|
| 127 |
+
"out_of_scope": [],
|
| 128 |
+
"risks": [],
|
| 129 |
+
})
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
# ── ContractCriterion ──────────────────────────────────────────────────────
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class TestContractCriterion:
|
| 136 |
+
def test_frozen(self) -> None:
|
| 137 |
+
c = ContractCriterion(
|
| 138 |
+
name="n", description="d", pass_condition="p",
|
| 139 |
+
)
|
| 140 |
+
with pytest.raises(Exception):
|
| 141 |
+
c.name = "m" # type: ignore[misc]
|
| 142 |
+
|
| 143 |
+
def test_defaults(self) -> None:
|
| 144 |
+
c = ContractCriterion(
|
| 145 |
+
name="n", description="d", pass_condition="p",
|
| 146 |
+
)
|
| 147 |
+
assert c.fail_condition == ""
|
| 148 |
+
assert c.metric == ""
|
| 149 |
+
assert c.threshold == ""
|
| 150 |
+
|
| 151 |
+
def test_as_evaluator_criterion_basic(self) -> None:
|
| 152 |
+
c = ContractCriterion(
|
| 153 |
+
name="x", description="d", pass_condition="returns 422",
|
| 154 |
+
)
|
| 155 |
+
assert c.as_evaluator_criterion() == "returns 422"
|
| 156 |
+
|
| 157 |
+
def test_as_evaluator_criterion_with_metric(self) -> None:
|
| 158 |
+
c = ContractCriterion(
|
| 159 |
+
name="x", description="d",
|
| 160 |
+
pass_condition="p95 fast enough",
|
| 161 |
+
metric="p95_latency_ms",
|
| 162 |
+
)
|
| 163 |
+
out = c.as_evaluator_criterion()
|
| 164 |
+
assert "p95 fast enough" in out
|
| 165 |
+
assert "p95_latency_ms" in out
|
| 166 |
+
|
| 167 |
+
def test_as_evaluator_criterion_with_threshold(self) -> None:
|
| 168 |
+
c = ContractCriterion(
|
| 169 |
+
name="x", description="d",
|
| 170 |
+
pass_condition="fast",
|
| 171 |
+
metric="latency",
|
| 172 |
+
threshold="< 200",
|
| 173 |
+
)
|
| 174 |
+
out = c.as_evaluator_criterion()
|
| 175 |
+
assert "latency" in out
|
| 176 |
+
assert "< 200" in out
|
| 177 |
+
|
| 178 |
+
def test_as_evaluator_criterion_falls_back_to_description(self) -> None:
|
| 179 |
+
# Empty pass_condition → use description.
|
| 180 |
+
c = ContractCriterion(
|
| 181 |
+
name="x", description="desc-text", pass_condition="",
|
| 182 |
+
)
|
| 183 |
+
assert c.as_evaluator_criterion() == "desc-text"
|
| 184 |
+
|
| 185 |
+
def test_as_evaluator_criterion_falls_back_to_name(self) -> None:
|
| 186 |
+
c = ContractCriterion(name="the-name", description="", pass_condition="")
|
| 187 |
+
assert c.as_evaluator_criterion() == "the-name"
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
# ── Contract ───────────────────────────────────────────────────────────────
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class TestContract:
|
| 194 |
+
def _mk(self) -> Contract:
|
| 195 |
+
return Contract(
|
| 196 |
+
task="t",
|
| 197 |
+
summary="s",
|
| 198 |
+
criteria=(
|
| 199 |
+
ContractCriterion(
|
| 200 |
+
name="a", description="d1", pass_condition="p1",
|
| 201 |
+
fail_condition="f1",
|
| 202 |
+
),
|
| 203 |
+
ContractCriterion(
|
| 204 |
+
name="b", description="d2", pass_condition="p2",
|
| 205 |
+
metric="m", threshold=">=0.8",
|
| 206 |
+
),
|
| 207 |
+
),
|
| 208 |
+
scope_in=("in1",),
|
| 209 |
+
scope_out=("out1",),
|
| 210 |
+
approach="do X",
|
| 211 |
+
usage=Usage(input_tokens=5, output_tokens=10),
|
| 212 |
+
raw_json="",
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
def test_frozen(self) -> None:
|
| 216 |
+
c = self._mk()
|
| 217 |
+
with pytest.raises(Exception):
|
| 218 |
+
c.summary = "other" # type: ignore[misc]
|
| 219 |
+
|
| 220 |
+
def test_as_evaluator_criteria(self) -> None:
|
| 221 |
+
crits = self._mk().as_evaluator_criteria()
|
| 222 |
+
assert crits[0] == "p1"
|
| 223 |
+
assert "p2" in crits[1]
|
| 224 |
+
assert "m" in crits[1]
|
| 225 |
+
assert ">=0.8" in crits[1]
|
| 226 |
+
|
| 227 |
+
def test_to_dict_shape(self) -> None:
|
| 228 |
+
d = self._mk().to_dict()
|
| 229 |
+
assert d["task"] == "t"
|
| 230 |
+
assert d["summary"] == "s"
|
| 231 |
+
assert len(d["criteria"]) == 2
|
| 232 |
+
assert d["criteria"][0]["name"] == "a"
|
| 233 |
+
assert d["scope_in"] == ["in1"]
|
| 234 |
+
assert d["scope_out"] == ["out1"]
|
| 235 |
+
assert d["parsed_ok"] is True
|
| 236 |
+
|
| 237 |
+
def test_to_markdown_shape(self) -> None:
|
| 238 |
+
md = self._mk().to_markdown()
|
| 239 |
+
assert "# Sprint Contract" in md
|
| 240 |
+
assert "**Task:** t" in md
|
| 241 |
+
assert "## Summary" in md
|
| 242 |
+
assert "### 1. a" in md
|
| 243 |
+
assert "### 2. b" in md
|
| 244 |
+
assert "**Pass:** p1" in md
|
| 245 |
+
assert "**Fail:** f1" in md
|
| 246 |
+
assert "**Metric:** m" in md
|
| 247 |
+
assert "threshold: >=0.8" in md
|
| 248 |
+
assert "## In scope" in md
|
| 249 |
+
assert "- in1" in md
|
| 250 |
+
assert "## Out of scope" in md
|
| 251 |
+
assert "- out1" in md
|
| 252 |
+
assert "## Approach" in md
|
| 253 |
+
|
| 254 |
+
def test_to_markdown_empty_sections(self) -> None:
|
| 255 |
+
c = Contract(
|
| 256 |
+
task="t", summary="", criteria=(),
|
| 257 |
+
scope_in=(), scope_out=(), approach="",
|
| 258 |
+
usage=Usage(), raw_json="",
|
| 259 |
+
)
|
| 260 |
+
md = c.to_markdown()
|
| 261 |
+
assert "_(no summary)_" in md
|
| 262 |
+
# Empty sections should not appear.
|
| 263 |
+
assert "## Criteria" not in md
|
| 264 |
+
assert "## In scope" not in md
|
| 265 |
+
assert "## Approach" not in md
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
# ── ContractBuilder ────────────────────────────────────────────────────────
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
class TestContractBuilder:
|
| 272 |
+
def test_happy_path_from_plan(self) -> None:
|
| 273 |
+
plan = PlanArtifact(
|
| 274 |
+
task="t",
|
| 275 |
+
summary="plan summary",
|
| 276 |
+
success_criteria=("empty input", "good perf"),
|
| 277 |
+
approach="approach",
|
| 278 |
+
out_of_scope=(),
|
| 279 |
+
risks=(),
|
| 280 |
+
usage=Usage(),
|
| 281 |
+
raw_json="",
|
| 282 |
+
)
|
| 283 |
+
provider = _Scripted([_resp(_VALID_CONTRACT_JSON)])
|
| 284 |
+
contract = ContractBuilder(provider).build("t", plan=plan)
|
| 285 |
+
assert contract.parsed_ok is True
|
| 286 |
+
assert len(contract.criteria) == 2
|
| 287 |
+
assert contract.criteria[0].name == "empty-input-returns-422"
|
| 288 |
+
assert contract.criteria[1].metric == "p95_latency_ms"
|
| 289 |
+
|
| 290 |
+
def test_happy_path_without_plan(self) -> None:
|
| 291 |
+
provider = _Scripted([_resp(_VALID_CONTRACT_JSON)])
|
| 292 |
+
contract = ContractBuilder(provider).build("task")
|
| 293 |
+
assert contract.parsed_ok is True
|
| 294 |
+
assert len(contract.criteria) == 2
|
| 295 |
+
|
| 296 |
+
def test_plan_markdown_embedded_in_user_turn(self) -> None:
|
| 297 |
+
plan = PlanArtifact(
|
| 298 |
+
task="t",
|
| 299 |
+
summary="plan-summary-marker",
|
| 300 |
+
success_criteria=(),
|
| 301 |
+
approach="",
|
| 302 |
+
out_of_scope=(),
|
| 303 |
+
risks=(),
|
| 304 |
+
usage=Usage(),
|
| 305 |
+
raw_json="",
|
| 306 |
+
)
|
| 307 |
+
provider = _Scripted([_resp(_VALID_CONTRACT_JSON)])
|
| 308 |
+
ContractBuilder(provider).build("task", plan=plan)
|
| 309 |
+
user_msg = next(
|
| 310 |
+
m for m in provider.calls[0]["messages"] if m.role == "user"
|
| 311 |
+
)
|
| 312 |
+
assert "plan-summary-marker" in user_msg.content
|
| 313 |
+
|
| 314 |
+
def test_unstructured_fallback(self) -> None:
|
| 315 |
+
provider = _Scripted([_resp("not JSON, just prose")])
|
| 316 |
+
contract = ContractBuilder(provider).build("t")
|
| 317 |
+
assert contract.parsed_ok is False
|
| 318 |
+
assert contract.criteria == ()
|
| 319 |
+
assert contract.summary == "not JSON, just prose"
|
| 320 |
+
|
| 321 |
+
def test_default_temperature_is_strict(self) -> None:
|
| 322 |
+
provider = _Scripted([_resp(_VALID_CONTRACT_JSON)])
|
| 323 |
+
ContractBuilder(provider).build("t")
|
| 324 |
+
# Default 0.2 — stricter than the planner (0.4) and generator (0.7).
|
| 325 |
+
assert provider.calls[0]["temperature"] == 0.2
|
| 326 |
+
|
| 327 |
+
def test_model_override(self) -> None:
|
| 328 |
+
provider = _Scripted([_resp(_VALID_CONTRACT_JSON)])
|
| 329 |
+
ContractBuilder(provider, model="contract-model").build("t")
|
| 330 |
+
assert provider.calls[0]["model"] == "contract-model"
|
| 331 |
+
|
| 332 |
+
def test_empty_response_produces_stub(self) -> None:
|
| 333 |
+
provider = _Scripted([_resp("")])
|
| 334 |
+
contract = ContractBuilder(provider).build("t")
|
| 335 |
+
assert contract.parsed_ok is False
|
| 336 |
+
# Empty response → summary carries the placeholder text
|
| 337 |
+
assert "empty" in contract.summary.lower()
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
# ── Parsers ────────────────────────────────────────────────────────────────
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
class TestParseCriteriaList:
|
| 344 |
+
def test_empty(self) -> None:
|
| 345 |
+
assert _parse_criteria_list([]) == ()
|
| 346 |
+
|
| 347 |
+
def test_non_list(self) -> None:
|
| 348 |
+
assert _parse_criteria_list({"a": 1}) == ()
|
| 349 |
+
assert _parse_criteria_list(None) == ()
|
| 350 |
+
|
| 351 |
+
def test_skips_non_dict_items(self) -> None:
|
| 352 |
+
out = _parse_criteria_list([
|
| 353 |
+
{"name": "a", "description": "d", "pass_condition": "p"},
|
| 354 |
+
"garbage",
|
| 355 |
+
42,
|
| 356 |
+
])
|
| 357 |
+
assert len(out) == 1
|
| 358 |
+
assert out[0].name == "a"
|
| 359 |
+
|
| 360 |
+
def test_synthesises_missing_name(self) -> None:
|
| 361 |
+
out = _parse_criteria_list([
|
| 362 |
+
{"description": "d", "pass_condition": "p"},
|
| 363 |
+
{"description": "d", "pass_condition": "p"},
|
| 364 |
+
])
|
| 365 |
+
assert out[0].name == "criterion-1"
|
| 366 |
+
assert out[1].name == "criterion-2"
|
| 367 |
+
|
| 368 |
+
def test_all_fields_preserved(self) -> None:
|
| 369 |
+
out = _parse_criteria_list([
|
| 370 |
+
{
|
| 371 |
+
"name": "n", "description": "d",
|
| 372 |
+
"pass_condition": "p", "fail_condition": "f",
|
| 373 |
+
"metric": "m", "threshold": "< 100",
|
| 374 |
+
}
|
| 375 |
+
])
|
| 376 |
+
c = out[0]
|
| 377 |
+
assert c.name == "n"
|
| 378 |
+
assert c.pass_condition == "p"
|
| 379 |
+
assert c.fail_condition == "f"
|
| 380 |
+
assert c.metric == "m"
|
| 381 |
+
assert c.threshold == "< 100"
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
class TestSafeStrTuple:
|
| 385 |
+
def test_none(self) -> None:
|
| 386 |
+
assert _safe_str_tuple(None) == ()
|
| 387 |
+
|
| 388 |
+
def test_list(self) -> None:
|
| 389 |
+
assert _safe_str_tuple(["a", "b"]) == ("a", "b")
|
| 390 |
+
|
| 391 |
+
def test_drops_empty(self) -> None:
|
| 392 |
+
assert _safe_str_tuple(["a", "", None, "b"]) == ("a", "b")
|
| 393 |
+
|
| 394 |
+
def test_string_fallback(self) -> None:
|
| 395 |
+
out = _safe_str_tuple("- first\n* second\nthird")
|
| 396 |
+
assert out == ("first", "second", "third")
|
| 397 |
+
|
| 398 |
+
def test_non_list_non_string(self) -> None:
|
| 399 |
+
assert _safe_str_tuple(42) == ()
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
# ── augmented_system_prompt_with_contract ────────────────────────────────
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
class TestAugmentedSystemPromptWithContract:
|
| 406 |
+
def test_contract_embedded(self) -> None:
|
| 407 |
+
contract = Contract(
|
| 408 |
+
task="t", summary="the contract summary",
|
| 409 |
+
criteria=(
|
| 410 |
+
ContractCriterion(
|
| 411 |
+
name="n", description="d",
|
| 412 |
+
pass_condition="MUST return 422",
|
| 413 |
+
),
|
| 414 |
+
),
|
| 415 |
+
scope_in=(), scope_out=(), approach="",
|
| 416 |
+
usage=Usage(), raw_json="",
|
| 417 |
+
)
|
| 418 |
+
out = augmented_system_prompt_with_contract("base", contract)
|
| 419 |
+
assert "base" in out
|
| 420 |
+
assert "# Sprint Contract" in out
|
| 421 |
+
assert "MUST return 422" in out
|
| 422 |
+
assert "the contract summary" in out
|
| 423 |
+
assert "non-negotiable" in out
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
# ── run_with_evaluation with contract_builder ─────────────────────────────
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
class TestRunWithContract:
|
| 430 |
+
def test_contract_criteria_used_by_evaluator(self) -> None:
|
| 431 |
+
# Response order: planner, contract, generator, evaluator
|
| 432 |
+
provider = _Scripted([
|
| 433 |
+
_resp(_VALID_PLAN_JSON),
|
| 434 |
+
_resp(_VALID_CONTRACT_JSON),
|
| 435 |
+
_resp("generator answer"),
|
| 436 |
+
_resp(json.dumps({
|
| 437 |
+
"verdict": "pass",
|
| 438 |
+
"overall_score": 1.0,
|
| 439 |
+
"criteria": [],
|
| 440 |
+
"summary_feedback": "good",
|
| 441 |
+
"revision_directive": "",
|
| 442 |
+
})),
|
| 443 |
+
])
|
| 444 |
+
outcome = run_with_evaluation(
|
| 445 |
+
provider=provider,
|
| 446 |
+
system_prompt="sys",
|
| 447 |
+
task="t",
|
| 448 |
+
evaluator=Evaluator(provider),
|
| 449 |
+
planner=Planner(provider),
|
| 450 |
+
contract_builder=ContractBuilder(provider),
|
| 451 |
+
max_rounds=1,
|
| 452 |
+
)
|
| 453 |
+
# Outcome carries plan + contract.
|
| 454 |
+
assert outcome.plan is not None
|
| 455 |
+
assert outcome.contract is not None
|
| 456 |
+
assert outcome.contract.summary.startswith("Ensure")
|
| 457 |
+
# Evaluator call (4th) should see contract-derived criteria.
|
| 458 |
+
evaluator_call = provider.calls[3]
|
| 459 |
+
user_content = next(
|
| 460 |
+
m.content for m in evaluator_call["messages"] if m.role == "user"
|
| 461 |
+
)
|
| 462 |
+
assert "POST with empty body returns HTTP 422" in user_content
|
| 463 |
+
|
| 464 |
+
def test_contract_prompt_injected_into_generator(self) -> None:
|
| 465 |
+
provider = _Scripted([
|
| 466 |
+
_resp(_VALID_PLAN_JSON),
|
| 467 |
+
_resp(_VALID_CONTRACT_JSON),
|
| 468 |
+
_resp("gen answer"),
|
| 469 |
+
_resp(json.dumps({
|
| 470 |
+
"verdict": "pass", "overall_score": 1.0, "criteria": [],
|
| 471 |
+
"summary_feedback": "", "revision_directive": "",
|
| 472 |
+
})),
|
| 473 |
+
])
|
| 474 |
+
run_with_evaluation(
|
| 475 |
+
provider=provider,
|
| 476 |
+
system_prompt="base-prompt",
|
| 477 |
+
task="t",
|
| 478 |
+
evaluator=Evaluator(provider),
|
| 479 |
+
planner=Planner(provider),
|
| 480 |
+
contract_builder=ContractBuilder(provider),
|
| 481 |
+
max_rounds=1,
|
| 482 |
+
)
|
| 483 |
+
# Generator call (3rd) should see contract markdown in system prompt.
|
| 484 |
+
generator_call = provider.calls[2]
|
| 485 |
+
sys_content = next(
|
| 486 |
+
m.content for m in generator_call["messages"] if m.role == "system"
|
| 487 |
+
)
|
| 488 |
+
assert "# Sprint Contract" in sys_content
|
| 489 |
+
assert "non-negotiable" in sys_content
|
| 490 |
+
# Plan's narrative still present too (base + contract embeds).
|
| 491 |
+
assert "base-prompt" in sys_content
|
| 492 |
+
|
| 493 |
+
def test_total_usage_includes_contract_cost(self) -> None:
|
| 494 |
+
# Each response reports 10 input + 20 output → 40 total input.
|
| 495 |
+
provider = _Scripted([
|
| 496 |
+
_resp(_VALID_PLAN_JSON), # planner
|
| 497 |
+
_resp(_VALID_CONTRACT_JSON), # contract
|
| 498 |
+
_resp("g"), # generator
|
| 499 |
+
_resp(json.dumps({
|
| 500 |
+
"verdict": "pass", "overall_score": 1.0, "criteria": [],
|
| 501 |
+
"summary_feedback": "", "revision_directive": "",
|
| 502 |
+
})), # evaluator
|
| 503 |
+
])
|
| 504 |
+
outcome = run_with_evaluation(
|
| 505 |
+
provider=provider,
|
| 506 |
+
system_prompt="s",
|
| 507 |
+
task="t",
|
| 508 |
+
evaluator=Evaluator(provider),
|
| 509 |
+
planner=Planner(provider),
|
| 510 |
+
contract_builder=ContractBuilder(provider),
|
| 511 |
+
max_rounds=1,
|
| 512 |
+
)
|
| 513 |
+
assert outcome.total_usage.input_tokens == 40
|
| 514 |
+
assert outcome.total_usage.output_tokens == 80
|
| 515 |
+
|
| 516 |
+
def test_contract_without_planner_also_works(self) -> None:
|
| 517 |
+
"""Contract can run without a plan — library escape hatch."""
|
| 518 |
+
provider = _Scripted([
|
| 519 |
+
_resp(_VALID_CONTRACT_JSON),
|
| 520 |
+
_resp("g"),
|
| 521 |
+
_resp(json.dumps({
|
| 522 |
+
"verdict": "pass", "overall_score": 1.0, "criteria": [],
|
| 523 |
+
"summary_feedback": "", "revision_directive": "",
|
| 524 |
+
})),
|
| 525 |
+
])
|
| 526 |
+
outcome = run_with_evaluation(
|
| 527 |
+
provider=provider,
|
| 528 |
+
system_prompt="s",
|
| 529 |
+
task="t",
|
| 530 |
+
evaluator=Evaluator(provider),
|
| 531 |
+
planner=None,
|
| 532 |
+
contract_builder=ContractBuilder(provider),
|
| 533 |
+
max_rounds=1,
|
| 534 |
+
)
|
| 535 |
+
assert outcome.plan is None
|
| 536 |
+
assert outcome.contract is not None
|
| 537 |
+
|
| 538 |
+
def test_empty_contract_criteria_falls_back_to_evaluator_defaults(
|
| 539 |
+
self,
|
| 540 |
+
) -> None:
|
| 541 |
+
"""When the contract builder produces no criteria (bad JSON),
|
| 542 |
+
the evaluator still runs with its default criteria set."""
|
| 543 |
+
empty_contract_json = json.dumps({
|
| 544 |
+
"summary": "stub", "criteria": [],
|
| 545 |
+
"scope_in": [], "scope_out": [], "approach": "",
|
| 546 |
+
})
|
| 547 |
+
provider = _Scripted([
|
| 548 |
+
_resp(_VALID_PLAN_JSON),
|
| 549 |
+
_resp(empty_contract_json),
|
| 550 |
+
_resp("g"),
|
| 551 |
+
_resp(json.dumps({
|
| 552 |
+
"verdict": "pass", "overall_score": 1.0, "criteria": [],
|
| 553 |
+
"summary_feedback": "", "revision_directive": "",
|
| 554 |
+
})),
|
| 555 |
+
])
|
| 556 |
+
outcome = run_with_evaluation(
|
| 557 |
+
provider=provider,
|
| 558 |
+
system_prompt="s",
|
| 559 |
+
task="t",
|
| 560 |
+
evaluator=Evaluator(provider),
|
| 561 |
+
planner=Planner(provider),
|
| 562 |
+
contract_builder=ContractBuilder(provider),
|
| 563 |
+
max_rounds=1,
|
| 564 |
+
)
|
| 565 |
+
# Contract captured but empty.
|
| 566 |
+
assert outcome.contract is not None
|
| 567 |
+
assert outcome.contract.criteria == ()
|
| 568 |
+
# Evaluator call saw the planner's success_criteria (since
|
| 569 |
+
# the contract had nothing to replace them with).
|
| 570 |
+
evaluator_call = provider.calls[3]
|
| 571 |
+
user_content = next(
|
| 572 |
+
m.content for m in evaluator_call["messages"] if m.role == "user"
|
| 573 |
+
)
|
| 574 |
+
# Planner criteria survive.
|
| 575 |
+
assert "Empty input should be rejected" in user_content
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
# ── CLI integration ───────────────────────────────────────────────────────
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
@pytest.fixture()
|
| 582 |
+
def fake_litellm_contract(monkeypatch: pytest.MonkeyPatch):
|
| 583 |
+
fake = types.ModuleType("litellm")
|
| 584 |
+
calls: list[dict[str, Any]] = []
|
| 585 |
+
|
| 586 |
+
def _mk(content: str) -> dict[str, Any]:
|
| 587 |
+
return {
|
| 588 |
+
"choices": [
|
| 589 |
+
{"message": {"content": content}, "finish_reason": "stop"}
|
| 590 |
+
],
|
| 591 |
+
"usage": {"prompt_tokens": 5, "completion_tokens": 10},
|
| 592 |
+
}
|
| 593 |
+
|
| 594 |
+
# Default queue: planner → contract → generator → evaluator(pass).
|
| 595 |
+
fake._responses = [ # type: ignore[attr-defined]
|
| 596 |
+
_mk(_VALID_PLAN_JSON),
|
| 597 |
+
_mk(_VALID_CONTRACT_JSON),
|
| 598 |
+
_mk("done"),
|
| 599 |
+
_mk(json.dumps({
|
| 600 |
+
"verdict": "pass", "overall_score": 1.0, "criteria": [],
|
| 601 |
+
"summary_feedback": "fine", "revision_directive": "",
|
| 602 |
+
})),
|
| 603 |
+
]
|
| 604 |
+
|
| 605 |
+
def completion(**kwargs):
|
| 606 |
+
calls.append(kwargs)
|
| 607 |
+
if not fake._responses: # type: ignore[attr-defined]
|
| 608 |
+
raise RuntimeError("fake: no more responses")
|
| 609 |
+
return fake._responses.pop(0) # type: ignore[attr-defined]
|
| 610 |
+
|
| 611 |
+
fake.completion = completion # type: ignore[attr-defined]
|
| 612 |
+
fake._calls = calls # type: ignore[attr-defined]
|
| 613 |
+
fake._mk = _mk # type: ignore[attr-defined]
|
| 614 |
+
monkeypatch.setitem(sys.modules, "litellm", fake)
|
| 615 |
+
return fake
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
class TestCliContract:
|
| 619 |
+
def test_contract_without_planner_rejected(self, tmp_path: Path) -> None:
|
| 620 |
+
from ctx.cli.run import main
|
| 621 |
+
|
| 622 |
+
with pytest.raises(SystemExit, match="--contract requires --planner"):
|
| 623 |
+
main(
|
| 624 |
+
[
|
| 625 |
+
"run",
|
| 626 |
+
"--model", "ollama/x",
|
| 627 |
+
"--task", "t",
|
| 628 |
+
"--sessions-dir", str(tmp_path),
|
| 629 |
+
"--evaluator",
|
| 630 |
+
"--contract",
|
| 631 |
+
"--no-ctx-tools",
|
| 632 |
+
"--quiet",
|
| 633 |
+
]
|
| 634 |
+
)
|
| 635 |
+
|
| 636 |
+
def test_contract_without_evaluator_rejected(
|
| 637 |
+
self, tmp_path: Path,
|
| 638 |
+
) -> None:
|
| 639 |
+
"""--contract is only meaningful with --evaluator + --planner."""
|
| 640 |
+
# Without --evaluator the contract flag is silently ignored
|
| 641 |
+
# (the solo path ignores it since run_with_evaluation isn't
|
| 642 |
+
# entered); that's acceptable behaviour — document but don't
|
| 643 |
+
# error. This test pins the current behaviour so a future
|
| 644 |
+
# change is explicit.
|
| 645 |
+
from ctx.cli.run import main
|
| 646 |
+
|
| 647 |
+
# Should not raise — --contract is silently ignored in the
|
| 648 |
+
# solo path (run_with_evaluation isn't entered). The solo
|
| 649 |
+
# path with --planner makes TWO provider calls: the planner
|
| 650 |
+
# call and the Generator's single iteration.
|
| 651 |
+
fake = types.ModuleType("litellm")
|
| 652 |
+
|
| 653 |
+
def _mk(content: str) -> dict[str, Any]:
|
| 654 |
+
return {
|
| 655 |
+
"choices": [
|
| 656 |
+
{"message": {"content": content}, "finish_reason": "stop"}
|
| 657 |
+
],
|
| 658 |
+
"usage": {"prompt_tokens": 1, "completion_tokens": 1},
|
| 659 |
+
}
|
| 660 |
+
|
| 661 |
+
fake._responses = [ # type: ignore[attr-defined]
|
| 662 |
+
_mk(_VALID_PLAN_JSON), # planner call
|
| 663 |
+
_mk("generator answer"), # generator
|
| 664 |
+
]
|
| 665 |
+
|
| 666 |
+
def completion(**kwargs):
|
| 667 |
+
return fake._responses.pop(0) # type: ignore[attr-defined]
|
| 668 |
+
|
| 669 |
+
fake.completion = completion # type: ignore[attr-defined]
|
| 670 |
+
import sys as _sys
|
| 671 |
+
_sys.modules["litellm"] = fake
|
| 672 |
+
exit_code = main(
|
| 673 |
+
[
|
| 674 |
+
"run",
|
| 675 |
+
"--model", "ollama/x",
|
| 676 |
+
"--task", "t",
|
| 677 |
+
"--sessions-dir", str(tmp_path),
|
| 678 |
+
"--planner", # planner enabled but evaluator isn't
|
| 679 |
+
"--contract", # contract solo path doesn't reach run_with_eval
|
| 680 |
+
"--no-ctx-tools",
|
| 681 |
+
"--quiet",
|
| 682 |
+
]
|
| 683 |
+
)
|
| 684 |
+
assert exit_code == 0
|
| 685 |
+
|
| 686 |
+
def test_contract_persisted_in_jsonl(
|
| 687 |
+
self, fake_litellm_contract: Any, tmp_path: Path,
|
| 688 |
+
) -> None:
|
| 689 |
+
from ctx.cli.run import main
|
| 690 |
+
|
| 691 |
+
main(
|
| 692 |
+
[
|
| 693 |
+
"run",
|
| 694 |
+
"--model", "ollama/x",
|
| 695 |
+
"--task", "add validation",
|
| 696 |
+
"--sessions-dir", str(tmp_path),
|
| 697 |
+
"--session-id", "cn-run",
|
| 698 |
+
"--planner",
|
| 699 |
+
"--evaluator",
|
| 700 |
+
"--contract",
|
| 701 |
+
"--no-ctx-tools",
|
| 702 |
+
"--quiet",
|
| 703 |
+
]
|
| 704 |
+
)
|
| 705 |
+
# JSONL should carry a 'contract' event with the refined criteria.
|
| 706 |
+
events = [
|
| 707 |
+
json.loads(line)
|
| 708 |
+
for line in (tmp_path / "cn-run.jsonl").read_text(encoding="utf-8").splitlines()
|
| 709 |
+
if line
|
| 710 |
+
]
|
| 711 |
+
contract_events = [e for e in events if e.get("type") == "contract"]
|
| 712 |
+
assert len(contract_events) == 1
|
| 713 |
+
ce = contract_events[0]
|
| 714 |
+
assert ce["summary"].startswith("Ensure")
|
| 715 |
+
assert len(ce["criteria"]) == 2
|
| 716 |
+
# session_start metadata contract_used True.
|
| 717 |
+
first = events[0]
|
| 718 |
+
assert first["type"] == "session_start"
|
| 719 |
+
assert first["contract_used"] is True
|
| 720 |
+
|
| 721 |
+
def test_contract_model_override(
|
| 722 |
+
self, fake_litellm_contract: Any, tmp_path: Path,
|
| 723 |
+
) -> None:
|
| 724 |
+
from ctx.cli.run import main
|
| 725 |
+
|
| 726 |
+
main(
|
| 727 |
+
[
|
| 728 |
+
"run",
|
| 729 |
+
"--model", "ollama/main",
|
| 730 |
+
"--contract-model", "ollama/contract",
|
| 731 |
+
"--task", "t",
|
| 732 |
+
"--sessions-dir", str(tmp_path),
|
| 733 |
+
"--session-id", "cn-override",
|
| 734 |
+
"--planner",
|
| 735 |
+
"--evaluator",
|
| 736 |
+
"--contract",
|
| 737 |
+
"--no-ctx-tools",
|
| 738 |
+
"--quiet",
|
| 739 |
+
]
|
| 740 |
+
)
|
| 741 |
+
calls = fake_litellm_contract._calls
|
| 742 |
+
# Order: planner → contract → generator → evaluator
|
| 743 |
+
contract_call = calls[1]
|
| 744 |
+
assert contract_call["model"] == "ollama/contract"
|
src/tests/test_harness_state.py
CHANGED
|
@@ -1,674 +1,674 @@
|
|
| 1 |
-
"""
|
| 2 |
-
test_harness_state.py -- SessionStore / JsonlObserver / load_session tests.
|
| 3 |
-
|
| 4 |
-
Covers:
|
| 5 |
-
* SessionStore lifecycle + append-mode (resume) safety
|
| 6 |
-
* Event serialisation for every event type the observer emits
|
| 7 |
-
* JsonlObserver drives a round-trip: a run_loop session written
|
| 8 |
-
to disk + load_session replay reconstructs the same conversation
|
| 9 |
-
* Malformed-line tolerance on the reader
|
| 10 |
-
* ``list_sessions`` + path helpers
|
| 11 |
-
* Session-id validation rejects traversal-shaped ids
|
| 12 |
-
"""
|
| 13 |
-
|
| 14 |
-
from __future__ import annotations
|
| 15 |
-
|
| 16 |
-
import json
|
| 17 |
-
from pathlib import Path
|
| 18 |
-
|
| 19 |
-
import pytest
|
| 20 |
-
|
| 21 |
-
from ctx.adapters.generic.loop import run_loop, LoopResult
|
| 22 |
-
from ctx.adapters.generic.providers import (
|
| 23 |
-
CompletionResponse,
|
| 24 |
-
Message,
|
| 25 |
-
ModelProvider,
|
| 26 |
-
ToolCall,
|
| 27 |
-
ToolDefinition,
|
| 28 |
-
Usage,
|
| 29 |
-
)
|
| 30 |
-
from ctx.adapters.generic.state import (
|
| 31 |
-
JsonlObserver,
|
| 32 |
-
SessionStore,
|
| 33 |
-
_safe_session_id,
|
| 34 |
-
default_sessions_dir,
|
| 35 |
-
list_sessions,
|
| 36 |
-
load_session,
|
| 37 |
-
new_session_id,
|
| 38 |
-
)
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
# ── Scripted provider for the round-trip tests ─────────────────────────────
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
def _symlink_or_skip(link: Path, target: Path) -> None:
|
| 45 |
-
try:
|
| 46 |
-
link.symlink_to(target)
|
| 47 |
-
except OSError as exc:
|
| 48 |
-
pytest.skip(f"symlinks unavailable in this environment: {exc}")
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
class _Scripted(ModelProvider):
|
| 52 |
-
name = "scripted"
|
| 53 |
-
|
| 54 |
-
def __init__(self, responses: list[CompletionResponse]) -> None:
|
| 55 |
-
self._responses = list(responses)
|
| 56 |
-
|
| 57 |
-
def complete(
|
| 58 |
-
self,
|
| 59 |
-
messages: list[Message],
|
| 60 |
-
tools: list[ToolDefinition] | None = None,
|
| 61 |
-
*,
|
| 62 |
-
model: str | None = None,
|
| 63 |
-
temperature: float = 0.7,
|
| 64 |
-
max_tokens: int | None = None,
|
| 65 |
-
) -> CompletionResponse:
|
| 66 |
-
if not self._responses:
|
| 67 |
-
raise RuntimeError("scripted: no more responses")
|
| 68 |
-
return self._responses.pop(0)
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
def _stop_response(content: str = "done") -> CompletionResponse:
|
| 72 |
-
return CompletionResponse(
|
| 73 |
-
content=content,
|
| 74 |
-
tool_calls=(),
|
| 75 |
-
finish_reason="stop",
|
| 76 |
-
usage=Usage(input_tokens=5, output_tokens=3),
|
| 77 |
-
provider="scripted",
|
| 78 |
-
model="x",
|
| 79 |
-
)
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
def _tool_response(*calls: ToolCall) -> CompletionResponse:
|
| 83 |
-
return CompletionResponse(
|
| 84 |
-
content="",
|
| 85 |
-
tool_calls=tuple(calls),
|
| 86 |
-
finish_reason="tool_calls",
|
| 87 |
-
usage=Usage(input_tokens=10, output_tokens=4),
|
| 88 |
-
provider="scripted",
|
| 89 |
-
model="x",
|
| 90 |
-
)
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
# ── Session-id safety ────────────────────────────────────────────────────
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
class TestSessionIdValidation:
|
| 97 |
-
@pytest.mark.parametrize(
|
| 98 |
-
"bad",
|
| 99 |
-
[
|
| 100 |
-
"",
|
| 101 |
-
"../evil",
|
| 102 |
-
"a/b",
|
| 103 |
-
"a\\b",
|
| 104 |
-
".",
|
| 105 |
-
"..",
|
| 106 |
-
"has space",
|
| 107 |
-
"has.dot", # dots disallowed — risks '.jsonl' shadowing
|
| 108 |
-
"a" * 129, # too long
|
| 109 |
-
],
|
| 110 |
-
)
|
| 111 |
-
def test_rejects_bad(self, bad: str) -> None:
|
| 112 |
-
with pytest.raises((ValueError, TypeError)):
|
| 113 |
-
_safe_session_id(bad)
|
| 114 |
-
|
| 115 |
-
@pytest.mark.parametrize(
|
| 116 |
-
"good",
|
| 117 |
-
[
|
| 118 |
-
"abc123",
|
| 119 |
-
"nightly_backfill",
|
| 120 |
-
"2026-04-24-trial",
|
| 121 |
-
"f9eaad988e79443b85b819099f3679a3",
|
| 122 |
-
],
|
| 123 |
-
)
|
| 124 |
-
def test_accepts_good(self, good: str) -> None:
|
| 125 |
-
assert _safe_session_id(good) == good
|
| 126 |
-
|
| 127 |
-
def test_non_string_rejected(self) -> None:
|
| 128 |
-
with pytest.raises((ValueError, TypeError)):
|
| 129 |
-
_safe_session_id(None) # type: ignore[arg-type]
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
class TestSessionIdGen:
|
| 133 |
-
def test_new_id_is_32_char_hex(self) -> None:
|
| 134 |
-
sid = new_session_id()
|
| 135 |
-
assert len(sid) == 32
|
| 136 |
-
assert all(c in "0123456789abcdef" for c in sid)
|
| 137 |
-
|
| 138 |
-
def test_ids_are_unique(self) -> None:
|
| 139 |
-
assert new_session_id() != new_session_id()
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
# ── default_sessions_dir ─────────────────────────────────────────────────
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
class TestDefaultSessionsDir:
|
| 146 |
-
def test_under_home(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
| 147 |
-
monkeypatch.setenv("HOME", str(tmp_path))
|
| 148 |
-
monkeypatch.setenv("USERPROFILE", str(tmp_path))
|
| 149 |
-
p = default_sessions_dir()
|
| 150 |
-
assert p == tmp_path / ".ctx" / "sessions"
|
| 151 |
-
|
| 152 |
-
def test_not_created_by_call(
|
| 153 |
-
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
| 154 |
-
) -> None:
|
| 155 |
-
monkeypatch.setenv("HOME", str(tmp_path))
|
| 156 |
-
monkeypatch.setenv("USERPROFILE", str(tmp_path))
|
| 157 |
-
p = default_sessions_dir()
|
| 158 |
-
# Intentionally lazy — SessionStore creates it, not the helper.
|
| 159 |
-
assert not p.exists()
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
# ── SessionStore ────────
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
class TestSessionStore:
|
| 166 |
-
def test_create_makes_parent_dir(self, tmp_path: Path) -> None:
|
| 167 |
-
nested = tmp_path / "deeply" / "nested"
|
| 168 |
-
store = SessionStore.create(
|
| 169 |
-
session_id="abc", sessions_dir=nested,
|
| 170 |
-
)
|
| 171 |
-
try:
|
| 172 |
-
assert nested.is_dir()
|
| 173 |
-
assert store.path == nested / "abc.jsonl"
|
| 174 |
-
finally:
|
| 175 |
-
store.close()
|
| 176 |
-
|
| 177 |
-
def test_create_auto_generates_id(self, tmp_path: Path) -> None:
|
| 178 |
-
store = SessionStore.create(sessions_dir=tmp_path)
|
| 179 |
-
try:
|
| 180 |
-
assert len(store.session_id) == 32
|
| 181 |
-
finally:
|
| 182 |
-
store.close()
|
| 183 |
-
|
| 184 |
-
def test_write_event_shapes_line(self, tmp_path: Path) -> None:
|
| 185 |
-
store = SessionStore.create(session_id="s1", sessions_dir=tmp_path)
|
| 186 |
-
try:
|
| 187 |
-
store.write_event("custom", {"key": "value"})
|
| 188 |
-
finally:
|
| 189 |
-
store.close()
|
| 190 |
-
raw = (tmp_path / "s1.jsonl").read_text(encoding="utf-8")
|
| 191 |
-
event = json.loads(raw)
|
| 192 |
-
assert event["type"] == "custom"
|
| 193 |
-
assert event["session_id"] == "s1"
|
| 194 |
-
assert event["key"] == "value"
|
| 195 |
-
assert "ts" in event
|
| 196 |
-
|
| 197 |
-
def test_create_rejects_existing_session_by_default(self, tmp_path: Path) -> None:
|
| 198 |
-
path = tmp_path / "s1.jsonl"
|
| 199 |
-
path.write_text("sentinel\n", encoding="utf-8")
|
| 200 |
-
with pytest.raises(FileExistsError):
|
| 201 |
-
SessionStore.create(session_id="s1", sessions_dir=tmp_path)
|
| 202 |
-
assert path.read_text(encoding="utf-8") == "sentinel\n"
|
| 203 |
-
|
| 204 |
-
def test_create_can_overwrite_existing_session_explicitly(
|
| 205 |
-
self, tmp_path: Path,
|
| 206 |
-
) -> None:
|
| 207 |
-
path = tmp_path / "s1.jsonl"
|
| 208 |
-
path.write_text("sentinel\n", encoding="utf-8")
|
| 209 |
-
store = SessionStore.create(
|
| 210 |
-
session_id="s1",
|
| 211 |
-
sessions_dir=tmp_path,
|
| 212 |
-
overwrite=True,
|
| 213 |
-
)
|
| 214 |
-
store.close()
|
| 215 |
-
assert path.read_text(encoding="utf-8") == ""
|
| 216 |
-
|
| 217 |
-
def test_create_overwrite_rejects_symlinked_session_log(
|
| 218 |
-
self, tmp_path: Path,
|
| 219 |
-
) -> None:
|
| 220 |
-
outside = tmp_path / "outside.jsonl"
|
| 221 |
-
outside.write_text("sentinel\n", encoding="utf-8")
|
| 222 |
-
_symlink_or_skip(tmp_path / "s1.jsonl", outside)
|
| 223 |
-
|
| 224 |
-
with pytest.raises(ValueError, match="symlink"):
|
| 225 |
-
SessionStore.create(
|
| 226 |
-
session_id="s1",
|
| 227 |
-
sessions_dir=tmp_path,
|
| 228 |
-
overwrite=True,
|
| 229 |
-
)
|
| 230 |
-
|
| 231 |
-
assert outside.read_text(encoding="utf-8") == "sentinel\n"
|
| 232 |
-
|
| 233 |
-
def test_context_manager(self, tmp_path: Path) -> None:
|
| 234 |
-
with SessionStore.create(session_id="s1", sessions_dir=tmp_path) as store:
|
| 235 |
-
store.write_event("x", {})
|
| 236 |
-
assert store.closed
|
| 237 |
-
assert (tmp_path / "s1.jsonl").is_file()
|
| 238 |
-
|
| 239 |
-
def test_write_after_close_raises(self, tmp_path: Path) -> None:
|
| 240 |
-
store = SessionStore.create(session_id="s1", sessions_dir=tmp_path)
|
| 241 |
-
store.close()
|
| 242 |
-
with pytest.raises(RuntimeError, match="closed"):
|
| 243 |
-
store.write_event("x", {})
|
| 244 |
-
|
| 245 |
-
def test_close_is_idempotent(self, tmp_path: Path) -> None:
|
| 246 |
-
store = SessionStore.create(session_id="s1", sessions_dir=tmp_path)
|
| 247 |
-
store.close()
|
| 248 |
-
store.close() # must not raise
|
| 249 |
-
|
| 250 |
-
def test_attach_requires_existing_file(self, tmp_path: Path) -> None:
|
| 251 |
-
with pytest.raises(FileNotFoundError):
|
| 252 |
-
SessionStore.attach("nope", sessions_dir=tmp_path)
|
| 253 |
-
|
| 254 |
-
def test_attach_rejects_symlinked_session_log(self, tmp_path: Path) -> None:
|
| 255 |
-
outside = tmp_path / "outside.jsonl"
|
| 256 |
-
outside.write_text("sentinel\n", encoding="utf-8")
|
| 257 |
-
_symlink_or_skip(tmp_path / "s1.jsonl", outside)
|
| 258 |
-
|
| 259 |
-
with pytest.raises(ValueError, match="symlink"):
|
| 260 |
-
SessionStore.attach("s1", sessions_dir=tmp_path)
|
| 261 |
-
|
| 262 |
-
def test_attach_appends_to_existing_file(self, tmp_path: Path) -> None:
|
| 263 |
-
# Create + write one event.
|
| 264 |
-
s1 = SessionStore.create(session_id="s1", sessions_dir=tmp_path)
|
| 265 |
-
s1.write_event("first", {})
|
| 266 |
-
s1.close()
|
| 267 |
-
# Attach + append.
|
| 268 |
-
s2 = SessionStore.attach("s1", sessions_dir=tmp_path)
|
| 269 |
-
s2.write_event("second", {})
|
| 270 |
-
s2.close()
|
| 271 |
-
lines = (tmp_path / "s1.jsonl").read_text(encoding="utf-8").strip().split("\n")
|
| 272 |
-
types = [json.loads(line)["type"] for line in lines]
|
| 273 |
-
assert types == ["first", "second"]
|
| 274 |
-
|
| 275 |
-
def test_unicode_content_roundtrips(self, tmp_path: Path) -> None:
|
| 276 |
-
with SessionStore.create(session_id="uni", sessions_dir=tmp_path) as s:
|
| 277 |
-
s.write_event("x", {"content": "café 日本 🚀"})
|
| 278 |
-
event = json.loads((tmp_path / "uni.jsonl").read_text(encoding="utf-8"))
|
| 279 |
-
assert event["content"] == "café 日本 🚀"
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
# ── Convenience writers ───────────────
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
class TestConvenienceWriters:
|
| 286 |
-
def test_write_session_start(self, tmp_path: Path) -> None:
|
| 287 |
-
with SessionStore.create(session_id="s", sessions_dir=tmp_path) as store:
|
| 288 |
-
store.write_session_start({"task": "hello", "model": "ollama/x"})
|
| 289 |
-
event = json.loads((tmp_path / "s.jsonl").read_text(encoding="utf-8"))
|
| 290 |
-
assert event["type"] == "session_start"
|
| 291 |
-
assert event["task"] == "hello"
|
| 292 |
-
assert event["model"] == "ollama/x"
|
| 293 |
-
|
| 294 |
-
def test_write_message(self, tmp_path: Path) -> None:
|
| 295 |
-
with SessionStore.create(session_id="s", sessions_dir=tmp_path) as store:
|
| 296 |
-
store.write_message(Message(role="user", content="hi"))
|
| 297 |
-
store.write_message(
|
| 298 |
-
Message(
|
| 299 |
-
role="assistant",
|
| 300 |
-
content="",
|
| 301 |
-
tool_calls=(ToolCall(id="c1", name="t", arguments={"x": 1}),),
|
| 302 |
-
)
|
| 303 |
-
)
|
| 304 |
-
events = [
|
| 305 |
-
json.loads(line) for line in
|
| 306 |
-
(tmp_path / "s.jsonl").read_text(encoding="utf-8").splitlines() if line
|
| 307 |
-
]
|
| 308 |
-
assert events[0]["role"] == "user"
|
| 309 |
-
assert events[1]["tool_calls"][0]["arguments"] == {"x": 1}
|
| 310 |
-
|
| 311 |
-
def test_write_model_response(self, tmp_path: Path) -> None:
|
| 312 |
-
with SessionStore.create(session_id="s", sessions_dir=tmp_path) as store:
|
| 313 |
-
store.write_model_response(
|
| 314 |
-
3,
|
| 315 |
-
CompletionResponse(
|
| 316 |
-
content="ok",
|
| 317 |
-
tool_calls=(),
|
| 318 |
-
finish_reason="stop",
|
| 319 |
-
usage=Usage(input_tokens=10, output_tokens=5, cost_usd=0.002),
|
| 320 |
-
provider="litellm",
|
| 321 |
-
model="openrouter/x",
|
| 322 |
-
),
|
| 323 |
-
)
|
| 324 |
-
event = json.loads((tmp_path / "s.jsonl").read_text(encoding="utf-8"))
|
| 325 |
-
assert event["iteration"] == 3
|
| 326 |
-
assert event["usage"]["cost_usd"] == 0.002
|
| 327 |
-
assert event["provider"] == "litellm"
|
| 328 |
-
assert event["model"] == "openrouter/x"
|
| 329 |
-
|
| 330 |
-
def test_write_tool_call(self, tmp_path: Path) -> None:
|
| 331 |
-
with SessionStore.create(session_id="s", sessions_dir=tmp_path) as store:
|
| 332 |
-
store.write_tool_call(
|
| 333 |
-
1,
|
| 334 |
-
ToolCall(id="c1", name="fs__read", arguments={"path": "/tmp"}),
|
| 335 |
-
result="file contents",
|
| 336 |
-
error=None,
|
| 337 |
-
)
|
| 338 |
-
event = json.loads((tmp_path / "s.jsonl").read_text(encoding="utf-8"))
|
| 339 |
-
assert event["call"]["arguments"] == {"path": "/tmp"}
|
| 340 |
-
assert event["error"] is None
|
| 341 |
-
|
| 342 |
-
def test_write_stop(self, tmp_path: Path) -> None:
|
| 343 |
-
with SessionStore.create(session_id="s", sessions_dir=tmp_path) as store:
|
| 344 |
-
store.write_stop(
|
| 345 |
-
LoopResult(
|
| 346 |
-
stop_reason="completed",
|
| 347 |
-
final_message="done",
|
| 348 |
-
iterations=3,
|
| 349 |
-
usage=Usage(input_tokens=30, output_tokens=15, cost_usd=0.01),
|
| 350 |
-
messages=(),
|
| 351 |
-
detail="",
|
| 352 |
-
)
|
| 353 |
-
)
|
| 354 |
-
event = json.loads((tmp_path / "s.jsonl").read_text(encoding="utf-8"))
|
| 355 |
-
assert event["stop_reason"] == "completed"
|
| 356 |
-
assert event["iterations"] == 3
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
# ── load_session ─────────────────────────────────────────────────────────
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
class TestLoadSession:
|
| 363 |
-
def test_file_not_found(self, tmp_path: Path) -> None:
|
| 364 |
-
with pytest.raises(FileNotFoundError):
|
| 365 |
-
load_session("nope", sessions_dir=tmp_path)
|
| 366 |
-
|
| 367 |
-
def test_rejects_symlinked_session_log(self, tmp_path: Path) -> None:
|
| 368 |
-
outside = tmp_path / "outside.jsonl"
|
| 369 |
-
outside.write_text(
|
| 370 |
-
json.dumps({"type": "session_start", "session_id": "s"}) + "\n",
|
| 371 |
-
encoding="utf-8",
|
| 372 |
-
)
|
| 373 |
-
_symlink_or_skip(tmp_path / "s.jsonl", outside)
|
| 374 |
-
|
| 375 |
-
with pytest.raises(ValueError, match="symlink"):
|
| 376 |
-
load_session("s", sessions_dir=tmp_path)
|
| 377 |
-
|
| 378 |
-
def test_replay_simple_session(self, tmp_path: Path) -> None:
|
| 379 |
-
with SessionStore.create(session_id="s", sessions_dir=tmp_path) as store:
|
| 380 |
-
store.write_session_start({"task": "hello", "model": "x"})
|
| 381 |
-
store.write_message(Message(role="system", content="sys"))
|
| 382 |
-
store.write_message(Message(role="user", content="hi"))
|
| 383 |
-
store.write_message(Message(role="assistant", content="hello back"))
|
| 384 |
-
store.write_stop(
|
| 385 |
-
LoopResult(
|
| 386 |
-
stop_reason="completed", final_message="hello back",
|
| 387 |
-
iterations=1, usage=Usage(), messages=(), detail="",
|
| 388 |
-
)
|
| 389 |
-
)
|
| 390 |
-
state = load_session("s", sessions_dir=tmp_path)
|
| 391 |
-
assert state.session_id == "s"
|
| 392 |
-
assert state.path == tmp_path / "s.jsonl"
|
| 393 |
-
assert [m.role for m in state.messages] == ["system", "user", "assistant"]
|
| 394 |
-
assert state.messages[2].content == "hello back"
|
| 395 |
-
assert state.metadata["task"] == "hello"
|
| 396 |
-
assert state.stopped is True
|
| 397 |
-
assert state.stop_reason == "completed"
|
| 398 |
-
|
| 399 |
-
def test_replay_unstopped_session(self, tmp_path: Path) -> None:
|
| 400 |
-
"""Session that trails off mid-run (no stop event) is flagged."""
|
| 401 |
-
with SessionStore.create(session_id="s", sessions_dir=tmp_path) as store:
|
| 402 |
-
store.write_session_start({"task": "x"})
|
| 403 |
-
store.write_message(Message(role="user", content="hi"))
|
| 404 |
-
state = load_session("s", sessions_dir=tmp_path)
|
| 405 |
-
assert state.stopped is False
|
| 406 |
-
assert state.stop_reason is None
|
| 407 |
-
|
| 408 |
-
def test_replay_tool_call_messages(self, tmp_path: Path) -> None:
|
| 409 |
-
"""Assistant-with-tool_calls + tool-result must round-trip faithfully."""
|
| 410 |
-
with SessionStore.create(session_id="s", sessions_dir=tmp_path) as store:
|
| 411 |
-
store.write_message(Message(role="user", content="go"))
|
| 412 |
-
tc = ToolCall(id="c1", name="srv__fetch", arguments={"url": "https://x"})
|
| 413 |
-
store.write_message(
|
| 414 |
-
Message(role="assistant", content="", tool_calls=(tc,))
|
| 415 |
-
)
|
| 416 |
-
store.write_message(
|
| 417 |
-
Message(role="tool", content="ok", tool_call_id="c1", name="srv__fetch")
|
| 418 |
-
)
|
| 419 |
-
state = load_session("s", sessions_dir=tmp_path)
|
| 420 |
-
assert len(state.messages) == 3
|
| 421 |
-
assistant = state.messages[1]
|
| 422 |
-
assert assistant.tool_calls[0].id == "c1"
|
| 423 |
-
assert assistant.tool_calls[0].arguments == {"url": "https://x"}
|
| 424 |
-
tool_msg = state.messages[2]
|
| 425 |
-
assert tool_msg.tool_call_id == "c1"
|
| 426 |
-
assert tool_msg.name == "srv__fetch"
|
| 427 |
-
|
| 428 |
-
def test_replay_repairs_unresolved_tool_call_tail(self, tmp_path: Path) -> None:
|
| 429 |
-
"""Crash after assistant tool_call message persists must resume safely."""
|
| 430 |
-
tc = ToolCall(id="c1", name="srv__fetch", arguments={"url": "https://x"})
|
| 431 |
-
with SessionStore.create(session_id="s", sessions_dir=tmp_path) as store:
|
| 432 |
-
store.write_message(Message(role="user", content="go"))
|
| 433 |
-
store.write_model_response(1, _tool_response(tc))
|
| 434 |
-
store.write_message(Message(role="assistant", content="", tool_calls=(tc,)))
|
| 435 |
-
|
| 436 |
-
state = load_session("s", sessions_dir=tmp_path)
|
| 437 |
-
|
| 438 |
-
assert [m.role for m in state.messages] == ["user", "assistant", "tool"]
|
| 439 |
-
tool_msg = state.messages[2]
|
| 440 |
-
assert tool_msg.tool_call_id == "c1"
|
| 441 |
-
assert tool_msg.name == "srv__fetch"
|
| 442 |
-
assert tool_msg.content.startswith("ERROR:")
|
| 443 |
-
|
| 444 |
-
def test_malformed_line_is_skipped_not_fatal(self, tmp_path: Path) -> None:
|
| 445 |
-
path = tmp_path / "s.jsonl"
|
| 446 |
-
path.write_text(
|
| 447 |
-
'\n'.join([
|
| 448 |
-
json.dumps({"type": "session_start", "ts": "t", "session_id": "s", "task": "hi"}),
|
| 449 |
-
"this is not json at all",
|
| 450 |
-
json.dumps({"type": "message", "ts": "t", "session_id": "s",
|
| 451 |
-
"role": "user", "content": "ok"}),
|
| 452 |
-
]) + "\n",
|
| 453 |
-
encoding="utf-8",
|
| 454 |
-
)
|
| 455 |
-
state = load_session("s", sessions_dir=tmp_path)
|
| 456 |
-
# Malformed line dropped; valid events still processed.
|
| 457 |
-
assert len(state.messages) == 1
|
| 458 |
-
assert state.metadata["task"] == "hi"
|
| 459 |
-
|
| 460 |
-
def test_empty_lines_are_skipped(self, tmp_path: Path) -> None:
|
| 461 |
-
path = tmp_path / "s.jsonl"
|
| 462 |
-
path.write_text(
|
| 463 |
-
json.dumps({"type": "session_start", "ts": "t", "session_id": "s", "task": "hi"})
|
| 464 |
-
+ "\n\n\n"
|
| 465 |
-
+ json.dumps({"type": "message", "ts": "t", "session_id": "s",
|
| 466 |
-
"role": "user", "content": "hi"})
|
| 467 |
-
+ "\n",
|
| 468 |
-
encoding="utf-8",
|
| 469 |
-
)
|
| 470 |
-
state = load_session("s", sessions_dir=tmp_path)
|
| 471 |
-
assert len(state.messages) == 1
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
# ── list_sessions ────────────────────────────────────────────────────────
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
class TestListSessions:
|
| 478 |
-
def test_empty_dir_returns_empty(self, tmp_path: Path) -> None:
|
| 479 |
-
assert list_sessions(sessions_dir=tmp_path) == []
|
| 480 |
-
|
| 481 |
-
def test_nonexistent_dir_returns_empty(self, tmp_path: Path) -> None:
|
| 482 |
-
assert list_sessions(sessions_dir=tmp_path / "missing") == []
|
| 483 |
-
|
| 484 |
-
def test_only_jsonl_files_listed(self, tmp_path: Path) -> None:
|
| 485 |
-
(tmp_path / "alpha.jsonl").write_text("", encoding="utf-8")
|
| 486 |
-
(tmp_path / "beta.jsonl").write_text("", encoding="utf-8")
|
| 487 |
-
(tmp_path / "not_a_session.txt").write_text("", encoding="utf-8")
|
| 488 |
-
(tmp_path / "subdir").mkdir()
|
| 489 |
-
assert list_sessions(sessions_dir=tmp_path) == ["alpha", "beta"]
|
| 490 |
-
|
| 491 |
-
def test_symlinked_jsonl_files_are_skipped(self, tmp_path: Path) -> None:
|
| 492 |
-
(tmp_path / "alpha.jsonl").write_text("", encoding="utf-8")
|
| 493 |
-
outside = tmp_path / "outside.jsonl"
|
| 494 |
-
outside.write_text("", encoding="utf-8")
|
| 495 |
-
_symlink_or_skip(tmp_path / "linked.jsonl", outside)
|
| 496 |
-
|
| 497 |
-
assert list_sessions(sessions_dir=tmp_path) == ["alpha", "outside"]
|
| 498 |
-
|
| 499 |
-
def test_sorted_alphabetically(self, tmp_path: Path) -> None:
|
| 500 |
-
for name in ("zzz", "aaa", "mmm"):
|
| 501 |
-
(tmp_path / f"{name}.jsonl").write_text("", encoding="utf-8")
|
| 502 |
-
assert list_sessions(sessions_dir=tmp_path) == ["aaa", "mmm", "zzz"]
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
# ── JsonlObserver end-to-end via run_loop ───────────────────────────────
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
class TestJsonlObserverRoundTrip:
|
| 509 |
-
def test_simple_completion_replay(self, tmp_path: Path) -> None:
|
| 510 |
-
provider = _Scripted([_stop_response("final answer")])
|
| 511 |
-
store = SessionStore.create(session_id="trip1", sessions_dir=tmp_path)
|
| 512 |
-
observer = JsonlObserver(
|
| 513 |
-
store,
|
| 514 |
-
session_metadata={"task": "smoke-test", "model": "ollama/x"},
|
| 515 |
-
)
|
| 516 |
-
try:
|
| 517 |
-
result = run_loop(
|
| 518 |
-
provider=provider,
|
| 519 |
-
system_prompt="sys",
|
| 520 |
-
task="hi",
|
| 521 |
-
observer=observer,
|
| 522 |
-
)
|
| 523 |
-
finally:
|
| 524 |
-
store.close()
|
| 525 |
-
|
| 526 |
-
assert result.stop_reason == "completed"
|
| 527 |
-
|
| 528 |
-
state = load_session("trip1", sessions_dir=tmp_path)
|
| 529 |
-
# Replay must match the live conversation byte-for-byte (for
|
| 530 |
-
# roles + content).
|
| 531 |
-
live = [
|
| 532 |
-
(m.role, m.content) for m in result.messages
|
| 533 |
-
]
|
| 534 |
-
replayed = [(m.role, m.content) for m in state.messages]
|
| 535 |
-
assert live == replayed
|
| 536 |
-
assert state.metadata["task"] == "smoke-test"
|
| 537 |
-
assert state.stop_reason == "completed"
|
| 538 |
-
assert state.stopped is True
|
| 539 |
-
|
| 540 |
-
def test_tool_call_round_trip(self, tmp_path: Path) -> None:
|
| 541 |
-
tc = ToolCall(id="c1", name="srv__echo", arguments={"text": "hi"})
|
| 542 |
-
provider = _Scripted(
|
| 543 |
-
[_tool_response(tc), _stop_response("seen hi")]
|
| 544 |
-
)
|
| 545 |
-
store = SessionStore.create(session_id="trip2", sessions_dir=tmp_path)
|
| 546 |
-
observer = JsonlObserver(store, session_metadata={"task": "go"})
|
| 547 |
-
try:
|
| 548 |
-
run_loop(
|
| 549 |
-
provider=provider,
|
| 550 |
-
system_prompt="",
|
| 551 |
-
task="go",
|
| 552 |
-
tool_executor=lambda call: f"echo:{call.arguments['text']}",
|
| 553 |
-
observer=observer,
|
| 554 |
-
)
|
| 555 |
-
finally:
|
| 556 |
-
store.close()
|
| 557 |
-
|
| 558 |
-
state = load_session("trip2", sessions_dir=tmp_path)
|
| 559 |
-
roles = [m.role for m in state.messages]
|
| 560 |
-
# user(task) + assistant(tool_calls) + tool(result) + assistant(final)
|
| 561 |
-
assert roles == ["user", "assistant", "tool", "assistant"]
|
| 562 |
-
tool_msg = state.messages[2]
|
| 563 |
-
assert tool_msg.content == "echo:hi"
|
| 564 |
-
assert tool_msg.tool_call_id == "c1"
|
| 565 |
-
|
| 566 |
-
def test_resume_via_messages_kwarg(self, tmp_path: Path) -> None:
|
| 567 |
-
"""Load a prior session and hand its messages to a fresh run_loop."""
|
| 568 |
-
# First run.
|
| 569 |
-
provider1 = _Scripted([_stop_response("first-answer")])
|
| 570 |
-
store1 = SessionStore.create(session_id="resume1", sessions_dir=tmp_path)
|
| 571 |
-
try:
|
| 572 |
-
run_loop(
|
| 573 |
-
provider=provider1,
|
| 574 |
-
system_prompt="sys",
|
| 575 |
-
task="initial task",
|
| 576 |
-
observer=JsonlObserver(store1, session_metadata={"task": "initial task"}),
|
| 577 |
-
)
|
| 578 |
-
finally:
|
| 579 |
-
store1.close()
|
| 580 |
-
|
| 581 |
-
# Resume: load + feed back.
|
| 582 |
-
state = load_session("resume1", sessions_dir=tmp_path)
|
| 583 |
-
provider2 = _Scripted([_stop_response("resumed-answer")])
|
| 584 |
-
store2 = SessionStore.attach("resume1", sessions_dir=tmp_path)
|
| 585 |
-
try:
|
| 586 |
-
result2 = run_loop(
|
| 587 |
-
provider=provider2,
|
| 588 |
-
system_prompt="sys",
|
| 589 |
-
task="follow-up",
|
| 590 |
-
messages=list(state.messages),
|
| 591 |
-
observer=JsonlObserver(
|
| 592 |
-
store2,
|
| 593 |
-
session_metadata={},
|
| 594 |
-
emit_session_start=False, # already written in first run
|
| 595 |
-
persisted_message_count=len(state.messages),
|
| 596 |
-
),
|
| 597 |
-
append_task_after_messages=True,
|
| 598 |
-
)
|
| 599 |
-
finally:
|
| 600 |
-
store2.close()
|
| 601 |
-
|
| 602 |
-
# First run's conversation is visible in the resumed result.
|
| 603 |
-
resumed_roles = [m.role for m in result2.messages]
|
| 604 |
-
assert resumed_roles == ["system", "user", "assistant", "user", "assistant"]
|
| 605 |
-
contents = [m.content for m in result2.messages]
|
| 606 |
-
assert contents == [
|
| 607 |
-
"sys",
|
| 608 |
-
"initial task",
|
| 609 |
-
"first-answer",
|
| 610 |
-
"follow-up",
|
| 611 |
-
"resumed-answer",
|
| 612 |
-
]
|
| 613 |
-
replayed = load_session("resume1", sessions_dir=tmp_path)
|
| 614 |
-
assert [m.content for m in replayed.messages] == contents
|
| 615 |
-
|
| 616 |
-
def test_metadata_includes_seed_messages(self, tmp_path: Path) -> None:
|
| 617 |
-
"""session_start payload captures the seed conversation."""
|
| 618 |
-
provider = _Scripted([_stop_response("ok")])
|
| 619 |
-
store = SessionStore.create(session_id="meta", sessions_dir=tmp_path)
|
| 620 |
-
observer = JsonlObserver(store, session_metadata={"task": "t"})
|
| 621 |
-
try:
|
| 622 |
-
run_loop(
|
| 623 |
-
provider=provider, system_prompt="sys", task="t", observer=observer,
|
| 624 |
-
)
|
| 625 |
-
finally:
|
| 626 |
-
store.close()
|
| 627 |
-
# Find the session_start event directly so we can inspect seeds.
|
| 628 |
-
first_line = (tmp_path / "meta.jsonl").read_text(encoding="utf-8").splitlines()[0]
|
| 629 |
-
event = json.loads(first_line)
|
| 630 |
-
assert event["type"] == "session_start"
|
| 631 |
-
assert len(event["seed_messages"]) == 2 # system + user(task)
|
| 632 |
-
assert event["seed_messages"][0]["role"] == "system"
|
| 633 |
-
assert event["seed_messages"][1]["role"] == "user"
|
| 634 |
-
|
| 635 |
-
def test_observer_no_emit_start(self, tmp_path: Path) -> None:
|
| 636 |
-
"""When emit_session_start=False the observer doesn't write it — caller did."""
|
| 637 |
-
provider = _Scripted([_stop_response("ok")])
|
| 638 |
-
store = SessionStore.create(session_id="noe", sessions_dir=tmp_path)
|
| 639 |
-
observer = JsonlObserver(
|
| 640 |
-
store, session_metadata={"task": "t"}, emit_session_start=False,
|
| 641 |
-
)
|
| 642 |
-
try:
|
| 643 |
-
run_loop(
|
| 644 |
-
provider=provider, system_prompt="", task="t", observer=observer,
|
| 645 |
-
)
|
| 646 |
-
finally:
|
| 647 |
-
store.close()
|
| 648 |
-
events = [
|
| 649 |
-
json.loads(line) for line in
|
| 650 |
-
(tmp_path / "noe.jsonl").read_text(encoding="utf-8").splitlines() if line
|
| 651 |
-
]
|
| 652 |
-
types = [e["type"] for e in events]
|
| 653 |
-
assert "session_start" not in types
|
| 654 |
-
assert types.count("message") == 2
|
| 655 |
-
|
| 656 |
-
def test_stop_event_always_written(self, tmp_path: Path) -> None:
|
| 657 |
-
provider = _Scripted([_stop_response("ok")])
|
| 658 |
-
store = SessionStore.create(session_id="stop", sessions_dir=tmp_path)
|
| 659 |
-
observer = JsonlObserver(store, session_metadata={"task": "t"})
|
| 660 |
-
try:
|
| 661 |
-
run_loop(
|
| 662 |
-
provider=provider, system_prompt="", task="t", observer=observer,
|
| 663 |
-
)
|
| 664 |
-
finally:
|
| 665 |
-
store.close()
|
| 666 |
-
last_line = (
|
| 667 |
-
(tmp_path / "stop.jsonl")
|
| 668 |
-
.read_text(encoding="utf-8")
|
| 669 |
-
.strip()
|
| 670 |
-
.split("\n")[-1]
|
| 671 |
-
)
|
| 672 |
-
event = json.loads(last_line)
|
| 673 |
-
assert event["type"] == "stop"
|
| 674 |
-
assert event["stop_reason"] == "completed"
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_harness_state.py -- SessionStore / JsonlObserver / load_session tests.
|
| 3 |
+
|
| 4 |
+
Covers:
|
| 5 |
+
* SessionStore lifecycle + append-mode (resume) safety
|
| 6 |
+
* Event serialisation for every event type the observer emits
|
| 7 |
+
* JsonlObserver drives a round-trip: a run_loop session written
|
| 8 |
+
to disk + load_session replay reconstructs the same conversation
|
| 9 |
+
* Malformed-line tolerance on the reader
|
| 10 |
+
* ``list_sessions`` + path helpers
|
| 11 |
+
* Session-id validation rejects traversal-shaped ids
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
import pytest
|
| 20 |
+
|
| 21 |
+
from ctx.adapters.generic.loop import run_loop, LoopResult
|
| 22 |
+
from ctx.adapters.generic.providers import (
|
| 23 |
+
CompletionResponse,
|
| 24 |
+
Message,
|
| 25 |
+
ModelProvider,
|
| 26 |
+
ToolCall,
|
| 27 |
+
ToolDefinition,
|
| 28 |
+
Usage,
|
| 29 |
+
)
|
| 30 |
+
from ctx.adapters.generic.state import (
|
| 31 |
+
JsonlObserver,
|
| 32 |
+
SessionStore,
|
| 33 |
+
_safe_session_id,
|
| 34 |
+
default_sessions_dir,
|
| 35 |
+
list_sessions,
|
| 36 |
+
load_session,
|
| 37 |
+
new_session_id,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# ── Scripted provider for the round-trip tests ─────────────────────────────
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _symlink_or_skip(link: Path, target: Path) -> None:
|
| 45 |
+
try:
|
| 46 |
+
link.symlink_to(target)
|
| 47 |
+
except OSError as exc:
|
| 48 |
+
pytest.skip(f"symlinks unavailable in this environment: {exc}")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class _Scripted(ModelProvider):
|
| 52 |
+
name = "scripted"
|
| 53 |
+
|
| 54 |
+
def __init__(self, responses: list[CompletionResponse]) -> None:
|
| 55 |
+
self._responses = list(responses)
|
| 56 |
+
|
| 57 |
+
def complete(
|
| 58 |
+
self,
|
| 59 |
+
messages: list[Message],
|
| 60 |
+
tools: list[ToolDefinition] | None = None,
|
| 61 |
+
*,
|
| 62 |
+
model: str | None = None,
|
| 63 |
+
temperature: float = 0.7,
|
| 64 |
+
max_tokens: int | None = None,
|
| 65 |
+
) -> CompletionResponse:
|
| 66 |
+
if not self._responses:
|
| 67 |
+
raise RuntimeError("scripted: no more responses")
|
| 68 |
+
return self._responses.pop(0)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _stop_response(content: str = "done") -> CompletionResponse:
|
| 72 |
+
return CompletionResponse(
|
| 73 |
+
content=content,
|
| 74 |
+
tool_calls=(),
|
| 75 |
+
finish_reason="stop",
|
| 76 |
+
usage=Usage(input_tokens=5, output_tokens=3),
|
| 77 |
+
provider="scripted",
|
| 78 |
+
model="x",
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _tool_response(*calls: ToolCall) -> CompletionResponse:
|
| 83 |
+
return CompletionResponse(
|
| 84 |
+
content="",
|
| 85 |
+
tool_calls=tuple(calls),
|
| 86 |
+
finish_reason="tool_calls",
|
| 87 |
+
usage=Usage(input_tokens=10, output_tokens=4),
|
| 88 |
+
provider="scripted",
|
| 89 |
+
model="x",
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
# ── Session-id safety ────────────────────────────────────────────────────
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class TestSessionIdValidation:
|
| 97 |
+
@pytest.mark.parametrize(
|
| 98 |
+
"bad",
|
| 99 |
+
[
|
| 100 |
+
"",
|
| 101 |
+
"../evil",
|
| 102 |
+
"a/b",
|
| 103 |
+
"a\\b",
|
| 104 |
+
".",
|
| 105 |
+
"..",
|
| 106 |
+
"has space",
|
| 107 |
+
"has.dot", # dots disallowed — risks '.jsonl' shadowing
|
| 108 |
+
"a" * 129, # too long
|
| 109 |
+
],
|
| 110 |
+
)
|
| 111 |
+
def test_rejects_bad(self, bad: str) -> None:
|
| 112 |
+
with pytest.raises((ValueError, TypeError)):
|
| 113 |
+
_safe_session_id(bad)
|
| 114 |
+
|
| 115 |
+
@pytest.mark.parametrize(
|
| 116 |
+
"good",
|
| 117 |
+
[
|
| 118 |
+
"abc123",
|
| 119 |
+
"nightly_backfill",
|
| 120 |
+
"2026-04-24-trial",
|
| 121 |
+
"f9eaad988e79443b85b819099f3679a3",
|
| 122 |
+
],
|
| 123 |
+
)
|
| 124 |
+
def test_accepts_good(self, good: str) -> None:
|
| 125 |
+
assert _safe_session_id(good) == good
|
| 126 |
+
|
| 127 |
+
def test_non_string_rejected(self) -> None:
|
| 128 |
+
with pytest.raises((ValueError, TypeError)):
|
| 129 |
+
_safe_session_id(None) # type: ignore[arg-type]
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class TestSessionIdGen:
|
| 133 |
+
def test_new_id_is_32_char_hex(self) -> None:
|
| 134 |
+
sid = new_session_id()
|
| 135 |
+
assert len(sid) == 32
|
| 136 |
+
assert all(c in "0123456789abcdef" for c in sid)
|
| 137 |
+
|
| 138 |
+
def test_ids_are_unique(self) -> None:
|
| 139 |
+
assert new_session_id() != new_session_id()
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ── default_sessions_dir ─────────────────────────────────────────────────
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class TestDefaultSessionsDir:
|
| 146 |
+
def test_under_home(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
| 147 |
+
monkeypatch.setenv("HOME", str(tmp_path))
|
| 148 |
+
monkeypatch.setenv("USERPROFILE", str(tmp_path))
|
| 149 |
+
p = default_sessions_dir()
|
| 150 |
+
assert p == tmp_path / ".ctx" / "sessions"
|
| 151 |
+
|
| 152 |
+
def test_not_created_by_call(
|
| 153 |
+
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
| 154 |
+
) -> None:
|
| 155 |
+
monkeypatch.setenv("HOME", str(tmp_path))
|
| 156 |
+
monkeypatch.setenv("USERPROFILE", str(tmp_path))
|
| 157 |
+
p = default_sessions_dir()
|
| 158 |
+
# Intentionally lazy — SessionStore creates it, not the helper.
|
| 159 |
+
assert not p.exists()
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
# ── SessionStore ─────────────────────────────────────────────────────────
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class TestSessionStore:
|
| 166 |
+
def test_create_makes_parent_dir(self, tmp_path: Path) -> None:
|
| 167 |
+
nested = tmp_path / "deeply" / "nested"
|
| 168 |
+
store = SessionStore.create(
|
| 169 |
+
session_id="abc", sessions_dir=nested,
|
| 170 |
+
)
|
| 171 |
+
try:
|
| 172 |
+
assert nested.is_dir()
|
| 173 |
+
assert store.path == nested / "abc.jsonl"
|
| 174 |
+
finally:
|
| 175 |
+
store.close()
|
| 176 |
+
|
| 177 |
+
def test_create_auto_generates_id(self, tmp_path: Path) -> None:
|
| 178 |
+
store = SessionStore.create(sessions_dir=tmp_path)
|
| 179 |
+
try:
|
| 180 |
+
assert len(store.session_id) == 32
|
| 181 |
+
finally:
|
| 182 |
+
store.close()
|
| 183 |
+
|
| 184 |
+
def test_write_event_shapes_line(self, tmp_path: Path) -> None:
|
| 185 |
+
store = SessionStore.create(session_id="s1", sessions_dir=tmp_path)
|
| 186 |
+
try:
|
| 187 |
+
store.write_event("custom", {"key": "value"})
|
| 188 |
+
finally:
|
| 189 |
+
store.close()
|
| 190 |
+
raw = (tmp_path / "s1.jsonl").read_text(encoding="utf-8")
|
| 191 |
+
event = json.loads(raw)
|
| 192 |
+
assert event["type"] == "custom"
|
| 193 |
+
assert event["session_id"] == "s1"
|
| 194 |
+
assert event["key"] == "value"
|
| 195 |
+
assert "ts" in event
|
| 196 |
+
|
| 197 |
+
def test_create_rejects_existing_session_by_default(self, tmp_path: Path) -> None:
|
| 198 |
+
path = tmp_path / "s1.jsonl"
|
| 199 |
+
path.write_text("sentinel\n", encoding="utf-8")
|
| 200 |
+
with pytest.raises(FileExistsError):
|
| 201 |
+
SessionStore.create(session_id="s1", sessions_dir=tmp_path)
|
| 202 |
+
assert path.read_text(encoding="utf-8") == "sentinel\n"
|
| 203 |
+
|
| 204 |
+
def test_create_can_overwrite_existing_session_explicitly(
|
| 205 |
+
self, tmp_path: Path,
|
| 206 |
+
) -> None:
|
| 207 |
+
path = tmp_path / "s1.jsonl"
|
| 208 |
+
path.write_text("sentinel\n", encoding="utf-8")
|
| 209 |
+
store = SessionStore.create(
|
| 210 |
+
session_id="s1",
|
| 211 |
+
sessions_dir=tmp_path,
|
| 212 |
+
overwrite=True,
|
| 213 |
+
)
|
| 214 |
+
store.close()
|
| 215 |
+
assert path.read_text(encoding="utf-8") == ""
|
| 216 |
+
|
| 217 |
+
def test_create_overwrite_rejects_symlinked_session_log(
|
| 218 |
+
self, tmp_path: Path,
|
| 219 |
+
) -> None:
|
| 220 |
+
outside = tmp_path / "outside.jsonl"
|
| 221 |
+
outside.write_text("sentinel\n", encoding="utf-8")
|
| 222 |
+
_symlink_or_skip(tmp_path / "s1.jsonl", outside)
|
| 223 |
+
|
| 224 |
+
with pytest.raises(ValueError, match="symlink"):
|
| 225 |
+
SessionStore.create(
|
| 226 |
+
session_id="s1",
|
| 227 |
+
sessions_dir=tmp_path,
|
| 228 |
+
overwrite=True,
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
assert outside.read_text(encoding="utf-8") == "sentinel\n"
|
| 232 |
+
|
| 233 |
+
def test_context_manager(self, tmp_path: Path) -> None:
|
| 234 |
+
with SessionStore.create(session_id="s1", sessions_dir=tmp_path) as store:
|
| 235 |
+
store.write_event("x", {})
|
| 236 |
+
assert store.closed
|
| 237 |
+
assert (tmp_path / "s1.jsonl").is_file()
|
| 238 |
+
|
| 239 |
+
def test_write_after_close_raises(self, tmp_path: Path) -> None:
|
| 240 |
+
store = SessionStore.create(session_id="s1", sessions_dir=tmp_path)
|
| 241 |
+
store.close()
|
| 242 |
+
with pytest.raises(RuntimeError, match="closed"):
|
| 243 |
+
store.write_event("x", {})
|
| 244 |
+
|
| 245 |
+
def test_close_is_idempotent(self, tmp_path: Path) -> None:
|
| 246 |
+
store = SessionStore.create(session_id="s1", sessions_dir=tmp_path)
|
| 247 |
+
store.close()
|
| 248 |
+
store.close() # must not raise
|
| 249 |
+
|
| 250 |
+
def test_attach_requires_existing_file(self, tmp_path: Path) -> None:
|
| 251 |
+
with pytest.raises(FileNotFoundError):
|
| 252 |
+
SessionStore.attach("nope", sessions_dir=tmp_path)
|
| 253 |
+
|
| 254 |
+
def test_attach_rejects_symlinked_session_log(self, tmp_path: Path) -> None:
|
| 255 |
+
outside = tmp_path / "outside.jsonl"
|
| 256 |
+
outside.write_text("sentinel\n", encoding="utf-8")
|
| 257 |
+
_symlink_or_skip(tmp_path / "s1.jsonl", outside)
|
| 258 |
+
|
| 259 |
+
with pytest.raises(ValueError, match="symlink"):
|
| 260 |
+
SessionStore.attach("s1", sessions_dir=tmp_path)
|
| 261 |
+
|
| 262 |
+
def test_attach_appends_to_existing_file(self, tmp_path: Path) -> None:
|
| 263 |
+
# Create + write one event.
|
| 264 |
+
s1 = SessionStore.create(session_id="s1", sessions_dir=tmp_path)
|
| 265 |
+
s1.write_event("first", {})
|
| 266 |
+
s1.close()
|
| 267 |
+
# Attach + append.
|
| 268 |
+
s2 = SessionStore.attach("s1", sessions_dir=tmp_path)
|
| 269 |
+
s2.write_event("second", {})
|
| 270 |
+
s2.close()
|
| 271 |
+
lines = (tmp_path / "s1.jsonl").read_text(encoding="utf-8").strip().split("\n")
|
| 272 |
+
types = [json.loads(line)["type"] for line in lines]
|
| 273 |
+
assert types == ["first", "second"]
|
| 274 |
+
|
| 275 |
+
def test_unicode_content_roundtrips(self, tmp_path: Path) -> None:
|
| 276 |
+
with SessionStore.create(session_id="uni", sessions_dir=tmp_path) as s:
|
| 277 |
+
s.write_event("x", {"content": "café 日本 🚀"})
|
| 278 |
+
event = json.loads((tmp_path / "uni.jsonl").read_text(encoding="utf-8"))
|
| 279 |
+
assert event["content"] == "café 日本 🚀"
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
# ── Convenience writers ──────────────────────────────────────────────────
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class TestConvenienceWriters:
|
| 286 |
+
def test_write_session_start(self, tmp_path: Path) -> None:
|
| 287 |
+
with SessionStore.create(session_id="s", sessions_dir=tmp_path) as store:
|
| 288 |
+
store.write_session_start({"task": "hello", "model": "ollama/x"})
|
| 289 |
+
event = json.loads((tmp_path / "s.jsonl").read_text(encoding="utf-8"))
|
| 290 |
+
assert event["type"] == "session_start"
|
| 291 |
+
assert event["task"] == "hello"
|
| 292 |
+
assert event["model"] == "ollama/x"
|
| 293 |
+
|
| 294 |
+
def test_write_message(self, tmp_path: Path) -> None:
|
| 295 |
+
with SessionStore.create(session_id="s", sessions_dir=tmp_path) as store:
|
| 296 |
+
store.write_message(Message(role="user", content="hi"))
|
| 297 |
+
store.write_message(
|
| 298 |
+
Message(
|
| 299 |
+
role="assistant",
|
| 300 |
+
content="",
|
| 301 |
+
tool_calls=(ToolCall(id="c1", name="t", arguments={"x": 1}),),
|
| 302 |
+
)
|
| 303 |
+
)
|
| 304 |
+
events = [
|
| 305 |
+
json.loads(line) for line in
|
| 306 |
+
(tmp_path / "s.jsonl").read_text(encoding="utf-8").splitlines() if line
|
| 307 |
+
]
|
| 308 |
+
assert events[0]["role"] == "user"
|
| 309 |
+
assert events[1]["tool_calls"][0]["arguments"] == {"x": 1}
|
| 310 |
+
|
| 311 |
+
def test_write_model_response(self, tmp_path: Path) -> None:
|
| 312 |
+
with SessionStore.create(session_id="s", sessions_dir=tmp_path) as store:
|
| 313 |
+
store.write_model_response(
|
| 314 |
+
3,
|
| 315 |
+
CompletionResponse(
|
| 316 |
+
content="ok",
|
| 317 |
+
tool_calls=(),
|
| 318 |
+
finish_reason="stop",
|
| 319 |
+
usage=Usage(input_tokens=10, output_tokens=5, cost_usd=0.002),
|
| 320 |
+
provider="litellm",
|
| 321 |
+
model="openrouter/x",
|
| 322 |
+
),
|
| 323 |
+
)
|
| 324 |
+
event = json.loads((tmp_path / "s.jsonl").read_text(encoding="utf-8"))
|
| 325 |
+
assert event["iteration"] == 3
|
| 326 |
+
assert event["usage"]["cost_usd"] == 0.002
|
| 327 |
+
assert event["provider"] == "litellm"
|
| 328 |
+
assert event["model"] == "openrouter/x"
|
| 329 |
+
|
| 330 |
+
def test_write_tool_call(self, tmp_path: Path) -> None:
|
| 331 |
+
with SessionStore.create(session_id="s", sessions_dir=tmp_path) as store:
|
| 332 |
+
store.write_tool_call(
|
| 333 |
+
1,
|
| 334 |
+
ToolCall(id="c1", name="fs__read", arguments={"path": "/tmp"}),
|
| 335 |
+
result="file contents",
|
| 336 |
+
error=None,
|
| 337 |
+
)
|
| 338 |
+
event = json.loads((tmp_path / "s.jsonl").read_text(encoding="utf-8"))
|
| 339 |
+
assert event["call"]["arguments"] == {"path": "/tmp"}
|
| 340 |
+
assert event["error"] is None
|
| 341 |
+
|
| 342 |
+
def test_write_stop(self, tmp_path: Path) -> None:
|
| 343 |
+
with SessionStore.create(session_id="s", sessions_dir=tmp_path) as store:
|
| 344 |
+
store.write_stop(
|
| 345 |
+
LoopResult(
|
| 346 |
+
stop_reason="completed",
|
| 347 |
+
final_message="done",
|
| 348 |
+
iterations=3,
|
| 349 |
+
usage=Usage(input_tokens=30, output_tokens=15, cost_usd=0.01),
|
| 350 |
+
messages=(),
|
| 351 |
+
detail="",
|
| 352 |
+
)
|
| 353 |
+
)
|
| 354 |
+
event = json.loads((tmp_path / "s.jsonl").read_text(encoding="utf-8"))
|
| 355 |
+
assert event["stop_reason"] == "completed"
|
| 356 |
+
assert event["iterations"] == 3
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
# ── load_session ─────────────────────────────────────────────────────────
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
class TestLoadSession:
|
| 363 |
+
def test_file_not_found(self, tmp_path: Path) -> None:
|
| 364 |
+
with pytest.raises(FileNotFoundError):
|
| 365 |
+
load_session("nope", sessions_dir=tmp_path)
|
| 366 |
+
|
| 367 |
+
def test_rejects_symlinked_session_log(self, tmp_path: Path) -> None:
|
| 368 |
+
outside = tmp_path / "outside.jsonl"
|
| 369 |
+
outside.write_text(
|
| 370 |
+
json.dumps({"type": "session_start", "session_id": "s"}) + "\n",
|
| 371 |
+
encoding="utf-8",
|
| 372 |
+
)
|
| 373 |
+
_symlink_or_skip(tmp_path / "s.jsonl", outside)
|
| 374 |
+
|
| 375 |
+
with pytest.raises(ValueError, match="symlink"):
|
| 376 |
+
load_session("s", sessions_dir=tmp_path)
|
| 377 |
+
|
| 378 |
+
def test_replay_simple_session(self, tmp_path: Path) -> None:
|
| 379 |
+
with SessionStore.create(session_id="s", sessions_dir=tmp_path) as store:
|
| 380 |
+
store.write_session_start({"task": "hello", "model": "x"})
|
| 381 |
+
store.write_message(Message(role="system", content="sys"))
|
| 382 |
+
store.write_message(Message(role="user", content="hi"))
|
| 383 |
+
store.write_message(Message(role="assistant", content="hello back"))
|
| 384 |
+
store.write_stop(
|
| 385 |
+
LoopResult(
|
| 386 |
+
stop_reason="completed", final_message="hello back",
|
| 387 |
+
iterations=1, usage=Usage(), messages=(), detail="",
|
| 388 |
+
)
|
| 389 |
+
)
|
| 390 |
+
state = load_session("s", sessions_dir=tmp_path)
|
| 391 |
+
assert state.session_id == "s"
|
| 392 |
+
assert state.path == tmp_path / "s.jsonl"
|
| 393 |
+
assert [m.role for m in state.messages] == ["system", "user", "assistant"]
|
| 394 |
+
assert state.messages[2].content == "hello back"
|
| 395 |
+
assert state.metadata["task"] == "hello"
|
| 396 |
+
assert state.stopped is True
|
| 397 |
+
assert state.stop_reason == "completed"
|
| 398 |
+
|
| 399 |
+
def test_replay_unstopped_session(self, tmp_path: Path) -> None:
|
| 400 |
+
"""Session that trails off mid-run (no stop event) is flagged."""
|
| 401 |
+
with SessionStore.create(session_id="s", sessions_dir=tmp_path) as store:
|
| 402 |
+
store.write_session_start({"task": "x"})
|
| 403 |
+
store.write_message(Message(role="user", content="hi"))
|
| 404 |
+
state = load_session("s", sessions_dir=tmp_path)
|
| 405 |
+
assert state.stopped is False
|
| 406 |
+
assert state.stop_reason is None
|
| 407 |
+
|
| 408 |
+
def test_replay_tool_call_messages(self, tmp_path: Path) -> None:
|
| 409 |
+
"""Assistant-with-tool_calls + tool-result must round-trip faithfully."""
|
| 410 |
+
with SessionStore.create(session_id="s", sessions_dir=tmp_path) as store:
|
| 411 |
+
store.write_message(Message(role="user", content="go"))
|
| 412 |
+
tc = ToolCall(id="c1", name="srv__fetch", arguments={"url": "https://x"})
|
| 413 |
+
store.write_message(
|
| 414 |
+
Message(role="assistant", content="", tool_calls=(tc,))
|
| 415 |
+
)
|
| 416 |
+
store.write_message(
|
| 417 |
+
Message(role="tool", content="ok", tool_call_id="c1", name="srv__fetch")
|
| 418 |
+
)
|
| 419 |
+
state = load_session("s", sessions_dir=tmp_path)
|
| 420 |
+
assert len(state.messages) == 3
|
| 421 |
+
assistant = state.messages[1]
|
| 422 |
+
assert assistant.tool_calls[0].id == "c1"
|
| 423 |
+
assert assistant.tool_calls[0].arguments == {"url": "https://x"}
|
| 424 |
+
tool_msg = state.messages[2]
|
| 425 |
+
assert tool_msg.tool_call_id == "c1"
|
| 426 |
+
assert tool_msg.name == "srv__fetch"
|
| 427 |
+
|
| 428 |
+
def test_replay_repairs_unresolved_tool_call_tail(self, tmp_path: Path) -> None:
|
| 429 |
+
"""Crash after assistant tool_call message persists must resume safely."""
|
| 430 |
+
tc = ToolCall(id="c1", name="srv__fetch", arguments={"url": "https://x"})
|
| 431 |
+
with SessionStore.create(session_id="s", sessions_dir=tmp_path) as store:
|
| 432 |
+
store.write_message(Message(role="user", content="go"))
|
| 433 |
+
store.write_model_response(1, _tool_response(tc))
|
| 434 |
+
store.write_message(Message(role="assistant", content="", tool_calls=(tc,)))
|
| 435 |
+
|
| 436 |
+
state = load_session("s", sessions_dir=tmp_path)
|
| 437 |
+
|
| 438 |
+
assert [m.role for m in state.messages] == ["user", "assistant", "tool"]
|
| 439 |
+
tool_msg = state.messages[2]
|
| 440 |
+
assert tool_msg.tool_call_id == "c1"
|
| 441 |
+
assert tool_msg.name == "srv__fetch"
|
| 442 |
+
assert tool_msg.content.startswith("ERROR:")
|
| 443 |
+
|
| 444 |
+
def test_malformed_line_is_skipped_not_fatal(self, tmp_path: Path) -> None:
|
| 445 |
+
path = tmp_path / "s.jsonl"
|
| 446 |
+
path.write_text(
|
| 447 |
+
'\n'.join([
|
| 448 |
+
json.dumps({"type": "session_start", "ts": "t", "session_id": "s", "task": "hi"}),
|
| 449 |
+
"this is not json at all",
|
| 450 |
+
json.dumps({"type": "message", "ts": "t", "session_id": "s",
|
| 451 |
+
"role": "user", "content": "ok"}),
|
| 452 |
+
]) + "\n",
|
| 453 |
+
encoding="utf-8",
|
| 454 |
+
)
|
| 455 |
+
state = load_session("s", sessions_dir=tmp_path)
|
| 456 |
+
# Malformed line dropped; valid events still processed.
|
| 457 |
+
assert len(state.messages) == 1
|
| 458 |
+
assert state.metadata["task"] == "hi"
|
| 459 |
+
|
| 460 |
+
def test_empty_lines_are_skipped(self, tmp_path: Path) -> None:
|
| 461 |
+
path = tmp_path / "s.jsonl"
|
| 462 |
+
path.write_text(
|
| 463 |
+
json.dumps({"type": "session_start", "ts": "t", "session_id": "s", "task": "hi"})
|
| 464 |
+
+ "\n\n\n"
|
| 465 |
+
+ json.dumps({"type": "message", "ts": "t", "session_id": "s",
|
| 466 |
+
"role": "user", "content": "hi"})
|
| 467 |
+
+ "\n",
|
| 468 |
+
encoding="utf-8",
|
| 469 |
+
)
|
| 470 |
+
state = load_session("s", sessions_dir=tmp_path)
|
| 471 |
+
assert len(state.messages) == 1
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
# ── list_sessions ────────────────────────────────────────────────────────
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
class TestListSessions:
|
| 478 |
+
def test_empty_dir_returns_empty(self, tmp_path: Path) -> None:
|
| 479 |
+
assert list_sessions(sessions_dir=tmp_path) == []
|
| 480 |
+
|
| 481 |
+
def test_nonexistent_dir_returns_empty(self, tmp_path: Path) -> None:
|
| 482 |
+
assert list_sessions(sessions_dir=tmp_path / "missing") == []
|
| 483 |
+
|
| 484 |
+
def test_only_jsonl_files_listed(self, tmp_path: Path) -> None:
|
| 485 |
+
(tmp_path / "alpha.jsonl").write_text("", encoding="utf-8")
|
| 486 |
+
(tmp_path / "beta.jsonl").write_text("", encoding="utf-8")
|
| 487 |
+
(tmp_path / "not_a_session.txt").write_text("", encoding="utf-8")
|
| 488 |
+
(tmp_path / "subdir").mkdir()
|
| 489 |
+
assert list_sessions(sessions_dir=tmp_path) == ["alpha", "beta"]
|
| 490 |
+
|
| 491 |
+
def test_symlinked_jsonl_files_are_skipped(self, tmp_path: Path) -> None:
|
| 492 |
+
(tmp_path / "alpha.jsonl").write_text("", encoding="utf-8")
|
| 493 |
+
outside = tmp_path / "outside.jsonl"
|
| 494 |
+
outside.write_text("", encoding="utf-8")
|
| 495 |
+
_symlink_or_skip(tmp_path / "linked.jsonl", outside)
|
| 496 |
+
|
| 497 |
+
assert list_sessions(sessions_dir=tmp_path) == ["alpha", "outside"]
|
| 498 |
+
|
| 499 |
+
def test_sorted_alphabetically(self, tmp_path: Path) -> None:
|
| 500 |
+
for name in ("zzz", "aaa", "mmm"):
|
| 501 |
+
(tmp_path / f"{name}.jsonl").write_text("", encoding="utf-8")
|
| 502 |
+
assert list_sessions(sessions_dir=tmp_path) == ["aaa", "mmm", "zzz"]
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
# ── JsonlObserver end-to-end via run_loop ───────────────────────────────
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
class TestJsonlObserverRoundTrip:
|
| 509 |
+
def test_simple_completion_replay(self, tmp_path: Path) -> None:
|
| 510 |
+
provider = _Scripted([_stop_response("final answer")])
|
| 511 |
+
store = SessionStore.create(session_id="trip1", sessions_dir=tmp_path)
|
| 512 |
+
observer = JsonlObserver(
|
| 513 |
+
store,
|
| 514 |
+
session_metadata={"task": "smoke-test", "model": "ollama/x"},
|
| 515 |
+
)
|
| 516 |
+
try:
|
| 517 |
+
result = run_loop(
|
| 518 |
+
provider=provider,
|
| 519 |
+
system_prompt="sys",
|
| 520 |
+
task="hi",
|
| 521 |
+
observer=observer,
|
| 522 |
+
)
|
| 523 |
+
finally:
|
| 524 |
+
store.close()
|
| 525 |
+
|
| 526 |
+
assert result.stop_reason == "completed"
|
| 527 |
+
|
| 528 |
+
state = load_session("trip1", sessions_dir=tmp_path)
|
| 529 |
+
# Replay must match the live conversation byte-for-byte (for
|
| 530 |
+
# roles + content).
|
| 531 |
+
live = [
|
| 532 |
+
(m.role, m.content) for m in result.messages
|
| 533 |
+
]
|
| 534 |
+
replayed = [(m.role, m.content) for m in state.messages]
|
| 535 |
+
assert live == replayed
|
| 536 |
+
assert state.metadata["task"] == "smoke-test"
|
| 537 |
+
assert state.stop_reason == "completed"
|
| 538 |
+
assert state.stopped is True
|
| 539 |
+
|
| 540 |
+
def test_tool_call_round_trip(self, tmp_path: Path) -> None:
|
| 541 |
+
tc = ToolCall(id="c1", name="srv__echo", arguments={"text": "hi"})
|
| 542 |
+
provider = _Scripted(
|
| 543 |
+
[_tool_response(tc), _stop_response("seen hi")]
|
| 544 |
+
)
|
| 545 |
+
store = SessionStore.create(session_id="trip2", sessions_dir=tmp_path)
|
| 546 |
+
observer = JsonlObserver(store, session_metadata={"task": "go"})
|
| 547 |
+
try:
|
| 548 |
+
run_loop(
|
| 549 |
+
provider=provider,
|
| 550 |
+
system_prompt="",
|
| 551 |
+
task="go",
|
| 552 |
+
tool_executor=lambda call: f"echo:{call.arguments['text']}",
|
| 553 |
+
observer=observer,
|
| 554 |
+
)
|
| 555 |
+
finally:
|
| 556 |
+
store.close()
|
| 557 |
+
|
| 558 |
+
state = load_session("trip2", sessions_dir=tmp_path)
|
| 559 |
+
roles = [m.role for m in state.messages]
|
| 560 |
+
# user(task) + assistant(tool_calls) + tool(result) + assistant(final)
|
| 561 |
+
assert roles == ["user", "assistant", "tool", "assistant"]
|
| 562 |
+
tool_msg = state.messages[2]
|
| 563 |
+
assert tool_msg.content == "echo:hi"
|
| 564 |
+
assert tool_msg.tool_call_id == "c1"
|
| 565 |
+
|
| 566 |
+
def test_resume_via_messages_kwarg(self, tmp_path: Path) -> None:
|
| 567 |
+
"""Load a prior session and hand its messages to a fresh run_loop."""
|
| 568 |
+
# First run.
|
| 569 |
+
provider1 = _Scripted([_stop_response("first-answer")])
|
| 570 |
+
store1 = SessionStore.create(session_id="resume1", sessions_dir=tmp_path)
|
| 571 |
+
try:
|
| 572 |
+
run_loop(
|
| 573 |
+
provider=provider1,
|
| 574 |
+
system_prompt="sys",
|
| 575 |
+
task="initial task",
|
| 576 |
+
observer=JsonlObserver(store1, session_metadata={"task": "initial task"}),
|
| 577 |
+
)
|
| 578 |
+
finally:
|
| 579 |
+
store1.close()
|
| 580 |
+
|
| 581 |
+
# Resume: load + feed back.
|
| 582 |
+
state = load_session("resume1", sessions_dir=tmp_path)
|
| 583 |
+
provider2 = _Scripted([_stop_response("resumed-answer")])
|
| 584 |
+
store2 = SessionStore.attach("resume1", sessions_dir=tmp_path)
|
| 585 |
+
try:
|
| 586 |
+
result2 = run_loop(
|
| 587 |
+
provider=provider2,
|
| 588 |
+
system_prompt="sys",
|
| 589 |
+
task="follow-up",
|
| 590 |
+
messages=list(state.messages),
|
| 591 |
+
observer=JsonlObserver(
|
| 592 |
+
store2,
|
| 593 |
+
session_metadata={},
|
| 594 |
+
emit_session_start=False, # already written in first run
|
| 595 |
+
persisted_message_count=len(state.messages),
|
| 596 |
+
),
|
| 597 |
+
append_task_after_messages=True,
|
| 598 |
+
)
|
| 599 |
+
finally:
|
| 600 |
+
store2.close()
|
| 601 |
+
|
| 602 |
+
# First run's conversation is visible in the resumed result.
|
| 603 |
+
resumed_roles = [m.role for m in result2.messages]
|
| 604 |
+
assert resumed_roles == ["system", "user", "assistant", "user", "assistant"]
|
| 605 |
+
contents = [m.content for m in result2.messages]
|
| 606 |
+
assert contents == [
|
| 607 |
+
"sys",
|
| 608 |
+
"initial task",
|
| 609 |
+
"first-answer",
|
| 610 |
+
"follow-up",
|
| 611 |
+
"resumed-answer",
|
| 612 |
+
]
|
| 613 |
+
replayed = load_session("resume1", sessions_dir=tmp_path)
|
| 614 |
+
assert [m.content for m in replayed.messages] == contents
|
| 615 |
+
|
| 616 |
+
def test_metadata_includes_seed_messages(self, tmp_path: Path) -> None:
|
| 617 |
+
"""session_start payload captures the seed conversation."""
|
| 618 |
+
provider = _Scripted([_stop_response("ok")])
|
| 619 |
+
store = SessionStore.create(session_id="meta", sessions_dir=tmp_path)
|
| 620 |
+
observer = JsonlObserver(store, session_metadata={"task": "t"})
|
| 621 |
+
try:
|
| 622 |
+
run_loop(
|
| 623 |
+
provider=provider, system_prompt="sys", task="t", observer=observer,
|
| 624 |
+
)
|
| 625 |
+
finally:
|
| 626 |
+
store.close()
|
| 627 |
+
# Find the session_start event directly so we can inspect seeds.
|
| 628 |
+
first_line = (tmp_path / "meta.jsonl").read_text(encoding="utf-8").splitlines()[0]
|
| 629 |
+
event = json.loads(first_line)
|
| 630 |
+
assert event["type"] == "session_start"
|
| 631 |
+
assert len(event["seed_messages"]) == 2 # system + user(task)
|
| 632 |
+
assert event["seed_messages"][0]["role"] == "system"
|
| 633 |
+
assert event["seed_messages"][1]["role"] == "user"
|
| 634 |
+
|
| 635 |
+
def test_observer_no_emit_start(self, tmp_path: Path) -> None:
|
| 636 |
+
"""When emit_session_start=False the observer doesn't write it — caller did."""
|
| 637 |
+
provider = _Scripted([_stop_response("ok")])
|
| 638 |
+
store = SessionStore.create(session_id="noe", sessions_dir=tmp_path)
|
| 639 |
+
observer = JsonlObserver(
|
| 640 |
+
store, session_metadata={"task": "t"}, emit_session_start=False,
|
| 641 |
+
)
|
| 642 |
+
try:
|
| 643 |
+
run_loop(
|
| 644 |
+
provider=provider, system_prompt="", task="t", observer=observer,
|
| 645 |
+
)
|
| 646 |
+
finally:
|
| 647 |
+
store.close()
|
| 648 |
+
events = [
|
| 649 |
+
json.loads(line) for line in
|
| 650 |
+
(tmp_path / "noe.jsonl").read_text(encoding="utf-8").splitlines() if line
|
| 651 |
+
]
|
| 652 |
+
types = [e["type"] for e in events]
|
| 653 |
+
assert "session_start" not in types
|
| 654 |
+
assert types.count("message") == 2
|
| 655 |
+
|
| 656 |
+
def test_stop_event_always_written(self, tmp_path: Path) -> None:
|
| 657 |
+
provider = _Scripted([_stop_response("ok")])
|
| 658 |
+
store = SessionStore.create(session_id="stop", sessions_dir=tmp_path)
|
| 659 |
+
observer = JsonlObserver(store, session_metadata={"task": "t"})
|
| 660 |
+
try:
|
| 661 |
+
run_loop(
|
| 662 |
+
provider=provider, system_prompt="", task="t", observer=observer,
|
| 663 |
+
)
|
| 664 |
+
finally:
|
| 665 |
+
store.close()
|
| 666 |
+
last_line = (
|
| 667 |
+
(tmp_path / "stop.jsonl")
|
| 668 |
+
.read_text(encoding="utf-8")
|
| 669 |
+
.strip()
|
| 670 |
+
.split("\n")[-1]
|
| 671 |
+
)
|
| 672 |
+
event = json.loads(last_line)
|
| 673 |
+
assert event["type"] == "stop"
|
| 674 |
+
assert event["stop_reason"] == "completed"
|
src/tests/test_incremental_attach_shadow.py
CHANGED
|
@@ -1,210 +1,210 @@
|
|
| 1 |
-
from __future__ import annotations
|
| 2 |
-
|
| 3 |
-
import json
|
| 4 |
-
from pathlib import Path
|
| 5 |
-
from typing import Any
|
| 6 |
-
|
| 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,
|
| 14 |
-
_topk_pairs_subset_with_optional_index,
|
| 15 |
-
)
|
| 16 |
-
from ctx.core.graph.vector_index import build_vector_index
|
| 17 |
-
from ctx.core.wiki import wiki_graphify as wg
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
def test_shadow_indexed_subset_matches_batch_semantic_candidates() -> None:
|
| 21 |
-
vecs = _l2_normalize(
|
| 22 |
-
np.array(
|
| 23 |
-
[
|
| 24 |
-
[1.0, 0.0],
|
| 25 |
-
[0.95, 0.05],
|
| 26 |
-
[0.0, 1.0],
|
| 27 |
-
[0.97, 0.03],
|
| 28 |
-
],
|
| 29 |
-
dtype="float32",
|
| 30 |
-
)
|
| 31 |
-
)
|
| 32 |
-
node_ids = ["skill:alpha", "skill:beta", "skill:gamma", "skill:new"]
|
| 33 |
-
hashes = ["ha", "hb", "hc", "hn"]
|
| 34 |
-
|
| 35 |
-
batch = {
|
| 36 |
-
pair: score
|
| 37 |
-
for pair, score in _topk_pairs(vecs, node_ids, top_k=2, min_cosine=0.5).items()
|
| 38 |
-
if "skill:new" in pair
|
| 39 |
-
}
|
| 40 |
-
indexed = _topk_pairs_subset_with_optional_index(
|
| 41 |
-
vecs,
|
| 42 |
-
node_ids,
|
| 43 |
-
hashes,
|
| 44 |
-
[3],
|
| 45 |
-
top_k=2,
|
| 46 |
-
min_cosine=0.5,
|
| 47 |
-
vector_index_kind="numpy-flat",
|
| 48 |
-
model_id="model-a",
|
| 49 |
-
ann_enabled_above_nodes=1,
|
| 50 |
-
cache_dir=Path(),
|
| 51 |
-
persist_index=False,
|
| 52 |
-
)
|
| 53 |
-
|
| 54 |
-
assert indexed == batch
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
def test_shadow_validation_reports_topk_overlap(tmp_path: Path) -> None:
|
| 58 |
-
index_dir = tmp_path / "vector-index"
|
| 59 |
-
build_vector_index(
|
| 60 |
-
kind="numpy-flat",
|
| 61 |
-
model_id="model-a",
|
| 62 |
-
node_ids=["skill:alpha", "skill:beta", "skill:gamma"],
|
| 63 |
-
content_hashes=["ha", "hb", "hc"],
|
| 64 |
-
vectors=np.asarray(
|
| 65 |
-
[[1.0, 0.0], [0.95, 0.05], [0.0, 1.0]],
|
| 66 |
-
dtype="float32",
|
| 67 |
-
),
|
| 68 |
-
).save(index_dir)
|
| 69 |
-
|
| 70 |
-
report = run_shadow_validation(
|
| 71 |
-
index_dir=index_dir,
|
| 72 |
-
node_ids=["skill:alpha"],
|
| 73 |
-
top_ks=(1, 2),
|
| 74 |
-
min_score=0.5,
|
| 75 |
-
min_overlap=0.85,
|
| 76 |
-
)
|
| 77 |
-
|
| 78 |
-
assert report["gate_passed"] is True
|
| 79 |
-
assert report["baseline"] == "exact-vector-topk"
|
| 80 |
-
assert report["metrics"]["top_1"]["recall"] == 1.0
|
| 81 |
-
assert report["score_deltas"]["max_abs"] == 0.0
|
| 82 |
-
assert report["bad_examples"] == []
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
def test_shadow_validation_can_gate_against_graph_baseline(tmp_path: Path) -> None:
|
| 86 |
-
index_dir = tmp_path / "vector-index"
|
| 87 |
-
build_vector_index(
|
| 88 |
-
kind="numpy-flat",
|
| 89 |
-
model_id="model-a",
|
| 90 |
-
node_ids=["skill:alpha", "skill:expected", "skill:actual"],
|
| 91 |
-
content_hashes=["ha", "he", "hc"],
|
| 92 |
-
vectors=np.asarray(
|
| 93 |
-
[[1.0, 0.0], [0.0, 1.0], [0.97, 0.03]],
|
| 94 |
-
dtype="float32",
|
| 95 |
-
),
|
| 96 |
-
).save(index_dir)
|
| 97 |
-
graph = nx.Graph()
|
| 98 |
-
graph.add_edge("skill:alpha", "skill:expected", semantic_sim=0.9)
|
| 99 |
-
|
| 100 |
-
report = run_shadow_validation(
|
| 101 |
-
index_dir=index_dir,
|
| 102 |
-
graph=graph,
|
| 103 |
-
node_ids=["skill:alpha"],
|
| 104 |
-
top_ks=(1,),
|
| 105 |
-
min_score=0.5,
|
| 106 |
-
min_final_weight=0.03,
|
| 107 |
-
min_overlap=0.85,
|
| 108 |
-
)
|
| 109 |
-
|
| 110 |
-
assert report["gate_passed"] is False
|
| 111 |
-
assert report["metrics"]["top_1"]["recall"] == 0.0
|
| 112 |
-
assert report["bad_examples"][0]["missing"] == ["skill:expected"]
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
def test_shadow_cli_returns_nonzero_when_gate_fails(tmp_path: Path, capsys) -> None:
|
| 116 |
-
index_dir = tmp_path / "vector-index"
|
| 117 |
-
build_vector_index(
|
| 118 |
-
kind="numpy-flat",
|
| 119 |
-
model_id="model-a",
|
| 120 |
-
node_ids=["skill:alpha", "skill:beta"],
|
| 121 |
-
content_hashes=["ha", "hb"],
|
| 122 |
-
vectors=np.asarray([[1.0, 0.0], [0.0, 1.0]], dtype="float32"),
|
| 123 |
-
).save(index_dir)
|
| 124 |
-
graph = nx.Graph()
|
| 125 |
-
graph.add_edge("skill:alpha", "skill:beta", semantic_sim=0.9)
|
| 126 |
-
graph_path = tmp_path / "graph.json"
|
| 127 |
-
from networkx.readwrite import node_link_data
|
| 128 |
-
|
| 129 |
-
graph_path.write_text(json.dumps(node_link_data(graph, edges="edges")), encoding="utf-8")
|
| 130 |
-
|
| 131 |
-
rc = main([
|
| 132 |
-
"--index-dir", str(index_dir),
|
| 133 |
-
"--graph", str(graph_path),
|
| 134 |
-
"--node", "skill:alpha",
|
| 135 |
-
"--top-k", "1",
|
| 136 |
-
"--min-score", "0.95",
|
| 137 |
-
"--json",
|
| 138 |
-
])
|
| 139 |
-
|
| 140 |
-
assert rc == 2
|
| 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,
|
| 147 |
-
) -> None:
|
| 148 |
-
import ctx_config
|
| 149 |
-
|
| 150 |
-
wiki = tmp_path / "wiki"
|
| 151 |
-
_isolate_graphify(wiki, tmp_path / "quality", monkeypatch)
|
| 152 |
-
monkeypatch.setattr(ctx_config.cfg, "graph_edge_weight_semantic", 0.0)
|
| 153 |
-
|
| 154 |
-
_write_entity(wiki / "entities" / "skills" / "alpha.md", "alpha", ["python"])
|
| 155 |
-
_write_entity(wiki / "entities" / "skills" / "beta.md", "beta", ["python"])
|
| 156 |
-
prior, _ = wg.build_graph(incremental=False)
|
| 157 |
-
|
| 158 |
-
_write_entity(wiki / "entities" / "skills" / "gamma.md", "gamma", ["python"])
|
| 159 |
-
monkeypatch.setattr(wg, "load_prior_graph", lambda: prior.copy())
|
| 160 |
-
incremental, _ = wg.build_graph(incremental=True)
|
| 161 |
-
|
| 162 |
-
monkeypatch.setattr(wg, "load_prior_graph", lambda: None)
|
| 163 |
-
full, _ = wg.build_graph(incremental=False)
|
| 164 |
-
|
| 165 |
-
assert _node_snapshot(incremental) == _node_snapshot(full)
|
| 166 |
-
assert _edge_snapshot(incremental) == _edge_snapshot(full)
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
def _isolate_graphify(wiki: Path, quality: Path, monkeypatch) -> None:
|
| 170 |
-
monkeypatch.setattr(wg, "WIKI_DIR", wiki)
|
| 171 |
-
monkeypatch.setattr(wg, "SKILL_ENTITIES", wiki / "entities" / "skills")
|
| 172 |
-
monkeypatch.setattr(wg, "AGENT_ENTITIES", wiki / "entities" / "agents")
|
| 173 |
-
monkeypatch.setattr(wg, "MCP_ENTITIES", wiki / "entities" / "mcp-servers")
|
| 174 |
-
monkeypatch.setattr(wg, "HARNESS_ENTITIES", wiki / "entities" / "harnesses")
|
| 175 |
-
monkeypatch.setattr(wg, "GRAPH_OUT", wiki / "graphify-out")
|
| 176 |
-
monkeypatch.setattr(wg, "QUALITY_SIDECAR_DIR", quality)
|
| 177 |
-
monkeypatch.setattr(wg, "load_prior_graph", lambda: None)
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
def _write_entity(path: Path, slug: str, tags: list[str]) -> None:
|
| 181 |
-
path.parent.mkdir(parents=True, exist_ok=True)
|
| 182 |
-
lines = ["---", f"title: {slug}", "type: skill", "tags:"]
|
| 183 |
-
lines.extend(f" - {tag}" for tag in tags)
|
| 184 |
-
lines.extend(["---", f"# {slug}", "body"])
|
| 185 |
-
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
def _node_snapshot(G: nx.Graph) -> dict[str, dict[str, Any]]:
|
| 189 |
-
keys = {"label", "type", "tags", "never_load"}
|
| 190 |
-
return {
|
| 191 |
-
node_id: {key: G.nodes[node_id].get(key) for key in keys}
|
| 192 |
-
for node_id in sorted(G.nodes)
|
| 193 |
-
}
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
def _edge_snapshot(G: nx.Graph) -> dict[tuple[str, str], dict[str, Any]]:
|
| 197 |
-
keys = {
|
| 198 |
-
"weight",
|
| 199 |
-
"final_weight",
|
| 200 |
-
"semantic_sim",
|
| 201 |
-
"tag_sim",
|
| 202 |
-
"token_sim",
|
| 203 |
-
"shared_tags",
|
| 204 |
-
"shared_tokens",
|
| 205 |
-
"edge_reasons",
|
| 206 |
-
}
|
| 207 |
-
return {
|
| 208 |
-
tuple(sorted((left, right))): {key: attrs.get(key) for key in keys}
|
| 209 |
-
for left, right, attrs in G.edges(data=True)
|
| 210 |
-
}
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 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,
|
| 14 |
+
_topk_pairs_subset_with_optional_index,
|
| 15 |
+
)
|
| 16 |
+
from ctx.core.graph.vector_index import build_vector_index
|
| 17 |
+
from ctx.core.wiki import wiki_graphify as wg
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def test_shadow_indexed_subset_matches_batch_semantic_candidates() -> None:
|
| 21 |
+
vecs = _l2_normalize(
|
| 22 |
+
np.array(
|
| 23 |
+
[
|
| 24 |
+
[1.0, 0.0],
|
| 25 |
+
[0.95, 0.05],
|
| 26 |
+
[0.0, 1.0],
|
| 27 |
+
[0.97, 0.03],
|
| 28 |
+
],
|
| 29 |
+
dtype="float32",
|
| 30 |
+
)
|
| 31 |
+
)
|
| 32 |
+
node_ids = ["skill:alpha", "skill:beta", "skill:gamma", "skill:new"]
|
| 33 |
+
hashes = ["ha", "hb", "hc", "hn"]
|
| 34 |
+
|
| 35 |
+
batch = {
|
| 36 |
+
pair: score
|
| 37 |
+
for pair, score in _topk_pairs(vecs, node_ids, top_k=2, min_cosine=0.5).items()
|
| 38 |
+
if "skill:new" in pair
|
| 39 |
+
}
|
| 40 |
+
indexed = _topk_pairs_subset_with_optional_index(
|
| 41 |
+
vecs,
|
| 42 |
+
node_ids,
|
| 43 |
+
hashes,
|
| 44 |
+
[3],
|
| 45 |
+
top_k=2,
|
| 46 |
+
min_cosine=0.5,
|
| 47 |
+
vector_index_kind="numpy-flat",
|
| 48 |
+
model_id="model-a",
|
| 49 |
+
ann_enabled_above_nodes=1,
|
| 50 |
+
cache_dir=Path(),
|
| 51 |
+
persist_index=False,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
assert indexed == batch
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_shadow_validation_reports_topk_overlap(tmp_path: Path) -> None:
|
| 58 |
+
index_dir = tmp_path / "vector-index"
|
| 59 |
+
build_vector_index(
|
| 60 |
+
kind="numpy-flat",
|
| 61 |
+
model_id="model-a",
|
| 62 |
+
node_ids=["skill:alpha", "skill:beta", "skill:gamma"],
|
| 63 |
+
content_hashes=["ha", "hb", "hc"],
|
| 64 |
+
vectors=np.asarray(
|
| 65 |
+
[[1.0, 0.0], [0.95, 0.05], [0.0, 1.0]],
|
| 66 |
+
dtype="float32",
|
| 67 |
+
),
|
| 68 |
+
).save(index_dir)
|
| 69 |
+
|
| 70 |
+
report = run_shadow_validation(
|
| 71 |
+
index_dir=index_dir,
|
| 72 |
+
node_ids=["skill:alpha"],
|
| 73 |
+
top_ks=(1, 2),
|
| 74 |
+
min_score=0.5,
|
| 75 |
+
min_overlap=0.85,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
assert report["gate_passed"] is True
|
| 79 |
+
assert report["baseline"] == "exact-vector-topk"
|
| 80 |
+
assert report["metrics"]["top_1"]["recall"] == 1.0
|
| 81 |
+
assert report["score_deltas"]["max_abs"] == 0.0
|
| 82 |
+
assert report["bad_examples"] == []
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def test_shadow_validation_can_gate_against_graph_baseline(tmp_path: Path) -> None:
|
| 86 |
+
index_dir = tmp_path / "vector-index"
|
| 87 |
+
build_vector_index(
|
| 88 |
+
kind="numpy-flat",
|
| 89 |
+
model_id="model-a",
|
| 90 |
+
node_ids=["skill:alpha", "skill:expected", "skill:actual"],
|
| 91 |
+
content_hashes=["ha", "he", "hc"],
|
| 92 |
+
vectors=np.asarray(
|
| 93 |
+
[[1.0, 0.0], [0.0, 1.0], [0.97, 0.03]],
|
| 94 |
+
dtype="float32",
|
| 95 |
+
),
|
| 96 |
+
).save(index_dir)
|
| 97 |
+
graph = nx.Graph()
|
| 98 |
+
graph.add_edge("skill:alpha", "skill:expected", semantic_sim=0.9)
|
| 99 |
+
|
| 100 |
+
report = run_shadow_validation(
|
| 101 |
+
index_dir=index_dir,
|
| 102 |
+
graph=graph,
|
| 103 |
+
node_ids=["skill:alpha"],
|
| 104 |
+
top_ks=(1,),
|
| 105 |
+
min_score=0.5,
|
| 106 |
+
min_final_weight=0.03,
|
| 107 |
+
min_overlap=0.85,
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
assert report["gate_passed"] is False
|
| 111 |
+
assert report["metrics"]["top_1"]["recall"] == 0.0
|
| 112 |
+
assert report["bad_examples"][0]["missing"] == ["skill:expected"]
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def test_shadow_cli_returns_nonzero_when_gate_fails(tmp_path: Path, capsys) -> None:
|
| 116 |
+
index_dir = tmp_path / "vector-index"
|
| 117 |
+
build_vector_index(
|
| 118 |
+
kind="numpy-flat",
|
| 119 |
+
model_id="model-a",
|
| 120 |
+
node_ids=["skill:alpha", "skill:beta"],
|
| 121 |
+
content_hashes=["ha", "hb"],
|
| 122 |
+
vectors=np.asarray([[1.0, 0.0], [0.0, 1.0]], dtype="float32"),
|
| 123 |
+
).save(index_dir)
|
| 124 |
+
graph = nx.Graph()
|
| 125 |
+
graph.add_edge("skill:alpha", "skill:beta", semantic_sim=0.9)
|
| 126 |
+
graph_path = tmp_path / "graph.json"
|
| 127 |
+
from networkx.readwrite import node_link_data
|
| 128 |
+
|
| 129 |
+
graph_path.write_text(json.dumps(node_link_data(graph, edges="edges")), encoding="utf-8")
|
| 130 |
+
|
| 131 |
+
rc = main([
|
| 132 |
+
"--index-dir", str(index_dir),
|
| 133 |
+
"--graph", str(graph_path),
|
| 134 |
+
"--node", "skill:alpha",
|
| 135 |
+
"--top-k", "1",
|
| 136 |
+
"--min-score", "0.95",
|
| 137 |
+
"--json",
|
| 138 |
+
])
|
| 139 |
+
|
| 140 |
+
assert rc == 2
|
| 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,
|
| 147 |
+
) -> None:
|
| 148 |
+
import ctx_config
|
| 149 |
+
|
| 150 |
+
wiki = tmp_path / "wiki"
|
| 151 |
+
_isolate_graphify(wiki, tmp_path / "quality", monkeypatch)
|
| 152 |
+
monkeypatch.setattr(ctx_config.cfg, "graph_edge_weight_semantic", 0.0)
|
| 153 |
+
|
| 154 |
+
_write_entity(wiki / "entities" / "skills" / "alpha.md", "alpha", ["python"])
|
| 155 |
+
_write_entity(wiki / "entities" / "skills" / "beta.md", "beta", ["python"])
|
| 156 |
+
prior, _ = wg.build_graph(incremental=False)
|
| 157 |
+
|
| 158 |
+
_write_entity(wiki / "entities" / "skills" / "gamma.md", "gamma", ["python"])
|
| 159 |
+
monkeypatch.setattr(wg, "load_prior_graph", lambda: prior.copy())
|
| 160 |
+
incremental, _ = wg.build_graph(incremental=True)
|
| 161 |
+
|
| 162 |
+
monkeypatch.setattr(wg, "load_prior_graph", lambda: None)
|
| 163 |
+
full, _ = wg.build_graph(incremental=False)
|
| 164 |
+
|
| 165 |
+
assert _node_snapshot(incremental) == _node_snapshot(full)
|
| 166 |
+
assert _edge_snapshot(incremental) == _edge_snapshot(full)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def _isolate_graphify(wiki: Path, quality: Path, monkeypatch) -> None:
|
| 170 |
+
monkeypatch.setattr(wg, "WIKI_DIR", wiki)
|
| 171 |
+
monkeypatch.setattr(wg, "SKILL_ENTITIES", wiki / "entities" / "skills")
|
| 172 |
+
monkeypatch.setattr(wg, "AGENT_ENTITIES", wiki / "entities" / "agents")
|
| 173 |
+
monkeypatch.setattr(wg, "MCP_ENTITIES", wiki / "entities" / "mcp-servers")
|
| 174 |
+
monkeypatch.setattr(wg, "HARNESS_ENTITIES", wiki / "entities" / "harnesses")
|
| 175 |
+
monkeypatch.setattr(wg, "GRAPH_OUT", wiki / "graphify-out")
|
| 176 |
+
monkeypatch.setattr(wg, "QUALITY_SIDECAR_DIR", quality)
|
| 177 |
+
monkeypatch.setattr(wg, "load_prior_graph", lambda: None)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _write_entity(path: Path, slug: str, tags: list[str]) -> None:
|
| 181 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 182 |
+
lines = ["---", f"title: {slug}", "type: skill", "tags:"]
|
| 183 |
+
lines.extend(f" - {tag}" for tag in tags)
|
| 184 |
+
lines.extend(["---", f"# {slug}", "body"])
|
| 185 |
+
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def _node_snapshot(G: nx.Graph) -> dict[str, dict[str, Any]]:
|
| 189 |
+
keys = {"label", "type", "tags", "never_load"}
|
| 190 |
+
return {
|
| 191 |
+
node_id: {key: G.nodes[node_id].get(key) for key in keys}
|
| 192 |
+
for node_id in sorted(G.nodes)
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _edge_snapshot(G: nx.Graph) -> dict[tuple[str, str], dict[str, Any]]:
|
| 197 |
+
keys = {
|
| 198 |
+
"weight",
|
| 199 |
+
"final_weight",
|
| 200 |
+
"semantic_sim",
|
| 201 |
+
"tag_sim",
|
| 202 |
+
"token_sim",
|
| 203 |
+
"shared_tags",
|
| 204 |
+
"shared_tokens",
|
| 205 |
+
"edge_reasons",
|
| 206 |
+
}
|
| 207 |
+
return {
|
| 208 |
+
tuple(sorted((left, right))): {key: attrs.get(key) for key in keys}
|
| 209 |
+
for left, right, attrs in G.edges(data=True)
|
| 210 |
+
}
|
src/tests/test_inject_hooks_security.py
CHANGED
|
@@ -1,376 +1,376 @@
|
|
| 1 |
-
"""
|
| 2 |
-
test_inject_hooks_security.py -- Security regression tests for inject_hooks.py.
|
| 3 |
-
|
| 4 |
-
Verifies:
|
| 5 |
-
1. Generated hook commands do NOT contain $CLAUDE_TOOL_INPUT or $CLAUDE_TOOL_NAME
|
| 6 |
-
as literal substrings (shell injection vectors).
|
| 7 |
-
2. The Stop array contains BOTH usage_tracker and quality_on_session_end entries.
|
| 8 |
-
3. Concurrent/repeated writes to settings.json leave a valid JSON file
|
| 9 |
-
(atomic write correctness).
|
| 10 |
-
"""
|
| 11 |
-
|
| 12 |
-
import json
|
| 13 |
-
import sys
|
| 14 |
-
import threading
|
| 15 |
-
from pathlib import Path
|
| 16 |
-
|
| 17 |
-
import pytest
|
| 18 |
-
|
| 19 |
-
# Ensure src/ is importable
|
| 20 |
-
_SRC = Path(__file__).resolve().parent.parent
|
| 21 |
-
if str(_SRC) not in sys.path:
|
| 22 |
-
sys.path.insert(0, str(_SRC))
|
| 23 |
-
|
| 24 |
-
from ctx.adapters.claude_code import inject_hooks # noqa: E402
|
| 25 |
-
from ctx.adapters.claude_code.inject_hooks import make_hooks, merge_hooks, write_settings_atomic # noqa: E402
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
# ---------------------------------------------------------------------------
|
| 29 |
-
# Helpers
|
| 30 |
-
# ---------------------------------------------------------------------------
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
def _all_commands(hooks_block: dict) -> list[str]:
|
| 34 |
-
"""Flatten every 'command' string out of a hooks block dict."""
|
| 35 |
-
cmds: list[str] = []
|
| 36 |
-
for entries in hooks_block.values():
|
| 37 |
-
for entry in entries:
|
| 38 |
-
if not isinstance(entry, dict):
|
| 39 |
-
continue
|
| 40 |
-
if "command" in entry:
|
| 41 |
-
cmds.append(entry["command"])
|
| 42 |
-
for sub in entry.get("hooks", []):
|
| 43 |
-
if isinstance(sub, dict) and "command" in sub:
|
| 44 |
-
cmds.append(sub["command"])
|
| 45 |
-
return cmds
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
def _all_modules(hooks_block: dict) -> list[str]:
|
| 49 |
-
"""Return every module invoked through ``python -m`` hook commands."""
|
| 50 |
-
modules: list[str] = []
|
| 51 |
-
for cmd in _all_commands(hooks_block):
|
| 52 |
-
parts = cmd.split()
|
| 53 |
-
if "-m" in parts:
|
| 54 |
-
idx = parts.index("-m")
|
| 55 |
-
if idx + 1 < len(parts):
|
| 56 |
-
modules.append(parts[idx + 1])
|
| 57 |
-
return modules
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
def _run_inject(ctx_dir: str, settings_path: Path) -> None:
|
| 61 |
-
"""Run the full inject pipeline (load → merge → atomic write)."""
|
| 62 |
-
from ctx.adapters.claude_code.inject_hooks import load_settings, _remove_stale_hooks
|
| 63 |
-
|
| 64 |
-
settings = load_settings(settings_path)
|
| 65 |
-
settings = _remove_stale_hooks(settings)
|
| 66 |
-
new_hooks = make_hooks(ctx_dir)
|
| 67 |
-
updated = merge_hooks(settings, new_hooks)
|
| 68 |
-
write_settings_atomic(settings_path, updated)
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
# ---------------------------------------------------------------------------
|
| 72 |
-
# Fix 1 — No shell-injection env vars in command strings
|
| 73 |
-
# ---------------------------------------------------------------------------
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
class TestNoShellInjectionVars:
|
| 77 |
-
"""Hook commands must not embed $CLAUDE_TOOL_INPUT or $CLAUDE_TOOL_NAME."""
|
| 78 |
-
|
| 79 |
-
def test_make_hooks_no_tool_input_var(self, tmp_path: Path) -> None:
|
| 80 |
-
ctx_dir = str(tmp_path / "ctx")
|
| 81 |
-
hooks = make_hooks(ctx_dir)
|
| 82 |
-
cmds = _all_commands(hooks)
|
| 83 |
-
for cmd in cmds:
|
| 84 |
-
assert "$CLAUDE_TOOL_INPUT" not in cmd, (
|
| 85 |
-
f"Shell injection vector $CLAUDE_TOOL_INPUT found in command: {cmd!r}"
|
| 86 |
-
)
|
| 87 |
-
|
| 88 |
-
def test_make_hooks_no_tool_name_var(self, tmp_path: Path) -> None:
|
| 89 |
-
ctx_dir = str(tmp_path / "ctx")
|
| 90 |
-
hooks = make_hooks(ctx_dir)
|
| 91 |
-
cmds = _all_commands(hooks)
|
| 92 |
-
for cmd in cmds:
|
| 93 |
-
assert "$CLAUDE_TOOL_NAME" not in cmd, (
|
| 94 |
-
f"Shell injection vector $CLAUDE_TOOL_NAME found in command: {cmd!r}"
|
| 95 |
-
)
|
| 96 |
-
|
| 97 |
-
def test_generated_settings_no_tool_input_var(self, tmp_path: Path) -> None:
|
| 98 |
-
"""End-to-end: the JSON written to disk must not contain the injection vars."""
|
| 99 |
-
settings_path = tmp_path / "settings.json"
|
| 100 |
-
ctx_dir = str(tmp_path / "ctx")
|
| 101 |
-
_run_inject(ctx_dir, settings_path)
|
| 102 |
-
|
| 103 |
-
raw = settings_path.read_text(encoding="utf-8")
|
| 104 |
-
assert "$CLAUDE_TOOL_INPUT" not in raw, (
|
| 105 |
-
"$CLAUDE_TOOL_INPUT found in written settings.json"
|
| 106 |
-
)
|
| 107 |
-
assert "$CLAUDE_TOOL_NAME" not in raw, (
|
| 108 |
-
"$CLAUDE_TOOL_NAME found in written settings.json"
|
| 109 |
-
)
|
| 110 |
-
|
| 111 |
-
def test_from_stdin_flag_present_in_posttooluse_commands(
|
| 112 |
-
self, tmp_path: Path
|
| 113 |
-
) -> None:
|
| 114 |
-
"""PostToolUse commands that replaced env-var args must use --from-stdin."""
|
| 115 |
-
ctx_dir = str(tmp_path / "ctx")
|
| 116 |
-
hooks = make_hooks(ctx_dir)
|
| 117 |
-
post_tool_entries = hooks.get("PostToolUse", [])
|
| 118 |
-
assert post_tool_entries, "PostToolUse block must not be empty"
|
| 119 |
-
|
| 120 |
-
# context_monitor and skill_add_detector commands must carry --from-stdin
|
| 121 |
-
sub_hooks = post_tool_entries[0].get("hooks", [])
|
| 122 |
-
cmds_with_stdin = [
|
| 123 |
-
h["command"] for h in sub_hooks
|
| 124 |
-
if isinstance(h, dict) and "--from-stdin" in h.get("command", "")
|
| 125 |
-
]
|
| 126 |
-
assert len(cmds_with_stdin) >= 2, (
|
| 127 |
-
f"Expected at least 2 --from-stdin commands; found {len(cmds_with_stdin)}: "
|
| 128 |
-
f"{cmds_with_stdin}"
|
| 129 |
-
)
|
| 130 |
-
|
| 131 |
-
def test_merge_hooks_repairs_partial_posttooluse_matcher(
|
| 132 |
-
self,
|
| 133 |
-
tmp_path: Path,
|
| 134 |
-
) -> None:
|
| 135 |
-
new_hooks = make_hooks(str(tmp_path / "ctx"))
|
| 136 |
-
existing = {
|
| 137 |
-
"hooks": {
|
| 138 |
-
"PostToolUse": [
|
| 139 |
-
{
|
| 140 |
-
"matcher": ".*",
|
| 141 |
-
"hooks": [new_hooks["PostToolUse"][0]["hooks"][0]],
|
| 142 |
-
},
|
| 143 |
-
],
|
| 144 |
-
},
|
| 145 |
-
}
|
| 146 |
-
|
| 147 |
-
merged = merge_hooks(existing, new_hooks)
|
| 148 |
-
|
| 149 |
-
commands = _all_commands({"PostToolUse": merged["hooks"]["PostToolUse"]})
|
| 150 |
-
assert any("context_monitor" in command for command in commands)
|
| 151 |
-
assert any("skill_add_detector" in command for command in commands)
|
| 152 |
-
assert any("bundle_orchestrator" in command for command in commands)
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
# ---------------------------------------------------------------------------
|
| 156 |
-
# Fix 2 — Stop array contains both usage_tracker and quality_on_session_end
|
| 157 |
-
# ---------------------------------------------------------------------------
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
class TestStopHooks:
|
| 161 |
-
def _stop_commands(self, hooks: dict) -> list[str]:
|
| 162 |
-
"""Flatten both legacy (flat) + current ({"hooks":[...]} matcher)
|
| 163 |
-
Stop-hook shapes into a list of command strings. The current
|
| 164 |
-
generator produces the matcher shape (required by Claude Code's
|
| 165 |
-
schema) but we accept both so legacy settings.json files that
|
| 166 |
-
still use the flat shape don't make the assertions drift.
|
| 167 |
-
"""
|
| 168 |
-
out: list[str] = []
|
| 169 |
-
for entry in hooks.get("Stop", []):
|
| 170 |
-
if not isinstance(entry, dict):
|
| 171 |
-
continue
|
| 172 |
-
if "command" in entry:
|
| 173 |
-
out.append(entry["command"])
|
| 174 |
-
for sub in entry.get("hooks", []):
|
| 175 |
-
if isinstance(sub, dict) and "command" in sub:
|
| 176 |
-
out.append(sub["command"])
|
| 177 |
-
return out
|
| 178 |
-
|
| 179 |
-
def test_stop_contains_usage_tracker(self, tmp_path: Path) -> None:
|
| 180 |
-
ctx_dir = str(tmp_path / "ctx")
|
| 181 |
-
hooks = make_hooks(ctx_dir)
|
| 182 |
-
stop_cmds = self._stop_commands(hooks)
|
| 183 |
-
assert any("-m usage_tracker" in c for c in stop_cmds), (
|
| 184 |
-
f"usage_tracker module not found in Stop hooks: {stop_cmds}"
|
| 185 |
-
)
|
| 186 |
-
|
| 187 |
-
def test_stop_contains_quality_on_session_end(self, tmp_path: Path) -> None:
|
| 188 |
-
ctx_dir = str(tmp_path / "ctx")
|
| 189 |
-
hooks = make_hooks(ctx_dir)
|
| 190 |
-
stop_cmds = self._stop_commands(hooks)
|
| 191 |
-
assert any("ctx.adapters.claude_code.hooks.lifecycle_hooks quality-on-session-end" in c for c in stop_cmds), (
|
| 192 |
-
f"quality hook module not found in Stop hooks: {stop_cmds}"
|
| 193 |
-
)
|
| 194 |
-
|
| 195 |
-
def test_stop_contains_both_in_generated_settings(self, tmp_path: Path) -> None:
|
| 196 |
-
settings_path = tmp_path / "settings.json"
|
| 197 |
-
ctx_dir = str(tmp_path / "ctx")
|
| 198 |
-
_run_inject(ctx_dir, settings_path)
|
| 199 |
-
|
| 200 |
-
data = json.loads(settings_path.read_text(encoding="utf-8"))
|
| 201 |
-
stop_cmds = self._stop_commands(data.get("hooks", {}))
|
| 202 |
-
|
| 203 |
-
assert any("-m usage_tracker" in c for c in stop_cmds), (
|
| 204 |
-
f"usage_tracker module missing from persisted Stop hooks: {stop_cmds}"
|
| 205 |
-
)
|
| 206 |
-
assert any("ctx.adapters.claude_code.hooks.lifecycle_hooks quality-on-session-end" in c for c in stop_cmds), (
|
| 207 |
-
f"quality hook module missing from persisted Stop hooks: {stop_cmds}"
|
| 208 |
-
)
|
| 209 |
-
|
| 210 |
-
def test_stop_hook_count_is_two(self, tmp_path: Path) -> None:
|
| 211 |
-
"""Both Stop hook commands must be present (usage_tracker + quality)."""
|
| 212 |
-
ctx_dir = str(tmp_path / "ctx")
|
| 213 |
-
hooks = make_hooks(ctx_dir)
|
| 214 |
-
stop_cmds = self._stop_commands(hooks)
|
| 215 |
-
assert len(stop_cmds) == 2, (
|
| 216 |
-
f"Expected exactly 2 Stop commands; got {len(stop_cmds)}: {stop_cmds}"
|
| 217 |
-
)
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
# ---------------------------------------------------------------------------
|
| 221 |
-
# Fix 3 — shlex.quote protects ctx_dir with special characters
|
| 222 |
-
# ---------------------------------------------------------------------------
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
class TestCtxDirQuoting:
|
| 226 |
-
def test_path_with_spaces_is_quoted(self, tmp_path: Path) -> None:
|
| 227 |
-
ctx_dir = str(tmp_path / "my ctx dir")
|
| 228 |
-
hooks = make_hooks(ctx_dir)
|
| 229 |
-
cmds = _all_commands(hooks)
|
| 230 |
-
for cmd in cmds:
|
| 231 |
-
# If the path contained spaces, the shell command must quote it —
|
| 232 |
-
# a bare space would split the path across two argv tokens.
|
| 233 |
-
if "my ctx dir" in cmd:
|
| 234 |
-
# shlex.quote wraps in single-quotes: 'my ctx dir'
|
| 235 |
-
assert "my ctx dir" not in cmd or "'" in cmd, (
|
| 236 |
-
f"Path with space is not quoted in: {cmd!r}"
|
| 237 |
-
)
|
| 238 |
-
|
| 239 |
-
def test_path_with_dollar_is_safe(self, tmp_path: Path) -> None:
|
| 240 |
-
"""A ctx_dir with a literal $ must be quoted so the shell doesn't expand it."""
|
| 241 |
-
import shlex as _shlex
|
| 242 |
-
ctx_dir = "/home/user/$HOME/ctx"
|
| 243 |
-
hooks = make_hooks(ctx_dir)
|
| 244 |
-
cmds = _all_commands(hooks)
|
| 245 |
-
quoted = _shlex.quote(ctx_dir)
|
| 246 |
-
for cmd in cmds:
|
| 247 |
-
if ctx_dir in cmd or quoted in cmd:
|
| 248 |
-
# The raw unquoted path must not appear unless it's the quoted form
|
| 249 |
-
assert f" {ctx_dir}/" not in cmd, (
|
| 250 |
-
f"Unquoted $ path found in: {cmd!r}"
|
| 251 |
-
)
|
| 252 |
-
|
| 253 |
-
def test_windows_python_path_with_spaces_uses_windows_quoting(
|
| 254 |
-
self,
|
| 255 |
-
monkeypatch: pytest.MonkeyPatch,
|
| 256 |
-
) -> None:
|
| 257 |
-
monkeypatch.setattr(
|
| 258 |
-
inject_hooks.sys,
|
| 259 |
-
"executable",
|
| 260 |
-
r"C:\Program Files\Python311\python.exe",
|
| 261 |
-
)
|
| 262 |
-
monkeypatch.setattr(inject_hooks.os, "name", "nt")
|
| 263 |
-
|
| 264 |
-
cmd = inject_hooks._module_cmd("usage_tracker", "--sync")
|
| 265 |
-
|
| 266 |
-
assert cmd == r'"C:\Program Files\Python311\python.exe" -m usage_tracker --sync'
|
| 267 |
-
assert "'" not in cmd
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
class TestPackagedHookCommands:
|
| 271 |
-
def test_commands_use_importable_modules_not_repo_paths(
|
| 272 |
-
self, tmp_path: Path
|
| 273 |
-
) -> None:
|
| 274 |
-
hooks = make_hooks(str(tmp_path / "ctx"))
|
| 275 |
-
cmds = _all_commands(hooks)
|
| 276 |
-
|
| 277 |
-
assert cmds
|
| 278 |
-
assert all(".py" not in cmd for cmd in cmds)
|
| 279 |
-
assert all("/../hooks/" not in cmd and "\\..\\hooks\\" not in cmd for cmd in cmds)
|
| 280 |
-
assert all(" 2>/dev/null" not in cmd and "|| true" not in cmd for cmd in cmds)
|
| 281 |
-
|
| 282 |
-
modules = _all_modules(hooks)
|
| 283 |
-
assert {
|
| 284 |
-
"ctx.adapters.claude_code.hooks.context_monitor",
|
| 285 |
-
"skill_add_detector",
|
| 286 |
-
"ctx.adapters.claude_code.hooks.bundle_orchestrator",
|
| 287 |
-
"usage_tracker",
|
| 288 |
-
"ctx.adapters.claude_code.hooks.lifecycle_hooks",
|
| 289 |
-
} <= set(modules)
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
# ---------------------------------------------------------------------------
|
| 293 |
-
# Fix 4 — Atomic write: concurrent writes leave valid JSON
|
| 294 |
-
# ---------------------------------------------------------------------------
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
class TestAtomicWrite:
|
| 298 |
-
def test_single_write_produces_valid_json(self, tmp_path: Path) -> None:
|
| 299 |
-
settings_path = tmp_path / "settings.json"
|
| 300 |
-
ctx_dir = str(tmp_path / "ctx")
|
| 301 |
-
_run_inject(ctx_dir, settings_path)
|
| 302 |
-
data = json.loads(settings_path.read_text(encoding="utf-8"))
|
| 303 |
-
assert "hooks" in data
|
| 304 |
-
|
| 305 |
-
def test_repeated_writes_leave_valid_json(self, tmp_path: Path) -> None:
|
| 306 |
-
"""Running inject twice (idempotent) must leave a valid, parseable JSON."""
|
| 307 |
-
settings_path = tmp_path / "settings.json"
|
| 308 |
-
ctx_dir = str(tmp_path / "ctx")
|
| 309 |
-
_run_inject(ctx_dir, settings_path)
|
| 310 |
-
_run_inject(ctx_dir, settings_path)
|
| 311 |
-
|
| 312 |
-
data = json.loads(settings_path.read_text(encoding="utf-8"))
|
| 313 |
-
assert "hooks" in data
|
| 314 |
-
|
| 315 |
-
def test_concurrent_writes_leave_valid_json(self, tmp_path: Path) -> None:
|
| 316 |
-
"""Concurrent write_settings_atomic calls must not produce a torn file.
|
| 317 |
-
|
| 318 |
-
The fix being tested: write goes to a tempfile then os.replace(), so a
|
| 319 |
-
reader never sees a partially-written JSON. We call write_settings_atomic
|
| 320 |
-
directly (bypassing load_settings) to isolate the write path from the
|
| 321 |
-
Windows file-lock behaviour on the read side.
|
| 322 |
-
"""
|
| 323 |
-
from ctx.adapters.claude_code.inject_hooks import write_settings_atomic
|
| 324 |
-
|
| 325 |
-
settings_path = tmp_path / "settings.json"
|
| 326 |
-
payload = {"hooks": {"Stop": [{"type": "command", "command": "python x.py"}]}}
|
| 327 |
-
|
| 328 |
-
# Seed the file.
|
| 329 |
-
write_settings_atomic(settings_path, payload)
|
| 330 |
-
|
| 331 |
-
errors: list[Exception] = []
|
| 332 |
-
|
| 333 |
-
def _writer() -> None:
|
| 334 |
-
try:
|
| 335 |
-
for _ in range(10):
|
| 336 |
-
write_settings_atomic(settings_path, payload)
|
| 337 |
-
except Exception as exc:
|
| 338 |
-
errors.append(exc)
|
| 339 |
-
|
| 340 |
-
t1 = threading.Thread(target=_writer)
|
| 341 |
-
t2 = threading.Thread(target=_writer)
|
| 342 |
-
t1.start()
|
| 343 |
-
t2.start()
|
| 344 |
-
t1.join()
|
| 345 |
-
t2.join()
|
| 346 |
-
|
| 347 |
-
assert not errors, f"Thread errors during concurrent writes: {errors}"
|
| 348 |
-
|
| 349 |
-
# File must still be valid JSON after concurrent writes.
|
| 350 |
-
raw = settings_path.read_text(encoding="utf-8")
|
| 351 |
-
data = json.loads(raw)
|
| 352 |
-
assert "hooks" in data
|
| 353 |
-
|
| 354 |
-
def test_write_settings_atomic_cleans_up_on_failure(
|
| 355 |
-
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 356 |
-
) -> None:
|
| 357 |
-
"""If os.replace() raises, the tempfile is removed and no stale .tmp lingers."""
|
| 358 |
-
import os as _os
|
| 359 |
-
from ctx.adapters.claude_code import inject_hooks as _ih
|
| 360 |
-
|
| 361 |
-
settings_path = tmp_path / "settings.json"
|
| 362 |
-
|
| 363 |
-
call_count = {"n": 0}
|
| 364 |
-
|
| 365 |
-
def _failing_replace(src: str, dst: str) -> None:
|
| 366 |
-
call_count["n"] += 1
|
| 367 |
-
raise OSError("simulated disk full")
|
| 368 |
-
|
| 369 |
-
monkeypatch.setattr(_os, "replace", _failing_replace)
|
| 370 |
-
|
| 371 |
-
with pytest.raises(OSError, match="simulated disk full"):
|
| 372 |
-
_ih.write_settings_atomic(settings_path, {"hooks": {}})
|
| 373 |
-
|
| 374 |
-
# No stale .tmp files should remain
|
| 375 |
-
tmp_files = list(tmp_path.glob("settings.json.*.tmp"))
|
| 376 |
-
assert not tmp_files, f"Stale tempfiles not cleaned up: {tmp_files}"
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_inject_hooks_security.py -- Security regression tests for inject_hooks.py.
|
| 3 |
+
|
| 4 |
+
Verifies:
|
| 5 |
+
1. Generated hook commands do NOT contain $CLAUDE_TOOL_INPUT or $CLAUDE_TOOL_NAME
|
| 6 |
+
as literal substrings (shell injection vectors).
|
| 7 |
+
2. The Stop array contains BOTH usage_tracker and quality_on_session_end entries.
|
| 8 |
+
3. Concurrent/repeated writes to settings.json leave a valid JSON file
|
| 9 |
+
(atomic write correctness).
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
import sys
|
| 14 |
+
import threading
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
import pytest
|
| 18 |
+
|
| 19 |
+
# Ensure src/ is importable
|
| 20 |
+
_SRC = Path(__file__).resolve().parent.parent
|
| 21 |
+
if str(_SRC) not in sys.path:
|
| 22 |
+
sys.path.insert(0, str(_SRC))
|
| 23 |
+
|
| 24 |
+
from ctx.adapters.claude_code import inject_hooks # noqa: E402
|
| 25 |
+
from ctx.adapters.claude_code.inject_hooks import make_hooks, merge_hooks, write_settings_atomic # noqa: E402
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# ---------------------------------------------------------------------------
|
| 29 |
+
# Helpers
|
| 30 |
+
# ---------------------------------------------------------------------------
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _all_commands(hooks_block: dict) -> list[str]:
|
| 34 |
+
"""Flatten every 'command' string out of a hooks block dict."""
|
| 35 |
+
cmds: list[str] = []
|
| 36 |
+
for entries in hooks_block.values():
|
| 37 |
+
for entry in entries:
|
| 38 |
+
if not isinstance(entry, dict):
|
| 39 |
+
continue
|
| 40 |
+
if "command" in entry:
|
| 41 |
+
cmds.append(entry["command"])
|
| 42 |
+
for sub in entry.get("hooks", []):
|
| 43 |
+
if isinstance(sub, dict) and "command" in sub:
|
| 44 |
+
cmds.append(sub["command"])
|
| 45 |
+
return cmds
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _all_modules(hooks_block: dict) -> list[str]:
|
| 49 |
+
"""Return every module invoked through ``python -m`` hook commands."""
|
| 50 |
+
modules: list[str] = []
|
| 51 |
+
for cmd in _all_commands(hooks_block):
|
| 52 |
+
parts = cmd.split()
|
| 53 |
+
if "-m" in parts:
|
| 54 |
+
idx = parts.index("-m")
|
| 55 |
+
if idx + 1 < len(parts):
|
| 56 |
+
modules.append(parts[idx + 1])
|
| 57 |
+
return modules
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _run_inject(ctx_dir: str, settings_path: Path) -> None:
|
| 61 |
+
"""Run the full inject pipeline (load → merge → atomic write)."""
|
| 62 |
+
from ctx.adapters.claude_code.inject_hooks import load_settings, _remove_stale_hooks
|
| 63 |
+
|
| 64 |
+
settings = load_settings(settings_path)
|
| 65 |
+
settings = _remove_stale_hooks(settings)
|
| 66 |
+
new_hooks = make_hooks(ctx_dir)
|
| 67 |
+
updated = merge_hooks(settings, new_hooks)
|
| 68 |
+
write_settings_atomic(settings_path, updated)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# ---------------------------------------------------------------------------
|
| 72 |
+
# Fix 1 — No shell-injection env vars in command strings
|
| 73 |
+
# ---------------------------------------------------------------------------
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class TestNoShellInjectionVars:
|
| 77 |
+
"""Hook commands must not embed $CLAUDE_TOOL_INPUT or $CLAUDE_TOOL_NAME."""
|
| 78 |
+
|
| 79 |
+
def test_make_hooks_no_tool_input_var(self, tmp_path: Path) -> None:
|
| 80 |
+
ctx_dir = str(tmp_path / "ctx")
|
| 81 |
+
hooks = make_hooks(ctx_dir)
|
| 82 |
+
cmds = _all_commands(hooks)
|
| 83 |
+
for cmd in cmds:
|
| 84 |
+
assert "$CLAUDE_TOOL_INPUT" not in cmd, (
|
| 85 |
+
f"Shell injection vector $CLAUDE_TOOL_INPUT found in command: {cmd!r}"
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
def test_make_hooks_no_tool_name_var(self, tmp_path: Path) -> None:
|
| 89 |
+
ctx_dir = str(tmp_path / "ctx")
|
| 90 |
+
hooks = make_hooks(ctx_dir)
|
| 91 |
+
cmds = _all_commands(hooks)
|
| 92 |
+
for cmd in cmds:
|
| 93 |
+
assert "$CLAUDE_TOOL_NAME" not in cmd, (
|
| 94 |
+
f"Shell injection vector $CLAUDE_TOOL_NAME found in command: {cmd!r}"
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
def test_generated_settings_no_tool_input_var(self, tmp_path: Path) -> None:
|
| 98 |
+
"""End-to-end: the JSON written to disk must not contain the injection vars."""
|
| 99 |
+
settings_path = tmp_path / "settings.json"
|
| 100 |
+
ctx_dir = str(tmp_path / "ctx")
|
| 101 |
+
_run_inject(ctx_dir, settings_path)
|
| 102 |
+
|
| 103 |
+
raw = settings_path.read_text(encoding="utf-8")
|
| 104 |
+
assert "$CLAUDE_TOOL_INPUT" not in raw, (
|
| 105 |
+
"$CLAUDE_TOOL_INPUT found in written settings.json"
|
| 106 |
+
)
|
| 107 |
+
assert "$CLAUDE_TOOL_NAME" not in raw, (
|
| 108 |
+
"$CLAUDE_TOOL_NAME found in written settings.json"
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
def test_from_stdin_flag_present_in_posttooluse_commands(
|
| 112 |
+
self, tmp_path: Path
|
| 113 |
+
) -> None:
|
| 114 |
+
"""PostToolUse commands that replaced env-var args must use --from-stdin."""
|
| 115 |
+
ctx_dir = str(tmp_path / "ctx")
|
| 116 |
+
hooks = make_hooks(ctx_dir)
|
| 117 |
+
post_tool_entries = hooks.get("PostToolUse", [])
|
| 118 |
+
assert post_tool_entries, "PostToolUse block must not be empty"
|
| 119 |
+
|
| 120 |
+
# context_monitor and skill_add_detector commands must carry --from-stdin
|
| 121 |
+
sub_hooks = post_tool_entries[0].get("hooks", [])
|
| 122 |
+
cmds_with_stdin = [
|
| 123 |
+
h["command"] for h in sub_hooks
|
| 124 |
+
if isinstance(h, dict) and "--from-stdin" in h.get("command", "")
|
| 125 |
+
]
|
| 126 |
+
assert len(cmds_with_stdin) >= 2, (
|
| 127 |
+
f"Expected at least 2 --from-stdin commands; found {len(cmds_with_stdin)}: "
|
| 128 |
+
f"{cmds_with_stdin}"
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
def test_merge_hooks_repairs_partial_posttooluse_matcher(
|
| 132 |
+
self,
|
| 133 |
+
tmp_path: Path,
|
| 134 |
+
) -> None:
|
| 135 |
+
new_hooks = make_hooks(str(tmp_path / "ctx"))
|
| 136 |
+
existing = {
|
| 137 |
+
"hooks": {
|
| 138 |
+
"PostToolUse": [
|
| 139 |
+
{
|
| 140 |
+
"matcher": ".*",
|
| 141 |
+
"hooks": [new_hooks["PostToolUse"][0]["hooks"][0]],
|
| 142 |
+
},
|
| 143 |
+
],
|
| 144 |
+
},
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
merged = merge_hooks(existing, new_hooks)
|
| 148 |
+
|
| 149 |
+
commands = _all_commands({"PostToolUse": merged["hooks"]["PostToolUse"]})
|
| 150 |
+
assert any("context_monitor" in command for command in commands)
|
| 151 |
+
assert any("skill_add_detector" in command for command in commands)
|
| 152 |
+
assert any("bundle_orchestrator" in command for command in commands)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
# ---------------------------------------------------------------------------
|
| 156 |
+
# Fix 2 — Stop array contains both usage_tracker and quality_on_session_end
|
| 157 |
+
# ---------------------------------------------------------------------------
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class TestStopHooks:
|
| 161 |
+
def _stop_commands(self, hooks: dict) -> list[str]:
|
| 162 |
+
"""Flatten both legacy (flat) + current ({"hooks":[...]} matcher)
|
| 163 |
+
Stop-hook shapes into a list of command strings. The current
|
| 164 |
+
generator produces the matcher shape (required by Claude Code's
|
| 165 |
+
schema) but we accept both so legacy settings.json files that
|
| 166 |
+
still use the flat shape don't make the assertions drift.
|
| 167 |
+
"""
|
| 168 |
+
out: list[str] = []
|
| 169 |
+
for entry in hooks.get("Stop", []):
|
| 170 |
+
if not isinstance(entry, dict):
|
| 171 |
+
continue
|
| 172 |
+
if "command" in entry:
|
| 173 |
+
out.append(entry["command"])
|
| 174 |
+
for sub in entry.get("hooks", []):
|
| 175 |
+
if isinstance(sub, dict) and "command" in sub:
|
| 176 |
+
out.append(sub["command"])
|
| 177 |
+
return out
|
| 178 |
+
|
| 179 |
+
def test_stop_contains_usage_tracker(self, tmp_path: Path) -> None:
|
| 180 |
+
ctx_dir = str(tmp_path / "ctx")
|
| 181 |
+
hooks = make_hooks(ctx_dir)
|
| 182 |
+
stop_cmds = self._stop_commands(hooks)
|
| 183 |
+
assert any("-m usage_tracker" in c for c in stop_cmds), (
|
| 184 |
+
f"usage_tracker module not found in Stop hooks: {stop_cmds}"
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
def test_stop_contains_quality_on_session_end(self, tmp_path: Path) -> None:
|
| 188 |
+
ctx_dir = str(tmp_path / "ctx")
|
| 189 |
+
hooks = make_hooks(ctx_dir)
|
| 190 |
+
stop_cmds = self._stop_commands(hooks)
|
| 191 |
+
assert any("ctx.adapters.claude_code.hooks.lifecycle_hooks quality-on-session-end" in c for c in stop_cmds), (
|
| 192 |
+
f"quality hook module not found in Stop hooks: {stop_cmds}"
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
def test_stop_contains_both_in_generated_settings(self, tmp_path: Path) -> None:
|
| 196 |
+
settings_path = tmp_path / "settings.json"
|
| 197 |
+
ctx_dir = str(tmp_path / "ctx")
|
| 198 |
+
_run_inject(ctx_dir, settings_path)
|
| 199 |
+
|
| 200 |
+
data = json.loads(settings_path.read_text(encoding="utf-8"))
|
| 201 |
+
stop_cmds = self._stop_commands(data.get("hooks", {}))
|
| 202 |
+
|
| 203 |
+
assert any("-m usage_tracker" in c for c in stop_cmds), (
|
| 204 |
+
f"usage_tracker module missing from persisted Stop hooks: {stop_cmds}"
|
| 205 |
+
)
|
| 206 |
+
assert any("ctx.adapters.claude_code.hooks.lifecycle_hooks quality-on-session-end" in c for c in stop_cmds), (
|
| 207 |
+
f"quality hook module missing from persisted Stop hooks: {stop_cmds}"
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
def test_stop_hook_count_is_two(self, tmp_path: Path) -> None:
|
| 211 |
+
"""Both Stop hook commands must be present (usage_tracker + quality)."""
|
| 212 |
+
ctx_dir = str(tmp_path / "ctx")
|
| 213 |
+
hooks = make_hooks(ctx_dir)
|
| 214 |
+
stop_cmds = self._stop_commands(hooks)
|
| 215 |
+
assert len(stop_cmds) == 2, (
|
| 216 |
+
f"Expected exactly 2 Stop commands; got {len(stop_cmds)}: {stop_cmds}"
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
# ---------------------------------------------------------------------------
|
| 221 |
+
# Fix 3 — shlex.quote protects ctx_dir with special characters
|
| 222 |
+
# ---------------------------------------------------------------------------
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
class TestCtxDirQuoting:
|
| 226 |
+
def test_path_with_spaces_is_quoted(self, tmp_path: Path) -> None:
|
| 227 |
+
ctx_dir = str(tmp_path / "my ctx dir")
|
| 228 |
+
hooks = make_hooks(ctx_dir)
|
| 229 |
+
cmds = _all_commands(hooks)
|
| 230 |
+
for cmd in cmds:
|
| 231 |
+
# If the path contained spaces, the shell command must quote it —
|
| 232 |
+
# a bare space would split the path across two argv tokens.
|
| 233 |
+
if "my ctx dir" in cmd:
|
| 234 |
+
# shlex.quote wraps in single-quotes: 'my ctx dir'
|
| 235 |
+
assert "my ctx dir" not in cmd or "'" in cmd, (
|
| 236 |
+
f"Path with space is not quoted in: {cmd!r}"
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
def test_path_with_dollar_is_safe(self, tmp_path: Path) -> None:
|
| 240 |
+
"""A ctx_dir with a literal $ must be quoted so the shell doesn't expand it."""
|
| 241 |
+
import shlex as _shlex
|
| 242 |
+
ctx_dir = "/home/user/$HOME/ctx"
|
| 243 |
+
hooks = make_hooks(ctx_dir)
|
| 244 |
+
cmds = _all_commands(hooks)
|
| 245 |
+
quoted = _shlex.quote(ctx_dir)
|
| 246 |
+
for cmd in cmds:
|
| 247 |
+
if ctx_dir in cmd or quoted in cmd:
|
| 248 |
+
# The raw unquoted path must not appear unless it's the quoted form
|
| 249 |
+
assert f" {ctx_dir}/" not in cmd, (
|
| 250 |
+
f"Unquoted $ path found in: {cmd!r}"
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
def test_windows_python_path_with_spaces_uses_windows_quoting(
|
| 254 |
+
self,
|
| 255 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 256 |
+
) -> None:
|
| 257 |
+
monkeypatch.setattr(
|
| 258 |
+
inject_hooks.sys,
|
| 259 |
+
"executable",
|
| 260 |
+
r"C:\Program Files\Python311\python.exe",
|
| 261 |
+
)
|
| 262 |
+
monkeypatch.setattr(inject_hooks.os, "name", "nt")
|
| 263 |
+
|
| 264 |
+
cmd = inject_hooks._module_cmd("usage_tracker", "--sync")
|
| 265 |
+
|
| 266 |
+
assert cmd == r'"C:\Program Files\Python311\python.exe" -m usage_tracker --sync'
|
| 267 |
+
assert "'" not in cmd
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
class TestPackagedHookCommands:
|
| 271 |
+
def test_commands_use_importable_modules_not_repo_paths(
|
| 272 |
+
self, tmp_path: Path
|
| 273 |
+
) -> None:
|
| 274 |
+
hooks = make_hooks(str(tmp_path / "ctx"))
|
| 275 |
+
cmds = _all_commands(hooks)
|
| 276 |
+
|
| 277 |
+
assert cmds
|
| 278 |
+
assert all(".py" not in cmd for cmd in cmds)
|
| 279 |
+
assert all("/../hooks/" not in cmd and "\\..\\hooks\\" not in cmd for cmd in cmds)
|
| 280 |
+
assert all(" 2>/dev/null" not in cmd and "|| true" not in cmd for cmd in cmds)
|
| 281 |
+
|
| 282 |
+
modules = _all_modules(hooks)
|
| 283 |
+
assert {
|
| 284 |
+
"ctx.adapters.claude_code.hooks.context_monitor",
|
| 285 |
+
"skill_add_detector",
|
| 286 |
+
"ctx.adapters.claude_code.hooks.bundle_orchestrator",
|
| 287 |
+
"usage_tracker",
|
| 288 |
+
"ctx.adapters.claude_code.hooks.lifecycle_hooks",
|
| 289 |
+
} <= set(modules)
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
# ---------------------------------------------------------------------------
|
| 293 |
+
# Fix 4 — Atomic write: concurrent writes leave valid JSON
|
| 294 |
+
# ---------------------------------------------------------------------------
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
class TestAtomicWrite:
|
| 298 |
+
def test_single_write_produces_valid_json(self, tmp_path: Path) -> None:
|
| 299 |
+
settings_path = tmp_path / "settings.json"
|
| 300 |
+
ctx_dir = str(tmp_path / "ctx")
|
| 301 |
+
_run_inject(ctx_dir, settings_path)
|
| 302 |
+
data = json.loads(settings_path.read_text(encoding="utf-8"))
|
| 303 |
+
assert "hooks" in data
|
| 304 |
+
|
| 305 |
+
def test_repeated_writes_leave_valid_json(self, tmp_path: Path) -> None:
|
| 306 |
+
"""Running inject twice (idempotent) must leave a valid, parseable JSON."""
|
| 307 |
+
settings_path = tmp_path / "settings.json"
|
| 308 |
+
ctx_dir = str(tmp_path / "ctx")
|
| 309 |
+
_run_inject(ctx_dir, settings_path)
|
| 310 |
+
_run_inject(ctx_dir, settings_path)
|
| 311 |
+
|
| 312 |
+
data = json.loads(settings_path.read_text(encoding="utf-8"))
|
| 313 |
+
assert "hooks" in data
|
| 314 |
+
|
| 315 |
+
def test_concurrent_writes_leave_valid_json(self, tmp_path: Path) -> None:
|
| 316 |
+
"""Concurrent write_settings_atomic calls must not produce a torn file.
|
| 317 |
+
|
| 318 |
+
The fix being tested: write goes to a tempfile then os.replace(), so a
|
| 319 |
+
reader never sees a partially-written JSON. We call write_settings_atomic
|
| 320 |
+
directly (bypassing load_settings) to isolate the write path from the
|
| 321 |
+
Windows file-lock behaviour on the read side.
|
| 322 |
+
"""
|
| 323 |
+
from ctx.adapters.claude_code.inject_hooks import write_settings_atomic
|
| 324 |
+
|
| 325 |
+
settings_path = tmp_path / "settings.json"
|
| 326 |
+
payload = {"hooks": {"Stop": [{"type": "command", "command": "python x.py"}]}}
|
| 327 |
+
|
| 328 |
+
# Seed the file.
|
| 329 |
+
write_settings_atomic(settings_path, payload)
|
| 330 |
+
|
| 331 |
+
errors: list[Exception] = []
|
| 332 |
+
|
| 333 |
+
def _writer() -> None:
|
| 334 |
+
try:
|
| 335 |
+
for _ in range(10):
|
| 336 |
+
write_settings_atomic(settings_path, payload)
|
| 337 |
+
except Exception as exc:
|
| 338 |
+
errors.append(exc)
|
| 339 |
+
|
| 340 |
+
t1 = threading.Thread(target=_writer)
|
| 341 |
+
t2 = threading.Thread(target=_writer)
|
| 342 |
+
t1.start()
|
| 343 |
+
t2.start()
|
| 344 |
+
t1.join()
|
| 345 |
+
t2.join()
|
| 346 |
+
|
| 347 |
+
assert not errors, f"Thread errors during concurrent writes: {errors}"
|
| 348 |
+
|
| 349 |
+
# File must still be valid JSON after concurrent writes.
|
| 350 |
+
raw = settings_path.read_text(encoding="utf-8")
|
| 351 |
+
data = json.loads(raw)
|
| 352 |
+
assert "hooks" in data
|
| 353 |
+
|
| 354 |
+
def test_write_settings_atomic_cleans_up_on_failure(
|
| 355 |
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
| 356 |
+
) -> None:
|
| 357 |
+
"""If os.replace() raises, the tempfile is removed and no stale .tmp lingers."""
|
| 358 |
+
import os as _os
|
| 359 |
+
from ctx.adapters.claude_code import inject_hooks as _ih
|
| 360 |
+
|
| 361 |
+
settings_path = tmp_path / "settings.json"
|
| 362 |
+
|
| 363 |
+
call_count = {"n": 0}
|
| 364 |
+
|
| 365 |
+
def _failing_replace(src: str, dst: str) -> None:
|
| 366 |
+
call_count["n"] += 1
|
| 367 |
+
raise OSError("simulated disk full")
|
| 368 |
+
|
| 369 |
+
monkeypatch.setattr(_os, "replace", _failing_replace)
|
| 370 |
+
|
| 371 |
+
with pytest.raises(OSError, match="simulated disk full"):
|
| 372 |
+
_ih.write_settings_atomic(settings_path, {"hooks": {}})
|
| 373 |
+
|
| 374 |
+
# No stale .tmp files should remain
|
| 375 |
+
tmp_files = list(tmp_path.glob("settings.json.*.tmp"))
|
| 376 |
+
assert not tmp_files, f"Stale tempfiles not cleaned up: {tmp_files}"
|
src/tests/test_mcp_enrich_render_scalar.py
CHANGED
|
@@ -1,121 +1,121 @@
|
|
| 1 |
-
"""
|
| 2 |
-
test_mcp_enrich_render_scalar.py -- pins the YAML-scalar rendering contract.
|
| 3 |
-
|
| 4 |
-
Security-auditor H-1: ``_render_scalar`` in ``mcp_enrich`` didn't
|
| 5 |
-
escape ``\\n`` / ``\\r`` in string values. The pulsemcp parser
|
| 6 |
-
happens to strip newlines from its regex groups today, but every
|
| 7 |
-
Source protocol implementation (future glama, mcp-get, ...) feeds
|
| 8 |
-
values straight into ``apply_enrichment`` which writes them into
|
| 9 |
-
YAML frontmatter. A multi-line value like
|
| 10 |
-
|
| 11 |
-
"https://github.com/a/b\\nstatus: installed\\ninstall_cmd: /tmp/evil"
|
| 12 |
-
|
| 13 |
-
would inject fake frontmatter keys. Once ``install_cmd`` lands in the
|
| 14 |
-
frontmatter, ``ctx-mcp-install`` on that slug would pick it up on
|
| 15 |
-
reinstall — defense-in-depth mattered (commit b79be55 added an
|
| 16 |
-
executable allowlist that catches most malicious values, but the
|
| 17 |
-
injection vector should be shut at the writer).
|
| 18 |
-
"""
|
| 19 |
-
|
| 20 |
-
from __future__ import annotations
|
| 21 |
-
|
| 22 |
-
import sys
|
| 23 |
-
from pathlib import Path
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
sys.path.insert(0, str(Path(__file__).parents[1]))
|
| 27 |
-
|
| 28 |
-
import mcp_enrich as _me
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
class TestRenderScalar:
|
| 32 |
-
def test_none_yields_null(self):
|
| 33 |
-
assert _me._render_scalar(None) == "null"
|
| 34 |
-
|
| 35 |
-
def test_int_unquoted(self):
|
| 36 |
-
assert _me._render_scalar(42) == "42"
|
| 37 |
-
|
| 38 |
-
def test_bare_string_unquoted(self):
|
| 39 |
-
assert _me._render_scalar("plain-value") == "plain-value"
|
| 40 |
-
|
| 41 |
-
def test_colon_in_string_forces_quote(self):
|
| 42 |
-
out = _me._render_scalar("https://github.com/foo/bar")
|
| 43 |
-
assert out.startswith('"')
|
| 44 |
-
assert out.endswith('"')
|
| 45 |
-
|
| 46 |
-
def test_embedded_newline_is_escaped_or_stripped(self):
|
| 47 |
-
"""H-1 regression. A newline inside a scalar must NOT survive
|
| 48 |
-
into the rendered YAML — otherwise it injects fake keys."""
|
| 49 |
-
out = _me._render_scalar("https://a.example/b\nstatus: installed")
|
| 50 |
-
# The rendered form must be a single YAML line. Accept either
|
| 51 |
-
# sanitisation (replace \\n with space) or escape (\\n literal
|
| 52 |
-
# inside a quoted string) — pin that NEITHER approach leaves a
|
| 53 |
-
# raw newline in the output.
|
| 54 |
-
assert "\n" not in out, (
|
| 55 |
-
f"rendered scalar contains raw newline — YAML injection "
|
| 56 |
-
f"vector: {out!r}"
|
| 57 |
-
)
|
| 58 |
-
# Whatever sanitisation happens, the string must not produce
|
| 59 |
-
# a ``status: installed`` key at the YAML top level. If the
|
| 60 |
-
# writer sanitises the newline to a space, the content still
|
| 61 |
-
# renders but as a single scalar value, not as a separate key.
|
| 62 |
-
lines = out.splitlines()
|
| 63 |
-
assert len(lines) == 1
|
| 64 |
-
|
| 65 |
-
def test_embedded_carriage_return_is_escaped_or_stripped(self):
|
| 66 |
-
out = _me._render_scalar("evil\rstatus: installed")
|
| 67 |
-
assert "\r" not in out
|
| 68 |
-
assert "\n" not in out
|
| 69 |
-
|
| 70 |
-
def test_windows_crlf_is_neutralised(self):
|
| 71 |
-
"""CRLF from a Windows source file must not pass through either."""
|
| 72 |
-
out = _me._render_scalar("a\r\nstatus: pwned")
|
| 73 |
-
assert "\r" not in out
|
| 74 |
-
assert "\n" not in out
|
| 75 |
-
# And the second "key" must not survive as an actual YAML key
|
| 76 |
-
# — it must be subsumed into the rendered scalar.
|
| 77 |
-
assert out.count(":") <= 2, (
|
| 78 |
-
f"suspicious colon count in {out!r} — possible key injection"
|
| 79 |
-
)
|
| 80 |
-
|
| 81 |
-
def test_null_sentinel_roundtrip_unaffected(self):
|
| 82 |
-
"""Empty string and None distinct rendering preserved — None
|
| 83 |
-
becomes ``null`` (YAML sentinel), '' stays as empty string."""
|
| 84 |
-
assert _me._render_scalar(None) == "null"
|
| 85 |
-
# Empty string hits the isinstance(str) branch but has no
|
| 86 |
-
# special chars — returns as-is.
|
| 87 |
-
assert _me._render_scalar("") == ""
|
| 88 |
-
|
| 89 |
-
def test_round_trip_through_apply_enrichment(self, tmp_path):
|
| 90 |
-
"""End-to-end: a poisoned enrichment value flows through
|
| 91 |
-
``apply_enrichment`` and the resulting file must NOT have
|
| 92 |
-
a fake ``status`` or ``install_cmd`` key inserted."""
|
| 93 |
-
entity = tmp_path / "e.md"
|
| 94 |
-
entity.write_text(
|
| 95 |
-
"---\n"
|
| 96 |
-
"slug: sample\n"
|
| 97 |
-
"github_url: null\n"
|
| 98 |
-
"updated: '2026-01-01'\n"
|
| 99 |
-
"---\n# sample\nbody\n",
|
| 100 |
-
encoding="utf-8",
|
| 101 |
-
)
|
| 102 |
-
# A Source that returned a multi-line URL injection attempt.
|
| 103 |
-
poisoned = {
|
| 104 |
-
"github_url": "https://evil.example/x\nstatus: installed",
|
| 105 |
-
}
|
| 106 |
-
_me.apply_enrichment(entity, poisoned, dry_run=False)
|
| 107 |
-
text = entity.read_text(encoding="utf-8")
|
| 108 |
-
# Count the number of top-level ``status:`` keys in the
|
| 109 |
-
# frontmatter. Zero expected — the poisoned newline must not
|
| 110 |
-
# have injected one.
|
| 111 |
-
fm = text.split("---", 2)[1]
|
| 112 |
-
status_keys = [
|
| 113 |
-
line for line in fm.splitlines()
|
| 114 |
-
if line.lstrip().startswith("status:")
|
| 115 |
-
# Must be at column 0 (not inside a quoted scalar).
|
| 116 |
-
and not line.startswith(" ")
|
| 117 |
-
]
|
| 118 |
-
assert len(status_keys) == 0, (
|
| 119 |
-
f"YAML injection via newline succeeded — found status keys: "
|
| 120 |
-
f"{status_keys!r}\nFull frontmatter:\n{fm}"
|
| 121 |
-
)
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_mcp_enrich_render_scalar.py -- pins the YAML-scalar rendering contract.
|
| 3 |
+
|
| 4 |
+
Security-auditor H-1: ``_render_scalar`` in ``mcp_enrich`` didn't
|
| 5 |
+
escape ``\\n`` / ``\\r`` in string values. The pulsemcp parser
|
| 6 |
+
happens to strip newlines from its regex groups today, but every
|
| 7 |
+
Source protocol implementation (future glama, mcp-get, ...) feeds
|
| 8 |
+
values straight into ``apply_enrichment`` which writes them into
|
| 9 |
+
YAML frontmatter. A multi-line value like
|
| 10 |
+
|
| 11 |
+
"https://github.com/a/b\\nstatus: installed\\ninstall_cmd: /tmp/evil"
|
| 12 |
+
|
| 13 |
+
would inject fake frontmatter keys. Once ``install_cmd`` lands in the
|
| 14 |
+
frontmatter, ``ctx-mcp-install`` on that slug would pick it up on
|
| 15 |
+
reinstall — defense-in-depth mattered (commit b79be55 added an
|
| 16 |
+
executable allowlist that catches most malicious values, but the
|
| 17 |
+
injection vector should be shut at the writer).
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import sys
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
sys.path.insert(0, str(Path(__file__).parents[1]))
|
| 27 |
+
|
| 28 |
+
import mcp_enrich as _me
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class TestRenderScalar:
|
| 32 |
+
def test_none_yields_null(self):
|
| 33 |
+
assert _me._render_scalar(None) == "null"
|
| 34 |
+
|
| 35 |
+
def test_int_unquoted(self):
|
| 36 |
+
assert _me._render_scalar(42) == "42"
|
| 37 |
+
|
| 38 |
+
def test_bare_string_unquoted(self):
|
| 39 |
+
assert _me._render_scalar("plain-value") == "plain-value"
|
| 40 |
+
|
| 41 |
+
def test_colon_in_string_forces_quote(self):
|
| 42 |
+
out = _me._render_scalar("https://github.com/foo/bar")
|
| 43 |
+
assert out.startswith('"')
|
| 44 |
+
assert out.endswith('"')
|
| 45 |
+
|
| 46 |
+
def test_embedded_newline_is_escaped_or_stripped(self):
|
| 47 |
+
"""H-1 regression. A newline inside a scalar must NOT survive
|
| 48 |
+
into the rendered YAML — otherwise it injects fake keys."""
|
| 49 |
+
out = _me._render_scalar("https://a.example/b\nstatus: installed")
|
| 50 |
+
# The rendered form must be a single YAML line. Accept either
|
| 51 |
+
# sanitisation (replace \\n with space) or escape (\\n literal
|
| 52 |
+
# inside a quoted string) — pin that NEITHER approach leaves a
|
| 53 |
+
# raw newline in the output.
|
| 54 |
+
assert "\n" not in out, (
|
| 55 |
+
f"rendered scalar contains raw newline — YAML injection "
|
| 56 |
+
f"vector: {out!r}"
|
| 57 |
+
)
|
| 58 |
+
# Whatever sanitisation happens, the string must not produce
|
| 59 |
+
# a ``status: installed`` key at the YAML top level. If the
|
| 60 |
+
# writer sanitises the newline to a space, the content still
|
| 61 |
+
# renders but as a single scalar value, not as a separate key.
|
| 62 |
+
lines = out.splitlines()
|
| 63 |
+
assert len(lines) == 1
|
| 64 |
+
|
| 65 |
+
def test_embedded_carriage_return_is_escaped_or_stripped(self):
|
| 66 |
+
out = _me._render_scalar("evil\rstatus: installed")
|
| 67 |
+
assert "\r" not in out
|
| 68 |
+
assert "\n" not in out
|
| 69 |
+
|
| 70 |
+
def test_windows_crlf_is_neutralised(self):
|
| 71 |
+
"""CRLF from a Windows source file must not pass through either."""
|
| 72 |
+
out = _me._render_scalar("a\r\nstatus: pwned")
|
| 73 |
+
assert "\r" not in out
|
| 74 |
+
assert "\n" not in out
|
| 75 |
+
# And the second "key" must not survive as an actual YAML key
|
| 76 |
+
# — it must be subsumed into the rendered scalar.
|
| 77 |
+
assert out.count(":") <= 2, (
|
| 78 |
+
f"suspicious colon count in {out!r} — possible key injection"
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
def test_null_sentinel_roundtrip_unaffected(self):
|
| 82 |
+
"""Empty string and None distinct rendering preserved — None
|
| 83 |
+
becomes ``null`` (YAML sentinel), '' stays as empty string."""
|
| 84 |
+
assert _me._render_scalar(None) == "null"
|
| 85 |
+
# Empty string hits the isinstance(str) branch but has no
|
| 86 |
+
# special chars — returns as-is.
|
| 87 |
+
assert _me._render_scalar("") == ""
|
| 88 |
+
|
| 89 |
+
def test_round_trip_through_apply_enrichment(self, tmp_path):
|
| 90 |
+
"""End-to-end: a poisoned enrichment value flows through
|
| 91 |
+
``apply_enrichment`` and the resulting file must NOT have
|
| 92 |
+
a fake ``status`` or ``install_cmd`` key inserted."""
|
| 93 |
+
entity = tmp_path / "e.md"
|
| 94 |
+
entity.write_text(
|
| 95 |
+
"---\n"
|
| 96 |
+
"slug: sample\n"
|
| 97 |
+
"github_url: null\n"
|
| 98 |
+
"updated: '2026-01-01'\n"
|
| 99 |
+
"---\n# sample\nbody\n",
|
| 100 |
+
encoding="utf-8",
|
| 101 |
+
)
|
| 102 |
+
# A Source that returned a multi-line URL injection attempt.
|
| 103 |
+
poisoned = {
|
| 104 |
+
"github_url": "https://evil.example/x\nstatus: installed",
|
| 105 |
+
}
|
| 106 |
+
_me.apply_enrichment(entity, poisoned, dry_run=False)
|
| 107 |
+
text = entity.read_text(encoding="utf-8")
|
| 108 |
+
# Count the number of top-level ``status:`` keys in the
|
| 109 |
+
# frontmatter. Zero expected — the poisoned newline must not
|
| 110 |
+
# have injected one.
|
| 111 |
+
fm = text.split("---", 2)[1]
|
| 112 |
+
status_keys = [
|
| 113 |
+
line for line in fm.splitlines()
|
| 114 |
+
if line.lstrip().startswith("status:")
|
| 115 |
+
# Must be at column 0 (not inside a quoted scalar).
|
| 116 |
+
and not line.startswith(" ")
|
| 117 |
+
]
|
| 118 |
+
assert len(status_keys) == 0, (
|
| 119 |
+
f"YAML injection via newline succeeded — found status keys: "
|
| 120 |
+
f"{status_keys!r}\nFull frontmatter:\n{fm}"
|
| 121 |
+
)
|
src/tests/test_mcp_router.py
CHANGED
|
@@ -1,423 +1,423 @@
|
|
| 1 |
-
"""
|
| 2 |
-
test_mcp_router.py -- McpClient + McpRouter tests against a real subprocess.
|
| 3 |
-
|
| 4 |
-
These tests spawn the fake MCP server in src/tests/fixtures/fake_mcp_server.py
|
| 5 |
-
as an actual subprocess and round-trip real JSON-RPC frames. That is
|
| 6 |
-
slower than mocking stdio, but the whole POINT of the router is to
|
| 7 |
-
talk JSON-RPC to a real child — mocking the subprocess surface would
|
| 8 |
-
verify nothing load-bearing. Each test starts + stops its own server,
|
| 9 |
-
so there's no cross-test state.
|
| 10 |
-
"""
|
| 11 |
-
|
| 12 |
-
from __future__ import annotations
|
| 13 |
-
|
| 14 |
-
import sys
|
| 15 |
-
import time
|
| 16 |
-
from pathlib import Path
|
| 17 |
-
|
| 18 |
-
import pytest
|
| 19 |
-
|
| 20 |
-
from ctx.adapters.generic.tools import (
|
| 21 |
-
McpClient,
|
| 22 |
-
McpRouter,
|
| 23 |
-
McpServerConfig,
|
| 24 |
-
McpServerError,
|
| 25 |
-
mcp_router,
|
| 26 |
-
running_router,
|
| 27 |
-
)
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
_FIXTURE = Path(__file__).parent / "fixtures" / "fake_mcp_server.py"
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
def _make_config(
|
| 34 |
-
name: str = "fake",
|
| 35 |
-
*,
|
| 36 |
-
extra_env: dict[str, str] | None = None,
|
| 37 |
-
credential_env: tuple[str, ...] = (),
|
| 38 |
-
startup_timeout: float = 5.0,
|
| 39 |
-
request_timeout: float = 5.0,
|
| 40 |
-
inherit_env: bool = False,
|
| 41 |
-
) -> McpServerConfig:
|
| 42 |
-
"""Return a config that launches the fake server via the test Python."""
|
| 43 |
-
return McpServerConfig(
|
| 44 |
-
name=name,
|
| 45 |
-
command=sys.executable,
|
| 46 |
-
args=(str(_FIXTURE),),
|
| 47 |
-
env=dict(extra_env or {}),
|
| 48 |
-
credential_env=credential_env,
|
| 49 |
-
startup_timeout=startup_timeout,
|
| 50 |
-
request_timeout=request_timeout,
|
| 51 |
-
inherit_env=inherit_env,
|
| 52 |
-
)
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
# ── McpClient basics ─────────────────────────────────────────────────────────
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
class TestClientLifecycle:
|
| 59 |
-
def test_start_and_stop(self) -> None:
|
| 60 |
-
client = McpClient(_make_config())
|
| 61 |
-
client.start()
|
| 62 |
-
try:
|
| 63 |
-
# Trivial health: list_tools succeeds → handshake completed.
|
| 64 |
-
tools = client.list_tools()
|
| 65 |
-
assert len(tools) >= 2 # echo + add
|
| 66 |
-
finally:
|
| 67 |
-
client.stop()
|
| 68 |
-
|
| 69 |
-
def test_context_manager(self) -> None:
|
| 70 |
-
with McpClient(_make_config()) as client:
|
| 71 |
-
tools = client.list_tools()
|
| 72 |
-
names = {t.name for t in tools}
|
| 73 |
-
assert {"echo", "add"} <= names
|
| 74 |
-
|
| 75 |
-
def test_double_start_rejected(self) -> None:
|
| 76 |
-
client = McpClient(_make_config())
|
| 77 |
-
client.start()
|
| 78 |
-
try:
|
| 79 |
-
with pytest.raises(RuntimeError, match="already started"):
|
| 80 |
-
client.start()
|
| 81 |
-
finally:
|
| 82 |
-
client.stop()
|
| 83 |
-
|
| 84 |
-
def test_stop_before_start_is_noop(self) -> None:
|
| 85 |
-
client = McpClient(_make_config())
|
| 86 |
-
client.stop() # must not raise
|
| 87 |
-
|
| 88 |
-
def test_bare_command_resolved_through_path(
|
| 89 |
-
self,
|
| 90 |
-
tmp_path: Path,
|
| 91 |
-
monkeypatch: pytest.MonkeyPatch,
|
| 92 |
-
) -> None:
|
| 93 |
-
resolved = tmp_path / ("npx.cmd" if sys.platform == "win32" else "npx")
|
| 94 |
-
resolved.write_text("", encoding="utf-8")
|
| 95 |
-
monkeypatch.setattr(
|
| 96 |
-
mcp_router.shutil,
|
| 97 |
-
"which",
|
| 98 |
-
lambda command, path=None: str(resolved) if command == "npx" else None,
|
| 99 |
-
)
|
| 100 |
-
|
| 101 |
-
assert mcp_router._resolve_executable("npx", {"PATH": str(tmp_path)}) == str(resolved)
|
| 102 |
-
|
| 103 |
-
def test_idempotent_stop(self) -> None:
|
| 104 |
-
client = McpClient(_make_config())
|
| 105 |
-
client.start()
|
| 106 |
-
client.stop()
|
| 107 |
-
client.stop() # second call is a no-op
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
class TestClientToolOperations:
|
| 111 |
-
def test_list_tools_shape(self) -> None:
|
| 112 |
-
with McpClient(_make_config()) as client:
|
| 113 |
-
tools = client.list_tools()
|
| 114 |
-
echo = next(t for t in tools if t.name == "echo")
|
| 115 |
-
assert echo.description == "Echo the input text verbatim."
|
| 116 |
-
assert echo.parameters["required"] == ["text"]
|
| 117 |
-
|
| 118 |
-
def test_list_tools_cached(self) -> None:
|
| 119 |
-
"""Second call must not fire a fresh tools/list RPC."""
|
| 120 |
-
with McpClient(_make_config()) as client:
|
| 121 |
-
first = client.list_tools()
|
| 122 |
-
second = client.list_tools()
|
| 123 |
-
assert first == second
|
| 124 |
-
# Cache check: same object identity on the list elements
|
| 125 |
-
assert first[0] is second[0]
|
| 126 |
-
|
| 127 |
-
def test_call_echo_round_trip(self) -> None:
|
| 128 |
-
with McpClient(_make_config()) as client:
|
| 129 |
-
result = client.call_tool("echo", {"text": "hello, world"})
|
| 130 |
-
assert result == "hello, world"
|
| 131 |
-
|
| 132 |
-
def test_call_add_integer_args(self) -> None:
|
| 133 |
-
with McpClient(_make_config()) as client:
|
| 134 |
-
result = client.call_tool("add", {"a": 3, "b": 4})
|
| 135 |
-
assert result == "7"
|
| 136 |
-
|
| 137 |
-
def test_call_unknown_tool_raises(self) -> None:
|
| 138 |
-
with McpClient(_make_config()) as client:
|
| 139 |
-
with pytest.raises(McpServerError, match="code=-32601"):
|
| 140 |
-
client.call_tool("nope", {})
|
| 141 |
-
|
| 142 |
-
def test_tool_reports_error(self) -> None:
|
| 143 |
-
with McpClient(_make_config(extra_env={"FAKE_MCP_TOOL_ERROR": "1"})) as c:
|
| 144 |
-
with pytest.raises(McpServerError, match="isError"):
|
| 145 |
-
c.call_tool("echo", {"text": "x"})
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
class TestClientRobustness:
|
| 149 |
-
def test_init_failure_surfaces_and_reaps_child(self) -> None:
|
| 150 |
-
"""When initialize errors, start() must clean up — no zombie child."""
|
| 151 |
-
client = McpClient(_make_config(extra_env={"FAKE_MCP_FAIL_INIT": "1"}))
|
| 152 |
-
with pytest.raises(McpServerError, match="init-forbidden"):
|
| 153 |
-
client.start()
|
| 154 |
-
# After failed start, _proc is reset to None so a follow-up stop()
|
| 155 |
-
# is a safe no-op and no resource leaks.
|
| 156 |
-
client.stop()
|
| 157 |
-
|
| 158 |
-
def test_server_crash_during_call(self) -> None:
|
| 159 |
-
secret = "GITHUB_TOKEN=ghp_supersecret123456789"
|
| 160 |
-
cfg = _make_config(
|
| 161 |
-
extra_env={
|
| 162 |
-
"FAKE_MCP_CRASH_ON_TOOL": "1",
|
| 163 |
-
"FAKE_MCP_STDERR_LINE": secret,
|
| 164 |
-
}
|
| 165 |
-
)
|
| 166 |
-
with McpClient(cfg) as c:
|
| 167 |
-
with pytest.raises(McpServerError, match="pipe closed") as excinfo:
|
| 168 |
-
c.call_tool("echo", {"text": "x"})
|
| 169 |
-
message = str(excinfo.value)
|
| 170 |
-
assert "ghp_supersecret" not in message
|
| 171 |
-
assert "[REDACTED]" in message
|
| 172 |
-
|
| 173 |
-
def test_killed_child_after_tool_listing_raises_mcp_error(self) -> None:
|
| 174 |
-
client = McpClient(_make_config())
|
| 175 |
-
client.start()
|
| 176 |
-
try:
|
| 177 |
-
client.list_tools()
|
| 178 |
-
proc = client._proc
|
| 179 |
-
assert proc is not None
|
| 180 |
-
proc.kill()
|
| 181 |
-
proc.wait(timeout=2.0)
|
| 182 |
-
|
| 183 |
-
with pytest.raises(McpServerError, match="write failed"):
|
| 184 |
-
client.call_tool("echo", {"text": "x"})
|
| 185 |
-
finally:
|
| 186 |
-
client.stop()
|
| 187 |
-
|
| 188 |
-
def test_server_notification_is_skipped(self) -> None:
|
| 189 |
-
"""The client ignores notifications that interleave with a response."""
|
| 190 |
-
cfg = _make_config(extra_env={"FAKE_MCP_EMIT_NOTIFICATION": "1"})
|
| 191 |
-
with McpClient(cfg) as client:
|
| 192 |
-
result = client.call_tool("echo", {"text": "hi"})
|
| 193 |
-
assert result == "hi"
|
| 194 |
-
|
| 195 |
-
def test_stderr_captured_on_startup(self) -> None:
|
| 196 |
-
cfg = _make_config(extra_env={"FAKE_MCP_NOISY_STDERR": "1"})
|
| 197 |
-
with McpClient(cfg) as client:
|
| 198 |
-
client.list_tools() # let the server run
|
| 199 |
-
# Can't poke at internal state much — just confirm no hang.
|
| 200 |
-
# The drain thread is a daemon; if it deadlocked the pipe,
|
| 201 |
-
# list_tools above would have timed out.
|
| 202 |
-
|
| 203 |
-
def test_request_before_start_raises(self) -> None:
|
| 204 |
-
client = McpClient(_make_config())
|
| 205 |
-
with pytest.raises(RuntimeError, match="not started"):
|
| 206 |
-
client.list_tools()
|
| 207 |
-
|
| 208 |
-
def test_request_timeout_when_server_stays_silent(self) -> None:
|
| 209 |
-
cfg = _make_config(
|
| 210 |
-
extra_env={"FAKE_MCP_IGNORE_TOOL": "1"},
|
| 211 |
-
request_timeout=0.2,
|
| 212 |
-
)
|
| 213 |
-
with McpClient(cfg) as client:
|
| 214 |
-
started = time.monotonic()
|
| 215 |
-
with pytest.raises(McpServerError, match="timed out after 0.2s"):
|
| 216 |
-
client.call_tool("echo", {"text": "x"})
|
| 217 |
-
assert time.monotonic() - started < 1.5
|
| 218 |
-
|
| 219 |
-
def test_parent_env_is_not_inherited_by_default(
|
| 220 |
-
self, monkeypatch: pytest.MonkeyPatch
|
| 221 |
-
) -> None:
|
| 222 |
-
monkeypatch.setenv("CTX_SECRET_SHOULD_NOT_LEAK", "leaked")
|
| 223 |
-
with McpClient(_make_config()) as client:
|
| 224 |
-
assert client.call_tool(
|
| 225 |
-
"echo_env", {"name": "CTX_SECRET_SHOULD_NOT_LEAK"}
|
| 226 |
-
) == ""
|
| 227 |
-
with McpClient(
|
| 228 |
-
_make_config(credential_env=("CTX_SECRET_SHOULD_NOT_LEAK",))
|
| 229 |
-
) as client:
|
| 230 |
-
assert client.call_tool(
|
| 231 |
-
"echo_env", {"name": "CTX_SECRET_SHOULD_NOT_LEAK"}
|
| 232 |
-
) == "leaked"
|
| 233 |
-
|
| 234 |
-
def test_explicit_env_overlay_is_passed(self) -> None:
|
| 235 |
-
cfg = _make_config(extra_env={"CTX_ALLOWED_FOR_TEST": "visible"})
|
| 236 |
-
with McpClient(cfg) as client:
|
| 237 |
-
assert client.call_tool(
|
| 238 |
-
"echo_env", {"name": "CTX_ALLOWED_FOR_TEST"}
|
| 239 |
-
) == "visible"
|
| 240 |
-
|
| 241 |
-
def test_full_env_inheritance_requires_opt_in(
|
| 242 |
-
self, monkeypatch: pytest.MonkeyPatch
|
| 243 |
-
) -> None:
|
| 244 |
-
monkeypatch.setenv("CTX_LEGACY_INHERIT_TEST", "visible")
|
| 245 |
-
with McpClient(_make_config(inherit_env=True)) as client:
|
| 246 |
-
assert client.call_tool(
|
| 247 |
-
"echo_env", {"name": "CTX_LEGACY_INHERIT_TEST"}
|
| 248 |
-
) == "visible"
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
# ── McpRouter ─────────────────────────────────────────────────────────────────
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
class TestRouter:
|
| 255 |
-
def test_single_server(self) -> None:
|
| 256 |
-
with running_router([_make_config("fake")]) as router:
|
| 257 |
-
tools = router.list_tools()
|
| 258 |
-
names = {t.name for t in tools}
|
| 259 |
-
assert {"fake__echo", "fake__add"} <= names
|
| 260 |
-
|
| 261 |
-
def test_namespaced_call(self) -> None:
|
| 262 |
-
with running_router([_make_config("fake")]) as router:
|
| 263 |
-
result = router.call("fake__echo", {"text": "round-trip"})
|
| 264 |
-
assert result == "round-trip"
|
| 265 |
-
|
| 266 |
-
def test_multi_server_union(self) -> None:
|
| 267 |
-
cfgs = [
|
| 268 |
-
_make_config("a"),
|
| 269 |
-
_make_config("b", extra_env={"FAKE_MCP_EXTRA_TOOL": "special"}),
|
| 270 |
-
]
|
| 271 |
-
with running_router(cfgs) as router:
|
| 272 |
-
tools = router.list_tools()
|
| 273 |
-
names = {t.name for t in tools}
|
| 274 |
-
assert "a__echo" in names
|
| 275 |
-
assert "a__add" in names
|
| 276 |
-
assert "b__echo" in names
|
| 277 |
-
assert "b__special" in names
|
| 278 |
-
|
| 279 |
-
def test_multi_server_routing(self) -> None:
|
| 280 |
-
"""Each server must get the call meant for it, and only it."""
|
| 281 |
-
cfgs = [_make_config("a"), _make_config("b")]
|
| 282 |
-
with running_router(cfgs) as router:
|
| 283 |
-
a_result = router.call("a__echo", {"text": "from-a"})
|
| 284 |
-
b_result = router.call("b__echo", {"text": "from-b"})
|
| 285 |
-
assert a_result == "from-a"
|
| 286 |
-
assert b_result == "from-b"
|
| 287 |
-
|
| 288 |
-
def test_unknown_server(self) -> None:
|
| 289 |
-
with running_router([_make_config("fake")]) as router:
|
| 290 |
-
with pytest.raises(ValueError, match="unknown MCP server"):
|
| 291 |
-
router.call("ghost__echo", {})
|
| 292 |
-
|
| 293 |
-
def test_malformed_qualified_name(self) -> None:
|
| 294 |
-
with running_router([_make_config("fake")]) as router:
|
| 295 |
-
with pytest.raises(ValueError, match="expected"):
|
| 296 |
-
router.call("no_separator_here", {})
|
| 297 |
-
|
| 298 |
-
def test_duplicate_server_name_rejected(self) -> None:
|
| 299 |
-
router = McpRouter([_make_config("dup"), _make_config("dup")])
|
| 300 |
-
with pytest.raises(ValueError, match="duplicate MCP server"):
|
| 301 |
-
router.start()
|
| 302 |
-
# Atomic rollback — the first (already-started) server must be
|
| 303 |
-
# reaped so we don't leak child processes.
|
| 304 |
-
assert router.server_names == []
|
| 305 |
-
|
| 306 |
-
def test_server_name_cannot_contain_router_separator(self) -> None:
|
| 307 |
-
with pytest.raises(ValueError, match="may not contain"):
|
| 308 |
-
McpServerConfig(name="foo__bar", command=sys.executable)
|
| 309 |
-
with pytest.raises(ValueError, match="reserved"):
|
| 310 |
-
McpServerConfig(name="ctx", command=sys.executable)
|
| 311 |
-
with running_router(
|
| 312 |
-
[_make_config("fake", extra_env={"FAKE_MCP_EXTRA_TOOL": "echo"})]
|
| 313 |
-
) as router:
|
| 314 |
-
with pytest.raises(ValueError, match="duplicate MCP tool name"):
|
| 315 |
-
router.list_tools()
|
| 316 |
-
|
| 317 |
-
def test_stopped_router_rejects_calls(self) -> None:
|
| 318 |
-
router = McpRouter([_make_config("fake")])
|
| 319 |
-
with pytest.raises(RuntimeError, match="not started"):
|
| 320 |
-
router.list_tools()
|
| 321 |
-
with pytest.raises(RuntimeError, match="not started"):
|
| 322 |
-
router.call("fake__echo", {})
|
| 323 |
-
|
| 324 |
-
def test_double_start_is_idempotent(self) -> None:
|
| 325 |
-
router = McpRouter([_make_config("fake")])
|
| 326 |
-
router.start()
|
| 327 |
-
try:
|
| 328 |
-
router.start() # must not spawn a second server
|
| 329 |
-
assert router.server_names == ["fake"]
|
| 330 |
-
finally:
|
| 331 |
-
router.stop()
|
| 332 |
-
|
| 333 |
-
def test_tool_descriptions_unchanged_by_namespacing(self) -> None:
|
| 334 |
-
"""The server prefix goes on the NAME only — descriptions stay clean."""
|
| 335 |
-
with running_router([_make_config("fake")]) as router:
|
| 336 |
-
tools = router.list_tools()
|
| 337 |
-
echo = next(t for t in tools if t.name == "fake__echo")
|
| 338 |
-
# Description is the server-local one, no "fake__" prefix.
|
| 339 |
-
assert echo.description == "Echo the input text verbatim."
|
| 340 |
-
|
| 341 |
-
def test_server_names_sorted(self) -> None:
|
| 342 |
-
cfgs = [_make_config("beta"), _make_config("alpha"), _make_config("gamma")]
|
| 343 |
-
with running_router(cfgs) as router:
|
| 344 |
-
assert router.server_names == ["alpha", "beta", "gamma"]
|
| 345 |
-
|
| 346 |
-
def test_atomic_startup_on_second_config_failure(self) -> None:
|
| 347 |
-
"""If one server fails to start, already-spawned ones must be reaped."""
|
| 348 |
-
cfgs = [
|
| 349 |
-
_make_config("ok"),
|
| 350 |
-
_make_config("bad", extra_env={"FAKE_MCP_FAIL_INIT": "1"}),
|
| 351 |
-
]
|
| 352 |
-
router = McpRouter(cfgs)
|
| 353 |
-
with pytest.raises(McpServerError):
|
| 354 |
-
router.start()
|
| 355 |
-
assert router.server_names == []
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
# ── _flatten_content ────────────────────────────────────────────────────────
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
class TestFlattenContent:
|
| 362 |
-
def test_empty(self) -> None:
|
| 363 |
-
from ctx.adapters.generic.tools.mcp_router import _flatten_content
|
| 364 |
-
|
| 365 |
-
assert _flatten_content([]) == ""
|
| 366 |
-
assert _flatten_content(None) == ""
|
| 367 |
-
|
| 368 |
-
def test_single_text(self) -> None:
|
| 369 |
-
from ctx.adapters.generic.tools.mcp_router import _flatten_content
|
| 370 |
-
|
| 371 |
-
assert _flatten_content([{"type": "text", "text": "hi"}]) == "hi"
|
| 372 |
-
|
| 373 |
-
def test_multi_text_concatenated(self) -> None:
|
| 374 |
-
from ctx.adapters.generic.tools.mcp_router import _flatten_content
|
| 375 |
-
|
| 376 |
-
assert _flatten_content(
|
| 377 |
-
[
|
| 378 |
-
{"type": "text", "text": "a"},
|
| 379 |
-
{"type": "text", "text": "b"},
|
| 380 |
-
{"type": "text", "text": "c"},
|
| 381 |
-
]
|
| 382 |
-
) == "abc"
|
| 383 |
-
|
| 384 |
-
def test_image_block_summarised(self) -> None:
|
| 385 |
-
from ctx.adapters.generic.tools.mcp_router import _flatten_content
|
| 386 |
-
|
| 387 |
-
out = _flatten_content([{"type": "image", "mimeType": "image/png"}])
|
| 388 |
-
assert "[image/png image omitted]" in out
|
| 389 |
-
|
| 390 |
-
def test_resource_block_summarised(self) -> None:
|
| 391 |
-
from ctx.adapters.generic.tools.mcp_router import _flatten_content
|
| 392 |
-
|
| 393 |
-
out = _flatten_content([
|
| 394 |
-
{"type": "resource", "resource": {"uri": "file:///x.md"}}
|
| 395 |
-
])
|
| 396 |
-
assert "[resource: file:///x.md]" in out
|
| 397 |
-
|
| 398 |
-
def test_unknown_type(self) -> None:
|
| 399 |
-
from ctx.adapters.generic.tools.mcp_router import _flatten_content
|
| 400 |
-
|
| 401 |
-
out = _flatten_content([{"type": "fancy", "blob": "opaque"}])
|
| 402 |
-
assert "[fancy block omitted]" in out
|
| 403 |
-
|
| 404 |
-
def test_non_dict_block(self) -> None:
|
| 405 |
-
from ctx.adapters.generic.tools.mcp_router import _flatten_content
|
| 406 |
-
|
| 407 |
-
assert _flatten_content(["just a string"]) == "just a string"
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
# ── Config dataclass ────────────────────────────────────────────────────────
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
class TestConfig:
|
| 414 |
-
def test_frozen(self) -> None:
|
| 415 |
-
cfg = _make_config("x")
|
| 416 |
-
with pytest.raises(Exception): # FrozenInstanceError
|
| 417 |
-
cfg.name = "y" # type: ignore[misc]
|
| 418 |
-
|
| 419 |
-
def test_default_env_is_fresh_dict_per_instance(self) -> None:
|
| 420 |
-
a = McpServerConfig(name="a", command="python")
|
| 421 |
-
b = McpServerConfig(name="b", command="python")
|
| 422 |
-
# dataclass field(default_factory=dict) must not share state.
|
| 423 |
-
assert a.env is not b.env
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_mcp_router.py -- McpClient + McpRouter tests against a real subprocess.
|
| 3 |
+
|
| 4 |
+
These tests spawn the fake MCP server in src/tests/fixtures/fake_mcp_server.py
|
| 5 |
+
as an actual subprocess and round-trip real JSON-RPC frames. That is
|
| 6 |
+
slower than mocking stdio, but the whole POINT of the router is to
|
| 7 |
+
talk JSON-RPC to a real child — mocking the subprocess surface would
|
| 8 |
+
verify nothing load-bearing. Each test starts + stops its own server,
|
| 9 |
+
so there's no cross-test state.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import sys
|
| 15 |
+
import time
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import pytest
|
| 19 |
+
|
| 20 |
+
from ctx.adapters.generic.tools import (
|
| 21 |
+
McpClient,
|
| 22 |
+
McpRouter,
|
| 23 |
+
McpServerConfig,
|
| 24 |
+
McpServerError,
|
| 25 |
+
mcp_router,
|
| 26 |
+
running_router,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
_FIXTURE = Path(__file__).parent / "fixtures" / "fake_mcp_server.py"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _make_config(
|
| 34 |
+
name: str = "fake",
|
| 35 |
+
*,
|
| 36 |
+
extra_env: dict[str, str] | None = None,
|
| 37 |
+
credential_env: tuple[str, ...] = (),
|
| 38 |
+
startup_timeout: float = 5.0,
|
| 39 |
+
request_timeout: float = 5.0,
|
| 40 |
+
inherit_env: bool = False,
|
| 41 |
+
) -> McpServerConfig:
|
| 42 |
+
"""Return a config that launches the fake server via the test Python."""
|
| 43 |
+
return McpServerConfig(
|
| 44 |
+
name=name,
|
| 45 |
+
command=sys.executable,
|
| 46 |
+
args=(str(_FIXTURE),),
|
| 47 |
+
env=dict(extra_env or {}),
|
| 48 |
+
credential_env=credential_env,
|
| 49 |
+
startup_timeout=startup_timeout,
|
| 50 |
+
request_timeout=request_timeout,
|
| 51 |
+
inherit_env=inherit_env,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# ── McpClient basics ─────────────────────────────────────────────────────────
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class TestClientLifecycle:
|
| 59 |
+
def test_start_and_stop(self) -> None:
|
| 60 |
+
client = McpClient(_make_config())
|
| 61 |
+
client.start()
|
| 62 |
+
try:
|
| 63 |
+
# Trivial health: list_tools succeeds → handshake completed.
|
| 64 |
+
tools = client.list_tools()
|
| 65 |
+
assert len(tools) >= 2 # echo + add
|
| 66 |
+
finally:
|
| 67 |
+
client.stop()
|
| 68 |
+
|
| 69 |
+
def test_context_manager(self) -> None:
|
| 70 |
+
with McpClient(_make_config()) as client:
|
| 71 |
+
tools = client.list_tools()
|
| 72 |
+
names = {t.name for t in tools}
|
| 73 |
+
assert {"echo", "add"} <= names
|
| 74 |
+
|
| 75 |
+
def test_double_start_rejected(self) -> None:
|
| 76 |
+
client = McpClient(_make_config())
|
| 77 |
+
client.start()
|
| 78 |
+
try:
|
| 79 |
+
with pytest.raises(RuntimeError, match="already started"):
|
| 80 |
+
client.start()
|
| 81 |
+
finally:
|
| 82 |
+
client.stop()
|
| 83 |
+
|
| 84 |
+
def test_stop_before_start_is_noop(self) -> None:
|
| 85 |
+
client = McpClient(_make_config())
|
| 86 |
+
client.stop() # must not raise
|
| 87 |
+
|
| 88 |
+
def test_bare_command_resolved_through_path(
|
| 89 |
+
self,
|
| 90 |
+
tmp_path: Path,
|
| 91 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 92 |
+
) -> None:
|
| 93 |
+
resolved = tmp_path / ("npx.cmd" if sys.platform == "win32" else "npx")
|
| 94 |
+
resolved.write_text("", encoding="utf-8")
|
| 95 |
+
monkeypatch.setattr(
|
| 96 |
+
mcp_router.shutil,
|
| 97 |
+
"which",
|
| 98 |
+
lambda command, path=None: str(resolved) if command == "npx" else None,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
assert mcp_router._resolve_executable("npx", {"PATH": str(tmp_path)}) == str(resolved)
|
| 102 |
+
|
| 103 |
+
def test_idempotent_stop(self) -> None:
|
| 104 |
+
client = McpClient(_make_config())
|
| 105 |
+
client.start()
|
| 106 |
+
client.stop()
|
| 107 |
+
client.stop() # second call is a no-op
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class TestClientToolOperations:
|
| 111 |
+
def test_list_tools_shape(self) -> None:
|
| 112 |
+
with McpClient(_make_config()) as client:
|
| 113 |
+
tools = client.list_tools()
|
| 114 |
+
echo = next(t for t in tools if t.name == "echo")
|
| 115 |
+
assert echo.description == "Echo the input text verbatim."
|
| 116 |
+
assert echo.parameters["required"] == ["text"]
|
| 117 |
+
|
| 118 |
+
def test_list_tools_cached(self) -> None:
|
| 119 |
+
"""Second call must not fire a fresh tools/list RPC."""
|
| 120 |
+
with McpClient(_make_config()) as client:
|
| 121 |
+
first = client.list_tools()
|
| 122 |
+
second = client.list_tools()
|
| 123 |
+
assert first == second
|
| 124 |
+
# Cache check: same object identity on the list elements
|
| 125 |
+
assert first[0] is second[0]
|
| 126 |
+
|
| 127 |
+
def test_call_echo_round_trip(self) -> None:
|
| 128 |
+
with McpClient(_make_config()) as client:
|
| 129 |
+
result = client.call_tool("echo", {"text": "hello, world"})
|
| 130 |
+
assert result == "hello, world"
|
| 131 |
+
|
| 132 |
+
def test_call_add_integer_args(self) -> None:
|
| 133 |
+
with McpClient(_make_config()) as client:
|
| 134 |
+
result = client.call_tool("add", {"a": 3, "b": 4})
|
| 135 |
+
assert result == "7"
|
| 136 |
+
|
| 137 |
+
def test_call_unknown_tool_raises(self) -> None:
|
| 138 |
+
with McpClient(_make_config()) as client:
|
| 139 |
+
with pytest.raises(McpServerError, match="code=-32601"):
|
| 140 |
+
client.call_tool("nope", {})
|
| 141 |
+
|
| 142 |
+
def test_tool_reports_error(self) -> None:
|
| 143 |
+
with McpClient(_make_config(extra_env={"FAKE_MCP_TOOL_ERROR": "1"})) as c:
|
| 144 |
+
with pytest.raises(McpServerError, match="isError"):
|
| 145 |
+
c.call_tool("echo", {"text": "x"})
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class TestClientRobustness:
|
| 149 |
+
def test_init_failure_surfaces_and_reaps_child(self) -> None:
|
| 150 |
+
"""When initialize errors, start() must clean up — no zombie child."""
|
| 151 |
+
client = McpClient(_make_config(extra_env={"FAKE_MCP_FAIL_INIT": "1"}))
|
| 152 |
+
with pytest.raises(McpServerError, match="init-forbidden"):
|
| 153 |
+
client.start()
|
| 154 |
+
# After failed start, _proc is reset to None so a follow-up stop()
|
| 155 |
+
# is a safe no-op and no resource leaks.
|
| 156 |
+
client.stop()
|
| 157 |
+
|
| 158 |
+
def test_server_crash_during_call(self) -> None:
|
| 159 |
+
secret = "GITHUB_TOKEN=ghp_supersecret123456789"
|
| 160 |
+
cfg = _make_config(
|
| 161 |
+
extra_env={
|
| 162 |
+
"FAKE_MCP_CRASH_ON_TOOL": "1",
|
| 163 |
+
"FAKE_MCP_STDERR_LINE": secret,
|
| 164 |
+
}
|
| 165 |
+
)
|
| 166 |
+
with McpClient(cfg) as c:
|
| 167 |
+
with pytest.raises(McpServerError, match="pipe closed") as excinfo:
|
| 168 |
+
c.call_tool("echo", {"text": "x"})
|
| 169 |
+
message = str(excinfo.value)
|
| 170 |
+
assert "ghp_supersecret" not in message
|
| 171 |
+
assert "[REDACTED]" in message
|
| 172 |
+
|
| 173 |
+
def test_killed_child_after_tool_listing_raises_mcp_error(self) -> None:
|
| 174 |
+
client = McpClient(_make_config())
|
| 175 |
+
client.start()
|
| 176 |
+
try:
|
| 177 |
+
client.list_tools()
|
| 178 |
+
proc = client._proc
|
| 179 |
+
assert proc is not None
|
| 180 |
+
proc.kill()
|
| 181 |
+
proc.wait(timeout=2.0)
|
| 182 |
+
|
| 183 |
+
with pytest.raises(McpServerError, match="write failed"):
|
| 184 |
+
client.call_tool("echo", {"text": "x"})
|
| 185 |
+
finally:
|
| 186 |
+
client.stop()
|
| 187 |
+
|
| 188 |
+
def test_server_notification_is_skipped(self) -> None:
|
| 189 |
+
"""The client ignores notifications that interleave with a response."""
|
| 190 |
+
cfg = _make_config(extra_env={"FAKE_MCP_EMIT_NOTIFICATION": "1"})
|
| 191 |
+
with McpClient(cfg) as client:
|
| 192 |
+
result = client.call_tool("echo", {"text": "hi"})
|
| 193 |
+
assert result == "hi"
|
| 194 |
+
|
| 195 |
+
def test_stderr_captured_on_startup(self) -> None:
|
| 196 |
+
cfg = _make_config(extra_env={"FAKE_MCP_NOISY_STDERR": "1"})
|
| 197 |
+
with McpClient(cfg) as client:
|
| 198 |
+
client.list_tools() # let the server run
|
| 199 |
+
# Can't poke at internal state much — just confirm no hang.
|
| 200 |
+
# The drain thread is a daemon; if it deadlocked the pipe,
|
| 201 |
+
# list_tools above would have timed out.
|
| 202 |
+
|
| 203 |
+
def test_request_before_start_raises(self) -> None:
|
| 204 |
+
client = McpClient(_make_config())
|
| 205 |
+
with pytest.raises(RuntimeError, match="not started"):
|
| 206 |
+
client.list_tools()
|
| 207 |
+
|
| 208 |
+
def test_request_timeout_when_server_stays_silent(self) -> None:
|
| 209 |
+
cfg = _make_config(
|
| 210 |
+
extra_env={"FAKE_MCP_IGNORE_TOOL": "1"},
|
| 211 |
+
request_timeout=0.2,
|
| 212 |
+
)
|
| 213 |
+
with McpClient(cfg) as client:
|
| 214 |
+
started = time.monotonic()
|
| 215 |
+
with pytest.raises(McpServerError, match="timed out after 0.2s"):
|
| 216 |
+
client.call_tool("echo", {"text": "x"})
|
| 217 |
+
assert time.monotonic() - started < 1.5
|
| 218 |
+
|
| 219 |
+
def test_parent_env_is_not_inherited_by_default(
|
| 220 |
+
self, monkeypatch: pytest.MonkeyPatch
|
| 221 |
+
) -> None:
|
| 222 |
+
monkeypatch.setenv("CTX_SECRET_SHOULD_NOT_LEAK", "leaked")
|
| 223 |
+
with McpClient(_make_config()) as client:
|
| 224 |
+
assert client.call_tool(
|
| 225 |
+
"echo_env", {"name": "CTX_SECRET_SHOULD_NOT_LEAK"}
|
| 226 |
+
) == ""
|
| 227 |
+
with McpClient(
|
| 228 |
+
_make_config(credential_env=("CTX_SECRET_SHOULD_NOT_LEAK",))
|
| 229 |
+
) as client:
|
| 230 |
+
assert client.call_tool(
|
| 231 |
+
"echo_env", {"name": "CTX_SECRET_SHOULD_NOT_LEAK"}
|
| 232 |
+
) == "leaked"
|
| 233 |
+
|
| 234 |
+
def test_explicit_env_overlay_is_passed(self) -> None:
|
| 235 |
+
cfg = _make_config(extra_env={"CTX_ALLOWED_FOR_TEST": "visible"})
|
| 236 |
+
with McpClient(cfg) as client:
|
| 237 |
+
assert client.call_tool(
|
| 238 |
+
"echo_env", {"name": "CTX_ALLOWED_FOR_TEST"}
|
| 239 |
+
) == "visible"
|
| 240 |
+
|
| 241 |
+
def test_full_env_inheritance_requires_opt_in(
|
| 242 |
+
self, monkeypatch: pytest.MonkeyPatch
|
| 243 |
+
) -> None:
|
| 244 |
+
monkeypatch.setenv("CTX_LEGACY_INHERIT_TEST", "visible")
|
| 245 |
+
with McpClient(_make_config(inherit_env=True)) as client:
|
| 246 |
+
assert client.call_tool(
|
| 247 |
+
"echo_env", {"name": "CTX_LEGACY_INHERIT_TEST"}
|
| 248 |
+
) == "visible"
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
# ── McpRouter ─────────────────────────────────────────────────────────────────
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class TestRouter:
|
| 255 |
+
def test_single_server(self) -> None:
|
| 256 |
+
with running_router([_make_config("fake")]) as router:
|
| 257 |
+
tools = router.list_tools()
|
| 258 |
+
names = {t.name for t in tools}
|
| 259 |
+
assert {"fake__echo", "fake__add"} <= names
|
| 260 |
+
|
| 261 |
+
def test_namespaced_call(self) -> None:
|
| 262 |
+
with running_router([_make_config("fake")]) as router:
|
| 263 |
+
result = router.call("fake__echo", {"text": "round-trip"})
|
| 264 |
+
assert result == "round-trip"
|
| 265 |
+
|
| 266 |
+
def test_multi_server_union(self) -> None:
|
| 267 |
+
cfgs = [
|
| 268 |
+
_make_config("a"),
|
| 269 |
+
_make_config("b", extra_env={"FAKE_MCP_EXTRA_TOOL": "special"}),
|
| 270 |
+
]
|
| 271 |
+
with running_router(cfgs) as router:
|
| 272 |
+
tools = router.list_tools()
|
| 273 |
+
names = {t.name for t in tools}
|
| 274 |
+
assert "a__echo" in names
|
| 275 |
+
assert "a__add" in names
|
| 276 |
+
assert "b__echo" in names
|
| 277 |
+
assert "b__special" in names
|
| 278 |
+
|
| 279 |
+
def test_multi_server_routing(self) -> None:
|
| 280 |
+
"""Each server must get the call meant for it, and only it."""
|
| 281 |
+
cfgs = [_make_config("a"), _make_config("b")]
|
| 282 |
+
with running_router(cfgs) as router:
|
| 283 |
+
a_result = router.call("a__echo", {"text": "from-a"})
|
| 284 |
+
b_result = router.call("b__echo", {"text": "from-b"})
|
| 285 |
+
assert a_result == "from-a"
|
| 286 |
+
assert b_result == "from-b"
|
| 287 |
+
|
| 288 |
+
def test_unknown_server(self) -> None:
|
| 289 |
+
with running_router([_make_config("fake")]) as router:
|
| 290 |
+
with pytest.raises(ValueError, match="unknown MCP server"):
|
| 291 |
+
router.call("ghost__echo", {})
|
| 292 |
+
|
| 293 |
+
def test_malformed_qualified_name(self) -> None:
|
| 294 |
+
with running_router([_make_config("fake")]) as router:
|
| 295 |
+
with pytest.raises(ValueError, match="expected"):
|
| 296 |
+
router.call("no_separator_here", {})
|
| 297 |
+
|
| 298 |
+
def test_duplicate_server_name_rejected(self) -> None:
|
| 299 |
+
router = McpRouter([_make_config("dup"), _make_config("dup")])
|
| 300 |
+
with pytest.raises(ValueError, match="duplicate MCP server"):
|
| 301 |
+
router.start()
|
| 302 |
+
# Atomic rollback — the first (already-started) server must be
|
| 303 |
+
# reaped so we don't leak child processes.
|
| 304 |
+
assert router.server_names == []
|
| 305 |
+
|
| 306 |
+
def test_server_name_cannot_contain_router_separator(self) -> None:
|
| 307 |
+
with pytest.raises(ValueError, match="may not contain"):
|
| 308 |
+
McpServerConfig(name="foo__bar", command=sys.executable)
|
| 309 |
+
with pytest.raises(ValueError, match="reserved"):
|
| 310 |
+
McpServerConfig(name="ctx", command=sys.executable)
|
| 311 |
+
with running_router(
|
| 312 |
+
[_make_config("fake", extra_env={"FAKE_MCP_EXTRA_TOOL": "echo"})]
|
| 313 |
+
) as router:
|
| 314 |
+
with pytest.raises(ValueError, match="duplicate MCP tool name"):
|
| 315 |
+
router.list_tools()
|
| 316 |
+
|
| 317 |
+
def test_stopped_router_rejects_calls(self) -> None:
|
| 318 |
+
router = McpRouter([_make_config("fake")])
|
| 319 |
+
with pytest.raises(RuntimeError, match="not started"):
|
| 320 |
+
router.list_tools()
|
| 321 |
+
with pytest.raises(RuntimeError, match="not started"):
|
| 322 |
+
router.call("fake__echo", {})
|
| 323 |
+
|
| 324 |
+
def test_double_start_is_idempotent(self) -> None:
|
| 325 |
+
router = McpRouter([_make_config("fake")])
|
| 326 |
+
router.start()
|
| 327 |
+
try:
|
| 328 |
+
router.start() # must not spawn a second server
|
| 329 |
+
assert router.server_names == ["fake"]
|
| 330 |
+
finally:
|
| 331 |
+
router.stop()
|
| 332 |
+
|
| 333 |
+
def test_tool_descriptions_unchanged_by_namespacing(self) -> None:
|
| 334 |
+
"""The server prefix goes on the NAME only — descriptions stay clean."""
|
| 335 |
+
with running_router([_make_config("fake")]) as router:
|
| 336 |
+
tools = router.list_tools()
|
| 337 |
+
echo = next(t for t in tools if t.name == "fake__echo")
|
| 338 |
+
# Description is the server-local one, no "fake__" prefix.
|
| 339 |
+
assert echo.description == "Echo the input text verbatim."
|
| 340 |
+
|
| 341 |
+
def test_server_names_sorted(self) -> None:
|
| 342 |
+
cfgs = [_make_config("beta"), _make_config("alpha"), _make_config("gamma")]
|
| 343 |
+
with running_router(cfgs) as router:
|
| 344 |
+
assert router.server_names == ["alpha", "beta", "gamma"]
|
| 345 |
+
|
| 346 |
+
def test_atomic_startup_on_second_config_failure(self) -> None:
|
| 347 |
+
"""If one server fails to start, already-spawned ones must be reaped."""
|
| 348 |
+
cfgs = [
|
| 349 |
+
_make_config("ok"),
|
| 350 |
+
_make_config("bad", extra_env={"FAKE_MCP_FAIL_INIT": "1"}),
|
| 351 |
+
]
|
| 352 |
+
router = McpRouter(cfgs)
|
| 353 |
+
with pytest.raises(McpServerError):
|
| 354 |
+
router.start()
|
| 355 |
+
assert router.server_names == []
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
# ── _flatten_content ────────────────────────────────────────────────────────
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
class TestFlattenContent:
|
| 362 |
+
def test_empty(self) -> None:
|
| 363 |
+
from ctx.adapters.generic.tools.mcp_router import _flatten_content
|
| 364 |
+
|
| 365 |
+
assert _flatten_content([]) == ""
|
| 366 |
+
assert _flatten_content(None) == ""
|
| 367 |
+
|
| 368 |
+
def test_single_text(self) -> None:
|
| 369 |
+
from ctx.adapters.generic.tools.mcp_router import _flatten_content
|
| 370 |
+
|
| 371 |
+
assert _flatten_content([{"type": "text", "text": "hi"}]) == "hi"
|
| 372 |
+
|
| 373 |
+
def test_multi_text_concatenated(self) -> None:
|
| 374 |
+
from ctx.adapters.generic.tools.mcp_router import _flatten_content
|
| 375 |
+
|
| 376 |
+
assert _flatten_content(
|
| 377 |
+
[
|
| 378 |
+
{"type": "text", "text": "a"},
|
| 379 |
+
{"type": "text", "text": "b"},
|
| 380 |
+
{"type": "text", "text": "c"},
|
| 381 |
+
]
|
| 382 |
+
) == "abc"
|
| 383 |
+
|
| 384 |
+
def test_image_block_summarised(self) -> None:
|
| 385 |
+
from ctx.adapters.generic.tools.mcp_router import _flatten_content
|
| 386 |
+
|
| 387 |
+
out = _flatten_content([{"type": "image", "mimeType": "image/png"}])
|
| 388 |
+
assert "[image/png image omitted]" in out
|
| 389 |
+
|
| 390 |
+
def test_resource_block_summarised(self) -> None:
|
| 391 |
+
from ctx.adapters.generic.tools.mcp_router import _flatten_content
|
| 392 |
+
|
| 393 |
+
out = _flatten_content([
|
| 394 |
+
{"type": "resource", "resource": {"uri": "file:///x.md"}}
|
| 395 |
+
])
|
| 396 |
+
assert "[resource: file:///x.md]" in out
|
| 397 |
+
|
| 398 |
+
def test_unknown_type(self) -> None:
|
| 399 |
+
from ctx.adapters.generic.tools.mcp_router import _flatten_content
|
| 400 |
+
|
| 401 |
+
out = _flatten_content([{"type": "fancy", "blob": "opaque"}])
|
| 402 |
+
assert "[fancy block omitted]" in out
|
| 403 |
+
|
| 404 |
+
def test_non_dict_block(self) -> None:
|
| 405 |
+
from ctx.adapters.generic.tools.mcp_router import _flatten_content
|
| 406 |
+
|
| 407 |
+
assert _flatten_content(["just a string"]) == "just a string"
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
# ── Config dataclass ────────────────────────────────────────────────────────
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
class TestConfig:
|
| 414 |
+
def test_frozen(self) -> None:
|
| 415 |
+
cfg = _make_config("x")
|
| 416 |
+
with pytest.raises(Exception): # FrozenInstanceError
|
| 417 |
+
cfg.name = "y" # type: ignore[misc]
|
| 418 |
+
|
| 419 |
+
def test_default_env_is_fresh_dict_per_instance(self) -> None:
|
| 420 |
+
a = McpServerConfig(name="a", command="python")
|
| 421 |
+
b = McpServerConfig(name="b", command="python")
|
| 422 |
+
# dataclass field(default_factory=dict) must not share state.
|
| 423 |
+
assert a.env is not b.env
|
src/tests/test_mcp_sources_awesome.py
CHANGED
|
@@ -1,169 +1,169 @@
|
|
| 1 |
-
"""
|
| 2 |
-
tests/test_mcp_sources_awesome.py -- Unit tests for mcp_sources.awesome_mcp.
|
| 3 |
-
|
| 4 |
-
Contracts tested (Phase 2a locked spec):
|
| 5 |
-
- _parse_readme(text) -> list[dict] (pure function, no network)
|
| 6 |
-
- Each dict has name, description, sources=["awesome-mcp"]
|
| 7 |
-
- GitHub links extracted to github_url
|
| 8 |
-
- Non-github links extracted to homepage_url
|
| 9 |
-
- Section headers produce tag entries
|
| 10 |
-
- Malformed lines skipped gracefully
|
| 11 |
-
- Parsed dicts round-trip through McpRecord.from_dict()
|
| 12 |
-
- SOURCE singleton has expected name / homepage attributes
|
| 13 |
-
"""
|
| 14 |
-
|
| 15 |
-
from __future__ import annotations
|
| 16 |
-
|
| 17 |
-
import sys
|
| 18 |
-
from pathlib import Path
|
| 19 |
-
|
| 20 |
-
import pytest
|
| 21 |
-
|
| 22 |
-
SRC_DIR = Path(__file__).resolve().parents[1]
|
| 23 |
-
if str(SRC_DIR) not in sys.path:
|
| 24 |
-
sys.path.insert(0, str(SRC_DIR))
|
| 25 |
-
|
| 26 |
-
_FIXTURE_PATH = Path(__file__).parent / "fixtures" / "awesome_mcp_excerpt.md"
|
| 27 |
-
|
| 28 |
-
from mcp_sources.awesome_mcp import SOURCE, _parse_readme # type: ignore[import-untyped] # noqa: E402
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
# ---------------------------------------------------------------------------
|
| 32 |
-
# Helpers
|
| 33 |
-
# ---------------------------------------------------------------------------
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
def _excerpt() -> str:
|
| 37 |
-
return _FIXTURE_PATH.read_text(encoding="utf-8")
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
# ---------------------------------------------------------------------------
|
| 41 |
-
# _parse_readme — edge cases
|
| 42 |
-
# ---------------------------------------------------------------------------
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
class TestParseReadmeEdgeCases:
|
| 46 |
-
def test_empty_string_returns_empty_list(self) -> None:
|
| 47 |
-
result = _parse_readme("")
|
| 48 |
-
assert result == []
|
| 49 |
-
|
| 50 |
-
def test_whitespace_only_returns_empty_list(self) -> None:
|
| 51 |
-
result = _parse_readme(" \n\n \n")
|
| 52 |
-
assert result == []
|
| 53 |
-
|
| 54 |
-
def test_malformed_line_does_not_crash(self) -> None:
|
| 55 |
-
# Parser only emits records found AFTER the ## Server Implementations
|
| 56 |
-
# gate; we include it so the ### subsection below is in scope.
|
| 57 |
-
text = (
|
| 58 |
-
"## Server Implementations\n\n"
|
| 59 |
-
"### 🛠️ Tools\n\n"
|
| 60 |
-
"This line has no link and should be skipped gracefully by the parser.\n"
|
| 61 |
-
"- [valid-mcp](https://github.com/example/valid-mcp) - A valid entry.\n"
|
| 62 |
-
)
|
| 63 |
-
result = _parse_readme(text)
|
| 64 |
-
assert [r["name"] for r in result] == ["valid-mcp"]
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
# ---------------------------------------------------------------------------
|
| 68 |
-
# _parse_readme — excerpt fixture (5 well-formed entries)
|
| 69 |
-
# ---------------------------------------------------------------------------
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
class TestParseReadmeExcerpt:
|
| 73 |
-
def test_excerpt_produces_correct_entry_count(self) -> None:
|
| 74 |
-
result = _parse_readme(_excerpt())
|
| 75 |
-
assert len(result) == 6
|
| 76 |
-
|
| 77 |
-
def test_excerpt_produces_exact_expected_names(self) -> None:
|
| 78 |
-
result = _parse_readme(_excerpt())
|
| 79 |
-
assert [entry["name"] for entry in result] == [
|
| 80 |
-
"github-mcp",
|
| 81 |
-
"gitlab-mcp",
|
| 82 |
-
"postgres-mcp",
|
| 83 |
-
"sqlite-mcp",
|
| 84 |
-
"notion-mcp",
|
| 85 |
-
"another-tool",
|
| 86 |
-
]
|
| 87 |
-
|
| 88 |
-
def test_each_dict_has_name_key(self) -> None:
|
| 89 |
-
result = _parse_readme(_excerpt())
|
| 90 |
-
for entry in result:
|
| 91 |
-
assert "name" in entry, f"Missing 'name' in {entry}"
|
| 92 |
-
|
| 93 |
-
def test_each_dict_has_description_key(self) -> None:
|
| 94 |
-
result = _parse_readme(_excerpt())
|
| 95 |
-
for entry in result:
|
| 96 |
-
assert "description" in entry, f"Missing 'description' in {entry}"
|
| 97 |
-
|
| 98 |
-
def test_each_dict_has_sources_list(self) -> None:
|
| 99 |
-
result = _parse_readme(_excerpt())
|
| 100 |
-
for entry in result:
|
| 101 |
-
assert "sources" in entry, f"Missing 'sources' in {entry}"
|
| 102 |
-
assert isinstance(entry["sources"], list)
|
| 103 |
-
|
| 104 |
-
def test_sources_contains_awesome_mcp(self) -> None:
|
| 105 |
-
result = _parse_readme(_excerpt())
|
| 106 |
-
for entry in result:
|
| 107 |
-
assert "awesome-mcp" in entry["sources"], (
|
| 108 |
-
f"'awesome-mcp' not in sources for {entry['name']}"
|
| 109 |
-
)
|
| 110 |
-
|
| 111 |
-
def test_github_url_extracted_for_github_links(self) -> None:
|
| 112 |
-
result = {entry["name"]: entry for entry in _parse_readme(_excerpt())}
|
| 113 |
-
assert result["github-mcp"]["github_url"] == (
|
| 114 |
-
"https://github.com/modelcontextprotocol/github-mcp"
|
| 115 |
-
)
|
| 116 |
-
assert result["gitlab-mcp"]["github_url"] == "https://github.com/acmecorp/gitlab-mcp"
|
| 117 |
-
assert result["postgres-mcp"]["github_url"] == "https://github.com/example/postgres-mcp"
|
| 118 |
-
assert result["sqlite-mcp"]["github_url"] == "https://github.com/example/sqlite-mcp"
|
| 119 |
-
assert result["another-tool"]["github_url"] == "https://github.com/example/another-tool"
|
| 120 |
-
assert "github_url" not in result["notion-mcp"]
|
| 121 |
-
|
| 122 |
-
def test_non_github_url_extracted_as_homepage_url(self) -> None:
|
| 123 |
-
# The fixture has notion-mcp linking to www.notion.so — not github
|
| 124 |
-
result = {entry["name"]: entry for entry in _parse_readme(_excerpt())}
|
| 125 |
-
assert result["notion-mcp"]["homepage_url"] == (
|
| 126 |
-
"https://www.notion.so/integrations/notion-mcp"
|
| 127 |
-
)
|
| 128 |
-
assert "homepage_url" not in result["github-mcp"]
|
| 129 |
-
|
| 130 |
-
def test_section_header_produces_tag_on_entries_below(self) -> None:
|
| 131 |
-
# Entries under "### 🐙 Version Control" should carry a version-control tag
|
| 132 |
-
result = {entry["name"]: entry for entry in _parse_readme(_excerpt())}
|
| 133 |
-
assert result["github-mcp"]["tags"] == ["version-control"]
|
| 134 |
-
assert result["gitlab-mcp"]["tags"] == ["version-control"]
|
| 135 |
-
assert result["postgres-mcp"]["tags"] == ["databases"]
|
| 136 |
-
assert result["sqlite-mcp"]["tags"] == ["databases"]
|
| 137 |
-
assert result["notion-mcp"]["tags"] == ["productivity"]
|
| 138 |
-
assert result["another-tool"]["tags"] == ["productivity"]
|
| 139 |
-
|
| 140 |
-
def test_parsed_dicts_round_trip_through_mcp_record(self) -> None:
|
| 141 |
-
from mcp_entity import McpRecord # noqa: PLC0415
|
| 142 |
-
|
| 143 |
-
result = _parse_readme(_excerpt())
|
| 144 |
-
for entry in result:
|
| 145 |
-
try:
|
| 146 |
-
McpRecord.from_dict(entry)
|
| 147 |
-
except Exception as exc:
|
| 148 |
-
pytest.fail(
|
| 149 |
-
f"McpRecord.from_dict() raised for entry {entry.get('name')!r}: {exc}"
|
| 150 |
-
)
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
# ---------------------------------------------------------------------------
|
| 154 |
-
# SOURCE singleton
|
| 155 |
-
# ---------------------------------------------------------------------------
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
class TestSourceSingleton:
|
| 159 |
-
def test_source_name_is_awesome_mcp(self) -> None:
|
| 160 |
-
assert SOURCE.name == "awesome-mcp"
|
| 161 |
-
|
| 162 |
-
def test_source_homepage_is_non_empty_string(self) -> None:
|
| 163 |
-
assert isinstance(SOURCE.homepage, str)
|
| 164 |
-
assert SOURCE.homepage.strip() != ""
|
| 165 |
-
|
| 166 |
-
def test_source_homepage_looks_like_url(self) -> None:
|
| 167 |
-
assert SOURCE.homepage.startswith("http"), (
|
| 168 |
-
f"SOURCE.homepage should start with 'http', got: {SOURCE.homepage!r}"
|
| 169 |
-
)
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
tests/test_mcp_sources_awesome.py -- Unit tests for mcp_sources.awesome_mcp.
|
| 3 |
+
|
| 4 |
+
Contracts tested (Phase 2a locked spec):
|
| 5 |
+
- _parse_readme(text) -> list[dict] (pure function, no network)
|
| 6 |
+
- Each dict has name, description, sources=["awesome-mcp"]
|
| 7 |
+
- GitHub links extracted to github_url
|
| 8 |
+
- Non-github links extracted to homepage_url
|
| 9 |
+
- Section headers produce tag entries
|
| 10 |
+
- Malformed lines skipped gracefully
|
| 11 |
+
- Parsed dicts round-trip through McpRecord.from_dict()
|
| 12 |
+
- SOURCE singleton has expected name / homepage attributes
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import sys
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
import pytest
|
| 21 |
+
|
| 22 |
+
SRC_DIR = Path(__file__).resolve().parents[1]
|
| 23 |
+
if str(SRC_DIR) not in sys.path:
|
| 24 |
+
sys.path.insert(0, str(SRC_DIR))
|
| 25 |
+
|
| 26 |
+
_FIXTURE_PATH = Path(__file__).parent / "fixtures" / "awesome_mcp_excerpt.md"
|
| 27 |
+
|
| 28 |
+
from mcp_sources.awesome_mcp import SOURCE, _parse_readme # type: ignore[import-untyped] # noqa: E402
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# ---------------------------------------------------------------------------
|
| 32 |
+
# Helpers
|
| 33 |
+
# ---------------------------------------------------------------------------
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _excerpt() -> str:
|
| 37 |
+
return _FIXTURE_PATH.read_text(encoding="utf-8")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# ---------------------------------------------------------------------------
|
| 41 |
+
# _parse_readme — edge cases
|
| 42 |
+
# ---------------------------------------------------------------------------
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class TestParseReadmeEdgeCases:
|
| 46 |
+
def test_empty_string_returns_empty_list(self) -> None:
|
| 47 |
+
result = _parse_readme("")
|
| 48 |
+
assert result == []
|
| 49 |
+
|
| 50 |
+
def test_whitespace_only_returns_empty_list(self) -> None:
|
| 51 |
+
result = _parse_readme(" \n\n \n")
|
| 52 |
+
assert result == []
|
| 53 |
+
|
| 54 |
+
def test_malformed_line_does_not_crash(self) -> None:
|
| 55 |
+
# Parser only emits records found AFTER the ## Server Implementations
|
| 56 |
+
# gate; we include it so the ### subsection below is in scope.
|
| 57 |
+
text = (
|
| 58 |
+
"## Server Implementations\n\n"
|
| 59 |
+
"### 🛠️ Tools\n\n"
|
| 60 |
+
"This line has no link and should be skipped gracefully by the parser.\n"
|
| 61 |
+
"- [valid-mcp](https://github.com/example/valid-mcp) - A valid entry.\n"
|
| 62 |
+
)
|
| 63 |
+
result = _parse_readme(text)
|
| 64 |
+
assert [r["name"] for r in result] == ["valid-mcp"]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# ---------------------------------------------------------------------------
|
| 68 |
+
# _parse_readme — excerpt fixture (5 well-formed entries)
|
| 69 |
+
# ---------------------------------------------------------------------------
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class TestParseReadmeExcerpt:
|
| 73 |
+
def test_excerpt_produces_correct_entry_count(self) -> None:
|
| 74 |
+
result = _parse_readme(_excerpt())
|
| 75 |
+
assert len(result) == 6
|
| 76 |
+
|
| 77 |
+
def test_excerpt_produces_exact_expected_names(self) -> None:
|
| 78 |
+
result = _parse_readme(_excerpt())
|
| 79 |
+
assert [entry["name"] for entry in result] == [
|
| 80 |
+
"github-mcp",
|
| 81 |
+
"gitlab-mcp",
|
| 82 |
+
"postgres-mcp",
|
| 83 |
+
"sqlite-mcp",
|
| 84 |
+
"notion-mcp",
|
| 85 |
+
"another-tool",
|
| 86 |
+
]
|
| 87 |
+
|
| 88 |
+
def test_each_dict_has_name_key(self) -> None:
|
| 89 |
+
result = _parse_readme(_excerpt())
|
| 90 |
+
for entry in result:
|
| 91 |
+
assert "name" in entry, f"Missing 'name' in {entry}"
|
| 92 |
+
|
| 93 |
+
def test_each_dict_has_description_key(self) -> None:
|
| 94 |
+
result = _parse_readme(_excerpt())
|
| 95 |
+
for entry in result:
|
| 96 |
+
assert "description" in entry, f"Missing 'description' in {entry}"
|
| 97 |
+
|
| 98 |
+
def test_each_dict_has_sources_list(self) -> None:
|
| 99 |
+
result = _parse_readme(_excerpt())
|
| 100 |
+
for entry in result:
|
| 101 |
+
assert "sources" in entry, f"Missing 'sources' in {entry}"
|
| 102 |
+
assert isinstance(entry["sources"], list)
|
| 103 |
+
|
| 104 |
+
def test_sources_contains_awesome_mcp(self) -> None:
|
| 105 |
+
result = _parse_readme(_excerpt())
|
| 106 |
+
for entry in result:
|
| 107 |
+
assert "awesome-mcp" in entry["sources"], (
|
| 108 |
+
f"'awesome-mcp' not in sources for {entry['name']}"
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
def test_github_url_extracted_for_github_links(self) -> None:
|
| 112 |
+
result = {entry["name"]: entry for entry in _parse_readme(_excerpt())}
|
| 113 |
+
assert result["github-mcp"]["github_url"] == (
|
| 114 |
+
"https://github.com/modelcontextprotocol/github-mcp"
|
| 115 |
+
)
|
| 116 |
+
assert result["gitlab-mcp"]["github_url"] == "https://github.com/acmecorp/gitlab-mcp"
|
| 117 |
+
assert result["postgres-mcp"]["github_url"] == "https://github.com/example/postgres-mcp"
|
| 118 |
+
assert result["sqlite-mcp"]["github_url"] == "https://github.com/example/sqlite-mcp"
|
| 119 |
+
assert result["another-tool"]["github_url"] == "https://github.com/example/another-tool"
|
| 120 |
+
assert "github_url" not in result["notion-mcp"]
|
| 121 |
+
|
| 122 |
+
def test_non_github_url_extracted_as_homepage_url(self) -> None:
|
| 123 |
+
# The fixture has notion-mcp linking to www.notion.so — not github
|
| 124 |
+
result = {entry["name"]: entry for entry in _parse_readme(_excerpt())}
|
| 125 |
+
assert result["notion-mcp"]["homepage_url"] == (
|
| 126 |
+
"https://www.notion.so/integrations/notion-mcp"
|
| 127 |
+
)
|
| 128 |
+
assert "homepage_url" not in result["github-mcp"]
|
| 129 |
+
|
| 130 |
+
def test_section_header_produces_tag_on_entries_below(self) -> None:
|
| 131 |
+
# Entries under "### 🐙 Version Control" should carry a version-control tag
|
| 132 |
+
result = {entry["name"]: entry for entry in _parse_readme(_excerpt())}
|
| 133 |
+
assert result["github-mcp"]["tags"] == ["version-control"]
|
| 134 |
+
assert result["gitlab-mcp"]["tags"] == ["version-control"]
|
| 135 |
+
assert result["postgres-mcp"]["tags"] == ["databases"]
|
| 136 |
+
assert result["sqlite-mcp"]["tags"] == ["databases"]
|
| 137 |
+
assert result["notion-mcp"]["tags"] == ["productivity"]
|
| 138 |
+
assert result["another-tool"]["tags"] == ["productivity"]
|
| 139 |
+
|
| 140 |
+
def test_parsed_dicts_round_trip_through_mcp_record(self) -> None:
|
| 141 |
+
from mcp_entity import McpRecord # noqa: PLC0415
|
| 142 |
+
|
| 143 |
+
result = _parse_readme(_excerpt())
|
| 144 |
+
for entry in result:
|
| 145 |
+
try:
|
| 146 |
+
McpRecord.from_dict(entry)
|
| 147 |
+
except Exception as exc:
|
| 148 |
+
pytest.fail(
|
| 149 |
+
f"McpRecord.from_dict() raised for entry {entry.get('name')!r}: {exc}"
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# ---------------------------------------------------------------------------
|
| 154 |
+
# SOURCE singleton
|
| 155 |
+
# ---------------------------------------------------------------------------
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class TestSourceSingleton:
|
| 159 |
+
def test_source_name_is_awesome_mcp(self) -> None:
|
| 160 |
+
assert SOURCE.name == "awesome-mcp"
|
| 161 |
+
|
| 162 |
+
def test_source_homepage_is_non_empty_string(self) -> None:
|
| 163 |
+
assert isinstance(SOURCE.homepage, str)
|
| 164 |
+
assert SOURCE.homepage.strip() != ""
|
| 165 |
+
|
| 166 |
+
def test_source_homepage_looks_like_url(self) -> None:
|
| 167 |
+
assert SOURCE.homepage.startswith("http"), (
|
| 168 |
+
f"SOURCE.homepage should start with 'http', got: {SOURCE.homepage!r}"
|
| 169 |
+
)
|
src/tests/test_patch_graph.py
CHANGED
|
@@ -1,394 +1,394 @@
|
|
| 1 |
-
"""
|
| 2 |
-
test_patch_graph.py -- Coverage for wiki_graphify.patch_graph.
|
| 3 |
-
|
| 4 |
-
patch_graph is the incremental-update core: given a prior graph + a
|
| 5 |
-
set of affected nodes + target edges, it mutates the prior graph
|
| 6 |
-
in-place so it matches the new target state while preserving edges
|
| 7 |
-
between unaffected node pairs.
|
| 8 |
-
|
| 9 |
-
A bug here produces silent gaps (missing edges), silent stale
|
| 10 |
-
edges (wrong weights lingering), or full-rebuild performance
|
| 11 |
-
regressions.
|
| 12 |
-
"""
|
| 13 |
-
|
| 14 |
-
from __future__ import annotations
|
| 15 |
-
|
| 16 |
-
from typing import Any
|
| 17 |
-
|
| 18 |
-
import networkx as nx
|
| 19 |
-
import pytest
|
| 20 |
-
|
| 21 |
-
from ctx.core.wiki.wiki_graphify import patch_graph
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
# ── Helpers ──────────────────────────────────────────────────────────────────
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
def _make_prior(
|
| 28 |
-
nodes: list[tuple[str, dict[str, Any]]] | None = None,
|
| 29 |
-
edges: list[tuple[str, str, dict[str, Any]]] | None = None,
|
| 30 |
-
) -> nx.Graph:
|
| 31 |
-
G = nx.Graph()
|
| 32 |
-
for nid, attrs in (nodes or []):
|
| 33 |
-
G.add_node(nid, **attrs)
|
| 34 |
-
for u, v, attrs in (edges or []):
|
| 35 |
-
G.add_edge(u, v, **attrs)
|
| 36 |
-
return G
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
def _info(label: str, type_: str = "skill", tags: list[str] | None = None) -> dict:
|
| 40 |
-
return {"label": label, "type": type_, "tags": list(tags or [])}
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
# ── Node-level delta ─────────────────────────────────────────────────────────
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
class TestNodeDelta:
|
| 47 |
-
def test_new_node_added_with_attrs(self) -> None:
|
| 48 |
-
prior = _make_prior()
|
| 49 |
-
current = {"skill:a": _info("a", "skill", ["py"])}
|
| 50 |
-
patch_graph(
|
| 51 |
-
prior,
|
| 52 |
-
current_node_info=current,
|
| 53 |
-
target_edges={},
|
| 54 |
-
affected_node_ids=set(),
|
| 55 |
-
)
|
| 56 |
-
assert "skill:a" in prior
|
| 57 |
-
assert prior.nodes["skill:a"]["label"] == "a"
|
| 58 |
-
assert prior.nodes["skill:a"]["type"] == "skill"
|
| 59 |
-
assert prior.nodes["skill:a"]["tags"] == ["py"]
|
| 60 |
-
|
| 61 |
-
def test_removed_node_dropped(self) -> None:
|
| 62 |
-
prior = _make_prior([("skill:gone", _info("gone"))])
|
| 63 |
-
patch_graph(
|
| 64 |
-
prior,
|
| 65 |
-
current_node_info={},
|
| 66 |
-
target_edges={},
|
| 67 |
-
affected_node_ids=set(),
|
| 68 |
-
)
|
| 69 |
-
assert "skill:gone" not in prior
|
| 70 |
-
|
| 71 |
-
def test_existing_node_attrs_refreshed(self) -> None:
|
| 72 |
-
"""Tags may have changed between runs — patch must refresh."""
|
| 73 |
-
prior = _make_prior(
|
| 74 |
-
[("skill:a", {"label": "a", "type": "skill", "tags": ["old"]})]
|
| 75 |
-
)
|
| 76 |
-
current = {"skill:a": _info("a", "skill", ["new"])}
|
| 77 |
-
patch_graph(
|
| 78 |
-
prior,
|
| 79 |
-
current_node_info=current,
|
| 80 |
-
target_edges={},
|
| 81 |
-
affected_node_ids=set(),
|
| 82 |
-
)
|
| 83 |
-
assert prior.nodes["skill:a"]["tags"] == ["new"]
|
| 84 |
-
|
| 85 |
-
def test_label_defaults_from_nid_suffix(self) -> None:
|
| 86 |
-
prior = _make_prior()
|
| 87 |
-
patch_graph(
|
| 88 |
-
prior,
|
| 89 |
-
current_node_info={"skill:fastapi-pro": {}},
|
| 90 |
-
target_edges={},
|
| 91 |
-
affected_node_ids=set(),
|
| 92 |
-
)
|
| 93 |
-
assert prior.nodes["skill:fastapi-pro"]["label"] == "fastapi-pro"
|
| 94 |
-
|
| 95 |
-
def test_type_preserved_when_info_omits_it(self) -> None:
|
| 96 |
-
"""Refresh on existing node should preserve the prior type if new info has none."""
|
| 97 |
-
prior = _make_prior(
|
| 98 |
-
[("skill:a", {"label": "a", "type": "skill", "tags": []})]
|
| 99 |
-
)
|
| 100 |
-
patch_graph(
|
| 101 |
-
prior,
|
| 102 |
-
current_node_info={"skill:a": {"label": "a", "tags": []}},
|
| 103 |
-
target_edges={},
|
| 104 |
-
affected_node_ids=set(),
|
| 105 |
-
)
|
| 106 |
-
assert prior.nodes["skill:a"]["type"] == "skill"
|
| 107 |
-
|
| 108 |
-
def test_tags_stored_as_fresh_list(self) -> None:
|
| 109 |
-
"""Mutating the info afterwards must not leak into the graph."""
|
| 110 |
-
tags = ["py"]
|
| 111 |
-
prior = _make_prior()
|
| 112 |
-
patch_graph(
|
| 113 |
-
prior,
|
| 114 |
-
current_node_info={"skill:a": _info("a", "skill", tags)},
|
| 115 |
-
target_edges={},
|
| 116 |
-
affected_node_ids=set(),
|
| 117 |
-
)
|
| 118 |
-
tags.append("leak")
|
| 119 |
-
assert "leak" not in prior.nodes["skill:a"]["tags"]
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
# ── Edge-level delta ─────────────────────────────────────────────────────────
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
class TestEdgeDelta:
|
| 126 |
-
def test_edges_between_unaffected_pairs_preserved(self) -> None:
|
| 127 |
-
"""The core invariant: unaffected pairs keep their prior edges untouched."""
|
| 128 |
-
prior = _make_prior(
|
| 129 |
-
[("skill:a", _info("a")), ("skill:b", _info("b"))],
|
| 130 |
-
[("skill:a", "skill:b", {"weight": 0.8, "semantic_sim": 0.8})],
|
| 131 |
-
)
|
| 132 |
-
current = {
|
| 133 |
-
"skill:a": _info("a"),
|
| 134 |
-
"skill:b": _info("b"),
|
| 135 |
-
}
|
| 136 |
-
patch_graph(
|
| 137 |
-
prior,
|
| 138 |
-
current_node_info=current,
|
| 139 |
-
target_edges={},
|
| 140 |
-
affected_node_ids=set(),
|
| 141 |
-
)
|
| 142 |
-
# Both nodes unaffected → edge should survive.
|
| 143 |
-
assert prior.has_edge("skill:a", "skill:b")
|
| 144 |
-
assert prior["skill:a"]["skill:b"]["weight"] == 0.8
|
| 145 |
-
|
| 146 |
-
def test_edge_incident_on_affected_node_refreshed(self) -> None:
|
| 147 |
-
prior = _make_prior(
|
| 148 |
-
[("skill:a", _info("a")), ("skill:b", _info("b"))],
|
| 149 |
-
[("skill:a", "skill:b", {"weight": 0.8})],
|
| 150 |
-
)
|
| 151 |
-
current = {
|
| 152 |
-
"skill:a": _info("a"),
|
| 153 |
-
"skill:b": _info("b"),
|
| 154 |
-
}
|
| 155 |
-
target = {("skill:a", "skill:b"): {"weight": 0.5, "semantic_sim": 0.5}}
|
| 156 |
-
patch_graph(
|
| 157 |
-
prior,
|
| 158 |
-
current_node_info=current,
|
| 159 |
-
target_edges=target,
|
| 160 |
-
affected_node_ids={"skill:a"},
|
| 161 |
-
)
|
| 162 |
-
assert prior["skill:a"]["skill:b"]["weight"] == 0.5
|
| 163 |
-
assert prior["skill:a"]["skill:b"]["semantic_sim"] == 0.5
|
| 164 |
-
|
| 165 |
-
def test_edge_to_removed_node_disappears(self) -> None:
|
| 166 |
-
prior = _make_prior(
|
| 167 |
-
[("skill:a", _info("a")), ("skill:gone", _info("gone"))],
|
| 168 |
-
[("skill:a", "skill:gone", {"weight": 0.5})],
|
| 169 |
-
)
|
| 170 |
-
patch_graph(
|
| 171 |
-
prior,
|
| 172 |
-
current_node_info={"skill:a": _info("a")},
|
| 173 |
-
target_edges={},
|
| 174 |
-
affected_node_ids=set(),
|
| 175 |
-
)
|
| 176 |
-
# Removing node also cleans up its edges (NetworkX semantics).
|
| 177 |
-
assert not prior.has_edge("skill:a", "skill:gone")
|
| 178 |
-
assert "skill:gone" not in prior
|
| 179 |
-
|
| 180 |
-
def test_new_edge_between_new_nodes(self) -> None:
|
| 181 |
-
prior = _make_prior()
|
| 182 |
-
current = {
|
| 183 |
-
"skill:a": _info("a"),
|
| 184 |
-
"skill:b": _info("b"),
|
| 185 |
-
}
|
| 186 |
-
target = {("skill:a", "skill:b"): {"weight": 0.7}}
|
| 187 |
-
patch_graph(
|
| 188 |
-
prior,
|
| 189 |
-
current_node_info=current,
|
| 190 |
-
target_edges=target,
|
| 191 |
-
affected_node_ids=set(),
|
| 192 |
-
)
|
| 193 |
-
assert prior.has_edge("skill:a", "skill:b")
|
| 194 |
-
assert prior["skill:a"]["skill:b"]["weight"] == 0.7
|
| 195 |
-
|
| 196 |
-
def test_target_edge_with_missing_endpoint_skipped(self) -> None:
|
| 197 |
-
"""Target edges referencing a node absent from current_node_info must not materialize."""
|
| 198 |
-
prior = _make_prior()
|
| 199 |
-
current = {"skill:a": _info("a")}
|
| 200 |
-
target = {("skill:a", "skill:ghost"): {"weight": 0.5}}
|
| 201 |
-
patch_graph(
|
| 202 |
-
prior,
|
| 203 |
-
current_node_info=current,
|
| 204 |
-
target_edges=target,
|
| 205 |
-
affected_node_ids={"skill:a"},
|
| 206 |
-
)
|
| 207 |
-
assert not prior.has_edge("skill:a", "skill:ghost")
|
| 208 |
-
|
| 209 |
-
def test_stale_edge_on_affected_node_removed(self) -> None:
|
| 210 |
-
"""Affected node loses all incident edges that aren't re-added by target_edges."""
|
| 211 |
-
prior = _make_prior(
|
| 212 |
-
[
|
| 213 |
-
("skill:a", _info("a")),
|
| 214 |
-
("skill:b", _info("b")),
|
| 215 |
-
("skill:c", _info("c")),
|
| 216 |
-
],
|
| 217 |
-
[
|
| 218 |
-
("skill:a", "skill:b", {"weight": 0.5}),
|
| 219 |
-
("skill:a", "skill:c", {"weight": 0.5}),
|
| 220 |
-
],
|
| 221 |
-
)
|
| 222 |
-
current = {
|
| 223 |
-
"skill:a": _info("a"),
|
| 224 |
-
"skill:b": _info("b"),
|
| 225 |
-
"skill:c": _info("c"),
|
| 226 |
-
}
|
| 227 |
-
# Only a-b is in the new target; a-c should be dropped.
|
| 228 |
-
target = {("skill:a", "skill:b"): {"weight": 0.6}}
|
| 229 |
-
patch_graph(
|
| 230 |
-
prior,
|
| 231 |
-
current_node_info=current,
|
| 232 |
-
target_edges=target,
|
| 233 |
-
affected_node_ids={"skill:a"},
|
| 234 |
-
)
|
| 235 |
-
assert prior.has_edge("skill:a", "skill:b")
|
| 236 |
-
assert prior["skill:a"]["skill:b"]["weight"] == 0.6
|
| 237 |
-
assert not prior.has_edge("skill:a", "skill:c")
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
# ── Affected set semantics ───────────────────────────────────────────────────
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
class TestAffectedSet:
|
| 244 |
-
def test_affected_union_new_nodes(self) -> None:
|
| 245 |
-
"""New nodes join the affected set implicitly — their edges must be evaluated."""
|
| 246 |
-
prior = _make_prior(
|
| 247 |
-
[("skill:a", _info("a"))],
|
| 248 |
-
[],
|
| 249 |
-
)
|
| 250 |
-
current = {
|
| 251 |
-
"skill:a": _info("a"),
|
| 252 |
-
"skill:b": _info("b"),
|
| 253 |
-
}
|
| 254 |
-
# Only b is new; caller did NOT include it in affected_node_ids.
|
| 255 |
-
target = {("skill:a", "skill:b"): {"weight": 0.9}}
|
| 256 |
-
patch_graph(
|
| 257 |
-
prior,
|
| 258 |
-
current_node_info=current,
|
| 259 |
-
target_edges=target,
|
| 260 |
-
affected_node_ids=set(), # empty
|
| 261 |
-
)
|
| 262 |
-
# Still materializes because new nodes are auto-affected.
|
| 263 |
-
assert prior.has_edge("skill:a", "skill:b")
|
| 264 |
-
|
| 265 |
-
def test_affected_union_removed_nodes(self) -> None:
|
| 266 |
-
"""Removed nodes' edges are dropped even when caller omits them from affected."""
|
| 267 |
-
prior = _make_prior(
|
| 268 |
-
[("skill:a", _info("a")), ("skill:gone", _info("gone"))],
|
| 269 |
-
[("skill:a", "skill:gone", {"weight": 0.5})],
|
| 270 |
-
)
|
| 271 |
-
patch_graph(
|
| 272 |
-
prior,
|
| 273 |
-
current_node_info={"skill:a": _info("a")},
|
| 274 |
-
target_edges={},
|
| 275 |
-
affected_node_ids=set(), # empty — but gone is removed
|
| 276 |
-
)
|
| 277 |
-
assert "skill:gone" not in prior
|
| 278 |
-
|
| 279 |
-
def test_affected_node_not_in_prior_tolerated(self) -> None:
|
| 280 |
-
"""Affected set may list a node not yet in prior — patch should not crash."""
|
| 281 |
-
prior = _make_prior()
|
| 282 |
-
patch_graph(
|
| 283 |
-
prior,
|
| 284 |
-
current_node_info={"skill:a": _info("a")},
|
| 285 |
-
target_edges={},
|
| 286 |
-
affected_node_ids={"skill:a", "skill:does-not-exist-yet"},
|
| 287 |
-
)
|
| 288 |
-
assert "skill:a" in prior
|
| 289 |
-
assert "skill:does-not-exist-yet" not in prior
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
# ── Return value ─────────────────────────────────────────────────────────────
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
class TestReturnValue:
|
| 296 |
-
def test_returns_same_instance(self) -> None:
|
| 297 |
-
"""Caller expects the same graph object they passed in."""
|
| 298 |
-
prior = _make_prior()
|
| 299 |
-
out = patch_graph(
|
| 300 |
-
prior,
|
| 301 |
-
current_node_info={},
|
| 302 |
-
target_edges={},
|
| 303 |
-
affected_node_ids=set(),
|
| 304 |
-
)
|
| 305 |
-
assert out is prior
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
# ── Integration: full cycle ─────────────────────────────────────────────────
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
class TestFullCycle:
|
| 312 |
-
def test_no_op_when_nothing_changes(self) -> None:
|
| 313 |
-
"""Idempotent: same inputs twice should leave the graph identical."""
|
| 314 |
-
prior = _make_prior(
|
| 315 |
-
[("skill:a", _info("a", tags=["py"])),
|
| 316 |
-
("skill:b", _info("b", tags=["py"]))],
|
| 317 |
-
[("skill:a", "skill:b", {"weight": 0.5})],
|
| 318 |
-
)
|
| 319 |
-
current = {
|
| 320 |
-
"skill:a": _info("a", tags=["py"]),
|
| 321 |
-
"skill:b": _info("b", tags=["py"]),
|
| 322 |
-
}
|
| 323 |
-
target = {("skill:a", "skill:b"): {"weight": 0.5}}
|
| 324 |
-
|
| 325 |
-
patch_graph(
|
| 326 |
-
prior,
|
| 327 |
-
current_node_info=current,
|
| 328 |
-
target_edges=target,
|
| 329 |
-
affected_node_ids=set(),
|
| 330 |
-
)
|
| 331 |
-
snapshot = (
|
| 332 |
-
set(prior.nodes()),
|
| 333 |
-
sorted(prior.edges()),
|
| 334 |
-
prior["skill:a"]["skill:b"]["weight"],
|
| 335 |
-
)
|
| 336 |
-
patch_graph(
|
| 337 |
-
prior,
|
| 338 |
-
current_node_info=current,
|
| 339 |
-
target_edges=target,
|
| 340 |
-
affected_node_ids=set(),
|
| 341 |
-
)
|
| 342 |
-
assert (
|
| 343 |
-
set(prior.nodes()),
|
| 344 |
-
sorted(prior.edges()),
|
| 345 |
-
prior["skill:a"]["skill:b"]["weight"],
|
| 346 |
-
) == snapshot
|
| 347 |
-
|
| 348 |
-
def test_prints_summary(self, capsys: pytest.CaptureFixture[str]) -> None:
|
| 349 |
-
"""Operational summary line must be emitted."""
|
| 350 |
-
prior = _make_prior()
|
| 351 |
-
patch_graph(
|
| 352 |
-
prior,
|
| 353 |
-
current_node_info={"skill:a": _info("a")},
|
| 354 |
-
target_edges={},
|
| 355 |
-
affected_node_ids=set(),
|
| 356 |
-
)
|
| 357 |
-
out = capsys.readouterr().out
|
| 358 |
-
assert "patch_graph:" in out
|
| 359 |
-
assert "added=1 nodes" in out
|
| 360 |
-
|
| 361 |
-
def test_combined_add_remove_update(self) -> None:
|
| 362 |
-
"""Stress: one node removed, one added, one updated, edges refreshed."""
|
| 363 |
-
prior = _make_prior(
|
| 364 |
-
[
|
| 365 |
-
("skill:a", _info("a", tags=["old"])),
|
| 366 |
-
("skill:b", _info("b")),
|
| 367 |
-
("skill:gone", _info("gone")),
|
| 368 |
-
],
|
| 369 |
-
[
|
| 370 |
-
("skill:a", "skill:b", {"weight": 0.3}),
|
| 371 |
-
("skill:a", "skill:gone", {"weight": 0.4}),
|
| 372 |
-
],
|
| 373 |
-
)
|
| 374 |
-
current = {
|
| 375 |
-
"skill:a": _info("a", tags=["fresh"]),
|
| 376 |
-
"skill:b": _info("b"),
|
| 377 |
-
"skill:new": _info("new"),
|
| 378 |
-
}
|
| 379 |
-
target = {
|
| 380 |
-
("skill:a", "skill:b"): {"weight": 0.7},
|
| 381 |
-
("skill:b", "skill:new"): {"weight": 0.6},
|
| 382 |
-
}
|
| 383 |
-
patch_graph(
|
| 384 |
-
prior,
|
| 385 |
-
current_node_info=current,
|
| 386 |
-
target_edges=target,
|
| 387 |
-
affected_node_ids={"skill:a"},
|
| 388 |
-
)
|
| 389 |
-
assert "skill:gone" not in prior
|
| 390 |
-
assert "skill:new" in prior
|
| 391 |
-
assert prior.nodes["skill:a"]["tags"] == ["fresh"]
|
| 392 |
-
assert prior["skill:a"]["skill:b"]["weight"] == 0.7
|
| 393 |
-
assert prior.has_edge("skill:b", "skill:new")
|
| 394 |
-
assert prior["skill:b"]["skill:new"]["weight"] == 0.6
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_patch_graph.py -- Coverage for wiki_graphify.patch_graph.
|
| 3 |
+
|
| 4 |
+
patch_graph is the incremental-update core: given a prior graph + a
|
| 5 |
+
set of affected nodes + target edges, it mutates the prior graph
|
| 6 |
+
in-place so it matches the new target state while preserving edges
|
| 7 |
+
between unaffected node pairs.
|
| 8 |
+
|
| 9 |
+
A bug here produces silent gaps (missing edges), silent stale
|
| 10 |
+
edges (wrong weights lingering), or full-rebuild performance
|
| 11 |
+
regressions.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
from typing import Any
|
| 17 |
+
|
| 18 |
+
import networkx as nx
|
| 19 |
+
import pytest
|
| 20 |
+
|
| 21 |
+
from ctx.core.wiki.wiki_graphify import patch_graph
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# ── Helpers ──────────────────────────────────────────────────────────────────
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _make_prior(
|
| 28 |
+
nodes: list[tuple[str, dict[str, Any]]] | None = None,
|
| 29 |
+
edges: list[tuple[str, str, dict[str, Any]]] | None = None,
|
| 30 |
+
) -> nx.Graph:
|
| 31 |
+
G = nx.Graph()
|
| 32 |
+
for nid, attrs in (nodes or []):
|
| 33 |
+
G.add_node(nid, **attrs)
|
| 34 |
+
for u, v, attrs in (edges or []):
|
| 35 |
+
G.add_edge(u, v, **attrs)
|
| 36 |
+
return G
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _info(label: str, type_: str = "skill", tags: list[str] | None = None) -> dict:
|
| 40 |
+
return {"label": label, "type": type_, "tags": list(tags or [])}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# ── Node-level delta ─────────────────────────────────────────────────────────
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class TestNodeDelta:
|
| 47 |
+
def test_new_node_added_with_attrs(self) -> None:
|
| 48 |
+
prior = _make_prior()
|
| 49 |
+
current = {"skill:a": _info("a", "skill", ["py"])}
|
| 50 |
+
patch_graph(
|
| 51 |
+
prior,
|
| 52 |
+
current_node_info=current,
|
| 53 |
+
target_edges={},
|
| 54 |
+
affected_node_ids=set(),
|
| 55 |
+
)
|
| 56 |
+
assert "skill:a" in prior
|
| 57 |
+
assert prior.nodes["skill:a"]["label"] == "a"
|
| 58 |
+
assert prior.nodes["skill:a"]["type"] == "skill"
|
| 59 |
+
assert prior.nodes["skill:a"]["tags"] == ["py"]
|
| 60 |
+
|
| 61 |
+
def test_removed_node_dropped(self) -> None:
|
| 62 |
+
prior = _make_prior([("skill:gone", _info("gone"))])
|
| 63 |
+
patch_graph(
|
| 64 |
+
prior,
|
| 65 |
+
current_node_info={},
|
| 66 |
+
target_edges={},
|
| 67 |
+
affected_node_ids=set(),
|
| 68 |
+
)
|
| 69 |
+
assert "skill:gone" not in prior
|
| 70 |
+
|
| 71 |
+
def test_existing_node_attrs_refreshed(self) -> None:
|
| 72 |
+
"""Tags may have changed between runs — patch must refresh."""
|
| 73 |
+
prior = _make_prior(
|
| 74 |
+
[("skill:a", {"label": "a", "type": "skill", "tags": ["old"]})]
|
| 75 |
+
)
|
| 76 |
+
current = {"skill:a": _info("a", "skill", ["new"])}
|
| 77 |
+
patch_graph(
|
| 78 |
+
prior,
|
| 79 |
+
current_node_info=current,
|
| 80 |
+
target_edges={},
|
| 81 |
+
affected_node_ids=set(),
|
| 82 |
+
)
|
| 83 |
+
assert prior.nodes["skill:a"]["tags"] == ["new"]
|
| 84 |
+
|
| 85 |
+
def test_label_defaults_from_nid_suffix(self) -> None:
|
| 86 |
+
prior = _make_prior()
|
| 87 |
+
patch_graph(
|
| 88 |
+
prior,
|
| 89 |
+
current_node_info={"skill:fastapi-pro": {}},
|
| 90 |
+
target_edges={},
|
| 91 |
+
affected_node_ids=set(),
|
| 92 |
+
)
|
| 93 |
+
assert prior.nodes["skill:fastapi-pro"]["label"] == "fastapi-pro"
|
| 94 |
+
|
| 95 |
+
def test_type_preserved_when_info_omits_it(self) -> None:
|
| 96 |
+
"""Refresh on existing node should preserve the prior type if new info has none."""
|
| 97 |
+
prior = _make_prior(
|
| 98 |
+
[("skill:a", {"label": "a", "type": "skill", "tags": []})]
|
| 99 |
+
)
|
| 100 |
+
patch_graph(
|
| 101 |
+
prior,
|
| 102 |
+
current_node_info={"skill:a": {"label": "a", "tags": []}},
|
| 103 |
+
target_edges={},
|
| 104 |
+
affected_node_ids=set(),
|
| 105 |
+
)
|
| 106 |
+
assert prior.nodes["skill:a"]["type"] == "skill"
|
| 107 |
+
|
| 108 |
+
def test_tags_stored_as_fresh_list(self) -> None:
|
| 109 |
+
"""Mutating the info afterwards must not leak into the graph."""
|
| 110 |
+
tags = ["py"]
|
| 111 |
+
prior = _make_prior()
|
| 112 |
+
patch_graph(
|
| 113 |
+
prior,
|
| 114 |
+
current_node_info={"skill:a": _info("a", "skill", tags)},
|
| 115 |
+
target_edges={},
|
| 116 |
+
affected_node_ids=set(),
|
| 117 |
+
)
|
| 118 |
+
tags.append("leak")
|
| 119 |
+
assert "leak" not in prior.nodes["skill:a"]["tags"]
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# ── Edge-level delta ─────────────────────────────────────────────────────────
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class TestEdgeDelta:
|
| 126 |
+
def test_edges_between_unaffected_pairs_preserved(self) -> None:
|
| 127 |
+
"""The core invariant: unaffected pairs keep their prior edges untouched."""
|
| 128 |
+
prior = _make_prior(
|
| 129 |
+
[("skill:a", _info("a")), ("skill:b", _info("b"))],
|
| 130 |
+
[("skill:a", "skill:b", {"weight": 0.8, "semantic_sim": 0.8})],
|
| 131 |
+
)
|
| 132 |
+
current = {
|
| 133 |
+
"skill:a": _info("a"),
|
| 134 |
+
"skill:b": _info("b"),
|
| 135 |
+
}
|
| 136 |
+
patch_graph(
|
| 137 |
+
prior,
|
| 138 |
+
current_node_info=current,
|
| 139 |
+
target_edges={},
|
| 140 |
+
affected_node_ids=set(),
|
| 141 |
+
)
|
| 142 |
+
# Both nodes unaffected → edge should survive.
|
| 143 |
+
assert prior.has_edge("skill:a", "skill:b")
|
| 144 |
+
assert prior["skill:a"]["skill:b"]["weight"] == 0.8
|
| 145 |
+
|
| 146 |
+
def test_edge_incident_on_affected_node_refreshed(self) -> None:
|
| 147 |
+
prior = _make_prior(
|
| 148 |
+
[("skill:a", _info("a")), ("skill:b", _info("b"))],
|
| 149 |
+
[("skill:a", "skill:b", {"weight": 0.8})],
|
| 150 |
+
)
|
| 151 |
+
current = {
|
| 152 |
+
"skill:a": _info("a"),
|
| 153 |
+
"skill:b": _info("b"),
|
| 154 |
+
}
|
| 155 |
+
target = {("skill:a", "skill:b"): {"weight": 0.5, "semantic_sim": 0.5}}
|
| 156 |
+
patch_graph(
|
| 157 |
+
prior,
|
| 158 |
+
current_node_info=current,
|
| 159 |
+
target_edges=target,
|
| 160 |
+
affected_node_ids={"skill:a"},
|
| 161 |
+
)
|
| 162 |
+
assert prior["skill:a"]["skill:b"]["weight"] == 0.5
|
| 163 |
+
assert prior["skill:a"]["skill:b"]["semantic_sim"] == 0.5
|
| 164 |
+
|
| 165 |
+
def test_edge_to_removed_node_disappears(self) -> None:
|
| 166 |
+
prior = _make_prior(
|
| 167 |
+
[("skill:a", _info("a")), ("skill:gone", _info("gone"))],
|
| 168 |
+
[("skill:a", "skill:gone", {"weight": 0.5})],
|
| 169 |
+
)
|
| 170 |
+
patch_graph(
|
| 171 |
+
prior,
|
| 172 |
+
current_node_info={"skill:a": _info("a")},
|
| 173 |
+
target_edges={},
|
| 174 |
+
affected_node_ids=set(),
|
| 175 |
+
)
|
| 176 |
+
# Removing node also cleans up its edges (NetworkX semantics).
|
| 177 |
+
assert not prior.has_edge("skill:a", "skill:gone")
|
| 178 |
+
assert "skill:gone" not in prior
|
| 179 |
+
|
| 180 |
+
def test_new_edge_between_new_nodes(self) -> None:
|
| 181 |
+
prior = _make_prior()
|
| 182 |
+
current = {
|
| 183 |
+
"skill:a": _info("a"),
|
| 184 |
+
"skill:b": _info("b"),
|
| 185 |
+
}
|
| 186 |
+
target = {("skill:a", "skill:b"): {"weight": 0.7}}
|
| 187 |
+
patch_graph(
|
| 188 |
+
prior,
|
| 189 |
+
current_node_info=current,
|
| 190 |
+
target_edges=target,
|
| 191 |
+
affected_node_ids=set(),
|
| 192 |
+
)
|
| 193 |
+
assert prior.has_edge("skill:a", "skill:b")
|
| 194 |
+
assert prior["skill:a"]["skill:b"]["weight"] == 0.7
|
| 195 |
+
|
| 196 |
+
def test_target_edge_with_missing_endpoint_skipped(self) -> None:
|
| 197 |
+
"""Target edges referencing a node absent from current_node_info must not materialize."""
|
| 198 |
+
prior = _make_prior()
|
| 199 |
+
current = {"skill:a": _info("a")}
|
| 200 |
+
target = {("skill:a", "skill:ghost"): {"weight": 0.5}}
|
| 201 |
+
patch_graph(
|
| 202 |
+
prior,
|
| 203 |
+
current_node_info=current,
|
| 204 |
+
target_edges=target,
|
| 205 |
+
affected_node_ids={"skill:a"},
|
| 206 |
+
)
|
| 207 |
+
assert not prior.has_edge("skill:a", "skill:ghost")
|
| 208 |
+
|
| 209 |
+
def test_stale_edge_on_affected_node_removed(self) -> None:
|
| 210 |
+
"""Affected node loses all incident edges that aren't re-added by target_edges."""
|
| 211 |
+
prior = _make_prior(
|
| 212 |
+
[
|
| 213 |
+
("skill:a", _info("a")),
|
| 214 |
+
("skill:b", _info("b")),
|
| 215 |
+
("skill:c", _info("c")),
|
| 216 |
+
],
|
| 217 |
+
[
|
| 218 |
+
("skill:a", "skill:b", {"weight": 0.5}),
|
| 219 |
+
("skill:a", "skill:c", {"weight": 0.5}),
|
| 220 |
+
],
|
| 221 |
+
)
|
| 222 |
+
current = {
|
| 223 |
+
"skill:a": _info("a"),
|
| 224 |
+
"skill:b": _info("b"),
|
| 225 |
+
"skill:c": _info("c"),
|
| 226 |
+
}
|
| 227 |
+
# Only a-b is in the new target; a-c should be dropped.
|
| 228 |
+
target = {("skill:a", "skill:b"): {"weight": 0.6}}
|
| 229 |
+
patch_graph(
|
| 230 |
+
prior,
|
| 231 |
+
current_node_info=current,
|
| 232 |
+
target_edges=target,
|
| 233 |
+
affected_node_ids={"skill:a"},
|
| 234 |
+
)
|
| 235 |
+
assert prior.has_edge("skill:a", "skill:b")
|
| 236 |
+
assert prior["skill:a"]["skill:b"]["weight"] == 0.6
|
| 237 |
+
assert not prior.has_edge("skill:a", "skill:c")
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
# ── Affected set semantics ───────────────────────────────────────────────────
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class TestAffectedSet:
|
| 244 |
+
def test_affected_union_new_nodes(self) -> None:
|
| 245 |
+
"""New nodes join the affected set implicitly — their edges must be evaluated."""
|
| 246 |
+
prior = _make_prior(
|
| 247 |
+
[("skill:a", _info("a"))],
|
| 248 |
+
[],
|
| 249 |
+
)
|
| 250 |
+
current = {
|
| 251 |
+
"skill:a": _info("a"),
|
| 252 |
+
"skill:b": _info("b"),
|
| 253 |
+
}
|
| 254 |
+
# Only b is new; caller did NOT include it in affected_node_ids.
|
| 255 |
+
target = {("skill:a", "skill:b"): {"weight": 0.9}}
|
| 256 |
+
patch_graph(
|
| 257 |
+
prior,
|
| 258 |
+
current_node_info=current,
|
| 259 |
+
target_edges=target,
|
| 260 |
+
affected_node_ids=set(), # empty
|
| 261 |
+
)
|
| 262 |
+
# Still materializes because new nodes are auto-affected.
|
| 263 |
+
assert prior.has_edge("skill:a", "skill:b")
|
| 264 |
+
|
| 265 |
+
def test_affected_union_removed_nodes(self) -> None:
|
| 266 |
+
"""Removed nodes' edges are dropped even when caller omits them from affected."""
|
| 267 |
+
prior = _make_prior(
|
| 268 |
+
[("skill:a", _info("a")), ("skill:gone", _info("gone"))],
|
| 269 |
+
[("skill:a", "skill:gone", {"weight": 0.5})],
|
| 270 |
+
)
|
| 271 |
+
patch_graph(
|
| 272 |
+
prior,
|
| 273 |
+
current_node_info={"skill:a": _info("a")},
|
| 274 |
+
target_edges={},
|
| 275 |
+
affected_node_ids=set(), # empty — but gone is removed
|
| 276 |
+
)
|
| 277 |
+
assert "skill:gone" not in prior
|
| 278 |
+
|
| 279 |
+
def test_affected_node_not_in_prior_tolerated(self) -> None:
|
| 280 |
+
"""Affected set may list a node not yet in prior — patch should not crash."""
|
| 281 |
+
prior = _make_prior()
|
| 282 |
+
patch_graph(
|
| 283 |
+
prior,
|
| 284 |
+
current_node_info={"skill:a": _info("a")},
|
| 285 |
+
target_edges={},
|
| 286 |
+
affected_node_ids={"skill:a", "skill:does-not-exist-yet"},
|
| 287 |
+
)
|
| 288 |
+
assert "skill:a" in prior
|
| 289 |
+
assert "skill:does-not-exist-yet" not in prior
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
# ── Return value ─────────────────────────────────────────────────────────────
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
class TestReturnValue:
|
| 296 |
+
def test_returns_same_instance(self) -> None:
|
| 297 |
+
"""Caller expects the same graph object they passed in."""
|
| 298 |
+
prior = _make_prior()
|
| 299 |
+
out = patch_graph(
|
| 300 |
+
prior,
|
| 301 |
+
current_node_info={},
|
| 302 |
+
target_edges={},
|
| 303 |
+
affected_node_ids=set(),
|
| 304 |
+
)
|
| 305 |
+
assert out is prior
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
# ── Integration: full cycle ─────────────────────────────────────────────────
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
class TestFullCycle:
|
| 312 |
+
def test_no_op_when_nothing_changes(self) -> None:
|
| 313 |
+
"""Idempotent: same inputs twice should leave the graph identical."""
|
| 314 |
+
prior = _make_prior(
|
| 315 |
+
[("skill:a", _info("a", tags=["py"])),
|
| 316 |
+
("skill:b", _info("b", tags=["py"]))],
|
| 317 |
+
[("skill:a", "skill:b", {"weight": 0.5})],
|
| 318 |
+
)
|
| 319 |
+
current = {
|
| 320 |
+
"skill:a": _info("a", tags=["py"]),
|
| 321 |
+
"skill:b": _info("b", tags=["py"]),
|
| 322 |
+
}
|
| 323 |
+
target = {("skill:a", "skill:b"): {"weight": 0.5}}
|
| 324 |
+
|
| 325 |
+
patch_graph(
|
| 326 |
+
prior,
|
| 327 |
+
current_node_info=current,
|
| 328 |
+
target_edges=target,
|
| 329 |
+
affected_node_ids=set(),
|
| 330 |
+
)
|
| 331 |
+
snapshot = (
|
| 332 |
+
set(prior.nodes()),
|
| 333 |
+
sorted(prior.edges()),
|
| 334 |
+
prior["skill:a"]["skill:b"]["weight"],
|
| 335 |
+
)
|
| 336 |
+
patch_graph(
|
| 337 |
+
prior,
|
| 338 |
+
current_node_info=current,
|
| 339 |
+
target_edges=target,
|
| 340 |
+
affected_node_ids=set(),
|
| 341 |
+
)
|
| 342 |
+
assert (
|
| 343 |
+
set(prior.nodes()),
|
| 344 |
+
sorted(prior.edges()),
|
| 345 |
+
prior["skill:a"]["skill:b"]["weight"],
|
| 346 |
+
) == snapshot
|
| 347 |
+
|
| 348 |
+
def test_prints_summary(self, capsys: pytest.CaptureFixture[str]) -> None:
|
| 349 |
+
"""Operational summary line must be emitted."""
|
| 350 |
+
prior = _make_prior()
|
| 351 |
+
patch_graph(
|
| 352 |
+
prior,
|
| 353 |
+
current_node_info={"skill:a": _info("a")},
|
| 354 |
+
target_edges={},
|
| 355 |
+
affected_node_ids=set(),
|
| 356 |
+
)
|
| 357 |
+
out = capsys.readouterr().out
|
| 358 |
+
assert "patch_graph:" in out
|
| 359 |
+
assert "added=1 nodes" in out
|
| 360 |
+
|
| 361 |
+
def test_combined_add_remove_update(self) -> None:
|
| 362 |
+
"""Stress: one node removed, one added, one updated, edges refreshed."""
|
| 363 |
+
prior = _make_prior(
|
| 364 |
+
[
|
| 365 |
+
("skill:a", _info("a", tags=["old"])),
|
| 366 |
+
("skill:b", _info("b")),
|
| 367 |
+
("skill:gone", _info("gone")),
|
| 368 |
+
],
|
| 369 |
+
[
|
| 370 |
+
("skill:a", "skill:b", {"weight": 0.3}),
|
| 371 |
+
("skill:a", "skill:gone", {"weight": 0.4}),
|
| 372 |
+
],
|
| 373 |
+
)
|
| 374 |
+
current = {
|
| 375 |
+
"skill:a": _info("a", tags=["fresh"]),
|
| 376 |
+
"skill:b": _info("b"),
|
| 377 |
+
"skill:new": _info("new"),
|
| 378 |
+
}
|
| 379 |
+
target = {
|
| 380 |
+
("skill:a", "skill:b"): {"weight": 0.7},
|
| 381 |
+
("skill:b", "skill:new"): {"weight": 0.6},
|
| 382 |
+
}
|
| 383 |
+
patch_graph(
|
| 384 |
+
prior,
|
| 385 |
+
current_node_info=current,
|
| 386 |
+
target_edges=target,
|
| 387 |
+
affected_node_ids={"skill:a"},
|
| 388 |
+
)
|
| 389 |
+
assert "skill:gone" not in prior
|
| 390 |
+
assert "skill:new" in prior
|
| 391 |
+
assert prior.nodes["skill:a"]["tags"] == ["fresh"]
|
| 392 |
+
assert prior["skill:a"]["skill:b"]["weight"] == 0.7
|
| 393 |
+
assert prior.has_edge("skill:b", "skill:new")
|
| 394 |
+
assert prior["skill:b"]["skill:new"]["weight"] == 0.6
|
src/tests/test_query.py
CHANGED
|
@@ -1,247 +1,247 @@
|
|
| 1 |
-
"""
|
| 2 |
-
test_query.py -- Tests for wiki_query (keyword search, tag filter, stats, related).
|
| 3 |
-
|
| 4 |
-
Every test builds its own minimal wiki structure via tmp_path so the real
|
| 5 |
-
~/.claude/skill-wiki is never touched.
|
| 6 |
-
"""
|
| 7 |
-
|
| 8 |
-
from __future__ import annotations
|
| 9 |
-
|
| 10 |
-
import sys
|
| 11 |
-
from pathlib import Path
|
| 12 |
-
|
| 13 |
-
# Ensure the project root is importable regardless of working directory.
|
| 14 |
-
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 15 |
-
|
| 16 |
-
from ctx.core.wiki import wiki_query as wq # noqa: E402
|
| 17 |
-
|
| 18 |
-
from ._wiki_helpers import make_entity_page, make_wiki # noqa: E402
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
def _write_entity_page(
|
| 22 |
-
wiki: Path,
|
| 23 |
-
relpath: str,
|
| 24 |
-
*,
|
| 25 |
-
title: str,
|
| 26 |
-
entity_type: str,
|
| 27 |
-
tags: list[str],
|
| 28 |
-
body: str,
|
| 29 |
-
description: str = "",
|
| 30 |
-
status: str = "installed",
|
| 31 |
-
) -> Path:
|
| 32 |
-
path = wiki / relpath
|
| 33 |
-
path.parent.mkdir(parents=True, exist_ok=True)
|
| 34 |
-
tags_str = "[" + ", ".join(tags) + "]"
|
| 35 |
-
path.write_text(
|
| 36 |
-
"\n".join([
|
| 37 |
-
"---",
|
| 38 |
-
f"title: {title}",
|
| 39 |
-
f"type: {entity_type}",
|
| 40 |
-
*([f"description: {description}"] if description else []),
|
| 41 |
-
f"tags: {tags_str}",
|
| 42 |
-
f"status: {status}",
|
| 43 |
-
"---",
|
| 44 |
-
"",
|
| 45 |
-
body,
|
| 46 |
-
]),
|
| 47 |
-
encoding="utf-8",
|
| 48 |
-
)
|
| 49 |
-
return path
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
class TestQueryKeywordMatch:
|
| 53 |
-
"""test_query_keyword_match -- searching 'docker' finds skills with docker in name/body."""
|
| 54 |
-
|
| 55 |
-
def test_query_keyword_match(self, tmp_path: Path) -> None:
|
| 56 |
-
wiki = make_wiki(tmp_path)
|
| 57 |
-
make_entity_page(wiki, "docker-compose-pro", ["docker"], body="Use docker-compose for local dev.")
|
| 58 |
-
# status="" ensures this page scores exactly 0 for a "docker" query (no installed bonus).
|
| 59 |
-
make_entity_page(wiki, "python-basics", ["python"], body="Learn Python fundamentals.", status="")
|
| 60 |
-
|
| 61 |
-
pages = wq.load_all_pages(wiki)
|
| 62 |
-
results = wq.search_by_query(pages, "docker")
|
| 63 |
-
|
| 64 |
-
names = [p.name for p in results]
|
| 65 |
-
assert "docker-compose-pro" in names, "docker skill must be returned for 'docker' query"
|
| 66 |
-
assert "python-basics" not in names, "unrelated skill must not appear"
|
| 67 |
-
|
| 68 |
-
def test_load_all_pages_includes_agents_and_sharded_mcps(self, tmp_path: Path) -> None:
|
| 69 |
-
wiki = make_wiki(tmp_path)
|
| 70 |
-
make_entity_page(wiki, "python-patterns", ["python"], body="Python skill.")
|
| 71 |
-
_write_entity_page(
|
| 72 |
-
wiki,
|
| 73 |
-
"entities/agents/code-reviewer.md",
|
| 74 |
-
title="Code Reviewer",
|
| 75 |
-
entity_type="agent",
|
| 76 |
-
tags=["review", "quality"],
|
| 77 |
-
body="Reviews code for defects.",
|
| 78 |
-
)
|
| 79 |
-
_write_entity_page(
|
| 80 |
-
wiki,
|
| 81 |
-
"entities/mcp-servers/f/filesystem.md",
|
| 82 |
-
title="Filesystem MCP",
|
| 83 |
-
entity_type="mcp-server",
|
| 84 |
-
tags=["filesystem", "io"],
|
| 85 |
-
body="Filesystem tools for local files.",
|
| 86 |
-
)
|
| 87 |
-
|
| 88 |
-
pages = wq.load_all_pages(wiki)
|
| 89 |
-
|
| 90 |
-
by_name = {p.name: p for p in pages}
|
| 91 |
-
assert by_name["python-patterns"].entity_type == "skill"
|
| 92 |
-
assert by_name["code-reviewer"].entity_type == "agent"
|
| 93 |
-
assert by_name["filesystem"].entity_type == "mcp-server"
|
| 94 |
-
assert by_name["filesystem"].wikilink == "[[entities/mcp-servers/f/filesystem]]"
|
| 95 |
-
|
| 96 |
-
def test_load_all_pages_validates_mcp_shards_and_slugs(self, tmp_path: Path) -> None:
|
| 97 |
-
wiki = make_wiki(tmp_path)
|
| 98 |
-
_write_entity_page(
|
| 99 |
-
wiki,
|
| 100 |
-
"entities/mcp-servers/0-9/1password.md",
|
| 101 |
-
title="1Password MCP",
|
| 102 |
-
entity_type="mcp-server",
|
| 103 |
-
tags=["secrets"],
|
| 104 |
-
body="Secret-management tools.",
|
| 105 |
-
)
|
| 106 |
-
_write_entity_page(
|
| 107 |
-
wiki,
|
| 108 |
-
"entities/mcp-servers/x/2wrong.md",
|
| 109 |
-
title="Mis-sharded MCP",
|
| 110 |
-
entity_type="mcp-server",
|
| 111 |
-
tags=["bad"],
|
| 112 |
-
body="Wrong shard.",
|
| 113 |
-
)
|
| 114 |
-
_write_entity_page(
|
| 115 |
-
wiki,
|
| 116 |
-
"entities/mcp-servers/f/Filesystem.md",
|
| 117 |
-
title="Uppercase MCP",
|
| 118 |
-
entity_type="mcp-server",
|
| 119 |
-
tags=["bad"],
|
| 120 |
-
body="Unsafe slug.",
|
| 121 |
-
)
|
| 122 |
-
|
| 123 |
-
pages = wq.load_all_pages(wiki)
|
| 124 |
-
|
| 125 |
-
by_name = {p.name: p for p in pages}
|
| 126 |
-
assert by_name["1password"].wikilink == "[[entities/mcp-servers/0-9/1password]]"
|
| 127 |
-
assert "2wrong" not in by_name
|
| 128 |
-
assert "Filesystem" not in by_name
|
| 129 |
-
|
| 130 |
-
def test_search_by_query_returns_agent_and_mcp_pages(self, tmp_path: Path) -> None:
|
| 131 |
-
wiki = make_wiki(tmp_path)
|
| 132 |
-
_write_entity_page(
|
| 133 |
-
wiki,
|
| 134 |
-
"entities/agents/code-reviewer.md",
|
| 135 |
-
title="Code Reviewer",
|
| 136 |
-
entity_type="agent",
|
| 137 |
-
tags=["review", "quality"],
|
| 138 |
-
body="Reviews code for defects.",
|
| 139 |
-
)
|
| 140 |
-
_write_entity_page(
|
| 141 |
-
wiki,
|
| 142 |
-
"entities/mcp-servers/f/filesystem.md",
|
| 143 |
-
title="Filesystem MCP",
|
| 144 |
-
entity_type="mcp-server",
|
| 145 |
-
tags=["filesystem", "io"],
|
| 146 |
-
body="Filesystem tools for local files.",
|
| 147 |
-
)
|
| 148 |
-
|
| 149 |
-
pages = wq.load_all_pages(wiki)
|
| 150 |
-
results = wq.search_by_query(pages, "filesystem review", top_n=10)
|
| 151 |
-
|
| 152 |
-
names = {p.name for p in results}
|
| 153 |
-
assert {"code-reviewer", "filesystem"} <= names
|
| 154 |
-
query_results = {r.name: r for r in map(wq._to_result, results)}
|
| 155 |
-
assert query_results["code-reviewer"].entity_type == "agent"
|
| 156 |
-
assert query_results["code-reviewer"].wikilink == "[[entities/agents/code-reviewer]]"
|
| 157 |
-
assert query_results["filesystem"].entity_type == "mcp-server"
|
| 158 |
-
assert query_results["filesystem"].wikilink == "[[entities/mcp-servers/f/filesystem]]"
|
| 159 |
-
|
| 160 |
-
def test_search_by_query_matches_title_and_description(self, tmp_path: Path) -> None:
|
| 161 |
-
wiki = make_wiki(tmp_path)
|
| 162 |
-
_write_entity_page(
|
| 163 |
-
wiki,
|
| 164 |
-
"entities/agents/sre-playbook.md",
|
| 165 |
-
title="Latency Debugger",
|
| 166 |
-
entity_type="agent",
|
| 167 |
-
description="Incident response runbook for production services.",
|
| 168 |
-
tags=[],
|
| 169 |
-
body="Operational checklist.",
|
| 170 |
-
status="",
|
| 171 |
-
)
|
| 172 |
-
|
| 173 |
-
pages = wq.load_all_pages(wiki)
|
| 174 |
-
title_hits = {p.name for p in wq.search_by_query(pages, "latency", top_n=10)}
|
| 175 |
-
description_hits = {p.name for p in wq.search_by_query(pages, "incident", top_n=10)}
|
| 176 |
-
|
| 177 |
-
assert "sre-playbook" in title_hits
|
| 178 |
-
assert "sre-playbook" in description_hits
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
class TestQueryTagFilter:
|
| 182 |
-
"""test_query_tag_filter -- --tag python returns only python-tagged skills."""
|
| 183 |
-
|
| 184 |
-
def test_query_tag_filter(self, tmp_path: Path) -> None:
|
| 185 |
-
wiki = make_wiki(tmp_path)
|
| 186 |
-
make_entity_page(wiki, "fastapi-service", ["python", "fastapi"], body="FastAPI patterns.")
|
| 187 |
-
make_entity_page(wiki, "docker-network", ["docker"], body="Docker networking tips.")
|
| 188 |
-
make_entity_page(wiki, "pytest-patterns", ["python", "testing"], body="Pytest best practices.")
|
| 189 |
-
|
| 190 |
-
pages = wq.load_all_pages(wiki)
|
| 191 |
-
results = wq.filter_by_tag(pages, "python")
|
| 192 |
-
|
| 193 |
-
names = {p.name for p in results}
|
| 194 |
-
assert "fastapi-service" in names
|
| 195 |
-
assert "pytest-patterns" in names
|
| 196 |
-
assert "docker-network" not in names, "non-python skill must be excluded"
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
class TestQueryStats:
|
| 200 |
-
"""test_query_stats -- compute_stats returns total_entity_pages, top_tags, with_pipeline."""
|
| 201 |
-
|
| 202 |
-
def test_query_stats(self, tmp_path: Path) -> None:
|
| 203 |
-
wiki = make_wiki(tmp_path)
|
| 204 |
-
make_entity_page(wiki, "skill-a", ["python"], body="A skill.")
|
| 205 |
-
make_entity_page(wiki, "skill-b", ["python", "fastapi"], body="B skill.", has_pipeline=True)
|
| 206 |
-
make_entity_page(wiki, "skill-c", ["docker"], body="C skill.")
|
| 207 |
-
# Create the converted dir so has_pipeline resolves
|
| 208 |
-
(wiki / "converted" / "skill-b").mkdir(parents=True)
|
| 209 |
-
|
| 210 |
-
pages = wq.load_all_pages(wiki)
|
| 211 |
-
stats = wq.compute_stats(wiki, pages)
|
| 212 |
-
|
| 213 |
-
assert stats["total_entity_pages"] == 3
|
| 214 |
-
assert stats["with_pipeline"] == 1
|
| 215 |
-
tag_keys = [t for t, _ in stats["top_tags"]]
|
| 216 |
-
assert "python" in tag_keys
|
| 217 |
-
assert "docker" in tag_keys
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
class TestQueryRelated:
|
| 221 |
-
"""test_query_related -- --related fastapi-pro finds python-tagged skills."""
|
| 222 |
-
|
| 223 |
-
def test_query_related(self, tmp_path: Path) -> None:
|
| 224 |
-
wiki = make_wiki(tmp_path)
|
| 225 |
-
make_entity_page(wiki, "fastapi-pro", ["python", "fastapi"], body="The target skill.")
|
| 226 |
-
make_entity_page(wiki, "pydantic-models", ["python", "fastapi"], body="Pydantic usage.")
|
| 227 |
-
make_entity_page(wiki, "docker-compose-pro", ["docker"], body="Docker only.")
|
| 228 |
-
|
| 229 |
-
pages = wq.load_all_pages(wiki)
|
| 230 |
-
related = wq.find_related(pages, "fastapi-pro")
|
| 231 |
-
|
| 232 |
-
names = [p.name for p in related]
|
| 233 |
-
assert "pydantic-models" in names, "pydantic-models shares tags so must appear as related"
|
| 234 |
-
assert "docker-compose-pro" not in names, "no shared tags with fastapi-pro"
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
class TestQueryNoResults:
|
| 238 |
-
"""test_query_no_results -- searching 'xyznonexistent' returns empty list."""
|
| 239 |
-
|
| 240 |
-
def test_query_no_results(self, tmp_path: Path) -> None:
|
| 241 |
-
wiki = make_wiki(tmp_path)
|
| 242 |
-
make_entity_page(wiki, "python-basics", ["python"], body="Learn Python.")
|
| 243 |
-
|
| 244 |
-
pages = wq.load_all_pages(wiki)
|
| 245 |
-
results = wq.search_by_query(pages, "xyznonexistent")
|
| 246 |
-
|
| 247 |
-
assert results == [], f"Expected no results, got {[p.name for p in results]}"
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_query.py -- Tests for wiki_query (keyword search, tag filter, stats, related).
|
| 3 |
+
|
| 4 |
+
Every test builds its own minimal wiki structure via tmp_path so the real
|
| 5 |
+
~/.claude/skill-wiki is never touched.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import sys
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
# Ensure the project root is importable regardless of working directory.
|
| 14 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 15 |
+
|
| 16 |
+
from ctx.core.wiki import wiki_query as wq # noqa: E402
|
| 17 |
+
|
| 18 |
+
from ._wiki_helpers import make_entity_page, make_wiki # noqa: E402
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _write_entity_page(
|
| 22 |
+
wiki: Path,
|
| 23 |
+
relpath: str,
|
| 24 |
+
*,
|
| 25 |
+
title: str,
|
| 26 |
+
entity_type: str,
|
| 27 |
+
tags: list[str],
|
| 28 |
+
body: str,
|
| 29 |
+
description: str = "",
|
| 30 |
+
status: str = "installed",
|
| 31 |
+
) -> Path:
|
| 32 |
+
path = wiki / relpath
|
| 33 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 34 |
+
tags_str = "[" + ", ".join(tags) + "]"
|
| 35 |
+
path.write_text(
|
| 36 |
+
"\n".join([
|
| 37 |
+
"---",
|
| 38 |
+
f"title: {title}",
|
| 39 |
+
f"type: {entity_type}",
|
| 40 |
+
*([f"description: {description}"] if description else []),
|
| 41 |
+
f"tags: {tags_str}",
|
| 42 |
+
f"status: {status}",
|
| 43 |
+
"---",
|
| 44 |
+
"",
|
| 45 |
+
body,
|
| 46 |
+
]),
|
| 47 |
+
encoding="utf-8",
|
| 48 |
+
)
|
| 49 |
+
return path
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class TestQueryKeywordMatch:
|
| 53 |
+
"""test_query_keyword_match -- searching 'docker' finds skills with docker in name/body."""
|
| 54 |
+
|
| 55 |
+
def test_query_keyword_match(self, tmp_path: Path) -> None:
|
| 56 |
+
wiki = make_wiki(tmp_path)
|
| 57 |
+
make_entity_page(wiki, "docker-compose-pro", ["docker"], body="Use docker-compose for local dev.")
|
| 58 |
+
# status="" ensures this page scores exactly 0 for a "docker" query (no installed bonus).
|
| 59 |
+
make_entity_page(wiki, "python-basics", ["python"], body="Learn Python fundamentals.", status="")
|
| 60 |
+
|
| 61 |
+
pages = wq.load_all_pages(wiki)
|
| 62 |
+
results = wq.search_by_query(pages, "docker")
|
| 63 |
+
|
| 64 |
+
names = [p.name for p in results]
|
| 65 |
+
assert "docker-compose-pro" in names, "docker skill must be returned for 'docker' query"
|
| 66 |
+
assert "python-basics" not in names, "unrelated skill must not appear"
|
| 67 |
+
|
| 68 |
+
def test_load_all_pages_includes_agents_and_sharded_mcps(self, tmp_path: Path) -> None:
|
| 69 |
+
wiki = make_wiki(tmp_path)
|
| 70 |
+
make_entity_page(wiki, "python-patterns", ["python"], body="Python skill.")
|
| 71 |
+
_write_entity_page(
|
| 72 |
+
wiki,
|
| 73 |
+
"entities/agents/code-reviewer.md",
|
| 74 |
+
title="Code Reviewer",
|
| 75 |
+
entity_type="agent",
|
| 76 |
+
tags=["review", "quality"],
|
| 77 |
+
body="Reviews code for defects.",
|
| 78 |
+
)
|
| 79 |
+
_write_entity_page(
|
| 80 |
+
wiki,
|
| 81 |
+
"entities/mcp-servers/f/filesystem.md",
|
| 82 |
+
title="Filesystem MCP",
|
| 83 |
+
entity_type="mcp-server",
|
| 84 |
+
tags=["filesystem", "io"],
|
| 85 |
+
body="Filesystem tools for local files.",
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
pages = wq.load_all_pages(wiki)
|
| 89 |
+
|
| 90 |
+
by_name = {p.name: p for p in pages}
|
| 91 |
+
assert by_name["python-patterns"].entity_type == "skill"
|
| 92 |
+
assert by_name["code-reviewer"].entity_type == "agent"
|
| 93 |
+
assert by_name["filesystem"].entity_type == "mcp-server"
|
| 94 |
+
assert by_name["filesystem"].wikilink == "[[entities/mcp-servers/f/filesystem]]"
|
| 95 |
+
|
| 96 |
+
def test_load_all_pages_validates_mcp_shards_and_slugs(self, tmp_path: Path) -> None:
|
| 97 |
+
wiki = make_wiki(tmp_path)
|
| 98 |
+
_write_entity_page(
|
| 99 |
+
wiki,
|
| 100 |
+
"entities/mcp-servers/0-9/1password.md",
|
| 101 |
+
title="1Password MCP",
|
| 102 |
+
entity_type="mcp-server",
|
| 103 |
+
tags=["secrets"],
|
| 104 |
+
body="Secret-management tools.",
|
| 105 |
+
)
|
| 106 |
+
_write_entity_page(
|
| 107 |
+
wiki,
|
| 108 |
+
"entities/mcp-servers/x/2wrong.md",
|
| 109 |
+
title="Mis-sharded MCP",
|
| 110 |
+
entity_type="mcp-server",
|
| 111 |
+
tags=["bad"],
|
| 112 |
+
body="Wrong shard.",
|
| 113 |
+
)
|
| 114 |
+
_write_entity_page(
|
| 115 |
+
wiki,
|
| 116 |
+
"entities/mcp-servers/f/Filesystem.md",
|
| 117 |
+
title="Uppercase MCP",
|
| 118 |
+
entity_type="mcp-server",
|
| 119 |
+
tags=["bad"],
|
| 120 |
+
body="Unsafe slug.",
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
pages = wq.load_all_pages(wiki)
|
| 124 |
+
|
| 125 |
+
by_name = {p.name: p for p in pages}
|
| 126 |
+
assert by_name["1password"].wikilink == "[[entities/mcp-servers/0-9/1password]]"
|
| 127 |
+
assert "2wrong" not in by_name
|
| 128 |
+
assert "Filesystem" not in by_name
|
| 129 |
+
|
| 130 |
+
def test_search_by_query_returns_agent_and_mcp_pages(self, tmp_path: Path) -> None:
|
| 131 |
+
wiki = make_wiki(tmp_path)
|
| 132 |
+
_write_entity_page(
|
| 133 |
+
wiki,
|
| 134 |
+
"entities/agents/code-reviewer.md",
|
| 135 |
+
title="Code Reviewer",
|
| 136 |
+
entity_type="agent",
|
| 137 |
+
tags=["review", "quality"],
|
| 138 |
+
body="Reviews code for defects.",
|
| 139 |
+
)
|
| 140 |
+
_write_entity_page(
|
| 141 |
+
wiki,
|
| 142 |
+
"entities/mcp-servers/f/filesystem.md",
|
| 143 |
+
title="Filesystem MCP",
|
| 144 |
+
entity_type="mcp-server",
|
| 145 |
+
tags=["filesystem", "io"],
|
| 146 |
+
body="Filesystem tools for local files.",
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
pages = wq.load_all_pages(wiki)
|
| 150 |
+
results = wq.search_by_query(pages, "filesystem review", top_n=10)
|
| 151 |
+
|
| 152 |
+
names = {p.name for p in results}
|
| 153 |
+
assert {"code-reviewer", "filesystem"} <= names
|
| 154 |
+
query_results = {r.name: r for r in map(wq._to_result, results)}
|
| 155 |
+
assert query_results["code-reviewer"].entity_type == "agent"
|
| 156 |
+
assert query_results["code-reviewer"].wikilink == "[[entities/agents/code-reviewer]]"
|
| 157 |
+
assert query_results["filesystem"].entity_type == "mcp-server"
|
| 158 |
+
assert query_results["filesystem"].wikilink == "[[entities/mcp-servers/f/filesystem]]"
|
| 159 |
+
|
| 160 |
+
def test_search_by_query_matches_title_and_description(self, tmp_path: Path) -> None:
|
| 161 |
+
wiki = make_wiki(tmp_path)
|
| 162 |
+
_write_entity_page(
|
| 163 |
+
wiki,
|
| 164 |
+
"entities/agents/sre-playbook.md",
|
| 165 |
+
title="Latency Debugger",
|
| 166 |
+
entity_type="agent",
|
| 167 |
+
description="Incident response runbook for production services.",
|
| 168 |
+
tags=[],
|
| 169 |
+
body="Operational checklist.",
|
| 170 |
+
status="",
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
pages = wq.load_all_pages(wiki)
|
| 174 |
+
title_hits = {p.name for p in wq.search_by_query(pages, "latency", top_n=10)}
|
| 175 |
+
description_hits = {p.name for p in wq.search_by_query(pages, "incident", top_n=10)}
|
| 176 |
+
|
| 177 |
+
assert "sre-playbook" in title_hits
|
| 178 |
+
assert "sre-playbook" in description_hits
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class TestQueryTagFilter:
|
| 182 |
+
"""test_query_tag_filter -- --tag python returns only python-tagged skills."""
|
| 183 |
+
|
| 184 |
+
def test_query_tag_filter(self, tmp_path: Path) -> None:
|
| 185 |
+
wiki = make_wiki(tmp_path)
|
| 186 |
+
make_entity_page(wiki, "fastapi-service", ["python", "fastapi"], body="FastAPI patterns.")
|
| 187 |
+
make_entity_page(wiki, "docker-network", ["docker"], body="Docker networking tips.")
|
| 188 |
+
make_entity_page(wiki, "pytest-patterns", ["python", "testing"], body="Pytest best practices.")
|
| 189 |
+
|
| 190 |
+
pages = wq.load_all_pages(wiki)
|
| 191 |
+
results = wq.filter_by_tag(pages, "python")
|
| 192 |
+
|
| 193 |
+
names = {p.name for p in results}
|
| 194 |
+
assert "fastapi-service" in names
|
| 195 |
+
assert "pytest-patterns" in names
|
| 196 |
+
assert "docker-network" not in names, "non-python skill must be excluded"
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
class TestQueryStats:
|
| 200 |
+
"""test_query_stats -- compute_stats returns total_entity_pages, top_tags, with_pipeline."""
|
| 201 |
+
|
| 202 |
+
def test_query_stats(self, tmp_path: Path) -> None:
|
| 203 |
+
wiki = make_wiki(tmp_path)
|
| 204 |
+
make_entity_page(wiki, "skill-a", ["python"], body="A skill.")
|
| 205 |
+
make_entity_page(wiki, "skill-b", ["python", "fastapi"], body="B skill.", has_pipeline=True)
|
| 206 |
+
make_entity_page(wiki, "skill-c", ["docker"], body="C skill.")
|
| 207 |
+
# Create the converted dir so has_pipeline resolves
|
| 208 |
+
(wiki / "converted" / "skill-b").mkdir(parents=True)
|
| 209 |
+
|
| 210 |
+
pages = wq.load_all_pages(wiki)
|
| 211 |
+
stats = wq.compute_stats(wiki, pages)
|
| 212 |
+
|
| 213 |
+
assert stats["total_entity_pages"] == 3
|
| 214 |
+
assert stats["with_pipeline"] == 1
|
| 215 |
+
tag_keys = [t for t, _ in stats["top_tags"]]
|
| 216 |
+
assert "python" in tag_keys
|
| 217 |
+
assert "docker" in tag_keys
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class TestQueryRelated:
|
| 221 |
+
"""test_query_related -- --related fastapi-pro finds python-tagged skills."""
|
| 222 |
+
|
| 223 |
+
def test_query_related(self, tmp_path: Path) -> None:
|
| 224 |
+
wiki = make_wiki(tmp_path)
|
| 225 |
+
make_entity_page(wiki, "fastapi-pro", ["python", "fastapi"], body="The target skill.")
|
| 226 |
+
make_entity_page(wiki, "pydantic-models", ["python", "fastapi"], body="Pydantic usage.")
|
| 227 |
+
make_entity_page(wiki, "docker-compose-pro", ["docker"], body="Docker only.")
|
| 228 |
+
|
| 229 |
+
pages = wq.load_all_pages(wiki)
|
| 230 |
+
related = wq.find_related(pages, "fastapi-pro")
|
| 231 |
+
|
| 232 |
+
names = [p.name for p in related]
|
| 233 |
+
assert "pydantic-models" in names, "pydantic-models shares tags so must appear as related"
|
| 234 |
+
assert "docker-compose-pro" not in names, "no shared tags with fastapi-pro"
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
class TestQueryNoResults:
|
| 238 |
+
"""test_query_no_results -- searching 'xyznonexistent' returns empty list."""
|
| 239 |
+
|
| 240 |
+
def test_query_no_results(self, tmp_path: Path) -> None:
|
| 241 |
+
wiki = make_wiki(tmp_path)
|
| 242 |
+
make_entity_page(wiki, "python-basics", ["python"], body="Learn Python.")
|
| 243 |
+
|
| 244 |
+
pages = wq.load_all_pages(wiki)
|
| 245 |
+
results = wq.search_by_query(pages, "xyznonexistent")
|
| 246 |
+
|
| 247 |
+
assert results == [], f"Expected no results, got {[p.name for p in results]}"
|
src/tests/test_resolve_skills.py
CHANGED
|
@@ -1,758 +1,758 @@
|
|
| 1 |
-
"""
|
| 2 |
-
tests/test_resolve_skills.py -- pytest suite for resolve_skills module.
|
| 3 |
-
|
| 4 |
-
Covers:
|
| 5 |
-
- discover_available_skills (happy path, empty dir, malformed frontmatter)
|
| 6 |
-
- read_wiki_overrides (happy path, missing dir, bad use_count, boolean flags)
|
| 7 |
-
- resolve (basic load, conflict resolution, always/never_load, cap)
|
| 8 |
-
- read_intent_signals (happy path, missing file, bad JSON lines, wrong date)
|
| 9 |
-
- apply_intent_boosts (boost in needed, suggestion when available only)
|
| 10 |
-
- main() (via subprocess with --profile arg)
|
| 11 |
-
"""
|
| 12 |
-
|
| 13 |
-
import json
|
| 14 |
-
import sys
|
| 15 |
-
from pathlib import Path
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
sys.path.insert(0, str(Path(__file__).parents[1]))
|
| 19 |
-
|
| 20 |
-
from ctx.core.resolve.resolve_skills import (
|
| 21 |
-
apply_intent_boosts,
|
| 22 |
-
discover_available_skills,
|
| 23 |
-
read_intent_signals,
|
| 24 |
-
read_wiki_overrides,
|
| 25 |
-
resolve,
|
| 26 |
-
)
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
# ---------------------------------------------------------------------------
|
| 30 |
-
# Helpers
|
| 31 |
-
# ---------------------------------------------------------------------------
|
| 32 |
-
|
| 33 |
-
def _make_skill(skills_dir: Path, name: str, frontmatter: str = "") -> Path:
|
| 34 |
-
"""Write a minimal SKILL.md under skills_dir/<name>/."""
|
| 35 |
-
d = skills_dir / name
|
| 36 |
-
d.mkdir(parents=True, exist_ok=True)
|
| 37 |
-
content = f"---\n{frontmatter}\n---\n# {name}\n" if frontmatter else f"# {name}\n"
|
| 38 |
-
p = d / "SKILL.md"
|
| 39 |
-
p.write_text(content, encoding="utf-8")
|
| 40 |
-
return p
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
def _minimal_profile(frameworks=None, languages=None) -> dict:
|
| 44 |
-
return {
|
| 45 |
-
"repo_path": "/tmp/repo",
|
| 46 |
-
"languages": languages or [],
|
| 47 |
-
"frameworks": frameworks or [],
|
| 48 |
-
"infrastructure": [],
|
| 49 |
-
"data_stores": [],
|
| 50 |
-
"testing": [],
|
| 51 |
-
"ai_tooling": [],
|
| 52 |
-
"build_system": [],
|
| 53 |
-
"docs": [],
|
| 54 |
-
}
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
def _detection(name: str, confidence: float = 0.9) -> dict:
|
| 58 |
-
return {"name": name, "confidence": confidence, "evidence": ["file.py"]}
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
def _resolve_without_graph(
|
| 62 |
-
profile: dict,
|
| 63 |
-
available: dict,
|
| 64 |
-
overrides: dict,
|
| 65 |
-
**kwargs,
|
| 66 |
-
) -> dict:
|
| 67 |
-
return resolve(profile, available, overrides, enable_graph=False, **kwargs)
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
# ---------------------------------------------------------------------------
|
| 71 |
-
# discover_available_skills
|
| 72 |
-
# ---------------------------------------------------------------------------
|
| 73 |
-
|
| 74 |
-
class TestDiscoverAvailableSkills:
|
| 75 |
-
def test_happy_path_single_skill(self, tmp_path):
|
| 76 |
-
_make_skill(tmp_path, "react", "tags: [javascript]\nversion: 1.0")
|
| 77 |
-
skills = discover_available_skills(str(tmp_path))
|
| 78 |
-
assert "react" in skills
|
| 79 |
-
assert skills["react"]["name"] == "react"
|
| 80 |
-
assert "path" in skills["react"]
|
| 81 |
-
|
| 82 |
-
def test_multiple_skills(self, tmp_path):
|
| 83 |
-
for name in ("react", "fastapi", "docker"):
|
| 84 |
-
_make_skill(tmp_path, name, f"tags: [{name}]")
|
| 85 |
-
skills = discover_available_skills(str(tmp_path))
|
| 86 |
-
assert set(skills.keys()) == {"react", "fastapi", "docker"}
|
| 87 |
-
|
| 88 |
-
def test_missing_directory_returns_empty(self, tmp_path):
|
| 89 |
-
skills = discover_available_skills(str(tmp_path / "nonexistent"))
|
| 90 |
-
assert skills == {}
|
| 91 |
-
|
| 92 |
-
def test_empty_skills_dir_returns_empty(self, tmp_path):
|
| 93 |
-
(tmp_path / "skills").mkdir()
|
| 94 |
-
skills = discover_available_skills(str(tmp_path / "skills"))
|
| 95 |
-
assert skills == {}
|
| 96 |
-
|
| 97 |
-
def test_malformed_frontmatter_still_registers_skill(self, tmp_path, capsys):
|
| 98 |
-
"""A skill with unreadable frontmatter should still be indexed by name."""
|
| 99 |
-
d = tmp_path / "broken-skill"
|
| 100 |
-
d.mkdir()
|
| 101 |
-
(d / "SKILL.md").write_text("not---valid---frontmatter", encoding="utf-8")
|
| 102 |
-
skills = discover_available_skills(str(tmp_path))
|
| 103 |
-
# Should still contain the skill (minimal record)
|
| 104 |
-
assert "broken-skill" in skills
|
| 105 |
-
|
| 106 |
-
def test_nested_skill_discovered(self, tmp_path):
|
| 107 |
-
nested = tmp_path / "category" / "deep-skill"
|
| 108 |
-
nested.mkdir(parents=True)
|
| 109 |
-
(nested / "SKILL.md").write_text("# deep\n", encoding="utf-8")
|
| 110 |
-
skills = discover_available_skills(str(tmp_path))
|
| 111 |
-
assert "deep-skill" in skills
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
# ---------------------------------------------------------------------------
|
| 115 |
-
# read_wiki_overrides
|
| 116 |
-
# ---------------------------------------------------------------------------
|
| 117 |
-
|
| 118 |
-
class TestReadWikiOverrides:
|
| 119 |
-
def _make_override_page(self, wiki: Path, name: str, fields: dict) -> None:
|
| 120 |
-
entities = wiki / "entities" / "skills"
|
| 121 |
-
entities.mkdir(parents=True, exist_ok=True)
|
| 122 |
-
fm_lines = "\n".join(f"{k}: {v}" for k, v in fields.items())
|
| 123 |
-
page = f"---\n{fm_lines}\n---\n# {name}\n"
|
| 124 |
-
(entities / f"{name}.md").write_text(page, encoding="utf-8")
|
| 125 |
-
|
| 126 |
-
def test_always_load_true(self, tmp_path):
|
| 127 |
-
self._make_override_page(tmp_path, "react", {"always_load": "true", "use_count": "3"})
|
| 128 |
-
overrides = read_wiki_overrides(str(tmp_path))
|
| 129 |
-
assert overrides["react"]["always_load"] is True
|
| 130 |
-
assert overrides["react"]["use_count"] == 3
|
| 131 |
-
|
| 132 |
-
def test_never_load_true(self, tmp_path):
|
| 133 |
-
self._make_override_page(tmp_path, "legacy", {"never_load": "true", "use_count": "0"})
|
| 134 |
-
overrides = read_wiki_overrides(str(tmp_path))
|
| 135 |
-
assert overrides["legacy"]["never_load"] is True
|
| 136 |
-
|
| 137 |
-
def test_defaults_when_fields_absent(self, tmp_path):
|
| 138 |
-
# Provide at least one field so _parse_fm returns non-empty and the
|
| 139 |
-
# entry isn't skipped by the `if not meta: continue` guard.
|
| 140 |
-
self._make_override_page(tmp_path, "plain", {"status": "installed"})
|
| 141 |
-
overrides = read_wiki_overrides(str(tmp_path))
|
| 142 |
-
assert overrides["plain"]["always_load"] is False
|
| 143 |
-
assert overrides["plain"]["never_load"] is False
|
| 144 |
-
assert overrides["plain"]["use_count"] == 0
|
| 145 |
-
|
| 146 |
-
def test_missing_entities_dir_returns_empty(self, tmp_path):
|
| 147 |
-
overrides = read_wiki_overrides(str(tmp_path))
|
| 148 |
-
assert overrides == {}
|
| 149 |
-
|
| 150 |
-
def test_bad_use_count_defaults_to_zero(self, tmp_path):
|
| 151 |
-
self._make_override_page(tmp_path, "bad", {"use_count": "not-a-number"})
|
| 152 |
-
# Should not raise; int(str("not-a-number")) will raise, so it goes to except
|
| 153 |
-
overrides = read_wiki_overrides(str(tmp_path))
|
| 154 |
-
# Page with parse error is skipped (continue in except)
|
| 155 |
-
assert "bad" not in overrides
|
| 156 |
-
|
| 157 |
-
def test_page_without_frontmatter_skipped(self, tmp_path):
|
| 158 |
-
entities = tmp_path / "entities" / "skills"
|
| 159 |
-
entities.mkdir(parents=True)
|
| 160 |
-
(entities / "plain.md").write_text("# plain\nno frontmatter here", encoding="utf-8")
|
| 161 |
-
overrides = read_wiki_overrides(str(tmp_path))
|
| 162 |
-
assert "plain" not in overrides
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
# ---------------------------------------------------------------------------
|
| 166 |
-
# resolve
|
| 167 |
-
# ---------------------------------------------------------------------------
|
| 168 |
-
|
| 169 |
-
class TestResolve:
|
| 170 |
-
def test_graph_can_be_disabled_for_deterministic_unit_resolution(
|
| 171 |
-
self, tmp_path, monkeypatch
|
| 172 |
-
):
|
| 173 |
-
from ctx.core.resolve import resolve_skills # noqa: PLC0415
|
| 174 |
-
|
| 175 |
-
def fail_if_loaded():
|
| 176 |
-
raise AssertionError("unit resolver tests must not load the live graph")
|
| 177 |
-
|
| 178 |
-
monkeypatch.setattr(resolve_skills, "_load_graph", fail_if_loaded)
|
| 179 |
-
available = {"react": {"path": str(tmp_path / "react/SKILL.md"), "name": "react"}}
|
| 180 |
-
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 181 |
-
|
| 182 |
-
manifest = _resolve_without_graph(profile, available, {})
|
| 183 |
-
|
| 184 |
-
assert "react" in [e["skill"] for e in manifest["load"]]
|
| 185 |
-
assert not any("graph walk skipped" in w for w in manifest["warnings"])
|
| 186 |
-
|
| 187 |
-
def test_basic_load_known_skill(self, tmp_path):
|
| 188 |
-
available = {"react": {"path": str(tmp_path / "react/SKILL.md"), "name": "react"}}
|
| 189 |
-
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 190 |
-
manifest = _resolve_without_graph(profile, available, {})
|
| 191 |
-
loaded_names = [e["skill"] for e in manifest["load"]]
|
| 192 |
-
assert "react" in loaded_names
|
| 193 |
-
|
| 194 |
-
def test_skill_not_available_goes_to_suggestions(self, tmp_path):
|
| 195 |
-
available = {} # react not installed
|
| 196 |
-
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 197 |
-
manifest = _resolve_without_graph(profile, available, {})
|
| 198 |
-
suggestion_skills = [s["skill"] for s in manifest["suggestions"]]
|
| 199 |
-
assert "react" in suggestion_skills
|
| 200 |
-
# The unavailable react skill must NOT be in load. Graph-matched
|
| 201 |
-
# agents (e.g. react-specialist found via the live knowledge graph)
|
| 202 |
-
# may legitimately appear in load — the assertion targets the
|
| 203 |
-
# specific skill, not the entire load list, so this test stays
|
| 204 |
-
# robust against richer graph-driven recommendations.
|
| 205 |
-
loaded_skills = [
|
| 206 |
-
e.get("skill") for e in manifest["load"]
|
| 207 |
-
if e.get("entity_type", "skill") == "skill"
|
| 208 |
-
]
|
| 209 |
-
assert "react" not in loaded_skills
|
| 210 |
-
|
| 211 |
-
def test_always_load_override_adds_skill(self, tmp_path):
|
| 212 |
-
available = {"docker": {"path": str(tmp_path / "docker/SKILL.md"), "name": "docker"}}
|
| 213 |
-
overrides = {"docker": {"always_load": True, "never_load": False, "use_count": 0, "last_used": "", "status": "installed"}}
|
| 214 |
-
profile = _minimal_profile() # no detection for docker
|
| 215 |
-
manifest = _resolve_without_graph(profile, available, overrides)
|
| 216 |
-
loaded_names = [e["skill"] for e in manifest["load"]]
|
| 217 |
-
assert "docker" in loaded_names
|
| 218 |
-
|
| 219 |
-
def test_never_load_override_removes_skill(self, tmp_path):
|
| 220 |
-
available = {"react": {"path": str(tmp_path / "react/SKILL.md"), "name": "react"}}
|
| 221 |
-
overrides = {"react": {"always_load": False, "never_load": True, "use_count": 0, "last_used": "", "status": "installed"}}
|
| 222 |
-
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 223 |
-
manifest = _resolve_without_graph(profile, available, overrides)
|
| 224 |
-
loaded_names = [e["skill"] for e in manifest["load"]]
|
| 225 |
-
assert "react" not in loaded_names
|
| 226 |
-
|
| 227 |
-
def test_conflict_resolution_keeps_higher_priority(self, tmp_path):
|
| 228 |
-
available = {
|
| 229 |
-
"fastapi": {"path": str(tmp_path / "fastapi/SKILL.md"), "name": "fastapi"},
|
| 230 |
-
"flask": {"path": str(tmp_path / "flask/SKILL.md"), "name": "flask"},
|
| 231 |
-
}
|
| 232 |
-
profile = _minimal_profile(frameworks=[
|
| 233 |
-
_detection("fastapi", confidence=0.95),
|
| 234 |
-
_detection("flask", confidence=0.6),
|
| 235 |
-
])
|
| 236 |
-
manifest = _resolve_without_graph(profile, available, {})
|
| 237 |
-
loaded_names = [e["skill"] for e in manifest["load"]]
|
| 238 |
-
# fastapi has higher base priority (8) and higher confidence boost
|
| 239 |
-
assert "fastapi" in loaded_names
|
| 240 |
-
assert "flask" not in loaded_names
|
| 241 |
-
assert any("Conflict" in w for w in manifest["warnings"])
|
| 242 |
-
|
| 243 |
-
def test_max_skills_cap(self, tmp_path):
|
| 244 |
-
# Create 20 available skills each mapped from detections
|
| 245 |
-
skills_with_map = ["react", "docker", "fastapi", "django", "flask",
|
| 246 |
-
"pytest", "jest", "langchain", "nextjs", "vue"]
|
| 247 |
-
available = {n: {"path": str(tmp_path / n / "SKILL.md"), "name": n} for n in skills_with_map}
|
| 248 |
-
profile = _minimal_profile(frameworks=[_detection(n, 0.9) for n in skills_with_map])
|
| 249 |
-
manifest = _resolve_without_graph(profile, available, {}, max_skills=3)
|
| 250 |
-
# At most 3 skill-mapped items (plus meta skills if available)
|
| 251 |
-
non_meta = [e for e in manifest["load"] if e["skill"] not in ("skill-router", "file-reading")]
|
| 252 |
-
assert len(non_meta) <= 3
|
| 253 |
-
assert any("Capped" in w for w in manifest["warnings"])
|
| 254 |
-
|
| 255 |
-
def test_meta_skills_added_if_available(self, tmp_path):
|
| 256 |
-
available = {"skill-router": {"path": str(tmp_path / "skill-router/SKILL.md"), "name": "skill-router"}}
|
| 257 |
-
profile = _minimal_profile()
|
| 258 |
-
manifest = _resolve_without_graph(profile, available, {})
|
| 259 |
-
loaded_names = [e["skill"] for e in manifest["load"]]
|
| 260 |
-
assert "skill-router" in loaded_names
|
| 261 |
-
|
| 262 |
-
def test_unloaded_skills_in_unload_list(self, tmp_path):
|
| 263 |
-
available = {
|
| 264 |
-
"react": {"path": str(tmp_path / "react/SKILL.md"), "name": "react"},
|
| 265 |
-
"docker": {"path": str(tmp_path / "docker/SKILL.md"), "name": "docker"},
|
| 266 |
-
}
|
| 267 |
-
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 268 |
-
manifest = _resolve_without_graph(profile, available, {})
|
| 269 |
-
unload_names = [e["skill"] for e in manifest["unload"]]
|
| 270 |
-
assert "docker" in unload_names
|
| 271 |
-
|
| 272 |
-
def test_empty_profile_no_crash(self):
|
| 273 |
-
manifest = _resolve_without_graph(_minimal_profile(), {}, {})
|
| 274 |
-
assert manifest["load"] == []
|
| 275 |
-
assert "generated_at" in manifest
|
| 276 |
-
|
| 277 |
-
def test_high_confidence_boost_applied(self, tmp_path):
|
| 278 |
-
"""Skills with confidence >=0.9 should get priority +10."""
|
| 279 |
-
available = {"react": {"path": str(tmp_path / "react/SKILL.md"), "name": "react"}}
|
| 280 |
-
profile = _minimal_profile(frameworks=[_detection("react", confidence=0.95)])
|
| 281 |
-
manifest = _resolve_without_graph(profile, available, {})
|
| 282 |
-
entry = next(e for e in manifest["load"] if e["skill"] == "react")
|
| 283 |
-
# PRIORITY_BASE["react"] = 7, +10 for confidence, +0 no use_count
|
| 284 |
-
assert entry["priority"] >= 17
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
class TestResolveMcpRecommendations:
|
| 288 |
-
"""Phase 5 regression: graph-walk hits with type=='mcp-server' land
|
| 289 |
-
in manifest['mcp_servers'], NOT manifest['load'] (the skill bucket).
|
| 290 |
-
"""
|
| 291 |
-
|
| 292 |
-
def _fake_graph(self, monkeypatch):
|
| 293 |
-
"""Make resolve() think the graph is available and non-empty."""
|
| 294 |
-
from ctx.core.resolve import resolve_skills # noqa: PLC0415
|
| 295 |
-
|
| 296 |
-
class _FakeGraph:
|
| 297 |
-
def number_of_nodes(self) -> int:
|
| 298 |
-
return 1
|
| 299 |
-
|
| 300 |
-
monkeypatch.setattr(
|
| 301 |
-
resolve_skills, "_load_graph", lambda: _FakeGraph()
|
| 302 |
-
)
|
| 303 |
-
monkeypatch.setattr(resolve_skills, "_GRAPH_AVAILABLE", True)
|
| 304 |
-
|
| 305 |
-
def test_mcp_graph_hit_lands_in_mcp_servers_not_load(
|
| 306 |
-
self, tmp_path, monkeypatch
|
| 307 |
-
):
|
| 308 |
-
from ctx.core.resolve import resolve_skills # noqa: PLC0415
|
| 309 |
-
self._fake_graph(monkeypatch)
|
| 310 |
-
|
| 311 |
-
# Synthetic graph hit: an MCP-type neighbor with score above the
|
| 312 |
-
# 1.5 noise floor.
|
| 313 |
-
def fake_resolve_by_seeds(graph, seeds, **kwargs):
|
| 314 |
-
return [
|
| 315 |
-
{
|
| 316 |
-
"name": "github-mcp-server",
|
| 317 |
-
"type": "mcp-server",
|
| 318 |
-
"score": 3.0,
|
| 319 |
-
"shared_tags": ["_t:github"],
|
| 320 |
-
"via": ["react"],
|
| 321 |
-
},
|
| 322 |
-
]
|
| 323 |
-
|
| 324 |
-
monkeypatch.setattr(
|
| 325 |
-
resolve_skills, "_resolve_by_seeds", fake_resolve_by_seeds
|
| 326 |
-
)
|
| 327 |
-
|
| 328 |
-
available = {"react": {"path": str(tmp_path / "react/SKILL.md"), "name": "react"}}
|
| 329 |
-
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 330 |
-
manifest = resolve(profile, available, {})
|
| 331 |
-
|
| 332 |
-
mcp_names = [m["name"] for m in manifest["mcp_servers"]]
|
| 333 |
-
load_names = [e["skill"] for e in manifest["load"]]
|
| 334 |
-
assert "github-mcp-server" in mcp_names, (
|
| 335 |
-
f"MCP should appear in mcp_servers bucket; got {manifest['mcp_servers']}"
|
| 336 |
-
)
|
| 337 |
-
assert "github-mcp-server" not in load_names, (
|
| 338 |
-
"MCP must NOT land in manifest['load'] — that's the skill-loader bucket"
|
| 339 |
-
)
|
| 340 |
-
|
| 341 |
-
def test_mcp_entry_has_reason_score_and_shared_tags(
|
| 342 |
-
self, tmp_path, monkeypatch
|
| 343 |
-
):
|
| 344 |
-
from ctx.core.resolve import resolve_skills # noqa: PLC0415
|
| 345 |
-
self._fake_graph(monkeypatch)
|
| 346 |
-
|
| 347 |
-
def fake_resolve_by_seeds(graph, seeds, **kwargs):
|
| 348 |
-
return [
|
| 349 |
-
{
|
| 350 |
-
"name": "fetch-mcp",
|
| 351 |
-
"type": "mcp-server",
|
| 352 |
-
"score": 2.5,
|
| 353 |
-
"shared_tags": ["_t:fetch", "http"],
|
| 354 |
-
"via": ["django"],
|
| 355 |
-
},
|
| 356 |
-
]
|
| 357 |
-
|
| 358 |
-
monkeypatch.setattr(
|
| 359 |
-
resolve_skills, "_resolve_by_seeds", fake_resolve_by_seeds
|
| 360 |
-
)
|
| 361 |
-
|
| 362 |
-
available = {"django": {"path": str(tmp_path / "django/SKILL.md"), "name": "django"}}
|
| 363 |
-
profile = _minimal_profile(frameworks=[_detection("django")])
|
| 364 |
-
manifest = resolve(profile, available, {})
|
| 365 |
-
|
| 366 |
-
assert len(manifest["mcp_servers"]) == 1
|
| 367 |
-
entry = manifest["mcp_servers"][0]
|
| 368 |
-
assert entry["name"] == "fetch-mcp"
|
| 369 |
-
assert entry["score"] == 2.5
|
| 370 |
-
assert "graph neighbor of django" in entry["reason"]
|
| 371 |
-
assert "_t:fetch" in entry["shared_tags"]
|
| 372 |
-
|
| 373 |
-
def test_mcp_deduped_when_same_name_hit_twice(
|
| 374 |
-
self, tmp_path, monkeypatch
|
| 375 |
-
):
|
| 376 |
-
from ctx.core.resolve import resolve_skills # noqa: PLC0415
|
| 377 |
-
self._fake_graph(monkeypatch)
|
| 378 |
-
|
| 379 |
-
def fake_resolve_by_seeds(graph, seeds, **kwargs):
|
| 380 |
-
return [
|
| 381 |
-
{"name": "duped-mcp", "type": "mcp-server", "score": 2.0,
|
| 382 |
-
"shared_tags": [], "via": ["a"]},
|
| 383 |
-
{"name": "duped-mcp", "type": "mcp-server", "score": 1.8,
|
| 384 |
-
"shared_tags": [], "via": ["b"]},
|
| 385 |
-
]
|
| 386 |
-
|
| 387 |
-
monkeypatch.setattr(
|
| 388 |
-
resolve_skills, "_resolve_by_seeds", fake_resolve_by_seeds
|
| 389 |
-
)
|
| 390 |
-
|
| 391 |
-
available = {"react": {"path": str(tmp_path / "react/SKILL.md"), "name": "react"}}
|
| 392 |
-
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 393 |
-
manifest = resolve(profile, available, {})
|
| 394 |
-
|
| 395 |
-
assert sum(1 for m in manifest["mcp_servers"] if m["name"] == "duped-mcp") == 1
|
| 396 |
-
|
| 397 |
-
def test_mcp_below_noise_floor_dropped(
|
| 398 |
-
self, tmp_path, monkeypatch
|
| 399 |
-
):
|
| 400 |
-
from ctx.core.resolve import resolve_skills # noqa: PLC0415
|
| 401 |
-
self._fake_graph(monkeypatch)
|
| 402 |
-
|
| 403 |
-
def fake_resolve_by_seeds(graph, seeds, **kwargs):
|
| 404 |
-
# Post-P2.5 the resolver uses normalized_score (percentile
|
| 405 |
-
# in [0,1]) against the 0.20 MCP floor. A value of 0.1
|
| 406 |
-
# sits below the floor so the hit must be dropped.
|
| 407 |
-
return [
|
| 408 |
-
{"name": "weak-mcp", "type": "mcp-server",
|
| 409 |
-
"score": 0.8, "normalized_score": 0.10,
|
| 410 |
-
"shared_tags": [], "via": ["a"]},
|
| 411 |
-
]
|
| 412 |
-
|
| 413 |
-
monkeypatch.setattr(
|
| 414 |
-
resolve_skills, "_resolve_by_seeds", fake_resolve_by_seeds
|
| 415 |
-
)
|
| 416 |
-
|
| 417 |
-
available = {"react": {"path": str(tmp_path / "react/SKILL.md"), "name": "react"}}
|
| 418 |
-
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 419 |
-
manifest = resolve(profile, available, {})
|
| 420 |
-
|
| 421 |
-
assert manifest["mcp_servers"] == []
|
| 422 |
-
|
| 423 |
-
def test_skill_hits_still_route_to_load(
|
| 424 |
-
self, tmp_path, monkeypatch
|
| 425 |
-
):
|
| 426 |
-
# Regression: mixing mcp-server hits and skill hits must not
|
| 427 |
-
# break the existing skill path.
|
| 428 |
-
from ctx.core.resolve import resolve_skills # noqa: PLC0415
|
| 429 |
-
self._fake_graph(monkeypatch)
|
| 430 |
-
|
| 431 |
-
def fake_resolve_by_seeds(graph, seeds, **kwargs):
|
| 432 |
-
return [
|
| 433 |
-
{"name": "pytest-something", "type": "skill", "score": 3.0,
|
| 434 |
-
"shared_tags": [], "via": ["django"]},
|
| 435 |
-
{"name": "fetch-mcp", "type": "mcp-server", "score": 2.0,
|
| 436 |
-
"shared_tags": [], "via": ["django"]},
|
| 437 |
-
]
|
| 438 |
-
|
| 439 |
-
monkeypatch.setattr(
|
| 440 |
-
resolve_skills, "_resolve_by_seeds", fake_resolve_by_seeds
|
| 441 |
-
)
|
| 442 |
-
|
| 443 |
-
available = {
|
| 444 |
-
"django": {"path": str(tmp_path / "django/SKILL.md"), "name": "django"},
|
| 445 |
-
"pytest-something": {
|
| 446 |
-
"path": str(tmp_path / "pytest-something/SKILL.md"),
|
| 447 |
-
"name": "pytest-something",
|
| 448 |
-
},
|
| 449 |
-
}
|
| 450 |
-
profile = _minimal_profile(frameworks=[_detection("django")])
|
| 451 |
-
manifest = resolve(profile, available, {})
|
| 452 |
-
|
| 453 |
-
mcp_names = [m["name"] for m in manifest["mcp_servers"]]
|
| 454 |
-
load_names = [e["skill"] for e in manifest["load"]]
|
| 455 |
-
assert "fetch-mcp" in mcp_names
|
| 456 |
-
assert "pytest-something" in load_names
|
| 457 |
-
|
| 458 |
-
def test_agent_graph_hit_lands_in_load_without_installed_skill(
|
| 459 |
-
self, tmp_path, monkeypatch
|
| 460 |
-
):
|
| 461 |
-
from ctx.core.resolve import resolve_skills # noqa: PLC0415
|
| 462 |
-
self._fake_graph(monkeypatch)
|
| 463 |
-
|
| 464 |
-
def fake_resolve_by_seeds(graph, seeds, **kwargs):
|
| 465 |
-
return [
|
| 466 |
-
{
|
| 467 |
-
"name": "code-reviewer",
|
| 468 |
-
"type": "agent",
|
| 469 |
-
"score": 2.0,
|
| 470 |
-
"normalized_score": 0.8,
|
| 471 |
-
"shared_tags": ["review"],
|
| 472 |
-
"via": ["django"],
|
| 473 |
-
},
|
| 474 |
-
]
|
| 475 |
-
|
| 476 |
-
monkeypatch.setattr(
|
| 477 |
-
resolve_skills, "_resolve_by_seeds", fake_resolve_by_seeds
|
| 478 |
-
)
|
| 479 |
-
|
| 480 |
-
available = {"django": {"path": str(tmp_path / "django/SKILL.md"), "name": "django"}}
|
| 481 |
-
profile = _minimal_profile(frameworks=[_detection("django")])
|
| 482 |
-
manifest = resolve(profile, available, {})
|
| 483 |
-
|
| 484 |
-
agents = [
|
| 485 |
-
e for e in manifest["load"]
|
| 486 |
-
if e.get("entity_type") == "agent"
|
| 487 |
-
]
|
| 488 |
-
assert [e["skill"] for e in agents] == ["code-reviewer"]
|
| 489 |
-
assert agents[0]["path"] == "/mnt/agents/unknown/code-reviewer.md"
|
| 490 |
-
assert not any("code-reviewer needed but not installed" in w for w in manifest["warnings"])
|
| 491 |
-
|
| 492 |
-
def test_real_graph_walk_routes_cross_type_hits(
|
| 493 |
-
self, tmp_path, monkeypatch
|
| 494 |
-
):
|
| 495 |
-
import networkx as nx
|
| 496 |
-
from ctx.core.resolve import resolve_skills # noqa: PLC0415
|
| 497 |
-
|
| 498 |
-
G = nx.Graph()
|
| 499 |
-
G.add_node("skill:react", label="react", type="skill")
|
| 500 |
-
G.add_node("skill:pytest-something", label="pytest-something", type="skill")
|
| 501 |
-
G.add_node("agent:code-reviewer", label="code-reviewer", type="agent")
|
| 502 |
-
G.add_node("mcp-server:github-mcp-server", label="github-mcp-server", type="mcp-server")
|
| 503 |
-
G.add_edge(
|
| 504 |
-
"skill:react",
|
| 505 |
-
"skill:pytest-something",
|
| 506 |
-
weight=0.85,
|
| 507 |
-
shared_tags=["test"],
|
| 508 |
-
)
|
| 509 |
-
G.add_edge(
|
| 510 |
-
"skill:react",
|
| 511 |
-
"agent:code-reviewer",
|
| 512 |
-
weight=0.90,
|
| 513 |
-
shared_tags=["review"],
|
| 514 |
-
)
|
| 515 |
-
G.add_edge(
|
| 516 |
-
"skill:react",
|
| 517 |
-
"mcp-server:github-mcp-server",
|
| 518 |
-
weight=0.95,
|
| 519 |
-
shared_tags=["github"],
|
| 520 |
-
)
|
| 521 |
-
monkeypatch.setattr(resolve_skills, "_load_graph", lambda: G)
|
| 522 |
-
monkeypatch.setattr(resolve_skills, "_GRAPH_AVAILABLE", True)
|
| 523 |
-
|
| 524 |
-
available = {
|
| 525 |
-
"react": {"path": str(tmp_path / "react/SKILL.md"), "name": "react"},
|
| 526 |
-
"pytest-something": {
|
| 527 |
-
"path": str(tmp_path / "pytest-something/SKILL.md"),
|
| 528 |
-
"name": "pytest-something",
|
| 529 |
-
},
|
| 530 |
-
}
|
| 531 |
-
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 532 |
-
|
| 533 |
-
manifest = resolve(profile, available, {})
|
| 534 |
-
|
| 535 |
-
load_by_name = {entry["skill"]: entry for entry in manifest["load"]}
|
| 536 |
-
assert load_by_name["pytest-something"]["entity_type"] == "skill"
|
| 537 |
-
assert load_by_name["code-reviewer"]["entity_type"] == "agent"
|
| 538 |
-
assert load_by_name["code-reviewer"]["path"] == "/mnt/agents/unknown/code-reviewer.md"
|
| 539 |
-
assert [entry["name"] for entry in manifest["mcp_servers"]] == [
|
| 540 |
-
"github-mcp-server",
|
| 541 |
-
]
|
| 542 |
-
assert manifest["mcp_servers"][0]["shared_tags"] == ["github"]
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
# ---------------------------------------------------------------------------
|
| 546 |
-
# read_intent_signals
|
| 547 |
-
# ---------------------------------------------------------------------------
|
| 548 |
-
|
| 549 |
-
class TestReadIntentSignals:
|
| 550 |
-
def _write_log(self, path: Path, entries: list[dict]) -> None:
|
| 551 |
-
lines = [json.dumps(e) for e in entries]
|
| 552 |
-
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
| 553 |
-
|
| 554 |
-
def test_returns_empty_when_file_missing(self, tmp_path):
|
| 555 |
-
signals = read_intent_signals(str(tmp_path / "no-such.jsonl"))
|
| 556 |
-
assert signals == {}
|
| 557 |
-
|
| 558 |
-
def test_counts_todays_signals(self, tmp_path, monkeypatch):
|
| 559 |
-
from datetime import datetime, timezone
|
| 560 |
-
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
| 561 |
-
log = tmp_path / "intent.jsonl"
|
| 562 |
-
self._write_log(log, [
|
| 563 |
-
{"date": today, "signals": ["react", "docker"]},
|
| 564 |
-
{"date": today, "signals": ["react"]},
|
| 565 |
-
])
|
| 566 |
-
signals = read_intent_signals(str(log))
|
| 567 |
-
assert signals["react"] == 2
|
| 568 |
-
assert signals["docker"] == 1
|
| 569 |
-
|
| 570 |
-
def test_ignores_other_dates(self, tmp_path):
|
| 571 |
-
log = tmp_path / "intent.jsonl"
|
| 572 |
-
self._write_log(log, [
|
| 573 |
-
{"date": "2020-01-01", "signals": ["react"]},
|
| 574 |
-
])
|
| 575 |
-
signals = read_intent_signals(str(log))
|
| 576 |
-
# Today's date != 2020-01-01, so nothing counted
|
| 577 |
-
assert "react" not in signals
|
| 578 |
-
|
| 579 |
-
def test_skips_bad_json_lines(self, tmp_path):
|
| 580 |
-
from datetime import datetime, timezone
|
| 581 |
-
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
| 582 |
-
log = tmp_path / "intent.jsonl"
|
| 583 |
-
log.write_text(
|
| 584 |
-
'not json\n'
|
| 585 |
-
f'{json.dumps({"date": today, "signals": ["fastapi"]})}\n',
|
| 586 |
-
encoding="utf-8",
|
| 587 |
-
)
|
| 588 |
-
signals = read_intent_signals(str(log))
|
| 589 |
-
assert signals.get("fastapi") == 1
|
| 590 |
-
|
| 591 |
-
def test_empty_file_returns_empty(self, tmp_path):
|
| 592 |
-
log = tmp_path / "intent.jsonl"
|
| 593 |
-
log.write_text("", encoding="utf-8")
|
| 594 |
-
signals = read_intent_signals(str(log))
|
| 595 |
-
assert signals == {}
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
# ---------------------------------------------------------------------------
|
| 599 |
-
# apply_intent_boosts
|
| 600 |
-
# ---------------------------------------------------------------------------
|
| 601 |
-
|
| 602 |
-
class TestApplyIntentBoosts:
|
| 603 |
-
def _make_manifest(self) -> dict:
|
| 604 |
-
return {"suggestions": [], "warnings": []}
|
| 605 |
-
|
| 606 |
-
def test_boosts_existing_skill_in_needed(self):
|
| 607 |
-
needed = {"react": {"priority": 10, "reason": "detected", "confidence": 0.9}}
|
| 608 |
-
available = {}
|
| 609 |
-
manifest = self._make_manifest()
|
| 610 |
-
apply_intent_boosts(needed, {"react": 2}, available, manifest)
|
| 611 |
-
# boost = 5 * min(2, 3) = 10
|
| 612 |
-
assert needed["react"]["priority"] == 20
|
| 613 |
-
|
| 614 |
-
def test_boost_capped_at_three_signals(self):
|
| 615 |
-
needed = {"react": {"priority": 10, "reason": "detected", "confidence": 0.9}}
|
| 616 |
-
manifest = self._make_manifest()
|
| 617 |
-
apply_intent_boosts(needed, {"react": 10}, {}, manifest)
|
| 618 |
-
# boost = 5 * min(10, 3) = 15
|
| 619 |
-
assert needed["react"]["priority"] == 25
|
| 620 |
-
|
| 621 |
-
def test_available_not_in_needed_becomes_suggestion(self, tmp_path):
|
| 622 |
-
needed = {}
|
| 623 |
-
available = {"docker": {"path": str(tmp_path / "docker/SKILL.md")}}
|
| 624 |
-
manifest = self._make_manifest()
|
| 625 |
-
apply_intent_boosts(needed, {"docker": 1}, available, manifest)
|
| 626 |
-
suggestion_skills = [s["skill"] for s in manifest["suggestions"]]
|
| 627 |
-
assert "docker" in suggestion_skills
|
| 628 |
-
|
| 629 |
-
def test_unknown_signal_no_crash(self):
|
| 630 |
-
needed = {}
|
| 631 |
-
manifest = self._make_manifest()
|
| 632 |
-
apply_intent_boosts(needed, {"totally-unknown-signal": 5}, {}, manifest)
|
| 633 |
-
assert manifest["suggestions"] == []
|
| 634 |
-
|
| 635 |
-
def test_empty_signals_no_change(self):
|
| 636 |
-
needed = {"react": {"priority": 10, "reason": "x", "confidence": 0.9}}
|
| 637 |
-
manifest = self._make_manifest()
|
| 638 |
-
apply_intent_boosts(needed, {}, {}, manifest)
|
| 639 |
-
assert needed["react"]["priority"] == 10
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
# ─────────────────────────────────────────────────────────────────────
|
| 643 |
-
# P2.5 normalised noise-floor regression
|
| 644 |
-
# ─────────────────────────────────────────────────────────────────────
|
| 645 |
-
#
|
| 646 |
-
# Pre-P2.5 the floors were absolute (1.5 / 1.0) and calibrated against
|
| 647 |
-
# the v0.6 integer-weight graph. On v0.7's blended float-weight graph
|
| 648 |
-
# a single edge is <=1.0, so absolute 1.5 dropped ALL single-seed
|
| 649 |
-
# hits on any sparse/test graph — the suggestion arm silently produced
|
| 650 |
-
# nothing. Post-fix the floors are percentile thresholds in [0,1],
|
| 651 |
-
# scale-invariant.
|
| 652 |
-
|
| 653 |
-
class TestNoiseFloorNormalized:
|
| 654 |
-
|
| 655 |
-
def _fake_graph(self, monkeypatch):
|
| 656 |
-
import networkx as nx
|
| 657 |
-
from ctx.core.resolve import resolve_skills
|
| 658 |
-
|
| 659 |
-
def fake_load_graph(_=None):
|
| 660 |
-
G = nx.Graph()
|
| 661 |
-
G.add_node("skill:foo", type="skill", label="foo")
|
| 662 |
-
return G
|
| 663 |
-
|
| 664 |
-
monkeypatch.setattr(resolve_skills, "_load_graph", fake_load_graph)
|
| 665 |
-
|
| 666 |
-
def test_normalized_score_at_top_survives(self, tmp_path, monkeypatch):
|
| 667 |
-
"""A hit with normalized_score=1.0 (the top of its ranking)
|
| 668 |
-
always passes the floor — otherwise the top recommendation
|
| 669 |
-
gets silently dropped on small fixtures."""
|
| 670 |
-
from ctx.core.resolve import resolve_skills
|
| 671 |
-
from ctx.core.resolve.resolve_skills import resolve
|
| 672 |
-
self._fake_graph(monkeypatch)
|
| 673 |
-
|
| 674 |
-
def fake_hits(*a, **kw):
|
| 675 |
-
return [
|
| 676 |
-
{"name": "top-skill", "type": "skill",
|
| 677 |
-
"score": 1.23, "normalized_score": 1.0,
|
| 678 |
-
"shared_tags": ["x"], "via": ["react"]},
|
| 679 |
-
]
|
| 680 |
-
|
| 681 |
-
monkeypatch.setattr(resolve_skills, "_resolve_by_seeds", fake_hits)
|
| 682 |
-
available = {"react": {"path": str(tmp_path / "r/SKILL.md"), "name": "react"},
|
| 683 |
-
"top-skill": {"path": str(tmp_path / "t/SKILL.md"), "name": "top-skill"}}
|
| 684 |
-
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 685 |
-
manifest = resolve(profile, available, {})
|
| 686 |
-
assert "top-skill" in {e["skill"] for e in manifest["load"]}
|
| 687 |
-
|
| 688 |
-
def test_skill_below_0_3_dropped(self, tmp_path, monkeypatch):
|
| 689 |
-
"""Skill hits with normalized_score < 0.30 don't make the cut."""
|
| 690 |
-
from ctx.core.resolve import resolve_skills
|
| 691 |
-
from ctx.core.resolve.resolve_skills import resolve
|
| 692 |
-
self._fake_graph(monkeypatch)
|
| 693 |
-
|
| 694 |
-
def fake_hits(*a, **kw):
|
| 695 |
-
return [
|
| 696 |
-
{"name": "noisy", "type": "skill",
|
| 697 |
-
"score": 0.12, "normalized_score": 0.10,
|
| 698 |
-
"shared_tags": [], "via": ["react"]},
|
| 699 |
-
]
|
| 700 |
-
monkeypatch.setattr(resolve_skills, "_resolve_by_seeds", fake_hits)
|
| 701 |
-
available = {"react": {"path": str(tmp_path / "r/SKILL.md"), "name": "react"},
|
| 702 |
-
"noisy": {"path": str(tmp_path / "n/SKILL.md"), "name": "noisy"}}
|
| 703 |
-
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 704 |
-
manifest = resolve(profile, available, {})
|
| 705 |
-
assert "noisy" not in {e["skill"] for e in manifest["load"]}
|
| 706 |
-
|
| 707 |
-
def test_mcp_floor_is_lower_than_skill_floor(self, tmp_path, monkeypatch):
|
| 708 |
-
"""MCPs are historically sparser; a hit with normalized_score=0.25
|
| 709 |
-
passes the MCP floor (0.20) but NOT the skill floor (0.30).
|
| 710 |
-
Pinning this asymmetry so a future 'unify the floors' refactor
|
| 711 |
-
wipes out MCP recommendations without CI noticing."""
|
| 712 |
-
from ctx.core.resolve import resolve_skills
|
| 713 |
-
from ctx.core.resolve.resolve_skills import resolve
|
| 714 |
-
self._fake_graph(monkeypatch)
|
| 715 |
-
|
| 716 |
-
def fake_hits(*a, **kw):
|
| 717 |
-
return [
|
| 718 |
-
{"name": "mid-mcp", "type": "mcp-server",
|
| 719 |
-
"score": 0.3, "normalized_score": 0.25,
|
| 720 |
-
"shared_tags": ["x"], "via": ["react"]},
|
| 721 |
-
{"name": "mid-skill", "type": "skill",
|
| 722 |
-
"score": 0.3, "normalized_score": 0.25,
|
| 723 |
-
"shared_tags": ["x"], "via": ["react"]},
|
| 724 |
-
]
|
| 725 |
-
monkeypatch.setattr(resolve_skills, "_resolve_by_seeds", fake_hits)
|
| 726 |
-
available = {
|
| 727 |
-
"react": {"path": str(tmp_path / "r/SKILL.md"), "name": "react"},
|
| 728 |
-
"mid-skill": {"path": str(tmp_path / "s/SKILL.md"), "name": "mid-skill"},
|
| 729 |
-
}
|
| 730 |
-
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 731 |
-
manifest = resolve(profile, available, {})
|
| 732 |
-
# Skill below 0.30 → dropped.
|
| 733 |
-
assert "mid-skill" not in {e["skill"] for e in manifest["load"]}
|
| 734 |
-
# MCP above 0.20 → kept.
|
| 735 |
-
mcp_names = {m["name"] for m in manifest["mcp_servers"]}
|
| 736 |
-
assert "mid-mcp" in mcp_names
|
| 737 |
-
|
| 738 |
-
def test_backward_compat_raw_score_fallback(self, tmp_path, monkeypatch):
|
| 739 |
-
"""An older resolver output without normalized_score must
|
| 740 |
-
still work via raw-score fallback, so a stale cached graph
|
| 741 |
-
doesn't silently return [] after the P2.5 upgrade."""
|
| 742 |
-
from ctx.core.resolve import resolve_skills
|
| 743 |
-
from ctx.core.resolve.resolve_skills import resolve
|
| 744 |
-
self._fake_graph(monkeypatch)
|
| 745 |
-
|
| 746 |
-
def fake_hits(*a, **kw):
|
| 747 |
-
# No ``normalized_score`` key — pre-P2.5 shape.
|
| 748 |
-
return [
|
| 749 |
-
{"name": "legacy-hit", "type": "skill",
|
| 750 |
-
"score": 2.5, "shared_tags": ["x"], "via": ["react"]},
|
| 751 |
-
]
|
| 752 |
-
monkeypatch.setattr(resolve_skills, "_resolve_by_seeds", fake_hits)
|
| 753 |
-
available = {"react": {"path": str(tmp_path / "r/SKILL.md"), "name": "react"},
|
| 754 |
-
"legacy-hit": {"path": str(tmp_path / "l/SKILL.md"), "name": "legacy-hit"}}
|
| 755 |
-
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 756 |
-
manifest = resolve(profile, available, {})
|
| 757 |
-
# Raw score 2.5 >> any old skill floor so legacy behaviour survives.
|
| 758 |
-
assert "legacy-hit" in {e["skill"] for e in manifest["load"]}
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
tests/test_resolve_skills.py -- pytest suite for resolve_skills module.
|
| 3 |
+
|
| 4 |
+
Covers:
|
| 5 |
+
- discover_available_skills (happy path, empty dir, malformed frontmatter)
|
| 6 |
+
- read_wiki_overrides (happy path, missing dir, bad use_count, boolean flags)
|
| 7 |
+
- resolve (basic load, conflict resolution, always/never_load, cap)
|
| 8 |
+
- read_intent_signals (happy path, missing file, bad JSON lines, wrong date)
|
| 9 |
+
- apply_intent_boosts (boost in needed, suggestion when available only)
|
| 10 |
+
- main() (via subprocess with --profile arg)
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import json
|
| 14 |
+
import sys
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
sys.path.insert(0, str(Path(__file__).parents[1]))
|
| 19 |
+
|
| 20 |
+
from ctx.core.resolve.resolve_skills import (
|
| 21 |
+
apply_intent_boosts,
|
| 22 |
+
discover_available_skills,
|
| 23 |
+
read_intent_signals,
|
| 24 |
+
read_wiki_overrides,
|
| 25 |
+
resolve,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# ---------------------------------------------------------------------------
|
| 30 |
+
# Helpers
|
| 31 |
+
# ---------------------------------------------------------------------------
|
| 32 |
+
|
| 33 |
+
def _make_skill(skills_dir: Path, name: str, frontmatter: str = "") -> Path:
|
| 34 |
+
"""Write a minimal SKILL.md under skills_dir/<name>/."""
|
| 35 |
+
d = skills_dir / name
|
| 36 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 37 |
+
content = f"---\n{frontmatter}\n---\n# {name}\n" if frontmatter else f"# {name}\n"
|
| 38 |
+
p = d / "SKILL.md"
|
| 39 |
+
p.write_text(content, encoding="utf-8")
|
| 40 |
+
return p
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _minimal_profile(frameworks=None, languages=None) -> dict:
|
| 44 |
+
return {
|
| 45 |
+
"repo_path": "/tmp/repo",
|
| 46 |
+
"languages": languages or [],
|
| 47 |
+
"frameworks": frameworks or [],
|
| 48 |
+
"infrastructure": [],
|
| 49 |
+
"data_stores": [],
|
| 50 |
+
"testing": [],
|
| 51 |
+
"ai_tooling": [],
|
| 52 |
+
"build_system": [],
|
| 53 |
+
"docs": [],
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _detection(name: str, confidence: float = 0.9) -> dict:
|
| 58 |
+
return {"name": name, "confidence": confidence, "evidence": ["file.py"]}
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _resolve_without_graph(
|
| 62 |
+
profile: dict,
|
| 63 |
+
available: dict,
|
| 64 |
+
overrides: dict,
|
| 65 |
+
**kwargs,
|
| 66 |
+
) -> dict:
|
| 67 |
+
return resolve(profile, available, overrides, enable_graph=False, **kwargs)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# ---------------------------------------------------------------------------
|
| 71 |
+
# discover_available_skills
|
| 72 |
+
# ---------------------------------------------------------------------------
|
| 73 |
+
|
| 74 |
+
class TestDiscoverAvailableSkills:
|
| 75 |
+
def test_happy_path_single_skill(self, tmp_path):
|
| 76 |
+
_make_skill(tmp_path, "react", "tags: [javascript]\nversion: 1.0")
|
| 77 |
+
skills = discover_available_skills(str(tmp_path))
|
| 78 |
+
assert "react" in skills
|
| 79 |
+
assert skills["react"]["name"] == "react"
|
| 80 |
+
assert "path" in skills["react"]
|
| 81 |
+
|
| 82 |
+
def test_multiple_skills(self, tmp_path):
|
| 83 |
+
for name in ("react", "fastapi", "docker"):
|
| 84 |
+
_make_skill(tmp_path, name, f"tags: [{name}]")
|
| 85 |
+
skills = discover_available_skills(str(tmp_path))
|
| 86 |
+
assert set(skills.keys()) == {"react", "fastapi", "docker"}
|
| 87 |
+
|
| 88 |
+
def test_missing_directory_returns_empty(self, tmp_path):
|
| 89 |
+
skills = discover_available_skills(str(tmp_path / "nonexistent"))
|
| 90 |
+
assert skills == {}
|
| 91 |
+
|
| 92 |
+
def test_empty_skills_dir_returns_empty(self, tmp_path):
|
| 93 |
+
(tmp_path / "skills").mkdir()
|
| 94 |
+
skills = discover_available_skills(str(tmp_path / "skills"))
|
| 95 |
+
assert skills == {}
|
| 96 |
+
|
| 97 |
+
def test_malformed_frontmatter_still_registers_skill(self, tmp_path, capsys):
|
| 98 |
+
"""A skill with unreadable frontmatter should still be indexed by name."""
|
| 99 |
+
d = tmp_path / "broken-skill"
|
| 100 |
+
d.mkdir()
|
| 101 |
+
(d / "SKILL.md").write_text("not---valid---frontmatter", encoding="utf-8")
|
| 102 |
+
skills = discover_available_skills(str(tmp_path))
|
| 103 |
+
# Should still contain the skill (minimal record)
|
| 104 |
+
assert "broken-skill" in skills
|
| 105 |
+
|
| 106 |
+
def test_nested_skill_discovered(self, tmp_path):
|
| 107 |
+
nested = tmp_path / "category" / "deep-skill"
|
| 108 |
+
nested.mkdir(parents=True)
|
| 109 |
+
(nested / "SKILL.md").write_text("# deep\n", encoding="utf-8")
|
| 110 |
+
skills = discover_available_skills(str(tmp_path))
|
| 111 |
+
assert "deep-skill" in skills
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
# ---------------------------------------------------------------------------
|
| 115 |
+
# read_wiki_overrides
|
| 116 |
+
# ---------------------------------------------------------------------------
|
| 117 |
+
|
| 118 |
+
class TestReadWikiOverrides:
|
| 119 |
+
def _make_override_page(self, wiki: Path, name: str, fields: dict) -> None:
|
| 120 |
+
entities = wiki / "entities" / "skills"
|
| 121 |
+
entities.mkdir(parents=True, exist_ok=True)
|
| 122 |
+
fm_lines = "\n".join(f"{k}: {v}" for k, v in fields.items())
|
| 123 |
+
page = f"---\n{fm_lines}\n---\n# {name}\n"
|
| 124 |
+
(entities / f"{name}.md").write_text(page, encoding="utf-8")
|
| 125 |
+
|
| 126 |
+
def test_always_load_true(self, tmp_path):
|
| 127 |
+
self._make_override_page(tmp_path, "react", {"always_load": "true", "use_count": "3"})
|
| 128 |
+
overrides = read_wiki_overrides(str(tmp_path))
|
| 129 |
+
assert overrides["react"]["always_load"] is True
|
| 130 |
+
assert overrides["react"]["use_count"] == 3
|
| 131 |
+
|
| 132 |
+
def test_never_load_true(self, tmp_path):
|
| 133 |
+
self._make_override_page(tmp_path, "legacy", {"never_load": "true", "use_count": "0"})
|
| 134 |
+
overrides = read_wiki_overrides(str(tmp_path))
|
| 135 |
+
assert overrides["legacy"]["never_load"] is True
|
| 136 |
+
|
| 137 |
+
def test_defaults_when_fields_absent(self, tmp_path):
|
| 138 |
+
# Provide at least one field so _parse_fm returns non-empty and the
|
| 139 |
+
# entry isn't skipped by the `if not meta: continue` guard.
|
| 140 |
+
self._make_override_page(tmp_path, "plain", {"status": "installed"})
|
| 141 |
+
overrides = read_wiki_overrides(str(tmp_path))
|
| 142 |
+
assert overrides["plain"]["always_load"] is False
|
| 143 |
+
assert overrides["plain"]["never_load"] is False
|
| 144 |
+
assert overrides["plain"]["use_count"] == 0
|
| 145 |
+
|
| 146 |
+
def test_missing_entities_dir_returns_empty(self, tmp_path):
|
| 147 |
+
overrides = read_wiki_overrides(str(tmp_path))
|
| 148 |
+
assert overrides == {}
|
| 149 |
+
|
| 150 |
+
def test_bad_use_count_defaults_to_zero(self, tmp_path):
|
| 151 |
+
self._make_override_page(tmp_path, "bad", {"use_count": "not-a-number"})
|
| 152 |
+
# Should not raise; int(str("not-a-number")) will raise, so it goes to except
|
| 153 |
+
overrides = read_wiki_overrides(str(tmp_path))
|
| 154 |
+
# Page with parse error is skipped (continue in except)
|
| 155 |
+
assert "bad" not in overrides
|
| 156 |
+
|
| 157 |
+
def test_page_without_frontmatter_skipped(self, tmp_path):
|
| 158 |
+
entities = tmp_path / "entities" / "skills"
|
| 159 |
+
entities.mkdir(parents=True)
|
| 160 |
+
(entities / "plain.md").write_text("# plain\nno frontmatter here", encoding="utf-8")
|
| 161 |
+
overrides = read_wiki_overrides(str(tmp_path))
|
| 162 |
+
assert "plain" not in overrides
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
# ---------------------------------------------------------------------------
|
| 166 |
+
# resolve
|
| 167 |
+
# ---------------------------------------------------------------------------
|
| 168 |
+
|
| 169 |
+
class TestResolve:
|
| 170 |
+
def test_graph_can_be_disabled_for_deterministic_unit_resolution(
|
| 171 |
+
self, tmp_path, monkeypatch
|
| 172 |
+
):
|
| 173 |
+
from ctx.core.resolve import resolve_skills # noqa: PLC0415
|
| 174 |
+
|
| 175 |
+
def fail_if_loaded():
|
| 176 |
+
raise AssertionError("unit resolver tests must not load the live graph")
|
| 177 |
+
|
| 178 |
+
monkeypatch.setattr(resolve_skills, "_load_graph", fail_if_loaded)
|
| 179 |
+
available = {"react": {"path": str(tmp_path / "react/SKILL.md"), "name": "react"}}
|
| 180 |
+
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 181 |
+
|
| 182 |
+
manifest = _resolve_without_graph(profile, available, {})
|
| 183 |
+
|
| 184 |
+
assert "react" in [e["skill"] for e in manifest["load"]]
|
| 185 |
+
assert not any("graph walk skipped" in w for w in manifest["warnings"])
|
| 186 |
+
|
| 187 |
+
def test_basic_load_known_skill(self, tmp_path):
|
| 188 |
+
available = {"react": {"path": str(tmp_path / "react/SKILL.md"), "name": "react"}}
|
| 189 |
+
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 190 |
+
manifest = _resolve_without_graph(profile, available, {})
|
| 191 |
+
loaded_names = [e["skill"] for e in manifest["load"]]
|
| 192 |
+
assert "react" in loaded_names
|
| 193 |
+
|
| 194 |
+
def test_skill_not_available_goes_to_suggestions(self, tmp_path):
|
| 195 |
+
available = {} # react not installed
|
| 196 |
+
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 197 |
+
manifest = _resolve_without_graph(profile, available, {})
|
| 198 |
+
suggestion_skills = [s["skill"] for s in manifest["suggestions"]]
|
| 199 |
+
assert "react" in suggestion_skills
|
| 200 |
+
# The unavailable react skill must NOT be in load. Graph-matched
|
| 201 |
+
# agents (e.g. react-specialist found via the live knowledge graph)
|
| 202 |
+
# may legitimately appear in load — the assertion targets the
|
| 203 |
+
# specific skill, not the entire load list, so this test stays
|
| 204 |
+
# robust against richer graph-driven recommendations.
|
| 205 |
+
loaded_skills = [
|
| 206 |
+
e.get("skill") for e in manifest["load"]
|
| 207 |
+
if e.get("entity_type", "skill") == "skill"
|
| 208 |
+
]
|
| 209 |
+
assert "react" not in loaded_skills
|
| 210 |
+
|
| 211 |
+
def test_always_load_override_adds_skill(self, tmp_path):
|
| 212 |
+
available = {"docker": {"path": str(tmp_path / "docker/SKILL.md"), "name": "docker"}}
|
| 213 |
+
overrides = {"docker": {"always_load": True, "never_load": False, "use_count": 0, "last_used": "", "status": "installed"}}
|
| 214 |
+
profile = _minimal_profile() # no detection for docker
|
| 215 |
+
manifest = _resolve_without_graph(profile, available, overrides)
|
| 216 |
+
loaded_names = [e["skill"] for e in manifest["load"]]
|
| 217 |
+
assert "docker" in loaded_names
|
| 218 |
+
|
| 219 |
+
def test_never_load_override_removes_skill(self, tmp_path):
|
| 220 |
+
available = {"react": {"path": str(tmp_path / "react/SKILL.md"), "name": "react"}}
|
| 221 |
+
overrides = {"react": {"always_load": False, "never_load": True, "use_count": 0, "last_used": "", "status": "installed"}}
|
| 222 |
+
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 223 |
+
manifest = _resolve_without_graph(profile, available, overrides)
|
| 224 |
+
loaded_names = [e["skill"] for e in manifest["load"]]
|
| 225 |
+
assert "react" not in loaded_names
|
| 226 |
+
|
| 227 |
+
def test_conflict_resolution_keeps_higher_priority(self, tmp_path):
|
| 228 |
+
available = {
|
| 229 |
+
"fastapi": {"path": str(tmp_path / "fastapi/SKILL.md"), "name": "fastapi"},
|
| 230 |
+
"flask": {"path": str(tmp_path / "flask/SKILL.md"), "name": "flask"},
|
| 231 |
+
}
|
| 232 |
+
profile = _minimal_profile(frameworks=[
|
| 233 |
+
_detection("fastapi", confidence=0.95),
|
| 234 |
+
_detection("flask", confidence=0.6),
|
| 235 |
+
])
|
| 236 |
+
manifest = _resolve_without_graph(profile, available, {})
|
| 237 |
+
loaded_names = [e["skill"] for e in manifest["load"]]
|
| 238 |
+
# fastapi has higher base priority (8) and higher confidence boost
|
| 239 |
+
assert "fastapi" in loaded_names
|
| 240 |
+
assert "flask" not in loaded_names
|
| 241 |
+
assert any("Conflict" in w for w in manifest["warnings"])
|
| 242 |
+
|
| 243 |
+
def test_max_skills_cap(self, tmp_path):
|
| 244 |
+
# Create 20 available skills each mapped from detections
|
| 245 |
+
skills_with_map = ["react", "docker", "fastapi", "django", "flask",
|
| 246 |
+
"pytest", "jest", "langchain", "nextjs", "vue"]
|
| 247 |
+
available = {n: {"path": str(tmp_path / n / "SKILL.md"), "name": n} for n in skills_with_map}
|
| 248 |
+
profile = _minimal_profile(frameworks=[_detection(n, 0.9) for n in skills_with_map])
|
| 249 |
+
manifest = _resolve_without_graph(profile, available, {}, max_skills=3)
|
| 250 |
+
# At most 3 skill-mapped items (plus meta skills if available)
|
| 251 |
+
non_meta = [e for e in manifest["load"] if e["skill"] not in ("skill-router", "file-reading")]
|
| 252 |
+
assert len(non_meta) <= 3
|
| 253 |
+
assert any("Capped" in w for w in manifest["warnings"])
|
| 254 |
+
|
| 255 |
+
def test_meta_skills_added_if_available(self, tmp_path):
|
| 256 |
+
available = {"skill-router": {"path": str(tmp_path / "skill-router/SKILL.md"), "name": "skill-router"}}
|
| 257 |
+
profile = _minimal_profile()
|
| 258 |
+
manifest = _resolve_without_graph(profile, available, {})
|
| 259 |
+
loaded_names = [e["skill"] for e in manifest["load"]]
|
| 260 |
+
assert "skill-router" in loaded_names
|
| 261 |
+
|
| 262 |
+
def test_unloaded_skills_in_unload_list(self, tmp_path):
|
| 263 |
+
available = {
|
| 264 |
+
"react": {"path": str(tmp_path / "react/SKILL.md"), "name": "react"},
|
| 265 |
+
"docker": {"path": str(tmp_path / "docker/SKILL.md"), "name": "docker"},
|
| 266 |
+
}
|
| 267 |
+
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 268 |
+
manifest = _resolve_without_graph(profile, available, {})
|
| 269 |
+
unload_names = [e["skill"] for e in manifest["unload"]]
|
| 270 |
+
assert "docker" in unload_names
|
| 271 |
+
|
| 272 |
+
def test_empty_profile_no_crash(self):
|
| 273 |
+
manifest = _resolve_without_graph(_minimal_profile(), {}, {})
|
| 274 |
+
assert manifest["load"] == []
|
| 275 |
+
assert "generated_at" in manifest
|
| 276 |
+
|
| 277 |
+
def test_high_confidence_boost_applied(self, tmp_path):
|
| 278 |
+
"""Skills with confidence >=0.9 should get priority +10."""
|
| 279 |
+
available = {"react": {"path": str(tmp_path / "react/SKILL.md"), "name": "react"}}
|
| 280 |
+
profile = _minimal_profile(frameworks=[_detection("react", confidence=0.95)])
|
| 281 |
+
manifest = _resolve_without_graph(profile, available, {})
|
| 282 |
+
entry = next(e for e in manifest["load"] if e["skill"] == "react")
|
| 283 |
+
# PRIORITY_BASE["react"] = 7, +10 for confidence, +0 no use_count
|
| 284 |
+
assert entry["priority"] >= 17
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
class TestResolveMcpRecommendations:
|
| 288 |
+
"""Phase 5 regression: graph-walk hits with type=='mcp-server' land
|
| 289 |
+
in manifest['mcp_servers'], NOT manifest['load'] (the skill bucket).
|
| 290 |
+
"""
|
| 291 |
+
|
| 292 |
+
def _fake_graph(self, monkeypatch):
|
| 293 |
+
"""Make resolve() think the graph is available and non-empty."""
|
| 294 |
+
from ctx.core.resolve import resolve_skills # noqa: PLC0415
|
| 295 |
+
|
| 296 |
+
class _FakeGraph:
|
| 297 |
+
def number_of_nodes(self) -> int:
|
| 298 |
+
return 1
|
| 299 |
+
|
| 300 |
+
monkeypatch.setattr(
|
| 301 |
+
resolve_skills, "_load_graph", lambda: _FakeGraph()
|
| 302 |
+
)
|
| 303 |
+
monkeypatch.setattr(resolve_skills, "_GRAPH_AVAILABLE", True)
|
| 304 |
+
|
| 305 |
+
def test_mcp_graph_hit_lands_in_mcp_servers_not_load(
|
| 306 |
+
self, tmp_path, monkeypatch
|
| 307 |
+
):
|
| 308 |
+
from ctx.core.resolve import resolve_skills # noqa: PLC0415
|
| 309 |
+
self._fake_graph(monkeypatch)
|
| 310 |
+
|
| 311 |
+
# Synthetic graph hit: an MCP-type neighbor with score above the
|
| 312 |
+
# 1.5 noise floor.
|
| 313 |
+
def fake_resolve_by_seeds(graph, seeds, **kwargs):
|
| 314 |
+
return [
|
| 315 |
+
{
|
| 316 |
+
"name": "github-mcp-server",
|
| 317 |
+
"type": "mcp-server",
|
| 318 |
+
"score": 3.0,
|
| 319 |
+
"shared_tags": ["_t:github"],
|
| 320 |
+
"via": ["react"],
|
| 321 |
+
},
|
| 322 |
+
]
|
| 323 |
+
|
| 324 |
+
monkeypatch.setattr(
|
| 325 |
+
resolve_skills, "_resolve_by_seeds", fake_resolve_by_seeds
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
available = {"react": {"path": str(tmp_path / "react/SKILL.md"), "name": "react"}}
|
| 329 |
+
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 330 |
+
manifest = resolve(profile, available, {})
|
| 331 |
+
|
| 332 |
+
mcp_names = [m["name"] for m in manifest["mcp_servers"]]
|
| 333 |
+
load_names = [e["skill"] for e in manifest["load"]]
|
| 334 |
+
assert "github-mcp-server" in mcp_names, (
|
| 335 |
+
f"MCP should appear in mcp_servers bucket; got {manifest['mcp_servers']}"
|
| 336 |
+
)
|
| 337 |
+
assert "github-mcp-server" not in load_names, (
|
| 338 |
+
"MCP must NOT land in manifest['load'] — that's the skill-loader bucket"
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
def test_mcp_entry_has_reason_score_and_shared_tags(
|
| 342 |
+
self, tmp_path, monkeypatch
|
| 343 |
+
):
|
| 344 |
+
from ctx.core.resolve import resolve_skills # noqa: PLC0415
|
| 345 |
+
self._fake_graph(monkeypatch)
|
| 346 |
+
|
| 347 |
+
def fake_resolve_by_seeds(graph, seeds, **kwargs):
|
| 348 |
+
return [
|
| 349 |
+
{
|
| 350 |
+
"name": "fetch-mcp",
|
| 351 |
+
"type": "mcp-server",
|
| 352 |
+
"score": 2.5,
|
| 353 |
+
"shared_tags": ["_t:fetch", "http"],
|
| 354 |
+
"via": ["django"],
|
| 355 |
+
},
|
| 356 |
+
]
|
| 357 |
+
|
| 358 |
+
monkeypatch.setattr(
|
| 359 |
+
resolve_skills, "_resolve_by_seeds", fake_resolve_by_seeds
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
available = {"django": {"path": str(tmp_path / "django/SKILL.md"), "name": "django"}}
|
| 363 |
+
profile = _minimal_profile(frameworks=[_detection("django")])
|
| 364 |
+
manifest = resolve(profile, available, {})
|
| 365 |
+
|
| 366 |
+
assert len(manifest["mcp_servers"]) == 1
|
| 367 |
+
entry = manifest["mcp_servers"][0]
|
| 368 |
+
assert entry["name"] == "fetch-mcp"
|
| 369 |
+
assert entry["score"] == 2.5
|
| 370 |
+
assert "graph neighbor of django" in entry["reason"]
|
| 371 |
+
assert "_t:fetch" in entry["shared_tags"]
|
| 372 |
+
|
| 373 |
+
def test_mcp_deduped_when_same_name_hit_twice(
|
| 374 |
+
self, tmp_path, monkeypatch
|
| 375 |
+
):
|
| 376 |
+
from ctx.core.resolve import resolve_skills # noqa: PLC0415
|
| 377 |
+
self._fake_graph(monkeypatch)
|
| 378 |
+
|
| 379 |
+
def fake_resolve_by_seeds(graph, seeds, **kwargs):
|
| 380 |
+
return [
|
| 381 |
+
{"name": "duped-mcp", "type": "mcp-server", "score": 2.0,
|
| 382 |
+
"shared_tags": [], "via": ["a"]},
|
| 383 |
+
{"name": "duped-mcp", "type": "mcp-server", "score": 1.8,
|
| 384 |
+
"shared_tags": [], "via": ["b"]},
|
| 385 |
+
]
|
| 386 |
+
|
| 387 |
+
monkeypatch.setattr(
|
| 388 |
+
resolve_skills, "_resolve_by_seeds", fake_resolve_by_seeds
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
available = {"react": {"path": str(tmp_path / "react/SKILL.md"), "name": "react"}}
|
| 392 |
+
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 393 |
+
manifest = resolve(profile, available, {})
|
| 394 |
+
|
| 395 |
+
assert sum(1 for m in manifest["mcp_servers"] if m["name"] == "duped-mcp") == 1
|
| 396 |
+
|
| 397 |
+
def test_mcp_below_noise_floor_dropped(
|
| 398 |
+
self, tmp_path, monkeypatch
|
| 399 |
+
):
|
| 400 |
+
from ctx.core.resolve import resolve_skills # noqa: PLC0415
|
| 401 |
+
self._fake_graph(monkeypatch)
|
| 402 |
+
|
| 403 |
+
def fake_resolve_by_seeds(graph, seeds, **kwargs):
|
| 404 |
+
# Post-P2.5 the resolver uses normalized_score (percentile
|
| 405 |
+
# in [0,1]) against the 0.20 MCP floor. A value of 0.1
|
| 406 |
+
# sits below the floor so the hit must be dropped.
|
| 407 |
+
return [
|
| 408 |
+
{"name": "weak-mcp", "type": "mcp-server",
|
| 409 |
+
"score": 0.8, "normalized_score": 0.10,
|
| 410 |
+
"shared_tags": [], "via": ["a"]},
|
| 411 |
+
]
|
| 412 |
+
|
| 413 |
+
monkeypatch.setattr(
|
| 414 |
+
resolve_skills, "_resolve_by_seeds", fake_resolve_by_seeds
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
available = {"react": {"path": str(tmp_path / "react/SKILL.md"), "name": "react"}}
|
| 418 |
+
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 419 |
+
manifest = resolve(profile, available, {})
|
| 420 |
+
|
| 421 |
+
assert manifest["mcp_servers"] == []
|
| 422 |
+
|
| 423 |
+
def test_skill_hits_still_route_to_load(
|
| 424 |
+
self, tmp_path, monkeypatch
|
| 425 |
+
):
|
| 426 |
+
# Regression: mixing mcp-server hits and skill hits must not
|
| 427 |
+
# break the existing skill path.
|
| 428 |
+
from ctx.core.resolve import resolve_skills # noqa: PLC0415
|
| 429 |
+
self._fake_graph(monkeypatch)
|
| 430 |
+
|
| 431 |
+
def fake_resolve_by_seeds(graph, seeds, **kwargs):
|
| 432 |
+
return [
|
| 433 |
+
{"name": "pytest-something", "type": "skill", "score": 3.0,
|
| 434 |
+
"shared_tags": [], "via": ["django"]},
|
| 435 |
+
{"name": "fetch-mcp", "type": "mcp-server", "score": 2.0,
|
| 436 |
+
"shared_tags": [], "via": ["django"]},
|
| 437 |
+
]
|
| 438 |
+
|
| 439 |
+
monkeypatch.setattr(
|
| 440 |
+
resolve_skills, "_resolve_by_seeds", fake_resolve_by_seeds
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
available = {
|
| 444 |
+
"django": {"path": str(tmp_path / "django/SKILL.md"), "name": "django"},
|
| 445 |
+
"pytest-something": {
|
| 446 |
+
"path": str(tmp_path / "pytest-something/SKILL.md"),
|
| 447 |
+
"name": "pytest-something",
|
| 448 |
+
},
|
| 449 |
+
}
|
| 450 |
+
profile = _minimal_profile(frameworks=[_detection("django")])
|
| 451 |
+
manifest = resolve(profile, available, {})
|
| 452 |
+
|
| 453 |
+
mcp_names = [m["name"] for m in manifest["mcp_servers"]]
|
| 454 |
+
load_names = [e["skill"] for e in manifest["load"]]
|
| 455 |
+
assert "fetch-mcp" in mcp_names
|
| 456 |
+
assert "pytest-something" in load_names
|
| 457 |
+
|
| 458 |
+
def test_agent_graph_hit_lands_in_load_without_installed_skill(
|
| 459 |
+
self, tmp_path, monkeypatch
|
| 460 |
+
):
|
| 461 |
+
from ctx.core.resolve import resolve_skills # noqa: PLC0415
|
| 462 |
+
self._fake_graph(monkeypatch)
|
| 463 |
+
|
| 464 |
+
def fake_resolve_by_seeds(graph, seeds, **kwargs):
|
| 465 |
+
return [
|
| 466 |
+
{
|
| 467 |
+
"name": "code-reviewer",
|
| 468 |
+
"type": "agent",
|
| 469 |
+
"score": 2.0,
|
| 470 |
+
"normalized_score": 0.8,
|
| 471 |
+
"shared_tags": ["review"],
|
| 472 |
+
"via": ["django"],
|
| 473 |
+
},
|
| 474 |
+
]
|
| 475 |
+
|
| 476 |
+
monkeypatch.setattr(
|
| 477 |
+
resolve_skills, "_resolve_by_seeds", fake_resolve_by_seeds
|
| 478 |
+
)
|
| 479 |
+
|
| 480 |
+
available = {"django": {"path": str(tmp_path / "django/SKILL.md"), "name": "django"}}
|
| 481 |
+
profile = _minimal_profile(frameworks=[_detection("django")])
|
| 482 |
+
manifest = resolve(profile, available, {})
|
| 483 |
+
|
| 484 |
+
agents = [
|
| 485 |
+
e for e in manifest["load"]
|
| 486 |
+
if e.get("entity_type") == "agent"
|
| 487 |
+
]
|
| 488 |
+
assert [e["skill"] for e in agents] == ["code-reviewer"]
|
| 489 |
+
assert agents[0]["path"] == "/mnt/agents/unknown/code-reviewer.md"
|
| 490 |
+
assert not any("code-reviewer needed but not installed" in w for w in manifest["warnings"])
|
| 491 |
+
|
| 492 |
+
def test_real_graph_walk_routes_cross_type_hits(
|
| 493 |
+
self, tmp_path, monkeypatch
|
| 494 |
+
):
|
| 495 |
+
import networkx as nx
|
| 496 |
+
from ctx.core.resolve import resolve_skills # noqa: PLC0415
|
| 497 |
+
|
| 498 |
+
G = nx.Graph()
|
| 499 |
+
G.add_node("skill:react", label="react", type="skill")
|
| 500 |
+
G.add_node("skill:pytest-something", label="pytest-something", type="skill")
|
| 501 |
+
G.add_node("agent:code-reviewer", label="code-reviewer", type="agent")
|
| 502 |
+
G.add_node("mcp-server:github-mcp-server", label="github-mcp-server", type="mcp-server")
|
| 503 |
+
G.add_edge(
|
| 504 |
+
"skill:react",
|
| 505 |
+
"skill:pytest-something",
|
| 506 |
+
weight=0.85,
|
| 507 |
+
shared_tags=["test"],
|
| 508 |
+
)
|
| 509 |
+
G.add_edge(
|
| 510 |
+
"skill:react",
|
| 511 |
+
"agent:code-reviewer",
|
| 512 |
+
weight=0.90,
|
| 513 |
+
shared_tags=["review"],
|
| 514 |
+
)
|
| 515 |
+
G.add_edge(
|
| 516 |
+
"skill:react",
|
| 517 |
+
"mcp-server:github-mcp-server",
|
| 518 |
+
weight=0.95,
|
| 519 |
+
shared_tags=["github"],
|
| 520 |
+
)
|
| 521 |
+
monkeypatch.setattr(resolve_skills, "_load_graph", lambda: G)
|
| 522 |
+
monkeypatch.setattr(resolve_skills, "_GRAPH_AVAILABLE", True)
|
| 523 |
+
|
| 524 |
+
available = {
|
| 525 |
+
"react": {"path": str(tmp_path / "react/SKILL.md"), "name": "react"},
|
| 526 |
+
"pytest-something": {
|
| 527 |
+
"path": str(tmp_path / "pytest-something/SKILL.md"),
|
| 528 |
+
"name": "pytest-something",
|
| 529 |
+
},
|
| 530 |
+
}
|
| 531 |
+
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 532 |
+
|
| 533 |
+
manifest = resolve(profile, available, {})
|
| 534 |
+
|
| 535 |
+
load_by_name = {entry["skill"]: entry for entry in manifest["load"]}
|
| 536 |
+
assert load_by_name["pytest-something"]["entity_type"] == "skill"
|
| 537 |
+
assert load_by_name["code-reviewer"]["entity_type"] == "agent"
|
| 538 |
+
assert load_by_name["code-reviewer"]["path"] == "/mnt/agents/unknown/code-reviewer.md"
|
| 539 |
+
assert [entry["name"] for entry in manifest["mcp_servers"]] == [
|
| 540 |
+
"github-mcp-server",
|
| 541 |
+
]
|
| 542 |
+
assert manifest["mcp_servers"][0]["shared_tags"] == ["github"]
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
# ---------------------------------------------------------------------------
|
| 546 |
+
# read_intent_signals
|
| 547 |
+
# ---------------------------------------------------------------------------
|
| 548 |
+
|
| 549 |
+
class TestReadIntentSignals:
|
| 550 |
+
def _write_log(self, path: Path, entries: list[dict]) -> None:
|
| 551 |
+
lines = [json.dumps(e) for e in entries]
|
| 552 |
+
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
| 553 |
+
|
| 554 |
+
def test_returns_empty_when_file_missing(self, tmp_path):
|
| 555 |
+
signals = read_intent_signals(str(tmp_path / "no-such.jsonl"))
|
| 556 |
+
assert signals == {}
|
| 557 |
+
|
| 558 |
+
def test_counts_todays_signals(self, tmp_path, monkeypatch):
|
| 559 |
+
from datetime import datetime, timezone
|
| 560 |
+
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
| 561 |
+
log = tmp_path / "intent.jsonl"
|
| 562 |
+
self._write_log(log, [
|
| 563 |
+
{"date": today, "signals": ["react", "docker"]},
|
| 564 |
+
{"date": today, "signals": ["react"]},
|
| 565 |
+
])
|
| 566 |
+
signals = read_intent_signals(str(log))
|
| 567 |
+
assert signals["react"] == 2
|
| 568 |
+
assert signals["docker"] == 1
|
| 569 |
+
|
| 570 |
+
def test_ignores_other_dates(self, tmp_path):
|
| 571 |
+
log = tmp_path / "intent.jsonl"
|
| 572 |
+
self._write_log(log, [
|
| 573 |
+
{"date": "2020-01-01", "signals": ["react"]},
|
| 574 |
+
])
|
| 575 |
+
signals = read_intent_signals(str(log))
|
| 576 |
+
# Today's date != 2020-01-01, so nothing counted
|
| 577 |
+
assert "react" not in signals
|
| 578 |
+
|
| 579 |
+
def test_skips_bad_json_lines(self, tmp_path):
|
| 580 |
+
from datetime import datetime, timezone
|
| 581 |
+
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
| 582 |
+
log = tmp_path / "intent.jsonl"
|
| 583 |
+
log.write_text(
|
| 584 |
+
'not json\n'
|
| 585 |
+
f'{json.dumps({"date": today, "signals": ["fastapi"]})}\n',
|
| 586 |
+
encoding="utf-8",
|
| 587 |
+
)
|
| 588 |
+
signals = read_intent_signals(str(log))
|
| 589 |
+
assert signals.get("fastapi") == 1
|
| 590 |
+
|
| 591 |
+
def test_empty_file_returns_empty(self, tmp_path):
|
| 592 |
+
log = tmp_path / "intent.jsonl"
|
| 593 |
+
log.write_text("", encoding="utf-8")
|
| 594 |
+
signals = read_intent_signals(str(log))
|
| 595 |
+
assert signals == {}
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
# ---------------------------------------------------------------------------
|
| 599 |
+
# apply_intent_boosts
|
| 600 |
+
# ---------------------------------------------------------------------------
|
| 601 |
+
|
| 602 |
+
class TestApplyIntentBoosts:
|
| 603 |
+
def _make_manifest(self) -> dict:
|
| 604 |
+
return {"suggestions": [], "warnings": []}
|
| 605 |
+
|
| 606 |
+
def test_boosts_existing_skill_in_needed(self):
|
| 607 |
+
needed = {"react": {"priority": 10, "reason": "detected", "confidence": 0.9}}
|
| 608 |
+
available = {}
|
| 609 |
+
manifest = self._make_manifest()
|
| 610 |
+
apply_intent_boosts(needed, {"react": 2}, available, manifest)
|
| 611 |
+
# boost = 5 * min(2, 3) = 10
|
| 612 |
+
assert needed["react"]["priority"] == 20
|
| 613 |
+
|
| 614 |
+
def test_boost_capped_at_three_signals(self):
|
| 615 |
+
needed = {"react": {"priority": 10, "reason": "detected", "confidence": 0.9}}
|
| 616 |
+
manifest = self._make_manifest()
|
| 617 |
+
apply_intent_boosts(needed, {"react": 10}, {}, manifest)
|
| 618 |
+
# boost = 5 * min(10, 3) = 15
|
| 619 |
+
assert needed["react"]["priority"] == 25
|
| 620 |
+
|
| 621 |
+
def test_available_not_in_needed_becomes_suggestion(self, tmp_path):
|
| 622 |
+
needed = {}
|
| 623 |
+
available = {"docker": {"path": str(tmp_path / "docker/SKILL.md")}}
|
| 624 |
+
manifest = self._make_manifest()
|
| 625 |
+
apply_intent_boosts(needed, {"docker": 1}, available, manifest)
|
| 626 |
+
suggestion_skills = [s["skill"] for s in manifest["suggestions"]]
|
| 627 |
+
assert "docker" in suggestion_skills
|
| 628 |
+
|
| 629 |
+
def test_unknown_signal_no_crash(self):
|
| 630 |
+
needed = {}
|
| 631 |
+
manifest = self._make_manifest()
|
| 632 |
+
apply_intent_boosts(needed, {"totally-unknown-signal": 5}, {}, manifest)
|
| 633 |
+
assert manifest["suggestions"] == []
|
| 634 |
+
|
| 635 |
+
def test_empty_signals_no_change(self):
|
| 636 |
+
needed = {"react": {"priority": 10, "reason": "x", "confidence": 0.9}}
|
| 637 |
+
manifest = self._make_manifest()
|
| 638 |
+
apply_intent_boosts(needed, {}, {}, manifest)
|
| 639 |
+
assert needed["react"]["priority"] == 10
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
# ─────────────────────────────────────────────────────────────────────
|
| 643 |
+
# P2.5 normalised noise-floor regression
|
| 644 |
+
# ─────────────────────────────────────────────────────────────────────
|
| 645 |
+
#
|
| 646 |
+
# Pre-P2.5 the floors were absolute (1.5 / 1.0) and calibrated against
|
| 647 |
+
# the v0.6 integer-weight graph. On v0.7's blended float-weight graph
|
| 648 |
+
# a single edge is <=1.0, so absolute 1.5 dropped ALL single-seed
|
| 649 |
+
# hits on any sparse/test graph — the suggestion arm silently produced
|
| 650 |
+
# nothing. Post-fix the floors are percentile thresholds in [0,1],
|
| 651 |
+
# scale-invariant.
|
| 652 |
+
|
| 653 |
+
class TestNoiseFloorNormalized:
|
| 654 |
+
|
| 655 |
+
def _fake_graph(self, monkeypatch):
|
| 656 |
+
import networkx as nx
|
| 657 |
+
from ctx.core.resolve import resolve_skills
|
| 658 |
+
|
| 659 |
+
def fake_load_graph(_=None):
|
| 660 |
+
G = nx.Graph()
|
| 661 |
+
G.add_node("skill:foo", type="skill", label="foo")
|
| 662 |
+
return G
|
| 663 |
+
|
| 664 |
+
monkeypatch.setattr(resolve_skills, "_load_graph", fake_load_graph)
|
| 665 |
+
|
| 666 |
+
def test_normalized_score_at_top_survives(self, tmp_path, monkeypatch):
|
| 667 |
+
"""A hit with normalized_score=1.0 (the top of its ranking)
|
| 668 |
+
always passes the floor — otherwise the top recommendation
|
| 669 |
+
gets silently dropped on small fixtures."""
|
| 670 |
+
from ctx.core.resolve import resolve_skills
|
| 671 |
+
from ctx.core.resolve.resolve_skills import resolve
|
| 672 |
+
self._fake_graph(monkeypatch)
|
| 673 |
+
|
| 674 |
+
def fake_hits(*a, **kw):
|
| 675 |
+
return [
|
| 676 |
+
{"name": "top-skill", "type": "skill",
|
| 677 |
+
"score": 1.23, "normalized_score": 1.0,
|
| 678 |
+
"shared_tags": ["x"], "via": ["react"]},
|
| 679 |
+
]
|
| 680 |
+
|
| 681 |
+
monkeypatch.setattr(resolve_skills, "_resolve_by_seeds", fake_hits)
|
| 682 |
+
available = {"react": {"path": str(tmp_path / "r/SKILL.md"), "name": "react"},
|
| 683 |
+
"top-skill": {"path": str(tmp_path / "t/SKILL.md"), "name": "top-skill"}}
|
| 684 |
+
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 685 |
+
manifest = resolve(profile, available, {})
|
| 686 |
+
assert "top-skill" in {e["skill"] for e in manifest["load"]}
|
| 687 |
+
|
| 688 |
+
def test_skill_below_0_3_dropped(self, tmp_path, monkeypatch):
|
| 689 |
+
"""Skill hits with normalized_score < 0.30 don't make the cut."""
|
| 690 |
+
from ctx.core.resolve import resolve_skills
|
| 691 |
+
from ctx.core.resolve.resolve_skills import resolve
|
| 692 |
+
self._fake_graph(monkeypatch)
|
| 693 |
+
|
| 694 |
+
def fake_hits(*a, **kw):
|
| 695 |
+
return [
|
| 696 |
+
{"name": "noisy", "type": "skill",
|
| 697 |
+
"score": 0.12, "normalized_score": 0.10,
|
| 698 |
+
"shared_tags": [], "via": ["react"]},
|
| 699 |
+
]
|
| 700 |
+
monkeypatch.setattr(resolve_skills, "_resolve_by_seeds", fake_hits)
|
| 701 |
+
available = {"react": {"path": str(tmp_path / "r/SKILL.md"), "name": "react"},
|
| 702 |
+
"noisy": {"path": str(tmp_path / "n/SKILL.md"), "name": "noisy"}}
|
| 703 |
+
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 704 |
+
manifest = resolve(profile, available, {})
|
| 705 |
+
assert "noisy" not in {e["skill"] for e in manifest["load"]}
|
| 706 |
+
|
| 707 |
+
def test_mcp_floor_is_lower_than_skill_floor(self, tmp_path, monkeypatch):
|
| 708 |
+
"""MCPs are historically sparser; a hit with normalized_score=0.25
|
| 709 |
+
passes the MCP floor (0.20) but NOT the skill floor (0.30).
|
| 710 |
+
Pinning this asymmetry so a future 'unify the floors' refactor
|
| 711 |
+
wipes out MCP recommendations without CI noticing."""
|
| 712 |
+
from ctx.core.resolve import resolve_skills
|
| 713 |
+
from ctx.core.resolve.resolve_skills import resolve
|
| 714 |
+
self._fake_graph(monkeypatch)
|
| 715 |
+
|
| 716 |
+
def fake_hits(*a, **kw):
|
| 717 |
+
return [
|
| 718 |
+
{"name": "mid-mcp", "type": "mcp-server",
|
| 719 |
+
"score": 0.3, "normalized_score": 0.25,
|
| 720 |
+
"shared_tags": ["x"], "via": ["react"]},
|
| 721 |
+
{"name": "mid-skill", "type": "skill",
|
| 722 |
+
"score": 0.3, "normalized_score": 0.25,
|
| 723 |
+
"shared_tags": ["x"], "via": ["react"]},
|
| 724 |
+
]
|
| 725 |
+
monkeypatch.setattr(resolve_skills, "_resolve_by_seeds", fake_hits)
|
| 726 |
+
available = {
|
| 727 |
+
"react": {"path": str(tmp_path / "r/SKILL.md"), "name": "react"},
|
| 728 |
+
"mid-skill": {"path": str(tmp_path / "s/SKILL.md"), "name": "mid-skill"},
|
| 729 |
+
}
|
| 730 |
+
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 731 |
+
manifest = resolve(profile, available, {})
|
| 732 |
+
# Skill below 0.30 → dropped.
|
| 733 |
+
assert "mid-skill" not in {e["skill"] for e in manifest["load"]}
|
| 734 |
+
# MCP above 0.20 → kept.
|
| 735 |
+
mcp_names = {m["name"] for m in manifest["mcp_servers"]}
|
| 736 |
+
assert "mid-mcp" in mcp_names
|
| 737 |
+
|
| 738 |
+
def test_backward_compat_raw_score_fallback(self, tmp_path, monkeypatch):
|
| 739 |
+
"""An older resolver output without normalized_score must
|
| 740 |
+
still work via raw-score fallback, so a stale cached graph
|
| 741 |
+
doesn't silently return [] after the P2.5 upgrade."""
|
| 742 |
+
from ctx.core.resolve import resolve_skills
|
| 743 |
+
from ctx.core.resolve.resolve_skills import resolve
|
| 744 |
+
self._fake_graph(monkeypatch)
|
| 745 |
+
|
| 746 |
+
def fake_hits(*a, **kw):
|
| 747 |
+
# No ``normalized_score`` key — pre-P2.5 shape.
|
| 748 |
+
return [
|
| 749 |
+
{"name": "legacy-hit", "type": "skill",
|
| 750 |
+
"score": 2.5, "shared_tags": ["x"], "via": ["react"]},
|
| 751 |
+
]
|
| 752 |
+
monkeypatch.setattr(resolve_skills, "_resolve_by_seeds", fake_hits)
|
| 753 |
+
available = {"react": {"path": str(tmp_path / "r/SKILL.md"), "name": "react"},
|
| 754 |
+
"legacy-hit": {"path": str(tmp_path / "l/SKILL.md"), "name": "legacy-hit"}}
|
| 755 |
+
profile = _minimal_profile(frameworks=[_detection("react")])
|
| 756 |
+
manifest = resolve(profile, available, {})
|
| 757 |
+
# Raw score 2.5 >> any old skill floor so legacy behaviour survives.
|
| 758 |
+
assert "legacy-hit" in {e["skill"] for e in manifest["load"]}
|
src/tests/test_safe_name.py
CHANGED
|
@@ -1,228 +1,228 @@
|
|
| 1 |
-
"""
|
| 2 |
-
test_safe_name.py -- unit tests for _safe_name validators.
|
| 3 |
-
|
| 4 |
-
Pins the security-auditor H-2 (relpath traversal) and H-3 (Windows drive-
|
| 5 |
-
relative source name) findings. These validators are shared between
|
| 6 |
-
mcp_canonical_index (relpath) and mcp_enrich / mcp_ingest (source name),
|
| 7 |
-
so regressions here would reopen both attack surfaces simultaneously.
|
| 8 |
-
"""
|
| 9 |
-
|
| 10 |
-
from __future__ import annotations
|
| 11 |
-
|
| 12 |
-
import os
|
| 13 |
-
from pathlib import Path
|
| 14 |
-
|
| 15 |
-
import pytest
|
| 16 |
-
|
| 17 |
-
from ctx.utils._safe_name import (
|
| 18 |
-
is_safe_relpath,
|
| 19 |
-
is_safe_source_name,
|
| 20 |
-
validate_relpath,
|
| 21 |
-
validate_source_name,
|
| 22 |
-
)
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
# ────────────────────────────────────────────────────────────────────
|
| 26 |
-
# Source-name validator
|
| 27 |
-
# ────────────────────────────────────────────────────────────────────
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
class TestIsSafeSourceName:
|
| 31 |
-
@pytest.mark.parametrize("name", [
|
| 32 |
-
"pulsemcp",
|
| 33 |
-
"awesome-mcp",
|
| 34 |
-
"glama",
|
| 35 |
-
"mcp-get",
|
| 36 |
-
"foo.v2",
|
| 37 |
-
"a",
|
| 38 |
-
"0",
|
| 39 |
-
"a" * 128, # exactly the max length
|
| 40 |
-
])
|
| 41 |
-
def test_accepts_valid_names(self, name: str):
|
| 42 |
-
assert is_safe_source_name(name)
|
| 43 |
-
|
| 44 |
-
@pytest.mark.parametrize("name", [
|
| 45 |
-
"", # empty
|
| 46 |
-
"-pulsemcp", # leading hyphen
|
| 47 |
-
".pulsemcp", # leading dot (hidden file)
|
| 48 |
-
"_pulsemcp", # leading underscore (disallowed: first char must be [a-z0-9])
|
| 49 |
-
"PULSEMCP", # uppercase (regex is lowercase)
|
| 50 |
-
"pulse mcp", # space
|
| 51 |
-
"pulse$mcp", # shell metachar
|
| 52 |
-
"a" * 129, # too long
|
| 53 |
-
])
|
| 54 |
-
def test_rejects_malformed(self, name: str):
|
| 55 |
-
assert not is_safe_source_name(name)
|
| 56 |
-
|
| 57 |
-
@pytest.mark.parametrize("name", [
|
| 58 |
-
"foo/bar", # directory separator (posix)
|
| 59 |
-
"foo\\bar", # directory separator (windows)
|
| 60 |
-
"../etc/passwd",
|
| 61 |
-
"..",
|
| 62 |
-
"/etc/passwd",
|
| 63 |
-
"\\windows\\system32",
|
| 64 |
-
])
|
| 65 |
-
def test_rejects_path_separators(self, name: str):
|
| 66 |
-
"""H-3 regression — traversal-shaped names must be blocked."""
|
| 67 |
-
assert not is_safe_source_name(name)
|
| 68 |
-
|
| 69 |
-
@pytest.mark.parametrize("name", [
|
| 70 |
-
"C:evil", # Windows drive-relative (the H-3 exploit)
|
| 71 |
-
"C:",
|
| 72 |
-
"c:foo",
|
| 73 |
-
"C:\\Windows", # drive-absolute
|
| 74 |
-
"Z:payload.json",
|
| 75 |
-
])
|
| 76 |
-
def test_rejects_windows_drive_relative(self, name: str):
|
| 77 |
-
"""H-3 regression — Windows drive-relative / absolute must be blocked.
|
| 78 |
-
|
| 79 |
-
Prior validator only checked ``/ \\ .``; ``C:evil`` passed through
|
| 80 |
-
and landed wherever drive C's CWD happened to be at the time.
|
| 81 |
-
"""
|
| 82 |
-
assert not is_safe_source_name(name)
|
| 83 |
-
|
| 84 |
-
@pytest.mark.parametrize("name", [
|
| 85 |
-
"CON", "con", "Con", # case-insensitive
|
| 86 |
-
"PRN",
|
| 87 |
-
"NUL",
|
| 88 |
-
"AUX",
|
| 89 |
-
"COM1", "COM9",
|
| 90 |
-
"LPT1", "LPT9",
|
| 91 |
-
])
|
| 92 |
-
def test_rejects_windows_reserved_device_names(self, name: str):
|
| 93 |
-
"""``NUL.json`` on Windows writes to the null device silently."""
|
| 94 |
-
assert not is_safe_source_name(name)
|
| 95 |
-
|
| 96 |
-
# Strix vuln-0003: Windows device-name reservation survives a suffix
|
| 97 |
-
# or trailing dot/space. `con.txt`, `aux.md`, `nul.`, `com1.log`, and
|
| 98 |
-
# `lpt1.txt` all still resolve to the device endpoint on Windows.
|
| 99 |
-
@pytest.mark.parametrize("name", [
|
| 100 |
-
"con.txt", "CON.TXT", "Con.Log",
|
| 101 |
-
"aux.md", "AUX.json",
|
| 102 |
-
"prn.bak",
|
| 103 |
-
"nul.", # trailing dot — Windows strips it then matches NUL
|
| 104 |
-
"com1.log", "COM9.cfg",
|
| 105 |
-
"lpt1.txt", "lpt9.ini",
|
| 106 |
-
])
|
| 107 |
-
def test_rejects_reserved_name_with_suffix_or_trailing_dot(
|
| 108 |
-
self, name: str,
|
| 109 |
-
) -> None:
|
| 110 |
-
assert not is_safe_source_name(name), (
|
| 111 |
-
f"{name!r} slipped past the Windows reserved-name normalize"
|
| 112 |
-
)
|
| 113 |
-
|
| 114 |
-
def test_rejects_non_string(self):
|
| 115 |
-
assert not is_safe_source_name(None) # type: ignore[arg-type]
|
| 116 |
-
assert not is_safe_source_name(123) # type: ignore[arg-type]
|
| 117 |
-
assert not is_safe_source_name(["pulsemcp"]) # type: ignore[arg-type]
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
class TestValidateSourceName:
|
| 121 |
-
def test_raises_on_invalid(self):
|
| 122 |
-
with pytest.raises(ValueError, match="invalid source name"):
|
| 123 |
-
validate_source_name("C:evil")
|
| 124 |
-
|
| 125 |
-
def test_custom_field_in_error_message(self):
|
| 126 |
-
with pytest.raises(ValueError, match="invalid mcp_source name"):
|
| 127 |
-
validate_source_name("../etc/passwd", field="mcp_source")
|
| 128 |
-
|
| 129 |
-
def test_silent_on_valid(self):
|
| 130 |
-
# Must not raise.
|
| 131 |
-
validate_source_name("pulsemcp")
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
# ────────────────────────────
|
| 135 |
-
# Relpath validator — the H-2 attack surface
|
| 136 |
-
# ────────────────────────────────────────────────────────────────────
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
class TestIsSafeRelpath:
|
| 140 |
-
@pytest.fixture()
|
| 141 |
-
def root(self, tmp_path: Path) -> Path:
|
| 142 |
-
(tmp_path / "a").mkdir()
|
| 143 |
-
(tmp_path / "a" / "foo.md").write_text("body", encoding="utf-8")
|
| 144 |
-
(tmp_path / "subdir" / "nested").mkdir(parents=True)
|
| 145 |
-
return tmp_path
|
| 146 |
-
|
| 147 |
-
@pytest.mark.parametrize("rel", [
|
| 148 |
-
"a/foo.md", # shallow
|
| 149 |
-
"subdir/nested/x.md", # nested
|
| 150 |
-
"a/b/c/d/e/f/deep.md", # very nested — no need to exist
|
| 151 |
-
"hooks/backup_on_change.py",
|
| 152 |
-
])
|
| 153 |
-
def test_accepts_safe_relative_paths(self, root: Path, rel: str):
|
| 154 |
-
assert is_safe_relpath(root, rel)
|
| 155 |
-
|
| 156 |
-
@pytest.mark.parametrize("rel", [
|
| 157 |
-
"",
|
| 158 |
-
"../etc/passwd",
|
| 159 |
-
"../../../../tmp/evil",
|
| 160 |
-
"a/../../../outside",
|
| 161 |
-
"..",
|
| 162 |
-
"a/../..",
|
| 163 |
-
])
|
| 164 |
-
def test_rejects_traversal(self, root: Path, rel: str):
|
| 165 |
-
"""H-2 regression — ``..`` components in the stored relpath."""
|
| 166 |
-
assert not is_safe_relpath(root, rel)
|
| 167 |
-
|
| 168 |
-
@pytest.mark.parametrize("rel", [
|
| 169 |
-
"/etc/passwd",
|
| 170 |
-
"/foo",
|
| 171 |
-
"\\windows\\system32",
|
| 172 |
-
"\\foo",
|
| 173 |
-
])
|
| 174 |
-
def test_rejects_absolute(self, root: Path, rel: str):
|
| 175 |
-
assert not is_safe_relpath(root, rel)
|
| 176 |
-
|
| 177 |
-
@pytest.mark.parametrize("rel", [
|
| 178 |
-
"C:evil", # drive-relative: resolves against drive C's CWD
|
| 179 |
-
"C:/foo",
|
| 180 |
-
"C:\\foo",
|
| 181 |
-
"Z:payload.md",
|
| 182 |
-
])
|
| 183 |
-
def test_rejects_windows_drive_relative(self, root: Path, rel: str):
|
| 184 |
-
"""H-3 cousin — drive-relative in a stored relpath is always wrong."""
|
| 185 |
-
assert not is_safe_relpath(root, rel)
|
| 186 |
-
|
| 187 |
-
def test_rejects_non_string(self, root: Path):
|
| 188 |
-
assert not is_safe_relpath(root, None) # type: ignore[arg-type]
|
| 189 |
-
assert not is_safe_relpath(root, 42) # type: ignore[arg-type]
|
| 190 |
-
|
| 191 |
-
def test_empty_string_rejected(self, root: Path):
|
| 192 |
-
assert not is_safe_relpath(root, "")
|
| 193 |
-
|
| 194 |
-
@pytest.mark.skipif(os.name == "nt", reason="POSIX-only: symlink requires admin on Windows")
|
| 195 |
-
def test_rejects_symlink_escape(self, tmp_path: Path):
|
| 196 |
-
"""A symlink INSIDE root that points OUTSIDE root must be caught.
|
| 197 |
-
|
| 198 |
-
Even with no ``..`` in the relpath, following a symlink to
|
| 199 |
-
/etc/passwd is traversal.
|
| 200 |
-
"""
|
| 201 |
-
outside = tmp_path / "outside"
|
| 202 |
-
outside.mkdir()
|
| 203 |
-
(outside / "secret").write_text("sensitive", encoding="utf-8")
|
| 204 |
-
|
| 205 |
-
root = tmp_path / "root"
|
| 206 |
-
root.mkdir()
|
| 207 |
-
# Symlink root/escape -> outside
|
| 208 |
-
try:
|
| 209 |
-
(root / "escape").symlink_to(outside)
|
| 210 |
-
except (OSError, NotImplementedError):
|
| 211 |
-
pytest.skip("Platform does not support symlinks in this context")
|
| 212 |
-
|
| 213 |
-
# "escape/secret" is a relative path with no ``..``, but after
|
| 214 |
-
# symlink resolution it lands at outside/secret.
|
| 215 |
-
assert not is_safe_relpath(root, "escape/secret")
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
class TestValidateRelpath:
|
| 219 |
-
def test_raises_on_traversal(self, tmp_path: Path):
|
| 220 |
-
with pytest.raises(ValueError, match="invalid relpath"):
|
| 221 |
-
validate_relpath(tmp_path, "../../etc/passwd")
|
| 222 |
-
|
| 223 |
-
def test_custom_field_in_error_message(self, tmp_path: Path):
|
| 224 |
-
with pytest.raises(ValueError, match="invalid entity_path"):
|
| 225 |
-
validate_relpath(tmp_path, "C:evil", field="entity_path")
|
| 226 |
-
|
| 227 |
-
def test_silent_on_valid(self, tmp_path: Path):
|
| 228 |
-
validate_relpath(tmp_path, "a/foo.md")
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_safe_name.py -- unit tests for _safe_name validators.
|
| 3 |
+
|
| 4 |
+
Pins the security-auditor H-2 (relpath traversal) and H-3 (Windows drive-
|
| 5 |
+
relative source name) findings. These validators are shared between
|
| 6 |
+
mcp_canonical_index (relpath) and mcp_enrich / mcp_ingest (source name),
|
| 7 |
+
so regressions here would reopen both attack surfaces simultaneously.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import os
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import pytest
|
| 16 |
+
|
| 17 |
+
from ctx.utils._safe_name import (
|
| 18 |
+
is_safe_relpath,
|
| 19 |
+
is_safe_source_name,
|
| 20 |
+
validate_relpath,
|
| 21 |
+
validate_source_name,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# ────────────────────────────────────────────────────────────────────
|
| 26 |
+
# Source-name validator
|
| 27 |
+
# ────────────────────────────────────────────────────────────────────
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class TestIsSafeSourceName:
|
| 31 |
+
@pytest.mark.parametrize("name", [
|
| 32 |
+
"pulsemcp",
|
| 33 |
+
"awesome-mcp",
|
| 34 |
+
"glama",
|
| 35 |
+
"mcp-get",
|
| 36 |
+
"foo.v2",
|
| 37 |
+
"a",
|
| 38 |
+
"0",
|
| 39 |
+
"a" * 128, # exactly the max length
|
| 40 |
+
])
|
| 41 |
+
def test_accepts_valid_names(self, name: str):
|
| 42 |
+
assert is_safe_source_name(name)
|
| 43 |
+
|
| 44 |
+
@pytest.mark.parametrize("name", [
|
| 45 |
+
"", # empty
|
| 46 |
+
"-pulsemcp", # leading hyphen
|
| 47 |
+
".pulsemcp", # leading dot (hidden file)
|
| 48 |
+
"_pulsemcp", # leading underscore (disallowed: first char must be [a-z0-9])
|
| 49 |
+
"PULSEMCP", # uppercase (regex is lowercase)
|
| 50 |
+
"pulse mcp", # space
|
| 51 |
+
"pulse$mcp", # shell metachar
|
| 52 |
+
"a" * 129, # too long
|
| 53 |
+
])
|
| 54 |
+
def test_rejects_malformed(self, name: str):
|
| 55 |
+
assert not is_safe_source_name(name)
|
| 56 |
+
|
| 57 |
+
@pytest.mark.parametrize("name", [
|
| 58 |
+
"foo/bar", # directory separator (posix)
|
| 59 |
+
"foo\\bar", # directory separator (windows)
|
| 60 |
+
"../etc/passwd",
|
| 61 |
+
"..",
|
| 62 |
+
"/etc/passwd",
|
| 63 |
+
"\\windows\\system32",
|
| 64 |
+
])
|
| 65 |
+
def test_rejects_path_separators(self, name: str):
|
| 66 |
+
"""H-3 regression — traversal-shaped names must be blocked."""
|
| 67 |
+
assert not is_safe_source_name(name)
|
| 68 |
+
|
| 69 |
+
@pytest.mark.parametrize("name", [
|
| 70 |
+
"C:evil", # Windows drive-relative (the H-3 exploit)
|
| 71 |
+
"C:",
|
| 72 |
+
"c:foo",
|
| 73 |
+
"C:\\Windows", # drive-absolute
|
| 74 |
+
"Z:payload.json",
|
| 75 |
+
])
|
| 76 |
+
def test_rejects_windows_drive_relative(self, name: str):
|
| 77 |
+
"""H-3 regression — Windows drive-relative / absolute must be blocked.
|
| 78 |
+
|
| 79 |
+
Prior validator only checked ``/ \\ .``; ``C:evil`` passed through
|
| 80 |
+
and landed wherever drive C's CWD happened to be at the time.
|
| 81 |
+
"""
|
| 82 |
+
assert not is_safe_source_name(name)
|
| 83 |
+
|
| 84 |
+
@pytest.mark.parametrize("name", [
|
| 85 |
+
"CON", "con", "Con", # case-insensitive
|
| 86 |
+
"PRN",
|
| 87 |
+
"NUL",
|
| 88 |
+
"AUX",
|
| 89 |
+
"COM1", "COM9",
|
| 90 |
+
"LPT1", "LPT9",
|
| 91 |
+
])
|
| 92 |
+
def test_rejects_windows_reserved_device_names(self, name: str):
|
| 93 |
+
"""``NUL.json`` on Windows writes to the null device silently."""
|
| 94 |
+
assert not is_safe_source_name(name)
|
| 95 |
+
|
| 96 |
+
# Strix vuln-0003: Windows device-name reservation survives a suffix
|
| 97 |
+
# or trailing dot/space. `con.txt`, `aux.md`, `nul.`, `com1.log`, and
|
| 98 |
+
# `lpt1.txt` all still resolve to the device endpoint on Windows.
|
| 99 |
+
@pytest.mark.parametrize("name", [
|
| 100 |
+
"con.txt", "CON.TXT", "Con.Log",
|
| 101 |
+
"aux.md", "AUX.json",
|
| 102 |
+
"prn.bak",
|
| 103 |
+
"nul.", # trailing dot — Windows strips it then matches NUL
|
| 104 |
+
"com1.log", "COM9.cfg",
|
| 105 |
+
"lpt1.txt", "lpt9.ini",
|
| 106 |
+
])
|
| 107 |
+
def test_rejects_reserved_name_with_suffix_or_trailing_dot(
|
| 108 |
+
self, name: str,
|
| 109 |
+
) -> None:
|
| 110 |
+
assert not is_safe_source_name(name), (
|
| 111 |
+
f"{name!r} slipped past the Windows reserved-name normalize"
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
def test_rejects_non_string(self):
|
| 115 |
+
assert not is_safe_source_name(None) # type: ignore[arg-type]
|
| 116 |
+
assert not is_safe_source_name(123) # type: ignore[arg-type]
|
| 117 |
+
assert not is_safe_source_name(["pulsemcp"]) # type: ignore[arg-type]
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class TestValidateSourceName:
|
| 121 |
+
def test_raises_on_invalid(self):
|
| 122 |
+
with pytest.raises(ValueError, match="invalid source name"):
|
| 123 |
+
validate_source_name("C:evil")
|
| 124 |
+
|
| 125 |
+
def test_custom_field_in_error_message(self):
|
| 126 |
+
with pytest.raises(ValueError, match="invalid mcp_source name"):
|
| 127 |
+
validate_source_name("../etc/passwd", field="mcp_source")
|
| 128 |
+
|
| 129 |
+
def test_silent_on_valid(self):
|
| 130 |
+
# Must not raise.
|
| 131 |
+
validate_source_name("pulsemcp")
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
# ────────────────────────────────────────────────────────────────────
|
| 135 |
+
# Relpath validator — the H-2 attack surface
|
| 136 |
+
# ────────────────────────────────────────────────────────────────────
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class TestIsSafeRelpath:
|
| 140 |
+
@pytest.fixture()
|
| 141 |
+
def root(self, tmp_path: Path) -> Path:
|
| 142 |
+
(tmp_path / "a").mkdir()
|
| 143 |
+
(tmp_path / "a" / "foo.md").write_text("body", encoding="utf-8")
|
| 144 |
+
(tmp_path / "subdir" / "nested").mkdir(parents=True)
|
| 145 |
+
return tmp_path
|
| 146 |
+
|
| 147 |
+
@pytest.mark.parametrize("rel", [
|
| 148 |
+
"a/foo.md", # shallow
|
| 149 |
+
"subdir/nested/x.md", # nested
|
| 150 |
+
"a/b/c/d/e/f/deep.md", # very nested — no need to exist
|
| 151 |
+
"hooks/backup_on_change.py",
|
| 152 |
+
])
|
| 153 |
+
def test_accepts_safe_relative_paths(self, root: Path, rel: str):
|
| 154 |
+
assert is_safe_relpath(root, rel)
|
| 155 |
+
|
| 156 |
+
@pytest.mark.parametrize("rel", [
|
| 157 |
+
"",
|
| 158 |
+
"../etc/passwd",
|
| 159 |
+
"../../../../tmp/evil",
|
| 160 |
+
"a/../../../outside",
|
| 161 |
+
"..",
|
| 162 |
+
"a/../..",
|
| 163 |
+
])
|
| 164 |
+
def test_rejects_traversal(self, root: Path, rel: str):
|
| 165 |
+
"""H-2 regression — ``..`` components in the stored relpath."""
|
| 166 |
+
assert not is_safe_relpath(root, rel)
|
| 167 |
+
|
| 168 |
+
@pytest.mark.parametrize("rel", [
|
| 169 |
+
"/etc/passwd",
|
| 170 |
+
"/foo",
|
| 171 |
+
"\\windows\\system32",
|
| 172 |
+
"\\foo",
|
| 173 |
+
])
|
| 174 |
+
def test_rejects_absolute(self, root: Path, rel: str):
|
| 175 |
+
assert not is_safe_relpath(root, rel)
|
| 176 |
+
|
| 177 |
+
@pytest.mark.parametrize("rel", [
|
| 178 |
+
"C:evil", # drive-relative: resolves against drive C's CWD
|
| 179 |
+
"C:/foo",
|
| 180 |
+
"C:\\foo",
|
| 181 |
+
"Z:payload.md",
|
| 182 |
+
])
|
| 183 |
+
def test_rejects_windows_drive_relative(self, root: Path, rel: str):
|
| 184 |
+
"""H-3 cousin — drive-relative in a stored relpath is always wrong."""
|
| 185 |
+
assert not is_safe_relpath(root, rel)
|
| 186 |
+
|
| 187 |
+
def test_rejects_non_string(self, root: Path):
|
| 188 |
+
assert not is_safe_relpath(root, None) # type: ignore[arg-type]
|
| 189 |
+
assert not is_safe_relpath(root, 42) # type: ignore[arg-type]
|
| 190 |
+
|
| 191 |
+
def test_empty_string_rejected(self, root: Path):
|
| 192 |
+
assert not is_safe_relpath(root, "")
|
| 193 |
+
|
| 194 |
+
@pytest.mark.skipif(os.name == "nt", reason="POSIX-only: symlink requires admin on Windows")
|
| 195 |
+
def test_rejects_symlink_escape(self, tmp_path: Path):
|
| 196 |
+
"""A symlink INSIDE root that points OUTSIDE root must be caught.
|
| 197 |
+
|
| 198 |
+
Even with no ``..`` in the relpath, following a symlink to
|
| 199 |
+
/etc/passwd is traversal.
|
| 200 |
+
"""
|
| 201 |
+
outside = tmp_path / "outside"
|
| 202 |
+
outside.mkdir()
|
| 203 |
+
(outside / "secret").write_text("sensitive", encoding="utf-8")
|
| 204 |
+
|
| 205 |
+
root = tmp_path / "root"
|
| 206 |
+
root.mkdir()
|
| 207 |
+
# Symlink root/escape -> outside
|
| 208 |
+
try:
|
| 209 |
+
(root / "escape").symlink_to(outside)
|
| 210 |
+
except (OSError, NotImplementedError):
|
| 211 |
+
pytest.skip("Platform does not support symlinks in this context")
|
| 212 |
+
|
| 213 |
+
# "escape/secret" is a relative path with no ``..``, but after
|
| 214 |
+
# symlink resolution it lands at outside/secret.
|
| 215 |
+
assert not is_safe_relpath(root, "escape/secret")
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
class TestValidateRelpath:
|
| 219 |
+
def test_raises_on_traversal(self, tmp_path: Path):
|
| 220 |
+
with pytest.raises(ValueError, match="invalid relpath"):
|
| 221 |
+
validate_relpath(tmp_path, "../../etc/passwd")
|
| 222 |
+
|
| 223 |
+
def test_custom_field_in_error_message(self, tmp_path: Path):
|
| 224 |
+
with pytest.raises(ValueError, match="invalid entity_path"):
|
| 225 |
+
validate_relpath(tmp_path, "C:evil", field="entity_path")
|
| 226 |
+
|
| 227 |
+
def test_silent_on_valid(self, tmp_path: Path):
|
| 228 |
+
validate_relpath(tmp_path, "a/foo.md")
|
src/tests/test_similarity_precision_recall.py
CHANGED
|
@@ -1,314 +1,314 @@
|
|
| 1 |
-
"""
|
| 2 |
-
test_similarity_precision_recall.py -- Integration test for the intake gate's
|
| 3 |
-
similarity detection against a curated corpus.
|
| 4 |
-
|
| 5 |
-
Purpose
|
| 6 |
-
-------
|
| 7 |
-
The intake gate's usefulness depends on two numbers:
|
| 8 |
-
|
| 9 |
-
- **Recall** on near-duplicates: when two skills genuinely overlap, the
|
| 10 |
-
gate must flag at least 90% of them (``DUPLICATE`` or
|
| 11 |
-
``NEAR_DUPLICATE``). Missed duplicates let redundant skills into the
|
| 12 |
-
corpus, which is the whole failure mode the gate exists to prevent.
|
| 13 |
-
|
| 14 |
-
- **Precision** against distinct and adversarial pairs: when two
|
| 15 |
-
skills are genuinely different, the gate must *not* flag them. False
|
| 16 |
-
positives block legitimate skills and train users to override the
|
| 17 |
-
gate — the worst failure mode.
|
| 18 |
-
|
| 19 |
-
This test runs all three fixture sets (30 near-duplicates, 30 distinct,
|
| 20 |
-
10 adversarial) through the real embedder and asserts precision/recall
|
| 21 |
-
≥ 0.90.
|
| 22 |
-
|
| 23 |
-
Tuning workflow
|
| 24 |
-
---------------
|
| 25 |
-
Fixtures are hand-written under ``src/tests/fixtures/similarity/``. If
|
| 26 |
-
the test fails:
|
| 27 |
-
|
| 28 |
-
1. Read the per-pair breakdown printed on failure — each misclassified
|
| 29 |
-
pair lists its cosine score and reasoning.
|
| 30 |
-
2. Adjust ``intake_dup_threshold`` / ``intake_near_dup_threshold`` in
|
| 31 |
-
``config.json`` (documented as tunable in ``ctx_config.py``).
|
| 32 |
-
3. Re-run.
|
| 33 |
-
|
| 34 |
-
If tuning thresholds cannot hit 0.9 on both axes, the bug is upstream —
|
| 35 |
-
either ``compose_corpus_text`` is dropping signal, or the fixtures need
|
| 36 |
-
revision. Do not lower the 0.9 bar without a plan.
|
| 37 |
-
|
| 38 |
-
Markers
|
| 39 |
-
-------
|
| 40 |
-
Marked ``@pytest.mark.integration`` because it loads the real MiniLM
|
| 41 |
-
model (~100MB on first run). Skip in fast CI with ``-m 'not integration'``.
|
| 42 |
-
"""
|
| 43 |
-
|
| 44 |
-
from __future__ import annotations
|
| 45 |
-
|
| 46 |
-
import json
|
| 47 |
-
import os
|
| 48 |
-
import sys
|
| 49 |
-
from dataclasses import dataclass
|
| 50 |
-
from pathlib import Path
|
| 51 |
-
|
| 52 |
-
import pytest
|
| 53 |
-
|
| 54 |
-
SRC_DIR = Path(__file__).resolve().parents[1]
|
| 55 |
-
if str(SRC_DIR) not in sys.path:
|
| 56 |
-
sys.path.insert(0, str(SRC_DIR))
|
| 57 |
-
|
| 58 |
-
from corpus_cache import CorpusCache # noqa: E402
|
| 59 |
-
from cosine_ranker import CosineRanker # noqa: E402
|
| 60 |
-
from ctx_config import cfg # noqa: E402
|
| 61 |
-
from intake_gate import compose_corpus_text, run_intake_gate # noqa: E402
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
FIXTURE_DIR = Path(__file__).parent / "fixtures" / "similarity"
|
| 65 |
-
|
| 66 |
-
# Minimum precision and recall the gate must clear to be shipped.
|
| 67 |
-
# Raising these is easy; lowering them requires a plan, not a fixup.
|
| 68 |
-
_MIN_PRECISION = 0.90
|
| 69 |
-
_MIN_RECALL = 0.90
|
| 70 |
-
_REQUIRE_SIMILARITY_EVAL = os.environ.get("CTX_REQUIRE_SIMILARITY_EVAL") == "1"
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
# ────────────────────────────────────────────────────────────────────
|
| 74 |
-
# Fixture loading
|
| 75 |
-
# ────────────────────────────────────────────────────────────────────
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
@dataclass(frozen=True)
|
| 79 |
-
class _Pair:
|
| 80 |
-
id: str
|
| 81 |
-
label: str # "near_duplicate" | "distinct" | "adversarial"
|
| 82 |
-
a_md: str
|
| 83 |
-
b_md: str
|
| 84 |
-
note: str
|
| 85 |
-
|
| 86 |
-
@property
|
| 87 |
-
def should_flag(self) -> bool:
|
| 88 |
-
"""A pair should be flagged iff its label is near_duplicate.
|
| 89 |
-
|
| 90 |
-
Distinct and adversarial pairs must pass unflagged — they exist
|
| 91 |
-
to prove the gate does not false-positive on legitimate skills.
|
| 92 |
-
"""
|
| 93 |
-
return self.label == "near_duplicate"
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
def _compose_md(entry: dict) -> str:
|
| 97 |
-
"""Build a full markdown document from a fixture entry.
|
| 98 |
-
|
| 99 |
-
Fixture files store only the semantic content (name, description,
|
| 100 |
-
body) so they stay focused and editable. This helper assembles the
|
| 101 |
-
full markdown with frontmatter + H1 so structural checks pass.
|
| 102 |
-
"""
|
| 103 |
-
name = entry["name"]
|
| 104 |
-
description = entry["description"]
|
| 105 |
-
body = entry["body"]
|
| 106 |
-
return (
|
| 107 |
-
"---\n"
|
| 108 |
-
f"name: {name}\n"
|
| 109 |
-
f"description: {description}\n"
|
| 110 |
-
"---\n"
|
| 111 |
-
f"# {name}\n\n"
|
| 112 |
-
f"{body}\n"
|
| 113 |
-
)
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
def _load_pairs(filename: str) -> list[_Pair]:
|
| 117 |
-
path = FIXTURE_DIR / filename
|
| 118 |
-
if not path.exists():
|
| 119 |
-
pytest.fail(f"tracked fixture file missing: {path}")
|
| 120 |
-
pairs: list[_Pair] = []
|
| 121 |
-
for line_num, raw in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
|
| 122 |
-
raw = raw.strip()
|
| 123 |
-
if not raw or raw.startswith("#"):
|
| 124 |
-
continue
|
| 125 |
-
try:
|
| 126 |
-
entry = json.loads(raw)
|
| 127 |
-
except json.JSONDecodeError as exc:
|
| 128 |
-
pytest.fail(f"{path}:{line_num} invalid JSON: {exc}")
|
| 129 |
-
pairs.append(_Pair(
|
| 130 |
-
id=entry["id"],
|
| 131 |
-
label=entry["label"],
|
| 132 |
-
a_md=_compose_md(entry["a"]),
|
| 133 |
-
b_md=_compose_md(entry["b"]),
|
| 134 |
-
note=entry.get("note", ""),
|
| 135 |
-
))
|
| 136 |
-
return pairs
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
# ───────────────────────────────────────
|
| 140 |
-
# Per-pair evaluation
|
| 141 |
-
# ────────────────────────────────────────────────────────────────────
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
@dataclass(frozen=True)
|
| 145 |
-
class _Outcome:
|
| 146 |
-
pair: _Pair
|
| 147 |
-
flagged: bool
|
| 148 |
-
top_score: float
|
| 149 |
-
top_code: str # "DUPLICATE" | "NEAR_DUPLICATE" | "" when not flagged
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
def _evaluate_pair(pair: _Pair, embedder, cache_root: Path) -> _Outcome:
|
| 153 |
-
"""Record A, check B, return whether B was flagged against A.
|
| 154 |
-
|
| 155 |
-
Each pair gets its own CorpusCache namespace so earlier pairs don't
|
| 156 |
-
leak into later ones. The embedder is reused across pairs — loading
|
| 157 |
-
MiniLM is the dominant cost, and it's immutable for this run.
|
| 158 |
-
"""
|
| 159 |
-
cache = CorpusCache(f"fixture-{pair.id}", root=cache_root)
|
| 160 |
-
|
| 161 |
-
# Record A into the per-pair cache.
|
| 162 |
-
a_text = compose_corpus_text(pair.a_md)
|
| 163 |
-
a_vec = embedder.embed([a_text])[0]
|
| 164 |
-
cache.put(f"{pair.id}-a", a_text, a_vec)
|
| 165 |
-
|
| 166 |
-
# Rank B against the single-entry corpus.
|
| 167 |
-
ranker = CosineRanker.from_cache(cache)
|
| 168 |
-
config = cfg.build_intake_config()
|
| 169 |
-
decision = run_intake_gate(
|
| 170 |
-
pair.b_md,
|
| 171 |
-
embedder=embedder,
|
| 172 |
-
ranker=ranker,
|
| 173 |
-
config=config,
|
| 174 |
-
)
|
| 175 |
-
|
| 176 |
-
codes = {f.code for f in decision.findings}
|
| 177 |
-
flagged = "DUPLICATE" in codes or "NEAR_DUPLICATE" in codes
|
| 178 |
-
top_score = decision.nearest[0].score if decision.nearest else 0.0
|
| 179 |
-
top_code = (
|
| 180 |
-
"DUPLICATE" if "DUPLICATE" in codes
|
| 181 |
-
else "NEAR_DUPLICATE" if "NEAR_DUPLICATE" in codes
|
| 182 |
-
else ""
|
| 183 |
-
)
|
| 184 |
-
return _Outcome(pair=pair, flagged=flagged, top_score=float(top_score), top_code=top_code)
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
# ────────────────────────────────────────────────────────────────────
|
| 188 |
-
# Module-scoped setup — embedder loads once
|
| 189 |
-
# ────────────────────────────────────────────────────────────────────
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
@pytest.fixture(scope="module")
|
| 193 |
-
def _embedder():
|
| 194 |
-
"""Load the real configured embedder once per module run.
|
| 195 |
-
|
| 196 |
-
Local runs may skip when the embedding backend is unavailable. The
|
| 197 |
-
dedicated CI similarity gate sets CTX_REQUIRE_SIMILARITY_EVAL=1, in
|
| 198 |
-
which case dependency/model setup failures are hard failures.
|
| 199 |
-
"""
|
| 200 |
-
try:
|
| 201 |
-
import sentence_transformers # noqa: F401
|
| 202 |
-
except ImportError as exc:
|
| 203 |
-
message = f"sentence-transformers is required for similarity evaluation: {exc}"
|
| 204 |
-
if _REQUIRE_SIMILARITY_EVAL:
|
| 205 |
-
pytest.fail(message)
|
| 206 |
-
pytest.skip(message)
|
| 207 |
-
try:
|
| 208 |
-
return cfg.build_intake_embedder()
|
| 209 |
-
except Exception as exc: # noqa: BLE001 - fail/skip policy depends on CI mode
|
| 210 |
-
message = f"cannot build intake embedder: {exc}"
|
| 211 |
-
if _REQUIRE_SIMILARITY_EVAL:
|
| 212 |
-
pytest.fail(message)
|
| 213 |
-
pytest.skip(message)
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
@pytest.fixture
|
| 217 |
-
def _tmp_cache_root(tmp_path, monkeypatch):
|
| 218 |
-
"""Isolate cache writes so tests never touch ~/.claude."""
|
| 219 |
-
root = tmp_path / "intake-cache"
|
| 220 |
-
root.mkdir()
|
| 221 |
-
monkeypatch.setattr(cfg, "intake_cache_root", root)
|
| 222 |
-
return root
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
# ────────────────────────────────────────────────────────────────────
|
| 226 |
-
# The three fixture sets — evaluated together for precision/recall
|
| 227 |
-
# ────────────────────────────────────────────────────────────────────
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
@pytest.mark.integration
|
| 231 |
-
def test_similarity_precision_and_recall(_embedder, _tmp_cache_root):
|
| 232 |
-
"""Precision and recall across the full curated fixture set.
|
| 233 |
-
|
| 234 |
-
Confusion matrix:
|
| 235 |
-
TP = near_duplicate pairs correctly flagged
|
| 236 |
-
FN = near_duplicate pairs NOT flagged (missed duplicates)
|
| 237 |
-
FP = distinct or adversarial pairs incorrectly flagged
|
| 238 |
-
TN = distinct or adversarial pairs correctly passed
|
| 239 |
-
|
| 240 |
-
precision = TP / (TP + FP)
|
| 241 |
-
recall = TP / (TP + FN)
|
| 242 |
-
"""
|
| 243 |
-
near = _load_pairs("near_duplicates.jsonl")
|
| 244 |
-
distinct = _load_pairs("distinct_pairs.jsonl")
|
| 245 |
-
adversarial = _load_pairs("adversarial.jsonl")
|
| 246 |
-
|
| 247 |
-
# Sanity-check fixture counts so a truncated JSONL doesn't silently
|
| 248 |
-
# lower the bar the test claims to enforce.
|
| 249 |
-
assert len(near) == 30, f"expected 30 near-duplicate pairs, got {len(near)}"
|
| 250 |
-
assert len(distinct) == 30, f"expected 30 distinct pairs, got {len(distinct)}"
|
| 251 |
-
assert len(adversarial) == 10, f"expected 10 adversarial pairs, got {len(adversarial)}"
|
| 252 |
-
|
| 253 |
-
all_pairs = near + distinct + adversarial
|
| 254 |
-
outcomes = [_evaluate_pair(p, _embedder, _tmp_cache_root) for p in all_pairs]
|
| 255 |
-
|
| 256 |
-
tp = sum(1 for o in outcomes if o.pair.should_flag and o.flagged)
|
| 257 |
-
fn = sum(1 for o in outcomes if o.pair.should_flag and not o.flagged)
|
| 258 |
-
fp = sum(1 for o in outcomes if not o.pair.should_flag and o.flagged)
|
| 259 |
-
tn = sum(1 for o in outcomes if not o.pair.should_flag and not o.flagged)
|
| 260 |
-
|
| 261 |
-
precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0
|
| 262 |
-
recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0
|
| 263 |
-
|
| 264 |
-
# Per-pair breakdown in the failure message so tuning is data-driven.
|
| 265 |
-
misses = [o for o in outcomes if o.pair.should_flag and not o.flagged]
|
| 266 |
-
false_pos = [o for o in outcomes if not o.pair.should_flag and o.flagged]
|
| 267 |
-
|
| 268 |
-
failure_lines = [
|
| 269 |
-
f"precision={precision:.3f} (need >= {_MIN_PRECISION})",
|
| 270 |
-
f"recall={recall:.3f} (need >= {_MIN_RECALL})",
|
| 271 |
-
f"TP={tp} FN={fn} FP={fp} TN={tn}",
|
| 272 |
-
"",
|
| 273 |
-
]
|
| 274 |
-
if misses:
|
| 275 |
-
failure_lines.append(f"Missed duplicates ({len(misses)}):")
|
| 276 |
-
for o in misses:
|
| 277 |
-
failure_lines.append(
|
| 278 |
-
f" {o.pair.id}: top_score={o.top_score:.3f} label={o.pair.label}"
|
| 279 |
-
)
|
| 280 |
-
if false_pos:
|
| 281 |
-
failure_lines.append(f"False positives ({len(false_pos)}):")
|
| 282 |
-
for o in false_pos:
|
| 283 |
-
failure_lines.append(
|
| 284 |
-
f" {o.pair.id}: top_score={o.top_score:.3f} "
|
| 285 |
-
f"flagged={o.top_code} label={o.pair.label}"
|
| 286 |
-
)
|
| 287 |
-
message = "\n".join(failure_lines)
|
| 288 |
-
|
| 289 |
-
assert recall >= _MIN_RECALL, message
|
| 290 |
-
assert precision >= _MIN_PRECISION, message
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
def test_fixture_schema_integrity():
|
| 294 |
-
"""Fail fast if any fixture file is malformed — catches JSONL typos
|
| 295 |
-
without having to load the embedder.
|
| 296 |
-
"""
|
| 297 |
-
for filename, expected_label in [
|
| 298 |
-
("near_duplicates.jsonl", "near_duplicate"),
|
| 299 |
-
("distinct_pairs.jsonl", "distinct"),
|
| 300 |
-
("adversarial.jsonl", "adversarial"),
|
| 301 |
-
]:
|
| 302 |
-
pairs = _load_pairs(filename)
|
| 303 |
-
for p in pairs:
|
| 304 |
-
assert p.label == expected_label, (
|
| 305 |
-
f"{filename} contains pair {p.id!r} labeled "
|
| 306 |
-
f"{p.label!r}, expected {expected_label!r}"
|
| 307 |
-
)
|
| 308 |
-
# Structural minimum: description + H1 + H2 + enough body.
|
| 309 |
-
# If these fail the intake gate will reject on structure
|
| 310 |
-
# before similarity is even checked, poisoning recall.
|
| 311 |
-
assert "description:" in p.a_md
|
| 312 |
-
assert "description:" in p.b_md
|
| 313 |
-
assert "## " in p.a_md
|
| 314 |
-
assert "## " in p.b_md
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_similarity_precision_recall.py -- Integration test for the intake gate's
|
| 3 |
+
similarity detection against a curated corpus.
|
| 4 |
+
|
| 5 |
+
Purpose
|
| 6 |
+
-------
|
| 7 |
+
The intake gate's usefulness depends on two numbers:
|
| 8 |
+
|
| 9 |
+
- **Recall** on near-duplicates: when two skills genuinely overlap, the
|
| 10 |
+
gate must flag at least 90% of them (``DUPLICATE`` or
|
| 11 |
+
``NEAR_DUPLICATE``). Missed duplicates let redundant skills into the
|
| 12 |
+
corpus, which is the whole failure mode the gate exists to prevent.
|
| 13 |
+
|
| 14 |
+
- **Precision** against distinct and adversarial pairs: when two
|
| 15 |
+
skills are genuinely different, the gate must *not* flag them. False
|
| 16 |
+
positives block legitimate skills and train users to override the
|
| 17 |
+
gate — the worst failure mode.
|
| 18 |
+
|
| 19 |
+
This test runs all three fixture sets (30 near-duplicates, 30 distinct,
|
| 20 |
+
10 adversarial) through the real embedder and asserts precision/recall
|
| 21 |
+
≥ 0.90.
|
| 22 |
+
|
| 23 |
+
Tuning workflow
|
| 24 |
+
---------------
|
| 25 |
+
Fixtures are hand-written under ``src/tests/fixtures/similarity/``. If
|
| 26 |
+
the test fails:
|
| 27 |
+
|
| 28 |
+
1. Read the per-pair breakdown printed on failure — each misclassified
|
| 29 |
+
pair lists its cosine score and reasoning.
|
| 30 |
+
2. Adjust ``intake_dup_threshold`` / ``intake_near_dup_threshold`` in
|
| 31 |
+
``config.json`` (documented as tunable in ``ctx_config.py``).
|
| 32 |
+
3. Re-run.
|
| 33 |
+
|
| 34 |
+
If tuning thresholds cannot hit 0.9 on both axes, the bug is upstream —
|
| 35 |
+
either ``compose_corpus_text`` is dropping signal, or the fixtures need
|
| 36 |
+
revision. Do not lower the 0.9 bar without a plan.
|
| 37 |
+
|
| 38 |
+
Markers
|
| 39 |
+
-------
|
| 40 |
+
Marked ``@pytest.mark.integration`` because it loads the real MiniLM
|
| 41 |
+
model (~100MB on first run). Skip in fast CI with ``-m 'not integration'``.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
from __future__ import annotations
|
| 45 |
+
|
| 46 |
+
import json
|
| 47 |
+
import os
|
| 48 |
+
import sys
|
| 49 |
+
from dataclasses import dataclass
|
| 50 |
+
from pathlib import Path
|
| 51 |
+
|
| 52 |
+
import pytest
|
| 53 |
+
|
| 54 |
+
SRC_DIR = Path(__file__).resolve().parents[1]
|
| 55 |
+
if str(SRC_DIR) not in sys.path:
|
| 56 |
+
sys.path.insert(0, str(SRC_DIR))
|
| 57 |
+
|
| 58 |
+
from corpus_cache import CorpusCache # noqa: E402
|
| 59 |
+
from cosine_ranker import CosineRanker # noqa: E402
|
| 60 |
+
from ctx_config import cfg # noqa: E402
|
| 61 |
+
from intake_gate import compose_corpus_text, run_intake_gate # noqa: E402
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
FIXTURE_DIR = Path(__file__).parent / "fixtures" / "similarity"
|
| 65 |
+
|
| 66 |
+
# Minimum precision and recall the gate must clear to be shipped.
|
| 67 |
+
# Raising these is easy; lowering them requires a plan, not a fixup.
|
| 68 |
+
_MIN_PRECISION = 0.90
|
| 69 |
+
_MIN_RECALL = 0.90
|
| 70 |
+
_REQUIRE_SIMILARITY_EVAL = os.environ.get("CTX_REQUIRE_SIMILARITY_EVAL") == "1"
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# ────────────────────────────────────────────────────────────────────
|
| 74 |
+
# Fixture loading
|
| 75 |
+
# ────────────────────────────────────────────────────────────────────
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@dataclass(frozen=True)
|
| 79 |
+
class _Pair:
|
| 80 |
+
id: str
|
| 81 |
+
label: str # "near_duplicate" | "distinct" | "adversarial"
|
| 82 |
+
a_md: str
|
| 83 |
+
b_md: str
|
| 84 |
+
note: str
|
| 85 |
+
|
| 86 |
+
@property
|
| 87 |
+
def should_flag(self) -> bool:
|
| 88 |
+
"""A pair should be flagged iff its label is near_duplicate.
|
| 89 |
+
|
| 90 |
+
Distinct and adversarial pairs must pass unflagged — they exist
|
| 91 |
+
to prove the gate does not false-positive on legitimate skills.
|
| 92 |
+
"""
|
| 93 |
+
return self.label == "near_duplicate"
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _compose_md(entry: dict) -> str:
|
| 97 |
+
"""Build a full markdown document from a fixture entry.
|
| 98 |
+
|
| 99 |
+
Fixture files store only the semantic content (name, description,
|
| 100 |
+
body) so they stay focused and editable. This helper assembles the
|
| 101 |
+
full markdown with frontmatter + H1 so structural checks pass.
|
| 102 |
+
"""
|
| 103 |
+
name = entry["name"]
|
| 104 |
+
description = entry["description"]
|
| 105 |
+
body = entry["body"]
|
| 106 |
+
return (
|
| 107 |
+
"---\n"
|
| 108 |
+
f"name: {name}\n"
|
| 109 |
+
f"description: {description}\n"
|
| 110 |
+
"---\n"
|
| 111 |
+
f"# {name}\n\n"
|
| 112 |
+
f"{body}\n"
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _load_pairs(filename: str) -> list[_Pair]:
|
| 117 |
+
path = FIXTURE_DIR / filename
|
| 118 |
+
if not path.exists():
|
| 119 |
+
pytest.fail(f"tracked fixture file missing: {path}")
|
| 120 |
+
pairs: list[_Pair] = []
|
| 121 |
+
for line_num, raw in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
|
| 122 |
+
raw = raw.strip()
|
| 123 |
+
if not raw or raw.startswith("#"):
|
| 124 |
+
continue
|
| 125 |
+
try:
|
| 126 |
+
entry = json.loads(raw)
|
| 127 |
+
except json.JSONDecodeError as exc:
|
| 128 |
+
pytest.fail(f"{path}:{line_num} invalid JSON: {exc}")
|
| 129 |
+
pairs.append(_Pair(
|
| 130 |
+
id=entry["id"],
|
| 131 |
+
label=entry["label"],
|
| 132 |
+
a_md=_compose_md(entry["a"]),
|
| 133 |
+
b_md=_compose_md(entry["b"]),
|
| 134 |
+
note=entry.get("note", ""),
|
| 135 |
+
))
|
| 136 |
+
return pairs
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
# ────────────────────────────────────────────────────────────────────
|
| 140 |
+
# Per-pair evaluation
|
| 141 |
+
# ────────────────────────────────────────────────────────────────────
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@dataclass(frozen=True)
|
| 145 |
+
class _Outcome:
|
| 146 |
+
pair: _Pair
|
| 147 |
+
flagged: bool
|
| 148 |
+
top_score: float
|
| 149 |
+
top_code: str # "DUPLICATE" | "NEAR_DUPLICATE" | "" when not flagged
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _evaluate_pair(pair: _Pair, embedder, cache_root: Path) -> _Outcome:
|
| 153 |
+
"""Record A, check B, return whether B was flagged against A.
|
| 154 |
+
|
| 155 |
+
Each pair gets its own CorpusCache namespace so earlier pairs don't
|
| 156 |
+
leak into later ones. The embedder is reused across pairs — loading
|
| 157 |
+
MiniLM is the dominant cost, and it's immutable for this run.
|
| 158 |
+
"""
|
| 159 |
+
cache = CorpusCache(f"fixture-{pair.id}", root=cache_root)
|
| 160 |
+
|
| 161 |
+
# Record A into the per-pair cache.
|
| 162 |
+
a_text = compose_corpus_text(pair.a_md)
|
| 163 |
+
a_vec = embedder.embed([a_text])[0]
|
| 164 |
+
cache.put(f"{pair.id}-a", a_text, a_vec)
|
| 165 |
+
|
| 166 |
+
# Rank B against the single-entry corpus.
|
| 167 |
+
ranker = CosineRanker.from_cache(cache)
|
| 168 |
+
config = cfg.build_intake_config()
|
| 169 |
+
decision = run_intake_gate(
|
| 170 |
+
pair.b_md,
|
| 171 |
+
embedder=embedder,
|
| 172 |
+
ranker=ranker,
|
| 173 |
+
config=config,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
codes = {f.code for f in decision.findings}
|
| 177 |
+
flagged = "DUPLICATE" in codes or "NEAR_DUPLICATE" in codes
|
| 178 |
+
top_score = decision.nearest[0].score if decision.nearest else 0.0
|
| 179 |
+
top_code = (
|
| 180 |
+
"DUPLICATE" if "DUPLICATE" in codes
|
| 181 |
+
else "NEAR_DUPLICATE" if "NEAR_DUPLICATE" in codes
|
| 182 |
+
else ""
|
| 183 |
+
)
|
| 184 |
+
return _Outcome(pair=pair, flagged=flagged, top_score=float(top_score), top_code=top_code)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
# ────────────────────────────────────────────────────────────────────
|
| 188 |
+
# Module-scoped setup — embedder loads once
|
| 189 |
+
# ────────────────────────────────────────────────────────────────────
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
@pytest.fixture(scope="module")
|
| 193 |
+
def _embedder():
|
| 194 |
+
"""Load the real configured embedder once per module run.
|
| 195 |
+
|
| 196 |
+
Local runs may skip when the embedding backend is unavailable. The
|
| 197 |
+
dedicated CI similarity gate sets CTX_REQUIRE_SIMILARITY_EVAL=1, in
|
| 198 |
+
which case dependency/model setup failures are hard failures.
|
| 199 |
+
"""
|
| 200 |
+
try:
|
| 201 |
+
import sentence_transformers # noqa: F401
|
| 202 |
+
except ImportError as exc:
|
| 203 |
+
message = f"sentence-transformers is required for similarity evaluation: {exc}"
|
| 204 |
+
if _REQUIRE_SIMILARITY_EVAL:
|
| 205 |
+
pytest.fail(message)
|
| 206 |
+
pytest.skip(message)
|
| 207 |
+
try:
|
| 208 |
+
return cfg.build_intake_embedder()
|
| 209 |
+
except Exception as exc: # noqa: BLE001 - fail/skip policy depends on CI mode
|
| 210 |
+
message = f"cannot build intake embedder: {exc}"
|
| 211 |
+
if _REQUIRE_SIMILARITY_EVAL:
|
| 212 |
+
pytest.fail(message)
|
| 213 |
+
pytest.skip(message)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
@pytest.fixture
|
| 217 |
+
def _tmp_cache_root(tmp_path, monkeypatch):
|
| 218 |
+
"""Isolate cache writes so tests never touch ~/.claude."""
|
| 219 |
+
root = tmp_path / "intake-cache"
|
| 220 |
+
root.mkdir()
|
| 221 |
+
monkeypatch.setattr(cfg, "intake_cache_root", root)
|
| 222 |
+
return root
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
# ────────────────────────────────────────────────────────────────────
|
| 226 |
+
# The three fixture sets — evaluated together for precision/recall
|
| 227 |
+
# ────────────────────────────────────────────────────────────────────
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
@pytest.mark.integration
|
| 231 |
+
def test_similarity_precision_and_recall(_embedder, _tmp_cache_root):
|
| 232 |
+
"""Precision and recall across the full curated fixture set.
|
| 233 |
+
|
| 234 |
+
Confusion matrix:
|
| 235 |
+
TP = near_duplicate pairs correctly flagged
|
| 236 |
+
FN = near_duplicate pairs NOT flagged (missed duplicates)
|
| 237 |
+
FP = distinct or adversarial pairs incorrectly flagged
|
| 238 |
+
TN = distinct or adversarial pairs correctly passed
|
| 239 |
+
|
| 240 |
+
precision = TP / (TP + FP)
|
| 241 |
+
recall = TP / (TP + FN)
|
| 242 |
+
"""
|
| 243 |
+
near = _load_pairs("near_duplicates.jsonl")
|
| 244 |
+
distinct = _load_pairs("distinct_pairs.jsonl")
|
| 245 |
+
adversarial = _load_pairs("adversarial.jsonl")
|
| 246 |
+
|
| 247 |
+
# Sanity-check fixture counts so a truncated JSONL doesn't silently
|
| 248 |
+
# lower the bar the test claims to enforce.
|
| 249 |
+
assert len(near) == 30, f"expected 30 near-duplicate pairs, got {len(near)}"
|
| 250 |
+
assert len(distinct) == 30, f"expected 30 distinct pairs, got {len(distinct)}"
|
| 251 |
+
assert len(adversarial) == 10, f"expected 10 adversarial pairs, got {len(adversarial)}"
|
| 252 |
+
|
| 253 |
+
all_pairs = near + distinct + adversarial
|
| 254 |
+
outcomes = [_evaluate_pair(p, _embedder, _tmp_cache_root) for p in all_pairs]
|
| 255 |
+
|
| 256 |
+
tp = sum(1 for o in outcomes if o.pair.should_flag and o.flagged)
|
| 257 |
+
fn = sum(1 for o in outcomes if o.pair.should_flag and not o.flagged)
|
| 258 |
+
fp = sum(1 for o in outcomes if not o.pair.should_flag and o.flagged)
|
| 259 |
+
tn = sum(1 for o in outcomes if not o.pair.should_flag and not o.flagged)
|
| 260 |
+
|
| 261 |
+
precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0
|
| 262 |
+
recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0
|
| 263 |
+
|
| 264 |
+
# Per-pair breakdown in the failure message so tuning is data-driven.
|
| 265 |
+
misses = [o for o in outcomes if o.pair.should_flag and not o.flagged]
|
| 266 |
+
false_pos = [o for o in outcomes if not o.pair.should_flag and o.flagged]
|
| 267 |
+
|
| 268 |
+
failure_lines = [
|
| 269 |
+
f"precision={precision:.3f} (need >= {_MIN_PRECISION})",
|
| 270 |
+
f"recall={recall:.3f} (need >= {_MIN_RECALL})",
|
| 271 |
+
f"TP={tp} FN={fn} FP={fp} TN={tn}",
|
| 272 |
+
"",
|
| 273 |
+
]
|
| 274 |
+
if misses:
|
| 275 |
+
failure_lines.append(f"Missed duplicates ({len(misses)}):")
|
| 276 |
+
for o in misses:
|
| 277 |
+
failure_lines.append(
|
| 278 |
+
f" {o.pair.id}: top_score={o.top_score:.3f} label={o.pair.label}"
|
| 279 |
+
)
|
| 280 |
+
if false_pos:
|
| 281 |
+
failure_lines.append(f"False positives ({len(false_pos)}):")
|
| 282 |
+
for o in false_pos:
|
| 283 |
+
failure_lines.append(
|
| 284 |
+
f" {o.pair.id}: top_score={o.top_score:.3f} "
|
| 285 |
+
f"flagged={o.top_code} label={o.pair.label}"
|
| 286 |
+
)
|
| 287 |
+
message = "\n".join(failure_lines)
|
| 288 |
+
|
| 289 |
+
assert recall >= _MIN_RECALL, message
|
| 290 |
+
assert precision >= _MIN_PRECISION, message
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def test_fixture_schema_integrity():
|
| 294 |
+
"""Fail fast if any fixture file is malformed — catches JSONL typos
|
| 295 |
+
without having to load the embedder.
|
| 296 |
+
"""
|
| 297 |
+
for filename, expected_label in [
|
| 298 |
+
("near_duplicates.jsonl", "near_duplicate"),
|
| 299 |
+
("distinct_pairs.jsonl", "distinct"),
|
| 300 |
+
("adversarial.jsonl", "adversarial"),
|
| 301 |
+
]:
|
| 302 |
+
pairs = _load_pairs(filename)
|
| 303 |
+
for p in pairs:
|
| 304 |
+
assert p.label == expected_label, (
|
| 305 |
+
f"{filename} contains pair {p.id!r} labeled "
|
| 306 |
+
f"{p.label!r}, expected {expected_label!r}"
|
| 307 |
+
)
|
| 308 |
+
# Structural minimum: description + H1 + H2 + enough body.
|
| 309 |
+
# If these fail the intake gate will reject on structure
|
| 310 |
+
# before similarity is even checked, poisoning recall.
|
| 311 |
+
assert "description:" in p.a_md
|
| 312 |
+
assert "description:" in p.b_md
|
| 313 |
+
assert "## " in p.a_md
|
| 314 |
+
assert "## " in p.b_md
|
src/tests/test_skill_loader.py
CHANGED
|
@@ -1,372 +1,372 @@
|
|
| 1 |
-
"""
|
| 2 |
-
test_skill_loader.py -- Regression tests for path-traversal hardening in skill_loader.
|
| 3 |
-
|
| 4 |
-
Covers Strix vuln-0001 (CWE-22): find_skill() must reject user-controlled names that
|
| 5 |
-
contain path separators, traversal sequences, glob metacharacters, or absolute paths,
|
| 6 |
-
and must confine resolved paths to SKILLS_DIR / AGENTS_DIR.
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
from __future__ import annotations
|
| 10 |
-
|
| 11 |
-
import json
|
| 12 |
-
import importlib
|
| 13 |
-
import subprocess
|
| 14 |
-
import sys
|
| 15 |
-
import textwrap
|
| 16 |
-
from pathlib import Path
|
| 17 |
-
|
| 18 |
-
import pytest
|
| 19 |
-
|
| 20 |
-
_SRC_ROOT = Path(__file__).resolve().parents[1]
|
| 21 |
-
_MANIFEST_DASHBOARD_WORKER = r"""
|
| 22 |
-
from __future__ import annotations
|
| 23 |
-
|
| 24 |
-
import os
|
| 25 |
-
import sys
|
| 26 |
-
import time
|
| 27 |
-
from pathlib import Path
|
| 28 |
-
|
| 29 |
-
sys.path.insert(0, sys.argv[3])
|
| 30 |
-
|
| 31 |
-
home = Path(sys.argv[1])
|
| 32 |
-
start_file = Path(sys.argv[2])
|
| 33 |
-
mode = sys.argv[4]
|
| 34 |
-
slug = sys.argv[5]
|
| 35 |
-
|
| 36 |
-
os.environ["HOME"] = str(home)
|
| 37 |
-
os.environ["USERPROFILE"] = str(home)
|
| 38 |
-
|
| 39 |
-
deadline = time.monotonic() + 5.0
|
| 40 |
-
while not start_file.exists():
|
| 41 |
-
if time.monotonic() > deadline:
|
| 42 |
-
raise TimeoutError("worker did not receive start signal")
|
| 43 |
-
time.sleep(0.005)
|
| 44 |
-
|
| 45 |
-
if mode == "load":
|
| 46 |
-
from ctx.adapters.claude_code import skill_loader
|
| 47 |
-
|
| 48 |
-
original_write = skill_loader._atomic_write_text
|
| 49 |
-
|
| 50 |
-
def slow_write(path, text):
|
| 51 |
-
time.sleep(0.15)
|
| 52 |
-
original_write(path, text)
|
| 53 |
-
|
| 54 |
-
skill_loader._atomic_write_text = slow_write
|
| 55 |
-
skill_loader.update_manifest(slug, entity_type="skill")
|
| 56 |
-
elif mode == "unload":
|
| 57 |
-
from ctx.adapters.claude_code.install import skill_unload
|
| 58 |
-
|
| 59 |
-
original_save = skill_unload.save_manifest
|
| 60 |
-
|
| 61 |
-
def slow_save(manifest):
|
| 62 |
-
time.sleep(0.15)
|
| 63 |
-
original_save(manifest)
|
| 64 |
-
|
| 65 |
-
skill_unload.save_manifest = slow_save
|
| 66 |
-
skill_unload.unload_from_session([slug])
|
| 67 |
-
else:
|
| 68 |
-
raise ValueError(mode)
|
| 69 |
-
"""
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
def _run_dashboard_manifest_workers(
|
| 73 |
-
home: Path,
|
| 74 |
-
tmp_path: Path,
|
| 75 |
-
*,
|
| 76 |
-
mode: str,
|
| 77 |
-
slugs: list[str],
|
| 78 |
-
) -> None:
|
| 79 |
-
start_file = tmp_path / f"{mode}.start"
|
| 80 |
-
code = textwrap.dedent(_MANIFEST_DASHBOARD_WORKER)
|
| 81 |
-
procs = [
|
| 82 |
-
subprocess.Popen(
|
| 83 |
-
[
|
| 84 |
-
sys.executable,
|
| 85 |
-
"-c",
|
| 86 |
-
code,
|
| 87 |
-
str(home),
|
| 88 |
-
str(start_file),
|
| 89 |
-
str(_SRC_ROOT),
|
| 90 |
-
mode,
|
| 91 |
-
slug,
|
| 92 |
-
],
|
| 93 |
-
stdout=subprocess.PIPE,
|
| 94 |
-
stderr=subprocess.PIPE,
|
| 95 |
-
text=True,
|
| 96 |
-
)
|
| 97 |
-
for slug in slugs
|
| 98 |
-
]
|
| 99 |
-
start_file.write_text("go", encoding="utf-8")
|
| 100 |
-
failures: list[str] = []
|
| 101 |
-
for proc in procs:
|
| 102 |
-
stdout, stderr = proc.communicate(timeout=20)
|
| 103 |
-
if proc.returncode:
|
| 104 |
-
failures.append(f"rc={proc.returncode}\nstdout={stdout}\nstderr={stderr}")
|
| 105 |
-
assert failures == []
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
def test_dashboard_agent_unload_preserves_same_slug_skill(
|
| 109 |
-
tmp_path: Path,
|
| 110 |
-
monkeypatch: pytest.MonkeyPatch,
|
| 111 |
-
) -> None:
|
| 112 |
-
import ctx_monitor as cm
|
| 113 |
-
from ctx.adapters.claude_code.install import skill_unload
|
| 114 |
-
|
| 115 |
-
class _AuditLog:
|
| 116 |
-
@staticmethod
|
| 117 |
-
def log_skill_event(*args: object, **kwargs: object) -> None:
|
| 118 |
-
return None
|
| 119 |
-
|
| 120 |
-
claude_dir = tmp_path / ".claude"
|
| 121 |
-
manifest_path = claude_dir / "skill-manifest.json"
|
| 122 |
-
manifest_path.parent.mkdir(parents=True)
|
| 123 |
-
manifest_path.write_text(
|
| 124 |
-
json.dumps({
|
| 125 |
-
"load": [
|
| 126 |
-
{"skill": "debugger", "entity_type": "skill", "source": "seed"},
|
| 127 |
-
{"skill": "debugger", "entity_type": "agent", "source": "seed"},
|
| 128 |
-
],
|
| 129 |
-
"unload": [],
|
| 130 |
-
"warnings": [],
|
| 131 |
-
}),
|
| 132 |
-
encoding="utf-8",
|
| 133 |
-
)
|
| 134 |
-
monkeypatch.setattr(cm, "_claude_dir", lambda: claude_dir)
|
| 135 |
-
monkeypatch.setattr(skill_unload, "CLAUDE_DIR", claude_dir)
|
| 136 |
-
monkeypatch.setattr(skill_unload, "MANIFEST_PATH", manifest_path)
|
| 137 |
-
monkeypatch.setitem(sys.modules, "ctx_audit_log", _AuditLog)
|
| 138 |
-
|
| 139 |
-
ok, message = cm._perform_unload("debugger", entity_type="agent")
|
| 140 |
-
|
| 141 |
-
data = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 142 |
-
assert ok, message
|
| 143 |
-
assert data["load"] == [
|
| 144 |
-
{"skill": "debugger", "entity_type": "skill", "source": "seed"}
|
| 145 |
-
]
|
| 146 |
-
assert data["unload"] == [
|
| 147 |
-
{"skill": "debugger", "entity_type": "agent", "source": "seed"}
|
| 148 |
-
]
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
@pytest.fixture()
|
| 152 |
-
def fake_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
|
| 153 |
-
"""Reload skill_loader with a throwaway HOME so module-level paths re-resolve."""
|
| 154 |
-
home = tmp_path / "home"
|
| 155 |
-
(home / ".claude" / "skills" / "goodskill").mkdir(parents=True)
|
| 156 |
-
(home / ".claude" / "skills" / "goodskill" / "SKILL.md").write_text("# good", encoding="utf-8")
|
| 157 |
-
(home / ".claude" / "skills").mkdir(parents=True, exist_ok=True)
|
| 158 |
-
(home / ".claude" / "outside-skill").mkdir(parents=True)
|
| 159 |
-
(home / ".claude" / "outside-skill" / "SKILL.md").write_text("# outside skill", encoding="utf-8")
|
| 160 |
-
(home / ".claude" / "agents").mkdir(parents=True, exist_ok=True)
|
| 161 |
-
(home / ".claude" / "agents" / "goodagent.md").write_text("# good agent", encoding="utf-8")
|
| 162 |
-
(home / ".claude" / "outside-agent.md").write_text("# outside agent", encoding="utf-8")
|
| 163 |
-
|
| 164 |
-
monkeypatch.setenv("HOME", str(home))
|
| 165 |
-
monkeypatch.setenv("USERPROFILE", str(home)) # Windows
|
| 166 |
-
|
| 167 |
-
from ctx.adapters.claude_code import skill_loader
|
| 168 |
-
importlib.reload(skill_loader)
|
| 169 |
-
monkeypatch.setattr(skill_loader, "SKILLS_DIR", home / ".claude" / "skills")
|
| 170 |
-
monkeypatch.setattr(skill_loader, "AGENTS_DIR", home / ".claude" / "agents")
|
| 171 |
-
monkeypatch.setattr(skill_loader, "WIKI_DIR", home / ".claude" / "skill-wiki")
|
| 172 |
-
monkeypatch.setattr(
|
| 173 |
-
skill_loader,
|
| 174 |
-
"PENDING_SKILLS",
|
| 175 |
-
home / ".claude" / "pending-skills.json",
|
| 176 |
-
)
|
| 177 |
-
monkeypatch.setattr(
|
| 178 |
-
skill_loader,
|
| 179 |
-
"MANIFEST_PATH",
|
| 180 |
-
home / ".claude" / "skill-manifest.json",
|
| 181 |
-
)
|
| 182 |
-
return skill_loader, home
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
def test_valid_skill_name_resolves(fake_home):
|
| 186 |
-
loader, _ = fake_home
|
| 187 |
-
result = loader.find_skill("goodskill")
|
| 188 |
-
assert result is not None
|
| 189 |
-
assert result["type"] == "skill"
|
| 190 |
-
assert result["name"] == "goodskill"
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
def test_valid_agent_name_resolves(fake_home):
|
| 194 |
-
loader, _ = fake_home
|
| 195 |
-
result = loader.find_skill("goodagent")
|
| 196 |
-
assert result is not None
|
| 197 |
-
assert result["type"] == "agent"
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
@pytest.mark.parametrize(
|
| 201 |
-
"bad_name",
|
| 202 |
-
[
|
| 203 |
-
"../outside-skill",
|
| 204 |
-
"../outside-agent",
|
| 205 |
-
"..",
|
| 206 |
-
"../..",
|
| 207 |
-
"../../etc/passwd",
|
| 208 |
-
"foo/../bar",
|
| 209 |
-
"/absolute/path",
|
| 210 |
-
"C:/Windows/System32",
|
| 211 |
-
"**/outside-agent",
|
| 212 |
-
"*",
|
| 213 |
-
"**",
|
| 214 |
-
"?*",
|
| 215 |
-
"name\x00.md",
|
| 216 |
-
"name with space",
|
| 217 |
-
"name\nwith\nnewline",
|
| 218 |
-
"",
|
| 219 |
-
"name/",
|
| 220 |
-
"name\\windows",
|
| 221 |
-
],
|
| 222 |
-
)
|
| 223 |
-
def test_traversal_and_metachars_rejected(fake_home, bad_name):
|
| 224 |
-
"""Every traversal, glob metacharacter, separator, or absolute path must return None."""
|
| 225 |
-
loader, _ = fake_home
|
| 226 |
-
assert loader.find_skill(bad_name) is None, f"expected None for {bad_name!r}"
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
def test_rglob_pattern_cannot_escape_agents_dir(fake_home):
|
| 230 |
-
"""Strix's original rglob PoC: AGENTS_DIR.rglob('../outside-agent.md') used to match."""
|
| 231 |
-
loader, _ = fake_home
|
| 232 |
-
assert loader.find_skill("../outside-agent") is None
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
def test_validate_skill_name_accepts_common_names(fake_home):
|
| 236 |
-
loader, _ = fake_home
|
| 237 |
-
from ctx.core.wiki.wiki_utils import validate_skill_name
|
| 238 |
-
for name in ("fastapi-pro", "docker_expert", "py3.11", "a", "Aa0._-"):
|
| 239 |
-
assert validate_skill_name(name) == name
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
def test_validate_skill_name_rejects_bad(fake_home):
|
| 243 |
-
from ctx.core.wiki.wiki_utils import validate_skill_name
|
| 244 |
-
for bad in ("../x", "x/y", "*", "", "_leading", ".leading", "-leading"):
|
| 245 |
-
with pytest.raises(ValueError):
|
| 246 |
-
validate_skill_name(bad)
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
# ─────────────────────────────────────────────────────────────────────
|
| 250 |
-
# update_manifest: (slug, entity_type) tuple dedup contract
|
| 251 |
-
# ─────────────────────────────────────────────────────────────────────
|
| 252 |
-
#
|
| 253 |
-
# Code-reviewer HIGH (P2.2). Prior impl deduped on slug alone and
|
| 254 |
-
# wrote entries without an ``entity_type`` field. A same-slug
|
| 255 |
-
# skill + agent collision silently dropped one of them.
|
| 256 |
-
|
| 257 |
-
class TestUpdateManifestEntityType:
|
| 258 |
-
|
| 259 |
-
def test_writes_entity_type_field(self, fake_home):
|
| 260 |
-
loader, home = fake_home
|
| 261 |
-
manifest_path = home / ".claude" / "skill-manifest.json"
|
| 262 |
-
loader.update_manifest("goodskill", entity_type="skill")
|
| 263 |
-
data = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 264 |
-
entries = [
|
| 265 |
-
e for e in data["load"]
|
| 266 |
-
if e.get("skill") == "goodskill"
|
| 267 |
-
]
|
| 268 |
-
assert len(entries) == 1
|
| 269 |
-
assert entries[0].get("entity_type") == "skill"
|
| 270 |
-
|
| 271 |
-
def test_same_slug_skill_and_agent_coexist(self, fake_home):
|
| 272 |
-
"""The regression: before the fix, adding an agent with the same
|
| 273 |
-
slug as an already-loaded skill was silently a no-op because
|
| 274 |
-
the slug-only dedup thought the agent was already loaded."""
|
| 275 |
-
loader, home = fake_home
|
| 276 |
-
manifest_path = home / ".claude" / "skill-manifest.json"
|
| 277 |
-
loader.update_manifest("code-reviewer", entity_type="skill")
|
| 278 |
-
loader.update_manifest("code-reviewer", entity_type="agent")
|
| 279 |
-
data = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 280 |
-
pairs = {
|
| 281 |
-
(e.get("skill"), e.get("entity_type"))
|
| 282 |
-
for e in data["load"]
|
| 283 |
-
}
|
| 284 |
-
assert ("code-reviewer", "skill") in pairs
|
| 285 |
-
assert ("code-reviewer", "agent") in pairs
|
| 286 |
-
|
| 287 |
-
def test_idempotent_same_type(self, fake_home):
|
| 288 |
-
"""Calling update_manifest twice with the same (slug, type)
|
| 289 |
-
must not append a duplicate entry."""
|
| 290 |
-
loader, home = fake_home
|
| 291 |
-
manifest_path = home / ".claude" / "skill-manifest.json"
|
| 292 |
-
loader.update_manifest("goodskill", entity_type="skill")
|
| 293 |
-
loader.update_manifest("goodskill", entity_type="skill")
|
| 294 |
-
data = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 295 |
-
entries = [e for e in data["load"] if e.get("skill") == "goodskill"]
|
| 296 |
-
assert len(entries) == 1
|
| 297 |
-
|
| 298 |
-
def test_default_entity_type_is_skill(self, fake_home):
|
| 299 |
-
"""Backward compat: call sites that don't pass entity_type
|
| 300 |
-
default to ``skill`` — the pre-fix implicit contract."""
|
| 301 |
-
loader, home = fake_home
|
| 302 |
-
manifest_path = home / ".claude" / "skill-manifest.json"
|
| 303 |
-
loader.update_manifest("legacy-caller")
|
| 304 |
-
data = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 305 |
-
entry = next(e for e in data["load"] if e.get("skill") == "legacy-caller")
|
| 306 |
-
assert entry.get("entity_type") == "skill"
|
| 307 |
-
|
| 308 |
-
def test_legacy_pre_fix_manifest_entry_is_not_duplicated(self, fake_home):
|
| 309 |
-
"""If the manifest already has a pre-fix entry (no ``entity_type``
|
| 310 |
-
key, slug == ``foo``), a new ``update_manifest("foo", "skill")``
|
| 311 |
-
call must recognise it as the same pair — the missing
|
| 312 |
-
``entity_type`` in the old entry implicitly meant ``skill``."""
|
| 313 |
-
loader, home = fake_home
|
| 314 |
-
manifest_path = home / ".claude" / "skill-manifest.json"
|
| 315 |
-
manifest_path.write_text(json.dumps({
|
| 316 |
-
"load": [{"skill": "foo", "source": "legacy"}],
|
| 317 |
-
"unload": [],
|
| 318 |
-
"warnings": [],
|
| 319 |
-
}), encoding="utf-8")
|
| 320 |
-
loader.update_manifest("foo", entity_type="skill")
|
| 321 |
-
data = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 322 |
-
foo_entries = [e for e in data["load"] if e.get("skill") == "foo"]
|
| 323 |
-
assert len(foo_entries) == 1, (
|
| 324 |
-
"legacy entry got duplicated — missing entity_type should "
|
| 325 |
-
"default to 'skill' for dedup purposes"
|
| 326 |
-
)
|
| 327 |
-
|
| 328 |
-
def test_concurrent_dashboard_loads_preserve_all_manifest_entries(
|
| 329 |
-
self,
|
| 330 |
-
tmp_path: Path,
|
| 331 |
-
) -> None:
|
| 332 |
-
home = tmp_path / "home"
|
| 333 |
-
manifest_path = home / ".claude" / "skill-manifest.json"
|
| 334 |
-
manifest_path.parent.mkdir(parents=True)
|
| 335 |
-
slugs = [f"skill-{i}" for i in range(8)]
|
| 336 |
-
|
| 337 |
-
_run_dashboard_manifest_workers(home, tmp_path, mode="load", slugs=slugs)
|
| 338 |
-
|
| 339 |
-
data = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 340 |
-
loaded = {entry["skill"] for entry in data["load"]}
|
| 341 |
-
assert loaded == set(slugs)
|
| 342 |
-
|
| 343 |
-
def test_concurrent_dashboard_unloads_preserve_all_manifest_removals(
|
| 344 |
-
self,
|
| 345 |
-
tmp_path: Path,
|
| 346 |
-
) -> None:
|
| 347 |
-
home = tmp_path / "home"
|
| 348 |
-
manifest_path = home / ".claude" / "skill-manifest.json"
|
| 349 |
-
manifest_path.parent.mkdir(parents=True)
|
| 350 |
-
slugs = [f"skill-{i}" for i in range(8)]
|
| 351 |
-
manifest_path.write_text(
|
| 352 |
-
json.dumps({
|
| 353 |
-
"load": [
|
| 354 |
-
{
|
| 355 |
-
"skill": slug,
|
| 356 |
-
"entity_type": "skill",
|
| 357 |
-
"source": "seed",
|
| 358 |
-
}
|
| 359 |
-
for slug in slugs
|
| 360 |
-
],
|
| 361 |
-
"unload": [],
|
| 362 |
-
"warnings": [],
|
| 363 |
-
}),
|
| 364 |
-
encoding="utf-8",
|
| 365 |
-
)
|
| 366 |
-
|
| 367 |
-
_run_dashboard_manifest_workers(home, tmp_path, mode="unload", slugs=slugs)
|
| 368 |
-
|
| 369 |
-
data = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 370 |
-
unloaded = {entry["skill"] for entry in data["unload"]}
|
| 371 |
-
assert data["load"] == []
|
| 372 |
-
assert unloaded == set(slugs)
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_skill_loader.py -- Regression tests for path-traversal hardening in skill_loader.
|
| 3 |
+
|
| 4 |
+
Covers Strix vuln-0001 (CWE-22): find_skill() must reject user-controlled names that
|
| 5 |
+
contain path separators, traversal sequences, glob metacharacters, or absolute paths,
|
| 6 |
+
and must confine resolved paths to SKILLS_DIR / AGENTS_DIR.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
import importlib
|
| 13 |
+
import subprocess
|
| 14 |
+
import sys
|
| 15 |
+
import textwrap
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import pytest
|
| 19 |
+
|
| 20 |
+
_SRC_ROOT = Path(__file__).resolve().parents[1]
|
| 21 |
+
_MANIFEST_DASHBOARD_WORKER = r"""
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
|
| 24 |
+
import os
|
| 25 |
+
import sys
|
| 26 |
+
import time
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
sys.path.insert(0, sys.argv[3])
|
| 30 |
+
|
| 31 |
+
home = Path(sys.argv[1])
|
| 32 |
+
start_file = Path(sys.argv[2])
|
| 33 |
+
mode = sys.argv[4]
|
| 34 |
+
slug = sys.argv[5]
|
| 35 |
+
|
| 36 |
+
os.environ["HOME"] = str(home)
|
| 37 |
+
os.environ["USERPROFILE"] = str(home)
|
| 38 |
+
|
| 39 |
+
deadline = time.monotonic() + 5.0
|
| 40 |
+
while not start_file.exists():
|
| 41 |
+
if time.monotonic() > deadline:
|
| 42 |
+
raise TimeoutError("worker did not receive start signal")
|
| 43 |
+
time.sleep(0.005)
|
| 44 |
+
|
| 45 |
+
if mode == "load":
|
| 46 |
+
from ctx.adapters.claude_code import skill_loader
|
| 47 |
+
|
| 48 |
+
original_write = skill_loader._atomic_write_text
|
| 49 |
+
|
| 50 |
+
def slow_write(path, text):
|
| 51 |
+
time.sleep(0.15)
|
| 52 |
+
original_write(path, text)
|
| 53 |
+
|
| 54 |
+
skill_loader._atomic_write_text = slow_write
|
| 55 |
+
skill_loader.update_manifest(slug, entity_type="skill")
|
| 56 |
+
elif mode == "unload":
|
| 57 |
+
from ctx.adapters.claude_code.install import skill_unload
|
| 58 |
+
|
| 59 |
+
original_save = skill_unload.save_manifest
|
| 60 |
+
|
| 61 |
+
def slow_save(manifest):
|
| 62 |
+
time.sleep(0.15)
|
| 63 |
+
original_save(manifest)
|
| 64 |
+
|
| 65 |
+
skill_unload.save_manifest = slow_save
|
| 66 |
+
skill_unload.unload_from_session([slug])
|
| 67 |
+
else:
|
| 68 |
+
raise ValueError(mode)
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _run_dashboard_manifest_workers(
|
| 73 |
+
home: Path,
|
| 74 |
+
tmp_path: Path,
|
| 75 |
+
*,
|
| 76 |
+
mode: str,
|
| 77 |
+
slugs: list[str],
|
| 78 |
+
) -> None:
|
| 79 |
+
start_file = tmp_path / f"{mode}.start"
|
| 80 |
+
code = textwrap.dedent(_MANIFEST_DASHBOARD_WORKER)
|
| 81 |
+
procs = [
|
| 82 |
+
subprocess.Popen(
|
| 83 |
+
[
|
| 84 |
+
sys.executable,
|
| 85 |
+
"-c",
|
| 86 |
+
code,
|
| 87 |
+
str(home),
|
| 88 |
+
str(start_file),
|
| 89 |
+
str(_SRC_ROOT),
|
| 90 |
+
mode,
|
| 91 |
+
slug,
|
| 92 |
+
],
|
| 93 |
+
stdout=subprocess.PIPE,
|
| 94 |
+
stderr=subprocess.PIPE,
|
| 95 |
+
text=True,
|
| 96 |
+
)
|
| 97 |
+
for slug in slugs
|
| 98 |
+
]
|
| 99 |
+
start_file.write_text("go", encoding="utf-8")
|
| 100 |
+
failures: list[str] = []
|
| 101 |
+
for proc in procs:
|
| 102 |
+
stdout, stderr = proc.communicate(timeout=20)
|
| 103 |
+
if proc.returncode:
|
| 104 |
+
failures.append(f"rc={proc.returncode}\nstdout={stdout}\nstderr={stderr}")
|
| 105 |
+
assert failures == []
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def test_dashboard_agent_unload_preserves_same_slug_skill(
|
| 109 |
+
tmp_path: Path,
|
| 110 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 111 |
+
) -> None:
|
| 112 |
+
import ctx_monitor as cm
|
| 113 |
+
from ctx.adapters.claude_code.install import skill_unload
|
| 114 |
+
|
| 115 |
+
class _AuditLog:
|
| 116 |
+
@staticmethod
|
| 117 |
+
def log_skill_event(*args: object, **kwargs: object) -> None:
|
| 118 |
+
return None
|
| 119 |
+
|
| 120 |
+
claude_dir = tmp_path / ".claude"
|
| 121 |
+
manifest_path = claude_dir / "skill-manifest.json"
|
| 122 |
+
manifest_path.parent.mkdir(parents=True)
|
| 123 |
+
manifest_path.write_text(
|
| 124 |
+
json.dumps({
|
| 125 |
+
"load": [
|
| 126 |
+
{"skill": "debugger", "entity_type": "skill", "source": "seed"},
|
| 127 |
+
{"skill": "debugger", "entity_type": "agent", "source": "seed"},
|
| 128 |
+
],
|
| 129 |
+
"unload": [],
|
| 130 |
+
"warnings": [],
|
| 131 |
+
}),
|
| 132 |
+
encoding="utf-8",
|
| 133 |
+
)
|
| 134 |
+
monkeypatch.setattr(cm, "_claude_dir", lambda: claude_dir)
|
| 135 |
+
monkeypatch.setattr(skill_unload, "CLAUDE_DIR", claude_dir)
|
| 136 |
+
monkeypatch.setattr(skill_unload, "MANIFEST_PATH", manifest_path)
|
| 137 |
+
monkeypatch.setitem(sys.modules, "ctx_audit_log", _AuditLog)
|
| 138 |
+
|
| 139 |
+
ok, message = cm._perform_unload("debugger", entity_type="agent")
|
| 140 |
+
|
| 141 |
+
data = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 142 |
+
assert ok, message
|
| 143 |
+
assert data["load"] == [
|
| 144 |
+
{"skill": "debugger", "entity_type": "skill", "source": "seed"}
|
| 145 |
+
]
|
| 146 |
+
assert data["unload"] == [
|
| 147 |
+
{"skill": "debugger", "entity_type": "agent", "source": "seed"}
|
| 148 |
+
]
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
@pytest.fixture()
|
| 152 |
+
def fake_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
|
| 153 |
+
"""Reload skill_loader with a throwaway HOME so module-level paths re-resolve."""
|
| 154 |
+
home = tmp_path / "home"
|
| 155 |
+
(home / ".claude" / "skills" / "goodskill").mkdir(parents=True)
|
| 156 |
+
(home / ".claude" / "skills" / "goodskill" / "SKILL.md").write_text("# good", encoding="utf-8")
|
| 157 |
+
(home / ".claude" / "skills").mkdir(parents=True, exist_ok=True)
|
| 158 |
+
(home / ".claude" / "outside-skill").mkdir(parents=True)
|
| 159 |
+
(home / ".claude" / "outside-skill" / "SKILL.md").write_text("# outside skill", encoding="utf-8")
|
| 160 |
+
(home / ".claude" / "agents").mkdir(parents=True, exist_ok=True)
|
| 161 |
+
(home / ".claude" / "agents" / "goodagent.md").write_text("# good agent", encoding="utf-8")
|
| 162 |
+
(home / ".claude" / "outside-agent.md").write_text("# outside agent", encoding="utf-8")
|
| 163 |
+
|
| 164 |
+
monkeypatch.setenv("HOME", str(home))
|
| 165 |
+
monkeypatch.setenv("USERPROFILE", str(home)) # Windows
|
| 166 |
+
|
| 167 |
+
from ctx.adapters.claude_code import skill_loader
|
| 168 |
+
importlib.reload(skill_loader)
|
| 169 |
+
monkeypatch.setattr(skill_loader, "SKILLS_DIR", home / ".claude" / "skills")
|
| 170 |
+
monkeypatch.setattr(skill_loader, "AGENTS_DIR", home / ".claude" / "agents")
|
| 171 |
+
monkeypatch.setattr(skill_loader, "WIKI_DIR", home / ".claude" / "skill-wiki")
|
| 172 |
+
monkeypatch.setattr(
|
| 173 |
+
skill_loader,
|
| 174 |
+
"PENDING_SKILLS",
|
| 175 |
+
home / ".claude" / "pending-skills.json",
|
| 176 |
+
)
|
| 177 |
+
monkeypatch.setattr(
|
| 178 |
+
skill_loader,
|
| 179 |
+
"MANIFEST_PATH",
|
| 180 |
+
home / ".claude" / "skill-manifest.json",
|
| 181 |
+
)
|
| 182 |
+
return skill_loader, home
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def test_valid_skill_name_resolves(fake_home):
|
| 186 |
+
loader, _ = fake_home
|
| 187 |
+
result = loader.find_skill("goodskill")
|
| 188 |
+
assert result is not None
|
| 189 |
+
assert result["type"] == "skill"
|
| 190 |
+
assert result["name"] == "goodskill"
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def test_valid_agent_name_resolves(fake_home):
|
| 194 |
+
loader, _ = fake_home
|
| 195 |
+
result = loader.find_skill("goodagent")
|
| 196 |
+
assert result is not None
|
| 197 |
+
assert result["type"] == "agent"
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
@pytest.mark.parametrize(
|
| 201 |
+
"bad_name",
|
| 202 |
+
[
|
| 203 |
+
"../outside-skill",
|
| 204 |
+
"../outside-agent",
|
| 205 |
+
"..",
|
| 206 |
+
"../..",
|
| 207 |
+
"../../etc/passwd",
|
| 208 |
+
"foo/../bar",
|
| 209 |
+
"/absolute/path",
|
| 210 |
+
"C:/Windows/System32",
|
| 211 |
+
"**/outside-agent",
|
| 212 |
+
"*",
|
| 213 |
+
"**",
|
| 214 |
+
"?*",
|
| 215 |
+
"name\x00.md",
|
| 216 |
+
"name with space",
|
| 217 |
+
"name\nwith\nnewline",
|
| 218 |
+
"",
|
| 219 |
+
"name/",
|
| 220 |
+
"name\\windows",
|
| 221 |
+
],
|
| 222 |
+
)
|
| 223 |
+
def test_traversal_and_metachars_rejected(fake_home, bad_name):
|
| 224 |
+
"""Every traversal, glob metacharacter, separator, or absolute path must return None."""
|
| 225 |
+
loader, _ = fake_home
|
| 226 |
+
assert loader.find_skill(bad_name) is None, f"expected None for {bad_name!r}"
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def test_rglob_pattern_cannot_escape_agents_dir(fake_home):
|
| 230 |
+
"""Strix's original rglob PoC: AGENTS_DIR.rglob('../outside-agent.md') used to match."""
|
| 231 |
+
loader, _ = fake_home
|
| 232 |
+
assert loader.find_skill("../outside-agent") is None
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def test_validate_skill_name_accepts_common_names(fake_home):
|
| 236 |
+
loader, _ = fake_home
|
| 237 |
+
from ctx.core.wiki.wiki_utils import validate_skill_name
|
| 238 |
+
for name in ("fastapi-pro", "docker_expert", "py3.11", "a", "Aa0._-"):
|
| 239 |
+
assert validate_skill_name(name) == name
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def test_validate_skill_name_rejects_bad(fake_home):
|
| 243 |
+
from ctx.core.wiki.wiki_utils import validate_skill_name
|
| 244 |
+
for bad in ("../x", "x/y", "*", "", "_leading", ".leading", "-leading"):
|
| 245 |
+
with pytest.raises(ValueError):
|
| 246 |
+
validate_skill_name(bad)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
# ─────────────────────────────────────────────────────────────────────
|
| 250 |
+
# update_manifest: (slug, entity_type) tuple dedup contract
|
| 251 |
+
# ─────────────────────────────────────────────────────────────────────
|
| 252 |
+
#
|
| 253 |
+
# Code-reviewer HIGH (P2.2). Prior impl deduped on slug alone and
|
| 254 |
+
# wrote entries without an ``entity_type`` field. A same-slug
|
| 255 |
+
# skill + agent collision silently dropped one of them.
|
| 256 |
+
|
| 257 |
+
class TestUpdateManifestEntityType:
|
| 258 |
+
|
| 259 |
+
def test_writes_entity_type_field(self, fake_home):
|
| 260 |
+
loader, home = fake_home
|
| 261 |
+
manifest_path = home / ".claude" / "skill-manifest.json"
|
| 262 |
+
loader.update_manifest("goodskill", entity_type="skill")
|
| 263 |
+
data = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 264 |
+
entries = [
|
| 265 |
+
e for e in data["load"]
|
| 266 |
+
if e.get("skill") == "goodskill"
|
| 267 |
+
]
|
| 268 |
+
assert len(entries) == 1
|
| 269 |
+
assert entries[0].get("entity_type") == "skill"
|
| 270 |
+
|
| 271 |
+
def test_same_slug_skill_and_agent_coexist(self, fake_home):
|
| 272 |
+
"""The regression: before the fix, adding an agent with the same
|
| 273 |
+
slug as an already-loaded skill was silently a no-op because
|
| 274 |
+
the slug-only dedup thought the agent was already loaded."""
|
| 275 |
+
loader, home = fake_home
|
| 276 |
+
manifest_path = home / ".claude" / "skill-manifest.json"
|
| 277 |
+
loader.update_manifest("code-reviewer", entity_type="skill")
|
| 278 |
+
loader.update_manifest("code-reviewer", entity_type="agent")
|
| 279 |
+
data = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 280 |
+
pairs = {
|
| 281 |
+
(e.get("skill"), e.get("entity_type"))
|
| 282 |
+
for e in data["load"]
|
| 283 |
+
}
|
| 284 |
+
assert ("code-reviewer", "skill") in pairs
|
| 285 |
+
assert ("code-reviewer", "agent") in pairs
|
| 286 |
+
|
| 287 |
+
def test_idempotent_same_type(self, fake_home):
|
| 288 |
+
"""Calling update_manifest twice with the same (slug, type)
|
| 289 |
+
must not append a duplicate entry."""
|
| 290 |
+
loader, home = fake_home
|
| 291 |
+
manifest_path = home / ".claude" / "skill-manifest.json"
|
| 292 |
+
loader.update_manifest("goodskill", entity_type="skill")
|
| 293 |
+
loader.update_manifest("goodskill", entity_type="skill")
|
| 294 |
+
data = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 295 |
+
entries = [e for e in data["load"] if e.get("skill") == "goodskill"]
|
| 296 |
+
assert len(entries) == 1
|
| 297 |
+
|
| 298 |
+
def test_default_entity_type_is_skill(self, fake_home):
|
| 299 |
+
"""Backward compat: call sites that don't pass entity_type
|
| 300 |
+
default to ``skill`` — the pre-fix implicit contract."""
|
| 301 |
+
loader, home = fake_home
|
| 302 |
+
manifest_path = home / ".claude" / "skill-manifest.json"
|
| 303 |
+
loader.update_manifest("legacy-caller")
|
| 304 |
+
data = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 305 |
+
entry = next(e for e in data["load"] if e.get("skill") == "legacy-caller")
|
| 306 |
+
assert entry.get("entity_type") == "skill"
|
| 307 |
+
|
| 308 |
+
def test_legacy_pre_fix_manifest_entry_is_not_duplicated(self, fake_home):
|
| 309 |
+
"""If the manifest already has a pre-fix entry (no ``entity_type``
|
| 310 |
+
key, slug == ``foo``), a new ``update_manifest("foo", "skill")``
|
| 311 |
+
call must recognise it as the same pair — the missing
|
| 312 |
+
``entity_type`` in the old entry implicitly meant ``skill``."""
|
| 313 |
+
loader, home = fake_home
|
| 314 |
+
manifest_path = home / ".claude" / "skill-manifest.json"
|
| 315 |
+
manifest_path.write_text(json.dumps({
|
| 316 |
+
"load": [{"skill": "foo", "source": "legacy"}],
|
| 317 |
+
"unload": [],
|
| 318 |
+
"warnings": [],
|
| 319 |
+
}), encoding="utf-8")
|
| 320 |
+
loader.update_manifest("foo", entity_type="skill")
|
| 321 |
+
data = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 322 |
+
foo_entries = [e for e in data["load"] if e.get("skill") == "foo"]
|
| 323 |
+
assert len(foo_entries) == 1, (
|
| 324 |
+
"legacy entry got duplicated — missing entity_type should "
|
| 325 |
+
"default to 'skill' for dedup purposes"
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
def test_concurrent_dashboard_loads_preserve_all_manifest_entries(
|
| 329 |
+
self,
|
| 330 |
+
tmp_path: Path,
|
| 331 |
+
) -> None:
|
| 332 |
+
home = tmp_path / "home"
|
| 333 |
+
manifest_path = home / ".claude" / "skill-manifest.json"
|
| 334 |
+
manifest_path.parent.mkdir(parents=True)
|
| 335 |
+
slugs = [f"skill-{i}" for i in range(8)]
|
| 336 |
+
|
| 337 |
+
_run_dashboard_manifest_workers(home, tmp_path, mode="load", slugs=slugs)
|
| 338 |
+
|
| 339 |
+
data = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 340 |
+
loaded = {entry["skill"] for entry in data["load"]}
|
| 341 |
+
assert loaded == set(slugs)
|
| 342 |
+
|
| 343 |
+
def test_concurrent_dashboard_unloads_preserve_all_manifest_removals(
|
| 344 |
+
self,
|
| 345 |
+
tmp_path: Path,
|
| 346 |
+
) -> None:
|
| 347 |
+
home = tmp_path / "home"
|
| 348 |
+
manifest_path = home / ".claude" / "skill-manifest.json"
|
| 349 |
+
manifest_path.parent.mkdir(parents=True)
|
| 350 |
+
slugs = [f"skill-{i}" for i in range(8)]
|
| 351 |
+
manifest_path.write_text(
|
| 352 |
+
json.dumps({
|
| 353 |
+
"load": [
|
| 354 |
+
{
|
| 355 |
+
"skill": slug,
|
| 356 |
+
"entity_type": "skill",
|
| 357 |
+
"source": "seed",
|
| 358 |
+
}
|
| 359 |
+
for slug in slugs
|
| 360 |
+
],
|
| 361 |
+
"unload": [],
|
| 362 |
+
"warnings": [],
|
| 363 |
+
}),
|
| 364 |
+
encoding="utf-8",
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
_run_dashboard_manifest_workers(home, tmp_path, mode="unload", slugs=slugs)
|
| 368 |
+
|
| 369 |
+
data = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 370 |
+
unloaded = {entry["skill"] for entry in data["unload"]}
|
| 371 |
+
assert data["load"] == []
|
| 372 |
+
assert unloaded == set(slugs)
|
src/tests/test_skill_mirror.py
CHANGED
|
@@ -1,322 +1,322 @@
|
|
| 1 |
-
"""
|
| 2 |
-
test_skill_mirror.py -- pins the short-skill mirror contract.
|
| 3 |
-
|
| 4 |
-
The mirror exists because ctx-skill-install reads
|
| 5 |
-
``<wiki>/converted/<slug>/SKILL.md`` and short skills (< line_threshold
|
| 6 |
-
lines) skip the batch_convert pipeline that would create that file.
|
| 7 |
-
Without the mirror, 835 of 1,791 skills are un-installable from the
|
| 8 |
-
shipped tarball.
|
| 9 |
-
|
| 10 |
-
Covers:
|
| 11 |
-
- short skill gets mirrored (creates converted/<slug>/SKILL.md)
|
| 12 |
-
- long skill is skipped (line_threshold guard)
|
| 13 |
-
- existing converted/<slug>/ dir is not overwritten without --force
|
| 14 |
-
- unchanged files skipped (idempotent re-run)
|
| 15 |
-
- --force overrides both guards
|
| 16 |
-
- invalid slugs rejected via validate_skill_name
|
| 17 |
-
- missing local source returns not-found
|
| 18 |
-
- prune removes short-skill mirrors whose local source vanished
|
| 19 |
-
- prune LEAVES long-skill pipeline dirs alone
|
| 20 |
-
"""
|
| 21 |
-
|
| 22 |
-
from __future__ import annotations
|
| 23 |
-
|
| 24 |
-
import sys
|
| 25 |
-
from pathlib import Path
|
| 26 |
-
|
| 27 |
-
import pytest
|
| 28 |
-
|
| 29 |
-
sys.path.insert(0, str(Path(__file__).parents[1]))
|
| 30 |
-
|
| 31 |
-
import skill_mirror as _sm
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
# ────────────────────────────────────────────────────────────────────
|
| 35 |
-
# Fixtures
|
| 36 |
-
# ───────────────────────────────────────────────────────────────────
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
@pytest.fixture()
|
| 40 |
-
def dirs(tmp_path: Path) -> tuple[Path, Path]:
|
| 41 |
-
"""Return (skills_dir, wiki_dir) set up as empty roots."""
|
| 42 |
-
skills = tmp_path / "skills"
|
| 43 |
-
wiki = tmp_path / "wiki"
|
| 44 |
-
skills.mkdir()
|
| 45 |
-
wiki.mkdir()
|
| 46 |
-
return skills, wiki
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
def _write_skill(skills: Path, slug: str, lines: int, content: str | None = None) -> Path:
|
| 50 |
-
"""Create ~/.claude/skills/<slug>/SKILL.md with *lines* lines of body."""
|
| 51 |
-
body = content if content is not None else "\n".join(f"line {i}" for i in range(lines))
|
| 52 |
-
if content is None and not body.endswith("\n"):
|
| 53 |
-
body += "\n"
|
| 54 |
-
path = skills / slug / "SKILL.md"
|
| 55 |
-
path.parent.mkdir(parents=True, exist_ok=True)
|
| 56 |
-
path.write_text(body, encoding="utf-8")
|
| 57 |
-
return path
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
# ────────────────────────────────────────────────────────────────────
|
| 61 |
-
# mirror_one
|
| 62 |
-
# ────────────────────────────────────────────────────────────────────
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
class TestMirrorOne:
|
| 66 |
-
def test_short_skill_gets_mirrored(self, dirs):
|
| 67 |
-
skills, wiki = dirs
|
| 68 |
-
_write_skill(skills, "short-skill", lines=30)
|
| 69 |
-
|
| 70 |
-
r = _sm.mirror_one(
|
| 71 |
-
"short-skill", skills_dir=skills, wiki_dir=wiki,
|
| 72 |
-
line_threshold=180,
|
| 73 |
-
)
|
| 74 |
-
|
| 75 |
-
assert r.status == "mirrored"
|
| 76 |
-
assert (wiki / "converted" / "short-skill" / "SKILL.md").is_file()
|
| 77 |
-
assert r.body_lines == 30
|
| 78 |
-
|
| 79 |
-
def test_long_skill_skipped(self, dirs):
|
| 80 |
-
"""Skills above line_threshold belong in the batch_convert
|
| 81 |
-
pipeline, not the mirror. Refusing here prevents a short-mirror
|
| 82 |
-
call from bypassing the pipeline's post-processing."""
|
| 83 |
-
skills, wiki = dirs
|
| 84 |
-
_write_skill(skills, "long-skill", lines=250)
|
| 85 |
-
|
| 86 |
-
r = _sm.mirror_one(
|
| 87 |
-
"long-skill", skills_dir=skills, wiki_dir=wiki,
|
| 88 |
-
line_threshold=180,
|
| 89 |
-
)
|
| 90 |
-
|
| 91 |
-
assert r.status == "skipped-too-long"
|
| 92 |
-
assert not (wiki / "converted" / "long-skill").exists()
|
| 93 |
-
|
| 94 |
-
def test_existing_pipeline_dir_not_overwritten(self, dirs):
|
| 95 |
-
"""An existing converted/<slug>/ with SKILL.md + references/
|
| 96 |
-
is a pipeline artifact. Mirror must NOT overwrite it."""
|
| 97 |
-
skills, wiki = dirs
|
| 98 |
-
_write_skill(skills, "had-pipeline", lines=30)
|
| 99 |
-
pipeline_dir = wiki / "converted" / "had-pipeline"
|
| 100 |
-
pipeline_dir.mkdir(parents=True)
|
| 101 |
-
pipeline_file = pipeline_dir / "SKILL.md"
|
| 102 |
-
pipeline_file.write_text("PIPELINE-CONVERTED BODY\n", encoding="utf-8")
|
| 103 |
-
(pipeline_dir / "references").mkdir()
|
| 104 |
-
|
| 105 |
-
r = _sm.mirror_one(
|
| 106 |
-
"had-pipeline", skills_dir=skills, wiki_dir=wiki,
|
| 107 |
-
line_threshold=180,
|
| 108 |
-
)
|
| 109 |
-
|
| 110 |
-
assert r.status == "skipped-existing-pipeline"
|
| 111 |
-
assert pipeline_file.read_text(encoding="utf-8") == "PIPELINE-CONVERTED BODY\n"
|
| 112 |
-
|
| 113 |
-
def test_force_overwrites_existing(self, dirs):
|
| 114 |
-
"""--force re-syncs after a local edit."""
|
| 115 |
-
skills, wiki = dirs
|
| 116 |
-
_write_skill(skills, "edited", lines=30, content="FRESH LOCAL BODY\n")
|
| 117 |
-
stale = wiki / "converted" / "edited" / "SKILL.md"
|
| 118 |
-
stale.parent.mkdir(parents=True)
|
| 119 |
-
stale.write_text("STALE WIKI BODY\n", encoding="utf-8")
|
| 120 |
-
|
| 121 |
-
r = _sm.mirror_one(
|
| 122 |
-
"edited", skills_dir=skills, wiki_dir=wiki,
|
| 123 |
-
line_threshold=180, force=True,
|
| 124 |
-
)
|
| 125 |
-
|
| 126 |
-
assert r.status == "mirrored"
|
| 127 |
-
assert stale.read_text(encoding="utf-8") == "FRESH LOCAL BODY\n"
|
| 128 |
-
|
| 129 |
-
def test_unchanged_is_idempotent(self, dirs):
|
| 130 |
-
"""Second run on already-mirrored content reports `unchanged`,
|
| 131 |
-
not a rewrite."""
|
| 132 |
-
skills, wiki = dirs
|
| 133 |
-
_write_skill(skills, "same", lines=30, content="BODY\n")
|
| 134 |
-
# Pre-create the mirror with identical content. Because dest_dir
|
| 135 |
-
# already exists AND content matches, path returns `unchanged`.
|
| 136 |
-
mirror_path = wiki / "converted" / "same" / "SKILL.md"
|
| 137 |
-
mirror_path.parent.mkdir(parents=True)
|
| 138 |
-
mirror_path.write_text("BODY\n", encoding="utf-8")
|
| 139 |
-
|
| 140 |
-
r = _sm.mirror_one(
|
| 141 |
-
"same", skills_dir=skills, wiki_dir=wiki, line_threshold=180,
|
| 142 |
-
)
|
| 143 |
-
assert r.status == "unchanged"
|
| 144 |
-
|
| 145 |
-
def test_invalid_slug_rejected(self, dirs):
|
| 146 |
-
skills, wiki = dirs
|
| 147 |
-
r = _sm.mirror_one(
|
| 148 |
-
"../etc/passwd", skills_dir=skills, wiki_dir=wiki,
|
| 149 |
-
line_threshold=180,
|
| 150 |
-
)
|
| 151 |
-
assert r.status == "skipped-invalid"
|
| 152 |
-
|
| 153 |
-
def test_missing_local_returns_not_found(self, dirs):
|
| 154 |
-
skills, wiki = dirs
|
| 155 |
-
r = _sm.mirror_one(
|
| 156 |
-
"does-not-exist", skills_dir=skills, wiki_dir=wiki,
|
| 157 |
-
line_threshold=180,
|
| 158 |
-
)
|
| 159 |
-
assert r.status == "not-found"
|
| 160 |
-
|
| 161 |
-
def test_dry_run_does_not_write(self, dirs):
|
| 162 |
-
skills, wiki = dirs
|
| 163 |
-
_write_skill(skills, "dry", lines=30)
|
| 164 |
-
|
| 165 |
-
r = _sm.mirror_one(
|
| 166 |
-
"dry", skills_dir=skills, wiki_dir=wiki,
|
| 167 |
-
line_threshold=180, dry_run=True,
|
| 168 |
-
)
|
| 169 |
-
|
| 170 |
-
assert r.status == "mirrored"
|
| 171 |
-
assert "dry-run" in r.message
|
| 172 |
-
assert not (wiki / "converted" / "dry").exists()
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
# ────────────────────────────────────────────────────────────────────
|
| 176 |
-
# mirror_all
|
| 177 |
-
# ────────────────────────────────────────────────────────────────────
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
class TestMirrorAll:
|
| 181 |
-
def test_mixed_corpus(self, dirs):
|
| 182 |
-
"""Bulk run: short mirrors, long skips, existing-pipeline skips."""
|
| 183 |
-
skills, wiki = dirs
|
| 184 |
-
_write_skill(skills, "short-a", lines=20)
|
| 185 |
-
_write_skill(skills, "short-b", lines=50)
|
| 186 |
-
_write_skill(skills, "long", lines=300)
|
| 187 |
-
_write_skill(skills, "had-pipeline", lines=30)
|
| 188 |
-
# Pre-existing pipeline for had-pipeline:
|
| 189 |
-
(wiki / "converted" / "had-pipeline").mkdir(parents=True)
|
| 190 |
-
(wiki / "converted" / "had-pipeline" / "SKILL.md").write_text("X\n", encoding="utf-8")
|
| 191 |
-
(wiki / "converted" / "had-pipeline" / "references").mkdir()
|
| 192 |
-
|
| 193 |
-
results = _sm.mirror_all(
|
| 194 |
-
skills_dir=skills, wiki_dir=wiki, line_threshold=180,
|
| 195 |
-
)
|
| 196 |
-
|
| 197 |
-
by_status = {r.slug: r.status for r in results}
|
| 198 |
-
assert by_status["short-a"] == "mirrored"
|
| 199 |
-
assert by_status["short-b"] == "mirrored"
|
| 200 |
-
assert by_status["long"] == "skipped-too-long"
|
| 201 |
-
assert by_status["had-pipeline"] == "skipped-existing-pipeline"
|
| 202 |
-
|
| 203 |
-
def test_sort_is_stable(self, dirs):
|
| 204 |
-
"""Order is deterministic across runs so log diffs are readable."""
|
| 205 |
-
skills, wiki = dirs
|
| 206 |
-
for slug in ("b-skill", "a-skill", "c-skill"):
|
| 207 |
-
_write_skill(skills, slug, lines=10)
|
| 208 |
-
|
| 209 |
-
results = _sm.mirror_all(
|
| 210 |
-
skills_dir=skills, wiki_dir=wiki, line_threshold=180,
|
| 211 |
-
)
|
| 212 |
-
assert [r.slug for r in results] == ["a-skill", "b-skill", "c-skill"]
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
# ────────────────────────────────────────────────────────────────────
|
| 216 |
-
# prune_orphans
|
| 217 |
-
# ────────────────────────────────────────────────────────────────────
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
class TestPruneOrphans:
|
| 221 |
-
def test_prune_short_mirror_when_local_gone(self, dirs):
|
| 222 |
-
"""Short mirror = converted/<slug>/ containing only SKILL.md.
|
| 223 |
-
If local source vanishes, prune drops the mirror."""
|
| 224 |
-
skills, wiki = dirs
|
| 225 |
-
mirror_dir = wiki / "converted" / "vanished"
|
| 226 |
-
mirror_dir.mkdir(parents=True)
|
| 227 |
-
(mirror_dir / "SKILL.md").write_text("orphan\n", encoding="utf-8")
|
| 228 |
-
|
| 229 |
-
results = _sm.prune_orphans(
|
| 230 |
-
skills_dir=skills, wiki_dir=wiki,
|
| 231 |
-
)
|
| 232 |
-
|
| 233 |
-
assert any(r.slug == "vanished" and r.status == "pruned" for r in results)
|
| 234 |
-
assert not mirror_dir.exists()
|
| 235 |
-
|
| 236 |
-
def test_prune_leaves_pipeline_dirs_alone(self, dirs):
|
| 237 |
-
"""Long-skill pipeline dirs (SKILL.md + references/ + siblings)
|
| 238 |
-
must not be pruned — they hold converted content the local
|
| 239 |
-
source no longer needs to generate from."""
|
| 240 |
-
skills, wiki = dirs
|
| 241 |
-
pipeline_dir = wiki / "converted" / "pipelined"
|
| 242 |
-
pipeline_dir.mkdir(parents=True)
|
| 243 |
-
(pipeline_dir / "SKILL.md").write_text("body\n", encoding="utf-8")
|
| 244 |
-
(pipeline_dir / "references").mkdir()
|
| 245 |
-
(pipeline_dir / "check-gates.md").write_text("gates\n", encoding="utf-8")
|
| 246 |
-
# No local source for "pipelined" — but it has siblings, so keep it.
|
| 247 |
-
|
| 248 |
-
results = _sm.prune_orphans(skills_dir=skills, wiki_dir=wiki)
|
| 249 |
-
|
| 250 |
-
assert not any(r.slug == "pipelined" for r in results)
|
| 251 |
-
assert pipeline_dir.exists()
|
| 252 |
-
|
| 253 |
-
def test_prune_skips_present_sources(self, dirs):
|
| 254 |
-
"""Mirror whose local source STILL exists is not pruned."""
|
| 255 |
-
skills, wiki = dirs
|
| 256 |
-
_write_skill(skills, "still-here", lines=20)
|
| 257 |
-
mirror_dir = wiki / "converted" / "still-here"
|
| 258 |
-
mirror_dir.mkdir(parents=True)
|
| 259 |
-
(mirror_dir / "SKILL.md").write_text("body\n", encoding="utf-8")
|
| 260 |
-
|
| 261 |
-
results = _sm.prune_orphans(skills_dir=skills, wiki_dir=wiki)
|
| 262 |
-
|
| 263 |
-
assert not any(r.slug == "still-here" for r in results)
|
| 264 |
-
assert mirror_dir.exists()
|
| 265 |
-
|
| 266 |
-
def test_prune_dry_run_reports_but_keeps(self, dirs):
|
| 267 |
-
skills, wiki = dirs
|
| 268 |
-
mirror_dir = wiki / "converted" / "to-prune"
|
| 269 |
-
mirror_dir.mkdir(parents=True)
|
| 270 |
-
(mirror_dir / "SKILL.md").write_text("x\n", encoding="utf-8")
|
| 271 |
-
|
| 272 |
-
results = _sm.prune_orphans(
|
| 273 |
-
skills_dir=skills, wiki_dir=wiki, dry_run=True,
|
| 274 |
-
)
|
| 275 |
-
|
| 276 |
-
assert any(r.status == "pruned" and "dry-run" in r.message for r in results)
|
| 277 |
-
assert mirror_dir.exists()
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
# ────────────────────────────────────────────────────────────────────
|
| 281 |
-
# Integration with skill_install
|
| 282 |
-
# ────────────────────────────────────────────────────────────────────
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
class TestIntegrationWithInstall:
|
| 286 |
-
def test_installed_after_mirror(self, dirs, tmp_path):
|
| 287 |
-
"""End-to-end: a short local skill has no wiki content -> install
|
| 288 |
-
would fail with not-in-wiki -> run mirror -> install now works.
|
| 289 |
-
|
| 290 |
-
This is the exact regression the mirror exists to fix.
|
| 291 |
-
"""
|
| 292 |
-
from ctx.adapters.claude_code.install.skill_install import install_skill
|
| 293 |
-
|
| 294 |
-
skills, wiki = dirs
|
| 295 |
-
_write_skill(
|
| 296 |
-
skills, "short-e2e", lines=10,
|
| 297 |
-
content="# short-e2e\n\nBody for a short skill.\n",
|
| 298 |
-
)
|
| 299 |
-
# Before mirror: install fails.
|
| 300 |
-
install_target = tmp_path / "install-target"
|
| 301 |
-
before = install_skill(
|
| 302 |
-
"short-e2e", wiki_dir=wiki, skills_dir=install_target,
|
| 303 |
-
)
|
| 304 |
-
assert before.status == "not-in-wiki"
|
| 305 |
-
|
| 306 |
-
# Run the mirror.
|
| 307 |
-
r = _sm.mirror_one(
|
| 308 |
-
"short-e2e", skills_dir=skills, wiki_dir=wiki,
|
| 309 |
-
line_threshold=180,
|
| 310 |
-
)
|
| 311 |
-
assert r.status == "mirrored"
|
| 312 |
-
|
| 313 |
-
# Install now succeeds with the mirrored body.
|
| 314 |
-
after = install_skill(
|
| 315 |
-
"short-e2e", wiki_dir=wiki, skills_dir=install_target,
|
| 316 |
-
)
|
| 317 |
-
assert after.status == "installed"
|
| 318 |
-
assert (install_target / "short-e2e" / "SKILL.md").is_file()
|
| 319 |
-
# Content matches the local body verbatim.
|
| 320 |
-
assert "Body for a short skill." in (
|
| 321 |
-
install_target / "short-e2e" / "SKILL.md"
|
| 322 |
-
).read_text(encoding="utf-8")
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_skill_mirror.py -- pins the short-skill mirror contract.
|
| 3 |
+
|
| 4 |
+
The mirror exists because ctx-skill-install reads
|
| 5 |
+
``<wiki>/converted/<slug>/SKILL.md`` and short skills (< line_threshold
|
| 6 |
+
lines) skip the batch_convert pipeline that would create that file.
|
| 7 |
+
Without the mirror, 835 of 1,791 skills are un-installable from the
|
| 8 |
+
shipped tarball.
|
| 9 |
+
|
| 10 |
+
Covers:
|
| 11 |
+
- short skill gets mirrored (creates converted/<slug>/SKILL.md)
|
| 12 |
+
- long skill is skipped (line_threshold guard)
|
| 13 |
+
- existing converted/<slug>/ dir is not overwritten without --force
|
| 14 |
+
- unchanged files skipped (idempotent re-run)
|
| 15 |
+
- --force overrides both guards
|
| 16 |
+
- invalid slugs rejected via validate_skill_name
|
| 17 |
+
- missing local source returns not-found
|
| 18 |
+
- prune removes short-skill mirrors whose local source vanished
|
| 19 |
+
- prune LEAVES long-skill pipeline dirs alone
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
|
| 24 |
+
import sys
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
import pytest
|
| 28 |
+
|
| 29 |
+
sys.path.insert(0, str(Path(__file__).parents[1]))
|
| 30 |
+
|
| 31 |
+
import skill_mirror as _sm
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# ────────────────────────────────────────────────────────────────────
|
| 35 |
+
# Fixtures
|
| 36 |
+
# ────���───────────────────────────────────────────────────────────────
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@pytest.fixture()
|
| 40 |
+
def dirs(tmp_path: Path) -> tuple[Path, Path]:
|
| 41 |
+
"""Return (skills_dir, wiki_dir) set up as empty roots."""
|
| 42 |
+
skills = tmp_path / "skills"
|
| 43 |
+
wiki = tmp_path / "wiki"
|
| 44 |
+
skills.mkdir()
|
| 45 |
+
wiki.mkdir()
|
| 46 |
+
return skills, wiki
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _write_skill(skills: Path, slug: str, lines: int, content: str | None = None) -> Path:
|
| 50 |
+
"""Create ~/.claude/skills/<slug>/SKILL.md with *lines* lines of body."""
|
| 51 |
+
body = content if content is not None else "\n".join(f"line {i}" for i in range(lines))
|
| 52 |
+
if content is None and not body.endswith("\n"):
|
| 53 |
+
body += "\n"
|
| 54 |
+
path = skills / slug / "SKILL.md"
|
| 55 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 56 |
+
path.write_text(body, encoding="utf-8")
|
| 57 |
+
return path
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# ────────────────────────────────────────────────────────────────────
|
| 61 |
+
# mirror_one
|
| 62 |
+
# ────────────────────────────────────────────────────────────────────
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class TestMirrorOne:
|
| 66 |
+
def test_short_skill_gets_mirrored(self, dirs):
|
| 67 |
+
skills, wiki = dirs
|
| 68 |
+
_write_skill(skills, "short-skill", lines=30)
|
| 69 |
+
|
| 70 |
+
r = _sm.mirror_one(
|
| 71 |
+
"short-skill", skills_dir=skills, wiki_dir=wiki,
|
| 72 |
+
line_threshold=180,
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
assert r.status == "mirrored"
|
| 76 |
+
assert (wiki / "converted" / "short-skill" / "SKILL.md").is_file()
|
| 77 |
+
assert r.body_lines == 30
|
| 78 |
+
|
| 79 |
+
def test_long_skill_skipped(self, dirs):
|
| 80 |
+
"""Skills above line_threshold belong in the batch_convert
|
| 81 |
+
pipeline, not the mirror. Refusing here prevents a short-mirror
|
| 82 |
+
call from bypassing the pipeline's post-processing."""
|
| 83 |
+
skills, wiki = dirs
|
| 84 |
+
_write_skill(skills, "long-skill", lines=250)
|
| 85 |
+
|
| 86 |
+
r = _sm.mirror_one(
|
| 87 |
+
"long-skill", skills_dir=skills, wiki_dir=wiki,
|
| 88 |
+
line_threshold=180,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
assert r.status == "skipped-too-long"
|
| 92 |
+
assert not (wiki / "converted" / "long-skill").exists()
|
| 93 |
+
|
| 94 |
+
def test_existing_pipeline_dir_not_overwritten(self, dirs):
|
| 95 |
+
"""An existing converted/<slug>/ with SKILL.md + references/
|
| 96 |
+
is a pipeline artifact. Mirror must NOT overwrite it."""
|
| 97 |
+
skills, wiki = dirs
|
| 98 |
+
_write_skill(skills, "had-pipeline", lines=30)
|
| 99 |
+
pipeline_dir = wiki / "converted" / "had-pipeline"
|
| 100 |
+
pipeline_dir.mkdir(parents=True)
|
| 101 |
+
pipeline_file = pipeline_dir / "SKILL.md"
|
| 102 |
+
pipeline_file.write_text("PIPELINE-CONVERTED BODY\n", encoding="utf-8")
|
| 103 |
+
(pipeline_dir / "references").mkdir()
|
| 104 |
+
|
| 105 |
+
r = _sm.mirror_one(
|
| 106 |
+
"had-pipeline", skills_dir=skills, wiki_dir=wiki,
|
| 107 |
+
line_threshold=180,
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
assert r.status == "skipped-existing-pipeline"
|
| 111 |
+
assert pipeline_file.read_text(encoding="utf-8") == "PIPELINE-CONVERTED BODY\n"
|
| 112 |
+
|
| 113 |
+
def test_force_overwrites_existing(self, dirs):
|
| 114 |
+
"""--force re-syncs after a local edit."""
|
| 115 |
+
skills, wiki = dirs
|
| 116 |
+
_write_skill(skills, "edited", lines=30, content="FRESH LOCAL BODY\n")
|
| 117 |
+
stale = wiki / "converted" / "edited" / "SKILL.md"
|
| 118 |
+
stale.parent.mkdir(parents=True)
|
| 119 |
+
stale.write_text("STALE WIKI BODY\n", encoding="utf-8")
|
| 120 |
+
|
| 121 |
+
r = _sm.mirror_one(
|
| 122 |
+
"edited", skills_dir=skills, wiki_dir=wiki,
|
| 123 |
+
line_threshold=180, force=True,
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
assert r.status == "mirrored"
|
| 127 |
+
assert stale.read_text(encoding="utf-8") == "FRESH LOCAL BODY\n"
|
| 128 |
+
|
| 129 |
+
def test_unchanged_is_idempotent(self, dirs):
|
| 130 |
+
"""Second run on already-mirrored content reports `unchanged`,
|
| 131 |
+
not a rewrite."""
|
| 132 |
+
skills, wiki = dirs
|
| 133 |
+
_write_skill(skills, "same", lines=30, content="BODY\n")
|
| 134 |
+
# Pre-create the mirror with identical content. Because dest_dir
|
| 135 |
+
# already exists AND content matches, path returns `unchanged`.
|
| 136 |
+
mirror_path = wiki / "converted" / "same" / "SKILL.md"
|
| 137 |
+
mirror_path.parent.mkdir(parents=True)
|
| 138 |
+
mirror_path.write_text("BODY\n", encoding="utf-8")
|
| 139 |
+
|
| 140 |
+
r = _sm.mirror_one(
|
| 141 |
+
"same", skills_dir=skills, wiki_dir=wiki, line_threshold=180,
|
| 142 |
+
)
|
| 143 |
+
assert r.status == "unchanged"
|
| 144 |
+
|
| 145 |
+
def test_invalid_slug_rejected(self, dirs):
|
| 146 |
+
skills, wiki = dirs
|
| 147 |
+
r = _sm.mirror_one(
|
| 148 |
+
"../etc/passwd", skills_dir=skills, wiki_dir=wiki,
|
| 149 |
+
line_threshold=180,
|
| 150 |
+
)
|
| 151 |
+
assert r.status == "skipped-invalid"
|
| 152 |
+
|
| 153 |
+
def test_missing_local_returns_not_found(self, dirs):
|
| 154 |
+
skills, wiki = dirs
|
| 155 |
+
r = _sm.mirror_one(
|
| 156 |
+
"does-not-exist", skills_dir=skills, wiki_dir=wiki,
|
| 157 |
+
line_threshold=180,
|
| 158 |
+
)
|
| 159 |
+
assert r.status == "not-found"
|
| 160 |
+
|
| 161 |
+
def test_dry_run_does_not_write(self, dirs):
|
| 162 |
+
skills, wiki = dirs
|
| 163 |
+
_write_skill(skills, "dry", lines=30)
|
| 164 |
+
|
| 165 |
+
r = _sm.mirror_one(
|
| 166 |
+
"dry", skills_dir=skills, wiki_dir=wiki,
|
| 167 |
+
line_threshold=180, dry_run=True,
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
assert r.status == "mirrored"
|
| 171 |
+
assert "dry-run" in r.message
|
| 172 |
+
assert not (wiki / "converted" / "dry").exists()
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
# ────────────────────────────────────────────────────────────────────
|
| 176 |
+
# mirror_all
|
| 177 |
+
# ────────────────────────────────────────────────────────────────────
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class TestMirrorAll:
|
| 181 |
+
def test_mixed_corpus(self, dirs):
|
| 182 |
+
"""Bulk run: short mirrors, long skips, existing-pipeline skips."""
|
| 183 |
+
skills, wiki = dirs
|
| 184 |
+
_write_skill(skills, "short-a", lines=20)
|
| 185 |
+
_write_skill(skills, "short-b", lines=50)
|
| 186 |
+
_write_skill(skills, "long", lines=300)
|
| 187 |
+
_write_skill(skills, "had-pipeline", lines=30)
|
| 188 |
+
# Pre-existing pipeline for had-pipeline:
|
| 189 |
+
(wiki / "converted" / "had-pipeline").mkdir(parents=True)
|
| 190 |
+
(wiki / "converted" / "had-pipeline" / "SKILL.md").write_text("X\n", encoding="utf-8")
|
| 191 |
+
(wiki / "converted" / "had-pipeline" / "references").mkdir()
|
| 192 |
+
|
| 193 |
+
results = _sm.mirror_all(
|
| 194 |
+
skills_dir=skills, wiki_dir=wiki, line_threshold=180,
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
by_status = {r.slug: r.status for r in results}
|
| 198 |
+
assert by_status["short-a"] == "mirrored"
|
| 199 |
+
assert by_status["short-b"] == "mirrored"
|
| 200 |
+
assert by_status["long"] == "skipped-too-long"
|
| 201 |
+
assert by_status["had-pipeline"] == "skipped-existing-pipeline"
|
| 202 |
+
|
| 203 |
+
def test_sort_is_stable(self, dirs):
|
| 204 |
+
"""Order is deterministic across runs so log diffs are readable."""
|
| 205 |
+
skills, wiki = dirs
|
| 206 |
+
for slug in ("b-skill", "a-skill", "c-skill"):
|
| 207 |
+
_write_skill(skills, slug, lines=10)
|
| 208 |
+
|
| 209 |
+
results = _sm.mirror_all(
|
| 210 |
+
skills_dir=skills, wiki_dir=wiki, line_threshold=180,
|
| 211 |
+
)
|
| 212 |
+
assert [r.slug for r in results] == ["a-skill", "b-skill", "c-skill"]
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
# ────────────────────────────────────────────────────────────────────
|
| 216 |
+
# prune_orphans
|
| 217 |
+
# ────────────────────────────────────────────────────────────────────
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class TestPruneOrphans:
|
| 221 |
+
def test_prune_short_mirror_when_local_gone(self, dirs):
|
| 222 |
+
"""Short mirror = converted/<slug>/ containing only SKILL.md.
|
| 223 |
+
If local source vanishes, prune drops the mirror."""
|
| 224 |
+
skills, wiki = dirs
|
| 225 |
+
mirror_dir = wiki / "converted" / "vanished"
|
| 226 |
+
mirror_dir.mkdir(parents=True)
|
| 227 |
+
(mirror_dir / "SKILL.md").write_text("orphan\n", encoding="utf-8")
|
| 228 |
+
|
| 229 |
+
results = _sm.prune_orphans(
|
| 230 |
+
skills_dir=skills, wiki_dir=wiki,
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
assert any(r.slug == "vanished" and r.status == "pruned" for r in results)
|
| 234 |
+
assert not mirror_dir.exists()
|
| 235 |
+
|
| 236 |
+
def test_prune_leaves_pipeline_dirs_alone(self, dirs):
|
| 237 |
+
"""Long-skill pipeline dirs (SKILL.md + references/ + siblings)
|
| 238 |
+
must not be pruned — they hold converted content the local
|
| 239 |
+
source no longer needs to generate from."""
|
| 240 |
+
skills, wiki = dirs
|
| 241 |
+
pipeline_dir = wiki / "converted" / "pipelined"
|
| 242 |
+
pipeline_dir.mkdir(parents=True)
|
| 243 |
+
(pipeline_dir / "SKILL.md").write_text("body\n", encoding="utf-8")
|
| 244 |
+
(pipeline_dir / "references").mkdir()
|
| 245 |
+
(pipeline_dir / "check-gates.md").write_text("gates\n", encoding="utf-8")
|
| 246 |
+
# No local source for "pipelined" — but it has siblings, so keep it.
|
| 247 |
+
|
| 248 |
+
results = _sm.prune_orphans(skills_dir=skills, wiki_dir=wiki)
|
| 249 |
+
|
| 250 |
+
assert not any(r.slug == "pipelined" for r in results)
|
| 251 |
+
assert pipeline_dir.exists()
|
| 252 |
+
|
| 253 |
+
def test_prune_skips_present_sources(self, dirs):
|
| 254 |
+
"""Mirror whose local source STILL exists is not pruned."""
|
| 255 |
+
skills, wiki = dirs
|
| 256 |
+
_write_skill(skills, "still-here", lines=20)
|
| 257 |
+
mirror_dir = wiki / "converted" / "still-here"
|
| 258 |
+
mirror_dir.mkdir(parents=True)
|
| 259 |
+
(mirror_dir / "SKILL.md").write_text("body\n", encoding="utf-8")
|
| 260 |
+
|
| 261 |
+
results = _sm.prune_orphans(skills_dir=skills, wiki_dir=wiki)
|
| 262 |
+
|
| 263 |
+
assert not any(r.slug == "still-here" for r in results)
|
| 264 |
+
assert mirror_dir.exists()
|
| 265 |
+
|
| 266 |
+
def test_prune_dry_run_reports_but_keeps(self, dirs):
|
| 267 |
+
skills, wiki = dirs
|
| 268 |
+
mirror_dir = wiki / "converted" / "to-prune"
|
| 269 |
+
mirror_dir.mkdir(parents=True)
|
| 270 |
+
(mirror_dir / "SKILL.md").write_text("x\n", encoding="utf-8")
|
| 271 |
+
|
| 272 |
+
results = _sm.prune_orphans(
|
| 273 |
+
skills_dir=skills, wiki_dir=wiki, dry_run=True,
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
assert any(r.status == "pruned" and "dry-run" in r.message for r in results)
|
| 277 |
+
assert mirror_dir.exists()
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
# ────────────────────────────────────────────────────────────────────
|
| 281 |
+
# Integration with skill_install
|
| 282 |
+
# ────────────────────────────────────────────────────────────────────
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class TestIntegrationWithInstall:
|
| 286 |
+
def test_installed_after_mirror(self, dirs, tmp_path):
|
| 287 |
+
"""End-to-end: a short local skill has no wiki content -> install
|
| 288 |
+
would fail with not-in-wiki -> run mirror -> install now works.
|
| 289 |
+
|
| 290 |
+
This is the exact regression the mirror exists to fix.
|
| 291 |
+
"""
|
| 292 |
+
from ctx.adapters.claude_code.install.skill_install import install_skill
|
| 293 |
+
|
| 294 |
+
skills, wiki = dirs
|
| 295 |
+
_write_skill(
|
| 296 |
+
skills, "short-e2e", lines=10,
|
| 297 |
+
content="# short-e2e\n\nBody for a short skill.\n",
|
| 298 |
+
)
|
| 299 |
+
# Before mirror: install fails.
|
| 300 |
+
install_target = tmp_path / "install-target"
|
| 301 |
+
before = install_skill(
|
| 302 |
+
"short-e2e", wiki_dir=wiki, skills_dir=install_target,
|
| 303 |
+
)
|
| 304 |
+
assert before.status == "not-in-wiki"
|
| 305 |
+
|
| 306 |
+
# Run the mirror.
|
| 307 |
+
r = _sm.mirror_one(
|
| 308 |
+
"short-e2e", skills_dir=skills, wiki_dir=wiki,
|
| 309 |
+
line_threshold=180,
|
| 310 |
+
)
|
| 311 |
+
assert r.status == "mirrored"
|
| 312 |
+
|
| 313 |
+
# Install now succeeds with the mirrored body.
|
| 314 |
+
after = install_skill(
|
| 315 |
+
"short-e2e", wiki_dir=wiki, skills_dir=install_target,
|
| 316 |
+
)
|
| 317 |
+
assert after.status == "installed"
|
| 318 |
+
assert (install_target / "short-e2e" / "SKILL.md").is_file()
|
| 319 |
+
# Content matches the local body verbatim.
|
| 320 |
+
assert "Body for a short skill." in (
|
| 321 |
+
install_target / "short-e2e" / "SKILL.md"
|
| 322 |
+
).read_text(encoding="utf-8")
|
src/tests/test_skill_quality_bench.py
CHANGED
|
@@ -1,141 +1,141 @@
|
|
| 1 |
-
"""
|
| 2 |
-
test_skill_quality_bench.py — P1-12 performance regression test.
|
| 3 |
-
|
| 4 |
-
Creates 1,000 fake telemetry events spread across 100 slugs and asserts
|
| 5 |
-
that ``recompute_all`` completes within the platform budget, confirming the
|
| 6 |
-
O(M) single-scan behaviour (vs the previous O(N·M) per-slug rescan).
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
from __future__ import annotations
|
| 10 |
-
|
| 11 |
-
import json
|
| 12 |
-
import os
|
| 13 |
-
import sys
|
| 14 |
-
import time
|
| 15 |
-
from datetime import datetime, timezone
|
| 16 |
-
from pathlib import Path
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
SRC_DIR = Path(__file__).resolve().parents[1]
|
| 20 |
-
if str(SRC_DIR) not in sys.path:
|
| 21 |
-
sys.path.insert(0, str(SRC_DIR))
|
| 22 |
-
|
| 23 |
-
import skill_quality as sq # noqa: E402
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
# ────────────────────────────────────────────────────────────────────
|
| 27 |
-
# Fixtures / helpers
|
| 28 |
-
# ────────────────────────────────────────────────────────────────────
|
| 29 |
-
|
| 30 |
-
_NUM_SLUGS = 100
|
| 31 |
-
_EVENTS_PER_SLUG = 10 # 1,000 total events
|
| 32 |
-
_NOW = datetime(2026, 4, 19, 12, 0, 0, tzinfo=timezone.utc)
|
| 33 |
-
|
| 34 |
-
_SKILL_MD = (
|
| 35 |
-
"---\nname: {slug}\ndescription: Benchmark skill {slug}.\n---\n"
|
| 36 |
-
"# {slug}\n\n" + "Body content for the benchmark skill. " * 10 + "\n"
|
| 37 |
-
)
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
def _benchmark_budget_seconds() -> float:
|
| 41 |
-
if sys.platform == "win32" and os.environ.get("PYTEST_XDIST_WORKER"):
|
| 42 |
-
return 5.0
|
| 43 |
-
return 2.0
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
def _make_bench_tree(tmp_path: Path) -> sq.SignalSources:
|
| 47 |
-
skills_dir = tmp_path / "skills"
|
| 48 |
-
agents_dir = tmp_path / "agents"
|
| 49 |
-
wiki_dir = tmp_path / "wiki"
|
| 50 |
-
events_path = tmp_path / "events.jsonl"
|
| 51 |
-
|
| 52 |
-
skills_dir.mkdir()
|
| 53 |
-
agents_dir.mkdir()
|
| 54 |
-
wiki_dir.mkdir()
|
| 55 |
-
|
| 56 |
-
slugs = [f"bench-skill-{i:03d}" for i in range(_NUM_SLUGS)]
|
| 57 |
-
|
| 58 |
-
# Create skill files.
|
| 59 |
-
for slug in slugs:
|
| 60 |
-
skill_dir = skills_dir / slug
|
| 61 |
-
skill_dir.mkdir()
|
| 62 |
-
(skill_dir / "SKILL.md").write_text(
|
| 63 |
-
_SKILL_MD.format(slug=slug), encoding="utf-8"
|
| 64 |
-
)
|
| 65 |
-
|
| 66 |
-
# Create JSONL with events spread evenly across slugs.
|
| 67 |
-
ts = _NOW.isoformat(timespec="seconds")
|
| 68 |
-
lines = []
|
| 69 |
-
for i in range(_NUM_SLUGS * _EVENTS_PER_SLUG):
|
| 70 |
-
slug = slugs[i % _NUM_SLUGS]
|
| 71 |
-
lines.append(json.dumps({"skill": slug, "event": "load", "timestamp": ts}))
|
| 72 |
-
events_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
| 73 |
-
|
| 74 |
-
return sq.SignalSources(
|
| 75 |
-
skills_dir=skills_dir,
|
| 76 |
-
agents_dir=agents_dir,
|
| 77 |
-
wiki_dir=wiki_dir,
|
| 78 |
-
events_path=events_path,
|
| 79 |
-
)
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
# ────────────────────────────────────────────────────────────────────
|
| 83 |
-
# Tests
|
| 84 |
-
# ────────────────────────────────────────────────────────────────────
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
def test_recompute_all_completes_within_budget(
|
| 88 |
-
tmp_path: Path,
|
| 89 |
-
monkeypatch,
|
| 90 |
-
) -> None:
|
| 91 |
-
"""recompute_all with 100 slugs / 1,000 events must stay fast."""
|
| 92 |
-
sources = _make_bench_tree(tmp_path)
|
| 93 |
-
sidecar_dir = tmp_path / "sidecars"
|
| 94 |
-
sidecar_dir.mkdir()
|
| 95 |
-
|
| 96 |
-
def fast_write(path: Path, text: str) -> None:
|
| 97 |
-
path.parent.mkdir(parents=True, exist_ok=True)
|
| 98 |
-
path.write_text(text, encoding="utf-8")
|
| 99 |
-
|
| 100 |
-
monkeypatch.setattr(sq, "_atomic_write", fast_write)
|
| 101 |
-
|
| 102 |
-
start = time.monotonic()
|
| 103 |
-
successes, failures = sq.recompute_all(
|
| 104 |
-
sources=sources,
|
| 105 |
-
now=_NOW,
|
| 106 |
-
sidecar_dir=sidecar_dir,
|
| 107 |
-
update_frontmatter=False,
|
| 108 |
-
)
|
| 109 |
-
elapsed = time.monotonic() - start
|
| 110 |
-
|
| 111 |
-
assert failures == [], f"Unexpected failures: {failures}"
|
| 112 |
-
assert len(successes) == _NUM_SLUGS
|
| 113 |
-
budget = _benchmark_budget_seconds()
|
| 114 |
-
assert elapsed < budget, (
|
| 115 |
-
f"recompute_all took {elapsed:.2f}s for {_NUM_SLUGS} slugs / "
|
| 116 |
-
f"{_NUM_SLUGS * _EVENTS_PER_SLUG} events — expected < {budget:.1f}s"
|
| 117 |
-
)
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
def test_events_index_used_single_read(tmp_path: Path) -> None:
|
| 121 |
-
"""_build_events_index partitions events correctly by slug."""
|
| 122 |
-
sources = _make_bench_tree(tmp_path)
|
| 123 |
-
|
| 124 |
-
index = sq._build_events_index(sources.events_path)
|
| 125 |
-
|
| 126 |
-
assert len(index) == _NUM_SLUGS
|
| 127 |
-
for slug, events in index.items():
|
| 128 |
-
assert len(events) == _EVENTS_PER_SLUG, (
|
| 129 |
-
f"{slug} has {len(events)} events, expected {_EVENTS_PER_SLUG}"
|
| 130 |
-
)
|
| 131 |
-
assert all(e["skill"] == slug for e in events)
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
def test_events_index_empty_file(tmp_path: Path) -> None:
|
| 135 |
-
"""_build_events_index returns an empty dict for a missing or empty file."""
|
| 136 |
-
missing = tmp_path / "does_not_exist.jsonl"
|
| 137 |
-
assert sq._build_events_index(missing) == {}
|
| 138 |
-
|
| 139 |
-
empty = tmp_path / "empty.jsonl"
|
| 140 |
-
empty.write_text("", encoding="utf-8")
|
| 141 |
-
assert sq._build_events_index(empty) == {}
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_skill_quality_bench.py — P1-12 performance regression test.
|
| 3 |
+
|
| 4 |
+
Creates 1,000 fake telemetry events spread across 100 slugs and asserts
|
| 5 |
+
that ``recompute_all`` completes within the platform budget, confirming the
|
| 6 |
+
O(M) single-scan behaviour (vs the previous O(N·M) per-slug rescan).
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import sys
|
| 14 |
+
import time
|
| 15 |
+
from datetime import datetime, timezone
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
SRC_DIR = Path(__file__).resolve().parents[1]
|
| 20 |
+
if str(SRC_DIR) not in sys.path:
|
| 21 |
+
sys.path.insert(0, str(SRC_DIR))
|
| 22 |
+
|
| 23 |
+
import skill_quality as sq # noqa: E402
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# ────────────────────────────────────────────────────────────────────
|
| 27 |
+
# Fixtures / helpers
|
| 28 |
+
# ────────────────────────────────────────────────────────────────────
|
| 29 |
+
|
| 30 |
+
_NUM_SLUGS = 100
|
| 31 |
+
_EVENTS_PER_SLUG = 10 # 1,000 total events
|
| 32 |
+
_NOW = datetime(2026, 4, 19, 12, 0, 0, tzinfo=timezone.utc)
|
| 33 |
+
|
| 34 |
+
_SKILL_MD = (
|
| 35 |
+
"---\nname: {slug}\ndescription: Benchmark skill {slug}.\n---\n"
|
| 36 |
+
"# {slug}\n\n" + "Body content for the benchmark skill. " * 10 + "\n"
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _benchmark_budget_seconds() -> float:
|
| 41 |
+
if sys.platform == "win32" and os.environ.get("PYTEST_XDIST_WORKER"):
|
| 42 |
+
return 5.0
|
| 43 |
+
return 2.0
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _make_bench_tree(tmp_path: Path) -> sq.SignalSources:
|
| 47 |
+
skills_dir = tmp_path / "skills"
|
| 48 |
+
agents_dir = tmp_path / "agents"
|
| 49 |
+
wiki_dir = tmp_path / "wiki"
|
| 50 |
+
events_path = tmp_path / "events.jsonl"
|
| 51 |
+
|
| 52 |
+
skills_dir.mkdir()
|
| 53 |
+
agents_dir.mkdir()
|
| 54 |
+
wiki_dir.mkdir()
|
| 55 |
+
|
| 56 |
+
slugs = [f"bench-skill-{i:03d}" for i in range(_NUM_SLUGS)]
|
| 57 |
+
|
| 58 |
+
# Create skill files.
|
| 59 |
+
for slug in slugs:
|
| 60 |
+
skill_dir = skills_dir / slug
|
| 61 |
+
skill_dir.mkdir()
|
| 62 |
+
(skill_dir / "SKILL.md").write_text(
|
| 63 |
+
_SKILL_MD.format(slug=slug), encoding="utf-8"
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
# Create JSONL with events spread evenly across slugs.
|
| 67 |
+
ts = _NOW.isoformat(timespec="seconds")
|
| 68 |
+
lines = []
|
| 69 |
+
for i in range(_NUM_SLUGS * _EVENTS_PER_SLUG):
|
| 70 |
+
slug = slugs[i % _NUM_SLUGS]
|
| 71 |
+
lines.append(json.dumps({"skill": slug, "event": "load", "timestamp": ts}))
|
| 72 |
+
events_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
| 73 |
+
|
| 74 |
+
return sq.SignalSources(
|
| 75 |
+
skills_dir=skills_dir,
|
| 76 |
+
agents_dir=agents_dir,
|
| 77 |
+
wiki_dir=wiki_dir,
|
| 78 |
+
events_path=events_path,
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# ────────────────────────────────────────────────────────────────────
|
| 83 |
+
# Tests
|
| 84 |
+
# ────────────────────────────────────────────────────────────────────
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_recompute_all_completes_within_budget(
|
| 88 |
+
tmp_path: Path,
|
| 89 |
+
monkeypatch,
|
| 90 |
+
) -> None:
|
| 91 |
+
"""recompute_all with 100 slugs / 1,000 events must stay fast."""
|
| 92 |
+
sources = _make_bench_tree(tmp_path)
|
| 93 |
+
sidecar_dir = tmp_path / "sidecars"
|
| 94 |
+
sidecar_dir.mkdir()
|
| 95 |
+
|
| 96 |
+
def fast_write(path: Path, text: str) -> None:
|
| 97 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 98 |
+
path.write_text(text, encoding="utf-8")
|
| 99 |
+
|
| 100 |
+
monkeypatch.setattr(sq, "_atomic_write", fast_write)
|
| 101 |
+
|
| 102 |
+
start = time.monotonic()
|
| 103 |
+
successes, failures = sq.recompute_all(
|
| 104 |
+
sources=sources,
|
| 105 |
+
now=_NOW,
|
| 106 |
+
sidecar_dir=sidecar_dir,
|
| 107 |
+
update_frontmatter=False,
|
| 108 |
+
)
|
| 109 |
+
elapsed = time.monotonic() - start
|
| 110 |
+
|
| 111 |
+
assert failures == [], f"Unexpected failures: {failures}"
|
| 112 |
+
assert len(successes) == _NUM_SLUGS
|
| 113 |
+
budget = _benchmark_budget_seconds()
|
| 114 |
+
assert elapsed < budget, (
|
| 115 |
+
f"recompute_all took {elapsed:.2f}s for {_NUM_SLUGS} slugs / "
|
| 116 |
+
f"{_NUM_SLUGS * _EVENTS_PER_SLUG} events — expected < {budget:.1f}s"
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def test_events_index_used_single_read(tmp_path: Path) -> None:
|
| 121 |
+
"""_build_events_index partitions events correctly by slug."""
|
| 122 |
+
sources = _make_bench_tree(tmp_path)
|
| 123 |
+
|
| 124 |
+
index = sq._build_events_index(sources.events_path)
|
| 125 |
+
|
| 126 |
+
assert len(index) == _NUM_SLUGS
|
| 127 |
+
for slug, events in index.items():
|
| 128 |
+
assert len(events) == _EVENTS_PER_SLUG, (
|
| 129 |
+
f"{slug} has {len(events)} events, expected {_EVENTS_PER_SLUG}"
|
| 130 |
+
)
|
| 131 |
+
assert all(e["skill"] == slug for e in events)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def test_events_index_empty_file(tmp_path: Path) -> None:
|
| 135 |
+
"""_build_events_index returns an empty dict for a missing or empty file."""
|
| 136 |
+
missing = tmp_path / "does_not_exist.jsonl"
|
| 137 |
+
assert sq._build_events_index(missing) == {}
|
| 138 |
+
|
| 139 |
+
empty = tmp_path / "empty.jsonl"
|
| 140 |
+
empty.write_text("", encoding="utf-8")
|
| 141 |
+
assert sq._build_events_index(empty) == {}
|
src/tests/test_skill_telemetry.py
CHANGED
|
@@ -1,329 +1,329 @@
|
|
| 1 |
-
"""
|
| 2 |
-
test_skill_telemetry.py -- Regression tests for skill_telemetry.
|
| 3 |
-
|
| 4 |
-
Covers the Phase 1 telemetry contract:
|
| 5 |
-
|
| 6 |
-
- event validation: type enum, skill-name sanitization, empty session_id
|
| 7 |
-
- round-trip: log_event -> read_events yields identical records
|
| 8 |
-
- malformed-line tolerance: partial/corrupt lines are skipped
|
| 9 |
-
- concurrent appends: two processes writing concurrently end up with
|
| 10 |
-
two well-formed lines (no interleaving corruption)
|
| 11 |
-
- retention window math: boundary and default-cap cases
|
| 12 |
-
- naive-timestamp handling: is_retained treats naive timestamps as UTC
|
| 13 |
-
- meta validation: rejects oversized, nested, or non-scalar values
|
| 14 |
-
- path containment: refuses caller-supplied paths that escape parents
|
| 15 |
-
"""
|
| 16 |
-
|
| 17 |
-
from __future__ import annotations
|
| 18 |
-
|
| 19 |
-
import json
|
| 20 |
-
import sys
|
| 21 |
-
from concurrent.futures import ThreadPoolExecutor
|
| 22 |
-
from datetime import datetime, timedelta, timezone
|
| 23 |
-
from pathlib import Path
|
| 24 |
-
|
| 25 |
-
import pytest
|
| 26 |
-
|
| 27 |
-
SRC_DIR = Path(__file__).resolve().parents[1]
|
| 28 |
-
if str(SRC_DIR) not in sys.path:
|
| 29 |
-
sys.path.insert(0, str(SRC_DIR))
|
| 30 |
-
|
| 31 |
-
import skill_telemetry as st # noqa: E402
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
def _iso(offset_seconds: float = 0.0) -> str:
|
| 35 |
-
return (
|
| 36 |
-
datetime.now(timezone.utc) + timedelta(seconds=offset_seconds)
|
| 37 |
-
).isoformat(timespec="seconds")
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
def _event(**overrides: object) -> st.TelemetryEvent:
|
| 41 |
-
defaults: dict[str, object] = {
|
| 42 |
-
"event": "load",
|
| 43 |
-
"skill": "x",
|
| 44 |
-
"timestamp": _iso(),
|
| 45 |
-
"session_id": "s1",
|
| 46 |
-
"event_id": "e-default",
|
| 47 |
-
}
|
| 48 |
-
defaults.update(overrides)
|
| 49 |
-
return st.TelemetryEvent(**defaults) # type: ignore[arg-type]
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
# ────────────────────────────────────────────────────────────────────
|
| 53 |
-
# Event validation
|
| 54 |
-
# ────────────────────────────────────────────────────────────────────
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
def test_event_accepts_all_defined_types() -> None:
|
| 58 |
-
for kind in ("load", "unload", "override", "switch_away"):
|
| 59 |
-
_event(event=kind)
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
def test_event_rejects_unknown_type() -> None:
|
| 63 |
-
with pytest.raises(ValueError, match="invalid event type"):
|
| 64 |
-
_event(event="explode")
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
@pytest.mark.parametrize(
|
| 68 |
-
"bad_name",
|
| 69 |
-
[
|
| 70 |
-
"",
|
| 71 |
-
"../etc/passwd",
|
| 72 |
-
"skill/with/slash",
|
| 73 |
-
"skill with space",
|
| 74 |
-
"-leading-dash",
|
| 75 |
-
"a" * 200,
|
| 76 |
-
],
|
| 77 |
-
)
|
| 78 |
-
def test_event_rejects_unsafe_skill_name(bad_name: str) -> None:
|
| 79 |
-
with pytest.raises(ValueError, match="invalid skill name"):
|
| 80 |
-
_event(skill=bad_name)
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
def test_event_rejects_empty_session_id() -> None:
|
| 84 |
-
with pytest.raises(ValueError, match="session_id"):
|
| 85 |
-
_event(session_id="")
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
def test_event_rejects_empty_event_id() -> None:
|
| 89 |
-
with pytest.raises(ValueError, match="event_id"):
|
| 90 |
-
_event(event_id="")
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
def test_event_rejects_non_iso_timestamp() -> None:
|
| 94 |
-
with pytest.raises(ValueError, match="timestamp must be ISO-8601"):
|
| 95 |
-
_event(timestamp="not-a-time")
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
# ────────────────────────────────────────────────────────────────────
|
| 99 |
-
# meta validation
|
| 100 |
-
# ────────────────────────────────────────────────────────────────────
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
def test_log_event_rejects_oversized_meta(tmp_path: Path) -> None:
|
| 104 |
-
big = {f"k{i}": i for i in range(st._MAX_META_KEYS + 1)}
|
| 105 |
-
with pytest.raises(ValueError, match="max"):
|
| 106 |
-
st.log_event("load", "x", "s1", meta=big, path=tmp_path / "e.jsonl",
|
| 107 |
-
trusted_root=tmp_path)
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
def test_log_event_rejects_non_scalar_meta_value(tmp_path: Path) -> None:
|
| 111 |
-
with pytest.raises(TypeError, match="must be str/int/float/bool/None"):
|
| 112 |
-
st.log_event(
|
| 113 |
-
"load", "x", "s1", meta={"nested": {"a": 1}},
|
| 114 |
-
path=tmp_path / "e.jsonl", trusted_root=tmp_path,
|
| 115 |
-
)
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
def test_log_event_rejects_oversized_meta_string(tmp_path: Path) -> None:
|
| 119 |
-
with pytest.raises(ValueError, match="exceeds"):
|
| 120 |
-
st.log_event(
|
| 121 |
-
"load", "x", "s1",
|
| 122 |
-
meta={"big": "a" * (st._MAX_META_VALUE_LEN + 1)},
|
| 123 |
-
path=tmp_path / "e.jsonl",
|
| 124 |
-
trusted_root=tmp_path,
|
| 125 |
-
)
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
# ────────────────────────────────────────────────────────────────────
|
| 129 |
-
# Round-trip
|
| 130 |
-
# ───────────────────────────────────────────────────
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
def test_log_event_and_read_events_round_trip(tmp_path: Path) -> None:
|
| 134 |
-
events_path = tmp_path / "skill-events.jsonl"
|
| 135 |
-
|
| 136 |
-
rec_a = st.log_event(
|
| 137 |
-
"load", "python-patterns", "sess-1",
|
| 138 |
-
meta={"source": "unit-test"}, path=events_path, trusted_root=tmp_path,
|
| 139 |
-
)
|
| 140 |
-
rec_b = st.log_event(
|
| 141 |
-
"unload", "python-patterns", "sess-1", path=events_path,
|
| 142 |
-
trusted_root=tmp_path,
|
| 143 |
-
)
|
| 144 |
-
rec_c = st.log_event(
|
| 145 |
-
"override", "flask", "sess-1",
|
| 146 |
-
meta={"replaced_with": "fastapi"}, path=events_path, trusted_root=tmp_path,
|
| 147 |
-
)
|
| 148 |
-
|
| 149 |
-
got = list(st.read_events(path=events_path, trusted_root=tmp_path))
|
| 150 |
-
assert [e.event for e in got] == ["load", "unload", "override"]
|
| 151 |
-
assert got[0].event_id == rec_a.event_id
|
| 152 |
-
assert got[1].event_id == rec_b.event_id
|
| 153 |
-
assert got[2].event_id == rec_c.event_id
|
| 154 |
-
assert got[0].meta == {"source": "unit-test"}
|
| 155 |
-
assert got[2].meta == {"replaced_with": "fastapi"}
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
def test_read_events_missing_file_yields_nothing(tmp_path: Path) -> None:
|
| 159 |
-
assert list(st.read_events(path=tmp_path / "nope.jsonl", trusted_root=tmp_path)) == []
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
def test_read_events_skips_malformed_lines(
|
| 163 |
-
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
| 164 |
-
) -> None:
|
| 165 |
-
events_path = tmp_path / "skill-events.jsonl"
|
| 166 |
-
# One valid event, one garbage line, one event missing a required key,
|
| 167 |
-
# one event missing event_id (now rejected), one blank line, one valid.
|
| 168 |
-
good1 = {
|
| 169 |
-
"event": "load", "skill": "x", "timestamp": _iso(),
|
| 170 |
-
"session_id": "s1", "event_id": "e1", "meta": {},
|
| 171 |
-
}
|
| 172 |
-
good2 = {
|
| 173 |
-
"event": "unload", "skill": "x", "timestamp": _iso(),
|
| 174 |
-
"session_id": "s1", "event_id": "e2", "meta": {},
|
| 175 |
-
}
|
| 176 |
-
missing_session = {
|
| 177 |
-
"event": "load", "skill": "x", "timestamp": _iso(), "event_id": "ex",
|
| 178 |
-
}
|
| 179 |
-
missing_event_id = {
|
| 180 |
-
"event": "load", "skill": "x", "timestamp": _iso(), "session_id": "s1",
|
| 181 |
-
}
|
| 182 |
-
events_path.write_text(
|
| 183 |
-
json.dumps(good1) + "\n"
|
| 184 |
-
+ "not-json-at-all\n"
|
| 185 |
-
+ json.dumps(missing_session) + "\n"
|
| 186 |
-
+ json.dumps(missing_event_id) + "\n"
|
| 187 |
-
+ "\n"
|
| 188 |
-
+ json.dumps(good2) + "\n",
|
| 189 |
-
encoding="utf-8",
|
| 190 |
-
)
|
| 191 |
-
|
| 192 |
-
got = list(st.read_events(path=events_path, trusted_root=tmp_path))
|
| 193 |
-
assert [e.event_id for e in got] == ["e1", "e2"]
|
| 194 |
-
captured = capsys.readouterr()
|
| 195 |
-
# Warning is sanitised — no raw line content, no file path.
|
| 196 |
-
assert "skipping malformed event at line" in captured.err
|
| 197 |
-
assert "not-json-at-all" not in captured.err
|
| 198 |
-
assert str(events_path) not in captured.err
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
def test_read_events_rejects_path_that_escapes_parent(tmp_path: Path) -> None:
|
| 202 |
-
# ``tmp_path / ".."`` resolves outside its own parent — must be refused.
|
| 203 |
-
bad = tmp_path / ".." / "evil.jsonl"
|
| 204 |
-
with pytest.raises(ValueError, match="escapes"):
|
| 205 |
-
list(st.read_events(path=bad))
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
# ────────────────────────────────────────────────────────────────────
|
| 209 |
-
# Concurrency
|
| 210 |
-
# ────────────────────────────────────────────────────────────────────
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
def test_concurrent_appends_produce_wellformed_lines(tmp_path: Path) -> None:
|
| 214 |
-
events_path = tmp_path / "skill-events.jsonl"
|
| 215 |
-
N = 32
|
| 216 |
-
|
| 217 |
-
def worker(i: int) -> None:
|
| 218 |
-
st.log_event("load", f"skill{i:03d}", f"sess-{i}", path=events_path,
|
| 219 |
-
trusted_root=tmp_path)
|
| 220 |
-
|
| 221 |
-
with ThreadPoolExecutor(max_workers=8) as pool:
|
| 222 |
-
list(pool.map(worker, range(N)))
|
| 223 |
-
|
| 224 |
-
lines = events_path.read_text(encoding="utf-8").splitlines()
|
| 225 |
-
assert len(lines) == N
|
| 226 |
-
for line in lines:
|
| 227 |
-
obj = json.loads(line)
|
| 228 |
-
assert obj["event"] == "load"
|
| 229 |
-
assert obj["session_id"].startswith("sess-")
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
# ────────────────────────────────────────────────────────────────────
|
| 233 |
-
# Retention window
|
| 234 |
-
# ────────────────────────────────────────────────────────────────────
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
def test_retention_window_floor_applies_below_threshold() -> None:
|
| 238 |
-
assert st.retention_window_seconds(30 * 60) == pytest.approx(20 * 60)
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
def test_retention_window_fraction_applies_above_threshold() -> None:
|
| 242 |
-
assert st.retention_window_seconds(4 * 3600) == pytest.approx(48 * 60)
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
def test_retention_window_rejects_negative_session() -> None:
|
| 246 |
-
with pytest.raises(ValueError):
|
| 247 |
-
st.retention_window_seconds(-1)
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
def test_retention_window_rejects_bad_fraction() -> None:
|
| 251 |
-
with pytest.raises(ValueError):
|
| 252 |
-
st.retention_window_seconds(60, fraction=1.5)
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
def test_is_retained_true_at_and_above_window() -> None:
|
| 256 |
-
t0 = datetime(2026, 4, 18, 12, 0, 0, tzinfo=timezone.utc)
|
| 257 |
-
t1 = t0 + timedelta(minutes=20)
|
| 258 |
-
assert st.is_retained(t0.isoformat(), t1.isoformat(), session_seconds=600) is True
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
def test_is_retained_false_below_window() -> None:
|
| 262 |
-
t0 = datetime(2026, 4, 18, 12, 0, 0, tzinfo=timezone.utc)
|
| 263 |
-
t1 = t0 + timedelta(minutes=19, seconds=59)
|
| 264 |
-
assert st.is_retained(t0.isoformat(), t1.isoformat(), session_seconds=600) is False
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
def test_is_retained_rejects_reversed_timestamps() -> None:
|
| 268 |
-
t0 = datetime(2026, 4, 18, 12, 0, 0, tzinfo=timezone.utc)
|
| 269 |
-
t1 = t0 - timedelta(minutes=1)
|
| 270 |
-
with pytest.raises(ValueError):
|
| 271 |
-
st.is_retained(t0.isoformat(), t1.isoformat(), session_seconds=600)
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
def test_is_retained_treats_naive_timestamps_as_utc() -> None:
|
| 275 |
-
# Naive load_ts (no tz) mixed with aware unload_ts must not raise.
|
| 276 |
-
load_ts = "2026-04-18T12:00:00"
|
| 277 |
-
unload_ts = "2026-04-18T12:30:00+00:00"
|
| 278 |
-
assert st.is_retained(load_ts, unload_ts, session_seconds=600) is True
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
def test_is_retained_both_naive_ok() -> None:
|
| 282 |
-
load_ts = "2026-04-18T12:00:00"
|
| 283 |
-
unload_ts = "2026-04-18T12:30:00"
|
| 284 |
-
assert st.is_retained(load_ts, unload_ts, session_seconds=600) is True
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
# ───────────────────────────────────────────────────────────────────
|
| 288 |
-
# Default path resolution
|
| 289 |
-
# ────────────────────────────────────────────────────────────────────
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
def test_default_events_path_resolves_under_claude_dir(
|
| 293 |
-
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
| 294 |
-
) -> None:
|
| 295 |
-
# Simpler than reloading the module: just monkeypatch the constant
|
| 296 |
-
# the tests care about.
|
| 297 |
-
target = tmp_path / ".claude" / "skill-events.jsonl"
|
| 298 |
-
monkeypatch.setattr(st, "DEFAULT_EVENTS_PATH", target)
|
| 299 |
-
assert st.DEFAULT_EVENTS_PATH == target
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
# ────────────────────────────────────────────────────────────────────
|
| 303 |
-
# Trusted-root path containment (regression for Strix LOW finding)
|
| 304 |
-
# ────────────────────────────────────────────────────────────────────
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
def test_resolve_events_path_rejects_etc_passwd() -> None:
|
| 308 |
-
"""Absolute path outside any trusted root must raise ValueError."""
|
| 309 |
-
with pytest.raises(ValueError, match="escapes trusted root"):
|
| 310 |
-
st._resolve_events_path(Path("/etc/passwd"))
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
def test_resolve_events_path_rejects_windows_temp() -> None:
|
| 314 |
-
"""Windows absolute path outside trusted root must raise ValueError."""
|
| 315 |
-
with pytest.raises(ValueError, match="escapes trusted root"):
|
| 316 |
-
st._resolve_events_path(Path("C:/Windows/Temp/x"))
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
def test_resolve_events_path_none_returns_default() -> None:
|
| 320 |
-
"""None path must return DEFAULT_EVENTS_PATH unchanged."""
|
| 321 |
-
result = st._resolve_events_path(None)
|
| 322 |
-
assert result == st.DEFAULT_EVENTS_PATH
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
def test_resolve_events_path_tmp_path_with_trusted_root(tmp_path: Path) -> None:
|
| 326 |
-
"""A path inside tmp_path succeeds when trusted_root=tmp_path."""
|
| 327 |
-
target = tmp_path / "x.jsonl"
|
| 328 |
-
result = st._resolve_events_path(target, trusted_root=tmp_path)
|
| 329 |
-
assert result == target
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_skill_telemetry.py -- Regression tests for skill_telemetry.
|
| 3 |
+
|
| 4 |
+
Covers the Phase 1 telemetry contract:
|
| 5 |
+
|
| 6 |
+
- event validation: type enum, skill-name sanitization, empty session_id
|
| 7 |
+
- round-trip: log_event -> read_events yields identical records
|
| 8 |
+
- malformed-line tolerance: partial/corrupt lines are skipped
|
| 9 |
+
- concurrent appends: two processes writing concurrently end up with
|
| 10 |
+
two well-formed lines (no interleaving corruption)
|
| 11 |
+
- retention window math: boundary and default-cap cases
|
| 12 |
+
- naive-timestamp handling: is_retained treats naive timestamps as UTC
|
| 13 |
+
- meta validation: rejects oversized, nested, or non-scalar values
|
| 14 |
+
- path containment: refuses caller-supplied paths that escape parents
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import json
|
| 20 |
+
import sys
|
| 21 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 22 |
+
from datetime import datetime, timedelta, timezone
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
import pytest
|
| 26 |
+
|
| 27 |
+
SRC_DIR = Path(__file__).resolve().parents[1]
|
| 28 |
+
if str(SRC_DIR) not in sys.path:
|
| 29 |
+
sys.path.insert(0, str(SRC_DIR))
|
| 30 |
+
|
| 31 |
+
import skill_telemetry as st # noqa: E402
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _iso(offset_seconds: float = 0.0) -> str:
|
| 35 |
+
return (
|
| 36 |
+
datetime.now(timezone.utc) + timedelta(seconds=offset_seconds)
|
| 37 |
+
).isoformat(timespec="seconds")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _event(**overrides: object) -> st.TelemetryEvent:
|
| 41 |
+
defaults: dict[str, object] = {
|
| 42 |
+
"event": "load",
|
| 43 |
+
"skill": "x",
|
| 44 |
+
"timestamp": _iso(),
|
| 45 |
+
"session_id": "s1",
|
| 46 |
+
"event_id": "e-default",
|
| 47 |
+
}
|
| 48 |
+
defaults.update(overrides)
|
| 49 |
+
return st.TelemetryEvent(**defaults) # type: ignore[arg-type]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# ────────────────────────────────────────────────────────────────────
|
| 53 |
+
# Event validation
|
| 54 |
+
# ────────────────────────────────────────────────────────────────────
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_event_accepts_all_defined_types() -> None:
|
| 58 |
+
for kind in ("load", "unload", "override", "switch_away"):
|
| 59 |
+
_event(event=kind)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def test_event_rejects_unknown_type() -> None:
|
| 63 |
+
with pytest.raises(ValueError, match="invalid event type"):
|
| 64 |
+
_event(event="explode")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@pytest.mark.parametrize(
|
| 68 |
+
"bad_name",
|
| 69 |
+
[
|
| 70 |
+
"",
|
| 71 |
+
"../etc/passwd",
|
| 72 |
+
"skill/with/slash",
|
| 73 |
+
"skill with space",
|
| 74 |
+
"-leading-dash",
|
| 75 |
+
"a" * 200,
|
| 76 |
+
],
|
| 77 |
+
)
|
| 78 |
+
def test_event_rejects_unsafe_skill_name(bad_name: str) -> None:
|
| 79 |
+
with pytest.raises(ValueError, match="invalid skill name"):
|
| 80 |
+
_event(skill=bad_name)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def test_event_rejects_empty_session_id() -> None:
|
| 84 |
+
with pytest.raises(ValueError, match="session_id"):
|
| 85 |
+
_event(session_id="")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def test_event_rejects_empty_event_id() -> None:
|
| 89 |
+
with pytest.raises(ValueError, match="event_id"):
|
| 90 |
+
_event(event_id="")
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def test_event_rejects_non_iso_timestamp() -> None:
|
| 94 |
+
with pytest.raises(ValueError, match="timestamp must be ISO-8601"):
|
| 95 |
+
_event(timestamp="not-a-time")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# ────────────────────────────────────────────────────────────────────
|
| 99 |
+
# meta validation
|
| 100 |
+
# ────────────────────────────────────────────────────────────────────
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def test_log_event_rejects_oversized_meta(tmp_path: Path) -> None:
|
| 104 |
+
big = {f"k{i}": i for i in range(st._MAX_META_KEYS + 1)}
|
| 105 |
+
with pytest.raises(ValueError, match="max"):
|
| 106 |
+
st.log_event("load", "x", "s1", meta=big, path=tmp_path / "e.jsonl",
|
| 107 |
+
trusted_root=tmp_path)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def test_log_event_rejects_non_scalar_meta_value(tmp_path: Path) -> None:
|
| 111 |
+
with pytest.raises(TypeError, match="must be str/int/float/bool/None"):
|
| 112 |
+
st.log_event(
|
| 113 |
+
"load", "x", "s1", meta={"nested": {"a": 1}},
|
| 114 |
+
path=tmp_path / "e.jsonl", trusted_root=tmp_path,
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def test_log_event_rejects_oversized_meta_string(tmp_path: Path) -> None:
|
| 119 |
+
with pytest.raises(ValueError, match="exceeds"):
|
| 120 |
+
st.log_event(
|
| 121 |
+
"load", "x", "s1",
|
| 122 |
+
meta={"big": "a" * (st._MAX_META_VALUE_LEN + 1)},
|
| 123 |
+
path=tmp_path / "e.jsonl",
|
| 124 |
+
trusted_root=tmp_path,
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# ────────────────────────────────────────────────────────────────────
|
| 129 |
+
# Round-trip
|
| 130 |
+
# ────────────────────────────────────────────────────────────────────
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def test_log_event_and_read_events_round_trip(tmp_path: Path) -> None:
|
| 134 |
+
events_path = tmp_path / "skill-events.jsonl"
|
| 135 |
+
|
| 136 |
+
rec_a = st.log_event(
|
| 137 |
+
"load", "python-patterns", "sess-1",
|
| 138 |
+
meta={"source": "unit-test"}, path=events_path, trusted_root=tmp_path,
|
| 139 |
+
)
|
| 140 |
+
rec_b = st.log_event(
|
| 141 |
+
"unload", "python-patterns", "sess-1", path=events_path,
|
| 142 |
+
trusted_root=tmp_path,
|
| 143 |
+
)
|
| 144 |
+
rec_c = st.log_event(
|
| 145 |
+
"override", "flask", "sess-1",
|
| 146 |
+
meta={"replaced_with": "fastapi"}, path=events_path, trusted_root=tmp_path,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
got = list(st.read_events(path=events_path, trusted_root=tmp_path))
|
| 150 |
+
assert [e.event for e in got] == ["load", "unload", "override"]
|
| 151 |
+
assert got[0].event_id == rec_a.event_id
|
| 152 |
+
assert got[1].event_id == rec_b.event_id
|
| 153 |
+
assert got[2].event_id == rec_c.event_id
|
| 154 |
+
assert got[0].meta == {"source": "unit-test"}
|
| 155 |
+
assert got[2].meta == {"replaced_with": "fastapi"}
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def test_read_events_missing_file_yields_nothing(tmp_path: Path) -> None:
|
| 159 |
+
assert list(st.read_events(path=tmp_path / "nope.jsonl", trusted_root=tmp_path)) == []
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def test_read_events_skips_malformed_lines(
|
| 163 |
+
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
| 164 |
+
) -> None:
|
| 165 |
+
events_path = tmp_path / "skill-events.jsonl"
|
| 166 |
+
# One valid event, one garbage line, one event missing a required key,
|
| 167 |
+
# one event missing event_id (now rejected), one blank line, one valid.
|
| 168 |
+
good1 = {
|
| 169 |
+
"event": "load", "skill": "x", "timestamp": _iso(),
|
| 170 |
+
"session_id": "s1", "event_id": "e1", "meta": {},
|
| 171 |
+
}
|
| 172 |
+
good2 = {
|
| 173 |
+
"event": "unload", "skill": "x", "timestamp": _iso(),
|
| 174 |
+
"session_id": "s1", "event_id": "e2", "meta": {},
|
| 175 |
+
}
|
| 176 |
+
missing_session = {
|
| 177 |
+
"event": "load", "skill": "x", "timestamp": _iso(), "event_id": "ex",
|
| 178 |
+
}
|
| 179 |
+
missing_event_id = {
|
| 180 |
+
"event": "load", "skill": "x", "timestamp": _iso(), "session_id": "s1",
|
| 181 |
+
}
|
| 182 |
+
events_path.write_text(
|
| 183 |
+
json.dumps(good1) + "\n"
|
| 184 |
+
+ "not-json-at-all\n"
|
| 185 |
+
+ json.dumps(missing_session) + "\n"
|
| 186 |
+
+ json.dumps(missing_event_id) + "\n"
|
| 187 |
+
+ "\n"
|
| 188 |
+
+ json.dumps(good2) + "\n",
|
| 189 |
+
encoding="utf-8",
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
got = list(st.read_events(path=events_path, trusted_root=tmp_path))
|
| 193 |
+
assert [e.event_id for e in got] == ["e1", "e2"]
|
| 194 |
+
captured = capsys.readouterr()
|
| 195 |
+
# Warning is sanitised — no raw line content, no file path.
|
| 196 |
+
assert "skipping malformed event at line" in captured.err
|
| 197 |
+
assert "not-json-at-all" not in captured.err
|
| 198 |
+
assert str(events_path) not in captured.err
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def test_read_events_rejects_path_that_escapes_parent(tmp_path: Path) -> None:
|
| 202 |
+
# ``tmp_path / ".."`` resolves outside its own parent — must be refused.
|
| 203 |
+
bad = tmp_path / ".." / "evil.jsonl"
|
| 204 |
+
with pytest.raises(ValueError, match="escapes"):
|
| 205 |
+
list(st.read_events(path=bad))
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
# ────────────────────────────────────────────────────────────────────
|
| 209 |
+
# Concurrency
|
| 210 |
+
# ────────────────────────────────────────────────────────────────────
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def test_concurrent_appends_produce_wellformed_lines(tmp_path: Path) -> None:
|
| 214 |
+
events_path = tmp_path / "skill-events.jsonl"
|
| 215 |
+
N = 32
|
| 216 |
+
|
| 217 |
+
def worker(i: int) -> None:
|
| 218 |
+
st.log_event("load", f"skill{i:03d}", f"sess-{i}", path=events_path,
|
| 219 |
+
trusted_root=tmp_path)
|
| 220 |
+
|
| 221 |
+
with ThreadPoolExecutor(max_workers=8) as pool:
|
| 222 |
+
list(pool.map(worker, range(N)))
|
| 223 |
+
|
| 224 |
+
lines = events_path.read_text(encoding="utf-8").splitlines()
|
| 225 |
+
assert len(lines) == N
|
| 226 |
+
for line in lines:
|
| 227 |
+
obj = json.loads(line)
|
| 228 |
+
assert obj["event"] == "load"
|
| 229 |
+
assert obj["session_id"].startswith("sess-")
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
# ────────────────────────────────────────────────────────────────────
|
| 233 |
+
# Retention window
|
| 234 |
+
# ────────────────────────────────────────────────────────────────────
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def test_retention_window_floor_applies_below_threshold() -> None:
|
| 238 |
+
assert st.retention_window_seconds(30 * 60) == pytest.approx(20 * 60)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def test_retention_window_fraction_applies_above_threshold() -> None:
|
| 242 |
+
assert st.retention_window_seconds(4 * 3600) == pytest.approx(48 * 60)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def test_retention_window_rejects_negative_session() -> None:
|
| 246 |
+
with pytest.raises(ValueError):
|
| 247 |
+
st.retention_window_seconds(-1)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def test_retention_window_rejects_bad_fraction() -> None:
|
| 251 |
+
with pytest.raises(ValueError):
|
| 252 |
+
st.retention_window_seconds(60, fraction=1.5)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def test_is_retained_true_at_and_above_window() -> None:
|
| 256 |
+
t0 = datetime(2026, 4, 18, 12, 0, 0, tzinfo=timezone.utc)
|
| 257 |
+
t1 = t0 + timedelta(minutes=20)
|
| 258 |
+
assert st.is_retained(t0.isoformat(), t1.isoformat(), session_seconds=600) is True
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def test_is_retained_false_below_window() -> None:
|
| 262 |
+
t0 = datetime(2026, 4, 18, 12, 0, 0, tzinfo=timezone.utc)
|
| 263 |
+
t1 = t0 + timedelta(minutes=19, seconds=59)
|
| 264 |
+
assert st.is_retained(t0.isoformat(), t1.isoformat(), session_seconds=600) is False
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def test_is_retained_rejects_reversed_timestamps() -> None:
|
| 268 |
+
t0 = datetime(2026, 4, 18, 12, 0, 0, tzinfo=timezone.utc)
|
| 269 |
+
t1 = t0 - timedelta(minutes=1)
|
| 270 |
+
with pytest.raises(ValueError):
|
| 271 |
+
st.is_retained(t0.isoformat(), t1.isoformat(), session_seconds=600)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def test_is_retained_treats_naive_timestamps_as_utc() -> None:
|
| 275 |
+
# Naive load_ts (no tz) mixed with aware unload_ts must not raise.
|
| 276 |
+
load_ts = "2026-04-18T12:00:00"
|
| 277 |
+
unload_ts = "2026-04-18T12:30:00+00:00"
|
| 278 |
+
assert st.is_retained(load_ts, unload_ts, session_seconds=600) is True
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def test_is_retained_both_naive_ok() -> None:
|
| 282 |
+
load_ts = "2026-04-18T12:00:00"
|
| 283 |
+
unload_ts = "2026-04-18T12:30:00"
|
| 284 |
+
assert st.is_retained(load_ts, unload_ts, session_seconds=600) is True
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
# ─────────────────────────────────────────────────���──────────────────
|
| 288 |
+
# Default path resolution
|
| 289 |
+
# ────────────────────────────────────────────────────────────────────
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def test_default_events_path_resolves_under_claude_dir(
|
| 293 |
+
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
| 294 |
+
) -> None:
|
| 295 |
+
# Simpler than reloading the module: just monkeypatch the constant
|
| 296 |
+
# the tests care about.
|
| 297 |
+
target = tmp_path / ".claude" / "skill-events.jsonl"
|
| 298 |
+
monkeypatch.setattr(st, "DEFAULT_EVENTS_PATH", target)
|
| 299 |
+
assert st.DEFAULT_EVENTS_PATH == target
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
# ────────────────────────────────────────────────────────────────────
|
| 303 |
+
# Trusted-root path containment (regression for Strix LOW finding)
|
| 304 |
+
# ────────────────────────────────────────────────────────────────────
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def test_resolve_events_path_rejects_etc_passwd() -> None:
|
| 308 |
+
"""Absolute path outside any trusted root must raise ValueError."""
|
| 309 |
+
with pytest.raises(ValueError, match="escapes trusted root"):
|
| 310 |
+
st._resolve_events_path(Path("/etc/passwd"))
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def test_resolve_events_path_rejects_windows_temp() -> None:
|
| 314 |
+
"""Windows absolute path outside trusted root must raise ValueError."""
|
| 315 |
+
with pytest.raises(ValueError, match="escapes trusted root"):
|
| 316 |
+
st._resolve_events_path(Path("C:/Windows/Temp/x"))
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def test_resolve_events_path_none_returns_default() -> None:
|
| 320 |
+
"""None path must return DEFAULT_EVENTS_PATH unchanged."""
|
| 321 |
+
result = st._resolve_events_path(None)
|
| 322 |
+
assert result == st.DEFAULT_EVENTS_PATH
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def test_resolve_events_path_tmp_path_with_trusted_root(tmp_path: Path) -> None:
|
| 326 |
+
"""A path inside tmp_path succeeds when trusted_root=tmp_path."""
|
| 327 |
+
target = tmp_path / "x.jsonl"
|
| 328 |
+
result = st._resolve_events_path(target, trusted_root=tmp_path)
|
| 329 |
+
assert result == target
|
src/tests/test_update_repo_stats.py
CHANGED
|
@@ -1,338 +1,391 @@
|
|
| 1 |
-
from __future__ import annotations
|
| 2 |
-
|
| 3 |
-
import io
|
| 4 |
-
import json
|
| 5 |
-
import sys
|
| 6 |
-
import tarfile
|
| 7 |
-
from pathlib import Path
|
| 8 |
-
|
| 9 |
-
import pytest
|
| 10 |
-
|
| 11 |
-
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 12 |
-
|
| 13 |
-
import update_repo_stats as urs # noqa: E402
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
def _add_bytes(tf: tarfile.TarFile, name: str, body: bytes) -> None:
|
| 17 |
-
info = tarfile.TarInfo(name)
|
| 18 |
-
info.size = len(body)
|
| 19 |
-
tf.addfile(info, io.BytesIO(body))
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
def _add_json(tf: tarfile.TarFile, name: str, body: object) -> None:
|
| 23 |
-
_add_bytes(tf, name, json.dumps(body).encode("utf-8"))
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
def _write_graph_tarball(root: Path, entries: list[tuple[str, object | bytes]]) -> None:
|
| 27 |
-
graph_dir = root / "graph"
|
| 28 |
-
graph_dir.mkdir()
|
| 29 |
-
with tarfile.open(graph_dir / "wiki-graph.tar.gz", "w:gz") as tf:
|
| 30 |
-
for name, body in entries:
|
| 31 |
-
if isinstance(body, bytes):
|
| 32 |
-
_add_bytes(tf, name, body)
|
| 33 |
-
else:
|
| 34 |
-
_add_json(tf, name, body)
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
def test_tarball_stats_only_trust_safe_regular_members(
|
| 38 |
-
tmp_path: Path,
|
| 39 |
-
monkeypatch: pytest.MonkeyPatch,
|
| 40 |
-
) -> None:
|
| 41 |
-
monkeypatch.setattr(urs, "REPO_ROOT", tmp_path)
|
| 42 |
-
_write_graph_tarball(
|
| 43 |
-
tmp_path,
|
| 44 |
-
[
|
| 45 |
-
("./graphify-out/graph.json", {"nodes": [{}, {}], "edges": [{}, {}, {}]}),
|
| 46 |
-
("./graphify-out/communities.json", {"total_communities": 4}),
|
| 47 |
-
("./entities/skills/good.md", b"# skill"),
|
| 48 |
-
("entities/agents/good.md", b"# agent"),
|
| 49 |
-
("entities/mcp-servers/a/good.md", b"# mcp"),
|
| 50 |
-
("entities/harnesses/good.md", b"# harness"),
|
| 51 |
-
("shadow/entities/skills/ignored.md", b"# ignored"),
|
| 52 |
-
("entities/skills/../ignored.md", b"# ignored"),
|
| 53 |
-
],
|
| 54 |
-
)
|
| 55 |
-
|
| 56 |
-
assert urs._read_graph_from_tarball() == {
|
| 57 |
-
"nodes": 2,
|
| 58 |
-
"edges": 3,
|
| 59 |
-
"skills": 1,
|
| 60 |
-
"agents": 1,
|
| 61 |
-
"mcps": 1,
|
| 62 |
-
"harnesses": 1,
|
| 63 |
-
"communities": 4,
|
| 64 |
-
}
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
def test_tarball_stats_reject_suffix_impersonation(
|
| 68 |
-
tmp_path: Path,
|
| 69 |
-
monkeypatch: pytest.MonkeyPatch,
|
| 70 |
-
) -> None:
|
| 71 |
-
monkeypatch.setattr(urs, "REPO_ROOT", tmp_path)
|
| 72 |
-
_write_graph_tarball(
|
| 73 |
-
tmp_path,
|
| 74 |
-
[
|
| 75 |
-
("evil/graphify-out/graph.json", {"nodes": [{}], "edges": []}),
|
| 76 |
-
("entities/skills/good.md", b"# skill"),
|
| 77 |
-
],
|
| 78 |
-
)
|
| 79 |
-
|
| 80 |
-
assert urs._read_graph_from_tarball() is None
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
def test_tarball_stats_reject_non_regular_json_member(
|
| 84 |
-
tmp_path: Path,
|
| 85 |
-
monkeypatch: pytest.MonkeyPatch,
|
| 86 |
-
) -> None:
|
| 87 |
-
monkeypatch.setattr(urs, "REPO_ROOT", tmp_path)
|
| 88 |
-
graph_dir = tmp_path / "graph"
|
| 89 |
-
graph_dir.mkdir()
|
| 90 |
-
with tarfile.open(graph_dir / "wiki-graph.tar.gz", "w:gz") as tf:
|
| 91 |
-
info = tarfile.TarInfo("graphify-out/graph.json")
|
| 92 |
-
info.type = tarfile.DIRTYPE
|
| 93 |
-
tf.addfile(info)
|
| 94 |
-
_add_bytes(tf, "entities/skills/good.md", b"# skill")
|
| 95 |
-
|
| 96 |
-
assert urs._read_graph_from_tarball() is None
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
def test_tarball_stats_reject_oversized_json_member(
|
| 100 |
-
tmp_path: Path,
|
| 101 |
-
monkeypatch: pytest.MonkeyPatch,
|
| 102 |
-
) -> None:
|
| 103 |
-
monkeypatch.setattr(urs, "REPO_ROOT", tmp_path)
|
| 104 |
-
monkeypatch.setattr(urs, "_MAX_TAR_JSON_BYTES", 8)
|
| 105 |
-
_write_graph_tarball(
|
| 106 |
-
tmp_path,
|
| 107 |
-
[
|
| 108 |
-
("graphify-out/graph.json", {"nodes": [{}], "edges": []}),
|
| 109 |
-
("entities/skills/good.md", b"# skill"),
|
| 110 |
-
],
|
| 111 |
-
)
|
| 112 |
-
|
| 113 |
-
assert urs._read_graph_from_tarball() is None
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
def test_tarball_stats_uses_report_when_graph_json_is_large(
|
| 117 |
-
tmp_path: Path,
|
| 118 |
-
monkeypatch: pytest.MonkeyPatch,
|
| 119 |
-
) -> None:
|
| 120 |
-
monkeypatch.setattr(urs, "REPO_ROOT", tmp_path)
|
| 121 |
-
monkeypatch.setattr(urs, "_MAX_TAR_JSON_BYTES", 8)
|
| 122 |
-
_write_graph_tarball(
|
| 123 |
-
tmp_path,
|
| 124 |
-
[
|
| 125 |
-
(
|
| 126 |
-
"graphify-out/graph-report.md",
|
| 127 |
-
b"# Graph Report\n\n> Nodes: 104078 | Edges: 2881027 | Communities: 50\n",
|
| 128 |
-
),
|
| 129 |
-
("graphify-out/graph.json", {"nodes": [{}], "edges": []}),
|
| 130 |
-
("entities/skills/good.md", b"# skill"),
|
| 131 |
-
("entities/agents/good.md", b"# agent"),
|
| 132 |
-
("entities/mcp-servers/a/good.md", b"# mcp"),
|
| 133 |
-
("entities/harnesses/good.md", b"# harness"),
|
| 134 |
-
],
|
| 135 |
-
)
|
| 136 |
-
|
| 137 |
-
stats = urs._read_graph_from_tarball()
|
| 138 |
-
assert stats is not None
|
| 139 |
-
assert {
|
| 140 |
-
key: stats[key]
|
| 141 |
-
for key in ("nodes", "edges", "skills", "agents", "mcps", "harnesses", "communities")
|
| 142 |
-
} == {
|
| 143 |
-
"nodes": 104078,
|
| 144 |
-
"edges": 2881027,
|
| 145 |
-
"skills": 1,
|
| 146 |
-
"agents": 1,
|
| 147 |
-
"mcps": 1,
|
| 148 |
-
"harnesses": 1,
|
| 149 |
-
"communities": 50,
|
| 150 |
-
}
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
def test_test_badge_is_labeled_collected_not_passing() -> None:
|
| 154 |
-
text = "[](#)"
|
| 155 |
-
stats = {
|
| 156 |
-
"nodes": None,
|
| 157 |
-
"edges": None,
|
| 158 |
-
"skills": None,
|
| 159 |
-
"agents": None,
|
| 160 |
-
"mcps": None,
|
| 161 |
-
"harnesses": None,
|
| 162 |
-
"communities": None,
|
| 163 |
-
}
|
| 164 |
-
patched = text
|
| 165 |
-
for pattern, replacement in urs.build_replacements(stats, tests=34, converted=None):
|
| 166 |
-
patched = pattern.sub(replacement, patched)
|
| 167 |
-
|
| 168 |
-
assert "Tests-34_collected" in patched
|
| 169 |
-
assert "_passing" not in patched
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
def test_docs_landing_test_count_is_updated() -> None:
|
| 173 |
-
text = "CI-matrixed, 3,617 tests collected. Ships console scripts."
|
| 174 |
-
stats = {
|
| 175 |
-
"nodes": None,
|
| 176 |
-
"edges": None,
|
| 177 |
-
"skills": None,
|
| 178 |
-
"agents": None,
|
| 179 |
-
"mcps": None,
|
| 180 |
-
"harnesses": None,
|
| 181 |
-
"communities": None,
|
| 182 |
-
}
|
| 183 |
-
patched = text
|
| 184 |
-
for pattern, replacement in urs.build_docs_replacements(
|
| 185 |
-
stats=stats,
|
| 186 |
-
tests=3619,
|
| 187 |
-
converted=None,
|
| 188 |
-
):
|
| 189 |
-
patched = pattern.sub(replacement, patched)
|
| 190 |
-
|
| 191 |
-
assert "3,619 tests collected" in patched
|
| 192 |
-
assert "3,617 tests collected" not in patched
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
def test_knowledge_graph_counts_are_updated() -> None:
|
| 196 |
-
text = "\n".join([
|
| 197 |
-
"| Total nodes | **102,925** |",
|
| 198 |
-
"| Curated core nodes | **13,460** (1,998 skills + 467 agents + 10,788 MCP servers + 207 harnesses) |",
|
| 199 |
-
"| Body-backed skill nodes | **89,463** hydrated installable skill entries |",
|
| 200 |
-
"| Total edges | **2,913,930** |",
|
| 201 |
-
"| Hydrated skill incident edges | **2,605,000** |",
|
| 202 |
-
"| Hydrated skill semantic incident edges | **1,500,000** |",
|
| 203 |
-
"| Edge sources (overlap-deduped) | semantic 1,683,163 - tag 897,754 - token 433,245 |",
|
| 204 |
-
"| Cross-type edges (skill <-> agent) | ~67K |",
|
| 205 |
-
"| Cross-type edges (skill <-> MCP) | ~41K |",
|
| 206 |
-
"| Cross-type edges (agent <-> MCP) | ~223 |",
|
| 207 |
-
"| Harness edges | **6,571** |",
|
| 208 |
-
])
|
| 209 |
-
stats = {
|
| 210 |
-
"nodes": 102928,
|
| 211 |
-
"edges": 2913960,
|
| 212 |
-
"skills": 91464,
|
| 213 |
-
"agents": 467,
|
| 214 |
-
"mcps": 10790,
|
| 215 |
-
"harnesses": 207,
|
| 216 |
-
"communities": 52,
|
| 217 |
-
"skills_sh_entries": 89465,
|
| 218 |
-
"skills_sh_bodies": 89465,
|
| 219 |
-
"semantic_edges": 1683193,
|
| 220 |
-
"tag_edges": 897784,
|
| 221 |
-
"token_edges": 433245,
|
| 222 |
-
"hydrated_incident_edges": 2605721,
|
| 223 |
-
"hydrated_semantic_incident_edges": 1500648,
|
| 224 |
-
"cross_skill_agent_edges": 66799,
|
| 225 |
-
"cross_skill_mcp_edges": 41521,
|
| 226 |
-
"cross_agent_mcp_edges": 229,
|
| 227 |
-
"harness_edges": 6576,
|
| 228 |
-
}
|
| 229 |
-
patched = text
|
| 230 |
-
for pattern, replacement in urs.build_replacements(stats, tests=None, converted=None):
|
| 231 |
-
patched = pattern.sub(replacement, patched)
|
| 232 |
-
|
| 233 |
-
assert "| Total nodes | **102,928** |" in patched
|
| 234 |
-
assert "| Curated core nodes | **13,463** (1,999 skills + 467 agents + 10,790 MCP servers + 207 harnesses) |" in patched
|
| 235 |
-
assert "| Body-backed skill nodes | **89,465** hydrated installable skill entries |" in patched
|
| 236 |
-
assert "| Total edges | **2,913,960** |" in patched
|
| 237 |
-
assert "semantic 1,683,193 - tag 897,784 - token 433,245" in patched
|
| 238 |
-
assert "| Cross-type edges (skill <-> agent) | ~66,799 |" in patched
|
| 239 |
-
assert "| Cross-type edges (skill <-> MCP) | ~41,521 |" in patched
|
| 240 |
-
assert "| Cross-type edges (agent <-> MCP) | ~229 |" in patched
|
| 241 |
-
assert "| Harness edges | **6,576** |" in patched
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
def test_harness_aware_readme_prose_is_updated() -> None:
|
| 245 |
-
text = (
|
| 246 |
-
"walks a **1,000 skills, 20 agents, 30 MCP servers, "
|
| 247 |
-
"and 4 cataloged harnesses** graph"
|
| 248 |
-
)
|
| 249 |
-
stats = {
|
| 250 |
-
"nodes": None,
|
| 251 |
-
"edges": None,
|
| 252 |
-
"skills": 92815,
|
| 253 |
-
"agents": 464,
|
| 254 |
-
"mcps": 10787,
|
| 255 |
-
"harnesses": 13,
|
| 256 |
-
"communities": None,
|
| 257 |
-
}
|
| 258 |
-
patched = text
|
| 259 |
-
for pattern, replacement in urs.build_replacements(stats, tests=None, converted=None):
|
| 260 |
-
patched = pattern.sub(replacement, patched)
|
| 261 |
-
|
| 262 |
-
assert "**92,815 skills, 464 agents, 10,787 MCP servers, and 13 harnesses**" in patched
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
def
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
assert
|
| 313 |
-
assert
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
monkeypatch.
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
)
|
| 330 |
-
(
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import io
|
| 4 |
+
import json
|
| 5 |
+
import sys
|
| 6 |
+
import tarfile
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
| 12 |
+
|
| 13 |
+
import update_repo_stats as urs # noqa: E402
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _add_bytes(tf: tarfile.TarFile, name: str, body: bytes) -> None:
|
| 17 |
+
info = tarfile.TarInfo(name)
|
| 18 |
+
info.size = len(body)
|
| 19 |
+
tf.addfile(info, io.BytesIO(body))
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _add_json(tf: tarfile.TarFile, name: str, body: object) -> None:
|
| 23 |
+
_add_bytes(tf, name, json.dumps(body).encode("utf-8"))
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _write_graph_tarball(root: Path, entries: list[tuple[str, object | bytes]]) -> None:
|
| 27 |
+
graph_dir = root / "graph"
|
| 28 |
+
graph_dir.mkdir()
|
| 29 |
+
with tarfile.open(graph_dir / "wiki-graph.tar.gz", "w:gz") as tf:
|
| 30 |
+
for name, body in entries:
|
| 31 |
+
if isinstance(body, bytes):
|
| 32 |
+
_add_bytes(tf, name, body)
|
| 33 |
+
else:
|
| 34 |
+
_add_json(tf, name, body)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def test_tarball_stats_only_trust_safe_regular_members(
|
| 38 |
+
tmp_path: Path,
|
| 39 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 40 |
+
) -> None:
|
| 41 |
+
monkeypatch.setattr(urs, "REPO_ROOT", tmp_path)
|
| 42 |
+
_write_graph_tarball(
|
| 43 |
+
tmp_path,
|
| 44 |
+
[
|
| 45 |
+
("./graphify-out/graph.json", {"nodes": [{}, {}], "edges": [{}, {}, {}]}),
|
| 46 |
+
("./graphify-out/communities.json", {"total_communities": 4}),
|
| 47 |
+
("./entities/skills/good.md", b"# skill"),
|
| 48 |
+
("entities/agents/good.md", b"# agent"),
|
| 49 |
+
("entities/mcp-servers/a/good.md", b"# mcp"),
|
| 50 |
+
("entities/harnesses/good.md", b"# harness"),
|
| 51 |
+
("shadow/entities/skills/ignored.md", b"# ignored"),
|
| 52 |
+
("entities/skills/../ignored.md", b"# ignored"),
|
| 53 |
+
],
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
assert urs._read_graph_from_tarball() == {
|
| 57 |
+
"nodes": 2,
|
| 58 |
+
"edges": 3,
|
| 59 |
+
"skills": 1,
|
| 60 |
+
"agents": 1,
|
| 61 |
+
"mcps": 1,
|
| 62 |
+
"harnesses": 1,
|
| 63 |
+
"communities": 4,
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def test_tarball_stats_reject_suffix_impersonation(
|
| 68 |
+
tmp_path: Path,
|
| 69 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 70 |
+
) -> None:
|
| 71 |
+
monkeypatch.setattr(urs, "REPO_ROOT", tmp_path)
|
| 72 |
+
_write_graph_tarball(
|
| 73 |
+
tmp_path,
|
| 74 |
+
[
|
| 75 |
+
("evil/graphify-out/graph.json", {"nodes": [{}], "edges": []}),
|
| 76 |
+
("entities/skills/good.md", b"# skill"),
|
| 77 |
+
],
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
assert urs._read_graph_from_tarball() is None
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def test_tarball_stats_reject_non_regular_json_member(
|
| 84 |
+
tmp_path: Path,
|
| 85 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 86 |
+
) -> None:
|
| 87 |
+
monkeypatch.setattr(urs, "REPO_ROOT", tmp_path)
|
| 88 |
+
graph_dir = tmp_path / "graph"
|
| 89 |
+
graph_dir.mkdir()
|
| 90 |
+
with tarfile.open(graph_dir / "wiki-graph.tar.gz", "w:gz") as tf:
|
| 91 |
+
info = tarfile.TarInfo("graphify-out/graph.json")
|
| 92 |
+
info.type = tarfile.DIRTYPE
|
| 93 |
+
tf.addfile(info)
|
| 94 |
+
_add_bytes(tf, "entities/skills/good.md", b"# skill")
|
| 95 |
+
|
| 96 |
+
assert urs._read_graph_from_tarball() is None
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def test_tarball_stats_reject_oversized_json_member(
|
| 100 |
+
tmp_path: Path,
|
| 101 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 102 |
+
) -> None:
|
| 103 |
+
monkeypatch.setattr(urs, "REPO_ROOT", tmp_path)
|
| 104 |
+
monkeypatch.setattr(urs, "_MAX_TAR_JSON_BYTES", 8)
|
| 105 |
+
_write_graph_tarball(
|
| 106 |
+
tmp_path,
|
| 107 |
+
[
|
| 108 |
+
("graphify-out/graph.json", {"nodes": [{}], "edges": []}),
|
| 109 |
+
("entities/skills/good.md", b"# skill"),
|
| 110 |
+
],
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
assert urs._read_graph_from_tarball() is None
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def test_tarball_stats_uses_report_when_graph_json_is_large(
|
| 117 |
+
tmp_path: Path,
|
| 118 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 119 |
+
) -> None:
|
| 120 |
+
monkeypatch.setattr(urs, "REPO_ROOT", tmp_path)
|
| 121 |
+
monkeypatch.setattr(urs, "_MAX_TAR_JSON_BYTES", 8)
|
| 122 |
+
_write_graph_tarball(
|
| 123 |
+
tmp_path,
|
| 124 |
+
[
|
| 125 |
+
(
|
| 126 |
+
"graphify-out/graph-report.md",
|
| 127 |
+
b"# Graph Report\n\n> Nodes: 104078 | Edges: 2881027 | Communities: 50\n",
|
| 128 |
+
),
|
| 129 |
+
("graphify-out/graph.json", {"nodes": [{}], "edges": []}),
|
| 130 |
+
("entities/skills/good.md", b"# skill"),
|
| 131 |
+
("entities/agents/good.md", b"# agent"),
|
| 132 |
+
("entities/mcp-servers/a/good.md", b"# mcp"),
|
| 133 |
+
("entities/harnesses/good.md", b"# harness"),
|
| 134 |
+
],
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
stats = urs._read_graph_from_tarball()
|
| 138 |
+
assert stats is not None
|
| 139 |
+
assert {
|
| 140 |
+
key: stats[key]
|
| 141 |
+
for key in ("nodes", "edges", "skills", "agents", "mcps", "harnesses", "communities")
|
| 142 |
+
} == {
|
| 143 |
+
"nodes": 104078,
|
| 144 |
+
"edges": 2881027,
|
| 145 |
+
"skills": 1,
|
| 146 |
+
"agents": 1,
|
| 147 |
+
"mcps": 1,
|
| 148 |
+
"harnesses": 1,
|
| 149 |
+
"communities": 50,
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def test_test_badge_is_labeled_collected_not_passing() -> None:
|
| 154 |
+
text = "[](#)"
|
| 155 |
+
stats = {
|
| 156 |
+
"nodes": None,
|
| 157 |
+
"edges": None,
|
| 158 |
+
"skills": None,
|
| 159 |
+
"agents": None,
|
| 160 |
+
"mcps": None,
|
| 161 |
+
"harnesses": None,
|
| 162 |
+
"communities": None,
|
| 163 |
+
}
|
| 164 |
+
patched = text
|
| 165 |
+
for pattern, replacement in urs.build_replacements(stats, tests=34, converted=None):
|
| 166 |
+
patched = pattern.sub(replacement, patched)
|
| 167 |
+
|
| 168 |
+
assert "Tests-34_collected" in patched
|
| 169 |
+
assert "_passing" not in patched
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def test_docs_landing_test_count_is_updated() -> None:
|
| 173 |
+
text = "CI-matrixed, 3,617 tests collected. Ships console scripts."
|
| 174 |
+
stats = {
|
| 175 |
+
"nodes": None,
|
| 176 |
+
"edges": None,
|
| 177 |
+
"skills": None,
|
| 178 |
+
"agents": None,
|
| 179 |
+
"mcps": None,
|
| 180 |
+
"harnesses": None,
|
| 181 |
+
"communities": None,
|
| 182 |
+
}
|
| 183 |
+
patched = text
|
| 184 |
+
for pattern, replacement in urs.build_docs_replacements(
|
| 185 |
+
stats=stats,
|
| 186 |
+
tests=3619,
|
| 187 |
+
converted=None,
|
| 188 |
+
):
|
| 189 |
+
patched = pattern.sub(replacement, patched)
|
| 190 |
+
|
| 191 |
+
assert "3,619 tests collected" in patched
|
| 192 |
+
assert "3,617 tests collected" not in patched
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def test_knowledge_graph_counts_are_updated() -> None:
|
| 196 |
+
text = "\n".join([
|
| 197 |
+
"| Total nodes | **102,925** |",
|
| 198 |
+
"| Curated core nodes | **13,460** (1,998 skills + 467 agents + 10,788 MCP servers + 207 harnesses) |",
|
| 199 |
+
"| Body-backed skill nodes | **89,463** hydrated installable skill entries |",
|
| 200 |
+
"| Total edges | **2,913,930** |",
|
| 201 |
+
"| Hydrated skill incident edges | **2,605,000** |",
|
| 202 |
+
"| Hydrated skill semantic incident edges | **1,500,000** |",
|
| 203 |
+
"| Edge sources (overlap-deduped) | semantic 1,683,163 - tag 897,754 - token 433,245 |",
|
| 204 |
+
"| Cross-type edges (skill <-> agent) | ~67K |",
|
| 205 |
+
"| Cross-type edges (skill <-> MCP) | ~41K |",
|
| 206 |
+
"| Cross-type edges (agent <-> MCP) | ~223 |",
|
| 207 |
+
"| Harness edges | **6,571** |",
|
| 208 |
+
])
|
| 209 |
+
stats = {
|
| 210 |
+
"nodes": 102928,
|
| 211 |
+
"edges": 2913960,
|
| 212 |
+
"skills": 91464,
|
| 213 |
+
"agents": 467,
|
| 214 |
+
"mcps": 10790,
|
| 215 |
+
"harnesses": 207,
|
| 216 |
+
"communities": 52,
|
| 217 |
+
"skills_sh_entries": 89465,
|
| 218 |
+
"skills_sh_bodies": 89465,
|
| 219 |
+
"semantic_edges": 1683193,
|
| 220 |
+
"tag_edges": 897784,
|
| 221 |
+
"token_edges": 433245,
|
| 222 |
+
"hydrated_incident_edges": 2605721,
|
| 223 |
+
"hydrated_semantic_incident_edges": 1500648,
|
| 224 |
+
"cross_skill_agent_edges": 66799,
|
| 225 |
+
"cross_skill_mcp_edges": 41521,
|
| 226 |
+
"cross_agent_mcp_edges": 229,
|
| 227 |
+
"harness_edges": 6576,
|
| 228 |
+
}
|
| 229 |
+
patched = text
|
| 230 |
+
for pattern, replacement in urs.build_replacements(stats, tests=None, converted=None):
|
| 231 |
+
patched = pattern.sub(replacement, patched)
|
| 232 |
+
|
| 233 |
+
assert "| Total nodes | **102,928** |" in patched
|
| 234 |
+
assert "| Curated core nodes | **13,463** (1,999 skills + 467 agents + 10,790 MCP servers + 207 harnesses) |" in patched
|
| 235 |
+
assert "| Body-backed skill nodes | **89,465** hydrated installable skill entries |" in patched
|
| 236 |
+
assert "| Total edges | **2,913,960** |" in patched
|
| 237 |
+
assert "semantic 1,683,193 - tag 897,784 - token 433,245" in patched
|
| 238 |
+
assert "| Cross-type edges (skill <-> agent) | ~66,799 |" in patched
|
| 239 |
+
assert "| Cross-type edges (skill <-> MCP) | ~41,521 |" in patched
|
| 240 |
+
assert "| Cross-type edges (agent <-> MCP) | ~229 |" in patched
|
| 241 |
+
assert "| Harness edges | **6,576** |" in patched
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def test_harness_aware_readme_prose_is_updated() -> None:
|
| 245 |
+
text = (
|
| 246 |
+
"walks a **1,000 skills, 20 agents, 30 MCP servers, "
|
| 247 |
+
"and 4 cataloged harnesses** graph"
|
| 248 |
+
)
|
| 249 |
+
stats = {
|
| 250 |
+
"nodes": None,
|
| 251 |
+
"edges": None,
|
| 252 |
+
"skills": 92815,
|
| 253 |
+
"agents": 464,
|
| 254 |
+
"mcps": 10787,
|
| 255 |
+
"harnesses": 13,
|
| 256 |
+
"communities": None,
|
| 257 |
+
}
|
| 258 |
+
patched = text
|
| 259 |
+
for pattern, replacement in urs.build_replacements(stats, tests=None, converted=None):
|
| 260 |
+
patched = pattern.sub(replacement, patched)
|
| 261 |
+
|
| 262 |
+
assert "**92,815 skills, 464 agents, 10,787 MCP servers, and 13 harnesses**" in patched
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def test_readme_entity_badges_are_updated() -> None:
|
| 266 |
+
text = "\n".join([
|
| 267 |
+
"[](graph/)",
|
| 268 |
+
"[](graph/)",
|
| 269 |
+
"[](graph/)",
|
| 270 |
+
"[](graph/)",
|
| 271 |
+
"[](graph/)",
|
| 272 |
+
])
|
| 273 |
+
stats = {
|
| 274 |
+
"nodes": None,
|
| 275 |
+
"edges": None,
|
| 276 |
+
"skills": 91464,
|
| 277 |
+
"agents": 467,
|
| 278 |
+
"mcps": 10790,
|
| 279 |
+
"harnesses": 207,
|
| 280 |
+
"communities": None,
|
| 281 |
+
}
|
| 282 |
+
patched = text
|
| 283 |
+
for pattern, replacement in urs.build_replacements(stats, tests=None, converted=None):
|
| 284 |
+
patched = pattern.sub(replacement, patched)
|
| 285 |
+
|
| 286 |
+
assert "badge/Skills-91%2C464-blue" in patched
|
| 287 |
+
assert "badge/Agents-467-purple" in patched
|
| 288 |
+
assert "badge/MCPs-10%2C790-pink" in patched
|
| 289 |
+
assert "badge/Harnesses-207-orange" in patched
|
| 290 |
+
assert "](https://stevesolun.github.io/ctx/knowledge-graph/)" in patched
|
| 291 |
+
assert (
|
| 292 |
+
patched.count("](https://stevesolun.github.io/ctx/dashboard/#catalog-badge-links)")
|
| 293 |
+
== 4
|
| 294 |
+
)
|
| 295 |
+
assert "127.0.0.1" not in patched
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def test_github_about_description_uses_current_entity_counts() -> None:
|
| 299 |
+
stats = {
|
| 300 |
+
"nodes": 102928,
|
| 301 |
+
"edges": 2_900_000,
|
| 302 |
+
"skills": 91464,
|
| 303 |
+
"agents": 467,
|
| 304 |
+
"mcps": 10790,
|
| 305 |
+
"harnesses": 207,
|
| 306 |
+
"communities": 52,
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
description = urs.build_github_about_description(stats)
|
| 310 |
+
|
| 311 |
+
assert "102,928-node LLM-wiki graph" in description
|
| 312 |
+
assert "91,464 skills" in description
|
| 313 |
+
assert "467 agents" in description
|
| 314 |
+
assert "10,790 MCPs" in description
|
| 315 |
+
assert "207 harnesses" in description
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def test_patch_readme_checks_knowledge_graph_doc(
|
| 319 |
+
tmp_path: Path,
|
| 320 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 321 |
+
) -> None:
|
| 322 |
+
readme = tmp_path / "README.md"
|
| 323 |
+
docs = tmp_path / "docs"
|
| 324 |
+
docs.mkdir()
|
| 325 |
+
docs_index = docs / "index.md"
|
| 326 |
+
docs_knowledge = docs / "knowledge-graph.md"
|
| 327 |
+
readme.write_text("Graph has 10 nodes and 20 edges\n", encoding="utf-8")
|
| 328 |
+
docs_index.write_text("3 tests collected\n", encoding="utf-8")
|
| 329 |
+
docs_knowledge.write_text("| Total nodes | **10** |\n", encoding="utf-8")
|
| 330 |
+
monkeypatch.setattr(urs, "REPO_ROOT", tmp_path)
|
| 331 |
+
monkeypatch.setattr(urs, "README", readme)
|
| 332 |
+
monkeypatch.setattr(urs, "DOCS_INDEX", docs_index)
|
| 333 |
+
monkeypatch.setattr(urs, "DOCS_KNOWLEDGE_GRAPH", docs_knowledge)
|
| 334 |
+
monkeypatch.setattr(
|
| 335 |
+
urs,
|
| 336 |
+
"read_graph_stats",
|
| 337 |
+
lambda: {
|
| 338 |
+
"nodes": 11,
|
| 339 |
+
"edges": 21,
|
| 340 |
+
"skills": None,
|
| 341 |
+
"agents": None,
|
| 342 |
+
"mcps": None,
|
| 343 |
+
"harnesses": None,
|
| 344 |
+
"communities": 1,
|
| 345 |
+
},
|
| 346 |
+
)
|
| 347 |
+
monkeypatch.setattr(urs, "read_test_count", lambda: None)
|
| 348 |
+
monkeypatch.setattr(urs, "read_converted_count", lambda: None)
|
| 349 |
+
|
| 350 |
+
assert urs.patch_readme(check_only=True) == 1
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def test_read_test_count_prefers_project_python(
|
| 354 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 355 |
+
) -> None:
|
| 356 |
+
calls: list[str] = []
|
| 357 |
+
|
| 358 |
+
def _collect(candidate: str) -> int | None:
|
| 359 |
+
calls.append(candidate)
|
| 360 |
+
return 34 if candidate == "python" else 30
|
| 361 |
+
|
| 362 |
+
monkeypatch.setattr(urs.sys, "executable", "python3")
|
| 363 |
+
monkeypatch.setattr(urs, "_pytest_collect", _collect)
|
| 364 |
+
|
| 365 |
+
assert urs.read_test_count() == 34
|
| 366 |
+
assert calls == ["python"]
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def test_uncollected_importorskip_tests_are_added_to_collection_count(
|
| 370 |
+
tmp_path: Path,
|
| 371 |
+
monkeypatch: pytest.MonkeyPatch,
|
| 372 |
+
) -> None:
|
| 373 |
+
monkeypatch.setattr(urs, "REPO_ROOT", tmp_path)
|
| 374 |
+
tests_dir = tmp_path / "src" / "tests"
|
| 375 |
+
tests_dir.mkdir(parents=True)
|
| 376 |
+
(tests_dir / "test_browser.py").write_text(
|
| 377 |
+
"import pytest\n"
|
| 378 |
+
"pytest.importorskip('playwright.sync_api')\n"
|
| 379 |
+
"def test_one(): pass\n"
|
| 380 |
+
"def test_two(): pass\n",
|
| 381 |
+
encoding="utf-8",
|
| 382 |
+
)
|
| 383 |
+
(tests_dir / "test_present.py").write_text(
|
| 384 |
+
"import pytest\n"
|
| 385 |
+
"pytest.importorskip('already.available')\n"
|
| 386 |
+
"def test_present(): pass\n",
|
| 387 |
+
encoding="utf-8",
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
stdout = "src/tests/test_present.py::test_present\n1 test collected\n"
|
| 391 |
+
assert urs._uncollected_importorskip_test_count(stdout) == 2
|
src/tests/test_validate_graph_artifacts.py
CHANGED
|
@@ -1,1192 +1,1193 @@
|
|
| 1 |
-
from __future__ import annotations
|
| 2 |
-
|
| 3 |
-
import gzip
|
| 4 |
-
import json
|
| 5 |
-
import sqlite3
|
| 6 |
-
import tarfile
|
| 7 |
-
import zlib
|
| 8 |
-
from io import BytesIO
|
| 9 |
-
from pathlib import Path
|
| 10 |
-
from typing import Any
|
| 11 |
-
|
| 12 |
-
import pytest
|
| 13 |
-
import yaml # type: ignore[import-untyped]
|
| 14 |
-
|
| 15 |
-
from validate_graph_artifacts import (
|
| 16 |
-
DEFAULT_HARNESSES,
|
| 17 |
-
GraphArtifactError,
|
| 18 |
-
_validate_root_entity_overlay,
|
| 19 |
-
_safe_tar_name,
|
| 20 |
-
_scan_graph_json,
|
| 21 |
-
validate_graph_artifacts,
|
| 22 |
-
)
|
| 23 |
-
|
| 24 |
-
_PREVIEW_HTML_FILES = (
|
| 25 |
-
"sample-top60.html",
|
| 26 |
-
"viz-ai-agents.html",
|
| 27 |
-
"viz-overview.html",
|
| 28 |
-
"viz-python.html",
|
| 29 |
-
"viz-security.html",
|
| 30 |
-
)
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
def _add_text(tf: tarfile.TarFile, name: str, text: str) -> None:
|
| 34 |
-
payload = text.encode("utf-8")
|
| 35 |
-
info = tarfile.TarInfo(name)
|
| 36 |
-
info.size = len(payload)
|
| 37 |
-
info.mode = 0o644
|
| 38 |
-
tf.addfile(info, BytesIO(payload))
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
def _add_bytes(tf: tarfile.TarFile, name: str, payload: bytes) -> None:
|
| 42 |
-
info = tarfile.TarInfo(name)
|
| 43 |
-
info.size = len(payload)
|
| 44 |
-
info.mode = 0o644
|
| 45 |
-
tf.addfile(info, BytesIO(payload))
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
def _dashboard_index_bytes(graph_dir: Path, *, export_id: str) -> bytes:
|
| 49 |
-
path = graph_dir / f"dashboard-index-{export_id}.sqlite3"
|
| 50 |
-
if path.exists():
|
| 51 |
-
path.unlink()
|
| 52 |
-
conn = sqlite3.connect(path)
|
| 53 |
-
try:
|
| 54 |
-
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
|
| 55 |
-
conn.execute(
|
| 56 |
-
"CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
|
| 57 |
-
"description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
|
| 58 |
-
)
|
| 59 |
-
conn.execute(
|
| 60 |
-
"CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
|
| 61 |
-
"PRIMARY KEY(slug,type,node_id))"
|
| 62 |
-
)
|
| 63 |
-
conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
|
| 64 |
-
conn.executemany(
|
| 65 |
-
"INSERT INTO meta VALUES(?,?)",
|
| 66 |
-
[
|
| 67 |
-
("version", "1"),
|
| 68 |
-
("export_id", json.dumps(export_id)),
|
| 69 |
-
("nodes_count", "2"),
|
| 70 |
-
("edges_count", "1"),
|
| 71 |
-
("max_degree", "1"),
|
| 72 |
-
("top_k", "40"),
|
| 73 |
-
],
|
| 74 |
-
)
|
| 75 |
-
conn.executemany(
|
| 76 |
-
"INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
|
| 77 |
-
[
|
| 78 |
-
("skill:skills-sh-example-skill", "skills-sh-example-skill", "skill", "[]", "", None, None, 1),
|
| 79 |
-
("harness:langgraph", "langgraph", "harness", "[]", "", None, None, 1),
|
| 80 |
-
],
|
| 81 |
-
)
|
| 82 |
-
conn.executemany(
|
| 83 |
-
"INSERT INTO slug_index VALUES(?,?,?)",
|
| 84 |
-
[
|
| 85 |
-
("skills-sh-example-skill", "skill", "skill:skills-sh-example-skill"),
|
| 86 |
-
("langgraph", "harness", "harness:langgraph"),
|
| 87 |
-
],
|
| 88 |
-
)
|
| 89 |
-
conn.executemany(
|
| 90 |
-
"INSERT INTO neighbors VALUES(?,?)",
|
| 91 |
-
[
|
| 92 |
-
("skill:skills-sh-example-skill", zlib.compress(json.dumps([{"target": "harness:langgraph"}]).encode("utf-8"))),
|
| 93 |
-
("harness:langgraph", zlib.compress(json.dumps([{"target": "skill:skills-sh-example-skill"}]).encode("utf-8"))),
|
| 94 |
-
],
|
| 95 |
-
)
|
| 96 |
-
conn.commit()
|
| 97 |
-
finally:
|
| 98 |
-
conn.close()
|
| 99 |
-
payload = path.read_bytes()
|
| 100 |
-
path.unlink()
|
| 101 |
-
return payload
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
def _write_catalog(graph_dir: Path, *, converted_path: str | None = None) -> None:
|
| 105 |
-
skill = {
|
| 106 |
-
"ctx_slug": "skills-sh-example-skill",
|
| 107 |
-
"graph_node_id": "skill:skills-sh-example-skill",
|
| 108 |
-
"entity_path": "entities/skills/skills-sh-example-skill.md",
|
| 109 |
-
"body_available": converted_path is not None,
|
| 110 |
-
"converted_path": converted_path,
|
| 111 |
-
}
|
| 112 |
-
catalog = {
|
| 113 |
-
"observed_unique_skills": 1,
|
| 114 |
-
"body_available_count": 1 if converted_path else 0,
|
| 115 |
-
"skills": [skill],
|
| 116 |
-
}
|
| 117 |
-
with gzip.open(graph_dir / "skills-sh-catalog.json.gz", "wt", encoding="utf-8") as f:
|
| 118 |
-
json.dump(catalog, f)
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
def _write_entity_overlay(graph_dir: Path) -> None:
|
| 122 |
-
payload = {
|
| 123 |
-
"overlay_id": "test-overlay",
|
| 124 |
-
"nodes": [
|
| 125 |
-
{
|
| 126 |
-
"id": "harness:langgraph",
|
| 127 |
-
"label": "langgraph",
|
| 128 |
-
"type": "harness",
|
| 129 |
-
}
|
| 130 |
-
],
|
| 131 |
-
"edges": [
|
| 132 |
-
{
|
| 133 |
-
"source": "skill:skills-sh-example-skill",
|
| 134 |
-
"target": "harness:langgraph",
|
| 135 |
-
"weight": 0.5,
|
| 136 |
-
"final_weight": 0.5,
|
| 137 |
-
"similarity_score": 0.5,
|
| 138 |
-
}
|
| 139 |
-
],
|
| 140 |
-
}
|
| 141 |
-
(graph_dir / "entity-overlays.jsonl").write_text(
|
| 142 |
-
json.dumps(payload) + "\n",
|
| 143 |
-
encoding="utf-8",
|
| 144 |
-
)
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
def _write_runtime_archive(
|
| 148 |
-
graph_dir: Path,
|
| 149 |
-
*,
|
| 150 |
-
graph: dict[str, Any],
|
| 151 |
-
include_queue: bool = False,
|
| 152 |
-
include_delta: bool = True,
|
| 153 |
-
include_report: bool = True,
|
| 154 |
-
include_manifest: bool = True,
|
| 155 |
-
delta_export_id: str = "export-test",
|
| 156 |
-
communities_export_id: str = "export-test",
|
| 157 |
-
report_export_id: str = "export-test",
|
| 158 |
-
manifest_export_id: str = "export-test",
|
| 159 |
-
) -> None:
|
| 160 |
-
with tarfile.open(graph_dir / "wiki-graph-runtime.tar.gz", "w:gz") as tf:
|
| 161 |
-
_add_text(tf, "index.md", "# Wiki\n")
|
| 162 |
-
_add_text(tf, "graphify-out/graph.json", json.dumps(graph, separators=(",", ":")))
|
| 163 |
-
if include_delta:
|
| 164 |
-
_add_text(
|
| 165 |
-
tf,
|
| 166 |
-
"graphify-out/graph-delta.json",
|
| 167 |
-
json.dumps({"export_id": delta_export_id, "nodes": [], "edges": []}),
|
| 168 |
-
)
|
| 169 |
-
_add_text(
|
| 170 |
-
tf,
|
| 171 |
-
"graphify-out/communities.json",
|
| 172 |
-
json.dumps({"export_id": communities_export_id, "total_communities": 1}),
|
| 173 |
-
)
|
| 174 |
-
if include_report:
|
| 175 |
-
_add_text(
|
| 176 |
-
tf,
|
| 177 |
-
"graphify-out/graph-report.md",
|
| 178 |
-
f"# Graph Report\n\n> Export ID: {report_export_id}\n",
|
| 179 |
-
)
|
| 180 |
-
if include_manifest:
|
| 181 |
-
_add_text(
|
| 182 |
-
tf,
|
| 183 |
-
"graphify-out/graph-export-manifest.json",
|
| 184 |
-
json.dumps({
|
| 185 |
-
"version": 1,
|
| 186 |
-
"export_id": manifest_export_id,
|
| 187 |
-
"artifacts": {
|
| 188 |
-
"graph": "graph.json",
|
| 189 |
-
"delta": "graph-delta.json",
|
| 190 |
-
"communities": "communities.json",
|
| 191 |
-
"report": "graph-report.md",
|
| 192 |
-
},
|
| 193 |
-
"counts": {"nodes": 2, "edges": 1, "communities": 1},
|
| 194 |
-
}),
|
| 195 |
-
)
|
| 196 |
-
_add_bytes(
|
| 197 |
-
tf,
|
| 198 |
-
"graphify-out/dashboard-neighborhoods.sqlite3",
|
| 199 |
-
_dashboard_index_bytes(graph_dir, export_id=manifest_export_id),
|
| 200 |
-
)
|
| 201 |
-
_add_text(tf, "external-catalogs/skills-sh/catalog.json", "{}")
|
| 202 |
-
if include_queue:
|
| 203 |
-
_add_text(tf, ".ctx/wiki-queue.sqlite3", "not a shipped artifact\n")
|
| 204 |
-
for slug in sorted(DEFAULT_HARNESSES):
|
| 205 |
-
_add_text(tf, f"entities/harnesses/{slug}.md", f"# {slug}\n")
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
def _write_archive(
|
| 209 |
-
graph_dir: Path,
|
| 210 |
-
*,
|
| 211 |
-
include_converted: bool = True,
|
| 212 |
-
converted_skill_text: str = "# Example\n",
|
| 213 |
-
include_original: bool = False,
|
| 214 |
-
include_lock: bool = False,
|
| 215 |
-
include_queue: bool = False,
|
| 216 |
-
include_delta: bool = True,
|
| 217 |
-
include_report: bool = True,
|
| 218 |
-
include_manifest: bool = True,
|
| 219 |
-
graph_export_id: str = "export-test",
|
| 220 |
-
delta_export_id: str = "export-test",
|
| 221 |
-
communities_export_id: str | None = None,
|
| 222 |
-
report_export_id: str | None = None,
|
| 223 |
-
manifest_export_id: str | None = None,
|
| 224 |
-
) -> None:
|
| 225 |
-
_write_entity_overlay(graph_dir)
|
| 226 |
-
communities_export_id = communities_export_id or graph_export_id
|
| 227 |
-
report_export_id = report_export_id or graph_export_id
|
| 228 |
-
manifest_export_id = manifest_export_id or graph_export_id
|
| 229 |
-
graph = {
|
| 230 |
-
"graph": {"export_id": graph_export_id},
|
| 231 |
-
"nodes": [
|
| 232 |
-
{
|
| 233 |
-
"id": "skill:skills-sh-example-skill",
|
| 234 |
-
"type": "skill",
|
| 235 |
-
"source_catalog": "skills.sh",
|
| 236 |
-
},
|
| 237 |
-
{"id": "harness:langgraph", "type": "harness"},
|
| 238 |
-
],
|
| 239 |
-
"edges": [
|
| 240 |
-
{
|
| 241 |
-
"source": "skill:skills-sh-example-skill",
|
| 242 |
-
"target": "harness:langgraph",
|
| 243 |
-
"semantic_sim": 0.91,
|
| 244 |
-
},
|
| 245 |
-
],
|
| 246 |
-
}
|
| 247 |
-
with tarfile.open(graph_dir / "wiki-graph.tar.gz", "w:gz") as tf:
|
| 248 |
-
_add_text(tf, "./index.md", "# Wiki\n")
|
| 249 |
-
_add_text(tf, "./graphify-out/graph.json", json.dumps(graph, separators=(",", ":")))
|
| 250 |
-
if include_delta:
|
| 251 |
-
_add_text(
|
| 252 |
-
tf,
|
| 253 |
-
"./graphify-out/graph-delta.json",
|
| 254 |
-
json.dumps({"export_id": delta_export_id, "nodes": [], "edges": []}),
|
| 255 |
-
)
|
| 256 |
-
_add_text(
|
| 257 |
-
tf,
|
| 258 |
-
"./graphify-out/communities.json",
|
| 259 |
-
json.dumps({"export_id": communities_export_id, "total_communities": 1}),
|
| 260 |
-
)
|
| 261 |
-
if include_report:
|
| 262 |
-
_add_text(
|
| 263 |
-
tf,
|
| 264 |
-
"./graphify-out/graph-report.md",
|
| 265 |
-
f"# Graph Report\n\n> Export ID: {report_export_id}\n",
|
| 266 |
-
)
|
| 267 |
-
if include_manifest:
|
| 268 |
-
_add_text(
|
| 269 |
-
tf,
|
| 270 |
-
"./graphify-out/graph-export-manifest.json",
|
| 271 |
-
json.dumps({
|
| 272 |
-
"version": 1,
|
| 273 |
-
"export_id": manifest_export_id,
|
| 274 |
-
"artifacts": {
|
| 275 |
-
"graph": "graph.json",
|
| 276 |
-
"delta": "graph-delta.json",
|
| 277 |
-
"communities": "communities.json",
|
| 278 |
-
"report": "graph-report.md",
|
| 279 |
-
},
|
| 280 |
-
"counts": {"nodes": 2, "edges": 1, "communities": 1},
|
| 281 |
-
}),
|
| 282 |
-
)
|
| 283 |
-
_add_bytes(
|
| 284 |
-
tf,
|
| 285 |
-
"./graphify-out/dashboard-neighborhoods.sqlite3",
|
| 286 |
-
_dashboard_index_bytes(graph_dir, export_id=manifest_export_id),
|
| 287 |
-
)
|
| 288 |
-
_add_text(tf, "./external-catalogs/skills-sh/catalog.json", "{}")
|
| 289 |
-
_add_text(tf, "./entities/skills/skills-sh-example-skill.md", "# Example\n")
|
| 290 |
-
_add_text(tf, "./entities/harnesses/langgraph.md", "# LangGraph\n")
|
| 291 |
-
if include_converted:
|
| 292 |
-
_add_text(tf, "./converted/skills-sh-example-skill/SKILL.md", converted_skill_text)
|
| 293 |
-
_add_text(tf, "./converted/skills-sh-example-skill/references/01-scope.md", "# Scope\n")
|
| 294 |
-
if include_original:
|
| 295 |
-
_add_text(tf, "./converted/skills-sh-example-skill/SKILL.md.original", "# Raw\n")
|
| 296 |
-
if include_lock:
|
| 297 |
-
_add_text(tf, "./index.md.lock", "")
|
| 298 |
-
if include_queue:
|
| 299 |
-
_add_text(tf, "./.ctx/wiki-queue.sqlite3", "not a shipped artifact\n")
|
| 300 |
-
for preview in _PREVIEW_HTML_FILES:
|
| 301 |
-
(graph_dir / preview).write_text(
|
| 302 |
-
"\n".join([
|
| 303 |
-
"<!DOCTYPE html>",
|
| 304 |
-
"<html><head>",
|
| 305 |
-
f'<meta name="ctx-graph-export-id" content="{manifest_export_id}">',
|
| 306 |
-
"</head><body>",
|
| 307 |
-
"const CTX_GRAPH_METADATA = "
|
| 308 |
-
+ json.dumps({
|
| 309 |
-
"export_id": manifest_export_id,
|
| 310 |
-
"source_graph_nodes": 2,
|
| 311 |
-
"source_graph_edges": 1,
|
| 312 |
-
}),
|
| 313 |
-
"</body></html>",
|
| 314 |
-
]),
|
| 315 |
-
encoding="utf-8",
|
| 316 |
-
)
|
| 317 |
-
_write_runtime_archive(
|
| 318 |
-
graph_dir,
|
| 319 |
-
graph=graph,
|
| 320 |
-
include_delta=include_delta,
|
| 321 |
-
include_report=include_report,
|
| 322 |
-
include_manifest=include_manifest,
|
| 323 |
-
delta_export_id=delta_export_id,
|
| 324 |
-
communities_export_id=communities_export_id,
|
| 325 |
-
report_export_id=report_export_id,
|
| 326 |
-
manifest_export_id=manifest_export_id,
|
| 327 |
-
)
|
| 328 |
-
(graph_dir / "communities.json").write_text(
|
| 329 |
-
json.dumps({"export_id": communities_export_id, "total_communities": 1}),
|
| 330 |
-
encoding="utf-8",
|
| 331 |
-
)
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
def test_validate_graph_artifacts_checks_catalog_paths_and_deep_graph_stats(
|
| 335 |
-
tmp_path: Path,
|
| 336 |
-
) -> None:
|
| 337 |
-
_write_catalog(
|
| 338 |
-
tmp_path,
|
| 339 |
-
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 340 |
-
)
|
| 341 |
-
(tmp_path / "communities.json").write_text(
|
| 342 |
-
json.dumps({"total_communities": 1}),
|
| 343 |
-
encoding="utf-8",
|
| 344 |
-
)
|
| 345 |
-
_write_archive(tmp_path)
|
| 346 |
-
|
| 347 |
-
stats = validate_graph_artifacts(
|
| 348 |
-
tmp_path,
|
| 349 |
-
deep=True,
|
| 350 |
-
min_nodes=2,
|
| 351 |
-
min_edges=1,
|
| 352 |
-
min_skills_sh_nodes=1,
|
| 353 |
-
min_semantic_edges=1,
|
| 354 |
-
expected_harnesses={"langgraph"},
|
| 355 |
-
line_threshold=180,
|
| 356 |
-
max_stage_lines=40,
|
| 357 |
-
expected_nodes=2,
|
| 358 |
-
expected_edges=1,
|
| 359 |
-
expected_semantic_edges=1,
|
| 360 |
-
expected_harness_nodes=1,
|
| 361 |
-
expected_skills_sh_nodes=1,
|
| 362 |
-
expected_skills_sh_catalog_entries=1,
|
| 363 |
-
expected_skills_sh_converted=1,
|
| 364 |
-
expected_skill_pages=1,
|
| 365 |
-
expected_agent_pages=0,
|
| 366 |
-
expected_mcp_pages=0,
|
| 367 |
-
expected_harness_pages=1,
|
| 368 |
-
)
|
| 369 |
-
|
| 370 |
-
assert stats.graph_nodes == 2
|
| 371 |
-
assert stats.graph_edges == 1
|
| 372 |
-
assert stats.harness_nodes == 1
|
| 373 |
-
assert stats.skills_sh_catalog_entries == 1
|
| 374 |
-
assert stats.skills_sh_converted == 1
|
| 375 |
-
assert stats.harness_pages == 1
|
| 376 |
-
|
| 377 |
-
with pytest.raises(GraphArtifactError, match="graph_edges exact count mismatch"):
|
| 378 |
-
validate_graph_artifacts(
|
| 379 |
-
tmp_path,
|
| 380 |
-
deep=True,
|
| 381 |
-
min_nodes=2,
|
| 382 |
-
min_edges=1,
|
| 383 |
-
min_skills_sh_nodes=1,
|
| 384 |
-
min_semantic_edges=1,
|
| 385 |
-
expected_harnesses={"langgraph"},
|
| 386 |
-
expected_edges=2,
|
| 387 |
-
)
|
| 388 |
-
|
| 389 |
-
with pytest.raises(GraphArtifactError, match="deep=True is required"):
|
| 390 |
-
validate_graph_artifacts(
|
| 391 |
-
tmp_path,
|
| 392 |
-
expected_harnesses={"langgraph"},
|
| 393 |
-
expected_nodes=2,
|
| 394 |
-
)
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
def test_validate_graph_artifacts_rejects_mixed_export_generation(
|
| 398 |
-
tmp_path: Path,
|
| 399 |
-
) -> None:
|
| 400 |
-
_write_catalog(
|
| 401 |
-
tmp_path,
|
| 402 |
-
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 403 |
-
)
|
| 404 |
-
(tmp_path / "communities.json").write_text("{}", encoding="utf-8")
|
| 405 |
-
_write_archive(tmp_path, graph_export_id="new-export", delta_export_id="old-export")
|
| 406 |
-
|
| 407 |
-
with pytest.raises(GraphArtifactError, match="export_id mismatch"):
|
| 408 |
-
validate_graph_artifacts(
|
| 409 |
-
tmp_path,
|
| 410 |
-
deep=True,
|
| 411 |
-
min_nodes=2,
|
| 412 |
-
min_edges=1,
|
| 413 |
-
min_skills_sh_nodes=1,
|
| 414 |
-
min_semantic_edges=1,
|
| 415 |
-
expected_harnesses={"langgraph"},
|
| 416 |
-
)
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
def test_validate_graph_artifacts_rejects_runtime_full_export_split(
|
| 420 |
-
tmp_path: Path,
|
| 421 |
-
) -> None:
|
| 422 |
-
_write_catalog(
|
| 423 |
-
tmp_path,
|
| 424 |
-
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 425 |
-
)
|
| 426 |
-
_write_archive(tmp_path, graph_export_id="full-export")
|
| 427 |
-
runtime_graph = {
|
| 428 |
-
"graph": {"export_id": "runtime-export"},
|
| 429 |
-
"nodes": [
|
| 430 |
-
{"id": "skill:skills-sh-example-skill", "type": "skill"},
|
| 431 |
-
{"id": "harness:langgraph", "type": "harness"},
|
| 432 |
-
],
|
| 433 |
-
"edges": [
|
| 434 |
-
{"source": "skill:skills-sh-example-skill", "target": "harness:langgraph"},
|
| 435 |
-
],
|
| 436 |
-
}
|
| 437 |
-
_write_runtime_archive(
|
| 438 |
-
tmp_path,
|
| 439 |
-
graph=runtime_graph,
|
| 440 |
-
delta_export_id="runtime-export",
|
| 441 |
-
communities_export_id="runtime-export",
|
| 442 |
-
report_export_id="runtime-export",
|
| 443 |
-
manifest_export_id="runtime-export",
|
| 444 |
-
)
|
| 445 |
-
|
| 446 |
-
with pytest.raises(GraphArtifactError, match="runtime graph archive export_id mismatch"):
|
| 447 |
-
validate_graph_artifacts(
|
| 448 |
-
tmp_path,
|
| 449 |
-
deep=True,
|
| 450 |
-
min_nodes=2,
|
| 451 |
-
min_edges=1,
|
| 452 |
-
min_skills_sh_nodes=1,
|
| 453 |
-
min_semantic_edges=1,
|
| 454 |
-
expected_harnesses={"langgraph"},
|
| 455 |
-
)
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
def test_validate_graph_artifacts_rejects_corrupt_dashboard_index(
|
| 459 |
-
tmp_path: Path,
|
| 460 |
-
) -> None:
|
| 461 |
-
_write_catalog(
|
| 462 |
-
tmp_path,
|
| 463 |
-
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 464 |
-
)
|
| 465 |
-
_write_archive(tmp_path)
|
| 466 |
-
with tarfile.open(tmp_path / "wiki-graph-runtime.tar.gz", "w:gz") as tf:
|
| 467 |
-
graph = {
|
| 468 |
-
"graph": {"export_id": "export-test"},
|
| 469 |
-
"nodes": [
|
| 470 |
-
{"id": "skill:skills-sh-example-skill", "type": "skill"},
|
| 471 |
-
{"id": "harness:langgraph", "type": "harness"},
|
| 472 |
-
],
|
| 473 |
-
"edges": [
|
| 474 |
-
{"source": "skill:skills-sh-example-skill", "target": "harness:langgraph"},
|
| 475 |
-
],
|
| 476 |
-
}
|
| 477 |
-
_add_text(tf, "index.md", "# Wiki\n")
|
| 478 |
-
_add_text(tf, "graphify-out/graph.json", json.dumps(graph, separators=(",", ":")))
|
| 479 |
-
_add_text(tf, "graphify-out/graph-delta.json", json.dumps({"export_id": "export-test"}))
|
| 480 |
-
_add_text(tf, "graphify-out/communities.json", json.dumps({"export_id": "export-test"}))
|
| 481 |
-
_add_text(tf, "graphify-out/graph-report.md", "# Graph Report\n\n> Export ID: export-test\n")
|
| 482 |
-
_add_text(
|
| 483 |
-
tf,
|
| 484 |
-
"graphify-out/graph-export-manifest.json",
|
| 485 |
-
json.dumps({
|
| 486 |
-
"version": 1,
|
| 487 |
-
"export_id": "export-test",
|
| 488 |
-
"artifacts": {
|
| 489 |
-
"graph": "graph.json",
|
| 490 |
-
"delta": "graph-delta.json",
|
| 491 |
-
"communities": "communities.json",
|
| 492 |
-
"report": "graph-report.md",
|
| 493 |
-
},
|
| 494 |
-
"counts": {"nodes": 2, "edges": 1, "communities": 1},
|
| 495 |
-
}),
|
| 496 |
-
)
|
| 497 |
-
_add_text(tf, "graphify-out/dashboard-neighborhoods.sqlite3", "not sqlite\n")
|
| 498 |
-
_add_text(tf, "external-catalogs/skills-sh/catalog.json", "{}")
|
| 499 |
-
for slug in sorted(DEFAULT_HARNESSES):
|
| 500 |
-
_add_text(tf, f"entities/harnesses/{slug}.md", f"# {slug}\n")
|
| 501 |
-
|
| 502 |
-
with pytest.raises(GraphArtifactError, match="dashboard index"):
|
| 503 |
-
validate_graph_artifacts(
|
| 504 |
-
tmp_path,
|
| 505 |
-
deep=True,
|
| 506 |
-
min_nodes=2,
|
| 507 |
-
min_edges=1,
|
| 508 |
-
min_skills_sh_nodes=1,
|
| 509 |
-
min_semantic_edges=1,
|
| 510 |
-
expected_harnesses={"langgraph"},
|
| 511 |
-
)
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
def test_validate_graph_artifacts_rejects_stale_dashboard_index(
|
| 515 |
-
tmp_path: Path,
|
| 516 |
-
) -> None:
|
| 517 |
-
_write_catalog(
|
| 518 |
-
tmp_path,
|
| 519 |
-
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 520 |
-
)
|
| 521 |
-
_write_archive(tmp_path, graph_export_id="new-export", manifest_export_id="new-export")
|
| 522 |
-
with tarfile.open(tmp_path / "wiki-graph-runtime.tar.gz", "w:gz") as tf:
|
| 523 |
-
graph = {
|
| 524 |
-
"graph": {"export_id": "new-export"},
|
| 525 |
-
"nodes": [
|
| 526 |
-
{"id": "skill:skills-sh-example-skill", "type": "skill"},
|
| 527 |
-
{"id": "harness:langgraph", "type": "harness"},
|
| 528 |
-
],
|
| 529 |
-
"edges": [
|
| 530 |
-
{"source": "skill:skills-sh-example-skill", "target": "harness:langgraph"},
|
| 531 |
-
],
|
| 532 |
-
}
|
| 533 |
-
_add_text(tf, "index.md", "# Wiki\n")
|
| 534 |
-
_add_text(tf, "graphify-out/graph.json", json.dumps(graph, separators=(",", ":")))
|
| 535 |
-
_add_text(tf, "graphify-out/graph-delta.json", json.dumps({"export_id": "new-export"}))
|
| 536 |
-
_add_text(tf, "graphify-out/communities.json", json.dumps({"export_id": "new-export"}))
|
| 537 |
-
_add_text(tf, "graphify-out/graph-report.md", "# Graph Report\n\n> Export ID: new-export\n")
|
| 538 |
-
_add_text(
|
| 539 |
-
tf,
|
| 540 |
-
"graphify-out/graph-export-manifest.json",
|
| 541 |
-
json.dumps({
|
| 542 |
-
"version": 1,
|
| 543 |
-
"export_id": "new-export",
|
| 544 |
-
"artifacts": {
|
| 545 |
-
"graph": "graph.json",
|
| 546 |
-
"delta": "graph-delta.json",
|
| 547 |
-
"communities": "communities.json",
|
| 548 |
-
"report": "graph-report.md",
|
| 549 |
-
},
|
| 550 |
-
"counts": {"nodes": 2, "edges": 1, "communities": 1},
|
| 551 |
-
}),
|
| 552 |
-
)
|
| 553 |
-
_add_bytes(
|
| 554 |
-
tf,
|
| 555 |
-
"graphify-out/dashboard-neighborhoods.sqlite3",
|
| 556 |
-
_dashboard_index_bytes(tmp_path, export_id="old-export"),
|
| 557 |
-
)
|
| 558 |
-
_add_text(tf, "external-catalogs/skills-sh/catalog.json", "{}")
|
| 559 |
-
for slug in sorted(DEFAULT_HARNESSES):
|
| 560 |
-
_add_text(tf, f"entities/harnesses/{slug}.md", f"# {slug}\n")
|
| 561 |
-
|
| 562 |
-
with pytest.raises(GraphArtifactError, match="dashboard index export_id mismatch"):
|
| 563 |
-
validate_graph_artifacts(
|
| 564 |
-
tmp_path,
|
| 565 |
-
deep=True,
|
| 566 |
-
min_nodes=2,
|
| 567 |
-
min_edges=1,
|
| 568 |
-
min_skills_sh_nodes=1,
|
| 569 |
-
min_semantic_edges=1,
|
| 570 |
-
expected_harnesses={"langgraph"},
|
| 571 |
-
)
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
def test_validate_graph_artifacts_rejects_stale_preview_html(
|
| 575 |
-
tmp_path: Path,
|
| 576 |
-
) -> None:
|
| 577 |
-
_write_catalog(
|
| 578 |
-
tmp_path,
|
| 579 |
-
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 580 |
-
)
|
| 581 |
-
(tmp_path / "communities.json").write_text(
|
| 582 |
-
json.dumps({"total_communities": 1}),
|
| 583 |
-
encoding="utf-8",
|
| 584 |
-
)
|
| 585 |
-
_write_archive(tmp_path)
|
| 586 |
-
(tmp_path / "viz-overview.html").write_text(
|
| 587 |
-
'<meta name="ctx-graph-export-id" content="old-export">',
|
| 588 |
-
encoding="utf-8",
|
| 589 |
-
)
|
| 590 |
-
|
| 591 |
-
with pytest.raises(GraphArtifactError, match="stale graph preview"):
|
| 592 |
-
validate_graph_artifacts(
|
| 593 |
-
tmp_path,
|
| 594 |
-
deep=True,
|
| 595 |
-
min_nodes=2,
|
| 596 |
-
min_edges=1,
|
| 597 |
-
min_skills_sh_nodes=1,
|
| 598 |
-
min_semantic_edges=1,
|
| 599 |
-
expected_harnesses={"langgraph"},
|
| 600 |
-
)
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
def test_validate_graph_artifacts_rejects_stale_root_communities(
|
| 604 |
-
tmp_path: Path,
|
| 605 |
-
) -> None:
|
| 606 |
-
_write_catalog(
|
| 607 |
-
tmp_path,
|
| 608 |
-
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 609 |
-
)
|
| 610 |
-
_write_archive(tmp_path)
|
| 611 |
-
(tmp_path / "communities.json").write_text(
|
| 612 |
-
json.dumps({"export_id": "old-export", "total_communities": 1}),
|
| 613 |
-
encoding="utf-8",
|
| 614 |
-
)
|
| 615 |
-
|
| 616 |
-
with pytest.raises(GraphArtifactError, match="stale graph/communities.json"):
|
| 617 |
-
validate_graph_artifacts(
|
| 618 |
-
tmp_path,
|
| 619 |
-
expected_harnesses={"langgraph"},
|
| 620 |
-
)
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
@pytest.mark.parametrize(
|
| 624 |
-
("archive_kwargs", "missing_name"),
|
| 625 |
-
[
|
| 626 |
-
({"include_delta": False}, "graph-delta.json"),
|
| 627 |
-
({"include_report": False}, "graph-report.md"),
|
| 628 |
-
({"include_manifest": False}, "graph-export-manifest.json"),
|
| 629 |
-
],
|
| 630 |
-
)
|
| 631 |
-
def test_validate_graph_artifacts_rejects_missing_graph_export_files(
|
| 632 |
-
tmp_path: Path,
|
| 633 |
-
archive_kwargs: dict[str, Any],
|
| 634 |
-
missing_name: str,
|
| 635 |
-
) -> None:
|
| 636 |
-
_write_catalog(
|
| 637 |
-
tmp_path,
|
| 638 |
-
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 639 |
-
)
|
| 640 |
-
(tmp_path / "communities.json").write_text("{}", encoding="utf-8")
|
| 641 |
-
_write_archive(tmp_path, **archive_kwargs)
|
| 642 |
-
|
| 643 |
-
with pytest.raises(GraphArtifactError, match=missing_name):
|
| 644 |
-
validate_graph_artifacts(tmp_path, expected_harnesses={"langgraph"})
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
@pytest.mark.parametrize(
|
| 648 |
-
"archive_kwargs",
|
| 649 |
-
[
|
| 650 |
-
{"graph_export_id": "artifact-export", "manifest_export_id": "manifest-export"},
|
| 651 |
-
{"delta_export_id": "artifact-export", "manifest_export_id": "manifest-export"},
|
| 652 |
-
{
|
| 653 |
-
"communities_export_id": "artifact-export",
|
| 654 |
-
"manifest_export_id": "manifest-export",
|
| 655 |
-
},
|
| 656 |
-
{"report_export_id": "artifact-export", "manifest_export_id": "manifest-export"},
|
| 657 |
-
],
|
| 658 |
-
)
|
| 659 |
-
def test_validate_graph_artifacts_rejects_artifact_export_id_mismatch(
|
| 660 |
-
tmp_path: Path,
|
| 661 |
-
archive_kwargs: dict[str, Any],
|
| 662 |
-
) -> None:
|
| 663 |
-
_write_catalog(
|
| 664 |
-
tmp_path,
|
| 665 |
-
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 666 |
-
)
|
| 667 |
-
(tmp_path / "communities.json").write_text("{}", encoding="utf-8")
|
| 668 |
-
_write_archive(tmp_path, **archive_kwargs)
|
| 669 |
-
|
| 670 |
-
with pytest.raises(GraphArtifactError, match="export_id mismatch"):
|
| 671 |
-
validate_graph_artifacts(tmp_path, expected_harnesses={"langgraph"})
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
def test_validate_graph_artifacts_rejects_missing_converted_catalog_path(
|
| 675 |
-
tmp_path: Path,
|
| 676 |
-
) -> None:
|
| 677 |
-
_write_catalog(
|
| 678 |
-
tmp_path,
|
| 679 |
-
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 680 |
-
)
|
| 681 |
-
(tmp_path / "communities.json").write_text("{}", encoding="utf-8")
|
| 682 |
-
_write_archive(tmp_path, include_converted=False)
|
| 683 |
-
|
| 684 |
-
with pytest.raises(GraphArtifactError, match="missing converted Skills.sh body"):
|
| 685 |
-
validate_graph_artifacts(tmp_path)
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
def test_validate_graph_artifacts_rejects_missing_skill_bundle_reference(
|
| 689 |
-
tmp_path: Path,
|
| 690 |
-
) -> None:
|
| 691 |
-
_write_catalog(
|
| 692 |
-
tmp_path,
|
| 693 |
-
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 694 |
-
)
|
| 695 |
-
(tmp_path / "communities.json").write_text("{}", encoding="utf-8")
|
| 696 |
-
_write_archive(
|
| 697 |
-
tmp_path,
|
| 698 |
-
converted_skill_text=(
|
| 699 |
-
"# Example\n\n"
|
| 700 |
-
"Use `resources/implementation-playbook.md` for the implementation flow.\n"
|
| 701 |
-
),
|
| 702 |
-
)
|
| 703 |
-
|
| 704 |
-
with pytest.raises(GraphArtifactError, match="missing bundled skill file"):
|
| 705 |
-
validate_graph_artifacts(tmp_path, expected_harnesses={"langgraph"})
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
def test_validate_graph_artifacts_rejects_body_unavailable_catalog_records(
|
| 709 |
-
tmp_path: Path,
|
| 710 |
-
) -> None:
|
| 711 |
-
_write_catalog(tmp_path, converted_path=None)
|
| 712 |
-
(tmp_path / "communities.json").write_text("{}", encoding="utf-8")
|
| 713 |
-
_write_archive(tmp_path, include_converted=False)
|
| 714 |
-
|
| 715 |
-
with pytest.raises(GraphArtifactError, match="body-unavailable records"):
|
| 716 |
-
validate_graph_artifacts(tmp_path)
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
def test_validate_graph_artifacts_rejects_missing_entity_overlay(tmp_path: Path) -> None:
|
| 720 |
-
_write_catalog(
|
| 721 |
-
tmp_path,
|
| 722 |
-
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 723 |
-
)
|
| 724 |
-
_write_archive(tmp_path)
|
| 725 |
-
(tmp_path / "entity-overlays.jsonl").unlink()
|
| 726 |
-
|
| 727 |
-
with pytest.raises(GraphArtifactError, match="entity-overlays.jsonl"):
|
| 728 |
-
validate_graph_artifacts(tmp_path)
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
def test_validate_graph_artifacts_rejects_invalid_entity_overlay(tmp_path: Path) -> None:
|
| 732 |
-
_write_catalog(
|
| 733 |
-
tmp_path,
|
| 734 |
-
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 735 |
-
)
|
| 736 |
-
_write_archive(tmp_path)
|
| 737 |
-
(tmp_path / "entity-overlays.jsonl").write_text(
|
| 738 |
-
json.dumps({
|
| 739 |
-
"overlay_id": "bad-overlay",
|
| 740 |
-
"nodes": [{"id": "skill:bad"}],
|
| 741 |
-
"edges": [{"source": "skill:bad", "target": "skill:other", "weight": 2}],
|
| 742 |
-
})
|
| 743 |
-
+ "\n",
|
| 744 |
-
encoding="utf-8",
|
| 745 |
-
)
|
| 746 |
-
|
| 747 |
-
with pytest.raises(GraphArtifactError, match="weight must be 0..1"):
|
| 748 |
-
validate_graph_artifacts(tmp_path)
|
| 749 |
-
|
| 750 |
-
|
| 751 |
-
def test_validate_graph_artifacts_rejects_original_backup_members(tmp_path: Path) -> None:
|
| 752 |
-
_write_catalog(
|
| 753 |
-
tmp_path,
|
| 754 |
-
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 755 |
-
)
|
| 756 |
-
(tmp_path / "communities.json").write_text("{}", encoding="utf-8")
|
| 757 |
-
_write_archive(tmp_path, include_original=True)
|
| 758 |
-
|
| 759 |
-
with pytest.raises(GraphArtifactError, match="raw backup"):
|
| 760 |
-
validate_graph_artifacts(tmp_path)
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
def test_validate_graph_artifacts_rejects_lock_members(tmp_path: Path) -> None:
|
| 764 |
-
_write_catalog(
|
| 765 |
-
tmp_path,
|
| 766 |
-
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 767 |
-
)
|
| 768 |
-
(tmp_path / "communities.json").write_text("{}", encoding="utf-8")
|
| 769 |
-
_write_archive(tmp_path, include_lock=True)
|
| 770 |
-
|
| 771 |
-
with pytest.raises(GraphArtifactError, match="lock member"):
|
| 772 |
-
validate_graph_artifacts(tmp_path)
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
def test_validate_graph_artifacts_rejects_transient_queue_state(tmp_path: Path) -> None:
|
| 776 |
-
_write_catalog(
|
| 777 |
-
tmp_path,
|
| 778 |
-
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 779 |
-
)
|
| 780 |
-
_write_archive(tmp_path, include_queue=True)
|
| 781 |
-
|
| 782 |
-
with pytest.raises(GraphArtifactError, match="transient queue state"):
|
| 783 |
-
validate_graph_artifacts(tmp_path)
|
| 784 |
-
|
| 785 |
-
|
| 786 |
-
def test_validate_graph_artifacts_rejects_runtime_queue_state(tmp_path: Path) -> None:
|
| 787 |
-
_write_catalog(
|
| 788 |
-
tmp_path,
|
| 789 |
-
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 790 |
-
)
|
| 791 |
-
_write_archive(tmp_path)
|
| 792 |
-
graph = {
|
| 793 |
-
"graph": {"export_id": "export-test"},
|
| 794 |
-
"nodes": [
|
| 795 |
-
{"id": "skill:skills-sh-example-skill", "type": "skill"},
|
| 796 |
-
{"id": "harness:langgraph", "type": "harness"},
|
| 797 |
-
],
|
| 798 |
-
"edges": [],
|
| 799 |
-
}
|
| 800 |
-
_write_runtime_archive(tmp_path, graph=graph, include_queue=True)
|
| 801 |
-
|
| 802 |
-
with pytest.raises(GraphArtifactError, match="transient queue state"):
|
| 803 |
-
validate_graph_artifacts(tmp_path, expected_harnesses={"langgraph"})
|
| 804 |
-
|
| 805 |
-
|
| 806 |
-
@pytest.mark.parametrize(
|
| 807 |
-
"raw_name",
|
| 808 |
-
[
|
| 809 |
-
"../graphify-out/graph.json",
|
| 810 |
-
"./../graphify-out/graph.json",
|
| 811 |
-
"entities/../graphify-out/graph.json",
|
| 812 |
-
"/graphify-out/graph.json",
|
| 813 |
-
r"C:\tmp\graph.json",
|
| 814 |
-
"entities//skills/example.md",
|
| 815 |
-
],
|
| 816 |
-
)
|
| 817 |
-
def test_safe_tar_name_rejects_unsafe_members(raw_name: str) -> None:
|
| 818 |
-
with pytest.raises(GraphArtifactError, match="unsafe archive member path"):
|
| 819 |
-
_safe_tar_name(raw_name)
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
def test_safe_tar_name_strips_only_exact_current_dir_prefix() -> None:
|
| 823 |
-
assert _safe_tar_name("./graphify-out/graph.json") == "graphify-out/graph.json"
|
| 824 |
-
|
| 825 |
-
|
| 826 |
-
def test_scan_graph_json_handles_pretty_printed_graph() -> None:
|
| 827 |
-
graph = {
|
| 828 |
-
"nodes": [
|
| 829 |
-
{
|
| 830 |
-
"id": "skill:skills-sh-example-skill",
|
| 831 |
-
"type": "skill",
|
| 832 |
-
"source_catalog": "skills.sh",
|
| 833 |
-
},
|
| 834 |
-
{
|
| 835 |
-
"id": "harness:text-to-cad",
|
| 836 |
-
"type": "harness",
|
| 837 |
-
},
|
| 838 |
-
],
|
| 839 |
-
"edges": [
|
| 840 |
-
{
|
| 841 |
-
"source": "skill:skills-sh-example-skill",
|
| 842 |
-
"target": "harness:text-to-cad",
|
| 843 |
-
"semantic_sim": 0.0,
|
| 844 |
-
},
|
| 845 |
-
{
|
| 846 |
-
"source": "skill:skills-sh-example-skill",
|
| 847 |
-
"target": "harness:text-to-cad",
|
| 848 |
-
"semantic_sim": 0.82,
|
| 849 |
-
},
|
| 850 |
-
],
|
| 851 |
-
}
|
| 852 |
-
payload = json.dumps(graph, indent=2).encode("utf-8")
|
| 853 |
-
|
| 854 |
-
assert _scan_graph_json(BytesIO(payload)) == (2, 2, 1, 1, 1, None)
|
| 855 |
-
|
| 856 |
-
|
| 857 |
-
def test_scan_graph_json_rejects_out_of_range_edge_scores() -> None:
|
| 858 |
-
graph = {
|
| 859 |
-
"nodes": [{"id": "skill:a", "type": "skill"}],
|
| 860 |
-
"edges": [
|
| 861 |
-
{
|
| 862 |
-
"source": "skill:a",
|
| 863 |
-
"target": "skill:b",
|
| 864 |
-
"semantic_sim": 2.0,
|
| 865 |
-
"tag_sim": 0.0,
|
| 866 |
-
"token_sim": 0.0,
|
| 867 |
-
"weight": 0.5,
|
| 868 |
-
"final_weight": 0.5,
|
| 869 |
-
},
|
| 870 |
-
],
|
| 871 |
-
}
|
| 872 |
-
payload = json.dumps(graph).encode("utf-8")
|
| 873 |
-
|
| 874 |
-
with pytest.raises(GraphArtifactError, match="semantic_sim must be 0..1"):
|
| 875 |
-
_scan_graph_json(BytesIO(payload))
|
| 876 |
-
|
| 877 |
-
|
| 878 |
-
@pytest.mark.parametrize("raw", ["NaN", "Infinity", "-Infinity"])
|
| 879 |
-
def test_scan_graph_json_rejects_non_finite_edge_scores(raw: str) -> None:
|
| 880 |
-
payload = (
|
| 881 |
-
b'{"nodes":[{"id":"skill:a","type":"skill"}],"edges":['
|
| 882 |
-
b'{"source":"skill:a","target":"skill:b","semantic_sim":'
|
| 883 |
-
+ raw.encode("ascii")
|
| 884 |
-
+ b',"tag_sim":0.0,"token_sim":0.0,"weight":0.5,"final_weight":0.5}'
|
| 885 |
-
b"]}"
|
| 886 |
-
)
|
| 887 |
-
|
| 888 |
-
with pytest.raises(GraphArtifactError, match="semantic_sim must be finite"):
|
| 889 |
-
_scan_graph_json(BytesIO(payload))
|
| 890 |
-
|
| 891 |
-
|
| 892 |
-
def test_scan_graph_json_rejects_weight_final_weight_drift() -> None:
|
| 893 |
-
graph = {
|
| 894 |
-
"nodes": [{"id": "skill:a", "type": "skill"}],
|
| 895 |
-
"edges": [
|
| 896 |
-
{
|
| 897 |
-
"source": "skill:a",
|
| 898 |
-
"target": "skill:b",
|
| 899 |
-
"semantic_sim": 0.8,
|
| 900 |
-
"tag_sim": 0.0,
|
| 901 |
-
"token_sim": 0.0,
|
| 902 |
-
"weight": 0.7,
|
| 903 |
-
"final_weight": 0.5,
|
| 904 |
-
},
|
| 905 |
-
],
|
| 906 |
-
}
|
| 907 |
-
payload = json.dumps(graph).encode("utf-8")
|
| 908 |
-
|
| 909 |
-
with pytest.raises(GraphArtifactError, match="weight must equal final_weight"):
|
| 910 |
-
_scan_graph_json(BytesIO(payload))
|
| 911 |
-
|
| 912 |
-
|
| 913 |
-
def test_scan_graph_json_rejects_weight_drift_with_nested_score_components() -> None:
|
| 914 |
-
graph = {
|
| 915 |
-
"nodes": [{"id": "skill:a", "type": "skill"}],
|
| 916 |
-
"edges": [
|
| 917 |
-
{
|
| 918 |
-
"source": "skill:a",
|
| 919 |
-
"target": "skill:b",
|
| 920 |
-
"semantic_sim": 0.8,
|
| 921 |
-
"tag_sim": 0.0,
|
| 922 |
-
"token_sim": 0.0,
|
| 923 |
-
"weight": 0.7,
|
| 924 |
-
"final_weight": 0.5,
|
| 925 |
-
"score_components": {
|
| 926 |
-
"semantic": 0.8,
|
| 927 |
-
"tag": 0.0,
|
| 928 |
-
"token": 0.0,
|
| 929 |
-
},
|
| 930 |
-
},
|
| 931 |
-
],
|
| 932 |
-
}
|
| 933 |
-
payload = json.dumps(graph).encode("utf-8")
|
| 934 |
-
|
| 935 |
-
with pytest.raises(GraphArtifactError, match="weight must equal final_weight"):
|
| 936 |
-
_scan_graph_json(BytesIO(payload))
|
| 937 |
-
|
| 938 |
-
|
| 939 |
-
def test_scan_graph_json_rejects_score_component_drift() -> None:
|
| 940 |
-
graph = {
|
| 941 |
-
"nodes": [{"id": "skill:a", "type": "skill"}],
|
| 942 |
-
"edges": [
|
| 943 |
-
{
|
| 944 |
-
"source": "skill:a",
|
| 945 |
-
"target": "skill:b",
|
| 946 |
-
"semantic_sim": 0.8,
|
| 947 |
-
"tag_sim": 0.0,
|
| 948 |
-
"token_sim": 0.0,
|
| 949 |
-
"weight": 0.8,
|
| 950 |
-
"final_weight": 0.8,
|
| 951 |
-
"score_components": {
|
| 952 |
-
"semantic": 0.4,
|
| 953 |
-
"type_affinity": 0.1,
|
| 954 |
-
},
|
| 955 |
-
},
|
| 956 |
-
],
|
| 957 |
-
}
|
| 958 |
-
payload = json.dumps(graph).encode("utf-8")
|
| 959 |
-
|
| 960 |
-
with pytest.raises(GraphArtifactError, match="score_components must sum"):
|
| 961 |
-
_scan_graph_json(BytesIO(payload))
|
| 962 |
-
|
| 963 |
-
|
| 964 |
-
@pytest.mark.parametrize("value", [-0.1, 1.1])
|
| 965 |
-
def test_scan_graph_json_rejects_out_of_range_score_components(value: float) -> None:
|
| 966 |
-
graph = {
|
| 967 |
-
"nodes": [{"id": "skill:a", "type": "skill"}],
|
| 968 |
-
"edges": [
|
| 969 |
-
{
|
| 970 |
-
"source": "skill:a",
|
| 971 |
-
"target": "skill:b",
|
| 972 |
-
"weight": 0.5,
|
| 973 |
-
"final_weight": 0.5,
|
| 974 |
-
"score_components": {
|
| 975 |
-
"semantic": value,
|
| 976 |
-
"tag": 0.5 - value,
|
| 977 |
-
},
|
| 978 |
-
},
|
| 979 |
-
],
|
| 980 |
-
}
|
| 981 |
-
payload = json.dumps(graph).encode("utf-8")
|
| 982 |
-
|
| 983 |
-
with pytest.raises(GraphArtifactError, match="score_components must be 0..1"):
|
| 984 |
-
_scan_graph_json(BytesIO(payload))
|
| 985 |
-
|
| 986 |
-
|
| 987 |
-
@pytest.mark.parametrize("field", ["semantic_sim", "tag_sim", "token_sim"])
|
| 988 |
-
def test_overlay_validation_rejects_out_of_range_similarity_fields(
|
| 989 |
-
tmp_path: Path,
|
| 990 |
-
field: str,
|
| 991 |
-
) -> None:
|
| 992 |
-
(tmp_path / "entity-overlays.jsonl").write_text(
|
| 993 |
-
json.dumps({
|
| 994 |
-
"nodes": [{"id": "skill:a"}],
|
| 995 |
-
"edges": [
|
| 996 |
-
{
|
| 997 |
-
"source": "skill:a",
|
| 998 |
-
"target": "skill:b",
|
| 999 |
-
"weight": 0.5,
|
| 1000 |
-
"final_weight": 0.5,
|
| 1001 |
-
field: 2.0,
|
| 1002 |
-
},
|
| 1003 |
-
],
|
| 1004 |
-
})
|
| 1005 |
-
+ "\n",
|
| 1006 |
-
encoding="utf-8",
|
| 1007 |
-
)
|
| 1008 |
-
|
| 1009 |
-
with pytest.raises(GraphArtifactError, match=f"{field} must be 0..1"):
|
| 1010 |
-
_validate_root_entity_overlay(tmp_path / "entity-overlays.jsonl")
|
| 1011 |
-
|
| 1012 |
-
|
| 1013 |
-
def test_overlay_validation_rejects_weight_final_weight_drift(tmp_path: Path) -> None:
|
| 1014 |
-
(tmp_path / "entity-overlays.jsonl").write_text(
|
| 1015 |
-
json.dumps({
|
| 1016 |
-
"nodes": [{"id": "skill:a"}],
|
| 1017 |
-
"edges": [
|
| 1018 |
-
{
|
| 1019 |
-
"source": "skill:a",
|
| 1020 |
-
"target": "skill:b",
|
| 1021 |
-
"weight": 0.7,
|
| 1022 |
-
"final_weight": 0.5,
|
| 1023 |
-
},
|
| 1024 |
-
],
|
| 1025 |
-
})
|
| 1026 |
-
+ "\n",
|
| 1027 |
-
encoding="utf-8",
|
| 1028 |
-
)
|
| 1029 |
-
|
| 1030 |
-
with pytest.raises(GraphArtifactError, match="weight must equal final_weight"):
|
| 1031 |
-
_validate_root_entity_overlay(tmp_path / "entity-overlays.jsonl")
|
| 1032 |
-
|
| 1033 |
-
|
| 1034 |
-
def test_overlay_validation_rejects_score_component_drift(tmp_path: Path) -> None:
|
| 1035 |
-
(tmp_path / "entity-overlays.jsonl").write_text(
|
| 1036 |
-
json.dumps({
|
| 1037 |
-
"nodes": [{"id": "skill:a"}],
|
| 1038 |
-
"edges": [
|
| 1039 |
-
{
|
| 1040 |
-
"source": "skill:a",
|
| 1041 |
-
"target": "skill:b",
|
| 1042 |
-
"weight": 0.8,
|
| 1043 |
-
"final_weight": 0.8,
|
| 1044 |
-
"score_components": {
|
| 1045 |
-
"semantic": 0.4,
|
| 1046 |
-
"type_affinity": 0.1,
|
| 1047 |
-
},
|
| 1048 |
-
},
|
| 1049 |
-
],
|
| 1050 |
-
})
|
| 1051 |
-
+ "\n",
|
| 1052 |
-
encoding="utf-8",
|
| 1053 |
-
)
|
| 1054 |
-
|
| 1055 |
-
with pytest.raises(GraphArtifactError, match="score_components must sum"):
|
| 1056 |
-
_validate_root_entity_overlay(tmp_path / "entity-overlays.jsonl")
|
| 1057 |
-
|
| 1058 |
-
|
| 1059 |
-
@pytest.mark.parametrize("value", [-0.1, 1.1])
|
| 1060 |
-
def test_overlay_validation_rejects_out_of_range_score_components(
|
| 1061 |
-
tmp_path: Path,
|
| 1062 |
-
value: float,
|
| 1063 |
-
) -> None:
|
| 1064 |
-
(tmp_path / "entity-overlays.jsonl").write_text(
|
| 1065 |
-
json.dumps({
|
| 1066 |
-
"nodes": [{"id": "skill:a"}],
|
| 1067 |
-
"edges": [
|
| 1068 |
-
{
|
| 1069 |
-
"source": "skill:a",
|
| 1070 |
-
"target": "skill:b",
|
| 1071 |
-
"weight": 0.5,
|
| 1072 |
-
"final_weight": 0.5,
|
| 1073 |
-
"score_components": {
|
| 1074 |
-
"semantic": value,
|
| 1075 |
-
"tag": 0.5 - value,
|
| 1076 |
-
},
|
| 1077 |
-
},
|
| 1078 |
-
],
|
| 1079 |
-
})
|
| 1080 |
-
+ "\n",
|
| 1081 |
-
encoding="utf-8",
|
| 1082 |
-
)
|
| 1083 |
-
|
| 1084 |
-
with pytest.raises(GraphArtifactError, match="score_components must be 0..1"):
|
| 1085 |
-
_validate_root_entity_overlay(tmp_path / "entity-overlays.jsonl")
|
| 1086 |
-
|
| 1087 |
-
|
| 1088 |
-
def test_scan_graph_json_extracts_top_level_graph_export_id() -> None:
|
| 1089 |
-
graph = {
|
| 1090 |
-
"directed": False,
|
| 1091 |
-
"graph": {
|
| 1092 |
-
"source_catalog_nodes": {"skills.sh": 1},
|
| 1093 |
-
"source_catalog_edges": {"skills.sh": 0},
|
| 1094 |
-
"export_id": "graph-export",
|
| 1095 |
-
},
|
| 1096 |
-
"nodes": [
|
| 1097 |
-
{
|
| 1098 |
-
"id": "skill:skills-sh-example-skill",
|
| 1099 |
-
"type": "skill",
|
| 1100 |
-
"source_catalog": "skills.sh",
|
| 1101 |
-
},
|
| 1102 |
-
],
|
| 1103 |
-
"edges": [],
|
| 1104 |
-
}
|
| 1105 |
-
payload = json.dumps(graph, separators=(",", ":")).encode("utf-8")
|
| 1106 |
-
|
| 1107 |
-
assert _scan_graph_json(BytesIO(payload)) == (1, 0, 0, 1, 0, "graph-export")
|
| 1108 |
-
|
| 1109 |
-
|
| 1110 |
-
def test_scan_graph_json_ignores_node_level_export_id() -> None:
|
| 1111 |
-
graph = {
|
| 1112 |
-
"nodes": [
|
| 1113 |
-
{
|
| 1114 |
-
"id": "skill:skills-sh-example-skill",
|
| 1115 |
-
"type": "skill",
|
| 1116 |
-
"source_catalog": "skills.sh",
|
| 1117 |
-
"export_id": "node-export",
|
| 1118 |
-
},
|
| 1119 |
-
],
|
| 1120 |
-
"edges": [],
|
| 1121 |
-
}
|
| 1122 |
-
payload = json.dumps(graph, separators=(",", ":")).encode("utf-8")
|
| 1123 |
-
|
| 1124 |
-
assert _scan_graph_json(BytesIO(payload)) == (1, 0, 0, 1, 0, None)
|
| 1125 |
-
|
| 1126 |
-
|
| 1127 |
-
def test_graph_only_workflow_uses_exact_release_counts() -> None:
|
| 1128 |
-
workflow = yaml.safe_load(Path(".github/workflows/test.yml").read_text(
|
| 1129 |
-
encoding="utf-8"
|
| 1130 |
-
))
|
| 1131 |
-
steps = workflow["jobs"]["graph-check"]["steps"]
|
| 1132 |
-
validate_step = next(
|
| 1133 |
-
step for step in steps if step.get("name") == "Validate shipped graph artifacts"
|
| 1134 |
-
)
|
| 1135 |
-
command = " ".join(
|
| 1136 |
-
line.rstrip("\\").strip()
|
| 1137 |
-
for line in validate_step["run"].splitlines()
|
| 1138 |
-
if line.strip()
|
| 1139 |
-
)
|
| 1140 |
-
argv = command.split()
|
| 1141 |
-
|
| 1142 |
-
script_index = argv.index("src/validate_graph_artifacts.py")
|
| 1143 |
-
args = argv[script_index + 1:]
|
| 1144 |
-
parsed: dict[str, str | bool] = {}
|
| 1145 |
-
i = 0
|
| 1146 |
-
while i < len(args):
|
| 1147 |
-
flag = args[i]
|
| 1148 |
-
if i + 1 >= len(args) or args[i + 1].startswith("--"):
|
| 1149 |
-
parsed[flag] = True
|
| 1150 |
-
i += 1
|
| 1151 |
-
else:
|
| 1152 |
-
parsed[flag] = args[i + 1]
|
| 1153 |
-
i += 2
|
| 1154 |
-
|
| 1155 |
-
assert argv[:script_index + 1] == ["python", "src/validate_graph_artifacts.py"]
|
| 1156 |
-
assert parsed == {
|
| 1157 |
-
"--graph-dir": "graph",
|
| 1158 |
-
"--deep": True,
|
| 1159 |
-
"--min-nodes": "100000",
|
| 1160 |
-
"--min-edges": "2000000",
|
| 1161 |
-
"--min-skills-sh-nodes": "89000",
|
| 1162 |
-
"--min-semantic-edges": "1000000",
|
| 1163 |
-
"--expected-nodes": "102928",
|
| 1164 |
-
"--expected-edges": "2913960",
|
| 1165 |
-
"--expected-semantic-edges": "1683193",
|
| 1166 |
-
"--expected-harness-nodes": "207",
|
| 1167 |
-
"--expected-skills-sh-nodes": "89471",
|
| 1168 |
-
"--expected-skills-sh-catalog-entries": "89465",
|
| 1169 |
-
"--expected-skills-sh-converted": "89465",
|
| 1170 |
-
"--expected-skill-pages": "91464",
|
| 1171 |
-
"--expected-agent-pages": "467",
|
| 1172 |
-
"--expected-mcp-pages": "10790",
|
| 1173 |
-
"--expected-harness-pages": "207",
|
| 1174 |
-
"--line-threshold": "180",
|
| 1175 |
-
"--max-stage-lines": "40",
|
| 1176 |
-
}
|
| 1177 |
-
|
| 1178 |
-
|
| 1179 |
-
def test_graph_only_workflow_waits_for_release_asset_upload() -> None:
|
| 1180 |
-
workflow = yaml.safe_load(Path(".github/workflows/test.yml").read_text(
|
| 1181 |
-
encoding="utf-8"
|
| 1182 |
-
))
|
| 1183 |
-
steps = workflow["jobs"]["graph-check"]["steps"]
|
| 1184 |
-
resolve_step = next(
|
| 1185 |
-
step for step in steps
|
| 1186 |
-
|
| 1187 |
-
|
| 1188 |
-
|
| 1189 |
-
|
| 1190 |
-
assert "
|
| 1191 |
-
assert "
|
| 1192 |
-
assert "
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import gzip
|
| 4 |
+
import json
|
| 5 |
+
import sqlite3
|
| 6 |
+
import tarfile
|
| 7 |
+
import zlib
|
| 8 |
+
from io import BytesIO
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
import pytest
|
| 13 |
+
import yaml # type: ignore[import-untyped]
|
| 14 |
+
|
| 15 |
+
from validate_graph_artifacts import (
|
| 16 |
+
DEFAULT_HARNESSES,
|
| 17 |
+
GraphArtifactError,
|
| 18 |
+
_validate_root_entity_overlay,
|
| 19 |
+
_safe_tar_name,
|
| 20 |
+
_scan_graph_json,
|
| 21 |
+
validate_graph_artifacts,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
_PREVIEW_HTML_FILES = (
|
| 25 |
+
"sample-top60.html",
|
| 26 |
+
"viz-ai-agents.html",
|
| 27 |
+
"viz-overview.html",
|
| 28 |
+
"viz-python.html",
|
| 29 |
+
"viz-security.html",
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _add_text(tf: tarfile.TarFile, name: str, text: str) -> None:
|
| 34 |
+
payload = text.encode("utf-8")
|
| 35 |
+
info = tarfile.TarInfo(name)
|
| 36 |
+
info.size = len(payload)
|
| 37 |
+
info.mode = 0o644
|
| 38 |
+
tf.addfile(info, BytesIO(payload))
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _add_bytes(tf: tarfile.TarFile, name: str, payload: bytes) -> None:
|
| 42 |
+
info = tarfile.TarInfo(name)
|
| 43 |
+
info.size = len(payload)
|
| 44 |
+
info.mode = 0o644
|
| 45 |
+
tf.addfile(info, BytesIO(payload))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _dashboard_index_bytes(graph_dir: Path, *, export_id: str) -> bytes:
|
| 49 |
+
path = graph_dir / f"dashboard-index-{export_id}.sqlite3"
|
| 50 |
+
if path.exists():
|
| 51 |
+
path.unlink()
|
| 52 |
+
conn = sqlite3.connect(path)
|
| 53 |
+
try:
|
| 54 |
+
conn.execute("CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL)")
|
| 55 |
+
conn.execute(
|
| 56 |
+
"CREATE TABLE nodes(id TEXT PRIMARY KEY,label TEXT,type TEXT,tags TEXT,"
|
| 57 |
+
"description TEXT,quality_score REAL,usage_score REAL,degree INTEGER)"
|
| 58 |
+
)
|
| 59 |
+
conn.execute(
|
| 60 |
+
"CREATE TABLE slug_index(slug TEXT,type TEXT,node_id TEXT,"
|
| 61 |
+
"PRIMARY KEY(slug,type,node_id))"
|
| 62 |
+
)
|
| 63 |
+
conn.execute("CREATE TABLE neighbors(source TEXT PRIMARY KEY, payload BLOB NOT NULL)")
|
| 64 |
+
conn.executemany(
|
| 65 |
+
"INSERT INTO meta VALUES(?,?)",
|
| 66 |
+
[
|
| 67 |
+
("version", "1"),
|
| 68 |
+
("export_id", json.dumps(export_id)),
|
| 69 |
+
("nodes_count", "2"),
|
| 70 |
+
("edges_count", "1"),
|
| 71 |
+
("max_degree", "1"),
|
| 72 |
+
("top_k", "40"),
|
| 73 |
+
],
|
| 74 |
+
)
|
| 75 |
+
conn.executemany(
|
| 76 |
+
"INSERT INTO nodes VALUES(?,?,?,?,?,?,?,?)",
|
| 77 |
+
[
|
| 78 |
+
("skill:skills-sh-example-skill", "skills-sh-example-skill", "skill", "[]", "", None, None, 1),
|
| 79 |
+
("harness:langgraph", "langgraph", "harness", "[]", "", None, None, 1),
|
| 80 |
+
],
|
| 81 |
+
)
|
| 82 |
+
conn.executemany(
|
| 83 |
+
"INSERT INTO slug_index VALUES(?,?,?)",
|
| 84 |
+
[
|
| 85 |
+
("skills-sh-example-skill", "skill", "skill:skills-sh-example-skill"),
|
| 86 |
+
("langgraph", "harness", "harness:langgraph"),
|
| 87 |
+
],
|
| 88 |
+
)
|
| 89 |
+
conn.executemany(
|
| 90 |
+
"INSERT INTO neighbors VALUES(?,?)",
|
| 91 |
+
[
|
| 92 |
+
("skill:skills-sh-example-skill", zlib.compress(json.dumps([{"target": "harness:langgraph"}]).encode("utf-8"))),
|
| 93 |
+
("harness:langgraph", zlib.compress(json.dumps([{"target": "skill:skills-sh-example-skill"}]).encode("utf-8"))),
|
| 94 |
+
],
|
| 95 |
+
)
|
| 96 |
+
conn.commit()
|
| 97 |
+
finally:
|
| 98 |
+
conn.close()
|
| 99 |
+
payload = path.read_bytes()
|
| 100 |
+
path.unlink()
|
| 101 |
+
return payload
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _write_catalog(graph_dir: Path, *, converted_path: str | None = None) -> None:
|
| 105 |
+
skill = {
|
| 106 |
+
"ctx_slug": "skills-sh-example-skill",
|
| 107 |
+
"graph_node_id": "skill:skills-sh-example-skill",
|
| 108 |
+
"entity_path": "entities/skills/skills-sh-example-skill.md",
|
| 109 |
+
"body_available": converted_path is not None,
|
| 110 |
+
"converted_path": converted_path,
|
| 111 |
+
}
|
| 112 |
+
catalog = {
|
| 113 |
+
"observed_unique_skills": 1,
|
| 114 |
+
"body_available_count": 1 if converted_path else 0,
|
| 115 |
+
"skills": [skill],
|
| 116 |
+
}
|
| 117 |
+
with gzip.open(graph_dir / "skills-sh-catalog.json.gz", "wt", encoding="utf-8") as f:
|
| 118 |
+
json.dump(catalog, f)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _write_entity_overlay(graph_dir: Path) -> None:
|
| 122 |
+
payload = {
|
| 123 |
+
"overlay_id": "test-overlay",
|
| 124 |
+
"nodes": [
|
| 125 |
+
{
|
| 126 |
+
"id": "harness:langgraph",
|
| 127 |
+
"label": "langgraph",
|
| 128 |
+
"type": "harness",
|
| 129 |
+
}
|
| 130 |
+
],
|
| 131 |
+
"edges": [
|
| 132 |
+
{
|
| 133 |
+
"source": "skill:skills-sh-example-skill",
|
| 134 |
+
"target": "harness:langgraph",
|
| 135 |
+
"weight": 0.5,
|
| 136 |
+
"final_weight": 0.5,
|
| 137 |
+
"similarity_score": 0.5,
|
| 138 |
+
}
|
| 139 |
+
],
|
| 140 |
+
}
|
| 141 |
+
(graph_dir / "entity-overlays.jsonl").write_text(
|
| 142 |
+
json.dumps(payload) + "\n",
|
| 143 |
+
encoding="utf-8",
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _write_runtime_archive(
|
| 148 |
+
graph_dir: Path,
|
| 149 |
+
*,
|
| 150 |
+
graph: dict[str, Any],
|
| 151 |
+
include_queue: bool = False,
|
| 152 |
+
include_delta: bool = True,
|
| 153 |
+
include_report: bool = True,
|
| 154 |
+
include_manifest: bool = True,
|
| 155 |
+
delta_export_id: str = "export-test",
|
| 156 |
+
communities_export_id: str = "export-test",
|
| 157 |
+
report_export_id: str = "export-test",
|
| 158 |
+
manifest_export_id: str = "export-test",
|
| 159 |
+
) -> None:
|
| 160 |
+
with tarfile.open(graph_dir / "wiki-graph-runtime.tar.gz", "w:gz") as tf:
|
| 161 |
+
_add_text(tf, "index.md", "# Wiki\n")
|
| 162 |
+
_add_text(tf, "graphify-out/graph.json", json.dumps(graph, separators=(",", ":")))
|
| 163 |
+
if include_delta:
|
| 164 |
+
_add_text(
|
| 165 |
+
tf,
|
| 166 |
+
"graphify-out/graph-delta.json",
|
| 167 |
+
json.dumps({"export_id": delta_export_id, "nodes": [], "edges": []}),
|
| 168 |
+
)
|
| 169 |
+
_add_text(
|
| 170 |
+
tf,
|
| 171 |
+
"graphify-out/communities.json",
|
| 172 |
+
json.dumps({"export_id": communities_export_id, "total_communities": 1}),
|
| 173 |
+
)
|
| 174 |
+
if include_report:
|
| 175 |
+
_add_text(
|
| 176 |
+
tf,
|
| 177 |
+
"graphify-out/graph-report.md",
|
| 178 |
+
f"# Graph Report\n\n> Export ID: {report_export_id}\n",
|
| 179 |
+
)
|
| 180 |
+
if include_manifest:
|
| 181 |
+
_add_text(
|
| 182 |
+
tf,
|
| 183 |
+
"graphify-out/graph-export-manifest.json",
|
| 184 |
+
json.dumps({
|
| 185 |
+
"version": 1,
|
| 186 |
+
"export_id": manifest_export_id,
|
| 187 |
+
"artifacts": {
|
| 188 |
+
"graph": "graph.json",
|
| 189 |
+
"delta": "graph-delta.json",
|
| 190 |
+
"communities": "communities.json",
|
| 191 |
+
"report": "graph-report.md",
|
| 192 |
+
},
|
| 193 |
+
"counts": {"nodes": 2, "edges": 1, "communities": 1},
|
| 194 |
+
}),
|
| 195 |
+
)
|
| 196 |
+
_add_bytes(
|
| 197 |
+
tf,
|
| 198 |
+
"graphify-out/dashboard-neighborhoods.sqlite3",
|
| 199 |
+
_dashboard_index_bytes(graph_dir, export_id=manifest_export_id),
|
| 200 |
+
)
|
| 201 |
+
_add_text(tf, "external-catalogs/skills-sh/catalog.json", "{}")
|
| 202 |
+
if include_queue:
|
| 203 |
+
_add_text(tf, ".ctx/wiki-queue.sqlite3", "not a shipped artifact\n")
|
| 204 |
+
for slug in sorted(DEFAULT_HARNESSES):
|
| 205 |
+
_add_text(tf, f"entities/harnesses/{slug}.md", f"# {slug}\n")
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def _write_archive(
|
| 209 |
+
graph_dir: Path,
|
| 210 |
+
*,
|
| 211 |
+
include_converted: bool = True,
|
| 212 |
+
converted_skill_text: str = "# Example\n",
|
| 213 |
+
include_original: bool = False,
|
| 214 |
+
include_lock: bool = False,
|
| 215 |
+
include_queue: bool = False,
|
| 216 |
+
include_delta: bool = True,
|
| 217 |
+
include_report: bool = True,
|
| 218 |
+
include_manifest: bool = True,
|
| 219 |
+
graph_export_id: str = "export-test",
|
| 220 |
+
delta_export_id: str = "export-test",
|
| 221 |
+
communities_export_id: str | None = None,
|
| 222 |
+
report_export_id: str | None = None,
|
| 223 |
+
manifest_export_id: str | None = None,
|
| 224 |
+
) -> None:
|
| 225 |
+
_write_entity_overlay(graph_dir)
|
| 226 |
+
communities_export_id = communities_export_id or graph_export_id
|
| 227 |
+
report_export_id = report_export_id or graph_export_id
|
| 228 |
+
manifest_export_id = manifest_export_id or graph_export_id
|
| 229 |
+
graph = {
|
| 230 |
+
"graph": {"export_id": graph_export_id},
|
| 231 |
+
"nodes": [
|
| 232 |
+
{
|
| 233 |
+
"id": "skill:skills-sh-example-skill",
|
| 234 |
+
"type": "skill",
|
| 235 |
+
"source_catalog": "skills.sh",
|
| 236 |
+
},
|
| 237 |
+
{"id": "harness:langgraph", "type": "harness"},
|
| 238 |
+
],
|
| 239 |
+
"edges": [
|
| 240 |
+
{
|
| 241 |
+
"source": "skill:skills-sh-example-skill",
|
| 242 |
+
"target": "harness:langgraph",
|
| 243 |
+
"semantic_sim": 0.91,
|
| 244 |
+
},
|
| 245 |
+
],
|
| 246 |
+
}
|
| 247 |
+
with tarfile.open(graph_dir / "wiki-graph.tar.gz", "w:gz") as tf:
|
| 248 |
+
_add_text(tf, "./index.md", "# Wiki\n")
|
| 249 |
+
_add_text(tf, "./graphify-out/graph.json", json.dumps(graph, separators=(",", ":")))
|
| 250 |
+
if include_delta:
|
| 251 |
+
_add_text(
|
| 252 |
+
tf,
|
| 253 |
+
"./graphify-out/graph-delta.json",
|
| 254 |
+
json.dumps({"export_id": delta_export_id, "nodes": [], "edges": []}),
|
| 255 |
+
)
|
| 256 |
+
_add_text(
|
| 257 |
+
tf,
|
| 258 |
+
"./graphify-out/communities.json",
|
| 259 |
+
json.dumps({"export_id": communities_export_id, "total_communities": 1}),
|
| 260 |
+
)
|
| 261 |
+
if include_report:
|
| 262 |
+
_add_text(
|
| 263 |
+
tf,
|
| 264 |
+
"./graphify-out/graph-report.md",
|
| 265 |
+
f"# Graph Report\n\n> Export ID: {report_export_id}\n",
|
| 266 |
+
)
|
| 267 |
+
if include_manifest:
|
| 268 |
+
_add_text(
|
| 269 |
+
tf,
|
| 270 |
+
"./graphify-out/graph-export-manifest.json",
|
| 271 |
+
json.dumps({
|
| 272 |
+
"version": 1,
|
| 273 |
+
"export_id": manifest_export_id,
|
| 274 |
+
"artifacts": {
|
| 275 |
+
"graph": "graph.json",
|
| 276 |
+
"delta": "graph-delta.json",
|
| 277 |
+
"communities": "communities.json",
|
| 278 |
+
"report": "graph-report.md",
|
| 279 |
+
},
|
| 280 |
+
"counts": {"nodes": 2, "edges": 1, "communities": 1},
|
| 281 |
+
}),
|
| 282 |
+
)
|
| 283 |
+
_add_bytes(
|
| 284 |
+
tf,
|
| 285 |
+
"./graphify-out/dashboard-neighborhoods.sqlite3",
|
| 286 |
+
_dashboard_index_bytes(graph_dir, export_id=manifest_export_id),
|
| 287 |
+
)
|
| 288 |
+
_add_text(tf, "./external-catalogs/skills-sh/catalog.json", "{}")
|
| 289 |
+
_add_text(tf, "./entities/skills/skills-sh-example-skill.md", "# Example\n")
|
| 290 |
+
_add_text(tf, "./entities/harnesses/langgraph.md", "# LangGraph\n")
|
| 291 |
+
if include_converted:
|
| 292 |
+
_add_text(tf, "./converted/skills-sh-example-skill/SKILL.md", converted_skill_text)
|
| 293 |
+
_add_text(tf, "./converted/skills-sh-example-skill/references/01-scope.md", "# Scope\n")
|
| 294 |
+
if include_original:
|
| 295 |
+
_add_text(tf, "./converted/skills-sh-example-skill/SKILL.md.original", "# Raw\n")
|
| 296 |
+
if include_lock:
|
| 297 |
+
_add_text(tf, "./index.md.lock", "")
|
| 298 |
+
if include_queue:
|
| 299 |
+
_add_text(tf, "./.ctx/wiki-queue.sqlite3", "not a shipped artifact\n")
|
| 300 |
+
for preview in _PREVIEW_HTML_FILES:
|
| 301 |
+
(graph_dir / preview).write_text(
|
| 302 |
+
"\n".join([
|
| 303 |
+
"<!DOCTYPE html>",
|
| 304 |
+
"<html><head>",
|
| 305 |
+
f'<meta name="ctx-graph-export-id" content="{manifest_export_id}">',
|
| 306 |
+
"</head><body>",
|
| 307 |
+
"const CTX_GRAPH_METADATA = "
|
| 308 |
+
+ json.dumps({
|
| 309 |
+
"export_id": manifest_export_id,
|
| 310 |
+
"source_graph_nodes": 2,
|
| 311 |
+
"source_graph_edges": 1,
|
| 312 |
+
}),
|
| 313 |
+
"</body></html>",
|
| 314 |
+
]),
|
| 315 |
+
encoding="utf-8",
|
| 316 |
+
)
|
| 317 |
+
_write_runtime_archive(
|
| 318 |
+
graph_dir,
|
| 319 |
+
graph=graph,
|
| 320 |
+
include_delta=include_delta,
|
| 321 |
+
include_report=include_report,
|
| 322 |
+
include_manifest=include_manifest,
|
| 323 |
+
delta_export_id=delta_export_id,
|
| 324 |
+
communities_export_id=communities_export_id,
|
| 325 |
+
report_export_id=report_export_id,
|
| 326 |
+
manifest_export_id=manifest_export_id,
|
| 327 |
+
)
|
| 328 |
+
(graph_dir / "communities.json").write_text(
|
| 329 |
+
json.dumps({"export_id": communities_export_id, "total_communities": 1}),
|
| 330 |
+
encoding="utf-8",
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def test_validate_graph_artifacts_checks_catalog_paths_and_deep_graph_stats(
|
| 335 |
+
tmp_path: Path,
|
| 336 |
+
) -> None:
|
| 337 |
+
_write_catalog(
|
| 338 |
+
tmp_path,
|
| 339 |
+
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 340 |
+
)
|
| 341 |
+
(tmp_path / "communities.json").write_text(
|
| 342 |
+
json.dumps({"total_communities": 1}),
|
| 343 |
+
encoding="utf-8",
|
| 344 |
+
)
|
| 345 |
+
_write_archive(tmp_path)
|
| 346 |
+
|
| 347 |
+
stats = validate_graph_artifacts(
|
| 348 |
+
tmp_path,
|
| 349 |
+
deep=True,
|
| 350 |
+
min_nodes=2,
|
| 351 |
+
min_edges=1,
|
| 352 |
+
min_skills_sh_nodes=1,
|
| 353 |
+
min_semantic_edges=1,
|
| 354 |
+
expected_harnesses={"langgraph"},
|
| 355 |
+
line_threshold=180,
|
| 356 |
+
max_stage_lines=40,
|
| 357 |
+
expected_nodes=2,
|
| 358 |
+
expected_edges=1,
|
| 359 |
+
expected_semantic_edges=1,
|
| 360 |
+
expected_harness_nodes=1,
|
| 361 |
+
expected_skills_sh_nodes=1,
|
| 362 |
+
expected_skills_sh_catalog_entries=1,
|
| 363 |
+
expected_skills_sh_converted=1,
|
| 364 |
+
expected_skill_pages=1,
|
| 365 |
+
expected_agent_pages=0,
|
| 366 |
+
expected_mcp_pages=0,
|
| 367 |
+
expected_harness_pages=1,
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
assert stats.graph_nodes == 2
|
| 371 |
+
assert stats.graph_edges == 1
|
| 372 |
+
assert stats.harness_nodes == 1
|
| 373 |
+
assert stats.skills_sh_catalog_entries == 1
|
| 374 |
+
assert stats.skills_sh_converted == 1
|
| 375 |
+
assert stats.harness_pages == 1
|
| 376 |
+
|
| 377 |
+
with pytest.raises(GraphArtifactError, match="graph_edges exact count mismatch"):
|
| 378 |
+
validate_graph_artifacts(
|
| 379 |
+
tmp_path,
|
| 380 |
+
deep=True,
|
| 381 |
+
min_nodes=2,
|
| 382 |
+
min_edges=1,
|
| 383 |
+
min_skills_sh_nodes=1,
|
| 384 |
+
min_semantic_edges=1,
|
| 385 |
+
expected_harnesses={"langgraph"},
|
| 386 |
+
expected_edges=2,
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
with pytest.raises(GraphArtifactError, match="deep=True is required"):
|
| 390 |
+
validate_graph_artifacts(
|
| 391 |
+
tmp_path,
|
| 392 |
+
expected_harnesses={"langgraph"},
|
| 393 |
+
expected_nodes=2,
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def test_validate_graph_artifacts_rejects_mixed_export_generation(
|
| 398 |
+
tmp_path: Path,
|
| 399 |
+
) -> None:
|
| 400 |
+
_write_catalog(
|
| 401 |
+
tmp_path,
|
| 402 |
+
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 403 |
+
)
|
| 404 |
+
(tmp_path / "communities.json").write_text("{}", encoding="utf-8")
|
| 405 |
+
_write_archive(tmp_path, graph_export_id="new-export", delta_export_id="old-export")
|
| 406 |
+
|
| 407 |
+
with pytest.raises(GraphArtifactError, match="export_id mismatch"):
|
| 408 |
+
validate_graph_artifacts(
|
| 409 |
+
tmp_path,
|
| 410 |
+
deep=True,
|
| 411 |
+
min_nodes=2,
|
| 412 |
+
min_edges=1,
|
| 413 |
+
min_skills_sh_nodes=1,
|
| 414 |
+
min_semantic_edges=1,
|
| 415 |
+
expected_harnesses={"langgraph"},
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def test_validate_graph_artifacts_rejects_runtime_full_export_split(
|
| 420 |
+
tmp_path: Path,
|
| 421 |
+
) -> None:
|
| 422 |
+
_write_catalog(
|
| 423 |
+
tmp_path,
|
| 424 |
+
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 425 |
+
)
|
| 426 |
+
_write_archive(tmp_path, graph_export_id="full-export")
|
| 427 |
+
runtime_graph = {
|
| 428 |
+
"graph": {"export_id": "runtime-export"},
|
| 429 |
+
"nodes": [
|
| 430 |
+
{"id": "skill:skills-sh-example-skill", "type": "skill"},
|
| 431 |
+
{"id": "harness:langgraph", "type": "harness"},
|
| 432 |
+
],
|
| 433 |
+
"edges": [
|
| 434 |
+
{"source": "skill:skills-sh-example-skill", "target": "harness:langgraph"},
|
| 435 |
+
],
|
| 436 |
+
}
|
| 437 |
+
_write_runtime_archive(
|
| 438 |
+
tmp_path,
|
| 439 |
+
graph=runtime_graph,
|
| 440 |
+
delta_export_id="runtime-export",
|
| 441 |
+
communities_export_id="runtime-export",
|
| 442 |
+
report_export_id="runtime-export",
|
| 443 |
+
manifest_export_id="runtime-export",
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
with pytest.raises(GraphArtifactError, match="runtime graph archive export_id mismatch"):
|
| 447 |
+
validate_graph_artifacts(
|
| 448 |
+
tmp_path,
|
| 449 |
+
deep=True,
|
| 450 |
+
min_nodes=2,
|
| 451 |
+
min_edges=1,
|
| 452 |
+
min_skills_sh_nodes=1,
|
| 453 |
+
min_semantic_edges=1,
|
| 454 |
+
expected_harnesses={"langgraph"},
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
def test_validate_graph_artifacts_rejects_corrupt_dashboard_index(
|
| 459 |
+
tmp_path: Path,
|
| 460 |
+
) -> None:
|
| 461 |
+
_write_catalog(
|
| 462 |
+
tmp_path,
|
| 463 |
+
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 464 |
+
)
|
| 465 |
+
_write_archive(tmp_path)
|
| 466 |
+
with tarfile.open(tmp_path / "wiki-graph-runtime.tar.gz", "w:gz") as tf:
|
| 467 |
+
graph = {
|
| 468 |
+
"graph": {"export_id": "export-test"},
|
| 469 |
+
"nodes": [
|
| 470 |
+
{"id": "skill:skills-sh-example-skill", "type": "skill"},
|
| 471 |
+
{"id": "harness:langgraph", "type": "harness"},
|
| 472 |
+
],
|
| 473 |
+
"edges": [
|
| 474 |
+
{"source": "skill:skills-sh-example-skill", "target": "harness:langgraph"},
|
| 475 |
+
],
|
| 476 |
+
}
|
| 477 |
+
_add_text(tf, "index.md", "# Wiki\n")
|
| 478 |
+
_add_text(tf, "graphify-out/graph.json", json.dumps(graph, separators=(",", ":")))
|
| 479 |
+
_add_text(tf, "graphify-out/graph-delta.json", json.dumps({"export_id": "export-test"}))
|
| 480 |
+
_add_text(tf, "graphify-out/communities.json", json.dumps({"export_id": "export-test"}))
|
| 481 |
+
_add_text(tf, "graphify-out/graph-report.md", "# Graph Report\n\n> Export ID: export-test\n")
|
| 482 |
+
_add_text(
|
| 483 |
+
tf,
|
| 484 |
+
"graphify-out/graph-export-manifest.json",
|
| 485 |
+
json.dumps({
|
| 486 |
+
"version": 1,
|
| 487 |
+
"export_id": "export-test",
|
| 488 |
+
"artifacts": {
|
| 489 |
+
"graph": "graph.json",
|
| 490 |
+
"delta": "graph-delta.json",
|
| 491 |
+
"communities": "communities.json",
|
| 492 |
+
"report": "graph-report.md",
|
| 493 |
+
},
|
| 494 |
+
"counts": {"nodes": 2, "edges": 1, "communities": 1},
|
| 495 |
+
}),
|
| 496 |
+
)
|
| 497 |
+
_add_text(tf, "graphify-out/dashboard-neighborhoods.sqlite3", "not sqlite\n")
|
| 498 |
+
_add_text(tf, "external-catalogs/skills-sh/catalog.json", "{}")
|
| 499 |
+
for slug in sorted(DEFAULT_HARNESSES):
|
| 500 |
+
_add_text(tf, f"entities/harnesses/{slug}.md", f"# {slug}\n")
|
| 501 |
+
|
| 502 |
+
with pytest.raises(GraphArtifactError, match="dashboard index"):
|
| 503 |
+
validate_graph_artifacts(
|
| 504 |
+
tmp_path,
|
| 505 |
+
deep=True,
|
| 506 |
+
min_nodes=2,
|
| 507 |
+
min_edges=1,
|
| 508 |
+
min_skills_sh_nodes=1,
|
| 509 |
+
min_semantic_edges=1,
|
| 510 |
+
expected_harnesses={"langgraph"},
|
| 511 |
+
)
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def test_validate_graph_artifacts_rejects_stale_dashboard_index(
|
| 515 |
+
tmp_path: Path,
|
| 516 |
+
) -> None:
|
| 517 |
+
_write_catalog(
|
| 518 |
+
tmp_path,
|
| 519 |
+
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 520 |
+
)
|
| 521 |
+
_write_archive(tmp_path, graph_export_id="new-export", manifest_export_id="new-export")
|
| 522 |
+
with tarfile.open(tmp_path / "wiki-graph-runtime.tar.gz", "w:gz") as tf:
|
| 523 |
+
graph = {
|
| 524 |
+
"graph": {"export_id": "new-export"},
|
| 525 |
+
"nodes": [
|
| 526 |
+
{"id": "skill:skills-sh-example-skill", "type": "skill"},
|
| 527 |
+
{"id": "harness:langgraph", "type": "harness"},
|
| 528 |
+
],
|
| 529 |
+
"edges": [
|
| 530 |
+
{"source": "skill:skills-sh-example-skill", "target": "harness:langgraph"},
|
| 531 |
+
],
|
| 532 |
+
}
|
| 533 |
+
_add_text(tf, "index.md", "# Wiki\n")
|
| 534 |
+
_add_text(tf, "graphify-out/graph.json", json.dumps(graph, separators=(",", ":")))
|
| 535 |
+
_add_text(tf, "graphify-out/graph-delta.json", json.dumps({"export_id": "new-export"}))
|
| 536 |
+
_add_text(tf, "graphify-out/communities.json", json.dumps({"export_id": "new-export"}))
|
| 537 |
+
_add_text(tf, "graphify-out/graph-report.md", "# Graph Report\n\n> Export ID: new-export\n")
|
| 538 |
+
_add_text(
|
| 539 |
+
tf,
|
| 540 |
+
"graphify-out/graph-export-manifest.json",
|
| 541 |
+
json.dumps({
|
| 542 |
+
"version": 1,
|
| 543 |
+
"export_id": "new-export",
|
| 544 |
+
"artifacts": {
|
| 545 |
+
"graph": "graph.json",
|
| 546 |
+
"delta": "graph-delta.json",
|
| 547 |
+
"communities": "communities.json",
|
| 548 |
+
"report": "graph-report.md",
|
| 549 |
+
},
|
| 550 |
+
"counts": {"nodes": 2, "edges": 1, "communities": 1},
|
| 551 |
+
}),
|
| 552 |
+
)
|
| 553 |
+
_add_bytes(
|
| 554 |
+
tf,
|
| 555 |
+
"graphify-out/dashboard-neighborhoods.sqlite3",
|
| 556 |
+
_dashboard_index_bytes(tmp_path, export_id="old-export"),
|
| 557 |
+
)
|
| 558 |
+
_add_text(tf, "external-catalogs/skills-sh/catalog.json", "{}")
|
| 559 |
+
for slug in sorted(DEFAULT_HARNESSES):
|
| 560 |
+
_add_text(tf, f"entities/harnesses/{slug}.md", f"# {slug}\n")
|
| 561 |
+
|
| 562 |
+
with pytest.raises(GraphArtifactError, match="dashboard index export_id mismatch"):
|
| 563 |
+
validate_graph_artifacts(
|
| 564 |
+
tmp_path,
|
| 565 |
+
deep=True,
|
| 566 |
+
min_nodes=2,
|
| 567 |
+
min_edges=1,
|
| 568 |
+
min_skills_sh_nodes=1,
|
| 569 |
+
min_semantic_edges=1,
|
| 570 |
+
expected_harnesses={"langgraph"},
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
def test_validate_graph_artifacts_rejects_stale_preview_html(
|
| 575 |
+
tmp_path: Path,
|
| 576 |
+
) -> None:
|
| 577 |
+
_write_catalog(
|
| 578 |
+
tmp_path,
|
| 579 |
+
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 580 |
+
)
|
| 581 |
+
(tmp_path / "communities.json").write_text(
|
| 582 |
+
json.dumps({"total_communities": 1}),
|
| 583 |
+
encoding="utf-8",
|
| 584 |
+
)
|
| 585 |
+
_write_archive(tmp_path)
|
| 586 |
+
(tmp_path / "viz-overview.html").write_text(
|
| 587 |
+
'<meta name="ctx-graph-export-id" content="old-export">',
|
| 588 |
+
encoding="utf-8",
|
| 589 |
+
)
|
| 590 |
+
|
| 591 |
+
with pytest.raises(GraphArtifactError, match="stale graph preview"):
|
| 592 |
+
validate_graph_artifacts(
|
| 593 |
+
tmp_path,
|
| 594 |
+
deep=True,
|
| 595 |
+
min_nodes=2,
|
| 596 |
+
min_edges=1,
|
| 597 |
+
min_skills_sh_nodes=1,
|
| 598 |
+
min_semantic_edges=1,
|
| 599 |
+
expected_harnesses={"langgraph"},
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
def test_validate_graph_artifacts_rejects_stale_root_communities(
|
| 604 |
+
tmp_path: Path,
|
| 605 |
+
) -> None:
|
| 606 |
+
_write_catalog(
|
| 607 |
+
tmp_path,
|
| 608 |
+
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 609 |
+
)
|
| 610 |
+
_write_archive(tmp_path)
|
| 611 |
+
(tmp_path / "communities.json").write_text(
|
| 612 |
+
json.dumps({"export_id": "old-export", "total_communities": 1}),
|
| 613 |
+
encoding="utf-8",
|
| 614 |
+
)
|
| 615 |
+
|
| 616 |
+
with pytest.raises(GraphArtifactError, match="stale graph/communities.json"):
|
| 617 |
+
validate_graph_artifacts(
|
| 618 |
+
tmp_path,
|
| 619 |
+
expected_harnesses={"langgraph"},
|
| 620 |
+
)
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
@pytest.mark.parametrize(
|
| 624 |
+
("archive_kwargs", "missing_name"),
|
| 625 |
+
[
|
| 626 |
+
({"include_delta": False}, "graph-delta.json"),
|
| 627 |
+
({"include_report": False}, "graph-report.md"),
|
| 628 |
+
({"include_manifest": False}, "graph-export-manifest.json"),
|
| 629 |
+
],
|
| 630 |
+
)
|
| 631 |
+
def test_validate_graph_artifacts_rejects_missing_graph_export_files(
|
| 632 |
+
tmp_path: Path,
|
| 633 |
+
archive_kwargs: dict[str, Any],
|
| 634 |
+
missing_name: str,
|
| 635 |
+
) -> None:
|
| 636 |
+
_write_catalog(
|
| 637 |
+
tmp_path,
|
| 638 |
+
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 639 |
+
)
|
| 640 |
+
(tmp_path / "communities.json").write_text("{}", encoding="utf-8")
|
| 641 |
+
_write_archive(tmp_path, **archive_kwargs)
|
| 642 |
+
|
| 643 |
+
with pytest.raises(GraphArtifactError, match=missing_name):
|
| 644 |
+
validate_graph_artifacts(tmp_path, expected_harnesses={"langgraph"})
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
@pytest.mark.parametrize(
|
| 648 |
+
"archive_kwargs",
|
| 649 |
+
[
|
| 650 |
+
{"graph_export_id": "artifact-export", "manifest_export_id": "manifest-export"},
|
| 651 |
+
{"delta_export_id": "artifact-export", "manifest_export_id": "manifest-export"},
|
| 652 |
+
{
|
| 653 |
+
"communities_export_id": "artifact-export",
|
| 654 |
+
"manifest_export_id": "manifest-export",
|
| 655 |
+
},
|
| 656 |
+
{"report_export_id": "artifact-export", "manifest_export_id": "manifest-export"},
|
| 657 |
+
],
|
| 658 |
+
)
|
| 659 |
+
def test_validate_graph_artifacts_rejects_artifact_export_id_mismatch(
|
| 660 |
+
tmp_path: Path,
|
| 661 |
+
archive_kwargs: dict[str, Any],
|
| 662 |
+
) -> None:
|
| 663 |
+
_write_catalog(
|
| 664 |
+
tmp_path,
|
| 665 |
+
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 666 |
+
)
|
| 667 |
+
(tmp_path / "communities.json").write_text("{}", encoding="utf-8")
|
| 668 |
+
_write_archive(tmp_path, **archive_kwargs)
|
| 669 |
+
|
| 670 |
+
with pytest.raises(GraphArtifactError, match="export_id mismatch"):
|
| 671 |
+
validate_graph_artifacts(tmp_path, expected_harnesses={"langgraph"})
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def test_validate_graph_artifacts_rejects_missing_converted_catalog_path(
|
| 675 |
+
tmp_path: Path,
|
| 676 |
+
) -> None:
|
| 677 |
+
_write_catalog(
|
| 678 |
+
tmp_path,
|
| 679 |
+
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 680 |
+
)
|
| 681 |
+
(tmp_path / "communities.json").write_text("{}", encoding="utf-8")
|
| 682 |
+
_write_archive(tmp_path, include_converted=False)
|
| 683 |
+
|
| 684 |
+
with pytest.raises(GraphArtifactError, match="missing converted Skills.sh body"):
|
| 685 |
+
validate_graph_artifacts(tmp_path)
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
def test_validate_graph_artifacts_rejects_missing_skill_bundle_reference(
|
| 689 |
+
tmp_path: Path,
|
| 690 |
+
) -> None:
|
| 691 |
+
_write_catalog(
|
| 692 |
+
tmp_path,
|
| 693 |
+
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 694 |
+
)
|
| 695 |
+
(tmp_path / "communities.json").write_text("{}", encoding="utf-8")
|
| 696 |
+
_write_archive(
|
| 697 |
+
tmp_path,
|
| 698 |
+
converted_skill_text=(
|
| 699 |
+
"# Example\n\n"
|
| 700 |
+
"Use `resources/implementation-playbook.md` for the implementation flow.\n"
|
| 701 |
+
),
|
| 702 |
+
)
|
| 703 |
+
|
| 704 |
+
with pytest.raises(GraphArtifactError, match="missing bundled skill file"):
|
| 705 |
+
validate_graph_artifacts(tmp_path, expected_harnesses={"langgraph"})
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
def test_validate_graph_artifacts_rejects_body_unavailable_catalog_records(
|
| 709 |
+
tmp_path: Path,
|
| 710 |
+
) -> None:
|
| 711 |
+
_write_catalog(tmp_path, converted_path=None)
|
| 712 |
+
(tmp_path / "communities.json").write_text("{}", encoding="utf-8")
|
| 713 |
+
_write_archive(tmp_path, include_converted=False)
|
| 714 |
+
|
| 715 |
+
with pytest.raises(GraphArtifactError, match="body-unavailable records"):
|
| 716 |
+
validate_graph_artifacts(tmp_path)
|
| 717 |
+
|
| 718 |
+
|
| 719 |
+
def test_validate_graph_artifacts_rejects_missing_entity_overlay(tmp_path: Path) -> None:
|
| 720 |
+
_write_catalog(
|
| 721 |
+
tmp_path,
|
| 722 |
+
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 723 |
+
)
|
| 724 |
+
_write_archive(tmp_path)
|
| 725 |
+
(tmp_path / "entity-overlays.jsonl").unlink()
|
| 726 |
+
|
| 727 |
+
with pytest.raises(GraphArtifactError, match="entity-overlays.jsonl"):
|
| 728 |
+
validate_graph_artifacts(tmp_path)
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
def test_validate_graph_artifacts_rejects_invalid_entity_overlay(tmp_path: Path) -> None:
|
| 732 |
+
_write_catalog(
|
| 733 |
+
tmp_path,
|
| 734 |
+
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 735 |
+
)
|
| 736 |
+
_write_archive(tmp_path)
|
| 737 |
+
(tmp_path / "entity-overlays.jsonl").write_text(
|
| 738 |
+
json.dumps({
|
| 739 |
+
"overlay_id": "bad-overlay",
|
| 740 |
+
"nodes": [{"id": "skill:bad"}],
|
| 741 |
+
"edges": [{"source": "skill:bad", "target": "skill:other", "weight": 2}],
|
| 742 |
+
})
|
| 743 |
+
+ "\n",
|
| 744 |
+
encoding="utf-8",
|
| 745 |
+
)
|
| 746 |
+
|
| 747 |
+
with pytest.raises(GraphArtifactError, match="weight must be 0..1"):
|
| 748 |
+
validate_graph_artifacts(tmp_path)
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
def test_validate_graph_artifacts_rejects_original_backup_members(tmp_path: Path) -> None:
|
| 752 |
+
_write_catalog(
|
| 753 |
+
tmp_path,
|
| 754 |
+
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 755 |
+
)
|
| 756 |
+
(tmp_path / "communities.json").write_text("{}", encoding="utf-8")
|
| 757 |
+
_write_archive(tmp_path, include_original=True)
|
| 758 |
+
|
| 759 |
+
with pytest.raises(GraphArtifactError, match="raw backup"):
|
| 760 |
+
validate_graph_artifacts(tmp_path)
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
def test_validate_graph_artifacts_rejects_lock_members(tmp_path: Path) -> None:
|
| 764 |
+
_write_catalog(
|
| 765 |
+
tmp_path,
|
| 766 |
+
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 767 |
+
)
|
| 768 |
+
(tmp_path / "communities.json").write_text("{}", encoding="utf-8")
|
| 769 |
+
_write_archive(tmp_path, include_lock=True)
|
| 770 |
+
|
| 771 |
+
with pytest.raises(GraphArtifactError, match="lock member"):
|
| 772 |
+
validate_graph_artifacts(tmp_path)
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
def test_validate_graph_artifacts_rejects_transient_queue_state(tmp_path: Path) -> None:
|
| 776 |
+
_write_catalog(
|
| 777 |
+
tmp_path,
|
| 778 |
+
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 779 |
+
)
|
| 780 |
+
_write_archive(tmp_path, include_queue=True)
|
| 781 |
+
|
| 782 |
+
with pytest.raises(GraphArtifactError, match="transient queue state"):
|
| 783 |
+
validate_graph_artifacts(tmp_path)
|
| 784 |
+
|
| 785 |
+
|
| 786 |
+
def test_validate_graph_artifacts_rejects_runtime_queue_state(tmp_path: Path) -> None:
|
| 787 |
+
_write_catalog(
|
| 788 |
+
tmp_path,
|
| 789 |
+
converted_path="converted/skills-sh-example-skill/SKILL.md",
|
| 790 |
+
)
|
| 791 |
+
_write_archive(tmp_path)
|
| 792 |
+
graph = {
|
| 793 |
+
"graph": {"export_id": "export-test"},
|
| 794 |
+
"nodes": [
|
| 795 |
+
{"id": "skill:skills-sh-example-skill", "type": "skill"},
|
| 796 |
+
{"id": "harness:langgraph", "type": "harness"},
|
| 797 |
+
],
|
| 798 |
+
"edges": [],
|
| 799 |
+
}
|
| 800 |
+
_write_runtime_archive(tmp_path, graph=graph, include_queue=True)
|
| 801 |
+
|
| 802 |
+
with pytest.raises(GraphArtifactError, match="transient queue state"):
|
| 803 |
+
validate_graph_artifacts(tmp_path, expected_harnesses={"langgraph"})
|
| 804 |
+
|
| 805 |
+
|
| 806 |
+
@pytest.mark.parametrize(
|
| 807 |
+
"raw_name",
|
| 808 |
+
[
|
| 809 |
+
"../graphify-out/graph.json",
|
| 810 |
+
"./../graphify-out/graph.json",
|
| 811 |
+
"entities/../graphify-out/graph.json",
|
| 812 |
+
"/graphify-out/graph.json",
|
| 813 |
+
r"C:\tmp\graph.json",
|
| 814 |
+
"entities//skills/example.md",
|
| 815 |
+
],
|
| 816 |
+
)
|
| 817 |
+
def test_safe_tar_name_rejects_unsafe_members(raw_name: str) -> None:
|
| 818 |
+
with pytest.raises(GraphArtifactError, match="unsafe archive member path"):
|
| 819 |
+
_safe_tar_name(raw_name)
|
| 820 |
+
|
| 821 |
+
|
| 822 |
+
def test_safe_tar_name_strips_only_exact_current_dir_prefix() -> None:
|
| 823 |
+
assert _safe_tar_name("./graphify-out/graph.json") == "graphify-out/graph.json"
|
| 824 |
+
|
| 825 |
+
|
| 826 |
+
def test_scan_graph_json_handles_pretty_printed_graph() -> None:
|
| 827 |
+
graph = {
|
| 828 |
+
"nodes": [
|
| 829 |
+
{
|
| 830 |
+
"id": "skill:skills-sh-example-skill",
|
| 831 |
+
"type": "skill",
|
| 832 |
+
"source_catalog": "skills.sh",
|
| 833 |
+
},
|
| 834 |
+
{
|
| 835 |
+
"id": "harness:text-to-cad",
|
| 836 |
+
"type": "harness",
|
| 837 |
+
},
|
| 838 |
+
],
|
| 839 |
+
"edges": [
|
| 840 |
+
{
|
| 841 |
+
"source": "skill:skills-sh-example-skill",
|
| 842 |
+
"target": "harness:text-to-cad",
|
| 843 |
+
"semantic_sim": 0.0,
|
| 844 |
+
},
|
| 845 |
+
{
|
| 846 |
+
"source": "skill:skills-sh-example-skill",
|
| 847 |
+
"target": "harness:text-to-cad",
|
| 848 |
+
"semantic_sim": 0.82,
|
| 849 |
+
},
|
| 850 |
+
],
|
| 851 |
+
}
|
| 852 |
+
payload = json.dumps(graph, indent=2).encode("utf-8")
|
| 853 |
+
|
| 854 |
+
assert _scan_graph_json(BytesIO(payload)) == (2, 2, 1, 1, 1, None)
|
| 855 |
+
|
| 856 |
+
|
| 857 |
+
def test_scan_graph_json_rejects_out_of_range_edge_scores() -> None:
|
| 858 |
+
graph = {
|
| 859 |
+
"nodes": [{"id": "skill:a", "type": "skill"}],
|
| 860 |
+
"edges": [
|
| 861 |
+
{
|
| 862 |
+
"source": "skill:a",
|
| 863 |
+
"target": "skill:b",
|
| 864 |
+
"semantic_sim": 2.0,
|
| 865 |
+
"tag_sim": 0.0,
|
| 866 |
+
"token_sim": 0.0,
|
| 867 |
+
"weight": 0.5,
|
| 868 |
+
"final_weight": 0.5,
|
| 869 |
+
},
|
| 870 |
+
],
|
| 871 |
+
}
|
| 872 |
+
payload = json.dumps(graph).encode("utf-8")
|
| 873 |
+
|
| 874 |
+
with pytest.raises(GraphArtifactError, match="semantic_sim must be 0..1"):
|
| 875 |
+
_scan_graph_json(BytesIO(payload))
|
| 876 |
+
|
| 877 |
+
|
| 878 |
+
@pytest.mark.parametrize("raw", ["NaN", "Infinity", "-Infinity"])
|
| 879 |
+
def test_scan_graph_json_rejects_non_finite_edge_scores(raw: str) -> None:
|
| 880 |
+
payload = (
|
| 881 |
+
b'{"nodes":[{"id":"skill:a","type":"skill"}],"edges":['
|
| 882 |
+
b'{"source":"skill:a","target":"skill:b","semantic_sim":'
|
| 883 |
+
+ raw.encode("ascii")
|
| 884 |
+
+ b',"tag_sim":0.0,"token_sim":0.0,"weight":0.5,"final_weight":0.5}'
|
| 885 |
+
b"]}"
|
| 886 |
+
)
|
| 887 |
+
|
| 888 |
+
with pytest.raises(GraphArtifactError, match="semantic_sim must be finite"):
|
| 889 |
+
_scan_graph_json(BytesIO(payload))
|
| 890 |
+
|
| 891 |
+
|
| 892 |
+
def test_scan_graph_json_rejects_weight_final_weight_drift() -> None:
|
| 893 |
+
graph = {
|
| 894 |
+
"nodes": [{"id": "skill:a", "type": "skill"}],
|
| 895 |
+
"edges": [
|
| 896 |
+
{
|
| 897 |
+
"source": "skill:a",
|
| 898 |
+
"target": "skill:b",
|
| 899 |
+
"semantic_sim": 0.8,
|
| 900 |
+
"tag_sim": 0.0,
|
| 901 |
+
"token_sim": 0.0,
|
| 902 |
+
"weight": 0.7,
|
| 903 |
+
"final_weight": 0.5,
|
| 904 |
+
},
|
| 905 |
+
],
|
| 906 |
+
}
|
| 907 |
+
payload = json.dumps(graph).encode("utf-8")
|
| 908 |
+
|
| 909 |
+
with pytest.raises(GraphArtifactError, match="weight must equal final_weight"):
|
| 910 |
+
_scan_graph_json(BytesIO(payload))
|
| 911 |
+
|
| 912 |
+
|
| 913 |
+
def test_scan_graph_json_rejects_weight_drift_with_nested_score_components() -> None:
|
| 914 |
+
graph = {
|
| 915 |
+
"nodes": [{"id": "skill:a", "type": "skill"}],
|
| 916 |
+
"edges": [
|
| 917 |
+
{
|
| 918 |
+
"source": "skill:a",
|
| 919 |
+
"target": "skill:b",
|
| 920 |
+
"semantic_sim": 0.8,
|
| 921 |
+
"tag_sim": 0.0,
|
| 922 |
+
"token_sim": 0.0,
|
| 923 |
+
"weight": 0.7,
|
| 924 |
+
"final_weight": 0.5,
|
| 925 |
+
"score_components": {
|
| 926 |
+
"semantic": 0.8,
|
| 927 |
+
"tag": 0.0,
|
| 928 |
+
"token": 0.0,
|
| 929 |
+
},
|
| 930 |
+
},
|
| 931 |
+
],
|
| 932 |
+
}
|
| 933 |
+
payload = json.dumps(graph).encode("utf-8")
|
| 934 |
+
|
| 935 |
+
with pytest.raises(GraphArtifactError, match="weight must equal final_weight"):
|
| 936 |
+
_scan_graph_json(BytesIO(payload))
|
| 937 |
+
|
| 938 |
+
|
| 939 |
+
def test_scan_graph_json_rejects_score_component_drift() -> None:
|
| 940 |
+
graph = {
|
| 941 |
+
"nodes": [{"id": "skill:a", "type": "skill"}],
|
| 942 |
+
"edges": [
|
| 943 |
+
{
|
| 944 |
+
"source": "skill:a",
|
| 945 |
+
"target": "skill:b",
|
| 946 |
+
"semantic_sim": 0.8,
|
| 947 |
+
"tag_sim": 0.0,
|
| 948 |
+
"token_sim": 0.0,
|
| 949 |
+
"weight": 0.8,
|
| 950 |
+
"final_weight": 0.8,
|
| 951 |
+
"score_components": {
|
| 952 |
+
"semantic": 0.4,
|
| 953 |
+
"type_affinity": 0.1,
|
| 954 |
+
},
|
| 955 |
+
},
|
| 956 |
+
],
|
| 957 |
+
}
|
| 958 |
+
payload = json.dumps(graph).encode("utf-8")
|
| 959 |
+
|
| 960 |
+
with pytest.raises(GraphArtifactError, match="score_components must sum"):
|
| 961 |
+
_scan_graph_json(BytesIO(payload))
|
| 962 |
+
|
| 963 |
+
|
| 964 |
+
@pytest.mark.parametrize("value", [-0.1, 1.1])
|
| 965 |
+
def test_scan_graph_json_rejects_out_of_range_score_components(value: float) -> None:
|
| 966 |
+
graph = {
|
| 967 |
+
"nodes": [{"id": "skill:a", "type": "skill"}],
|
| 968 |
+
"edges": [
|
| 969 |
+
{
|
| 970 |
+
"source": "skill:a",
|
| 971 |
+
"target": "skill:b",
|
| 972 |
+
"weight": 0.5,
|
| 973 |
+
"final_weight": 0.5,
|
| 974 |
+
"score_components": {
|
| 975 |
+
"semantic": value,
|
| 976 |
+
"tag": 0.5 - value,
|
| 977 |
+
},
|
| 978 |
+
},
|
| 979 |
+
],
|
| 980 |
+
}
|
| 981 |
+
payload = json.dumps(graph).encode("utf-8")
|
| 982 |
+
|
| 983 |
+
with pytest.raises(GraphArtifactError, match="score_components must be 0..1"):
|
| 984 |
+
_scan_graph_json(BytesIO(payload))
|
| 985 |
+
|
| 986 |
+
|
| 987 |
+
@pytest.mark.parametrize("field", ["semantic_sim", "tag_sim", "token_sim"])
|
| 988 |
+
def test_overlay_validation_rejects_out_of_range_similarity_fields(
|
| 989 |
+
tmp_path: Path,
|
| 990 |
+
field: str,
|
| 991 |
+
) -> None:
|
| 992 |
+
(tmp_path / "entity-overlays.jsonl").write_text(
|
| 993 |
+
json.dumps({
|
| 994 |
+
"nodes": [{"id": "skill:a"}],
|
| 995 |
+
"edges": [
|
| 996 |
+
{
|
| 997 |
+
"source": "skill:a",
|
| 998 |
+
"target": "skill:b",
|
| 999 |
+
"weight": 0.5,
|
| 1000 |
+
"final_weight": 0.5,
|
| 1001 |
+
field: 2.0,
|
| 1002 |
+
},
|
| 1003 |
+
],
|
| 1004 |
+
})
|
| 1005 |
+
+ "\n",
|
| 1006 |
+
encoding="utf-8",
|
| 1007 |
+
)
|
| 1008 |
+
|
| 1009 |
+
with pytest.raises(GraphArtifactError, match=f"{field} must be 0..1"):
|
| 1010 |
+
_validate_root_entity_overlay(tmp_path / "entity-overlays.jsonl")
|
| 1011 |
+
|
| 1012 |
+
|
| 1013 |
+
def test_overlay_validation_rejects_weight_final_weight_drift(tmp_path: Path) -> None:
|
| 1014 |
+
(tmp_path / "entity-overlays.jsonl").write_text(
|
| 1015 |
+
json.dumps({
|
| 1016 |
+
"nodes": [{"id": "skill:a"}],
|
| 1017 |
+
"edges": [
|
| 1018 |
+
{
|
| 1019 |
+
"source": "skill:a",
|
| 1020 |
+
"target": "skill:b",
|
| 1021 |
+
"weight": 0.7,
|
| 1022 |
+
"final_weight": 0.5,
|
| 1023 |
+
},
|
| 1024 |
+
],
|
| 1025 |
+
})
|
| 1026 |
+
+ "\n",
|
| 1027 |
+
encoding="utf-8",
|
| 1028 |
+
)
|
| 1029 |
+
|
| 1030 |
+
with pytest.raises(GraphArtifactError, match="weight must equal final_weight"):
|
| 1031 |
+
_validate_root_entity_overlay(tmp_path / "entity-overlays.jsonl")
|
| 1032 |
+
|
| 1033 |
+
|
| 1034 |
+
def test_overlay_validation_rejects_score_component_drift(tmp_path: Path) -> None:
|
| 1035 |
+
(tmp_path / "entity-overlays.jsonl").write_text(
|
| 1036 |
+
json.dumps({
|
| 1037 |
+
"nodes": [{"id": "skill:a"}],
|
| 1038 |
+
"edges": [
|
| 1039 |
+
{
|
| 1040 |
+
"source": "skill:a",
|
| 1041 |
+
"target": "skill:b",
|
| 1042 |
+
"weight": 0.8,
|
| 1043 |
+
"final_weight": 0.8,
|
| 1044 |
+
"score_components": {
|
| 1045 |
+
"semantic": 0.4,
|
| 1046 |
+
"type_affinity": 0.1,
|
| 1047 |
+
},
|
| 1048 |
+
},
|
| 1049 |
+
],
|
| 1050 |
+
})
|
| 1051 |
+
+ "\n",
|
| 1052 |
+
encoding="utf-8",
|
| 1053 |
+
)
|
| 1054 |
+
|
| 1055 |
+
with pytest.raises(GraphArtifactError, match="score_components must sum"):
|
| 1056 |
+
_validate_root_entity_overlay(tmp_path / "entity-overlays.jsonl")
|
| 1057 |
+
|
| 1058 |
+
|
| 1059 |
+
@pytest.mark.parametrize("value", [-0.1, 1.1])
|
| 1060 |
+
def test_overlay_validation_rejects_out_of_range_score_components(
|
| 1061 |
+
tmp_path: Path,
|
| 1062 |
+
value: float,
|
| 1063 |
+
) -> None:
|
| 1064 |
+
(tmp_path / "entity-overlays.jsonl").write_text(
|
| 1065 |
+
json.dumps({
|
| 1066 |
+
"nodes": [{"id": "skill:a"}],
|
| 1067 |
+
"edges": [
|
| 1068 |
+
{
|
| 1069 |
+
"source": "skill:a",
|
| 1070 |
+
"target": "skill:b",
|
| 1071 |
+
"weight": 0.5,
|
| 1072 |
+
"final_weight": 0.5,
|
| 1073 |
+
"score_components": {
|
| 1074 |
+
"semantic": value,
|
| 1075 |
+
"tag": 0.5 - value,
|
| 1076 |
+
},
|
| 1077 |
+
},
|
| 1078 |
+
],
|
| 1079 |
+
})
|
| 1080 |
+
+ "\n",
|
| 1081 |
+
encoding="utf-8",
|
| 1082 |
+
)
|
| 1083 |
+
|
| 1084 |
+
with pytest.raises(GraphArtifactError, match="score_components must be 0..1"):
|
| 1085 |
+
_validate_root_entity_overlay(tmp_path / "entity-overlays.jsonl")
|
| 1086 |
+
|
| 1087 |
+
|
| 1088 |
+
def test_scan_graph_json_extracts_top_level_graph_export_id() -> None:
|
| 1089 |
+
graph = {
|
| 1090 |
+
"directed": False,
|
| 1091 |
+
"graph": {
|
| 1092 |
+
"source_catalog_nodes": {"skills.sh": 1},
|
| 1093 |
+
"source_catalog_edges": {"skills.sh": 0},
|
| 1094 |
+
"export_id": "graph-export",
|
| 1095 |
+
},
|
| 1096 |
+
"nodes": [
|
| 1097 |
+
{
|
| 1098 |
+
"id": "skill:skills-sh-example-skill",
|
| 1099 |
+
"type": "skill",
|
| 1100 |
+
"source_catalog": "skills.sh",
|
| 1101 |
+
},
|
| 1102 |
+
],
|
| 1103 |
+
"edges": [],
|
| 1104 |
+
}
|
| 1105 |
+
payload = json.dumps(graph, separators=(",", ":")).encode("utf-8")
|
| 1106 |
+
|
| 1107 |
+
assert _scan_graph_json(BytesIO(payload)) == (1, 0, 0, 1, 0, "graph-export")
|
| 1108 |
+
|
| 1109 |
+
|
| 1110 |
+
def test_scan_graph_json_ignores_node_level_export_id() -> None:
|
| 1111 |
+
graph = {
|
| 1112 |
+
"nodes": [
|
| 1113 |
+
{
|
| 1114 |
+
"id": "skill:skills-sh-example-skill",
|
| 1115 |
+
"type": "skill",
|
| 1116 |
+
"source_catalog": "skills.sh",
|
| 1117 |
+
"export_id": "node-export",
|
| 1118 |
+
},
|
| 1119 |
+
],
|
| 1120 |
+
"edges": [],
|
| 1121 |
+
}
|
| 1122 |
+
payload = json.dumps(graph, separators=(",", ":")).encode("utf-8")
|
| 1123 |
+
|
| 1124 |
+
assert _scan_graph_json(BytesIO(payload)) == (1, 0, 0, 1, 0, None)
|
| 1125 |
+
|
| 1126 |
+
|
| 1127 |
+
def test_graph_only_workflow_uses_exact_release_counts() -> None:
|
| 1128 |
+
workflow = yaml.safe_load(Path(".github/workflows/test.yml").read_text(
|
| 1129 |
+
encoding="utf-8"
|
| 1130 |
+
))
|
| 1131 |
+
steps = workflow["jobs"]["graph-check"]["steps"]
|
| 1132 |
+
validate_step = next(
|
| 1133 |
+
step for step in steps if step.get("name") == "Validate shipped graph artifacts"
|
| 1134 |
+
)
|
| 1135 |
+
command = " ".join(
|
| 1136 |
+
line.rstrip("\\").strip()
|
| 1137 |
+
for line in validate_step["run"].splitlines()
|
| 1138 |
+
if line.strip()
|
| 1139 |
+
)
|
| 1140 |
+
argv = command.split()
|
| 1141 |
+
|
| 1142 |
+
script_index = argv.index("src/validate_graph_artifacts.py")
|
| 1143 |
+
args = argv[script_index + 1:]
|
| 1144 |
+
parsed: dict[str, str | bool] = {}
|
| 1145 |
+
i = 0
|
| 1146 |
+
while i < len(args):
|
| 1147 |
+
flag = args[i]
|
| 1148 |
+
if i + 1 >= len(args) or args[i + 1].startswith("--"):
|
| 1149 |
+
parsed[flag] = True
|
| 1150 |
+
i += 1
|
| 1151 |
+
else:
|
| 1152 |
+
parsed[flag] = args[i + 1]
|
| 1153 |
+
i += 2
|
| 1154 |
+
|
| 1155 |
+
assert argv[:script_index + 1] == ["python", "src/validate_graph_artifacts.py"]
|
| 1156 |
+
assert parsed == {
|
| 1157 |
+
"--graph-dir": "graph",
|
| 1158 |
+
"--deep": True,
|
| 1159 |
+
"--min-nodes": "100000",
|
| 1160 |
+
"--min-edges": "2000000",
|
| 1161 |
+
"--min-skills-sh-nodes": "89000",
|
| 1162 |
+
"--min-semantic-edges": "1000000",
|
| 1163 |
+
"--expected-nodes": "102928",
|
| 1164 |
+
"--expected-edges": "2913960",
|
| 1165 |
+
"--expected-semantic-edges": "1683193",
|
| 1166 |
+
"--expected-harness-nodes": "207",
|
| 1167 |
+
"--expected-skills-sh-nodes": "89471",
|
| 1168 |
+
"--expected-skills-sh-catalog-entries": "89465",
|
| 1169 |
+
"--expected-skills-sh-converted": "89465",
|
| 1170 |
+
"--expected-skill-pages": "91464",
|
| 1171 |
+
"--expected-agent-pages": "467",
|
| 1172 |
+
"--expected-mcp-pages": "10790",
|
| 1173 |
+
"--expected-harness-pages": "207",
|
| 1174 |
+
"--line-threshold": "180",
|
| 1175 |
+
"--max-stage-lines": "40",
|
| 1176 |
+
}
|
| 1177 |
+
|
| 1178 |
+
|
| 1179 |
+
def test_graph_only_workflow_waits_for_release_asset_upload() -> None:
|
| 1180 |
+
workflow = yaml.safe_load(Path(".github/workflows/test.yml").read_text(
|
| 1181 |
+
encoding="utf-8"
|
| 1182 |
+
))
|
| 1183 |
+
steps = workflow["jobs"]["graph-check"]["steps"]
|
| 1184 |
+
resolve_step = next(
|
| 1185 |
+
step for step in steps
|
| 1186 |
+
if step.get("name") == "Resolve graph artifacts from release assets"
|
| 1187 |
+
)
|
| 1188 |
+
script = resolve_step["run"]
|
| 1189 |
+
|
| 1190 |
+
assert "release_asset_wait_seconds = 300" in script
|
| 1191 |
+
assert "while True:" in script
|
| 1192 |
+
assert "Waiting for matching release asset" in script
|
| 1193 |
+
assert "time.sleep(release_asset_poll_seconds)" in script
|