diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index a3d1d657..eedb8bb7 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -15,7 +15,11 @@ }, { "name": "pathiel-research", - "source": "./services/research_mcp", + "source": { + "source": "github", + "repo": "Julian-dev28/pathiel", + "ref": "plugin-research" + }, "description": "The risk-gated research layer AI agents trade through: a free, read-only, keyless MCP server with 6 tools (research_brief, events, prediction_odds, fred_series, headlines, levels) for BRENTOIL, HYPE, BTC, ETH and SP500. Hyperliquid public candles, news/RSS, Polymarket/Kalshi odds, the scheduled-event calendar, and pathiel's own stored desk thesis. Never touches a key, an account or an order.", "category": "finance", "keywords": ["research", "mcp", "claude-code", "hyperliquid", "polymarket", "kalshi", "fred", "market-research", "oil", "crypto"] diff --git a/scripts/build_plugin_bundle.py b/scripts/build_plugin_bundle.py index ac964779..bec34749 100644 --- a/scripts/build_plugin_bundle.py +++ b/scripts/build_plugin_bundle.py @@ -61,7 +61,7 @@ import sys import tempfile from pathlib import Path -from typing import Dict, Iterable, List, Optional, Set, Tuple +from typing import Dict, FrozenSet, Iterable, List, Optional, Set, Tuple ROOT = Path(__file__).resolve().parents[1] BRANCH = "plugin" @@ -232,10 +232,20 @@ def _package_of(path: str) -> List[str]: return parts[:-1] -def imports_of(path: str, source: bytes, files: Set[str]) -> Set[str]: +def _is_forbidden(name: str, forbidden: FrozenSet[str]) -> bool: + return any(name == f or name.startswith(f + ".") for f in forbidden) + + +def imports_of(path: str, source: bytes, files: Set[str], + forbidden: FrozenSet[str] = frozenset()) -> Set[str]: """Repo files `path` imports: every Import/ImportFrom anywhere in the tree (lazy ones inside functions included), dotted first-party module strings, - and for scripts/ files, siblings imported by bare name.""" + and for scripts/ files, siblings imported by bare name. `forbidden` + (dotted module names, exact or by prefix) are never resolved to a file, + so a shipped file's own dead/lazy import of one of them (e.g. + services/strategies/levels.py's `check()` importing pathiel.agents. + bracket, never called by services/research_mcp) cannot pull that file + or its own imports into the result -- see RESEARCH_FORBIDDEN_MODULES.""" try: tree = ast.parse(source, filename=path) except SyntaxError as exc: @@ -243,6 +253,8 @@ def imports_of(path: str, source: bytes, files: Set[str]) -> Set[str]: found: Set[str] = set() def add(name: str) -> None: + if _is_forbidden(name, forbidden): + return found.update(_module_files(name, files)) for node in ast.walk(tree): @@ -269,8 +281,10 @@ def add(name: str) -> None: return found -def closure(entries: Iterable[str], files: Dict[str, Tuple[str, str]]) -> Set[str]: - """Every .py file reachable from `entries`, with each package's __init__.""" +def closure(entries: Iterable[str], files: Dict[str, Tuple[str, str]], + forbidden: FrozenSet[str] = frozenset()) -> Set[str]: + """Every .py file reachable from `entries`, with each package's __init__. + `forbidden` is passed straight through to imports_of().""" names = set(files) seen: Set[str] = set() todo = [e for e in entries] @@ -287,7 +301,8 @@ def closure(entries: Iterable[str], files: Dict[str, Tuple[str, str]]) -> Set[st init = "/".join(parts[:i]) + "/__init__.py" if init in names and init not in seen: todo.append(init) - todo.extend(p for p in imports_of(path, blobs[files[path][1]], names) if p not in seen) + todo.extend(p for p in imports_of(path, blobs[files[path][1]], names, forbidden) + if p not in seen) return seen @@ -414,8 +429,8 @@ def _rev(name: str) -> Optional[str]: return out.stdout.strip() or None -def publish(ref: str, push: bool) -> str: - """Commit the bundle of ref onto the `plugin` branch. Returns its sha.""" +def _publish_guard(ref: str) -> None: + """Shared by publish() and research_publish().""" if ref == INDEX: raise SystemExit("publish needs a commit (a tag or main), not the index") # Inside a git hook, git exports GIT_DIR / GIT_INDEX_FILE for the repo @@ -426,24 +441,28 @@ def publish(ref: str, push: bool) -> str: if hooked: raise SystemExit(f"publish refused: {', '.join(hooked)} is set (a git hook or a " f"nested git command); run it from a plain shell") - tree = tree_sha(ref) - source = _git("rev-parse", f"{ref}^{{commit}}").strip() + + +def _do_publish(branch: str, tree: str, version: str, source: str, push: bool, label: str) -> str: + """One commit onto `branch` whose tree is `tree`, fast-forward only. + Shared by publish() (BRANCH, label "plugin bundle") and research_publish() + (RESEARCH_BRANCH, label "research plugin bundle").""" if push: - subprocess.run(["git", "fetch", "-q", "origin", BRANCH], cwd=ROOT, capture_output=True) - parent = _rev(f"refs/heads/{BRANCH}") or _rev(f"refs/remotes/origin/{BRANCH}") - remote = _rev(f"refs/remotes/origin/{BRANCH}") + subprocess.run(["git", "fetch", "-q", "origin", branch], cwd=ROOT, capture_output=True) + parent = _rev(f"refs/heads/{branch}") or _rev(f"refs/remotes/origin/{branch}") + remote = _rev(f"refs/remotes/origin/{branch}") if parent and remote and parent != remote: merged = subprocess.run(["git", "merge-base", "--is-ancestor", remote, parent], cwd=ROOT) if merged.returncode != 0: - raise SystemExit(f"local {BRANCH} does not contain origin/{BRANCH}; " - f"run: git branch -f {BRANCH} origin/{BRANCH}") + raise SystemExit(f"local {branch} does not contain origin/{branch}; " + f"run: git branch -f {branch} origin/{branch}") if parent and _git("rev-parse", f"{parent}^{{tree}}").strip() == tree: commit = parent - if not _rev(f"refs/heads/{BRANCH}"): # only origin/plugin had it: track it locally - _git("update-ref", f"refs/heads/{BRANCH}", commit, "") - print(f"{BRANCH}: already the bundle of {source[:7]} ({commit[:7]})", file=sys.stderr) + if not _rev(f"refs/heads/{branch}"): # only origin/ had it: track it locally + _git("update-ref", f"refs/heads/{branch}", commit, "") + print(f"{branch}: already the bundle of {source[:7]} ({commit[:7]})", file=sys.stderr) else: - msg = (f"plugin bundle {version_at(ref)} from {source[:12]}\n\n" + msg = (f"{label} {version} from {source[:12]}\n\n" f"Built by scripts/build_plugin_bundle.py from {source}.\n" f"Do not edit this branch by hand: publish again from main.\n") args = ["commit-tree", tree, "-m", msg] + (["-p", parent] if parent else []) @@ -454,49 +473,230 @@ def publish(ref: str, push: bool) -> str: if sign == "true": args.insert(1, "-S") commit = _git(*args).strip() - _git("update-ref", f"refs/heads/{BRANCH}", commit, *( [parent] if parent and - _rev(f"refs/heads/{BRANCH}") else [])) - print(f"{BRANCH}: {commit[:7]} = bundle {version_at(ref)} of {source[:7]}", file=sys.stderr) + _git("update-ref", f"refs/heads/{branch}", commit, *( [parent] if parent and + _rev(f"refs/heads/{branch}") else [])) + print(f"{branch}: {commit[:7]} = bundle {version} of {source[:7]}", file=sys.stderr) if push: - _git("push", "origin", f"refs/heads/{BRANCH}:refs/heads/{BRANCH}") - print(f"pushed {BRANCH}", file=sys.stderr) + _git("push", "origin", f"refs/heads/{branch}:refs/heads/{branch}") + print(f"pushed {branch}", file=sys.stderr) return commit -def check(ref: str, against: str) -> bool: - want, have = tree_sha(ref), _git("rev-parse", f"{against}^{{tree}}").strip() - if want == have: - print(f"ok: {against} holds the bundle of {ref} ({version_at(ref)})") +def publish(ref: str, push: bool) -> str: + """Commit the bundle of ref onto the `plugin` branch. Returns its sha.""" + _publish_guard(ref) + source = _git("rev-parse", f"{ref}^{{commit}}").strip() + return _do_publish(BRANCH, tree_sha(ref), version_at(ref), source, push, "plugin bundle") + + +def _do_check(tree: str, version: str, ref: str, against: str, publish_cmd: str) -> bool: + """Shared by check() and research_check().""" + have = _git("rev-parse", f"{against}^{{tree}}").strip() + if tree == have: + print(f"ok: {against} holds the bundle of {ref} ({version})") return True - print(f"MISMATCH: the bundle of {ref} is tree {want[:12]}, {against} has {have[:12]}. " - f"Run: python3 scripts/build_plugin_bundle.py publish --ref {ref} --push", file=sys.stderr) + print(f"MISMATCH: the bundle of {ref} is tree {tree[:12]}, {against} has {have[:12]}. " + f"Run: {publish_cmd}", file=sys.stderr) return False +def check(ref: str, against: str) -> bool: + return _do_check(tree_sha(ref), version_at(ref), ref, against, + f"python3 scripts/build_plugin_bundle.py publish --ref {ref} --push") + + +# ── the research bundle (services/research_mcp/) ─────────────────────────── +# +# A second, independent plugin in this same repo: the read-only research MCP +# server. Bundled onto its own branch, `plugin-research`, whose ROOT is a +# self-contained plugin root -- not nested under services/research_mcp/ the +# way the checked-in manifest sits, because Claude Code only copies a plugin +# ENTRY's own source directory into its cache: a marketplace entry whose +# source is the relative path "./services/research_mcp" ships none of +# scripts/, services/intel/, services/strategies/ or contracts/, so the +# launcher it starts cannot import the server at all (see +# code.claude.com/docs/en/plugins/loading#in-place-and-copied-plugins: "Every +# other marketplace plugin: ... Files outside the plugin directory aren't +# copied"). This bundle instead ships, at ITS OWN root, every real-repo-root +# relative file the server's import closure touches (the exact same relative +# layout as a checkout, just a subset of files), so +# ${CLAUDE_PLUGIN_ROOT}/scripts/pathiel-research-mcp.sh keeps working +# whichever root it loads from -- see .claude-plugin/marketplace.json's +# pathiel-research entry, a `github` source pinned to this branch. +RESEARCH_BRANCH = "plugin-research" +RESEARCH_PLUGIN_JSON_SRC = "services/research_mcp/.claude-plugin/plugin.json" +RESEARCH_README_SRC = "services/research_mcp/README.md" +RESEARCH_ENTRY_SCRIPTS = ("scripts/pathiel-research-mcp.py",) +# requirements.lock: the one root lock file (scripts/pathiel-research-mcp.sh +# pip-installs from it, same as scripts/pathiel-mcp.sh does for the trading +# bundle). It is the full repo's lock, not a trimmed one -- same tradeoff the +# trading bundle already makes (ship the one tested lock file, accept the +# extra packages this server does not import, rather than maintain a second +# lock that could drift from what CI actually runs against). +RESEARCH_RUNTIME_FILES = ("scripts/pathiel-research-mcp.sh", "requirements.lock") +# services/intel/data/scheduled_events.json: the one non-.py data file any +# module in the closure actually reads (services/intel/scheduled_events.py's +# DATA_PATH). Everything else DATA_INCLUDE allows for the trading bundle +# (pathiel/agents/unlock_map.json, contracts/*/fixtures) is reachable only +# through this server's own dead trading-code imports (see +# RESEARCH_FORBIDDEN_MODULES) and ships to neither bundle. +RESEARCH_REPO_DATA = ("services/intel/data/scheduled_events.json",) +# Reused byte for byte at the bundle root, same path (no relocation: the +# icon already lives at ".claude-plugin/icon.png", same relative path the +# research bundle needs it at). This plugin's security posture (no key, +# keeps no key, see SECURITY.md) does not apply, so that file does not ship. +RESEARCH_LISTING_FILES = ("LICENSE", ".claude-plugin/icon.png") +# source path -> bundle path. Every other shipped file keeps its repo path. +RESEARCH_PATH_MAP: Dict[str, str] = { + RESEARCH_PLUGIN_JSON_SRC: ".claude-plugin/plugin.json", + RESEARCH_README_SRC: "README.md", +} +# services/research_mcp/tests/test_no_trading_imports.py's own +# FORBIDDEN_MODULES (order placement and signing code), duplicated here -- +# not imported from the test, since a build script importing a test module +# is backwards -- and pinned a superset of it by +# tests/test_eval_plugin_bundle_research.py:: +# test_research_forbidden_modules_cover_the_servers_own_gate. "scripts. +# pathiel-mcp-server" is that test's own documentary entry (not a valid +# dotted module name; closure() never sees it as an import target) and is +# left out here on purpose. "services.accounts" is added on top of that +# test's list: it is credential/key-vault code, not itself order or signing +# code, but a keyless, read-only server (this README: "Never touches a key, +# an account, or an order") must not ship it either, even as dead weight +# reached only through pathiel.client.hl_client.resolve_user_address (a +# function this server never calls -- see levels.py's fetch_mid/fetch_candles, +# which use fetch_all_mids/_http_post instead). +RESEARCH_FORBIDDEN_MODULES: FrozenSet[str] = frozenset({ + "pathiel.agents.bracket", "pathiel.agents.executor", "pathiel.client.exchange", + "services.strategies.next_trade", "eth_account", "hyperliquid.exchange", + "services.accounts", +}) + + +def research_bundle_paths(files: Dict[str, Tuple[str, str]]) -> List[str]: + """The sorted repo (source) paths the research bundle holds. Two of them + (RESEARCH_PATH_MAP's keys) ship at a different bundle path; see + research_build()/research_tree_sha().""" + required = (RESEARCH_PLUGIN_JSON_SRC, RESEARCH_README_SRC) + RESEARCH_LISTING_FILES \ + + RESEARCH_RUNTIME_FILES + RESEARCH_ENTRY_SCRIPTS + missing = [p for p in required if p not in files] + if missing: + raise SystemExit(f"research bundle source is missing required files: {', '.join(missing)}") + picked: Set[str] = {RESEARCH_PLUGIN_JSON_SRC, RESEARCH_README_SRC} | set(RESEARCH_LISTING_FILES) + picked |= set(RESEARCH_RUNTIME_FILES) + picked |= closure(RESEARCH_ENTRY_SCRIPTS, files, RESEARCH_FORBIDDEN_MODULES) + picked |= {p for p in files if any(fnmatch.fnmatch(p, pat) for pat in RESEARCH_REPO_DATA)} + return sorted(picked) + + +def _research_dest(path: str) -> str: + return RESEARCH_PATH_MAP.get(path, path) + + +def research_version_at(ref: str) -> str: + spec = (":" if ref == INDEX else f"{ref}:") + RESEARCH_PLUGIN_JSON_SRC + return json.loads(_git("show", spec))["version"] + + +def _research_shipped_blobs(files: Dict[str, Tuple[str, str]], paths: List[str]) -> Dict[str, bytes]: + """Bundle-dest-path -> content, for the one research file that gets a + text transform (README.md: its one relative link outside + services/research_mcp/ would otherwise be dead at the bundle's new root; + see bundle_text()).""" + if RESEARCH_README_SRC not in paths: + return {} + shipped, names = set(paths), set(files) + raw = read_blobs([files[RESEARCH_README_SRC][1]]) + text = raw[files[RESEARCH_README_SRC][1]].decode("utf-8") + return {_research_dest(RESEARCH_README_SRC): bundle_text(RESEARCH_README_SRC, text, shipped, + names).encode("utf-8")} + + +def research_tree_sha(ref: str) -> str: + """The git tree of the research bundle built from ref. Same files, same + sha, with RESEARCH_PATH_MAP's relocations applied.""" + files = ls_tree(ref) + paths = research_bundle_paths(files) + entries = {_research_dest(p): files[p] for p in paths} + for dest, data in _research_shipped_blobs(files, paths).items(): + sha = subprocess.run(["git", "hash-object", "-w", "--stdin"], cwd=ROOT, input=data, + capture_output=True, check=True).stdout.decode().strip() + entries[dest] = ("100644", sha) + lines = "".join(f"{entries[d][0]} {entries[d][1]}\t{d}\n" for d in sorted(entries)) + with tempfile.TemporaryDirectory() as tmp: + env = dict(os.environ, GIT_INDEX_FILE=os.path.join(tmp, "index")) + _git("read-tree", "--empty", env=env) + _git("update-index", "--index-info", env=env, input_text=lines) + return _git("write-tree", env=env).strip() + + +def research_build(ref: str, out: Path) -> List[str]: + """Write the research bundle's files into an empty directory (relocated + paths included), exec bits kept. Returns the SOURCE paths, as build() + does.""" + out.mkdir(parents=True, exist_ok=True) + if any(out.iterdir()): + raise SystemExit(f"{out} is not empty") + files = ls_tree(ref) + paths = research_bundle_paths(files) + blobs = read_blobs(files[p][1] for p in paths) + changed = _research_shipped_blobs(files, paths) + for p in paths: + mode, sha = files[p] + dest_path = _research_dest(p) + dest = out / dest_path + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(changed.get(dest_path, blobs[sha])) + if mode == "100755": + dest.chmod(0o755) + return paths + + +def research_publish(ref: str, push: bool) -> str: + """Commit the research bundle of ref onto the `plugin-research` branch.""" + _publish_guard(ref) + source = _git("rev-parse", f"{ref}^{{commit}}").strip() + return _do_publish(RESEARCH_BRANCH, research_tree_sha(ref), research_version_at(ref), source, + push, "research plugin bundle") + + +def research_check(ref: str, against: str) -> bool: + return _do_check(research_tree_sha(ref), research_version_at(ref), ref, against, + f"python3 scripts/build_plugin_bundle.py publish --plugin research " + f"--ref {ref} --push") + + def main(argv: Optional[List[str]] = None) -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) sub = ap.add_subparsers(dest="cmd", required=True) for name in ("list", "tree", "build", "publish", "check"): p = sub.add_parser(name) p.add_argument("--ref", default="HEAD") + p.add_argument("--plugin", choices=("pathiel", "research"), default="pathiel", + help="which plugin's bundle to operate on (default: pathiel)") if name == "build": p.add_argument("out", type=Path) if name == "publish": p.add_argument("--push", action="store_true") if name == "check": - p.add_argument("--against", default=f"origin/{BRANCH}") + p.add_argument("--against", default=None) a = ap.parse_args(argv) + research = a.plugin == "research" + if a.cmd == "check" and a.against is None: + a.against = f"origin/{RESEARCH_BRANCH if research else BRANCH}" if a.cmd == "list": - print("\n".join(bundle_paths(ls_tree(a.ref)))) + paths = research_bundle_paths(ls_tree(a.ref)) if research else bundle_paths(ls_tree(a.ref)) + print("\n".join(paths)) elif a.cmd == "tree": - print(tree_sha(a.ref)) + print(research_tree_sha(a.ref) if research else tree_sha(a.ref)) elif a.cmd == "build": - paths = build(a.ref, a.out) + paths = research_build(a.ref, a.out) if research else build(a.ref, a.out) print(f"{len(paths)} files -> {a.out}", file=sys.stderr) elif a.cmd == "publish": - print(publish(a.ref, a.push)) + print(research_publish(a.ref, a.push) if research else publish(a.ref, a.push)) elif a.cmd == "check": - return 0 if check(a.ref, a.against) else 1 + ok = research_check(a.ref, a.against) if research else check(a.ref, a.against) + return 0 if ok else 1 return 0 diff --git a/scripts/pathiel-research-mcp.sh b/scripts/pathiel-research-mcp.sh index 25f72ac1..ff15a480 100755 --- a/scripts/pathiel-research-mcp.sh +++ b/scripts/pathiel-research-mcp.sh @@ -1,12 +1,21 @@ #!/usr/bin/env bash # The pathiel research MCP server as a Claude Code plugin entry point. # -# services/research_mcp/.claude-plugin/plugin.json runs this as -# "${CLAUDE_PLUGIN_ROOT}/../../scripts/pathiel-research-mcp.sh" (the plugin's -# source is the services/research_mcp/ subdirectory of this same monorepo; a -# relative-path plugin source resolves against the already-cloned repo, so -# that ../../ reaches the repo root on disk -- see the marketplace docs on -# relative-path plugin sources). +# .claude-plugin/plugin.json (bundle root; the checked-in copy lives at +# services/research_mcp/.claude-plugin/plugin.json and is relocated there by +# scripts/build_plugin_bundle.py --plugin research) runs this as +# "${CLAUDE_PLUGIN_ROOT}/scripts/pathiel-research-mcp.sh". Claude Code only +# copies a plugin's OWN source directory into its cache -- a relative-path +# marketplace entry scoped to services/research_mcp/ alone never carries +# scripts/, services/intel/, services/strategies/ or contracts/ along with +# it, so this file could not import the server at all (see +# code.claude.com/docs/en/plugins/loading#in-place-and-copied-plugins). The +# real install instead comes from the self-contained `plugin-research` +# branch, whose root holds this same scripts/ directory alongside every +# other file the server's import closure touches -- see +# .claude-plugin/marketplace.json's pathiel-research entry (a `github` +# source pinned to that branch) and build_plugin_bundle.py's own +# RESEARCH_* constants for the exact file list. # # Deliberately does NOT source scripts/_plugin_env.sh: that file resolves # PATHIEL_HOME=~/.pathiel and loads the trading server's keys/config. This diff --git a/services/research_mcp/.claude-plugin/plugin.json b/services/research_mcp/.claude-plugin/plugin.json index 3917a1da..d0bf23e3 100644 --- a/services/research_mcp/.claude-plugin/plugin.json +++ b/services/research_mcp/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "pathiel-research", "displayName": "pathiel research", - "version": "0.1.0", + "version": "0.2.0", "description": "The risk-gated research layer AI agents trade through: a free, read-only, keyless MCP server with 6 tools (research_brief, events, prediction_odds, fred_series, headlines, levels) for BRENTOIL, HYPE, BTC, ETH and SP500. Hyperliquid public candles, news/RSS, Polymarket/Kalshi odds, the scheduled-event calendar, and pathiel's own stored desk thesis. Never touches a key, an account or an order.", "author": { "name": "Julian Martinez", @@ -9,7 +9,7 @@ }, "homepage": "https://julian-dev28.github.io/pathiel/", "documentationUrl": "https://github.com/Julian-dev28/pathiel/blob/main/services/research_mcp/README.md", - "privacyPolicyUrl": "https://github.com/Julian-dev28/pathiel/blob/main/docs/PRIVACY.md", + "privacyPolicyUrl": "https://julian-dev28.github.io/pathiel/privacy.html", "supportUrl": "https://github.com/Julian-dev28/pathiel/issues", "termsOfServiceUrl": "https://github.com/Julian-dev28/pathiel/blob/main/docs/TERMS.md", "repository": "https://github.com/Julian-dev28/pathiel", @@ -18,7 +18,7 @@ "mcpServers": { "pathiel-research": { "command": "bash", - "args": ["${CLAUDE_PLUGIN_ROOT}/../../scripts/pathiel-research-mcp.sh"] + "args": ["${CLAUDE_PLUGIN_ROOT}/scripts/pathiel-research-mcp.sh"] } } } diff --git a/services/research_mcp/server.py b/services/research_mcp/server.py index 72ae4596..a739fb6d 100644 --- a/services/research_mcp/server.py +++ b/services/research_mcp/server.py @@ -44,7 +44,7 @@ # cert-bundle patch, PATHIA_*/PATHIEL_* environment mirroring) that this # server has no reason to carry, and importing it would be one more thing # tests/test_no_trading_imports.py's reviewer has to re-check stays clean. -SERVER_VERSION = "0.1.0" +SERVER_VERSION = "0.2.0" SERVER_INSTRUCTIONS = ( "pathiel research: the risk-gated research layer AI agents trade through. Read-only and " diff --git a/services/research_mcp/tests/test_server_version_matches_plugin.py b/services/research_mcp/tests/test_server_version_matches_plugin.py new file mode 100644 index 00000000..07cae80c --- /dev/null +++ b/services/research_mcp/tests/test_server_version_matches_plugin.py @@ -0,0 +1,12 @@ +"""The version the research server reports in initialize must match its +plugin.json (2026-11-22: plugin.json said 0.2.0, the server still said 0.1.0).""" +import json +import pathlib + +from services.research_mcp import server + +PLUGIN_JSON = pathlib.Path(__file__).resolve().parents[1] / ".claude-plugin" / "plugin.json" + + +def test_server_version_matches_plugin_json(): + assert server.SERVER_VERSION == json.loads(PLUGIN_JSON.read_text())["version"] diff --git a/tests/test_eval_plugin_bundle_research.py b/tests/test_eval_plugin_bundle_research.py new file mode 100644 index 00000000..4e30f554 --- /dev/null +++ b/tests/test_eval_plugin_bundle_research.py @@ -0,0 +1,125 @@ +"""Eval: would the plugin directory's review of the RESEARCH bundle come +back clean? Mirrors tests/test_eval_plugin_bundle.py for the research +server (scripts/build_plugin_bundle.py --plugin research). + +Rows (every one must meet its target): + + bundle files / repo files < 1/3 + paths that escape ${CLAUDE_PLUGIN_ROOT} 0 + install commands in shipped Markdown 0 (docker run/build, git clone) + dead relative links in shipped Markdown 0 + banned trading/credential files shipped 0 + forbidden module loaded, fresh import 0 + MCP server declarations, named interpreter 1, bash + server tools, bundle vs checkout equal, 6 + claude plugin validate --profile directory 0 findings, 0 warnings (--strict) + +The validator row needs the claude CLI; without it the row says "not run" +in its got column and does not fail (CI has no claude). + + .venv/bin/python -m pytest -q -s tests/test_eval_plugin_bundle_research.py +""" +from __future__ import annotations + +import importlib.util +import json +import re +import shutil +import subprocess +from pathlib import Path +from typing import List + +ROOT = Path(__file__).resolve().parents[1] +HERE = Path(__file__).resolve().parent + +_spec = importlib.util.spec_from_file_location("_eval_plugin_bundle_research_checks", + HERE / "test_plugin_bundle_research.py") +T = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(T) +B = T.B + + +def _validate(bundle: Path) -> dict: + proc = subprocess.run(["claude", "plugin", "validate", "--profile", "directory", "--strict", + "--json", str(bundle)], capture_output=True, text=True, timeout=120) + report = json.loads(proc.stdout) + parts = [report["manifest"], *report.get("contents", [])] + return {"exit": proc.returncode, + "errors": sum(len(p["errors"]) for p in parts), + "warnings": sum(len(p["warnings"]) for p in parts), + "findings": len(report["directory"]["findings"]) + len(report["directory"]["undecided"])} + + +def run(bundle: Path, public_env) -> List[dict]: + def row(check: str, got, want, ok: bool) -> dict: + return {"check": check, "got": got, "want": want, "ok": bool(ok)} + + files = B.ls_tree(B.INDEX) + paths = B.research_build(B.INDEX, bundle) + rows: List[dict] = [] + rows.append(row("bundle files / repo files", f"{len(paths)}/{len(files)}", "< 1/3", + len(paths) * 3 < len(files))) + + escapees = [] + import posixpath + for p in paths: + dest = B._research_dest(p) + if dest.startswith("..") or dest.startswith("/") or posixpath.normpath(dest) != dest: + escapees.append(dest) + rows.append(row("paths that escape ${CLAUDE_PLUGIN_ROOT}", len(escapees), 0, not escapees)) + + shipped = set(paths) | {B._research_dest(p) for p in paths} + readme = (bundle / "README.md").read_text(encoding="utf-8") + installs = sum(readme.count(n) for n in ("docker run", "docker build", "git clone")) + dead = sum(1 for m in re.finditer(r"\]\((?!https?://|mailto:|#)([^)\s#]+)", readme) + if m.group(1) not in shipped) + rows.append(row("install commands in shipped Markdown", installs, 0, installs == 0)) + rows.append(row("dead relative links in shipped Markdown", dead, 0, dead == 0)) + + banned_prefixes = ("pathiel/agents/bracket.py", "pathiel/agents/executor.py", + "pathiel/client/exchange.py", "services/strategies/next_trade.py", + "services/accounts/") + banned = [p for p in paths if any(p == b or p.startswith(b) for b in banned_prefixes)] + rows.append(row("banned trading/credential files shipped", len(banned), 0, not banned)) + + import subprocess as sp + import sys as _sys + code = ("import sys, json\n" + f"sys.path.insert(0, {str(bundle)!r})\n" + "from services.research_mcp import server\n" + f"forbidden = {sorted(B.RESEARCH_FORBIDDEN_MODULES)!r}\n" + "hits = [m for m in sys.modules if any(m == f or m.startswith(f + '.') for f in forbidden)]\n" + "print(json.dumps(hits))\n") + proc = sp.run([_sys.executable, "-c", code], capture_output=True, text=True, timeout=30, + cwd=str(bundle)) + hits = json.loads(proc.stdout.strip()) if proc.returncode == 0 else [""] + rows.append(row("forbidden module loaded, fresh import", hits, [], not hits)) + + plugin = json.loads((bundle / ".claude-plugin" / "plugin.json").read_text()) + servers = plugin.get("mcpServers", {}) + decl = len(servers) + int((bundle / ".mcp.json").exists()) + cmd = servers.get("pathiel-research", {}).get("command") + rows.append(row("MCP server declarations, interpreter", f"{decl}, {cmd}", "1, bash", + decl == 1 and cmd == "bash")) + + from_bundle = T._tools(bundle / "scripts" / "pathiel-research-mcp.py", public_env) + from_checkout = T._tools(ROOT / "scripts" / "pathiel-research-mcp.py", public_env) + rows.append(row("server tools, bundle vs checkout", f"{len(from_bundle)} vs {len(from_checkout)}", + "equal, 6", from_bundle == from_checkout and len(from_bundle) == 6)) + + if shutil.which("claude"): + v = _validate(bundle) + rows.append(row("claude plugin validate --profile directory --strict", + f"exit {v['exit']}, {v['errors']} errors, {v['warnings']} warnings, " + f"{v['findings']} findings", "exit 0, all 0", + v["exit"] == 0 and not (v["errors"] or v["warnings"] or v["findings"]))) + else: + rows.append(row("claude plugin validate --profile directory --strict", + "not run (no claude CLI on PATH)", "exit 0, all 0", True)) + return rows + + +def test_eval_plugin_bundle_research_meets_every_target(tmp_path, public_env, scorecard): + card = scorecard("plugin_bundle_research", run(tmp_path / "pathiel-research", public_env)) + failed = [r for r in card["rows"] if not r["ok"]] + assert not failed, f"research plugin bundle eval: {card['passed']}/{card['total']}; failed: {failed}" diff --git a/tests/test_listing_metadata.py b/tests/test_listing_metadata.py index f85932bd..5adc389e 100644 --- a/tests/test_listing_metadata.py +++ b/tests/test_listing_metadata.py @@ -320,3 +320,16 @@ def test_listing_urls_point_at_files_that_exist_and_terms_say_what_matters(copy_ "never withdraw", "charges no fee", "opt-in"): assert must in terms, must assert copy_lint.style_hits(terms) == [] and copy_lint.claim_hits(terms) == [] + + +def test_research_plugin_privacy_url_matches_the_trading_one(): + """services/research_mcp/.claude-plugin/plugin.json shares the same + hosted privacy page (site/privacy.html has its own "The research + server" section) instead of the old docs/PRIVACY.md repo-blob link, + which described only the trading server's keys.""" + research = _json(ROOT / "services" / "research_mcp" / ".claude-plugin" / "plugin.json") + plugin = _json(PLUGIN_JSON) + assert research["privacyPolicyUrl"] == plugin["privacyPolicyUrl"] == \ + "https://julian-dev28.github.io/pathiel/privacy.html" + privacy_text = (ROOT / "site" / "privacy.html").read_text(encoding="utf-8") + assert "pathiel-research" in privacy_text and "research server" in privacy_text.lower() diff --git a/tests/test_plugin.py b/tests/test_plugin.py index 69a20b28..4ed006f8 100644 --- a/tests/test_plugin.py +++ b/tests/test_plugin.py @@ -47,7 +47,18 @@ def test_the_plugin_and_marketplace_names_agree_and_the_version_is_the_packages( server, services/research_mcp/ — its own deploy unit, see tests/test_deploy_config.py::test_dockerfile_does_not_bundle_research_mcp). Only the trading plugin's version tracks pathiel/__init__.py; the - research plugin is a genuinely separate product with its own version.""" + research plugin is a genuinely separate product with its own version. + + pathiel-research's entry is a `github` source pinned to the + `plugin-research` branch (scripts/build_plugin_bundle.py --plugin + research), not a relative path: Claude Code only copies a relative-path + entry's OWN directory into the cache, so "./services/research_mcp" ships + none of scripts/, services/intel/, services/strategies/ or contracts/ on + a real (non-local) marketplace install and the server cannot start (see + code.claude.com/docs/en/plugins/loading#in-place-and-copied-plugins). + The checked-in services/research_mcp/.claude-plugin/plugin.json is bundle + SOURCE input only now (relocated to the branch's own .claude-plugin/ + plugin.json byte for byte); see tests/test_plugin_bundle_research.py.""" from pathiel import __version__ m, mk = _manifest(), _marketplace() assert m["name"] == "pathiel" @@ -63,11 +74,16 @@ def test_the_plugin_and_marketplace_names_agree_and_the_version_is_the_packages( assert m["author"]["name"] and mk["owner"]["name"] research_source = by_name["pathiel-research"]["source"] - assert research_source == "./services/research_mcp" - research_manifest = json.loads((ROOT / research_source.removeprefix("./") / + assert research_source == {"source": "github", "repo": "Julian-dev28/pathiel", + "ref": "plugin-research"} + research_manifest = json.loads((ROOT / "services" / "research_mcp" / ".claude-plugin" / "plugin.json").read_text()) assert research_manifest["name"] == "pathiel-research" == by_name["pathiel-research"]["name"] assert re.fullmatch(r"\d+\.\d+\.\d+", research_manifest["version"]) + assert research_manifest["mcpServers"]["pathiel-research"]["args"] == \ + ["${CLAUDE_PLUGIN_ROOT}/scripts/pathiel-research-mcp.sh"], \ + "the args must stay inside ${CLAUDE_PLUGIN_ROOT}: see the bug this plugin shipped with " \ + "(../../scripts/...), fixed by building a self-contained bundle instead" assert research_manifest["author"]["name"] diff --git a/tests/test_plugin_bundle_research.py b/tests/test_plugin_bundle_research.py new file mode 100644 index 00000000..da9adcb9 --- /dev/null +++ b/tests/test_plugin_bundle_research.py @@ -0,0 +1,312 @@ +"""The research plugin bundle (scripts/build_plugin_bundle.py --plugin +research): what a marketplace install of `pathiel-research` actually gets. + +Mirrors tests/test_plugin_bundle.py's checks for the trading bundle, scoped +to the research server. The bug this bundle exists to fix: services/ +research_mcp/.claude-plugin/plugin.json used to start its server with +"${CLAUDE_PLUGIN_ROOT}/../../scripts/pathiel-research-mcp.sh", and the +marketplace entry's source was the relative path "./services/research_mcp". +Claude Code only copies a relative-path entry's OWN directory into the +plugin cache (code.claude.com/docs/en/plugins/loading#in-place-and-copied- +plugins: "Every other marketplace plugin: ... Files outside the plugin +directory aren't copied"), so a real (non-local) marketplace install got +services/research_mcp/ alone -- no scripts/, services/intel/, services/ +strategies/ or contracts/ -- and the launcher could not import the server +at all. The fix: build a SELF-CONTAINED bundle (this file's `built` fixture) +whose root holds every file the server's import closure touches, at their +real repo-root-relative paths, and point the marketplace entry at that +bundle's branch instead (a `github` source with `ref: "plugin-research"`; +see .claude-plugin/marketplace.json and tests/test_plugin.py). + + .venv/bin/python -m pytest -q tests/test_plugin_bundle_research.py +""" +from __future__ import annotations + +import ast +import importlib.util +import json +import re +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / "scripts" / "build_plugin_bundle.py" +HERE = Path(__file__).resolve().parent + +_spec = importlib.util.spec_from_file_location("build_plugin_bundle", SCRIPT) +B = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(B) + +# The trading bundle's own test module: reused for its git-plumbing test +# helpers (_clean_env, _git, _refs, _repo_state), not duplicated. +_tspec = importlib.util.spec_from_file_location("_research_bundle_shared", HERE / "test_plugin_bundle.py") +T = importlib.util.module_from_spec(_tspec) +_tspec.loader.exec_module(T) + +# services/research_mcp/tests/test_no_trading_imports.py's own FORBIDDEN_MODULES: +# the canonical, server-side gate this bundle must still satisfy. +_gspec = importlib.util.spec_from_file_location( + "_research_no_trading_gate", ROOT / "services" / "research_mcp" / "tests" / "test_no_trading_imports.py") +GATE = importlib.util.module_from_spec(_gspec) +_gspec.loader.exec_module(GATE) + + +@pytest.fixture(scope="module") +def files(): + return B.ls_tree(B.INDEX) + + +@pytest.fixture(scope="module") +def paths(files): + return B.research_bundle_paths(files) + + +@pytest.fixture(scope="module") +def built(tmp_path_factory, paths): + out = tmp_path_factory.mktemp("research_bundle") / "pathiel-research" + assert B.research_build(B.INDEX, out) == paths + return out + + +# ── the forbidden-module cut ──────────────────────────────────────────────── + +def test_research_forbidden_modules_cover_the_servers_own_static_gate(): + """RESEARCH_FORBIDDEN_MODULES must be a superset of the server's own + canonical list (the one documentary, non-dotted entry, "scripts. + pathiel-mcp-server", excepted -- closure() never sees it as an import + target). A drift here (someone trims the build script's list without + noticing the server's gate grew) fails right here, not in a shipped + bundle.""" + # "scripts.pathiel-mcp-server" is that module's own documentary entry + # (not a valid dotted module name -- it says so in its own comment); + # closure() never sees it as an import target, so it is not expected + # here either. + canonical = set(GATE.FORBIDDEN_MODULES) - {"scripts.pathiel-mcp-server"} + assert canonical <= B.RESEARCH_FORBIDDEN_MODULES, canonical - B.RESEARCH_FORBIDDEN_MODULES + + +def test_banned_trading_and_credential_files_are_absent_from_the_bundle(paths): + banned_prefixes = ("pathiel/agents/bracket.py", "pathiel/agents/executor.py", + "pathiel/client/exchange.py", "pathiel/client/builder.py", + "pathiel/client/account_snapshot.py", "services/strategies/next_trade.py", + "services/accounts/") + hits = [p for p in paths if any(p == b or p.startswith(b) for b in banned_prefixes)] + assert hits == [] + + +def test_no_shipped_research_file_statically_imports_a_forbidden_module(built, paths): + """services/research_mcp/tests/test_no_trading_imports.py's own static + technique, run over the server's own files INSIDE the built bundle (byte + for byte the same files; this proves the bundling step did not change + that gate's answer).""" + offenders = [] + for p in paths: + if not (p.startswith("services/research_mcp/") and p.endswith(".py")): + continue + tree = ast.parse((built / p).read_bytes(), filename=p) + for node in ast.walk(tree): + names = [] + if isinstance(node, ast.Import): + names = [a.name for a in node.names] + elif isinstance(node, ast.ImportFrom) and node.module: + names = [node.module] + for n in names: + if GATE._is_forbidden(n): + offenders.append(f"{p}: {n}") + assert offenders == [] + + +def test_dynamic_fresh_process_never_loads_a_forbidden_module_from_the_bundle(built): + """The bundle's own services.research_mcp.server, imported fresh in a + subprocess whose sys.path is ONLY the bundle directory (so a forbidden + module could only come from inside the bundle, never the checkout).""" + code = ( + "import sys, json\n" + f"sys.path.insert(0, {str(built)!r})\n" + "from services.research_mcp import server\n" + f"forbidden = {sorted(B.RESEARCH_FORBIDDEN_MODULES)!r}\n" + "hits = [m for m in sys.modules if any(m == f or m.startswith(f + '.') for f in forbidden)]\n" + "print(json.dumps(hits))\n" + ) + proc = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=30, + cwd=str(built)) + assert proc.returncode == 0, proc.stderr + assert json.loads(proc.stdout.strip()) == [] + + +# ── self-containment: every path inside ${CLAUDE_PLUGIN_ROOT} ────────────── + +def test_every_required_research_file_is_in_the_bundle(paths): + required = (B.RESEARCH_PLUGIN_JSON_SRC, B.RESEARCH_README_SRC) + B.RESEARCH_LISTING_FILES \ + + B.RESEARCH_RUNTIME_FILES + B.RESEARCH_ENTRY_SCRIPTS + for p in required: + assert p in paths, p + + +def test_no_relocated_or_shipped_path_escapes_the_bundle_root(paths): + import posixpath + for p in paths: + dest = B._research_dest(p) + assert not dest.startswith("..") and not dest.startswith("/"), dest + assert posixpath.normpath(dest) == dest, dest # no "./", no redundant ".." + + +def test_the_bundle_declares_one_mcp_server_with_args_fully_inside_claude_plugin_root(built): + plugin = json.loads((built / ".claude-plugin" / "plugin.json").read_text()) + assert plugin["mcpServers"] == {"pathiel-research": { + "command": "bash", "args": ["${CLAUDE_PLUGIN_ROOT}/scripts/pathiel-research-mcp.sh"]}} + assert ".." not in json.dumps(plugin) + assert not (built / ".mcp.json").exists() + assert sorted(p.name for p in (built / ".claude-plugin").iterdir()) == ["icon.png", "plugin.json"] + + +def test_build_keeps_the_launcher_executable(built): + assert (built / "scripts" / "pathiel-research-mcp.sh").stat().st_mode & 0o100 + + +def test_the_research_bundle_is_far_smaller_than_the_repo_and_has_no_tests_or_evals(files, paths): + assert len(paths) < len(files) / 3, (len(paths), len(files)) + assert not any("/tests/" in p or "/evals/" in p for p in paths) + assert not any(p.startswith(("tests/", "CLAUDE.md", ".github/", "docs/")) for p in paths) + + +# ── the import closure resolves, and the server runs from the bundle alone ── + +def test_every_first_party_import_in_the_research_bundle_resolves_inside_it(built, paths): + shipped = set(paths) + missing = [] + for p in paths: + if not p.endswith(".py"): + continue + for node in ast.walk(ast.parse((built / p).read_bytes())): + mods = [] + if isinstance(node, ast.Import): + mods = [a.name for a in node.names] + elif isinstance(node, ast.ImportFrom) and not node.level and node.module: + mods = [node.module] + for m in mods: + if m.split(".")[0] in ("pathiel", "services", "contracts"): + base = m.replace(".", "/") + namespace = any(s.startswith(base + "/") for s in shipped) + if f"{base}.py" not in shipped and f"{base}/__init__.py" not in shipped \ + and not namespace and not B._is_forbidden(m, B.RESEARCH_FORBIDDEN_MODULES): + missing.append(f"{p}: {m}") + assert missing == [] + + +def _tools(server: Path, public_env) -> list: + msgs = [{"jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-06-18", "capabilities": {}}}, + {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}] + proc = subprocess.run([sys.executable, str(server)], + input="".join(json.dumps(m) + "\n" for m in msgs), + capture_output=True, text=True, timeout=90, env=public_env(), + cwd=str(server.parent.parent)) + assert proc.returncode == 0, proc.stderr[-2000:] + out = {json.loads(ln).get("id"): json.loads(ln) for ln in proc.stdout.splitlines()} + return sorted(t["name"] for t in out[2]["result"]["tools"]) + + +def test_the_research_server_lists_the_same_six_tools_from_the_bundle_alone(built, public_env): + from_bundle = _tools(built / "scripts" / "pathiel-research-mcp.py", public_env) + from_checkout = _tools(ROOT / "scripts" / "pathiel-research-mcp.py", public_env) + assert from_bundle == from_checkout and len(from_bundle) == 6 + assert from_bundle == ["events", "fred_series", "headlines", "levels", "prediction_odds", + "research_brief"] + + +def test_every_bundled_research_module_imports_from_the_bundle_alone(built, paths, public_env): + mods = [p[:-3].replace("/", ".").removesuffix(".__init__") for p in paths + if p.endswith(".py") and p.startswith(("pathiel/", "services/", "contracts/"))] + code = ("import importlib, sys\nsys.path.insert(0, sys.argv[1])\nbad = []\n" + "for m in sys.argv[2:]:\n" + " try:\n importlib.import_module(m)\n" + " except Exception as e:\n bad.append(f'{m}: {type(e).__name__}: {e}')\n" + "print('\\n'.join(bad))\n") + proc = subprocess.run([sys.executable, "-c", code, str(built), *mods], capture_output=True, + text=True, timeout=120, env=public_env(), cwd=str(built)) + assert proc.returncode == 0, proc.stderr[-2000:] + assert proc.stdout.strip() == "", proc.stdout + + +# ── the shipped README ────────────────────────────────────────────────────── + +def test_the_research_readme_has_no_install_commands_and_no_dead_links(built, paths): + shipped = set(paths) | {B._research_dest(p) for p in paths} + text = (built / "README.md").read_text(encoding="utf-8") + for needle in ("docker run", "docker build", "git clone"): + assert needle not in text, needle + for m in re.finditer(r"\]\((?!https?://|mailto:|#)([^)\s#]+)", text): + assert m.group(1) in shipped, f"dead link: {m.group(1)}" + + +def test_the_research_readme_still_documents_the_install_command(built): + text = (built / "README.md").read_text(encoding="utf-8") + assert "/plugin marketplace add Julian-dev28/pathiel" in text + assert "/plugin install pathiel-research@pathiel" in text + + +# ── publish, on a throwaway clone (never the real repo's refs) ───────────── + +@pytest.fixture +def real_refs_unchanged(): + before = T._repo_state(ROOT) + yield + assert T._repo_state(ROOT) == before, "a research bundle test changed a ref or config of the real repo" + + +@pytest.mark.parametrize("var", B.HOOK_ENV) +def test_research_publish_refuses_inside_a_git_hook(tmp_path, var, real_refs_unchanged): + decoy = tmp_path / "decoy" + subprocess.run(["git", "init", "-q", str(decoy)], check=True, env=T._clean_env()) + env = dict(T._clean_env(), **{var: str(decoy / ".git") if var != "GIT_INDEX_FILE" + else str(decoy / ".git" / "index")}) + proc = subprocess.run([sys.executable, str(SCRIPT), "publish", "--plugin", "research", + "--ref", "HEAD"], cwd=ROOT, capture_output=True, text=True, env=env) + assert proc.returncode != 0 and "publish refused" in proc.stderr and var in proc.stderr + assert T._refs(decoy) == "" + + +def test_research_publish_is_idempotent_fast_forward_and_check_catches_drift(tmp_path, real_refs_unchanged): + clone = tmp_path / "clone" + head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=ROOT, check=True, capture_output=True, + text=True).stdout.strip() + subprocess.run(["git", "clone", "-q", "--shared", "--no-checkout", str(ROOT), str(clone)], + check=True, env=T._clean_env()) + T._git(clone, "checkout", "-q", "--detach", head) + (clone / "scripts").mkdir(exist_ok=True) + shutil.copy(SCRIPT, clone / "scripts" / "build_plugin_bundle.py") # this version, uncommitted + run = [sys.executable, str(clone / "scripts" / "build_plugin_bundle.py")] + + def bundle(*args): + return subprocess.run(run + list(args) + ["--plugin", "research"], cwd=clone, + capture_output=True, text=True, env=T._clean_env()) + + if T._git(clone, "branch", "-r", "--list", "origin/plugin-research"): + assert bundle("publish").stdout.strip() == T._git(clone, "rev-parse", "plugin-research") + T._git(clone, "branch", "-D", "plugin-research") + T._git(clone, "update-ref", "-d", "refs/remotes/origin/plugin-research") + first = bundle("publish").stdout.strip() + assert first and T._git(clone, "rev-parse", "plugin-research") == first + assert T._git(clone, "rev-parse", "plugin-research^{tree}") == bundle("tree").stdout.strip() + assert bundle("publish").stdout.strip() == first + assert bundle("check", "--against", "plugin-research").returncode == 0 + + readme = clone / "services" / "research_mcp" / "README.md" + readme.write_text(readme.read_text(encoding="utf-8") + "\nchanged\n", encoding="utf-8") + T._git(clone, "commit", "-q", "-am", "change a bundled research file") + stale = bundle("check", "--against", "plugin-research") + assert stale.returncode == 1 and "MISMATCH" in stale.stderr + second = bundle("publish").stdout.strip() + assert second != first and T._git(clone, "rev-parse", f"{second}^") == first + assert bundle("check", "--against", "plugin-research").returncode == 0 + + t = clone / "CLAUDE.md" + t.write_text(t.read_text(encoding="utf-8") + "\nchanged\n", encoding="utf-8") + T._git(clone, "commit", "-q", "-am", "change an unbundled file") + assert bundle("check", "--against", "plugin-research").returncode == 0 + assert bundle("publish").stdout.strip() == second