1
0
forked from jason/echo
Files
chorus/build.py
T

223 lines
10 KiB
Python
Raw Permalink Normal View History

2026-06-22 09:27:36 -05:00
#!/usr/bin/env python3
"""build.py — package the echo-memory plugin source into a .plugin artifact.
Zips the CONTENTS of echo-memory.plugin.src/ at the archive root (the layout the plugin
loader expects: .claude-plugin/plugin.json, commands/, skills/ all at top level), excluding
dev cruft. The version is read from the manifest, so the output is named automatically.
Usage:
python build.py # build echo-memory-<version>.plugin + refresh echo-memory.plugin
2026-06-25 17:54:03 -05:00
# (token-free: ships no credentials; user configures at runtime)
python build.py --bake-key --from coworker.json [--label alice]
# SECRET-BEARING per-user artifact: bake owner/endpoint/key from a
# config.json (or --owner/--endpoint/--key, or ECHO_* env) into the
# echo_config DEFAULT_* constants. Defaults to dist/ and skips the
# shared pointer. Deliver directly to that one user — NEVER commit it.
python build.py --strip-key # force-blank the DEFAULT_* constants -> guaranteed token-free artifact
2026-06-22 09:27:36 -05:00
python build.py --no-pointer # don't update the echo-memory.plugin "current" pointer
python build.py --outdir dist # write artifacts somewhere other than the repo root
Deterministic: entries are sorted and stamped with a fixed timestamp, so an unchanged
source tree always produces a byte-identical archive (clean diffs / reproducible builds).
Pure stdlib; runs the same on Windows/macOS/Linux.
"""
from __future__ import annotations
import argparse
import json
2026-06-25 17:54:03 -05:00
import os
2026-06-22 09:27:36 -05:00
import re
import sys
import zipfile
from pathlib import Path
# Keep non-ASCII (em-dashes in our messages) from raising/garbling on a legacy console.
for _stream in (sys.stdout, sys.stderr):
try:
_stream.reconfigure(encoding="utf-8", errors="replace") # type: ignore[union-attr]
except Exception:
pass
REPO = Path(__file__).resolve().parent
SRC = REPO / "echo-memory.plugin.src"
MANIFEST = "/".join([".claude-plugin", "plugin.json"])
2026-06-25 17:54:03 -05:00
# The baked DEFAULT_* constants live in echo_config.py (resolution lowest tier).
CONFIG_PY = "/".join(["skills", "echo-memory", "scripts", "echo_config.py"])
2026-06-22 09:27:36 -05:00
EXCLUDE_DIRS = {"__pycache__", ".git"}
EXCLUDE_NAMES = {".DS_Store"}
EXCLUDE_SUFFIXES = {".pyc", ".pyo"}
FIXED_DATE = (2026, 1, 1, 0, 0, 0) # stable timestamp for reproducible archives
2026-06-23 07:18:23 -05:00
MAX_DESCRIPTION = 500 # plugin-marketplace cap: plugin.json "description" must be UNDER this
# (it has silently regressed past the limit before — fail the build now)
2026-06-22 09:27:36 -05:00
2026-06-25 17:54:03 -05:00
# field name -> the constant assigned in echo_config.py
_CONSTS = {"owner": "DEFAULT_OWNER", "endpoint": "DEFAULT_BASE", "key": "DEFAULT_KEY"}
def _const_re(const: str) -> re.Pattern:
"""Match a whole `CONST = <anything>` assignment line."""
return re.compile(r'^(' + re.escape(const) + r'\s*=\s*).*$', re.M)
2026-06-22 09:27:36 -05:00
def included_files() -> list[Path]:
out = []
for p in sorted(SRC.rglob("*")):
if p.is_dir():
continue
if any(part in EXCLUDE_DIRS for part in p.relative_to(SRC).parts):
continue
if p.name in EXCLUDE_NAMES or p.suffix in EXCLUDE_SUFFIXES:
continue
out.append(p)
return out
2026-06-25 17:54:03 -05:00
def file_bytes(path: Path, arcname: str, bake: dict | None, strip_key: bool) -> bytes:
"""Return the bytes to archive. For echo_config.py, optionally rewrite the
DEFAULT_* constants — inject `bake` values, or blank them with --strip-key."""
2026-06-22 09:27:36 -05:00
data = path.read_bytes()
2026-06-25 17:54:03 -05:00
if arcname != CONFIG_PY or (bake is None and not strip_key):
return data
text = data.decode("utf-8")
for field, const in _CONSTS.items():
repl = json.dumps(bake[field]) if bake is not None else '""'
# function replacement so backslashes in repl (e.g. \uXXXX) stay literal
text, n = _const_re(const).subn(lambda m, r=repl: m.group(1) + r, text, count=1)
if n != 1:
raise RuntimeError(f"build: could not find `{const} = ...` in {arcname}")
return text.encode("utf-8")
2026-06-22 09:27:36 -05:00
def token_present(path: Path) -> bool:
2026-06-25 17:54:03 -05:00
"""True if any DEFAULT_* constant in echo_config.py holds a non-empty value."""
text = path.read_text(encoding="utf-8")
for const in _CONSTS.values():
m = re.search(r'^' + re.escape(const) + r'\s*=\s*"(.*)"\s*$', text, re.M)
if m and m.group(1):
return True
return False
2026-06-22 09:27:36 -05:00
2026-06-25 17:54:03 -05:00
def build(out: Path, files: list[Path], bake: dict | None, strip_key: bool) -> int:
2026-06-22 09:27:36 -05:00
if out.exists():
out.unlink()
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z:
for p in files:
arc = p.relative_to(SRC).as_posix()
info = zipfile.ZipInfo(arc, date_time=FIXED_DATE)
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = 0o644 << 16
2026-06-25 17:54:03 -05:00
z.writestr(info, file_bytes(p, arc, bake, strip_key))
2026-06-22 09:27:36 -05:00
return out.stat().st_size
2026-06-25 17:54:03 -05:00
def bake_values(args) -> dict:
"""Resolve owner/endpoint/key for --bake-key from --owner/--endpoint/--key,
else --from <config.json>, else ECHO_OWNER/ECHO_BASE/ECHO_KEY env."""
src = {}
if args.from_file:
fp = Path(args.from_file).expanduser()
if not fp.exists():
raise RuntimeError(f"build: --from file not found: {fp}")
try:
loaded = json.loads(fp.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise RuntimeError(f"build: --from file is not valid JSON ({exc})")
if isinstance(loaded, dict):
src = loaded
vals = {
"owner": args.owner or src.get("owner") or os.environ.get("ECHO_OWNER") or "",
"endpoint": (args.endpoint or src.get("endpoint") or os.environ.get("ECHO_BASE") or "").rstrip("/"),
"key": args.key or src.get("key") or os.environ.get("ECHO_KEY") or "",
}
missing = [f for f in ("endpoint", "key") if not vals[f]]
if missing:
raise RuntimeError(
"build: --bake-key needs a real endpoint and key — missing "
+ ", ".join(missing) + ". Provide --from <config.json>, the --owner/"
"--endpoint/--key flags, or set ECHO_OWNER/ECHO_BASE/ECHO_KEY.")
if "your-obsidian-rest-endpoint" in vals["endpoint"] or vals["key"].startswith("<"):
raise RuntimeError("build: --bake-key got the template placeholders, not real values.")
return vals
2026-06-22 09:27:36 -05:00
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description="Build the echo-memory .plugin artifact")
2026-06-25 17:54:03 -05:00
ap.add_argument("--bake-key", action="store_true",
help="bake a user's owner/endpoint/key into the artifact (secret-bearing — never commit)")
ap.add_argument("--from", dest="from_file", metavar="FILE",
help="config.json to read owner/endpoint/key from when baking")
ap.add_argument("--owner", help="baked owner (overrides --from / env)")
ap.add_argument("--endpoint", help="baked endpoint (overrides --from / env)")
ap.add_argument("--key", help="baked key (overrides --from / env)")
ap.add_argument("--label", help="suffix for the artifact name, e.g. --label alice")
2026-06-22 09:27:36 -05:00
ap.add_argument("--strip-key", action="store_true",
2026-06-25 17:54:03 -05:00
help="force-blank the DEFAULT_* constants so no token ships in the artifact")
2026-06-22 09:27:36 -05:00
ap.add_argument("--no-pointer", action="store_true",
help="do not refresh the echo-memory.plugin 'current' pointer")
2026-06-25 17:54:03 -05:00
ap.add_argument("--outdir", help="output directory (default: repo root; dist/ when --bake-key)")
2026-06-22 09:27:36 -05:00
args = ap.parse_args(argv)
2026-06-25 17:54:03 -05:00
if args.bake_key and args.strip_key:
print("build: --bake-key and --strip-key are mutually exclusive", file=sys.stderr)
return 2
2026-06-22 09:27:36 -05:00
if not SRC.is_dir():
print(f"build: source tree not found at {SRC}", file=sys.stderr)
return 1
2026-06-25 17:54:03 -05:00
bake = None
if args.bake_key:
try:
bake = bake_values(args)
except RuntimeError as exc:
print(exc, file=sys.stderr)
return 2
2026-06-22 09:27:36 -05:00
manifest_path = SRC / ".claude-plugin" / "plugin.json"
2026-06-23 07:18:23 -05:00
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
version = manifest["version"]
desc = manifest.get("description", "")
if len(desc) >= MAX_DESCRIPTION:
print(f"build: plugin description is {len(desc)} chars — must be under "
f"{MAX_DESCRIPTION} (marketplace cap). Trim \"description\" in {MANIFEST}.",
file=sys.stderr)
return 1
2026-06-22 09:27:36 -05:00
files = included_files()
arcnames = {p.relative_to(SRC).as_posix() for p in files}
if MANIFEST not in arcnames:
print(f"build: {MANIFEST} missing from the archive root — aborting", file=sys.stderr)
return 1
2026-06-25 17:54:03 -05:00
# Baked artifacts are secret-bearing: default them into dist/ (gitignored) and
# never touch the shared, committable echo-memory.plugin pointer.
default_outdir = (REPO / "dist") if bake else REPO
outdir = Path(args.outdir) if args.outdir else default_outdir
2026-06-22 09:27:36 -05:00
outdir.mkdir(parents=True, exist_ok=True)
2026-06-25 17:54:03 -05:00
label = f"-{args.label}" if args.label else ""
targets = [outdir / f"echo-memory-{version}{label}.plugin"]
if not args.no_pointer and not bake:
2026-06-22 09:27:36 -05:00
targets.append(outdir / "echo-memory.plugin")
for out in targets:
2026-06-25 17:54:03 -05:00
size = build(out, files, bake, args.strip_key)
2026-06-22 09:27:36 -05:00
print(f"built {out.name} ({len(files)} entries, {size:,} bytes)")
2026-06-25 17:54:03 -05:00
if bake:
who = bake.get("owner") or "(no owner)"
print(f"note: --bake-key baked credentials for {who} into {CONFIG_PY}.")
print("WARNING: this artifact carries a vault key — deliver it directly to that one "
"user and NEVER commit, push, or publish it (dist/ is gitignored).")
elif args.strip_key:
print("note: --strip-key set — artifact is token-free; user configures owner/endpoint/key at runtime.")
elif token_present(SRC / "skills" / "echo-memory" / "scripts" / "echo_config.py"):
print("WARNING: a DEFAULT_* constant in echo_config.py is non-empty — this artifact carries a "
"secret. Do not commit it. Build from a clean source tree, or use --strip-key.")
2026-06-22 09:27:36 -05:00
return 0
if __name__ == "__main__":
raise SystemExit(main())