feat(core): implement Plan #62 efficiency, deduplication, caching & hook optimizations

This commit is contained in:
Hermes Agent committed 2026-12-02 22:09:58 +00:00
1 parent d4b7502501
commit 9b587d6351
20 files changed
+176 -195

No files matched your search

@@ -32,7 +32,7 @@ from pathlib import Path
from typing import Any
from hyperstitionstud_io import __version__ as CURRENT_VERSION
from hyperstitionstud_io.config import load_json_cached, load_workspace_config
from hyperstitionstud_io.config import load_json_cached, load_workspace_config, normalize_workspace_relpath
from hyperstitionstud_io.db.sqlite_meta import ensure_single_layer_gzip_file, parse_size_spec_bytes
from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard, sha256_file
from hyperstitionstud_io.ipld import compute_dag_json_cidv1
@@ -47,15 +47,6 @@ INACTIVE_MANIFEST_FILENAME = "inactive-archive-manifest.json"
DEFAULT_MAX_ARCHIVE_BUNDLE_BYTES = 256 * 1024 # 262,144 bytes (256 KB)
def _norm_ws_path(p: Path | str, workspace_root: str | Path | None = None) -> str:
cfg = load_workspace_config(workspace_root=workspace_root)
ws_res = str(cfg.workspace_root.resolve())
s = str(Path(p).resolve())
if s.startswith(ws_res):
return "/workspace" + s[len(ws_res):]
return str(p)
def assert_not_gematria_pipeline_source(target_path: str | Path, workspace_root: str | Path | None = None) -> Path:
"""
Hard programmatic block guaranteeing that NO file supplying any gematria, phonemic,
@@ -571,7 +562,7 @@ def _load_existing_manifest_maps(manifest_p: Path) -> tuple[dict[str, dict[str,
existing_manifest: dict[str, Any] = {}
if manifest_p.is_file():
try:
existing_manifest = load_json_cached(manifest_p)
existing_manifest = load_json_cached(manifest_p, copy_result=False)
except Exception:
existing_manifest = {}
@@ -690,8 +681,8 @@ def rotate_docs_archive_directory(
staged_files = sorted(p for p in stage_dir.iterdir() if p.is_file() and p.suffix == ".md")
if not staged_files and not long_term_by_name:
return {
"archive_dir": _norm_ws_path(arc_p),
"bundle_path": _norm_ws_path(bundle_p),
"archive_dir": normalize_workspace_relpath(arc_p),
"bundle_path": normalize_workspace_relpath(bundle_p),
"member_count": 0,
"rotated_loose_files": 0,
"preserved_standalone_pdfs": preserved_standalone_pdfs,
@@ -720,9 +711,9 @@ def rotate_docs_archive_directory(
lp.unlink()
return {
"archive_dir": _norm_ws_path(arc_p),
"bundle_path": _norm_ws_path(bundle_p),
"manifest_path": _norm_ws_path(manifest_p),
"archive_dir": normalize_workspace_relpath(arc_p),
"bundle_path": normalize_workspace_relpath(bundle_p),
"manifest_path": normalize_workspace_relpath(manifest_p),
"manifest_dag_json_cid": manifest_cid,
"max_bundle_bytes": eff_max_bytes,
"bundle_size_bytes": bundle_p.stat().st_size,
@@ -815,8 +806,8 @@ def rotate_inactive_plans_marked_for_archival(
if not staged_files and not long_term_by_name:
return {
"ok": True,
"inactive_dir": _norm_ws_path(inactive_dir, workspace_root=workspace_root),
"bundle_path": _norm_ws_path(bundle_p, workspace_root=workspace_root),
"inactive_dir": normalize_workspace_relpath(inactive_dir, workspace_root=workspace_root),
"bundle_path": normalize_workspace_relpath(bundle_p, workspace_root=workspace_root),
"member_count": 0,
"rotated_loose_files": 0,
"retained_inactive_plans": retained_inactive_plans,
@@ -843,9 +834,9 @@ def rotate_inactive_plans_marked_for_archival(
return {
"ok": True,
"version": CURRENT_VERSION,
"inactive_dir": _norm_ws_path(inactive_dir, workspace_root=workspace_root),
"bundle_path": _norm_ws_path(bundle_p, workspace_root=workspace_root),
"manifest_path": _norm_ws_path(manifest_p, workspace_root=workspace_root),
"inactive_dir": normalize_workspace_relpath(inactive_dir, workspace_root=workspace_root),
"bundle_path": normalize_workspace_relpath(bundle_p, workspace_root=workspace_root),
"manifest_path": normalize_workspace_relpath(manifest_p, workspace_root=workspace_root),
"manifest_dag_json_cid": manifest_cid,
"bundle_size_bytes": bundle_p.stat().st_size,
"bundle_sha256": bundle_sha,
@@ -981,10 +972,10 @@ def audit_and_fix_multi_compressed_files(
fp.unlink()
else:
fp.rename(base_p)
removed_double_sidecars.append(_norm_ws_path(fp, workspace_root=workspace_root))
removed_double_sidecars.append(normalize_workspace_relpath(fp, workspace_root=workspace_root))
continue
else:
removed_double_sidecars.append(_norm_ws_path(fp, workspace_root=workspace_root))
removed_double_sidecars.append(normalize_workspace_relpath(fp, workspace_root=workspace_root))
if fn.endswith((".gz", ".tgz")):
scanned_gz_count += 1
@@ -996,7 +987,7 @@ def audit_and_fix_multi_compressed_files(
if head.startswith((b"\x1f\x8b", b"\xfd7zXZ\x00")):
if fix:
ensure_single_layer_gzip_file(fp)
peeled_gzip_files.append(_norm_ws_path(fp, workspace_root=workspace_root))
peeled_gzip_files.append(normalize_workspace_relpath(fp, workspace_root=workspace_root))
if fn.endswith((".tar.gz", ".tgz", ".tar.xz")):
scanned_tar_count += 1
@@ -1025,12 +1016,12 @@ def audit_and_fix_multi_compressed_files(
elif bad_members and fix and fn.startswith("ingglish-isopsephic-exegesis-") and fn.endswith((".tar.gz", ".tar.xz")):
# Remove legacy 2x-compressed packaging wrapper if still present in an unpulled/live directory
fp.unlink()
removed_double_sidecars.append(_norm_ws_path(fp, workspace_root=workspace_root))
removed_double_sidecars.append(normalize_workspace_relpath(fp, workspace_root=workspace_root))
bad_members = []
if bad_members:
nested_archive_violations.append(
{
"archive": _norm_ws_path(fp, workspace_root=workspace_root),
"archive": normalize_workspace_relpath(fp, workspace_root=workspace_root),
"nested_compressed_members": bad_members,
}
)
@@ -1150,7 +1141,7 @@ def main(argv: list[str] | None = None) -> int:
):
mp = d / mf
if mp.is_file():
out[_norm_ws_path(d, workspace_root=args.workspace_root)] = load_json_cached(mp)
out[normalize_workspace_relpath(d, workspace_root=args.workspace_root)] = load_json_cached(mp, copy_result=False)
print(json.dumps(out, indent=2))
return 0
@@ -30,12 +30,15 @@ from typing import Any
from PIL import Image, ImageDraw
from hyperstitionstud_io import __version__ as CURRENT_VERSION
from hyperstitionstud_io.config import load_json_cached, load_workspace_config
from hyperstitionstud_io.config import count_file_lines_cached, load_json_cached, load_workspace_config
from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard
from hyperstitionstud_io.ipld import compute_dag_json_cidv1
from hyperstitionstud_io.publishing.fonts import (
GROUP3_PALETTE,
draw_bounded_box_text,
draw_bounded_kv_row,
draw_group3_chamfered_plate,
fit_pillow_text_to_width,
load_pillow_font,
)
@@ -126,17 +129,15 @@ def _fit_font_for_width(
min_size: int = 8,
bold: bool = False,
) -> tuple[Any, int, int]:
font_file = FONT_MONO_B if bold else FONT_MONO
for sz in range(preferred_size, min_size - 1, -1):
f = _fnt(font_file, sz)
tb = d.textbbox((0, 0), text, font=f)
w = int(tb[2] - tb[0])
h = int(tb[3] - tb[1])
if w <= max_width:
return f, w, h
f = _fnt(font_file, min_size)
tb = d.textbbox((0, 0), text, font=f)
return f, int(tb[2] - tb[0]), int(tb[3] - tb[1])
return fit_pillow_text_to_width(
d,
text,
max_width,
preferred_size=preferred_size,
min_size=min_size,
bold=bold,
font_filename=FONT_MONO_B if bold else FONT_MONO,
)
def _draw_box_text(
@@ -152,18 +153,19 @@ def _draw_box_text(
bold: bool = False,
y_pos: int | None = None,
) -> tuple[int, int, int, int]:
bx1, by1, bx2, by2 = box
avail_w = max(16, (bx2 - bx1) - 2 * pad_x)
f, tw, th = _fit_font_for_width(d, text, avail_w, preferred_size=preferred_size, min_size=min_size, bold=bold)
if align == "center":
tx = bx1 + max(pad_x, ((bx2 - bx1) - tw) // 2)
elif align == "right":
tx = max(bx1 + pad_x, bx2 - pad_x - tw)
else:
tx = bx1 + pad_x
ty = y_pos if y_pos is not None else (by1 + max(2, ((by2 - by1) - th) // 2 - 1))
d.text((tx, ty), text, font=f, fill=fill)
return d.texts[-1][2]
return draw_bounded_box_text(
d,
box,
text,
fill,
pad_x=pad_x,
align=align,
preferred_size=preferred_size,
min_size=min_size,
bold=bold,
y_pos=y_pos,
font_filename=FONT_MONO_B if bold else FONT_MONO,
)
def _draw_kv_row(
@@ -181,22 +183,20 @@ def _draw_kv_row(
val_bold: bool = False,
min_val_x: int | None = None,
) -> None:
bx1, by1, bx2, by2 = box
d.rectangle([bx1, by1, bx2, by2], fill=fill_bg, outline=outline)
total_inner = (bx2 - bx1) - 16
kf, kw, kh = _fit_font_for_width(d, key_text, max(40, int(total_inner * 0.52)), preferred_size=key_size, min_size=8, bold=True)
ky = by1 + max(2, ((by2 - by1) - kh) // 2 - 1)
kx = bx1 + 8
d.text((kx, ky), key_text, font=kf, fill=key_fill)
key_tb = d.texts[-1][2]
vx_start = max(key_tb[2] + 8, min_val_x if min_val_x is not None else (key_tb[2] + 10))
avail_val_w = max(24, (bx2 - 6) - vx_start)
vf, vw, vh = _fit_font_for_width(d, val_text, avail_val_w, preferred_size=val_size, min_size=8, bold=val_bold)
if vx_start + vw > bx2 - 6:
vx_start = max(key_tb[2] + 6, (bx2 - 6) - vw)
vy = by1 + max(2, ((by2 - by1) - vh) // 2 - 1)
d.text((vx_start, vy), val_text, font=vf, fill=val_fill)
draw_bounded_kv_row(
d,
box,
key_text,
val_text,
fill_bg=fill_bg,
outline=outline,
key_fill=key_fill,
val_fill=val_fill,
key_size=key_size,
val_size=val_size,
val_bold=val_bold,
min_val_x=min_val_x,
)
def verify_closeup_geometry(tracked_by_filename: dict[str, _TrackedCanvasDraw]) -> dict[str, Any]:
@@ -408,7 +408,7 @@ def introspect_live_ui_elements(workspace_root: str | Path | None = None) -> dic
}
db_txt_p = calc_dir / "db.txt"
db_entries_count = sum(1 for _ in db_txt_p.open(encoding="utf-8")) if db_txt_p.is_file() else 231615
db_entries_count = count_file_lines_cached(db_txt_p) if db_txt_p.is_file() else 231615
ci_rep_p = ci_dir / "ci-audit-report.json"
ci_obj = load_json_cached(ci_rep_p, copy_result=False) if ci_rep_p.is_file() else {}
@@ -486,7 +486,7 @@ def render_all_quadrant_closeups(
prev_fp = ""
if manifest_path.is_file():
try:
prev_obj = json.loads(manifest_path.read_text(encoding="utf-8"))
prev_obj = load_json_cached(manifest_path, copy_result=False)
prev_fp = prev_obj.get("ui_elements_fingerprint_sha256", "")
except Exception:
prev_fp = ""
@@ -9,6 +9,7 @@ clamping (`breach_count == 0`).
from __future__ import annotations
import hashlib
import json
import os
from pathlib import Path
@@ -20,6 +21,7 @@ from hyperstitionstud_io.publishing.fonts import (
GROUP3_PALETTE,
chamfer_polygon_points as _chamfer_pts,
draw_group3_chamfered_plate as _draw_group3_plate,
fit_pillow_text_to_width,
load_pillow_font,
)
@@ -55,18 +57,48 @@ def _draw_arrow_right(draw: Any, x0: int, x1: int, y: int, color: tuple[int, int
draw.polygon([(x1 - 10, y - 5), (x1 - 10, y + 5), (x1, y)], fill=color)
def _compute_flow_diagram_sha256() -> str:
src_bytes = Path(__file__).resolve().read_bytes()
h = hashlib.sha256()
h.update(f"v{CURRENT_VERSION}:{DIAGRAM_WIDTH}x{DIAGRAM_HEIGHT}:".encode("utf-8"))
h.update(src_bytes)
return h.hexdigest()
def render_periodic_harvest_cicd_flow_diagram_png(
output_path: str | Path | None = None,
*,
if_changed: bool = True,
) -> dict[str, Any]:
"""
Render the 5-Stage End-to-End Periodic Data Harvest -> CI/CD -> Deployed VPS Infrastructure Flow Diagram
to `/workspace/encyclopedia-knowledge-graph/docs/periodic-harvest-cicd-to-vps-flow-diagram.png`.
When `if_changed=True` and the existing PNG embeds a matching `hs_diagram_sha256` tEXt chunk,
skips rewriting the file.
"""
from PIL import Image, ImageDraw
from PIL.PngImagePlugin import PngInfo
cfg = load_workspace_config()
out_p = Path(output_path) if output_path else (cfg.knowledge_graph_dir / "docs" / "periodic-harvest-cicd-to-vps-flow-diagram.png")
out_p = out_p.resolve()
diagram_sha256 = _compute_flow_diagram_sha256()
if if_changed and out_p.is_file():
try:
with Image.open(out_p) as existing_im:
if existing_im.info.get("hs_diagram_sha256") == diagram_sha256:
return {
"png_path": str(out_p),
"dimensions": [DIAGRAM_WIDTH, DIAGRAM_HEIGHT],
"size_bytes": out_p.stat().st_size,
"breach_count": 0,
"skipped_unchanged": True,
"hs_diagram_sha256": diagram_sha256,
}
except Exception:
pass
out_p.parent.mkdir(parents=True, exist_ok=True)
tmp_p = out_p.with_suffix(f".tmp.{os.getpid()}.png")
@@ -381,13 +413,17 @@ def render_periodic_harvest_cicd_flow_diagram_png(
fit_text(bbox[0] + 12, ly, ln, TXT_PRI, [f_m11, f_m10], max_x=bbox[2] - 10)
ly += 20
img.save(tmp_p, format="PNG")
pnginfo = PngInfo()
pnginfo.add_text("hs_diagram_sha256", diagram_sha256)
img.save(tmp_p, format="PNG", pnginfo=pnginfo)
os.replace(tmp_p, out_p)
return {
"png_path": str(out_p),
"dimensions": [DIAGRAM_WIDTH, DIAGRAM_HEIGHT],
"size_bytes": out_p.stat().st_size,
"breach_count": breach_count,
"skipped_unchanged": False,
"hs_diagram_sha256": diagram_sha256,
}
@@ -20,7 +20,7 @@ from pathlib import Path
from typing import Any
from hyperstitionstud_io import __version__ as CURRENT_VERSION
from hyperstitionstud_io.config import load_workspace_config
from hyperstitionstud_io.config import load_json_cached, load_workspace_config
from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard
from hyperstitionstud_io.ipld import compute_dag_json_cidv1
from hyperstitionstud_io.mcp.tools import MCP_TOOLS_SCHEMA
@@ -44,7 +44,7 @@ def compute_corpus_delta_report(workspace_root: str | Path | None = None) -> dic
prior_snap = cur_snap
if cache_p.is_file():
try:
prior_snap = json.loads(cache_p.read_text(encoding="utf-8"))
prior_snap = load_json_cached(cache_p, copy_result=False)
except Exception:
prior_snap = cur_snap
@@ -39,7 +39,7 @@ from pathlib import Path
from typing import Any
from hyperstitionstud_io import __version__ as CURRENT_VERSION
from hyperstitionstud_io.config import load_workspace_config
from hyperstitionstud_io.config import load_json_cached, load_workspace_config
from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard
from hyperstitionstud_io.phonetics import translate_batch
@@ -393,7 +393,7 @@ def build_quant_tour_voice_assets(
prev_clips_by_id: dict[str, dict[str, Any]] = {}
if not force and manifest_p.is_file():
try:
prev_man = json.loads(manifest_p.read_text(encoding="utf-8"))
prev_man = load_json_cached(manifest_p, copy_result=False)
for c_item in prev_man.get("clips") or []:
cid = str(c_item.get("clip_id") or "")
if cid and (target_dir / f"{cid}.wav").is_file():
@@ -34,7 +34,7 @@ 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, resolve_workspace_repo_dir # noqa: E402
from hyperstitionstud_io.config import load_workspace_config, resolve_workspace_repo_dir, run_git_stdout # noqa: E402
STATUS_START = "<!-- HS-COMMIT-STATUS:START -->"
STATUS_END = "<!-- HS-COMMIT-STATUS:END -->"
@@ -73,22 +73,6 @@ REPO_SPECS: dict[str, dict[str, str]] = {
}
def _git_out(repo_dir: Path, args: list[str], strip_leading: bool = True) -> str:
try:
res = subprocess.run(
["git", "-C", str(repo_dir), *args],
capture_output=True,
text=True,
timeout=5,
check=False,
)
if res.returncode == 0:
return res.stdout.strip() if strip_leading else res.stdout.rstrip("\r\n")
except Exception:
pass
return ""
def _resolve_repo_dir(ws_root: Path, repo_key: str) -> Path:
return resolve_workspace_repo_dir(ws_root, repo_key)
@@ -106,11 +90,11 @@ def _introspect_repo_commit_context(repo_dir: Path, version: str) -> dict[str, A
}
# Check staged files first (for pre-commit hook)
staged_raw = _git_out(repo_dir, ["diff", "--cached", "--name-only"])
staged_raw = run_git_stdout(repo_dir, ["diff", "--cached", "--name-only"])
staged = [ln.strip() for ln in staged_raw.splitlines() if ln.strip() and ln.strip() != "README.md"]
# Check working-tree modified files next (preserve leading status column on line 1!)
status_raw = _git_out(repo_dir, ["status", "--porcelain"], strip_leading=False)
status_raw = run_git_stdout(repo_dir, ["status", "--porcelain"], strip_leading=False)
dirty: list[str] = []
for ln in status_raw.splitlines():
if not ln.strip():
@@ -119,7 +103,7 @@ def _introspect_repo_commit_context(repo_dir: Path, version: str) -> dict[str, A
if p and p != "README.md" and not p.startswith("untracked/"):
dirty.append(p)
head_files_raw = _git_out(repo_dir, ["diff-tree", "--no-commit-id", "--name-only", "-r", "HEAD"])
head_files_raw = run_git_stdout(repo_dir, ["diff-tree", "--no-commit-id", "--name-only", "-r", "HEAD"])
head_files = [ln.strip() for ln in head_files_raw.splitlines() if ln.strip() and ln.strip() != "README.md"]
active_files = staged if staged else (dirty if dirty else head_files)
@@ -488,8 +472,8 @@ def sync_all_repo_readmes(
PRE_COMMIT_HOOK_SCRIPT = """#!/usr/bin/env bash
# Auto-installed by hyperstitionstud_io.publishing.readme_sync (hs-readme-sync --install-hooks)
# Prepares & validates push-all-to-git-libre-audio.sh and deploy/sync-vps-repos.sh (Gates D1-D8),
# re-renders homepage UI closeups when page UI elements change, and synchronizes root README.md before every commit.
# Path-aware pre-commit hook: runs deploy_scripts_sync & closeups_sync only when staged files
# affect their respective surfaces, and synchronizes root README.md + shorthand_lint before every commit.
set -euo pipefail
REPO_ROOT="$(git rev-parse --show-toplevel)"
@@ -506,14 +490,19 @@ fi
if [[ -d "${CORE_SRC}" ]]; then
export PYTHONPATH="${CORE_SRC}${PYTHONPATH:+:${PYTHONPATH}}"
STAGED_FILES="$(git -C "${REPO_ROOT}" diff --cached --name-only || true)"
if [[ "${REPO_NAME}" == "hyperstitionstudio-core" ]]; then
"${PYTHON_BIN}" -m hyperstitionstud_io.ci.deploy_scripts_sync --workspace-root "${WS_ROOT}" --stage
else
"${PYTHON_BIN}" -m hyperstitionstud_io.ci.deploy_scripts_sync --workspace-root "${WS_ROOT}"
if printf '%s\n' "${STAGED_FILES}" | grep -Eq '^(deploy/|pyproject\\.toml|src/hyperstitionstud_io/__init__\\.py)'; then
"${PYTHON_BIN}" -m hyperstitionstud_io.ci.deploy_scripts_sync --workspace-root "${WS_ROOT}" --stage
else
"${PYTHON_BIN}" -m hyperstitionstud_io.ci.deploy_scripts_sync --workspace-root "${WS_ROOT}" --check
fi
fi
"${PYTHON_BIN}" -m hyperstitionstud_io.publishing.closeups_sync
if [[ -d "${WS_ROOT}/hyperstitionstudio-core/site/assets/closeups" ]] && [[ "${REPO_NAME}" == "hyperstitionstudio-core" ]]; then
git -C "${REPO_ROOT}" add site/assets/closeups/
if printf '%s\n' "${STAGED_FILES}" | grep -Eq '(^site/|^index\\.html$|^config\\.default\\.js$|^ci-audit-report\\.json$|^src/hyperstitionstud_io/(publishing|quant)/)'; then
"${PYTHON_BIN}" -m hyperstitionstud_io.publishing.closeups_sync
if [[ -d "${WS_ROOT}/hyperstitionstudio-core/site/assets/closeups" ]] && [[ "${REPO_NAME}" == "hyperstitionstudio-core" ]]; then
git -C "${REPO_ROOT}" add site/assets/closeups/
fi
fi
"${PYTHON_BIN}" -m hyperstitionstud_io.publishing.readme_sync --repo "${REPO_NAME}" --stage
"${PYTHON_BIN}" -m hyperstitionstud_io.ci.shorthand_lint --staged-diff --repo "${REPO_ROOT}"