Files
hyperstitionstudio-core/src/hyperstitionstud_io/version_sync.py
T

508 lines
22 KiB
Python
Executable File

#!/usr/bin/env python3
"""
hyperstitionstud_io.version_sync — Single-Source-of-Truth Version Synchronizer & Verifier (`hs-sync-version`).
Ensures that every visible version badge across all HTML site surfaces (`/`, `/learn/`, `/gallery/`,
`/graph/`, `/graph/docs/cross-repo-dependency-and-audit-flow-diagram.html`, `/calc/`), JS bundles,
MCP/Quant servers, and package manifests updates in lockstep on every version change.
"""
from __future__ import annotations
import argparse
import json
import re
import subprocess
import sys
from pathlib import Path
from typing import Any
_SRC_DIR = Path(__file__).resolve().parents[1]
if _SRC_DIR.is_dir() and str(_SRC_DIR) not in sys.path:
sys.path.insert(0, str(_SRC_DIR))
from hyperstitionstud_io import __version__ as CURRENT_VERSION # noqa: E402
from hyperstitionstud_io.config import load_workspace_config # noqa: E402
SEMVER_RE = r"\d+\.\d+\.\d+"
def _bump_semver(version_str: str, bump_level: str) -> str:
clean = version_str.lstrip("v").strip()
m = re.match(r"^(\d+)\.(\d+)\.(\d+)$", clean)
if not m:
raise ValueError(f"Invalid semantic version '{version_str}'")
major, minor, patch = int(m.group(1)), int(m.group(2)), int(m.group(3))
if bump_level == "major":
return f"{major + 1}.0.0"
if bump_level == "minor":
return f"{major}.{minor + 1}.0"
if bump_level == "patch":
return f"{major}.{minor}.{patch + 1}"
return clean
def evaluate_change_scope_heuristics(signals: dict[str, Any]) -> dict[str, Any]:
"""
Pure, deterministic 4-tier change-scope evaluator (`0` LLM tokens).
Classifies workspace change signals into `noop`, `patch`, `minor`, or `major`.
"""
current_v = str(signals.get("current_version", CURRENT_VERSION)).lstrip("v").strip()
dirty_files = int(signals.get("total_dirty_files", 0))
commits_ahead = int(signals.get("total_commits_ahead", 0))
newly_archived_plans = list(signals.get("newly_archived_plans", []))
skill_completed_plans_delta = list(signals.get("skill_completed_plans_delta", []))
new_cli_scripts = list(signals.get("new_cli_scripts", []))
removed_cli_scripts = list(signals.get("removed_cli_scripts", []))
new_mcp_tools = list(signals.get("new_mcp_tools", []))
removed_mcp_tools = list(signals.get("removed_mcp_tools", []))
new_schemas = list(signals.get("new_schemas", []))
removed_schemas = list(signals.get("removed_schemas", []))
new_subpages = list(signals.get("new_subpages", []))
schema_urn_major_changed = bool(signals.get("schema_urn_major_changed", False))
isolation_baseline_replaced = bool(signals.get("isolation_baseline_replaced", False))
triggered: list[str] = []
if (
schema_urn_major_changed
or isolation_baseline_replaced
or len(removed_cli_scripts) > 0
or len(removed_mcp_tools) > 0
or len(removed_schemas) > 0
):
if schema_urn_major_changed:
triggered.append("schema_urn_major_changed: True")
if isolation_baseline_replaced:
triggered.append("isolation_baseline_replaced: True")
if removed_cli_scripts:
triggered.append(f"removed_cli_scripts: {removed_cli_scripts}")
if removed_mcp_tools:
triggered.append(f"removed_mcp_tools: {removed_mcp_tools}")
if removed_schemas:
triggered.append(f"removed_schemas: {removed_schemas}")
bump_level = "major"
elif (
len(newly_archived_plans) > 0
or len(skill_completed_plans_delta) > 0
or len(new_cli_scripts) > 0
or len(new_mcp_tools) > 0
or len(new_schemas) > 0
or len(new_subpages) > 0
):
if newly_archived_plans:
triggered.append(f"newly_archived_plans: {newly_archived_plans}")
if skill_completed_plans_delta:
triggered.append(f"skill_completed_plans_delta: {skill_completed_plans_delta}")
if new_cli_scripts:
triggered.append(f"new_cli_scripts: {new_cli_scripts}")
if new_mcp_tools:
triggered.append(f"new_mcp_tools: {new_mcp_tools}")
if new_schemas:
triggered.append(f"new_schemas: {new_schemas}")
if new_subpages:
triggered.append(f"new_subpages: {new_subpages}")
bump_level = "minor"
elif dirty_files > 0 or commits_ahead > 0:
triggered.append(f"workspace_changes: dirty_files={dirty_files}, commits_ahead={commits_ahead}")
bump_level = "patch"
else:
triggered.append("clean_workspace_at_tag: dirty_files=0, commits_ahead=0")
bump_level = "noop"
next_v = _bump_semver(current_v, bump_level)
return {
"current_version": current_v,
"baseline_git_tag": signals.get("baseline_git_tag", f"v{current_v}"),
"recommended_bump_level": bump_level,
"next_version": next_v,
"llm_tokens_used": 0,
"signals_triggered": triggered,
"signals": signals,
}
def _git_run(repo_dir: Path, args: list[str]) -> str:
if not (repo_dir / ".git").exists():
return ""
proc = subprocess.run(
["git", "-C", str(repo_dir), *args],
capture_output=True,
text=True,
check=False,
)
return proc.stdout.strip() if proc.returncode == 0 else ""
def _extract_archived_plan_ids_from_text(text: str) -> set[str]:
return set(re.findall(r"\bPLAN-[A-Z0-9-]+\b", text))
def _extract_cli_scripts_from_pyproject(text: str) -> set[str]:
m = re.search(r"\[project\.scripts\](.*?)(?:\n\[|\Z)", text, flags=re.S)
if not m:
return set()
return set(re.findall(r"^\s*([a-z0-9-]+)\s*=", m.group(1), flags=re.M))
def _extract_mcp_tool_names(text: str) -> set[str]:
return set(re.findall(r'"name":\s*"(hs_[a-z0-9_]+)"', text))
def collect_workspace_change_signals(ws_root: Path | None = None) -> dict[str, Any]:
"""
Collect deterministic change-scope signals from the 6 Git repositories,
`docs/archive/archive-manifest.json`, `docs/archive/README.md`, and `SKILL.md` (`0` LLM tokens).
"""
cfg = load_workspace_config(workspace_root=ws_root)
core = cfg.core_dir
kg = cfg.knowledge_graph_dir
current_v = CURRENT_VERSION
init_path = core / "src" / "hyperstitionstud_io" / "__init__.py"
if init_path.is_file():
m_v = re.search(rf'__version__\s*=\s*"({SEMVER_RE})"', init_path.read_text(encoding="utf-8"))
if m_v:
current_v = m_v.group(1)
baseline_tag = _git_run(core, ["describe", "--tags", "--abbrev=0"]) or f"v{current_v}"
repo_dirs = [
core,
cfg.archive_dir.parent,
cfg.zoology_dir,
kg,
cfg.paths["gematria_js_dir"],
cfg.paths.get("ci_repo_dir", cfg.workspace_root / "hyperdope-ci-build"),
]
repo_diff_summary: dict[str, dict[str, int]] = {}
total_dirty = 0
total_ahead = 0
for rdir in repo_dirs:
if not rdir.is_dir():
continue
porcelain = _git_run(rdir, ["status", "--porcelain"])
dirty_cnt = len([ln for ln in porcelain.splitlines() if ln.strip()]) if porcelain else 0
rtag = _git_run(rdir, ["describe", "--tags", "--abbrev=0"])
ahead_cnt = 0
if rtag:
ahead_str = _git_run(rdir, ["rev-list", f"{rtag}..HEAD", "--count"])
ahead_cnt = int(ahead_str) if ahead_str.isdigit() else 0
repo_diff_summary[rdir.name] = {
"dirty_files": dirty_cnt,
"commits_ahead_of_tag": ahead_cnt,
}
total_dirty += dirty_cnt
total_ahead += ahead_cnt
# 1. Plan archive delta (`archive-manifest.json` + `docs/archive/README.md` + loose `docs/archive/PLAN-*`)
current_archived_plans: set[str] = set()
arch_dir = kg / "docs" / "archive"
manifest_p = arch_dir / "archive-manifest.json"
if manifest_p.is_file():
current_archived_plans |= _extract_archived_plan_ids_from_text(manifest_p.read_text(encoding="utf-8"))
readme_p = arch_dir / "README.md"
if readme_p.is_file():
current_archived_plans |= _extract_archived_plan_ids_from_text(readme_p.read_text(encoding="utf-8"))
if arch_dir.is_dir():
for p in arch_dir.iterdir():
current_archived_plans |= _extract_archived_plan_ids_from_text(p.name)
baseline_archived_plans: set[str] = set()
kg_tag = _git_run(kg, ["describe", "--tags", "--abbrev=0"]) or baseline_tag
if kg_tag:
old_manifest = _git_run(kg, ["show", f"{kg_tag}:docs/archive/archive-manifest.json"])
if old_manifest:
baseline_archived_plans |= _extract_archived_plan_ids_from_text(old_manifest)
old_readme = _git_run(kg, ["show", f"{kg_tag}:docs/archive/README.md"])
if old_readme:
baseline_archived_plans |= _extract_archived_plan_ids_from_text(old_readme)
old_ls = _git_run(kg, ["ls-tree", "--name-only", kg_tag, "docs/archive/"])
if old_ls:
baseline_archived_plans |= _extract_archived_plan_ids_from_text(old_ls)
newly_archived_plans = sorted(current_archived_plans - baseline_archived_plans)
# 2. Optional Skill Ledger introspection (`hyperstitionstudio-roadmap-and-release/SKILL.md`)
skill_completed_plans: list[str] = []
skill_candidates = [
Path.home() / ".hermes" / "skills" / "software-development" / "hyperstitionstudio-roadmap-and-release" / "SKILL.md",
]
for sp in skill_candidates:
if sp.is_file():
for line in sp.read_text(encoding="utf-8").splitlines():
if "COMPLETED" in line and "PLAN-" in line:
skill_completed_plans.extend(re.findall(r"\bPLAN-[A-Z0-9-]+\b", line))
break
skill_completed_delta = sorted(set(skill_completed_plans) - baseline_archived_plans) if baseline_archived_plans else []
# 3. CLI entrypoints (`pyproject.toml`), MCP tools (`mcp/tools.py`), JSON schemas (`schemas/v1/`), & subpages (`site/<slug>/index.html`)
pyproj_p = core / "pyproject.toml"
cur_scripts = _extract_cli_scripts_from_pyproject(pyproj_p.read_text(encoding="utf-8")) if pyproj_p.is_file() else set()
old_pyproj = _git_run(core, ["show", f"{baseline_tag}:pyproject.toml"])
old_scripts = _extract_cli_scripts_from_pyproject(old_pyproj) if old_pyproj else cur_scripts
tools_p = core / "src" / "hyperstitionstud_io" / "mcp" / "tools.py"
cur_tools = _extract_mcp_tool_names(tools_p.read_text(encoding="utf-8")) if tools_p.is_file() else set()
old_tools_txt = _git_run(core, ["show", f"{baseline_tag}:src/hyperstitionstud_io/mcp/tools.py"])
old_tools = _extract_mcp_tool_names(old_tools_txt) if old_tools_txt else cur_tools
schemas_dir = core / "schemas" / "v1"
cur_schemas = {p.name for p in schemas_dir.glob("*.schema.json")} if schemas_dir.is_dir() else set()
old_schemas_ls = _git_run(core, ["ls-tree", "--name-only", baseline_tag, "schemas/v1/"])
old_schemas = {Path(ln).name for ln in old_schemas_ls.splitlines() if ln.endswith(".schema.json")} if old_schemas_ls else cur_schemas
site_dir = core / "site"
cur_subpages = {p.parent.name for p in site_dir.glob("*/index.html")} if site_dir.is_dir() else set()
old_site_ls = _git_run(core, ["ls-tree", "-r", "--name-only", baseline_tag, "site/"])
old_subpages = {
Path(ln).parts[1]
for ln in old_site_ls.splitlines()
if len(Path(ln).parts) == 3 and Path(ln).parts[0] == "site" and Path(ln).parts[2] == "index.html"
} if old_site_ls else cur_subpages
return {
"current_version": current_v,
"baseline_git_tag": baseline_tag,
"total_dirty_files": total_dirty,
"total_commits_ahead": total_ahead,
"newly_archived_plans": newly_archived_plans,
"skill_completed_plans_delta": skill_completed_delta,
"new_cli_scripts": sorted(cur_scripts - old_scripts),
"removed_cli_scripts": sorted(old_scripts - cur_scripts),
"new_mcp_tools": sorted(cur_tools - old_tools),
"removed_mcp_tools": sorted(old_tools - cur_tools),
"new_schemas": sorted(cur_schemas - old_schemas),
"removed_schemas": sorted(old_schemas - cur_schemas),
"new_subpages": sorted(cur_subpages - old_subpages),
"schema_urn_major_changed": False,
"isolation_baseline_replaced": False,
"repo_diff_summary": repo_diff_summary,
}
def compute_programmatic_version_bump(ws_root: Path | None = None) -> dict[str, Any]:
signals = collect_workspace_change_signals(ws_root=ws_root)
return evaluate_change_scope_heuristics(signals)
def get_version_targets(ws_root: Path | None = None) -> list[tuple[Path, list[tuple[str, str]]]]:
cfg = load_workspace_config(workspace_root=ws_root)
core = cfg.core_dir
kg = cfg.knowledge_graph_dir
calc = cfg.paths["gematria_js_dir"]
return [
(
core / "src" / "hyperstitionstud_io" / "__init__.py",
[
(rf'\(v{SEMVER_RE}\)', "(v{V})"),
(rf'__version__\s*=\s*"{SEMVER_RE}"', '__version__ = "{V}"'),
],
),
(
core / "pyproject.toml",
[(rf'^version\s*=\s*"{SEMVER_RE}"', 'version = "{V}"')],
),
(
core / "package.json",
[(rf'"version":\s*"{SEMVER_RE}"', '"version": "{V}"')],
),
(
core / "packages-js" / "ciphers-aq" / "package.json",
[(rf'"version":\s*"{SEMVER_RE}"', '"version": "{V}"')],
),
(
core / "workspace.example.toml",
[(rf'schema_version\s*=\s*"{SEMVER_RE}"', 'schema_version = "{V}"')],
),
(
core / "site" / "index.html",
[
(rf'urn:io:hyperstitionstud \(v{SEMVER_RE}\)', "urn:io:hyperstitionstud (v{V})"),
(rf'urn:io:hyperstitionstud v{SEMVER_RE}\)', "urn:io:hyperstitionstud v{V})"),
(rf'graph-data\.js\?v={SEMVER_RE}', "graph-data.js?v={V}"),
(rf'hs-group3-basalt-chamfer\.css\?v={SEMVER_RE}', "hs-group3-basalt-chamfer.css?v={V}"),
],
),
(
core / "site" / "learn" / "index.html",
[
(rf'learn-progress-state v{SEMVER_RE}\)', "learn-progress-state v{V})"),
(rf'learn-app\.js\?v={SEMVER_RE}', "learn-app.js?v={V}"),
(rf'hs-group3-basalt-chamfer\.css\?v={SEMVER_RE}', "hs-group3-basalt-chamfer.css?v={V}"),
],
),
(
core / "site" / "learn" / "learn-app.js",
[
(rf'version:\s*"{SEMVER_RE}"', 'version: "{V}"'),
],
),
(
core / "site" / "quant" / "index.html",
[
(rf'urn:io:hyperstitionstud:quant-timeseries:v{SEMVER_RE}\)', "urn:io:hyperstitionstud:quant-timeseries:v{V})"),
(rf'hyperstitionstud\.io/quant v{SEMVER_RE}', "hyperstitionstud.io/quant v{V}"),
(rf'quant-timeseries-data\.js\?v={SEMVER_RE}', "quant-timeseries-data.js?v={V}"),
(rf'real-macro-indicators-data\.js\?v={SEMVER_RE}', "real-macro-indicators-data.js?v={V}"),
(rf'daily-brief-data\.js\?v={SEMVER_RE}', "daily-brief-data.js?v={V}"),
(rf'quant-app\.js\?v={SEMVER_RE}', "quant-app.js?v={V}"),
(rf'quant-tutorials\.js\?v={SEMVER_RE}', "quant-tutorials.js?v={V}"),
(rf'hs-group3-basalt-chamfer\.css\?v={SEMVER_RE}', "hs-group3-basalt-chamfer.css?v={V}"),
],
),
(
core / "site" / "quant" / "quant-app.js",
[
(rf'Time-Series Workbench \(v{SEMVER_RE}\)', "Time-Series Workbench (v{V})"),
],
),
(
core / "site" / "quant" / "quant-tutorials.js",
[
(rf'Deep-Link Choreographer \(v{SEMVER_RE}\)', "Deep-Link Choreographer (v{V})"),
(rf'version:\s*"{SEMVER_RE}"', 'version: "{V}"'),
],
),
(
core / "site" / "donate" / "index.html",
[
(rf'urn:io:hyperstitionstud:donate:v{SEMVER_RE}', "urn:io:hyperstitionstud:donate:v{V}"),
(rf'hyperstitionstud\.io/donate v{SEMVER_RE}', "hyperstitionstud.io/donate v{V}"),
(rf'hs-group3-basalt-chamfer\.css\?v={SEMVER_RE}', "hs-group3-basalt-chamfer.css?v={V}"),
],
),
(
core / "site" / "gallery" / "index.html",
[
(rf'urn:io:hyperstitionstud:gallery:{SEMVER_RE}\)', "urn:io:hyperstitionstud:gallery:{V})"),
],
),
(
core / "scripts" / "build_gallery_manifest.py",
[
(rf'"version":\s*"{SEMVER_RE}"', '"version": "{V}"'),
(rf'urn:io:hyperstitionstud:gallery:{SEMVER_RE}', "urn:io:hyperstitionstud:gallery:{V}"),
],
),
(
core / "src" / "hyperstitionstud_io" / "mcp" / "server.py",
[
(rf'"version":\s*"{SEMVER_RE}"', '"version": "{V}"'),
(rf'urn:io:hyperstitionstud:mcp:{SEMVER_RE}', "urn:io:hyperstitionstud:mcp:{V}"),
],
),
(
core / "src" / "hyperstitionstud_io" / "quant" / "collector.py",
[
(rf'"version":\s*"{SEMVER_RE}"', '"version": "{V}"'),
],
),
(
kg / "index.html",
[
(rf'Interactive Knowledge Graph \(v{SEMVER_RE}\)', "Interactive Knowledge Graph (v{V})"),
(rf'Zero Glossary Leak(?: &bull; v{SEMVER_RE})?</p>', "Zero Glossary Leak &bull; v{V}</p>"),
(rf'(?:hyperstitionstud\.io/graph v{SEMVER_RE} &bull; )?Made with <span class="hs-heart"', "hyperstitionstud.io/graph v{V} &bull; Made with <span class=\"hs-heart\""),
(rf'graph-data\.js\?v={SEMVER_RE}', "graph-data.js?v={V}"),
],
),
(
kg / "scripts" / "build_encyclopedia_knowledge_graph.py",
[
(rf'"version":\s*"{SEMVER_RE}"', '"version": "{V}"'),
],
),
(
kg / "docs" / "cross-repo-dependency-and-audit-flow-diagram.html",
[
(rf'technocapital-singularity-zoology \(v{SEMVER_RE}\)', "technocapital-singularity-zoology (v{V})"),
(rf'encyclopedia-knowledge-graph \(v{SEMVER_RE}\)', "encyclopedia-knowledge-graph (v{V})"),
],
),
(
calc / "index.html",
[
(rf'(?:hyperstitionstud\.io/calc v{SEMVER_RE} &bull; )?Made with <span class="hs-heart"', "hyperstitionstud.io/calc v{V} &bull; Made with <span class=\"hs-heart\""),
],
),
]
def sync_workspace_version(target_version: str, check_only: bool = False, ws_root: Path | None = None) -> dict[str, Any]:
v = target_version.lstrip("v").strip()
if not re.match(rf"^{SEMVER_RE}$", v):
raise ValueError(f"Invalid semantic version '{target_version}' (expected X.Y.Z)")
cfg = load_workspace_config(workspace_root=ws_root)
targets = get_version_targets(ws_root=ws_root)
modified_files: list[str] = []
mismatched_files: list[str] = []
for path, patterns in targets:
if not path.is_file():
continue
orig = path.read_text(encoding="utf-8")
updated = orig
for pat_re, repl_tmpl in patterns:
repl = repl_tmpl.replace("{V}", v)
updated = re.sub(pat_re, repl, updated, flags=re.M)
if f"v{v}" not in updated and f'"{v}"' not in updated and f":{v}" not in updated:
mismatched_files.append(str(path))
elif updated != orig:
if check_only:
mismatched_files.append(str(path))
else:
path.write_text(updated, encoding="utf-8")
modified_files.append(str(path))
if not check_only:
ws_toml = cfg.workspace_root / "workspace.toml"
if ws_toml.is_file():
orig_ws = ws_toml.read_text(encoding="utf-8")
upd_ws = re.sub(rf'schema_version\s*=\s*"{SEMVER_RE}"', f'schema_version = "{v}"', orig_ws, flags=re.M)
if upd_ws != orig_ws:
ws_toml.write_text(upd_ws, encoding="utf-8")
modified_files.append(str(ws_toml))
return {
"target_version": v,
"check_only": check_only,
"all_in_sync": len(mismatched_files) == 0,
"modified_files": modified_files,
"mismatched_files": mismatched_files,
}
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(prog="hs-sync-version", description="Synchronize or verify version numbers across all site elements and manifests.")
ap.add_argument("--set", dest="set_version", default=None, help="Set new version X.Y.Z across all site HTML elements, JS bundles, and manifests.")
ap.add_argument("--check", action="store_true", help="Verify that all site elements match hyperstitionstud_io.__version__ without modifying files.")
ap.add_argument("--explain-bump", action="store_true", help="Evaluate zero-LLM-token change-scope heuristics and print the recommended bump level without modifying files.")
ap.add_argument("--auto-bump", action="store_true", help="Programmatically determine the next semantic version via change-scope heuristics (0 LLM tokens) and synchronize all workspace files.")
args = ap.parse_args(argv)
if args.explain_bump:
report = compute_programmatic_version_bump()
print(json.dumps(report, indent=2))
return 0
if args.auto_bump:
report = compute_programmatic_version_bump()
next_v = report["next_version"]
check_only = report["recommended_bump_level"] == "noop"
sync_res = sync_workspace_version(next_v, check_only=check_only)
sync_res["auto_bump"] = report
print(json.dumps(sync_res, indent=2))
return 0 if sync_res["all_in_sync"] else 1
target_v = args.set_version.lstrip("v") if args.set_version else CURRENT_VERSION
res = sync_workspace_version(target_v, check_only=args.check)
print(json.dumps(res, indent=2))
return 0 if res["all_in_sync"] else 1
if __name__ == "__main__":
raise SystemExit(main())