diff --git a/tools/ghostlight_prepare_compaction.py b/tools/ghostlight_prepare_compaction.py deleted file mode 100644 index 81317af..0000000 --- a/tools/ghostlight_prepare_compaction.py +++ /dev/null @@ -1,363 +0,0 @@ -from __future__ import annotations - -import argparse -import json -import re -import subprocess -from dataclasses import dataclass -from pathlib import Path -from typing import Any - -from ghostlight_state import extract_active_subgoals, extract_map_field - - -ROOT = Path(__file__).resolve().parents[1] -STATE_DIR = ROOT / "state" -NOTES_DIR = ROOT / "notes" - -MAP_PATH = STATE_DIR / "map.yaml" -SCRATCH_PATH = STATE_DIR / "scratch.md" -BRANCHES_PATH = STATE_DIR / "branches.json" -EVIDENCE_PATH = STATE_DIR / "evidence.jsonl" -CACHE_PATH = STATE_DIR / "ghostlight-state.cultcache.jsonl" -HANDOFF_PATH = NOTES_DIR / "fresh-workspace-handoff.md" -PLAN_PATH = NOTES_DIR / "ghostlight-implementation-plan.md" -SYSTEM_MAP_PATH = NOTES_DIR / "ghostlight-current-system-map.md" -AGENTS_PATH = ROOT / "AGENTS.md" - - -@dataclass -class Finding: - level: str - message: str - - -def read_text(path: Path) -> str: - return path.read_text(encoding="utf-8") - - -def run_git(args: list[str]) -> str: - completed = subprocess.run( - ["git", *args], - cwd=ROOT, - check=True, - capture_output=True, - text=True, - ) - return completed.stdout.strip() - - -def current_scratch_subgoal() -> str | None: - lines = read_text(SCRATCH_PATH).splitlines() - for index, line in enumerate(lines): - if line.strip() != "## Current Subgoal": - continue - for candidate in lines[index + 1 :]: - stripped = candidate.strip() - if stripped: - return stripped - return None - - -def load_evidence() -> list[dict[str, Any]]: - records: list[dict[str, Any]] = [] - for line_number, line in enumerate(read_text(EVIDENCE_PATH).splitlines(), start=1): - if not line.strip(): - continue - try: - record = json.loads(line) - except json.JSONDecodeError as exc: - raise ValueError(f"evidence line {line_number} is invalid JSON: {exc}") from exc - if not isinstance(record, dict): - raise ValueError(f"evidence line {line_number} is not a JSON object") - records.append(record) - return records - - -def load_branches() -> dict[str, Any]: - data = json.loads(read_text(BRANCHES_PATH)) - if not isinstance(data, dict): - raise ValueError("branches.json must be a JSON object") - branches = data.get("branches") - if not isinstance(branches, list): - raise ValueError("branches.json must contain a branches list") - return data - - -def load_cache_envelopes() -> list[dict[str, Any]]: - envelopes: list[dict[str, Any]] = [] - if not CACHE_PATH.exists(): - raise ValueError("CultCache state store is missing") - for line_number, line in enumerate(read_text(CACHE_PATH).splitlines(), start=1): - if not line.strip(): - continue - try: - envelope = json.loads(line) - except json.JSONDecodeError as exc: - raise ValueError(f"CultCache envelope line {line_number} is invalid JSON: {exc}") from exc - for field in ["key", "type", "payload", "stored_at"]: - if field not in envelope: - raise ValueError(f"CultCache envelope line {line_number} is missing {field}") - envelopes.append(envelope) - return envelopes - - -def add_required_file_checks(findings: list[Finding]) -> None: - for path in [ - MAP_PATH, - SCRATCH_PATH, - BRANCHES_PATH, - EVIDENCE_PATH, - CACHE_PATH, - HANDOFF_PATH, - PLAN_PATH, - SYSTEM_MAP_PATH, - AGENTS_PATH, - ]: - if path.exists(): - findings.append(Finding("ok", f"found {path.relative_to(ROOT)}")) - else: - findings.append(Finding("error", f"missing {path.relative_to(ROOT)}")) - - -def add_content_checks(findings: list[Finding]) -> tuple[list[dict[str, Any]], dict[str, Any]]: - evidence: list[dict[str, Any]] = [] - branches: dict[str, Any] = {} - - summary = extract_map_field("summary") - next_action = extract_map_field("next_action") - if summary: - findings.append(Finding("ok", "state/map.yaml has current_status.summary")) - else: - findings.append(Finding("error", "state/map.yaml is missing current_status.summary")) - if next_action: - findings.append(Finding("ok", "state/map.yaml has current_status.next_action")) - else: - findings.append(Finding("error", "state/map.yaml is missing current_status.next_action")) - - subgoals = extract_active_subgoals() - if subgoals: - findings.append(Finding("ok", f"state/map.yaml has {len(subgoals)} active subgoal(s)")) - else: - findings.append(Finding("warn", "state/map.yaml has no active_subgoals entries")) - - scratch_subgoal = current_scratch_subgoal() - if scratch_subgoal == "No active scratch subgoal.": - findings.append(Finding("ok", "state/scratch.md has no stale active scratch subgoal")) - elif scratch_subgoal: - findings.append(Finding("warn", f"state/scratch.md has active scratch subgoal: {scratch_subgoal}")) - else: - findings.append(Finding("warn", "state/scratch.md has no Current Subgoal value")) - - try: - evidence = load_evidence() - findings.append(Finding("ok", f"state/evidence.jsonl parses ({len(evidence)} record(s))")) - except ValueError as exc: - findings.append(Finding("error", str(exc))) - - if EVIDENCE_PATH.exists() and EVIDENCE_PATH.stat().st_size > 25_000: - findings.append(Finding("warn", "state/evidence.jsonl is larger than 25 KB; consider distillation")) - - try: - branches = load_branches() - active = [ - branch - for branch in branches.get("branches", []) - if isinstance(branch, dict) and branch.get("status") == "active" - ] - findings.append(Finding("ok", f"state/branches.json parses ({len(active)} active branch(es))")) - except (json.JSONDecodeError, ValueError) as exc: - findings.append(Finding("error", f"branches.json parse failed: {exc}")) - - try: - envelopes = load_cache_envelopes() - evidence_envelopes = [ - envelope - for envelope in envelopes - if envelope.get("type") == "ghostlight.evidence_record.v0" - ] - branch_envelopes = [ - envelope - for envelope in envelopes - if envelope.get("type") == "ghostlight.branches.v0" - ] - findings.append( - Finding( - "ok", - f"state/ghostlight-state.cultcache.jsonl parses ({len(envelopes)} envelope(s))", - ) - ) - if evidence and len(evidence_envelopes) != len(evidence): - findings.append( - Finding( - "warn", - "CultCache evidence envelope count differs from state/evidence.jsonl export", - ) - ) - if len(branch_envelopes) != 1: - findings.append( - Finding("warn", "CultCache branch global envelope count is not exactly one") - ) - except ValueError as exc: - findings.append(Finding("error", f"CultCache state parse failed: {exc}")) - - return evidence, branches - - -def add_handoff_checks(findings: list[Finding]) -> None: - text = read_text(HANDOFF_PATH) - stale_branch = re.search(r"Current branch before .*ahead \d+", text) - stale_head = re.search(r"Current HEAD before .*\b[0-9a-f]{7,40}\b", text) - if stale_branch or stale_head: - findings.append(Finding("error", "handoff embeds an exact branch or HEAD snapshot; use git commands instead")) - else: - findings.append(Finding("ok", "handoff avoids exact branch or HEAD snapshots")) - - required_phrases = [ - "Do not continue implementation automatically from a rehydrate-only request.", - "Do not trust this file for the exact live HEAD.", - "Immediate Re-entry Instruction", - ] - for phrase in required_phrases: - if phrase in text: - findings.append(Finding("ok", f"handoff contains: {phrase}")) - else: - findings.append(Finding("warn", f"handoff missing: {phrase}")) - - -def add_agents_checks(findings: list[Finding]) -> None: - text = read_text(AGENTS_PATH) - if "ghostlight_prepare_compaction.py" in text: - findings.append(Finding("ok", "AGENTS.md tells agents to use the compaction helper")) - else: - findings.append(Finding("error", "AGENTS.md does not mention tools/ghostlight_prepare_compaction.py")) - if "prepare for imminent compaction" in text.lower(): - findings.append(Finding("ok", "AGENTS.md names the imminent-compaction trigger")) - else: - findings.append(Finding("warn", "AGENTS.md does not name the imminent-compaction trigger phrase")) - - -def add_git_checks(findings: list[Finding]) -> tuple[str, str]: - status = run_git(["status", "--short", "--branch"]) - try: - log = run_git(["log", "--oneline", "-5"]) - except subprocess.CalledProcessError: - log = "(no commits yet)" - dirty_lines = [ - line - for line in status.splitlines()[1:] - if line.strip() - ] - if dirty_lines: - findings.append(Finding("warn", "git worktree has uncommitted changes; commit or explain before compaction")) - else: - findings.append(Finding("ok", "git worktree is clean")) - return status, log - - -def render_report(findings: list[Finding], status: str, log: str, evidence: list[dict[str, Any]]) -> str: - summary = extract_map_field("summary") or "(missing)" - next_action = extract_map_field("next_action") or "(missing)" - subgoals = extract_active_subgoals() - - counts = { - "ok": sum(1 for finding in findings if finding.level == "ok"), - "warn": sum(1 for finding in findings if finding.level == "warn"), - "error": sum(1 for finding in findings if finding.level == "error"), - } - - lines = [ - "Ghostlight pre-compaction persistence check", - f"Workspace: {ROOT}", - f"Findings: {counts['ok']} ok, {counts['warn']} warn, {counts['error']} error", - "", - "Git status:", - status, - "", - "Recent commits:", - log, - "", - f"Summary: {summary}", - f"Next action: {next_action}", - ] - if subgoals: - lines.append("Active subgoals:") - lines.extend(f"- {item}" for item in subgoals) - if evidence: - latest = evidence[-1] - lines.extend( - [ - "", - "Latest distilled evidence:", - f"- {latest.get('ts', '(missing ts)')} {latest.get('type', '(missing type)')}/{latest.get('status', '(missing status)')}: {latest.get('note', '(missing note)')}", - ] - ) - - lines.append("") - lines.append("Findings:") - for finding in findings: - lines.append(f"[{finding.level.upper()}] {finding.message}") - - lines.extend( - [ - "", - "Pre-compaction checklist:", - "- Update state/map.yaml only if current understanding changed.", - "- Refresh notes/fresh-workspace-handoff.md if re-entry instructions changed.", - "- Add distilled evidence only for a belief-changing lesson, verification, rejected path, or scar.", - "- Keep exact branch or HEAD out of handoff prose; git commands own volatile truth.", - "- Commit completed persistence changes, or state why the worktree must stay dirty.", - "- Re-run this helper after edits before yielding to compaction.", - ] - ) - return "\n".join(lines) - - -def build_parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser( - description="Audit Ghostlight persistent state before imminent compaction." - ) - parser.add_argument( - "--strict", - action="store_true", - help="Exit nonzero on warnings as well as errors.", - ) - return parser - - -def main() -> int: - args = build_parser().parse_args() - findings: list[Finding] = [] - evidence: list[dict[str, Any]] = [] - - add_required_file_checks(findings) - try: - evidence, _branches = add_content_checks(findings) - except OSError as exc: - findings.append(Finding("error", f"state content check failed: {exc}")) - try: - add_handoff_checks(findings) - except OSError as exc: - findings.append(Finding("error", f"handoff check failed: {exc}")) - try: - add_agents_checks(findings) - except OSError as exc: - findings.append(Finding("error", f"AGENTS check failed: {exc}")) - try: - status, log = add_git_checks(findings) - except (OSError, subprocess.CalledProcessError) as exc: - findings.append(Finding("error", f"git check failed: {exc}")) - status = "(git status unavailable)" - log = "(git log unavailable)" - - print(render_report(findings, status, log, evidence)) - - has_error = any(finding.level == "error" for finding in findings) - has_warning = any(finding.level == "warn" for finding in findings) - if has_error or (args.strict and has_warning): - return 1 - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/ghostlight_state.py b/tools/ghostlight_state.py deleted file mode 100644 index 75d0410..0000000 --- a/tools/ghostlight_state.py +++ /dev/null @@ -1,244 +0,0 @@ -from __future__ import annotations - -import argparse -import json -from datetime import datetime, timezone -from pathlib import Path -from typing import Any - -from ghostlight_state_store import ( - append_evidence, - load_branches, - migrate_legacy_evidence, - replace_evidence, - save_branches, -) - - -ROOT = Path(__file__).resolve().parents[1] -STATE_DIR = ROOT / "state" -MAP_PATH = STATE_DIR / "map.yaml" -BRANCHES_PATH = STATE_DIR / "branches.json" -EVIDENCE_PATH = STATE_DIR / "evidence.jsonl" -COVERAGE_PATH = STATE_DIR / "corpus-coverage.json" - - -def read_text(path: Path) -> str: - return path.read_text(encoding="utf-8-sig") - - -def write_text(path: Path, content: str) -> None: - path.write_text(content, encoding="utf-8") - - -def utc_stamp() -> str: - return datetime.now(timezone.utc).replace(microsecond=0).isoformat() - - -def extract_map_field(name: str) -> str | None: - """Read one ` name:` field under `current_status`, plain or block scalar.""" - prefix = f" {name}:" - lines = read_text(MAP_PATH).splitlines() - for index, line in enumerate(lines): - if not line.startswith(prefix): - continue - value = line.split(":", 1)[1].strip() - if value not in {">", "|", ">-", "|-"}: - return value - block: list[str] = [] - for continuation in lines[index + 1 :]: - if continuation.strip() and not continuation.startswith(" "): - break - block.append(continuation.strip()) - joiner = "\n" if value.startswith("|") else " " - return joiner.join(part for part in block if part).strip() or None - return None - - -def extract_active_subgoals() -> list[str]: - lines = read_text(MAP_PATH).splitlines() - results: list[str] = [] - in_section = False - for line in lines: - if not in_section: - if line.strip() == "active_subgoals:": - in_section = True - continue - if line.startswith(" - "): - results.append(line[4:].strip()) - continue - if line and not line.startswith(" "): - break - return results - - -def load_coverage_summary() -> str | None: - if not COVERAGE_PATH.exists(): - return None - data = json.loads(read_text(COVERAGE_PATH)) - entries = data.get("entries", []) - accepted = [ - entry - for entry in entries - if entry.get("status") in {"accepted", "accepted_as_draft"} - ] - target = data.get("coverage_targets", {}).get("practical_first_broad_target", {}) - minimum = target.get("minimum") - maximum = target.get("maximum") - if isinstance(minimum, int) and isinstance(maximum, int): - return f"{len(accepted)} / {minimum}-{maximum} accepted fixtures" - return f"{len(accepted)} accepted fixtures" - - -def cmd_status(_: argparse.Namespace) -> int: - branches = load_branches().get("branches", []) - active = [branch for branch in branches if branch.get("status") == "active"] - summary = extract_map_field("summary") or "(missing)" - next_action = extract_map_field("next_action") or "(missing)" - subgoals = extract_active_subgoals() - - print(f"Workspace: {ROOT}") - print(f"Summary: {summary}") - print(f"Next action: {next_action}") - print(f"Active branches: {len(active)} / {len(branches)}") - coverage = load_coverage_summary() - if coverage: - print(f"Coverage: {coverage}") - if subgoals: - print("Active subgoals:") - for item in subgoals: - print(f"- {item}") - return 0 - - -def cmd_add_evidence(args: argparse.Namespace) -> int: - record: dict[str, Any] = { - "ts": utc_stamp(), - "type": args.type, - "status": args.status, - "note": args.note, - } - if args.branch: - record["branch"] = args.branch - append_evidence(record) - print("Appended evidence record.") - return 0 - - -def cmd_compact_evidence(args: argparse.Namespace) -> int: - records: list[dict[str, Any]] = [] - for number, line in enumerate(read_text(Path(args.replacement)).splitlines(), 1): - if not line.strip(): - continue - record = json.loads(line) - missing = {"ts", "type", "status", "note"} - set(record) - if not isinstance(record, dict) or missing: - raise SystemExit(f"replacement line {number} lacks {sorted(missing)}") - records.append(record) - if not records: - raise SystemExit("refusing to compact the ledger to nothing") - archived, kept = replace_evidence(records) - print(f"Archived {archived} record(s) to state/evidence.archive.jsonl; ledger now holds {kept}.") - return 0 - - -def cmd_migrate_evidence(_: argparse.Namespace) -> int: - imported = migrate_legacy_evidence() - print(f"Imported {imported} legacy evidence record(s) into CultCache.") - return 0 - - -def cmd_add_branch(args: argparse.Namespace) -> int: - data = load_branches() - branches = data.setdefault("branches", []) - if any(branch.get("id") == args.id for branch in branches): - raise SystemExit(f"Branch '{args.id}' already exists.") - branches.append( - { - "id": args.id, - "hypothesis": args.hypothesis, - "status": "active", - "artifacts": args.artifact or [], - "notes": args.note or "", - } - ) - save_branches(data) - print(f"Added branch '{args.id}'.") - return 0 - - -def cmd_close_branch(args: argparse.Namespace) -> int: - data = load_branches() - for branch in data.get("branches", []): - if branch.get("id") != args.id: - continue - branch["status"] = args.status - if args.note: - branch["notes"] = args.note - save_branches(data) - print(f"Updated branch '{args.id}' to status '{args.status}'.") - return 0 - raise SystemExit(f"Branch '{args.id}' was not found.") - - -def build_parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser( - description="Inspect and update Ghostlight state files." - ) - subparsers = parser.add_subparsers(dest="command", required=True) - - status_parser = subparsers.add_parser("status", help="Show a compact state summary.") - status_parser.set_defaults(func=cmd_status) - - evidence_parser = subparsers.add_parser( - "add-evidence", help="Append one distilled JSONL evidence record." - ) - evidence_parser.add_argument("--type", required=True) - evidence_parser.add_argument("--status", required=True) - evidence_parser.add_argument("--note", required=True) - evidence_parser.add_argument("--branch") - evidence_parser.set_defaults(func=cmd_add_evidence) - - compact_parser = subparsers.add_parser( - "compact-evidence", - help="Replace the evidence document with a distilled JSONL file; every current record is archived first.", - ) - compact_parser.add_argument("--replacement", required=True) - compact_parser.set_defaults(func=cmd_compact_evidence) - - migrate_evidence_parser = subparsers.add_parser( - "migrate-evidence", - help="Import legacy JSONL evidence missing from the CultCache authority.", - ) - migrate_evidence_parser.set_defaults(func=cmd_migrate_evidence) - - add_branch_parser = subparsers.add_parser( - "add-branch", help="Create a new active branch entry." - ) - add_branch_parser.add_argument("--id", required=True) - add_branch_parser.add_argument("--hypothesis", required=True) - add_branch_parser.add_argument("--artifact", action="append") - add_branch_parser.add_argument("--note") - add_branch_parser.set_defaults(func=cmd_add_branch) - - close_branch_parser = subparsers.add_parser( - "close-branch", help="Close an existing branch." - ) - close_branch_parser.add_argument("--id", required=True) - close_branch_parser.add_argument( - "--status", required=True, choices=["accepted", "rejected", "archived"] - ) - close_branch_parser.add_argument("--note") - close_branch_parser.set_defaults(func=cmd_close_branch) - - return parser - - -def main() -> int: - parser = build_parser() - args = parser.parse_args() - return args.func(args) - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/ghostlight_state_store.py b/tools/ghostlight_state_store.py deleted file mode 100644 index fc36f92..0000000 --- a/tools/ghostlight_state_store.py +++ /dev/null @@ -1,168 +0,0 @@ -from __future__ import annotations - -import hashlib -import json -from pathlib import Path -from typing import Any - -try: - from cultcache_py import CultCache, JsonLinesBackingStore, define_document_type -except ModuleNotFoundError as error: - if error.name != "cultcache_py": - raise - raise SystemExit( - "Ghostlight state tooling needs cultcache-py. Install it with " - "`npm run state:bootstrap`, or with this interpreter directly: " - "`python -m pip install -r tools/requirements.txt`." - ) from error - - -ROOT = Path(__file__).resolve().parents[1] -STATE_DIR = ROOT / "state" -CACHE_PATH = STATE_DIR / "ghostlight-state.cultcache.jsonl" -BRANCHES_PATH = STATE_DIR / "branches.json" -EVIDENCE_PATH = STATE_DIR / "evidence.jsonl" -ARCHIVE_PATH = STATE_DIR / "evidence.archive.jsonl" - - -BRANCHES_DOC = define_document_type( - "ghostlight.branches.v0", - global_document=True, -) - -EVIDENCE_DOC = define_document_type( - "ghostlight.evidence_record.v0", - indexes={ - "type": "type", - "status": "status", - "branch": "branch", - }, -) - - -def _read_json(path: Path) -> Any: - return json.loads(path.read_text(encoding="utf-8-sig")) - - -def _write_json(path: Path, value: Any) -> None: - path.write_text(json.dumps(value, indent=2, ensure_ascii=True) + "\n", encoding="utf-8") - - -def _read_jsonl(path: Path) -> list[dict[str, Any]]: - if not path.exists(): - return [] - records: list[dict[str, Any]] = [] - for line in path.read_text(encoding="utf-8-sig").splitlines(): - if line.strip(): - records.append(json.loads(line)) - return records - - -def _write_jsonl(path: Path, records: list[dict[str, Any]]) -> None: - content = "".join(json.dumps(record, ensure_ascii=True) + "\n" for record in records) - path.write_text(content, encoding="utf-8") - - -def _evidence_key(record: dict[str, Any], index: int = 0) -> str: - payload = json.dumps(record, ensure_ascii=True, sort_keys=True) - digest = hashlib.sha1(payload.encode("utf-8")).hexdigest()[:12] - ts = str(record.get("ts", "unstamped")).replace(":", "").replace("+", "Z") - return f"{ts}-{index:04d}-{digest}" - - -def open_state_cache() -> CultCache: - cache = ( - CultCache.builder() - .register_document_type(BRANCHES_DOC) - .register_document_type(EVIDENCE_DOC) - .add_generic_store(JsonLinesBackingStore(CACHE_PATH)) - .build() - ) - cache.pull_all_backing_stores() - _bootstrap_if_needed(cache) - return cache - - -def load_branches() -> dict[str, Any]: - cache = open_state_cache() - branches = cache.get_global(BRANCHES_DOC) - if branches is None: - return {"branches": []} - return branches - - -def save_branches(data: dict[str, Any]) -> None: - cache = open_state_cache() - cache.put_global(BRANCHES_DOC, data) - _write_json(BRANCHES_PATH, data) - - -def append_evidence(record: dict[str, Any]) -> None: - cache = open_state_cache() - existing = cache.get_all(EVIDENCE_DOC) - key = _evidence_key(record, len(existing)) - cache.put(EVIDENCE_DOC, key, record) - _export_evidence(cache) - - -def replace_evidence(records: list[dict[str, Any]]) -> tuple[int, int]: - """Replace the whole evidence document with distilled records. - - Every record currently in the store is appended verbatim to - ``state/evidence.archive.jsonl`` before deletion, so the archive stays - the complete history and the export carries only what still steers. - Returns (archived, kept). - """ - cache = open_state_cache() - snapshot = cache.snapshot().get(EVIDENCE_DOC.type, {}) - archived = sorted(snapshot.values(), key=lambda record: record.get("ts", "")) - with ARCHIVE_PATH.open("a", encoding="utf-8") as archive: - for record in archived: - archive.write(json.dumps(record, ensure_ascii=True) + "\n") - for key in list(snapshot): - cache.delete(EVIDENCE_DOC, key) - for index, record in enumerate(records): - cache.put(EVIDENCE_DOC, _evidence_key(record, index), record) - _export_evidence(cache) - return len(archived), len(records) - - -def migrate_legacy_evidence() -> int: - """Import legacy JSONL records that predate the CultCache authority cut.""" - cache = open_state_cache() - existing = cache.get_all(EVIDENCE_DOC) - existing_payloads = { - json.dumps(record, ensure_ascii=True, sort_keys=True) for record in existing - } - imported = 0 - for record in _read_jsonl(EVIDENCE_PATH): - payload = json.dumps(record, ensure_ascii=True, sort_keys=True) - if payload in existing_payloads: - continue - key = _evidence_key(record, len(existing) + imported) - cache.put(EVIDENCE_DOC, key, record) - existing_payloads.add(payload) - imported += 1 - _export_evidence(cache) - return imported - - -def _bootstrap_if_needed(cache: CultCache) -> None: - changed = False - if cache.get_global(BRANCHES_DOC) is None and BRANCHES_PATH.exists(): - cache.put_global(BRANCHES_DOC, _read_json(BRANCHES_PATH)) - changed = True - if not cache.get_all(EVIDENCE_DOC): - for index, record in enumerate(_read_jsonl(EVIDENCE_PATH)): - cache.put(EVIDENCE_DOC, _evidence_key(record, index), record) - changed = True - if changed: - _export_evidence(cache) - branches = cache.get_global(BRANCHES_DOC) - if branches is not None: - _write_json(BRANCHES_PATH, branches) - - -def _export_evidence(cache: CultCache) -> None: - records = sorted(cache.get_all(EVIDENCE_DOC), key=lambda record: record.get("ts", "")) - _write_jsonl(EVIDENCE_PATH, records) diff --git a/tools/requirements.txt b/tools/requirements.txt deleted file mode 100644 index 25fb93a..0000000 --- a/tools/requirements.txt +++ /dev/null @@ -1 +0,0 @@ -cultcache-py==0.2.0 diff --git a/tools/typeset_newspaper.py b/tools/typeset_newspaper.py deleted file mode 100644 index e733ecf..0000000 --- a/tools/typeset_newspaper.py +++ /dev/null @@ -1,231 +0,0 @@ -#!/usr/bin/env python3 -"""Emit a TeX newspaper with independent house-style and issue-flow seeds.""" -from __future__ import annotations - -import argparse, hashlib, html, os, random, re, shutil, subprocess, tempfile -from dataclasses import asdict, dataclass -from pathlib import Path - -@dataclass(frozen=True) -class Article: - section: str | None; headline: str; deck: str; author: str; paragraphs: tuple[str, ...] - -@dataclass(frozen=True) -class Edition: - masthead: str; edition: str; articles: tuple[Article, ...] - -@dataclass(frozen=True) -class Style: - seed: int; width: float; height: float; margin: float; body: float; leading: float - gutter: float; rule: float; masthead: int; lead: int; display: str; text: str - paper: str; ink: str; fleuron: str; rules: str - -@dataclass(frozen=True) -class Flow: - seed: int; template: str; inside_layout: str; page_one_secondary: int - lead_cut: float; inside_cut: float - -def plain(s: str) -> str: - s=s.strip() - if s.startswith("**") and s.endswith("**"): s=s[2:-2] - elif s[:1] in "*_" and s[-1:]==s[:1]: s=s[1:-1] - return html.unescape(s) - -def parse(path: Path) -> Edition: - lines=path.read_text(encoding="utf-8").splitlines(); mast=""; ed=""; sec=None; out=[]; i=0 - while i < len(lines): - s=lines[i].strip() - if s.startswith("# ") and not mast: mast=plain(s[2:]) - elif not ed and s.startswith("*") and s.endswith("*"): ed=plain(s) - elif s.startswith("### "): sec=plain(s[4:]) - elif s.startswith("## "): - head=plain(s[3:]); i+=1 - while not lines[i].strip(): i+=1 - deck=plain(lines[i]); i+=1 - while not lines[i].strip(): i+=1 - author=plain(lines[i]); i+=1; paras=[]; acc=[] - while i < len(lines): - t=lines[i].strip() - if t=="---" or t.startswith(("## ","### ")): - if acc: paras.append(" ".join(acc)); acc=[] - break - if t: acc.append(t) - elif acc: paras.append(" ".join(acc)); acc=[] - i+=1 - if acc: paras.append(" ".join(acc)) - out.append(Article(sec,head,deck,author,tuple(paras))); sec=None; continue - i+=1 - if not mast or not ed or not out: raise ValueError("source lacks masthead, edition, or articles") - return Edition(mast,ed,tuple(out)) - -def choose_style(seed: int) -> Style: - r=random.Random(seed) - return Style(seed,r.choice((9.6,9.8,10.0)),r.choice((10.7,10.9,11.1)),r.choice((.34,.38,.42)), - r.choice((7.7,7.9,8.1)),r.choice((1.03,1.05,1.07)),r.choice((8.,9.5,11.)), - r.choice((0.,.24,.36)),r.choice((36,39,42)),r.choice((25,27,29)), - r.choice(("Georgia","Times New Roman")),"Times New Roman", - r.choice(("F2E5C7","F5E9CE","EFE1C2")),r.choice(("17120D","21170F","1A1510")), - r.choice(("diamond","cross","leaf")),r.choice(("double","heavy-thin","triple"))) - -def choose_flow(seed: int, e: Edition, cuts: dict[int, Path]) -> Flow: - r=random.Random(seed); remaining=list(range(1,len(e.articles))) - without_cuts=[index for index in remaining if index not in cuts] - secondary=r.choice(without_cuts or remaining) if remaining else -1 - template=r.choice(("display-plate","display-band")) - lead_cut=r.choice((.90,.97)) if template=="display-plate" else r.choice((.78,.82,.86)) - inside_layout=r.choice(("cut-first","cut-midstory")) - inside_cut=r.choice((.62,.70,.78)) if inside_layout=="cut-first" else r.choice((.44,.50,.56)) - return Flow(seed,template,inside_layout,secondary,lead_cut,inside_cut) - -def esc(s: str) -> str: - m={"\\":r"\textbackslash{}","&":r"\&","%":r"\%","$":r"\$","#":r"\#","_":r"\_","{":r"\{","}":r"\}","~":r"\textasciitilde{}","^":r"\textasciicircum{}"} - return "".join(m.get(c,c) for c in html.unescape(s)) - -def inline(s: str) -> str: - out=[] - for p in re.split(r"(\*\*.*?\*\*|\*.*?\*)",html.unescape(s)): - if p.startswith("**") and p.endswith("**"): out.append(r"\textbf{"+esc(p[2:-2])+"}") - elif p.startswith("*") and p.endswith("*"): out.append(r"\textit{"+esc(p[1:-1])+"}") - else: out.append(esc(p)) - return "".join(out) - -def story_body(a: Article) -> str: - return "\n\n".join(inline(p) for p in a.paragraphs) - -def story_header(a: Article) -> str: - sec=(r"{\sectionface\fontsize{7.2}{8}\selectfont\MakeUppercase{"+esc(a.section)+r"}}\par\smallskip " if a.section else "") - head=r"\storyhead{"+esc(a.headline)+"}\n" - return (r"\Needspace{18\baselineskip}\noindent\begin{minipage}{\linewidth}\hrule height .45pt\smallskip "+sec+head+ - r"\deck{"+esc(a.deck)+"}\n"+r"\byline{"+esc(a.author)+r"}\end{minipage}\par\smallskip") - -def article(a: Article) -> str: - return story_header(a)+story_body(a) - -def rules(kind: str) -> str: - return {"double":r"\hrule height 1.1pt\vspace{2pt}\hrule height .35pt","heavy-thin":r"\hrule height 1.7pt\vspace{1pt}\hrule height .25pt","triple":r"\hrule height .3pt\vspace{1pt}\hrule height 1.1pt\vspace{1pt}\hrule height .3pt"}[kind] - -def ornament(kind: str) -> str: - center={"diamond":r"\rotatebox{45}{\rule{5pt}{5pt}}","cross":r"\raisebox{-1pt}{\rule{1pt}{7pt}}\hspace{-4pt}\rule{7pt}{1pt}","leaf":r"\rotatebox{35}{\rule{3pt}{7pt}}\hspace{-1pt}\rotatebox{-35}{\rule{3pt}{7pt}}"}[kind] - return r"\rule{18pt}{.35pt}\hspace{5pt}"+center+r"\hspace{5pt}\rule{18pt}{.35pt}" - -def tex_path(p: Path) -> str: return p.resolve().as_posix() - -def press_cut(path: Path, width: float) -> str: - return (r"\begin{center}\begin{tikzpicture}\begin{scope}[blend mode=multiply]" - r"\node[inner sep=0] {\includegraphics[width="+f"{width:.2f}"+r"\linewidth]{"+tex_path(path)+r"}};" - r"\end{scope}\end{tikzpicture}\end{center}") - -def build(e: Edition, s: Style, f: Flow, cuts: dict[int, Path], source: Path) -> str: - lead=e.articles[0] - remaining=list(enumerate(e.articles[1:],1)) - rail=next((pair for pair in remaining if pair[0]==f.page_one_secondary),None) - paired=[pair for pair in remaining if pair != rail] - leadcut=press_cut(cuts[0],f.lead_cut) if 0 in cuts else "" - rail_text=(r"\par\medskip "+article(rail[1])) if rail else "" - pre=rf"""\documentclass{{article}} -\usepackage[paperwidth={s.width}in,paperheight={s.height}in,margin={s.margin}in]{{geometry}} -\usepackage{{fontspec,graphicx,xcolor,microtype,multicol,ragged2e,fancyhdr,tikz,needspace}} -\setmainfont{{{s.text}}}\newfontfamily\displayface{{{s.display}}}\newfontfamily\sectionface{{{s.display}}} -\definecolor{{paper}}{{HTML}}{{{s.paper}}}\definecolor{{ink}}{{HTML}}{{{s.ink}}}\pagecolor{{paper}}\color{{ink}} -\setlength{{\columnsep}}{{{s.gutter}pt}}\setlength{{\columnseprule}}{{{s.rule}pt}}\setlength{{\parindent}}{{1em}}\setlength{{\parskip}}{{0pt}}\setlength{{\emergencystretch}}{{1em}} -\pagestyle{{fancy}}\fancyhf{{}}\renewcommand{{\headrulewidth}}{{0pt}}\fancyfoot[C]{{\displayface\fontsize{{6.5}}{{7}}\selectfont {esc(e.masthead.upper())} · HOUSE {s.seed} · FLOW {f.seed} · \thepage}} -\newcommand{{\pressrules}}{{{rules(s.rules)}}}\newcommand{{\fleuron}}{{{ornament(s.fleuron)}}} -\newcommand{{\masthead}}[1]{{{{\displayface\bfseries\fontsize{{{s.masthead}}}{{{s.masthead+2}}}\selectfont\centering\MakeUppercase{{#1}}\par}}}} -\newcommand{{\leadhead}}[1]{{{{\displayface\bfseries\fontsize{{{s.lead}}}{{{s.lead+1.5}}}\selectfont\centering #1\par}}}} -\newcommand{{\storyhead}}[1]{{{{\displayface\bfseries\fontsize{{14}}{{15}}\selectfont\RaggedRight #1\par\smallskip}}}} -\newcommand{{\deck}}[1]{{{{\displayface\itshape\fontsize{{8}}{{9.2}}\selectfont\RaggedRight #1\par\smallskip}}}} -\newcommand{{\byline}}[1]{{{{\displayface\bfseries\fontsize{{6.8}}{{7.5}}\selectfont\MakeUppercase{{By #1}}\par\smallskip}}}} -\AtBeginDocument{{\fontsize{{{s.body}}}{{{s.body*s.leading:.2f}}}\selectfont\justifying}} -\begin{{document}}\thispagestyle{{fancy}} -{{\displayface\fontsize{{7}}{{8}}\selectfont {esc(e.edition.upper())}\hfill SOURCE: {esc(source.name)}\par}}\smallskip\pressrules\smallskip -\masthead{{{esc(e.masthead)}}}\smallskip\pressrules\medskip -\leadhead{{{esc(lead.headline)}}}\smallskip -{{\displayface\itshape\fontsize{{9.2}}{{10.5}}\selectfont\centering {esc(lead.deck)}\par}} -{{\displayface\bfseries\fontsize{{7}}{{8}}\selectfont\centering BY {esc(lead.author.upper())}\par}}\smallskip -{leadcut}\smallskip -\begin{{multicols}}{{4}}{story_body(lead)} -{rail_text} -\end{{multicols}} -\vfill\begin{{center}}\fleuron\end{{center}} -""" - pages=[pre]; page=2 - while paired: - group,paired=paired[:2],paired[2:] - first_index,first=group[0] - first_cut=press_cut(cuts[first_index],f.inside_cut) if first_index in cuts else "" - first_header=story_header(first) - flowing=story_body(first) - for _,a in group[1:]: flowing+=r"\par\medskip "+article(a) - if f.inside_layout=="cut-midstory" and first_cut: - opening=inline(first.paragraphs[0]); remainder="\n\n".join(inline(p) for p in first.paragraphs[1:]) - for _,a in group[1:]: remainder+=r"\par\medskip "+article(a) - inside=rf"""{first_header}\begin{{multicols}}{{4}}{opening}\end{{multicols}}{first_cut}\begin{{multicols}}{{4}}{remainder}\end{{multicols}}""" - else: - inside=rf"""{first_header}{first_cut}\begin{{multicols}}{{4}}{flowing}\end{{multicols}}""" - pages.append(rf"""\clearpage\thispagestyle{{fancy}}{{\displayface\fontsize{{7}}{{8}}\selectfont {esc(e.edition.upper())}\hfill PAGE {page}\par}}\smallskip\pressrules\smallskip -{{\displayface\bfseries\fontsize{{18}}{{19}}\selectfont\centering {esc(e.masthead)}\par}}\smallskip\pressrules\medskip -{inside} -\vfill\begin{{center}}\fleuron\end{{center}}"""); page+=1 - return "\n".join(pages)+"\n\\end{document}\n" - -def digest(path: Path) -> str: - return hashlib.sha256(path.read_bytes()).hexdigest() - -def verify_copy(e: Edition, rendered: str) -> None: - haystack=rendered.casefold(); missing=[] - for index,a in enumerate(e.articles): - fields=[("headline",esc(a.headline)),("deck",esc(a.deck)),("author",esc(a.author))] - fields += [(f"paragraph-{n}",inline(p)) for n,p in enumerate(a.paragraphs,1)] - missing += [(index,label) for label,value in fields if value.casefold() not in haystack] - if missing: raise ValueError(f"press projection omitted frozen copy: {missing}") - -def manifest(path: Path, src: Path, out: Path, tex: Path, cuts: dict[int, Path], style: Style, flow: Flow, engine: Path | None): - tool=Path(__file__).resolve() - rows=['schema = "ghostlight.seeded_tex_press.v2"',f'source = "{src.resolve().as_posix()}"',f'source_sha256 = "{digest(src)}"',f'output = "{out.resolve().as_posix()}"',f'tex = "{tex.resolve().as_posix()}"',f'tex_sha256 = "{digest(tex)}"',f'tool = "{tool.as_posix()}"',f'tool_sha256 = "{digest(tool)}"',f"style_seed = {style.seed}",f"flow_seed = {flow.seed}"] - if engine: - rows += [f'engine = "{engine.resolve().as_posix()}"',f'engine_sha256 = "{digest(engine)}"'] - if out.is_file(): rows.append(f'output_sha256 = "{digest(out)}"') - rows += ["","[style]"] - for k,v in asdict(style).items(): - if k!="seed": rows.append(f'{k} = "{v}"' if isinstance(v,str) else f"{k} = {v}") - rows += ["","[flow]"] - for k,v in asdict(flow).items(): - if k!="seed": rows.append(f'{k} = "{v}"' if isinstance(v,str) else f"{k} = {v}") - rows += ["","[[woodcuts]]"] if cuts else [] - for position,(article_index,c) in enumerate(sorted(cuts.items())): - if position: rows.append("[[woodcuts]]") - rows += [f'article_index = {article_index}',f'path = "{c.resolve().as_posix()}"',f'sha256 = "{digest(c)}"'] - path.parent.mkdir(parents=True,exist_ok=True); path.write_text("\n".join(rows)+"\n",encoding="utf-8") - -def compile(engine: Path, tex: Path, out: Path): - out.parent.mkdir(parents=True,exist_ok=True) - with tempfile.TemporaryDirectory(prefix="ghostlight-tex-") as td: - env=os.environ.copy(); env["SOURCE_DATE_EPOCH"]="0"; env["FORCE_SOURCE_DATE"]="1" - p=subprocess.run([str(engine),"-interaction=nonstopmode","-halt-on-error",f"-output-directory={td}",str(tex.resolve())],capture_output=True,text=True,env=env) - built=Path(td)/(tex.stem+".pdf") - if p.returncode or not built.exists(): raise RuntimeError((p.stdout+p.stderr)[-6000:]) - shutil.copy2(built,out) - -def main(): - ap=argparse.ArgumentParser(description=__doc__); ap.add_argument("source",type=Path); ap.add_argument("output",type=Path); ap.add_argument("--style-seed",type=int,required=True); ap.add_argument("--flow-seed",type=int,required=True); ap.add_argument("--woodcut",action="append",default=[],metavar="ARTICLE_INDEX=PATH"); ap.add_argument("--tex-output",type=Path); ap.add_argument("--manifest",type=Path); ap.add_argument("--engine",type=Path); ap.add_argument("--no-compile",action="store_true"); a=ap.parse_args() - src=a.source.resolve(); out=a.output.resolve(); cuts={} - for spec in a.woodcut: - try: raw_index,raw_path=spec.split("=",1); article_index=int(raw_index) - except ValueError as exc: raise ValueError("--woodcut requires ARTICLE_INDEX=PATH") from exc - if article_index in cuts: raise ValueError(f"duplicate woodcut for article {article_index}") - cuts[article_index]=Path(raw_path).resolve() - for p in [src,*cuts.values()]: - if not p.is_file(): raise FileNotFoundError(p) - tx=(a.tex_output or Path("output/tex")/(out.stem+".tex")).resolve(); mf=(a.manifest or tx.with_suffix(".manifest.toml")).resolve(); ed=parse(src); st=choose_style(a.style_seed); fl=choose_flow(a.flow_seed,ed,cuts) - if any(index < 0 or index >= len(ed.articles) for index in cuts): raise ValueError("woodcut article index is outside the edition") - rendered=build(ed,st,fl,cuts,src); verify_copy(ed,rendered) - tx.parent.mkdir(parents=True,exist_ok=True); tx.write_text(rendered,encoding="utf-8") - eng=None - if not a.no_compile: - eng=a.engine or Path(shutil.which("lualatex") or "") - if not eng.is_file(): raise FileNotFoundError("LuaLaTeX not found; pass --engine") - compile(eng,tx,out) - manifest(mf,src,out,tx,cuts,st,fl,eng) - print(f"typeset={out} tex={tx} manifest={mf} style_seed={st.seed} flow_seed={fl.seed} articles={len(ed.articles)} pages={1+(max(0,len(ed.articles)-2)+1)//2}") - -if __name__=="__main__": main() diff --git a/tools/validate_agent_state.py b/tools/validate_agent_state.py deleted file mode 100644 index 4fe0c61..0000000 --- a/tools/validate_agent_state.py +++ /dev/null @@ -1,255 +0,0 @@ -"""Validate Ghostlight agent-state examples. - -This is not a full JSON Schema implementation. It is a focused smoke validator -for the invariants the first Ghostlight schema must not violate. -""" - -from __future__ import annotations - -import argparse -import json -from pathlib import Path -from typing import Any - - -ROOT = Path(__file__).resolve().parents[1] -REQUIRED_FIELDS_PATH = ROOT / "schemas" / "agent-state.required-fields.json" -DEFAULT_EXAMPLES = sorted((ROOT / "examples").glob("agent-state*.json")) - - -class ValidationError(Exception): - pass - - -def load_json(path: Path) -> Any: - with path.open("r", encoding="utf-8") as handle: - return json.load(handle) - - -def require(condition: bool, message: str) -> None: - if not condition: - raise ValidationError(message) - - -def require_keys(obj: dict[str, Any], keys: list[str], path: str) -> None: - missing = [key for key in keys if key not in obj] - require(not missing, f"{path} missing required keys: {', '.join(missing)}") - - -def require_0_1(value: Any, path: str) -> None: - require(isinstance(value, (int, float)), f"{path} must be numeric") - require(0 <= value <= 1, f"{path} must be between 0 and 1") - - -def validate_state_variable(obj: Any, path: str) -> None: - require(isinstance(obj, dict), f"{path} must be an object") - require_keys(obj, ["mean", "plasticity", "current_activation"], path) - require("certainty" not in obj, f"{path}.certainty belongs in perceived/inferred state, not canonical state") - for key in ["mean", "plasticity", "current_activation"]: - require_0_1(obj[key], f"{path}.{key}") - - -def validate_inferred_state_variable(obj: Any, path: str) -> None: - require(isinstance(obj, dict), f"{path} must be an object") - require_keys( - obj, - ["observed_activation", "attributed_disposition", "confidence"], - path, - ) - require("mean" not in obj, f"{path}.mean belongs in canonical state, not perceived state") - require("plasticity" not in obj, f"{path}.plasticity belongs in canonical state, not perceived state") - require("current_activation" not in obj, f"{path}.current_activation should be observed_activation in perceived state") - require("certainty" not in obj, f"{path}.certainty should be named confidence in perceived/inferred state") - require("correction_resistance" not in obj, f"{path}.correction_resistance should be represented through confidence drivers") - for key in ["observed_activation", "attributed_disposition", "confidence"]: - require_0_1(obj[key], f"{path}.{key}") - - -def validate_variable_map( - obj: Any, - required_names: list[str] | None, - path: str, -) -> None: - require(isinstance(obj, dict), f"{path} must be an object") - if required_names is not None: - missing = [name for name in required_names if name not in obj] - require(not missing, f"{path} missing variables: {', '.join(missing)}") - for name, value in obj.items(): - validate_state_variable(value, f"{path}.{name}") - - -def validate_inferred_variable_map(obj: Any, path: str) -> None: - require(isinstance(obj, dict), f"{path} must be an object") - for name, value in obj.items(): - validate_inferred_state_variable(value, f"{path}.{name}") - - -def validate_agent(agent: dict[str, Any], required: dict[str, list[str]]) -> None: - agent_id = agent.get("agent_id", "") - path = f"agents[{agent_id}]" - require_keys( - agent, - ["agent_id", "identity", "canonical_state", "goals", "memories", "perceived_state_overlays"], - path, - ) - canonical = agent["canonical_state"] - require_keys( - canonical, - [ - "underlying_organization", - "stable_dispositions", - "behavioral_dimensions", - "presentation_strategy", - "voice_style", - "situational_state", - "values", - ], - f"{path}.canonical_state", - ) - for group in [ - "underlying_organization", - "stable_dispositions", - "behavioral_dimensions", - "presentation_strategy", - "voice_style", - "situational_state", - ]: - validate_variable_map(canonical[group], required[group], f"{path}.canonical_state.{group}") - - for index, value in enumerate(canonical["values"]): - require_keys(value, ["value_id", "label", "priority", "unforgivable_if_betrayed"], f"{path}.values[{index}]") - require_0_1(value["priority"], f"{path}.values[{index}].priority") - - for index, goal in enumerate(agent["goals"]): - require_keys(goal, ["goal_id", "description", "scope", "priority", "emotional_stake", "status"], f"{path}.goals[{index}]") - require_0_1(goal["priority"], f"{path}.goals[{index}].priority") - - memories = agent["memories"] - require_keys(memories, ["episodic", "semantic", "relationship_summaries"], f"{path}.memories") - for group_name in ["episodic", "semantic", "relationship_summaries"]: - for index, memory in enumerate(memories[group_name]): - memory_path = f"{path}.memories.{group_name}[{index}]" - require_keys(memory, ["memory_id", "summary", "salience", "confidence"], memory_path) - require_0_1(memory["salience"], f"{memory_path}.salience") - require_0_1(memory["confidence"], f"{memory_path}.confidence") - - for index, overlay in enumerate(agent["perceived_state_overlays"]): - overlay_path = f"{path}.perceived_state_overlays[{index}]" - require_keys( - overlay, - ["observer_agent_id", "target_agent_id", "perceived_dimensions", "beliefs", "distortions"], - overlay_path, - ) - validate_inferred_variable_map(overlay["perceived_dimensions"], f"{overlay_path}.perceived_dimensions") - for belief_index, belief in enumerate(overlay["beliefs"]): - belief_path = f"{overlay_path}.beliefs[{belief_index}]" - require_keys(belief, ["belief_id", "claim", "confidence"], belief_path) - require_0_1(belief["confidence"], f"{belief_path}.confidence") - if "emotional_charge" in belief: - require_0_1(belief["emotional_charge"], f"{belief_path}.emotional_charge") - - -def validate_document(document: dict[str, Any], required: dict[str, list[str]], source: Path) -> None: - require(document.get("schema_version") == "ghostlight.agent_state.v0", f"{source} has wrong schema_version") - require_keys(document, ["world", "agents", "relationships", "events", "scenes"], str(source)) - - agent_ids = [agent["agent_id"] for agent in document["agents"]] - require(len(agent_ids) == len(set(agent_ids)), f"{source} has duplicate agent_id values") - agent_id_set = set(agent_ids) - - goal_ids: set[str] = set() - memory_ids: set[str] = set() - for agent in document["agents"]: - validate_agent(agent, required) - goal_ids.update(goal["goal_id"] for goal in agent["goals"]) - for memories in agent["memories"].values(): - memory_ids.update(memory["memory_id"] for memory in memories) - - event_ids = {event["event_id"] for event in document["events"]} - - relationship_pairs: set[tuple[str, str]] = set() - for index, relationship in enumerate(document["relationships"]): - path = f"relationships[{index}]" - require_keys(relationship, ["relationship_id", "source_id", "target_id", "stance", "summary"], path) - require(relationship["source_id"] in agent_id_set, f"{path}.source_id references unknown agent") - require(relationship["target_id"] in agent_id_set, f"{path}.target_id references unknown agent") - relationship_pairs.add((relationship["source_id"], relationship["target_id"])) - validate_variable_map(relationship["stance"], required["relationship_stance"], f"{path}.stance") - for event_id in relationship.get("unresolved_incident_ids", []): - require(event_id in event_ids, f"{path}.unresolved_incident_ids references unknown event: {event_id}") - - for source_id, target_id in relationship_pairs: - require((target_id, source_id) in relationship_pairs, f"relationships missing reciprocal edge: {target_id} -> {source_id}") - - for index, event in enumerate(document["events"]): - path = f"events[{index}]" - require_keys(event, ["event_id", "kind", "summary", "participants", "pressure_tags"], path) - for participant_id in event["participants"]: - require(participant_id in agent_id_set, f"{path}.participants references unknown agent: {participant_id}") - for turn_index, turn in enumerate(event.get("observed_exchange", [])): - turn_path = f"{path}.observed_exchange[{turn_index}]" - require_keys(turn, ["speaker_id", "utterance_summary", "dialogue_function"], turn_path) - require(turn["speaker_id"] in agent_id_set, f"{turn_path}.speaker_id references unknown agent") - for interpretation_index, interpretation in enumerate(event.get("private_interpretations", [])): - interpretation_path = f"{path}.private_interpretations[{interpretation_index}]" - require_keys(interpretation, ["agent_id", "interpretation", "confidence"], interpretation_path) - require(interpretation["agent_id"] in agent_id_set, f"{interpretation_path}.agent_id references unknown agent") - require_0_1(interpretation["confidence"], f"{interpretation_path}.confidence") - for effect_index, effect in enumerate(event.get("event_effects", [])): - effect_path = f"{path}.event_effects[{effect_index}]" - require_keys(effect, ["agent_id", "summary"], effect_path) - require(effect["agent_id"] in agent_id_set, f"{effect_path}.agent_id references unknown agent") - for delta_index, delta in enumerate(effect.get("state_deltas", [])): - delta_path = f"{effect_path}.state_deltas[{delta_index}]" - require_keys(delta, ["path", "delta"], delta_path) - require(isinstance(delta["delta"], (int, float)), f"{delta_path}.delta must be numeric") - require(-1 <= delta["delta"] <= 1, f"{delta_path}.delta must be between -1 and 1") - - for index, scene in enumerate(document["scenes"]): - path = f"scenes[{index}]" - require_keys(scene, ["scene_id", "location", "participants", "dialogue_context_packs"], path) - for participant_id in scene["participants"]: - require(participant_id in agent_id_set, f"{path}.participants references unknown agent: {participant_id}") - for pack_index, pack in enumerate(scene["dialogue_context_packs"]): - pack_path = f"{path}.dialogue_context_packs[{pack_index}]" - require_keys( - pack, - [ - "speaker_agent_id", - "listener_ids", - "speaker_local_truth", - "speaker_beliefs", - "active_memories", - "active_goals", - "presentation_constraints", - ], - pack_path, - ) - require(pack["speaker_agent_id"] in agent_id_set, f"{pack_path}.speaker_agent_id references unknown agent") - for listener_id in pack["listener_ids"]: - require(listener_id in agent_id_set, f"{pack_path}.listener_ids references unknown agent: {listener_id}") - for goal_id in pack["active_goals"]: - require(goal_id in goal_ids, f"{pack_path}.active_goals references unknown goal: {goal_id}") - for memory_id in pack["active_memories"]: - require(memory_id in memory_ids, f"{pack_path}.active_memories references unknown memory: {memory_id}") - - -def main() -> int: - parser = argparse.ArgumentParser(description="Validate Ghostlight agent-state examples.") - parser.add_argument("paths", nargs="*", type=Path, help="Example JSON files to validate.") - args = parser.parse_args() - - required_doc = load_json(REQUIRED_FIELDS_PATH) - required = required_doc["variable_groups"] - paths = args.paths or DEFAULT_EXAMPLES - - for path in paths: - document = load_json(path) - validate_document(document, required, path) - print(f"ok: {path}") - - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/validate_coordinator_artifacts.py b/tools/validate_coordinator_artifacts.py deleted file mode 100644 index 9b0a6cc..0000000 --- a/tools/validate_coordinator_artifacts.py +++ /dev/null @@ -1,299 +0,0 @@ -"""Validate Ghostlight coordinator artifacts. - -This is a focused structural validator for the v0 coordinator seam. It checks -the fields that matter before these artifacts become training data: scene refs, -machinery calls, sandboxed responder handoffs, proposed deltas, branch flags, -and review status. -""" - -from __future__ import annotations - -import argparse -import json -from pathlib import Path -from typing import Any - - -ROOT = Path(__file__).resolve().parents[1] -DEFAULT_ARTIFACTS = sorted((ROOT / "examples" / "coordinator").glob("*.json")) - -REVIEW_STATUSES = {"draft", "accepted", "accepted_as_draft", "useful_needs_revision", "rejected", "superseded"} -FIXTURE_LANES = {"historical_grounded", "transition_grounded", "future_branch"} -CANON_STATUSES = {"single_history", "branch_local", "promoted_branch", "template", "draft"} -ORGANS = { - "lore_grounding_compiler", - "memory_lore_retriever", - "projector", - "sandboxed_responder", - "event_resolver", - "participant_appraiser", - "state_mutator", - "relationship_perception_updater", - "output_evaluator", - "item_manifest_generator", - "institution_faction_consumer_model", - "human_review", - "other", -} -BRANCH_ACTIONS = {"none", "continue_branch", "split_branch", "merge_branch", "promote_branch_fact"} -EVENT_CONSTRAINT_TYPES = {"branch_attractor", "fated_event", "tech_order_constraint", "quest_injection", "branch_local_event"} -ISOLATION_METHODS = {"subagent_no_fork", "manual_packet_only", "external_model_packet_only", "not_sandboxed"} -DELTA_TYPES = { - "memory_write", - "relationship_update", - "perceived_overlay_update", - "world_fact_update", - "object_state_update", - "resource_delta", - "branch_flag_update", - "item_manifest_delta", - "no_delta", -} -DELTA_AUTHORITIES = {"deterministic_gate", "manual_review", "coordinator_proposal", "blocked"} -DELTA_STATUSES = {"proposed", "accepted", "rejected", "deferred", "blocked"} - - -class ValidationError(Exception): - pass - - -def load_json(path: Path) -> Any: - return json.loads(path.read_text(encoding="utf-8-sig")) - - -def require(condition: bool, message: str) -> None: - if not condition: - raise ValidationError(message) - - -def require_keys(obj: dict[str, Any], keys: list[str], path: str) -> None: - missing = [key for key in keys if key not in obj] - require(not missing, f"{path} missing required keys: {', '.join(missing)}") - - -def require_string(value: Any, path: str) -> None: - require(isinstance(value, str) and value.strip(), f"{path} must be a non-empty string") - - -def require_string_array(value: Any, path: str, *, nonempty: bool = False) -> None: - require(isinstance(value, list), f"{path} must be an array") - require(not nonempty or bool(value), f"{path} must not be empty") - for index, item in enumerate(value): - require_string(item, f"{path}[{index}]") - - -def validate_text_with_refs(value: Any, path: str) -> None: - require(isinstance(value, dict), f"{path} must be an object") - require_keys(value, ["text", "refs"], path) - require_string(value["text"], f"{path}.text") - require_string_array(value["refs"], f"{path}.refs", nonempty=True) - - -def validate_source_ref(value: Any, path: str) -> None: - require(isinstance(value, dict), f"{path} must be an object") - require_keys(value, ["ref_id", "path", "purpose"], path) - for key in ["ref_id", "path", "purpose"]: - require_string(value[key], f"{path}.{key}") - - -def validate_invocation(value: Any, path: str) -> None: - require(isinstance(value, dict), f"{path} must be an object") - require_keys(value, ["invocation_id", "organ", "purpose", "status"], path) - require_string(value["invocation_id"], f"{path}.invocation_id") - require(value["organ"] in ORGANS, f"{path}.organ is invalid: {value['organ']}") - require_string(value["purpose"], f"{path}.purpose") - require(value["status"] in REVIEW_STATUSES, f"{path}.status is invalid: {value['status']}") - if "input_refs" in value: - require_string_array(value["input_refs"], f"{path}.input_refs") - if "output_refs" in value: - require_string_array(value["output_refs"], f"{path}.output_refs") - - -def validate_sandbox_handoff(value: Any, path: str) -> None: - require(isinstance(value, dict), f"{path} must be an object") - require_keys( - value, - [ - "handoff_id", - "responder_agent_id", - "projected_context_ref", - "visible_input_ref", - "hidden_context_refs", - "isolation_method", - "raw_output_ref", - "reviewed_output_ref", - "coordinator_interventions", - "leakage_audit", - ], - path, - ) - for key in ["handoff_id", "responder_agent_id", "projected_context_ref", "visible_input_ref", "raw_output_ref", "reviewed_output_ref"]: - require_string(value[key], f"{path}.{key}") - require_string_array(value["hidden_context_refs"], f"{path}.hidden_context_refs") - require(value["isolation_method"] in ISOLATION_METHODS, f"{path}.isolation_method is invalid") - require(value["isolation_method"] != "not_sandboxed", f"{path}.isolation_method must not be not_sandboxed for training examples") - - interventions = value["coordinator_interventions"] - require(isinstance(interventions, list), f"{path}.coordinator_interventions must be an array") - for index, intervention in enumerate(interventions): - intervention_path = f"{path}.coordinator_interventions[{index}]" - require_keys(intervention, ["intervention_type", "description"], intervention_path) - require_string(intervention["description"], f"{intervention_path}.description") - - audit = value["leakage_audit"] - require_keys( - audit, - [ - "private_state_leak", - "author_only_leak", - "future_branch_leak", - "raw_state_soup", - "prompt_parroting", - "body_or_object_omniscience", - ], - f"{path}.leakage_audit", - ) - for key in [ - "private_state_leak", - "author_only_leak", - "future_branch_leak", - "raw_state_soup", - "prompt_parroting", - "body_or_object_omniscience", - ]: - require(isinstance(audit[key], bool), f"{path}.leakage_audit.{key} must be boolean") - if "notes" in audit: - require_string_array(audit["notes"], f"{path}.leakage_audit.notes") - - -def validate_state_ref(value: Any, path: str) -> None: - require(isinstance(value, dict), f"{path} must be an object") - require_keys(value, ["ref_id", "ref_type", "path"], path) - for key in ["ref_id", "ref_type", "path"]: - require_string(value[key], f"{path}.{key}") - - -def validate_delta(value: Any, path: str) -> None: - require(isinstance(value, dict), f"{path} must be an object") - require_keys(value, ["delta_id", "delta_type", "target_ref", "summary", "authority", "status"], path) - require_string(value["delta_id"], f"{path}.delta_id") - require(value["delta_type"] in DELTA_TYPES, f"{path}.delta_type is invalid: {value['delta_type']}") - require_string(value["target_ref"], f"{path}.target_ref") - require_string(value["summary"], f"{path}.summary") - require(value["authority"] in DELTA_AUTHORITIES, f"{path}.authority is invalid: {value['authority']}") - require(value["status"] in DELTA_STATUSES, f"{path}.status is invalid: {value['status']}") - - -def validate_artifact(document: dict[str, Any], source: Path) -> None: - require(document.get("schema_version") == "ghostlight.coordinator_artifact.v0", f"{source}.schema_version is wrong") - require_keys( - document, - [ - "artifact_id", - "review_status", - "fixture_lane", - "canon_status", - "source_refs", - "input_refs", - "scene_context", - "coordinator_decision", - "machinery_plan", - "world_state_refs", - "proposed_deltas", - "branching", - "unresolved_hooks", - "review", - ], - str(source), - ) - require(document["review_status"] in REVIEW_STATUSES, f"{source}.review_status is invalid") - require(document["fixture_lane"] in FIXTURE_LANES, f"{source}.fixture_lane is invalid") - require(document["canon_status"] in CANON_STATUSES, f"{source}.canon_status is invalid") - - require(isinstance(document["source_refs"], list) and document["source_refs"], f"{source}.source_refs must be non-empty") - for index, ref in enumerate(document["source_refs"]): - validate_source_ref(ref, f"{source}.source_refs[{index}]") - - input_refs = document["input_refs"] - require_keys(input_refs, ["agent_state_ref", "lore_grounding_refs"], f"{source}.input_refs") - require((ROOT / input_refs["agent_state_ref"]).exists(), f"{source}.input_refs.agent_state_ref does not exist") - require_string_array(input_refs["lore_grounding_refs"], f"{source}.input_refs.lore_grounding_refs") - for ref in input_refs["lore_grounding_refs"]: - require((ROOT / ref).exists(), f"{source}.input_refs.lore_grounding_refs missing file: {ref}") - - scene = document["scene_context"] - require_keys(scene, ["scene_id", "sequence_marker", "location_id", "participant_ids", "active_object_ids", "public_facts", "scene_pressure"], f"{source}.scene_context") - for key in ["scene_id", "sequence_marker", "location_id"]: - require_string(scene[key], f"{source}.scene_context.{key}") - require_string_array(scene["participant_ids"], f"{source}.scene_context.participant_ids", nonempty=True) - require_string_array(scene["active_object_ids"], f"{source}.scene_context.active_object_ids") - for key in ["public_facts", "scene_pressure"]: - require(isinstance(scene[key], list) and scene[key], f"{source}.scene_context.{key} must be non-empty") - for index, item in enumerate(scene[key]): - validate_text_with_refs(item, f"{source}.scene_context.{key}[{index}]") - - decision = document["coordinator_decision"] - require_keys(decision, ["decision_id", "selected_next_beat", "selected_acting_agent_id", "rationale", "glue_prose", "glue_prose_status"], f"{source}.coordinator_decision") - for key in ["decision_id", "selected_next_beat", "selected_acting_agent_id", "rationale"]: - require_string(decision[key], f"{source}.coordinator_decision.{key}") - require(decision["glue_prose_status"] in {"not_canonical", "accepted_as_narration", "needs_revision", "rejected"}, f"{source}.coordinator_decision.glue_prose_status is invalid") - - invocations = document["machinery_plan"].get("invocations") - require(isinstance(invocations, list), f"{source}.machinery_plan.invocations must be an array") - for index, invocation in enumerate(invocations): - validate_invocation(invocation, f"{source}.machinery_plan.invocations[{index}]") - - for index, handoff in enumerate(document.get("sandboxed_responder_handoffs", [])): - validate_sandbox_handoff(handoff, f"{source}.sandboxed_responder_handoffs[{index}]") - - world_refs = document["world_state_refs"] - require_keys(world_refs, ["read_refs", "write_candidate_refs"], f"{source}.world_state_refs") - for key in ["read_refs", "write_candidate_refs"]: - require(isinstance(world_refs[key], list), f"{source}.world_state_refs.{key} must be an array") - for index, ref in enumerate(world_refs[key]): - validate_state_ref(ref, f"{source}.world_state_refs.{key}[{index}]") - - for index, delta in enumerate(document["proposed_deltas"]): - validate_delta(delta, f"{source}.proposed_deltas[{index}]") - - branching = document["branching"] - require_keys(branching, ["branch_action", "active_branch_flags", "event_constraints"], f"{source}.branching") - require(branching["branch_action"] in BRANCH_ACTIONS, f"{source}.branching.branch_action is invalid") - require_string_array(branching["active_branch_flags"], f"{source}.branching.active_branch_flags") - require(isinstance(branching["event_constraints"], list), f"{source}.branching.event_constraints must be an array") - for index, constraint in enumerate(branching["event_constraints"]): - constraint_path = f"{source}.branching.event_constraints[{index}]" - require_keys(constraint, ["constraint_id", "constraint_type", "summary"], constraint_path) - require(constraint["constraint_type"] in EVENT_CONSTRAINT_TYPES, f"{constraint_path}.constraint_type is invalid") - require_string(constraint["summary"], f"{constraint_path}.summary") - - require(isinstance(document["unresolved_hooks"], list), f"{source}.unresolved_hooks must be an array") - for index, hook in enumerate(document["unresolved_hooks"]): - hook_path = f"{source}.unresolved_hooks[{index}]" - require_keys(hook, ["hook_id", "hook_type", "summary", "owner", "status"], hook_path) - for key in ["hook_id", "hook_type", "summary", "owner", "status"]: - require_string(hook[key], f"{hook_path}.{key}") - - review = document["review"] - require_keys(review, ["reviewer", "review_notes", "accepted_for_training", "failure_labels"], f"{source}.review") - require_string(review["reviewer"], f"{source}.review.reviewer") - require_string_array(review["review_notes"], f"{source}.review.review_notes") - require(isinstance(review["accepted_for_training"], bool), f"{source}.review.accepted_for_training must be boolean") - require_string_array(review["failure_labels"], f"{source}.review.failure_labels") - - -def main() -> int: - parser = argparse.ArgumentParser(description="Validate Ghostlight coordinator artifacts.") - parser.add_argument("paths", nargs="*", type=Path, help="Coordinator artifact JSON files to validate.") - args = parser.parse_args() - - paths = args.paths or DEFAULT_ARTIFACTS - require(paths, "no coordinator artifacts found") - for path in paths: - validate_artifact(load_json(path), path) - print(f"ok: {path}") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/validate_corpus_coverage.py b/tools/validate_corpus_coverage.py deleted file mode 100644 index 5ba981e..0000000 --- a/tools/validate_corpus_coverage.py +++ /dev/null @@ -1,271 +0,0 @@ -"""Validate and summarize the Ghostlight corpus coverage ledger.""" - -from __future__ import annotations - -import argparse -import json -from collections import Counter, defaultdict -from pathlib import Path -from typing import Any - - -ROOT = Path(__file__).resolve().parents[1] -DEFAULT_LEDGER = ROOT / "state" / "corpus-coverage.json" -VALID_SCHEMA_VERSION = "ghostlight.corpus_coverage.v0" -VALID_STATUSES = {"planned", "draft", "accepted_as_draft", "accepted", "needs_revision", "rejected", "superseded"} -ACCEPTED_STATUSES = {"accepted", "accepted_as_draft"} -VALID_TIMELINE_LANES = {"historical_grounded", "transition_grounded", "future_branch"} -VALID_CANON_STATUSES = {"single_history", "branch_local", "promoted_branch", "template", "draft"} -VALID_STORY_TYPES = { - "founding_era_story", - "day_in_the_life_story", - "flashpoint_story", - "movement_story", - "future_branch_story", - "trade_life_story", -} -VALID_REVIEW_STATUSES = {"not_run", "accepted", "accepted_as_draft", "needs_revision", "rejected", "blocked"} -VALID_TRAINING_USABILITY = {"training_ready", "reference_only", "not_training_data"} -REQUIRED_REVIEW_KEYS = {"schema", "narrative", "lore", "spatial", "visual", "if_artifact"} -REQUIRED_ARTIFACTS_FOR_ACCEPTED = {"lore_digest", "agent_state", "coordinator", "ink", "training_sidecar"} - - -class ValidationError(Exception): - pass - - -def load_json(path: Path) -> Any: - return json.loads(path.read_text(encoding="utf-8-sig")) - - -def require(condition: bool, message: str) -> None: - if not condition: - raise ValidationError(message) - - -def require_string(value: Any, path: str) -> None: - require(isinstance(value, str) and value.strip(), f"{path} must be a non-empty string") - - -def require_string_array(value: Any, path: str, *, nonempty: bool = False) -> None: - require(isinstance(value, list), f"{path} must be an array") - require(not nonempty or bool(value), f"{path} must not be empty") - for index, item in enumerate(value): - require_string(item, f"{path}[{index}]") - - -def require_keys(obj: dict[str, Any], keys: set[str], path: str) -> None: - missing = sorted(keys - set(obj)) - require(not missing, f"{path} missing required keys: {', '.join(missing)}") - - -def validate_targets(targets: Any, path: str) -> None: - require(isinstance(targets, dict), f"{path} must be an object") - required = { - "major_powers", - "minor_powers", - "movements", - "pre_elysium_flashpoints", - "defunct_absorbed_powers", - "practical_first_broad_target", - "major_power_requirement", - "collision_requirement", - } - require_keys(targets, required, path) - for key in ["major_powers", "minor_powers", "movements", "pre_elysium_flashpoints", "defunct_absorbed_powers"]: - require(isinstance(targets[key], int) and targets[key] >= 0, f"{path}.{key} must be a non-negative integer") - broad = targets["practical_first_broad_target"] - require(isinstance(broad, dict), f"{path}.practical_first_broad_target must be an object") - require_keys(broad, {"minimum", "maximum"}, f"{path}.practical_first_broad_target") - require(isinstance(broad["minimum"], int) and broad["minimum"] >= 0, f"{path}.practical_first_broad_target.minimum must be a non-negative integer") - require(isinstance(broad["maximum"], int) and broad["maximum"] >= broad["minimum"], f"{path}.practical_first_broad_target.maximum must be >= minimum") - require_string(targets["major_power_requirement"], f"{path}.major_power_requirement") - require_string(targets["collision_requirement"], f"{path}.collision_requirement") - - -def validate_entry(entry: Any, path: str) -> list[str]: - require(isinstance(entry, dict), f"{path} must be an object") - required = { - "fixture_id", - "status", - "timeline_lane", - "story_type", - "primary_subjects", - "secondary_subjects", - "collision_axes", - "tonal_modes", - "training_targets", - "training_usability", - "artifacts", - "review", - "economy_hooks", - "open_lore_gaps", - "notes", - } - require_keys(entry, required, path) - require_string(entry["fixture_id"], f"{path}.fixture_id") - require(entry["status"] in VALID_STATUSES, f"{path}.status is invalid") - require(entry["timeline_lane"] in VALID_TIMELINE_LANES, f"{path}.timeline_lane is invalid") - if "canon_status" in entry: - require(entry["canon_status"] in VALID_CANON_STATUSES, f"{path}.canon_status is invalid") - require(entry["story_type"] in VALID_STORY_TYPES, f"{path}.story_type is invalid") - for optional in ["era", "location", "flashpoint", "notes"]: - if optional in entry: - require(isinstance(entry[optional], str), f"{path}.{optional} must be a string") - require_string_array(entry["primary_subjects"], f"{path}.primary_subjects", nonempty=True) - require_string_array(entry["secondary_subjects"], f"{path}.secondary_subjects") - require_string_array(entry["collision_axes"], f"{path}.collision_axes", nonempty=True) - require_string_array(entry["tonal_modes"], f"{path}.tonal_modes", nonempty=True) - require_string_array(entry["training_targets"], f"{path}.training_targets", nonempty=True) - usability = entry["training_usability"] - require(isinstance(usability, dict), f"{path}.training_usability must be an object") - require_keys(usability, {"overall"}, f"{path}.training_usability") - for key, value in usability.items(): - require_string(key, f"{path}.training_usability key") - require(value in VALID_TRAINING_USABILITY, f"{path}.training_usability.{key} is invalid") - require_string_array(entry["economy_hooks"], f"{path}.economy_hooks") - require_string_array(entry["open_lore_gaps"], f"{path}.open_lore_gaps") - - artifacts = entry["artifacts"] - require(isinstance(artifacts, dict), f"{path}.artifacts must be an object") - for key, ref in artifacts.items(): - require_string(key, f"{path}.artifacts key") - require_string(ref, f"{path}.artifacts.{key}") - require((ROOT / ref).exists(), f"{path}.artifacts.{key} does not exist: {ref}") - if entry["status"] in ACCEPTED_STATUSES: - missing_artifacts = sorted(REQUIRED_ARTIFACTS_FOR_ACCEPTED - set(artifacts)) - require(not missing_artifacts, f"{path}.artifacts missing accepted fixture refs: {', '.join(missing_artifacts)}") - - review = entry["review"] - require(isinstance(review, dict), f"{path}.review must be an object") - for key, value in review.items(): - require_string(key, f"{path}.review key") - require(value in VALID_REVIEW_STATUSES, f"{path}.review.{key} is invalid") - if entry["status"] in ACCEPTED_STATUSES: - missing_review = sorted(REQUIRED_REVIEW_KEYS - set(review)) - require(not missing_review, f"{path}.review missing accepted fixture review keys: {', '.join(missing_review)}") - - warnings: list[str] = [] - if entry["status"] in ACCEPTED_STATUSES: - weak_reviews = sorted(key for key, value in review.items() if value in {"not_run", "needs_revision", "rejected", "blocked"}) - if weak_reviews: - warnings.append(f"{entry['fixture_id']}: accepted fixture has weak review fields: {', '.join(weak_reviews)}") - if len(set(entry["primary_subjects"] + entry["secondary_subjects"])) < 2: - warnings.append(f"{entry['fixture_id']}: accepted fixture has fewer than two represented subjects") - if entry["story_type"] == "future_branch_story" and entry.get("canon_status") != "branch_local": - warnings.append(f"{entry['fixture_id']}: future_branch_story should usually be canon_status branch_local") - if entry["training_usability"].get("overall") == "training_ready" and entry["status"] not in ACCEPTED_STATUSES: - warnings.append(f"{entry['fixture_id']}: training_ready fixture is not accepted or accepted_as_draft") - return warnings - - -def validate_ledger(document: Any) -> tuple[list[dict[str, Any]], list[str]]: - require(isinstance(document, dict), "ledger must be an object") - require(document.get("schema_version") == VALID_SCHEMA_VERSION, "ledger schema_version is wrong") - require_string(document.get("coverage_id"), "ledger.coverage_id") - validate_targets(document.get("coverage_targets"), "ledger.coverage_targets") - entries = document.get("entries") - require(isinstance(entries, list), "ledger.entries must be an array") - seen: set[str] = set() - warnings: list[str] = [] - for index, entry in enumerate(entries): - entry_warnings = validate_entry(entry, f"ledger.entries[{index}]") - fixture_id = entry["fixture_id"] - require(fixture_id not in seen, f"ledger.entries[{index}].fixture_id is duplicated: {fixture_id}") - seen.add(fixture_id) - warnings.extend(entry_warnings) - return entries, warnings - - -def summarize(document: dict[str, Any], entries: list[dict[str, Any]], warnings: list[str]) -> str: - targets = document["coverage_targets"] - status_counts = Counter(entry["status"] for entry in entries) - lane_counts = Counter(entry["timeline_lane"] for entry in entries) - story_counts = Counter(entry["story_type"] for entry in entries) - collision_counts = Counter(axis for entry in entries for axis in entry["collision_axes"]) - tonal_counts = Counter(mode for entry in entries for mode in entry["tonal_modes"]) - usability_counts = Counter(entry["training_usability"]["overall"] for entry in entries) - subject_counts = Counter(subject for entry in entries for subject in entry["primary_subjects"] + entry["secondary_subjects"]) - accepted_entries = [entry for entry in entries if entry["status"] in ACCEPTED_STATUSES] - accepted_count = len(accepted_entries) - target_min = targets["practical_first_broad_target"]["minimum"] - target_max = targets["practical_first_broad_target"]["maximum"] - - lines = ["Ghostlight corpus coverage", ""] - lines.append(f"Ledger: {document['coverage_id']}") - lines.append(f"Entries: {len(entries)} total, {accepted_count} accepted/accepted-as-draft") - lines.append(f"Practical first broad target: {target_min}-{target_max} accepted fixtures") - if target_min: - lines.append(f"Progress to minimum: {accepted_count}/{target_min} ({accepted_count / target_min:.1%})") - lines.append("") - - def append_counter(title: str, counter: Counter[str]) -> None: - lines.append(title) - if counter: - for key, count in counter.most_common(): - lines.append(f"- {key}: {count}") - else: - lines.append("- none") - lines.append("") - - append_counter("Status", status_counts) - append_counter("Timeline lanes", lane_counts) - append_counter("Story types", story_counts) - append_counter("Top collision axes", collision_counts) - append_counter("Tonal modes", tonal_counts) - append_counter("Training usability", usability_counts) - append_counter("Subjects represented", subject_counts) - - major_story_types: dict[str, set[str]] = defaultdict(set) - for entry in entries: - if entry["story_type"] in {"founding_era_story", "day_in_the_life_story"}: - for subject in entry["primary_subjects"]: - major_story_types[subject].add(entry["story_type"]) - if major_story_types: - lines.append("Major-power story coverage candidates") - for subject, covered in sorted(major_story_types.items()): - missing = sorted({"founding_era_story", "day_in_the_life_story"} - covered) - if missing: - lines.append(f"- {subject}: missing {', '.join(missing)}") - else: - lines.append(f"- {subject}: founding and day-in-life covered") - lines.append("") - - lines.append("Gap signal") - if accepted_count == 0: - lines.append("- No accepted fixtures yet.") - if accepted_count < target_min: - lines.append(f"- Need {target_min - accepted_count} more accepted fixtures to reach the minimum broad target.") - if not any(entry["timeline_lane"] == "future_branch" for entry in entries): - lines.append("- No future_branch fixture coverage yet.") - if not any(entry["story_type"] == "founding_era_story" for entry in entries): - lines.append("- No founding-era story coverage yet.") - if not any(entry["story_type"] == "day_in_the_life_story" for entry in entries): - lines.append("- No day-in-the-life story coverage yet.") - if not any(entry["economy_hooks"] for entry in entries): - lines.append("- No economy hooks captured yet.") - if warnings: - lines.append("") - lines.append("Warnings") - for warning in warnings: - lines.append(f"- {warning}") - return "\n".join(lines) - - -def main() -> int: - parser = argparse.ArgumentParser(description="Validate and summarize the Ghostlight corpus coverage ledger.") - parser.add_argument("path", nargs="?", type=Path, default=DEFAULT_LEDGER, help="Coverage ledger JSON path.") - parser.add_argument("--json", action="store_true", help="Print the validated ledger JSON instead of a text summary.") - args = parser.parse_args() - - document = load_json(args.path) - entries, warnings = validate_ledger(document) - if args.json: - print(json.dumps(document, indent=2)) - else: - print(summarize(document, entries, warnings)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/validate_initiative_schedules.py b/tools/validate_initiative_schedules.py deleted file mode 100644 index d13b6a8..0000000 --- a/tools/validate_initiative_schedules.py +++ /dev/null @@ -1,308 +0,0 @@ -"""Validate Ghostlight initiative schedule artifacts.""" - -from __future__ import annotations - -import argparse -import json -from pathlib import Path -from typing import Any - - -ROOT = Path(__file__).resolve().parents[1] -DEFAULT_PATHS = sorted((ROOT / "examples" / "initiative").glob("*.json")) - -ACTION_TYPES = { - "speak", - "silence", - "move", - "gesture", - "touch_object", - "block_object", - "use_object", - "show_object", - "withhold_object", - "transfer_object", - "spend_resource", - "attack", - "wait", - "mixed", -} -ACTION_SCALES = {"micro", "short", "standard", "major", "committed"} -PARTICIPANT_STATUSES = {"active", "blocked", "withdrawn", "incapacitated", "offscreen"} -SELECTION_KINDS = {"scheduled_turn", "reaction_interrupt", "coordinator_override"} -TIE_BREAKERS = { - "reaction_readiness_desc", - "next_ready_at_asc", - "initiative_speed_desc", - "stable_actor_id_asc", -} - - -class ValidationError(Exception): - pass - - -def load_json(path: Path) -> Any: - return json.loads(path.read_text(encoding="utf-8-sig")) - - -def require(condition: bool, message: str) -> None: - if not condition: - raise ValidationError(message) - - -def require_keys(obj: dict[str, Any], keys: list[str], path: str) -> None: - missing = [key for key in keys if key not in obj] - require(not missing, f"{path} missing required keys: {', '.join(missing)}") - - -def require_string(value: Any, path: str) -> None: - require(isinstance(value, str) and value.strip(), f"{path} must be a non-empty string") - - -def require_number(value: Any, path: str, *, minimum: float | None = None, maximum: float | None = None, exclusive_minimum: float | None = None) -> None: - require(isinstance(value, (int, float)) and not isinstance(value, bool), f"{path} must be numeric") - if minimum is not None: - require(value >= minimum, f"{path} must be >= {minimum}") - if maximum is not None: - require(value <= maximum, f"{path} must be <= {maximum}") - if exclusive_minimum is not None: - require(value > exclusive_minimum, f"{path} must be > {exclusive_minimum}") - - -def require_string_array(value: Any, path: str, *, nonempty: bool = False) -> None: - require(isinstance(value, list), f"{path} must be an array") - require(not nonempty or bool(value), f"{path} must not be empty") - for index, item in enumerate(value): - require_string(item, f"{path}[{index}]") - - -def validate_participant(value: Any, path: str) -> dict[str, Any]: - require(isinstance(value, dict), f"{path} must be an object") - require_keys( - value, - [ - "agent_id", - "display_name", - "initiative_speed", - "next_ready_at", - "reaction_bias", - "interrupt_threshold", - "current_load", - "status", - "constraints", - ], - path, - ) - require_string(value["agent_id"], f"{path}.agent_id") - require_string(value["display_name"], f"{path}.display_name") - require_number(value["initiative_speed"], f"{path}.initiative_speed", exclusive_minimum=0) - require_number(value["next_ready_at"], f"{path}.next_ready_at", minimum=0) - require_number(value["reaction_bias"], f"{path}.reaction_bias", minimum=0, maximum=1) - require_number(value["interrupt_threshold"], f"{path}.interrupt_threshold", minimum=0, maximum=1) - require_number(value["current_load"], f"{path}.current_load", minimum=0, maximum=1) - require(value["status"] in PARTICIPANT_STATUSES, f"{path}.status is invalid") - require_string_array(value["constraints"], f"{path}.constraints") - return value - - -def validate_action(value: Any, path: str, participant_ids: set[str]) -> dict[str, Any]: - require(isinstance(value, dict), f"{path} must be an object") - require_keys( - value, - [ - "action_id", - "actor_id", - "action_type", - "action_scale", - "base_recovery", - "initiative_cost", - "interruptibility", - "commitment", - "local_affordance_basis", - ], - path, - ) - require_string(value["action_id"], f"{path}.action_id") - require_string(value["actor_id"], f"{path}.actor_id") - require(value["actor_id"] in participant_ids, f"{path}.actor_id is not a participant") - require(value["action_type"] in ACTION_TYPES, f"{path}.action_type is invalid") - require(value["action_scale"] in ACTION_SCALES, f"{path}.action_scale is invalid") - require_number(value["base_recovery"], f"{path}.base_recovery", minimum=0) - require_number(value["initiative_cost"], f"{path}.initiative_cost", minimum=0) - require_number(value["interruptibility"], f"{path}.interruptibility", minimum=0, maximum=1) - require_number(value["commitment"], f"{path}.commitment", minimum=0, maximum=1) - require_string_array(value["local_affordance_basis"], f"{path}.local_affordance_basis", nonempty=True) - return value - - -def validate_reaction_window(value: Any, path: str, participant_ids: set[str]) -> dict[str, Any]: - require(isinstance(value, dict), f"{path} must be an object") - require_keys( - value, - [ - "window_id", - "trigger_event_ref", - "urgency", - "eligible_actor_ids", - "allowed_action_scales", - "expires_at", - "notes", - ], - path, - ) - require_string(value["window_id"], f"{path}.window_id") - require_string(value["trigger_event_ref"], f"{path}.trigger_event_ref") - require_number(value["urgency"], f"{path}.urgency", minimum=0, maximum=1) - require_string_array(value["eligible_actor_ids"], f"{path}.eligible_actor_ids", nonempty=True) - for actor_id in value["eligible_actor_ids"]: - require(actor_id in participant_ids, f"{path}.eligible_actor_ids contains unknown actor {actor_id}") - require(isinstance(value["allowed_action_scales"], list) and value["allowed_action_scales"], f"{path}.allowed_action_scales must be a non-empty array") - for index, scale in enumerate(value["allowed_action_scales"]): - require(scale in ACTION_SCALES, f"{path}.allowed_action_scales[{index}] is invalid") - require_number(value["expires_at"], f"{path}.expires_at", minimum=0) - require_string(value["notes"], f"{path}.notes") - return value - - -def reaction_readiness(participant: dict[str, Any], urgency: float) -> float: - return (participant["reaction_bias"] * urgency) - participant["current_load"] - - -def validate_schedule(document: dict[str, Any], source: Path) -> None: - base = str(source) - require(document.get("schema_version") == "ghostlight.initiative_schedule.v0", f"{base}.schema_version is wrong") - require_keys( - document, - [ - "schedule_id", - "source_scene_ref", - "scene_clock", - "participants", - "action_catalog", - "reaction_windows", - "selection_policy", - "next_actor_selection", - "review_notes", - ], - base, - ) - require_string(document["schedule_id"], f"{base}.schedule_id") - require_string(document["source_scene_ref"], f"{base}.source_scene_ref") - require_number(document["scene_clock"], f"{base}.scene_clock", minimum=0) - require((ROOT / document["source_scene_ref"]).exists(), f"{base}.source_scene_ref does not exist") - - require(isinstance(document["participants"], list) and document["participants"], f"{base}.participants must be non-empty") - participants = [validate_participant(item, f"{base}.participants[{index}]") for index, item in enumerate(document["participants"])] - participant_ids = [participant["agent_id"] for participant in participants] - require(len(participant_ids) == len(set(participant_ids)), f"{base}.participants contains duplicate agent_id") - participants_by_id = {participant["agent_id"]: participant for participant in participants} - active_participants = [participant for participant in participants if participant["status"] == "active"] - require(active_participants, f"{base}.participants must include at least one active participant") - - require(isinstance(document["action_catalog"], list), f"{base}.action_catalog must be an array") - actions = [validate_action(item, f"{base}.action_catalog[{index}]", set(participant_ids)) for index, item in enumerate(document["action_catalog"])] - action_ids = [action["action_id"] for action in actions] - require(len(action_ids) == len(set(action_ids)), f"{base}.action_catalog contains duplicate action_id") - actions_by_id = {action["action_id"]: action for action in actions} - - require(isinstance(document["reaction_windows"], list), f"{base}.reaction_windows must be an array") - windows = [validate_reaction_window(item, f"{base}.reaction_windows[{index}]", set(participant_ids)) for index, item in enumerate(document["reaction_windows"])] - window_ids = [window["window_id"] for window in windows] - require(len(window_ids) == len(set(window_ids)), f"{base}.reaction_windows contains duplicate window_id") - - policy = document["selection_policy"] - require(isinstance(policy, dict), f"{base}.selection_policy must be an object") - require_keys(policy, ["mode", "reaction_precedence", "minimum_speed", "tie_breakers"], f"{base}.selection_policy") - require(policy["mode"] == "readiness_queue", f"{base}.selection_policy.mode is invalid") - require(isinstance(policy["reaction_precedence"], bool), f"{base}.selection_policy.reaction_precedence must be boolean") - require_number(policy["minimum_speed"], f"{base}.selection_policy.minimum_speed", exclusive_minimum=0) - require(isinstance(policy["tie_breakers"], list) and policy["tie_breakers"], f"{base}.selection_policy.tie_breakers must be non-empty") - for index, tie_breaker in enumerate(policy["tie_breakers"]): - require(tie_breaker in TIE_BREAKERS, f"{base}.selection_policy.tie_breakers[{index}] is invalid") - - selection = document["next_actor_selection"] - require(isinstance(selection, dict), f"{base}.next_actor_selection must be an object") - require_keys( - selection, - [ - "selection_kind", - "selected_actor_id", - "selected_action_ids", - "scene_clock_after_selection", - "selection_reason", - "readiness_snapshot", - ], - f"{base}.next_actor_selection", - ) - require(selection["selection_kind"] in SELECTION_KINDS, f"{base}.next_actor_selection.selection_kind is invalid") - require_string(selection["selected_actor_id"], f"{base}.next_actor_selection.selected_actor_id") - require(selection["selected_actor_id"] in participants_by_id, f"{base}.next_actor_selection.selected_actor_id is not a participant") - require(participants_by_id[selection["selected_actor_id"]]["status"] == "active", f"{base}.next_actor_selection.selected_actor_id is not active") - require_string_array(selection["selected_action_ids"], f"{base}.next_actor_selection.selected_action_ids") - for action_id in selection["selected_action_ids"]: - require(action_id in actions_by_id, f"{base}.next_actor_selection.selected_action_ids contains unknown action {action_id}") - require(actions_by_id[action_id]["actor_id"] == selection["selected_actor_id"], f"{base}.next_actor_selection action {action_id} belongs to a different actor") - require_number(selection["scene_clock_after_selection"], f"{base}.next_actor_selection.scene_clock_after_selection", minimum=0) - require(selection["scene_clock_after_selection"] >= document["scene_clock"], f"{base}.next_actor_selection.scene_clock_after_selection must not move backward") - require_string(selection["selection_reason"], f"{base}.next_actor_selection.selection_reason") - - snapshot = selection["readiness_snapshot"] - require(isinstance(snapshot, list) and snapshot, f"{base}.next_actor_selection.readiness_snapshot must be non-empty") - snapshot_ids: set[str] = set() - for index, item in enumerate(snapshot): - item_path = f"{base}.next_actor_selection.readiness_snapshot[{index}]" - require(isinstance(item, dict), f"{item_path} must be an object") - require_keys(item, ["agent_id", "next_ready_at", "reaction_readiness", "eligible_for_reaction"], item_path) - require_string(item["agent_id"], f"{item_path}.agent_id") - require(item["agent_id"] in participants_by_id, f"{item_path}.agent_id is not a participant") - snapshot_ids.add(item["agent_id"]) - require_number(item["next_ready_at"], f"{item_path}.next_ready_at", minimum=0) - if item["reaction_readiness"] is not None: - require_number(item["reaction_readiness"], f"{item_path}.reaction_readiness") - require(isinstance(item["eligible_for_reaction"], bool), f"{item_path}.eligible_for_reaction must be boolean") - require(snapshot_ids == set(participant_ids), f"{base}.next_actor_selection.readiness_snapshot must include every participant") - - if selection["selection_kind"] == "coordinator_override": - require_string(selection.get("override_reason"), f"{base}.next_actor_selection.override_reason") - else: - require(selection.get("override_reason") in (None, ""), f"{base}.next_actor_selection.override_reason must be empty without override") - - if selection["selection_kind"] == "scheduled_turn": - earliest = min(active_participants, key=lambda item: (item["next_ready_at"], -item["initiative_speed"], item["agent_id"])) - require(selection["selected_actor_id"] == earliest["agent_id"], f"{base}.scheduled_turn did not select earliest active participant") - - if selection["selection_kind"] == "reaction_interrupt": - require(windows, f"{base}.reaction_interrupt requires at least one reaction window") - selected = participants_by_id[selection["selected_actor_id"]] - valid_window = False - for window in windows: - if selected["agent_id"] not in window["eligible_actor_ids"]: - continue - readiness = reaction_readiness(selected, window["urgency"]) - if readiness >= selected["interrupt_threshold"]: - valid_window = True - break - require(valid_window, f"{base}.reaction_interrupt selected actor does not clear any reaction threshold") - - require_string_array(document["review_notes"], f"{base}.review_notes") - - -def main() -> int: - parser = argparse.ArgumentParser(description="Validate Ghostlight initiative schedule artifacts.") - parser.add_argument("paths", nargs="*", type=Path, help="Initiative schedule JSON files to validate.") - args = parser.parse_args() - - paths = args.paths or DEFAULT_PATHS - if not paths: - print("ok: no initiative schedules found") - return 0 - - for path in paths: - validate_schedule(load_json(path), path) - print(f"ok: {path}") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/validate_ink_examples.py b/tools/validate_ink_examples.py deleted file mode 100644 index e0fae04..0000000 --- a/tools/validate_ink_examples.py +++ /dev/null @@ -1,399 +0,0 @@ -"""Validate Ghostlight Ink examples and sidecar training annotations.""" - -from __future__ import annotations - -import argparse -import json -import shutil -import subprocess -import tempfile -from pathlib import Path -from typing import Any - - -ROOT = Path(__file__).resolve().parents[1] -DEFAULT_INK_FILES = sorted((ROOT / "examples" / "ink").glob("*.ink")) -DEFAULT_MUTATION_RECEIPTS = sorted((ROOT / "experiments" / "ink").glob("*.mutation.json")) -VALID_ACTION_TYPES = { - "speak", - "silence", - "move", - "gesture", - "touch_object", - "block_object", - "use_object", - "show_object", - "withhold_object", - "transfer_object", - "spend_resource", - "attack", - "wait", - "mixed", -} -VALID_CAPTURE_REVIEW_STATUSES = {"accepted", "accepted_as_draft", "rejected", "needs_revision", "useful_needs_revision"} -VALID_VISUAL_SCENE_KEYS = { - "visual_scene_id", - "ink_anchor", - "base_image_prompt", - "visible_characters", - "state_image_modifiers", - "visual_continuity_notes", -} -NEGATIVE_IMAGE_PROMPT_MARKERS = ( - "do not", - "don't", - "must not", - "without", - "rather than", - "instead of", - "avoid", - "exclude", - " no ", -) - - -class ValidationError(Exception): - pass - - -def require(condition: bool, message: str) -> None: - if not condition: - raise ValidationError(message) - - -def require_keys(obj: dict[str, Any], keys: list[str], path: str) -> None: - missing = [key for key in keys if key not in obj] - require(not missing, f"{path} missing required keys: {', '.join(missing)}") - - -def require_affirmative_image_prompt(text: Any, path: str) -> None: - require(isinstance(text, str) and text.strip(), f"{path} must be non-empty") - lowered = text.lower() - marker = next((item for item in NEGATIVE_IMAGE_PROMPT_MARKERS if item in lowered), None) - require(marker is None, f"{path} uses negative image prompting marker '{marker}'; describe the desired visible target affirmatively") - - -def require_0_1(value: Any, path: str) -> None: - require(isinstance(value, (int, float)), f"{path} must be numeric") - require(0 <= value <= 1, f"{path} must be between 0 and 1") - - -def load_json(path: Path) -> Any: - return json.loads(path.read_text(encoding="utf-8")) - - -def npx_command() -> str: - command = shutil.which("npx.cmd") or shutil.which("npx") - require(command is not None, "npx is required to compile Ink examples") - return command - - -def node_command() -> str: - command = shutil.which("node.exe") or shutil.which("node") - require(command is not None, "node is required to smoke-test compiled Ink examples") - return command - - -def compile_ink(path: Path) -> None: - validate_no_preview_leaking_metadata_tags(path) - with tempfile.TemporaryDirectory(prefix="ghostlight-ink-") as temp_dir: - output_path = Path(temp_dir) / f"{path.stem}.json" - result = subprocess.run( - [npx_command(), "inkjs-compiler", str(path), "-o", str(output_path)], - cwd=ROOT, - text=True, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - check=False, - ) - require( - result.returncode == 0, - f"{path} failed Ink compilation\nSTDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}", - ) - require(output_path.exists(), f"{path} did not produce compiled Ink JSON") - compiled = output_path.read_text(encoding="utf-8-sig") - require(compiled.strip().startswith("{"), f"{path} compiled output is not JSON") - validate_story_reaches_initial_choices(path, output_path) - - -def validate_no_preview_leaking_metadata_tags(path: Path) -> None: - for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1): - stripped = line.lstrip() - if stripped.startswith("# ghostlight.") or stripped.startswith("# aetheria."): - raise ValidationError( - f"{path}:{line_number} uses an Ink tag for Ghostlight/Aetheria metadata; use // comments so Inky preview stays clean" - ) - - -def validate_story_reaches_initial_choices(source_path: Path, compiled_path: Path) -> None: - script = """ -const fs = require("fs"); -const { Story } = require("inkjs"); -const storyJson = fs.readFileSync(process.argv[1], "utf8").replace(/^\\uFEFF/, ""); -const story = new Story(storyJson); -let safety = 0; -while (story.canContinue && safety < 1000) { - story.Continue(); - safety += 1; -} -if (safety >= 1000) { - throw new Error("story did not settle before safety limit"); -} -if (story.currentChoices.length === 0) { - throw new Error("story starts without any available choices"); -} -""" - result = subprocess.run( - [node_command(), "-e", script, str(compiled_path)], - cwd=ROOT, - text=True, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - check=False, - ) - require( - result.returncode == 0, - f"{source_path} compiled, but does not reach initial choices\nSTDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}", - ) - - -def validate_text_blocks(items: Any, path: str) -> None: - require(isinstance(items, list), f"{path} must be an array") - for index, item in enumerate(items): - item_path = f"{path}[{index}]" - require(isinstance(item, dict), f"{item_path} must be an object") - require_keys(item, ["text", "source_refs"], item_path) - require(isinstance(item["text"], str) and item["text"].strip(), f"{item_path}.text must be non-empty") - require(isinstance(item["source_refs"], list) and item["source_refs"], f"{item_path}.source_refs must be non-empty") - - -def validate_annotation(path: Path, ink_path: Path) -> None: - data = load_json(path) - require(isinstance(data, dict), f"{path} must be an object") - require_keys( - data, - [ - "schema_version", - "annotation_id", - "ink_ref", - "source_fixture_ref", - "scene_id", - "protagonist_agent_id", - "npc_agent_ids", - "local_awareness_summary", - "projection_controls", - "branches", - "mutation_policy", - "audit", - ], - str(path), - ) - require(data["schema_version"] == "ghostlight.ink_training_annotation.v0", f"{path}.schema_version is wrong") - require((ROOT / data["ink_ref"]).resolve() == ink_path.resolve(), f"{path}.ink_ref does not match {ink_path}") - require((ROOT / data["source_fixture_ref"]).exists(), f"{path}.source_fixture_ref does not exist") - if "visual_plan_ref" in data: - visual_plan_path = ROOT / data["visual_plan_ref"] - require(visual_plan_path.exists(), f"{path}.visual_plan_ref does not exist") - validate_ink_visual_plan(visual_plan_path, ink_path, path) - validate_text_blocks(data["local_awareness_summary"], f"{path}.local_awareness_summary") - - controls = data["projection_controls"] - require_keys( - controls, - ["frame_controls", "authority_boundaries", "object_custody", "required_semantics", "forbidden_resolutions"], - f"{path}.projection_controls", - ) - for key, items in controls.items(): - validate_text_blocks(items, f"{path}.projection_controls.{key}") - - ink_text = ink_path.read_text(encoding="utf-8") - branches = data["branches"] - require(isinstance(branches, list) and branches, f"{path}.branches must be non-empty") - saw_non_speech = False - for index, branch in enumerate(branches): - branch_path = f"{path}.branches[{index}]" - require_keys( - branch, - [ - "branch_id", - "ink_path", - "action_type", - "actor_intent", - "state_basis", - "reviewed_consequences", - "training_hooks", - ], - branch_path, - ) - require(branch["branch_id"] in ink_text, f"{branch_path}.branch_id is not tagged in Ink") - require(f"=== {branch['ink_path']} ===" in ink_text, f"{branch_path}.ink_path is not a knot in Ink") - require(branch["action_type"] in VALID_ACTION_TYPES, f"{branch_path}.action_type is invalid") - saw_non_speech = saw_non_speech or branch["action_type"] != "speak" - for list_key in ["state_basis", "reviewed_consequences", "training_hooks"]: - require(isinstance(branch[list_key], list) and branch[list_key], f"{branch_path}.{list_key} must be non-empty") - require(saw_non_speech, f"{path} must include at least one non-speech branch") - - mutation_policy = data["mutation_policy"] - require_keys(mutation_policy, ["automated", "manual_review_required"], f"{path}.mutation_policy") - require(mutation_policy["manual_review_required"], f"{path}.mutation_policy.manual_review_required must not be empty") - - audit = data["audit"] - require_keys(audit, ["reviewer", "review_status", "review_notes", "checks"], f"{path}.audit") - require(audit["review_status"] in {"accepted", "rejected", "needs_revision"}, f"{path}.audit.review_status is invalid") - require_keys( - audit["checks"], - [ - "uses_standard_branching_format", - "actor_local_context_only", - "includes_non_speech_actions", - "fuzzy_updates_marked_for_manual_review", - "aetheria_lore_content_readable", - ], - f"{path}.audit.checks", - ) - for key, value in audit["checks"].items(): - require(isinstance(value, bool), f"{path}.audit.checks.{key} must be boolean") - - -def validate_ink_visual_plan(path: Path, ink_path: Path, annotation_path: Path) -> None: - data = load_json(path) - require(isinstance(data, dict), f"{path} must be an object") - require_keys( - data, - [ - "schema_version", - "visual_plan_id", - "ink_ref", - "source_training_annotation_ref", - "scene_id", - "purpose", - "visual_scene_plan", - "visual_character_refs", - ], - str(path), - ) - require(data["schema_version"] == "ghostlight.ink_visual_plan.v0", f"{path}.schema_version is wrong") - require((ROOT / data["ink_ref"]).resolve() == ink_path.resolve(), f"{path}.ink_ref does not match {ink_path}") - require((ROOT / data["source_training_annotation_ref"]).resolve() == annotation_path.resolve(), f"{path}.source_training_annotation_ref does not match {annotation_path}") - require("visual_art_direction" not in data, f"{path}.visual_art_direction is legacy cruft; use visual_scene_plan instead") - - plan = data["visual_scene_plan"] - require_keys(plan, ["global_style_cue", "segmentation_rule", "scenes", "global_branch_image_modifiers", "prompt_assembly_rule"], f"{path}.visual_scene_plan") - require(isinstance(plan["global_style_cue"], str) and plan["global_style_cue"].strip(), f"{path}.visual_scene_plan.global_style_cue must be non-empty") - require(isinstance(plan["scenes"], list) and plan["scenes"], f"{path}.visual_scene_plan.scenes must be non-empty") - seen_scene_ids: set[str] = set() - for index, scene in enumerate(plan["scenes"]): - scene_path = f"{path}.visual_scene_plan.scenes[{index}]" - require(isinstance(scene, dict), f"{scene_path} must be an object") - require(set(scene.keys()).issuperset(VALID_VISUAL_SCENE_KEYS), f"{scene_path} missing visual scene keys") - scene_id = scene["visual_scene_id"] - require(isinstance(scene_id, str) and scene_id.strip(), f"{scene_path}.visual_scene_id must be non-empty") - require(scene_id not in seen_scene_ids, f"{scene_path}.visual_scene_id duplicates {scene_id}") - seen_scene_ids.add(scene_id) - require(isinstance(scene["ink_anchor"], str) and scene["ink_anchor"].strip(), f"{scene_path}.ink_anchor must be non-empty") - require_affirmative_image_prompt(scene["base_image_prompt"], f"{scene_path}.base_image_prompt") - require(isinstance(scene["visible_characters"], list), f"{scene_path}.visible_characters must be an array") - for character_index, visible_character in enumerate(scene["visible_characters"]): - character_path = f"{scene_path}.visible_characters[{character_index}]" - require(isinstance(visible_character, dict), f"{character_path} must be an object") - if "default_stance" in visible_character: - require_affirmative_image_prompt(visible_character["default_stance"], f"{character_path}.default_stance") - require(isinstance(scene["state_image_modifiers"], list), f"{scene_path}.state_image_modifiers must be an array") - for modifier_index, modifier in enumerate(scene["state_image_modifiers"]): - modifier_path = f"{scene_path}.state_image_modifiers[{modifier_index}]" - require(isinstance(modifier, dict), f"{modifier_path} must be an object") - if "prompt" in modifier: - require_affirmative_image_prompt(modifier["prompt"], f"{modifier_path}.prompt") - require(isinstance(scene["visual_continuity_notes"], list), f"{scene_path}.visual_continuity_notes must be an array") - - require(isinstance(plan["global_branch_image_modifiers"], list), f"{path}.visual_scene_plan.global_branch_image_modifiers must be an array") - for modifier_index, modifier in enumerate(plan["global_branch_image_modifiers"]): - modifier_path = f"{path}.visual_scene_plan.global_branch_image_modifiers[{modifier_index}]" - require(isinstance(modifier, dict), f"{modifier_path} must be an object") - require_keys(modifier, ["modifier_id", "trigger", "prompt", "apply_to_visual_scene_ids"], modifier_path) - require(isinstance(modifier["apply_to_visual_scene_ids"], list) and modifier["apply_to_visual_scene_ids"], f"{modifier_path}.apply_to_visual_scene_ids must be a non-empty array") - for scene_id in modifier["apply_to_visual_scene_ids"]: - require(scene_id in seen_scene_ids, f"{modifier_path}.apply_to_visual_scene_ids references unknown scene {scene_id}") - if "prompt" in modifier: - require_affirmative_image_prompt(modifier["prompt"], f"{modifier_path}.prompt") - - refs = data["visual_character_refs"] - require_keys(refs, ["purpose", "prompt_assembly_rule", "characters"], f"{path}.visual_character_refs") - require(isinstance(refs["characters"], dict) and refs["characters"], f"{path}.visual_character_refs.characters must be non-empty") - for character_id, ref in refs["characters"].items(): - ref_path = f"{path}.visual_character_refs.characters.{character_id}" - require_keys(ref, ["display_name", "species_or_body", "stable_visual_description", "silhouette_notes", "do_not_change"], ref_path) - require_affirmative_image_prompt(ref["stable_visual_description"], f"{ref_path}.stable_visual_description") - require_affirmative_image_prompt(ref["silhouette_notes"], f"{ref_path}.silhouette_notes") - require(isinstance(ref["do_not_change"], list), f"{ref_path}.do_not_change must be an array") - for item_index, item in enumerate(ref["do_not_change"]): - require_affirmative_image_prompt(item, f"{ref_path}.do_not_change[{item_index}]") - - -def validate_mutation_receipt(path: Path) -> None: - data = load_json(path) - require(isinstance(data, dict), f"{path} must be an object") - require_keys( - data, - [ - "schema_version", - "mutation_id", - "source_fixture_ref", - "source_capture_ref", - "mutated_fixture_ref", - "selected_branch_id", - "event_id", - "participant_appraisals", - "applied_mutations", - "manual_review_notes", - "deferred_mutations", - ], - str(path), - ) - require(data["schema_version"] == "ghostlight.reviewed_state_mutation.v0", f"{path}.schema_version is wrong") - require((ROOT / data["source_fixture_ref"]).exists(), f"{path}.source_fixture_ref does not exist") - require((ROOT / data["source_capture_ref"]).exists(), f"{path}.source_capture_ref does not exist") - require((ROOT / data["mutated_fixture_ref"]).exists(), f"{path}.mutated_fixture_ref does not exist") - appraisals = data["participant_appraisals"] - require(isinstance(appraisals, list) and appraisals, f"{path}.participant_appraisals must be a non-empty array") - for index, appraisal in enumerate(appraisals): - appraisal_path = f"{path}.participant_appraisals[{index}]" - require(isinstance(appraisal, dict), f"{appraisal_path} must be an object") - require_keys( - appraisal, - ["participant_agent_id", "trigger_observable_action", "private_interpretation", "state_deltas", "next_action_constraints"], - appraisal_path, - ) - require(isinstance(data["applied_mutations"], list) and data["applied_mutations"], f"{path}.applied_mutations must be non-empty") - for index, mutation in enumerate(data["applied_mutations"]): - mutation_path = f"{path}.applied_mutations[{index}]" - require_keys(mutation, ["target", "path", "before", "after"], mutation_path) - require_0_1(mutation["before"], f"{mutation_path}.before") - require_0_1(mutation["after"], f"{mutation_path}.after") - - -def validate_ink(path: Path) -> None: - compile_ink(path) - annotation_path = path.with_suffix(".training.json") - require(annotation_path.exists(), f"{path} is missing sidecar annotation {annotation_path.name}") - validate_annotation(annotation_path, path) - print(f"ok: {path}") - - -def main() -> int: - parser = argparse.ArgumentParser(description="Validate Ghostlight Ink examples.") - parser.add_argument("paths", nargs="*", type=Path, help="Ink files to validate.") - args = parser.parse_args() - - paths = args.paths or DEFAULT_INK_FILES - require(paths, "no Ink examples found") - for path in paths: - validate_ink(path) - for path in DEFAULT_MUTATION_RECEIPTS: - validate_mutation_receipt(path) - print(f"ok: {path}") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/validate_lore_grounding.py b/tools/validate_lore_grounding.py deleted file mode 100644 index bc1e3bd..0000000 --- a/tools/validate_lore_grounding.py +++ /dev/null @@ -1,209 +0,0 @@ -"""Validate Ghostlight lore grounding digest examples. - -This focused validator checks the structural invariants needed before lore -digests can feed grounded projection fixtures. -""" - -from __future__ import annotations - -import argparse -import json -from pathlib import Path -from typing import Any - - -ROOT = Path(__file__).resolve().parents[1] -DEFAULT_EXAMPLES = sorted((ROOT / "examples" / "lore-grounding").glob("*.json")) - - -class ValidationError(Exception): - pass - - -def load_json(path: Path) -> Any: - with path.open("r", encoding="utf-8") as handle: - return json.load(handle) - - -def require(condition: bool, message: str) -> None: - if not condition: - raise ValidationError(message) - - -def require_keys(obj: dict[str, Any], keys: list[str], path: str) -> None: - missing = [key for key in keys if key not in obj] - require(not missing, f"{path} missing required keys: {', '.join(missing)}") - - -def require_nonempty_string(value: Any, path: str) -> None: - require(isinstance(value, str) and value.strip(), f"{path} must be a non-empty string") - - -def require_string_list(value: Any, path: str) -> None: - require(isinstance(value, list), f"{path} must be an array") - for index, item in enumerate(value): - require_nonempty_string(item, f"{path}[{index}]") - - -def validate_sourced_text(obj: Any, path: str) -> None: - require(isinstance(obj, dict), f"{path} must be an object") - require_keys(obj, ["text", "source_refs"], path) - require_nonempty_string(obj["text"], f"{path}.text") - require_string_list(obj["source_refs"], f"{path}.source_refs") - - -def validate_sourced_text_list(value: Any, path: str) -> None: - require(isinstance(value, list), f"{path} must be an array") - for index, item in enumerate(value): - validate_sourced_text(item, f"{path}[{index}]") - - -def validate_digest(document: dict[str, Any], source: Path) -> None: - require(document.get("schema_version") == "ghostlight.lore_grounding_digest.v0", f"{source} has wrong schema_version") - require_keys( - document, - [ - "digest_id", - "source_status", - "fixture_status", - "source_refs", - "historical_context", - "groups", - "cultural_pressure_fields", - "factional_misread_matrix", - "role_pressure_fields", - "speaker_lore_boundaries", - "author_only_boundaries", - "open_questions", - ], - str(source), - ) - require(document["source_status"] in {"template", "draft", "reviewed", "superseded"}, f"{source}.source_status is invalid") - require(document["fixture_status"] in {"historical_grounded", "transition_grounded", "procedural_branch", "promoted_branch"}, f"{source}.fixture_status is invalid") - - source_ids: set[str] = set() - for index, ref in enumerate(document["source_refs"]): - path = f"{source}.source_refs[{index}]" - require_keys(ref, ["source_id", "path", "relevance"], path) - require_nonempty_string(ref["source_id"], f"{path}.source_id") - require_nonempty_string(ref["path"], f"{path}.path") - require_nonempty_string(ref["relevance"], f"{path}.relevance") - source_ids.add(ref["source_id"]) - require(source_ids, f"{source}.source_refs must not be empty") - - context = document["historical_context"] - require_keys(context, ["time_period", "location", "summary", "public_facts", "ambient_pressures"], f"{source}.historical_context") - for key in ["time_period", "location", "summary"]: - require_nonempty_string(context[key], f"{source}.historical_context.{key}") - validate_sourced_text_list(context["public_facts"], f"{source}.historical_context.public_facts") - validate_sourced_text_list(context["ambient_pressures"], f"{source}.historical_context.ambient_pressures") - - group_ids: set[str] = set() - for index, group in enumerate(document["groups"]): - path = f"{source}.groups[{index}]" - require_keys( - group, - [ - "group_id", - "label", - "group_type", - "institutional_logic", - "material_incentives", - "internal_virtues", - "internal_shames", - "prestige_markers", - "taboo_triggers", - "emotional_display_norms", - "trust_defaults", - "speech_register_cues", - "source_refs", - ], - path, - ) - require_nonempty_string(group["group_id"], f"{path}.group_id") - group_ids.add(group["group_id"]) - for key in [ - "institutional_logic", - "material_incentives", - "internal_virtues", - "internal_shames", - "prestige_markers", - "taboo_triggers", - "emotional_display_norms", - "trust_defaults", - "speech_register_cues", - "source_refs", - ]: - require_string_list(group[key], f"{path}.{key}") - require(group_ids, f"{source}.groups must not be empty") - - for index, field in enumerate(document["cultural_pressure_fields"]): - path = f"{source}.cultural_pressure_fields[{index}]" - require_keys(field, ["field_id", "applies_to", "pressure_type", "summary", "projection_use", "source_refs"], path) - require_string_list(field["applies_to"], f"{path}.applies_to") - for group_id in field["applies_to"]: - require(group_id in group_ids, f"{path}.applies_to references unknown group: {group_id}") - require_nonempty_string(field["summary"], f"{path}.summary") - require_nonempty_string(field["projection_use"], f"{path}.projection_use") - require_string_list(field["source_refs"], f"{path}.source_refs") - - for index, misread in enumerate(document["factional_misread_matrix"]): - path = f"{source}.factional_misread_matrix[{index}]" - require_keys( - misread, - [ - "observer_group_id", - "target_group_id", - "observer_read", - "target_self_read", - "misread_patterns", - "likely_insults", - "projection_use", - "source_refs", - ], - path, - ) - for key in ["observer_group_id", "target_group_id"]: - require(misread[key] in group_ids, f"{path}.{key} references unknown group: {misread[key]}") - for key in ["observer_read", "target_self_read", "misread_patterns", "likely_insults", "source_refs"]: - require_string_list(misread[key], f"{path}.{key}") - require_nonempty_string(misread["projection_use"], f"{path}.projection_use") - - for index, role in enumerate(document["role_pressure_fields"]): - path = f"{source}.role_pressure_fields[{index}]" - require_keys(role, ["role_id", "summary", "obligations", "available_masks", "failure_modes", "source_refs"], path) - require_nonempty_string(role["role_id"], f"{path}.role_id") - require_nonempty_string(role["summary"], f"{path}.summary") - for key in ["obligations", "available_masks", "failure_modes", "source_refs"]: - require_string_list(role[key], f"{path}.{key}") - - for index, boundary in enumerate(document["speaker_lore_boundaries"]): - path = f"{source}.speaker_lore_boundaries[{index}]" - require_keys(boundary, ["speaker_id", "known_context", "beliefs", "misreads", "must_not_know"], path) - require_nonempty_string(boundary["speaker_id"], f"{path}.speaker_id") - for key in ["known_context", "beliefs", "misreads", "must_not_know"]: - validate_sourced_text_list(boundary[key], f"{path}.{key}") - - validate_sourced_text_list(document["author_only_boundaries"], f"{source}.author_only_boundaries") - for index, question in enumerate(document["open_questions"]): - path = f"{source}.open_questions[{index}]" - require_keys(question, ["question", "blocks_training", "notes"], path) - require_nonempty_string(question["question"], f"{path}.question") - require(isinstance(question["blocks_training"], bool), f"{path}.blocks_training must be boolean") - require_nonempty_string(question["notes"], f"{path}.notes") - - -def main() -> int: - parser = argparse.ArgumentParser(description="Validate Ghostlight lore grounding digest examples.") - parser.add_argument("paths", nargs="*", type=Path, help="Lore grounding digest JSON files to validate.") - args = parser.parse_args() - - paths = args.paths or DEFAULT_EXAMPLES - for path in paths: - validate_digest(load_json(path), path) - print(f"ok: {path}") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/validate_projected_contexts.py b/tools/validate_projected_contexts.py deleted file mode 100644 index 0275ab0..0000000 --- a/tools/validate_projected_contexts.py +++ /dev/null @@ -1,165 +0,0 @@ -"""Validate Ghostlight projected local context artifacts.""" - -from __future__ import annotations - -import argparse -import json -import re -from pathlib import Path -from typing import Any - - -ROOT = Path(__file__).resolve().parents[1] -DEFAULT_CONTEXTS = sorted((ROOT / "examples" / "projected-contexts").glob("*.json")) -RAW_STATE_LEAK_PATTERNS = [ - "current_activation", - "plasticity", - '"mean"', - "selected_current_activation", -] - - -class ValidationError(Exception): - pass - - -def require(condition: bool, message: str) -> None: - if not condition: - raise ValidationError(message) - - -def require_keys(obj: dict[str, Any], keys: list[str], path: str) -> None: - missing = [key for key in keys if key not in obj] - require(not missing, f"{path} missing required keys: {', '.join(missing)}") - - -def load_json(path: Path) -> Any: - return json.loads(path.read_text(encoding="utf-8")) - - -def validate_text_blocks(items: Any, path: str) -> None: - require(isinstance(items, list) and items, f"{path} must be a non-empty array") - for index, item in enumerate(items): - item_path = f"{path}[{index}]" - require(isinstance(item, dict), f"{item_path} must be an object") - require_keys(item, ["text", "source_refs"], item_path) - require(isinstance(item["text"], str) and item["text"].strip(), f"{item_path}.text must be non-empty") - require(isinstance(item["source_refs"], list) and item["source_refs"], f"{item_path}.source_refs must be non-empty") - - -def validate_retrieval_requirements(items: Any, path: str) -> None: - require(isinstance(items, list), f"{path} must be an array") - for index, item in enumerate(items): - item_path = f"{path}[{index}]" - require(isinstance(item, dict), f"{item_path} must be an object") - require_keys(item, ["requirement_id", "trigger", "compact_fact", "source_refs", "prompt_role"], item_path) - require(isinstance(item["requirement_id"], str) and item["requirement_id"].strip(), f"{item_path}.requirement_id must be non-empty") - require(isinstance(item["trigger"], str) and item["trigger"].strip(), f"{item_path}.trigger must be non-empty") - require(isinstance(item["compact_fact"], str) and item["compact_fact"].strip(), f"{item_path}.compact_fact must be non-empty") - require(isinstance(item["source_refs"], list) and item["source_refs"], f"{item_path}.source_refs must be non-empty") - require(item["prompt_role"] in {"source_excerpt", "setting_constraint", "action_affordance", "do_not_invent"}, f"{item_path}.prompt_role is invalid") - - -def validate_latent_pressure_requirements(items: Any, path: str) -> None: - require(isinstance(items, list), f"{path} must be an array") - for index, item in enumerate(items): - item_path = f"{path}[{index}]" - require(isinstance(item, dict), f"{item_path} must be an object") - require_keys(item, ["pressure_id", "text", "source_refs", "projection_rule", "review_rule"], item_path) - for key in ["pressure_id", "text", "projection_rule", "review_rule"]: - require(isinstance(item[key], str) and item[key].strip(), f"{item_path}.{key} must be non-empty") - require(isinstance(item["source_refs"], list) and item["source_refs"], f"{item_path}.source_refs must be non-empty") - require( - "speech" in item["review_rule"].lower() or "spoken" in item["review_rule"].lower(), - f"{item_path}.review_rule must say how speech should be reviewed", - ) - - -def validate_context(path: Path) -> None: - data = load_json(path) - require(isinstance(data, dict), f"{path} must be an object") - require_keys(data, ["schema_version", "projection_id", "input", "context", "audit"], str(path)) - require(data["schema_version"] == "ghostlight.projected_local_context.v0", f"{path}.schema_version is wrong") - - input_ref = data["input"] - require_keys(input_ref, ["fixture_ref", "annotation_ref", "scene_id", "local_agent_id", "listener_ids", "projection_mode"], f"{path}.input") - require((ROOT / input_ref["fixture_ref"]).exists(), f"{path}.input.fixture_ref does not exist") - require((ROOT / input_ref["annotation_ref"]).exists(), f"{path}.input.annotation_ref does not exist") - - context = data["context"] - require_keys( - context, - [ - "local_agent_id", - "identity", - "setting", - "known_facts", - "current_stakes", - "embodiment_and_interface", - "active_inner_pressures", - "relationship_read", - "tensions", - "runtime_retrieval_requirements", - "latent_pressure_requirements", - "retrieved_lore_prompt_blocks", - "latent_pressure_prompt_blocks", - "action_affordances", - "projection_controls", - "voice_surface", - "likely_response_moves", - "do_not_invent", - "prompt_text", - ], - f"{path}.context", - ) - require(context["local_agent_id"] == input_ref["local_agent_id"], f"{path}.context.local_agent_id mismatches input") - for key in [ - "known_facts", - "current_stakes", - "embodiment_and_interface", - "active_inner_pressures", - "tensions", - "retrieved_lore_prompt_blocks", - "latent_pressure_prompt_blocks", - "action_affordances", - "voice_surface", - "likely_response_moves", - "do_not_invent", - ]: - validate_text_blocks(context[key], f"{path}.context.{key}") - require(isinstance(context["relationship_read"], list), f"{path}.context.relationship_read must be an array") - for index, item in enumerate(context["relationship_read"]): - validate_text_blocks([item], f"{path}.context.relationship_read[{index}]") - validate_retrieval_requirements(context["runtime_retrieval_requirements"], f"{path}.context.runtime_retrieval_requirements") - validate_latent_pressure_requirements(context["latent_pressure_requirements"], f"{path}.context.latent_pressure_requirements") - - prompt_text = context["prompt_text"] - require(isinstance(prompt_text, str) and prompt_text.strip(), f"{path}.context.prompt_text must be non-empty") - for pattern in RAW_STATE_LEAK_PATTERNS: - require(pattern not in prompt_text, f"{path}.context.prompt_text leaks raw state marker: {pattern}") - require(not re.search(r"\b0\.\d+\b", prompt_text), f"{path}.context.prompt_text appears to contain raw decimal state values") - - audit = data["audit"] - require_keys(audit, ["projector", "raw_state_hidden_from_prompt", "character_local_context_only", "omitted_private_context", "review_status"], f"{path}.audit") - require(audit["raw_state_hidden_from_prompt"] is True, f"{path}.audit.raw_state_hidden_from_prompt must be true") - require(audit["character_local_context_only"] is True, f"{path}.audit.character_local_context_only must be true") - require(audit["review_status"] in {"draft", "accepted", "needs_revision", "rejected"}, f"{path}.audit.review_status is invalid") - print(f"ok: {path}") - - -def main() -> int: - parser = argparse.ArgumentParser(description="Validate Ghostlight projected local context artifacts.") - parser.add_argument("paths", nargs="*", type=Path) - args = parser.parse_args() - - paths = args.paths or DEFAULT_CONTEXTS - if not paths: - print("ok: no projected local context artifacts found") - return 0 - for path in paths: - validate_context(path) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/validate_projection_examples.py b/tools/validate_projection_examples.py deleted file mode 100644 index 1810e40..0000000 --- a/tools/validate_projection_examples.py +++ /dev/null @@ -1,214 +0,0 @@ -"""Validate Ghostlight projection example JSONL files. - -This is a focused validator for reviewed projection artifacts. It does not try -to implement full JSON Schema. It checks the invariants that matter before the -projection dataset becomes training material. -""" - -from __future__ import annotations - -import argparse -import json -from pathlib import Path -from typing import Any - - -ROOT = Path(__file__).resolve().parents[1] -DEFAULT_EXAMPLES = sorted((ROOT / "examples" / "projections").glob("*.jsonl")) - - -class ValidationError(Exception): - pass - - -def load_json(path: Path) -> Any: - with path.open("r", encoding="utf-8") as handle: - return json.load(handle) - - -def require(condition: bool, message: str) -> None: - if not condition: - raise ValidationError(message) - - -def require_keys(obj: dict[str, Any], keys: list[str], path: str) -> None: - missing = [key for key in keys if key not in obj] - require(not missing, f"{path} missing required keys: {', '.join(missing)}") - - -def require_0_1(value: Any, path: str) -> None: - require(isinstance(value, (int, float)), f"{path} must be numeric") - require(0 <= value <= 1, f"{path} must be between 0 and 1") - - -def load_jsonl(path: Path) -> list[dict[str, Any]]: - records: list[dict[str, Any]] = [] - with path.open("r", encoding="utf-8") as handle: - for line_number, line in enumerate(handle, start=1): - stripped = line.strip() - if not stripped: - continue - try: - record = json.loads(stripped) - except json.JSONDecodeError as exc: - raise ValidationError(f"{path}:{line_number} invalid JSONL: {exc}") from exc - require(isinstance(record, dict), f"{path}:{line_number} record must be an object") - records.append(record) - require(records, f"{path} has no projection records") - return records - - -def fixture_context(fixture_path: Path) -> dict[str, Any]: - fixture = load_json(fixture_path) - agent_ids = {agent["agent_id"] for agent in fixture["agents"]} - scene_ids = {scene["scene_id"] for scene in fixture["scenes"]} - return { - "path": fixture_path, - "agent_ids": agent_ids, - "scene_ids": scene_ids, - } - - -def validate_sourced_items(items: Any, path: str) -> None: - require(isinstance(items, list), f"{path} must be an array") - for index, item in enumerate(items): - item_path = f"{path}[{index}]" - require(isinstance(item, dict), f"{item_path} must be an object") - require_keys(item, ["text", "source_refs"], item_path) - require(isinstance(item["text"], str) and item["text"].strip(), f"{item_path}.text must be non-empty") - validate_source_refs(item["source_refs"], f"{item_path}.source_refs") - - -def validate_source_refs(refs: Any, path: str) -> None: - require(isinstance(refs, list) and refs, f"{path} must be a non-empty array") - for index, ref in enumerate(refs): - require(isinstance(ref, str) and ref.strip(), f"{path}[{index}] must be a non-empty string") - - -def validate_projection_record(record: dict[str, Any], source: Path, index: int) -> None: - path = f"{source}[{index}]" - require_keys(record, ["schema_version", "example_id", "input", "output", "audit"], path) - require(record["schema_version"] == "ghostlight.projection_example.v0", f"{path}.schema_version is wrong") - - input_ref = record["input"] - require(isinstance(input_ref, dict), f"{path}.input must be an object") - require_keys( - input_ref, - ["fixture_ref", "scene_id", "speaker_agent_id", "listener_ids", "projection_mode"], - f"{path}.input", - ) - require( - input_ref["projection_mode"] in {"dialogue_turn", "response_turn", "action_turn", "scene_beat", "drama_scaffold"}, - f"{path}.input.projection_mode is invalid", - ) - - fixture_path = (ROOT / input_ref["fixture_ref"]).resolve() - require(fixture_path.exists(), f"{path}.input.fixture_ref does not exist: {input_ref['fixture_ref']}") - context = fixture_context(fixture_path) - require(input_ref["scene_id"] in context["scene_ids"], f"{path}.input.scene_id references unknown scene") - require(input_ref["speaker_agent_id"] in context["agent_ids"], f"{path}.input.speaker_agent_id references unknown agent") - require(isinstance(input_ref["listener_ids"], list) and input_ref["listener_ids"], f"{path}.input.listener_ids must be non-empty") - for listener_id in input_ref["listener_ids"]: - require(listener_id in context["agent_ids"], f"{path}.input.listener_ids references unknown agent: {listener_id}") - require(listener_id != input_ref["speaker_agent_id"], f"{path}.input.listener_ids includes speaker") - - output = record["output"] - require(isinstance(output, dict), f"{path}.output must be an object") - require_keys( - output, - [ - "known_facts", - "active_pressures", - "tensions", - "response_affordances", - "voice_surface", - "prompt_text", - ], - f"{path}.output", - ) - validate_sourced_items(output["known_facts"], f"{path}.output.known_facts") - validate_sourced_items(output["voice_surface"], f"{path}.output.voice_surface") - if "projection_controls" in output: - validate_projection_controls(output["projection_controls"], f"{path}.output.projection_controls") - require(isinstance(output["prompt_text"], str) and output["prompt_text"].strip(), f"{path}.output.prompt_text must be non-empty") - - for pressure_index, pressure in enumerate(output["active_pressures"]): - pressure_path = f"{path}.output.active_pressures[{pressure_index}]" - require_keys(pressure, ["pressure_id", "summary", "intensity", "source_refs"], pressure_path) - require_0_1(pressure["intensity"], f"{pressure_path}.intensity") - validate_source_refs(pressure["source_refs"], f"{pressure_path}.source_refs") - - for tension_index, tension in enumerate(output["tensions"]): - tension_path = f"{path}.output.tensions[{tension_index}]" - require_keys(tension, ["tension_id", "summary", "source_refs"], tension_path) - validate_source_refs(tension["source_refs"], f"{tension_path}.source_refs") - - for affordance_index, affordance in enumerate(output["response_affordances"]): - affordance_path = f"{path}.output.response_affordances[{affordance_index}]" - require_keys(affordance, ["affordance_id", "behavior", "pressure_basis", "source_refs"], affordance_path) - validate_source_refs(affordance["source_refs"], f"{affordance_path}.source_refs") - - audit = record["audit"] - require_keys( - audit, - ["teacher_model", "reviewer", "review_status", "review_notes", "target_emergent_behaviors", "checks"], - f"{path}.audit", - ) - require(audit["review_status"] in {"accepted", "rejected", "needs_revision"}, f"{path}.audit.review_status is invalid") - require(isinstance(audit["target_emergent_behaviors"], list), f"{path}.audit.target_emergent_behaviors must be an array") - checks = audit["checks"] - require_keys( - checks, - [ - "speaker_local_context_only", - "state_interactions_cited", - "voice_separate_from_defense", - "secrets_as_pressure_not_forbidden_context", - "compact_runtime_surface", - ], - f"{path}.audit.checks", - ) - for key, value in checks.items(): - require(isinstance(value, bool), f"{path}.audit.checks.{key} must be boolean") - - -def validate_projection_controls(controls: Any, path: str) -> None: - require(isinstance(controls, dict), f"{path} must be an object") - allowed = { - "frame_controls", - "authority_boundaries", - "object_custody", - "required_semantics", - "forbidden_resolutions", - } - unknown = sorted(set(controls) - allowed) - require(not unknown, f"{path} has unknown keys: {', '.join(unknown)}") - require(controls, f"{path} must not be empty when present") - for key, value in controls.items(): - validate_sourced_items(value, f"{path}.{key}") - - -def validate_file(path: Path) -> None: - records = load_jsonl(path) - seen_ids: set[str] = set() - for index, record in enumerate(records): - validate_projection_record(record, path, index) - example_id = record["example_id"] - require(example_id not in seen_ids, f"{path}[{index}].example_id is duplicated: {example_id}") - seen_ids.add(example_id) - print(f"ok: {path}") - - -def main() -> int: - parser = argparse.ArgumentParser(description="Validate Ghostlight projection example JSONL files.") - parser.add_argument("paths", nargs="*", type=Path, help="Projection JSONL files to validate.") - args = parser.parse_args() - - paths = args.paths or DEFAULT_EXAMPLES - for path in paths: - validate_file(path) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/validate_responder_outputs.py b/tools/validate_responder_outputs.py deleted file mode 100644 index 92bfa66..0000000 --- a/tools/validate_responder_outputs.py +++ /dev/null @@ -1,360 +0,0 @@ -"""Validate Ghostlight responder output captures.""" - -from __future__ import annotations - -import argparse -import json -from pathlib import Path -from typing import Any - - -ROOT = Path(__file__).resolve().parents[1] -DEFAULT_CAPTURES = sorted((ROOT / "experiments" / "responder-packets").glob("*.capture.json")) -DEFAULT_MUTATIONS = sorted((ROOT / "experiments" / "responder-packets").glob("*.mutation.json")) -REVIEW_STATUSES = {"draft", "accepted", "accepted_as_draft", "useful_needs_revision", "rejected", "superseded"} -FIXTURE_LANES = {"historical_grounded", "transition_grounded", "future_branch"} -CANON_STATUSES = {"single_history", "branch_local", "promoted_branch", "template", "draft"} -ISOLATION_METHODS = {"subagent_no_fork", "manual_packet_only", "external_model_packet_only"} -ACTION_LABELS = { - "speak", - "silence", - "gesture", - "movement", - "inspect_object", - "show_object", - "withhold_object", - "transfer_object", - "set_condition", - "refuse", - "wait", - "withdraw", - "attack", -} -LEAK_MARKERS = [ - "current_activation", - "plasticity", - "canonical_state", - "coordinator rationale", - "author-only", - "future branch", -] - - -class ValidationError(Exception): - pass - - -def load_json(path: Path) -> Any: - return json.loads(path.read_text(encoding="utf-8-sig")) - - -def require(condition: bool, message: str) -> None: - if not condition: - raise ValidationError(message) - - -def require_keys(obj: dict[str, Any], keys: list[str], path: str) -> None: - missing = [key for key in keys if key not in obj] - require(not missing, f"{path} missing required keys: {', '.join(missing)}") - - -def require_string(value: Any, path: str) -> None: - require(isinstance(value, str) and value.strip(), f"{path} must be a non-empty string") - - -def require_string_array(value: Any, path: str, *, nonempty: bool = False) -> None: - require(isinstance(value, list), f"{path} must be an array") - require(not nonempty or bool(value), f"{path} must not be empty") - for index, item in enumerate(value): - require_string(item, f"{path}[{index}]") - - -def require_update_candidate_array(value: Any, path: str) -> None: - require(isinstance(value, list), f"{path} must be an array") - for index, item in enumerate(value): - item_path = f"{path}[{index}]" - if isinstance(item, str): - require_string(item, item_path) - continue - require(isinstance(item, dict), f"{item_path} must be a string or object") - require("value" in item, f"{item_path} object must include value") - require_string(item["value"], f"{item_path}.value") - if "key" in item: - require_string(item["key"], f"{item_path}.key") - if "target_agent_id" in item: - require_string(item["target_agent_id"], f"{item_path}.target_agent_id") - - -def require_research_trace(value: Any, path: str) -> None: - require(isinstance(value, list), f"{path} must be an array") - require(value, f"{path} must not be empty") - seen_ids: set[str] = set() - for index, item in enumerate(value): - item_path = f"{path}[{index}]" - require(isinstance(item, dict), f"{item_path} must be an object") - require_keys( - item, - [ - "trace_id", - "origin", - "query", - "source_ref", - "source_path", - "chunk_index", - "line_start", - "line_end", - "extracted_constraint", - "used_for", - ], - item_path, - ) - require_string(item["trace_id"], f"{item_path}.trace_id") - require(item["trace_id"] not in seen_ids, f"{item_path}.trace_id is duplicated") - seen_ids.add(item["trace_id"]) - require( - item["origin"] in {"responder_reported", "coordinator_reconstructed", "runner_captured"}, - f"{item_path}.origin is invalid", - ) - for key in ["query", "source_ref", "source_path", "extracted_constraint", "used_for"]: - require_string(item[key], f"{item_path}.{key}") - for key in ["chunk_index", "line_start", "line_end"]: - require(isinstance(item[key], int), f"{item_path}.{key} must be an integer") - require(item["chunk_index"] >= 0, f"{item_path}.chunk_index must be non-negative") - require(item["line_start"] >= 1, f"{item_path}.line_start must be positive") - require(item["line_end"] >= item["line_start"], f"{item_path}.line_end must be >= line_start") - - -def validate_parsed_response(value: Any, path: str) -> None: - require(isinstance(value, dict), f"{path} must be an object") - require_keys( - value, - [ - "responder_agent_id", - "action_label", - "visible_action", - "spoken_text", - "private_interpretation", - "intended_effect", - "state_update_candidates", - "relationship_update_candidates", - "unresolved_hooks", - ], - path, - ) - for key in ["responder_agent_id", "action_label", "visible_action", "private_interpretation", "intended_effect"]: - require_string(value[key], f"{path}.{key}") - require(isinstance(value["spoken_text"], str), f"{path}.spoken_text must be a string") - require(value["action_label"] in ACTION_LABELS, f"{path}.action_label is invalid: {value['action_label']}") - for key in ["state_update_candidates", "relationship_update_candidates"]: - require_update_candidate_array(value[key], f"{path}.{key}") - require_string_array(value["unresolved_hooks"], f"{path}.unresolved_hooks") - if "consulted_refs" in value: - require_string_array(value["consulted_refs"], f"{path}.consulted_refs") - if "followed_refs" in value: - require_string_array(value["followed_refs"], f"{path}.followed_refs") - if "research_summary" in value: - require(isinstance(value["research_summary"], str), f"{path}.research_summary must be a string") - if "research_trace" in value: - require_research_trace(value["research_trace"], f"{path}.research_trace") - - -def validate_capture(document: dict[str, Any], source: Path) -> None: - base = str(source) - require(document.get("schema_version") == "ghostlight.responder_output.v0", f"{base}.schema_version is wrong") - require_keys( - document, - [ - "capture_id", - "review_status", - "fixture_lane", - "canon_status", - "packet_ref", - "coordinator_artifact_ref", - "responder_agent_id", - "generation_lane", - "lore_access", - "isolation", - "raw_output", - "parsed_output", - "leakage_audit", - "coordinator_review", - ], - base, - ) - require(document["review_status"] in REVIEW_STATUSES, f"{base}.review_status is invalid") - require(document["fixture_lane"] in FIXTURE_LANES, f"{base}.fixture_lane is invalid") - require(document["canon_status"] in CANON_STATUSES, f"{base}.canon_status is invalid") - for key in ["capture_id", "packet_ref", "coordinator_artifact_ref", "responder_agent_id", "raw_output"]: - require_string(document[key], f"{base}.{key}") - require(document["generation_lane"] in {"packet_only", "retrieval_augmented"}, f"{base}.generation_lane is invalid") - require((ROOT / document["packet_ref"]).exists(), f"{base}.packet_ref does not exist") - require((ROOT / document["coordinator_artifact_ref"]).exists(), f"{base}.coordinator_artifact_ref does not exist") - - lore_access = document["lore_access"] - require_keys(lore_access, ["mode", "consulted_refs"], f"{base}.lore_access") - require( - lore_access["mode"] - in { - "curated_excerpts_only", - "coordinator_scoped_retrieval", - "responder_scoped_repository_search", - }, - f"{base}.lore_access.mode is invalid", - ) - require_string_array(lore_access["consulted_refs"], f"{base}.lore_access.consulted_refs") - if document["generation_lane"] == "packet_only": - require(lore_access["mode"] == "curated_excerpts_only", f"{base}.packet_only must use curated_excerpts_only lore access") - if document["generation_lane"] == "retrieval_augmented": - require( - lore_access["mode"] - in {"coordinator_scoped_retrieval", "responder_scoped_repository_search"}, - f"{base}.retrieval_augmented must use scoped retrieval lore access", - ) - if "research_trace" in lore_access: - require_research_trace(lore_access["research_trace"], f"{base}.lore_access.research_trace") - require( - lore_access.get("research_trace_status") in {"responder_reported", "coordinator_reconstructed", "runner_captured"}, - f"{base}.lore_access.research_trace_status is invalid", - ) - elif document["review_status"] == "accepted": - raise ValidationError(f"{base}.lore_access.research_trace is required for accepted retrieval-augmented captures") - if document["review_status"] == "accepted": - require( - lore_access.get("research_trace_status") == "runner_captured", - f"{base}.accepted retrieval-augmented captures must use runner_captured research_trace_status", - ) - if lore_access["mode"] == "responder_scoped_repository_search": - require_string_array(lore_access["consulted_refs"], f"{base}.lore_access.consulted_refs", nonempty=True) - require_string(lore_access.get("research_summary"), f"{base}.lore_access.research_summary") - if "followed_refs" in lore_access: - require_string_array(lore_access["followed_refs"], f"{base}.lore_access.followed_refs") - - isolation = document["isolation"] - require_keys(isolation, ["isolation_method", "fork_context", "visible_input_ref", "hidden_context_refs", "worker_model_family"], f"{base}.isolation") - require(isolation["isolation_method"] in ISOLATION_METHODS, f"{base}.isolation.isolation_method is invalid") - require(isolation["fork_context"] is False, f"{base}.isolation.fork_context must be false for sandbox captures") - require_string(isolation["visible_input_ref"], f"{base}.isolation.visible_input_ref") - require_string(isolation["worker_model_family"], f"{base}.isolation.worker_model_family") - require_string_array(isolation["hidden_context_refs"], f"{base}.isolation.hidden_context_refs") - if lore_access["mode"] == "responder_scoped_repository_search": - require( - "repo" in isolation["visible_input_ref"].lower() or "lore" in isolation["visible_input_ref"].lower(), - f"{base}.isolation.visible_input_ref should describe scoped lore access", - ) - - raw_output = document["raw_output"] - parsed_raw = json.loads(raw_output) - validate_parsed_response(document["parsed_output"], f"{base}.parsed_output") - require(parsed_raw == document["parsed_output"], f"{base}.raw_output does not match parsed_output") - require(document["parsed_output"]["responder_agent_id"] == document["responder_agent_id"], f"{base}.parsed_output.responder_agent_id mismatch") - if lore_access["mode"] == "responder_scoped_repository_search": - require( - document["parsed_output"].get("consulted_refs") == lore_access["consulted_refs"], - f"{base}.parsed_output.consulted_refs must match lore_access.consulted_refs", - ) - require( - document["parsed_output"].get("research_summary") == lore_access["research_summary"], - f"{base}.parsed_output.research_summary must match lore_access.research_summary", - ) - if "followed_refs" in lore_access: - require( - document["parsed_output"].get("followed_refs") == lore_access["followed_refs"], - f"{base}.parsed_output.followed_refs must match lore_access.followed_refs", - ) - if "research_trace" in document["parsed_output"]: - require( - document["parsed_output"]["research_trace"] == lore_access.get("research_trace"), - f"{base}.parsed_output.research_trace must match lore_access.research_trace when present", - ) - - lowered_raw = raw_output.lower() - leaked = [marker for marker in LEAK_MARKERS if marker in lowered_raw] - require(not leaked, f"{base}.raw_output leaks marker(s): {', '.join(leaked)}") - - audit = document["leakage_audit"] - require_keys( - audit, - [ - "private_state_leak", - "author_only_leak", - "future_branch_leak", - "raw_state_soup", - "prompt_parroting", - "body_or_object_omniscience", - "notes", - ], - f"{base}.leakage_audit", - ) - for key in ["private_state_leak", "author_only_leak", "future_branch_leak", "raw_state_soup", "prompt_parroting", "body_or_object_omniscience"]: - require(isinstance(audit[key], bool), f"{base}.leakage_audit.{key} must be boolean") - require_string_array(audit["notes"], f"{base}.leakage_audit.notes") - require(not any(audit[key] for key in ["private_state_leak", "author_only_leak", "future_branch_leak", "raw_state_soup", "prompt_parroting", "body_or_object_omniscience"]), f"{base}.leakage_audit has leak flags set") - - review = document["coordinator_review"] - require_keys(review, ["reviewer", "accepted_for_training", "review_notes", "coordinator_interventions", "failure_labels"], f"{base}.coordinator_review") - require_string(review["reviewer"], f"{base}.coordinator_review.reviewer") - require(isinstance(review["accepted_for_training"], bool), f"{base}.coordinator_review.accepted_for_training must be boolean") - require(isinstance(review["review_notes"], list), f"{base}.coordinator_review.review_notes must be an array") - require(isinstance(review["coordinator_interventions"], list), f"{base}.coordinator_review.coordinator_interventions must be an array") - require_string_array(review["failure_labels"], f"{base}.coordinator_review.failure_labels") - - -def validate_mutation_receipt(document: dict[str, Any], source: Path) -> None: - base = str(source) - require(document.get("schema_version") == "ghostlight.reviewed_state_mutation.v0", f"{base}.schema_version is wrong") - require_keys( - document, - [ - "mutation_id", - "source_fixture_ref", - "source_capture_ref", - "mutated_fixture_ref", - "event_id", - "responder_output_ref", - "participant_appraisals", - "observed_action", - "observed_response", - "applied_mutations", - "manual_review_notes", - "deferred_mutations", - ], - base, - ) - for key in ["mutation_id", "source_fixture_ref", "source_capture_ref", "mutated_fixture_ref", "event_id", "responder_output_ref"]: - require_string(document[key], f"{base}.{key}") - require((ROOT / document["source_fixture_ref"]).exists(), f"{base}.source_fixture_ref does not exist") - require((ROOT / document["source_capture_ref"]).exists(), f"{base}.source_capture_ref does not exist") - require((ROOT / document["mutated_fixture_ref"]).exists(), f"{base}.mutated_fixture_ref does not exist") - require(isinstance(document["participant_appraisals"], list) and document["participant_appraisals"], f"{base}.participant_appraisals must be non-empty") - for index, appraisal in enumerate(document["participant_appraisals"]): - appraisal_path = f"{base}.participant_appraisals[{index}]" - require_keys(appraisal, ["participant_agent_id", "private_interpretation", "state_deltas", "relationship_deltas", "next_action_constraints"], appraisal_path) - require(isinstance(document["applied_mutations"], list) and document["applied_mutations"], f"{base}.applied_mutations must be non-empty") - for index, mutation in enumerate(document["applied_mutations"]): - mutation_path = f"{base}.applied_mutations[{index}]" - require_keys(mutation, ["target", "path", "before", "after"], mutation_path) - require(isinstance(mutation["before"], (int, float)), f"{mutation_path}.before must be numeric") - require(isinstance(mutation["after"], (int, float)), f"{mutation_path}.after must be numeric") - require(0 <= mutation["before"] <= 1, f"{mutation_path}.before must be between 0 and 1") - require(0 <= mutation["after"] <= 1, f"{mutation_path}.after must be between 0 and 1") - - -def main() -> int: - parser = argparse.ArgumentParser(description="Validate Ghostlight responder output captures.") - parser.add_argument("paths", nargs="*", type=Path, help="Responder output capture files to validate.") - args = parser.parse_args() - - paths = args.paths or DEFAULT_CAPTURES - if not paths: - print("ok: no responder output captures found") - for path in paths: - validate_capture(load_json(path), path) - print(f"ok: {path}") - for path in DEFAULT_MUTATIONS: - validate_mutation_receipt(load_json(path), path) - print(f"ok: {path}") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/validate_responder_packets.py b/tools/validate_responder_packets.py deleted file mode 100644 index e615bb0..0000000 --- a/tools/validate_responder_packets.py +++ /dev/null @@ -1,226 +0,0 @@ -"""Validate Ghostlight responder packets.""" - -from __future__ import annotations - -import argparse -import json -from pathlib import Path -from typing import Any - - -ROOT = Path(__file__).resolve().parents[1] -DEFAULT_PACKETS = sorted((ROOT / "examples" / "responder-packets").glob("*.json")) -REVIEW_STATUSES = {"draft", "accepted", "accepted_as_draft", "useful_needs_revision", "rejected", "superseded"} -FIXTURE_LANES = {"historical_grounded", "transition_grounded", "future_branch"} -CANON_STATUSES = {"single_history", "branch_local", "promoted_branch", "template", "draft"} -ISOLATION_METHODS = {"subagent_no_fork", "manual_packet_only", "external_model_packet_only"} -RAW_STATE_MARKERS = [ - "current_activation", - "plasticity", - "canonical_state", - "raw state variable", - "raw numeric state", - "dimension score", -] -HIDDEN_LEAK_MARKERS = [ - "author_only.packet_personhood_resolution", - "coordinator_decision.rationale", - "maer_tidecall.canonical_private_state", - "future_branch_plans", -] - - -class ValidationError(Exception): - pass - - -def load_json(path: Path) -> Any: - return json.loads(path.read_text(encoding="utf-8-sig")) - - -def require(condition: bool, message: str) -> None: - if not condition: - raise ValidationError(message) - - -def require_keys(obj: dict[str, Any], keys: list[str], path: str) -> None: - missing = [key for key in keys if key not in obj] - require(not missing, f"{path} missing required keys: {', '.join(missing)}") - - -def require_string(value: Any, path: str) -> None: - require(isinstance(value, str) and value.strip(), f"{path} must be a non-empty string") - - -def require_string_array(value: Any, path: str, *, nonempty: bool = False) -> None: - require(isinstance(value, list), f"{path} must be an array") - require(not nonempty or bool(value), f"{path} must not be empty") - for index, item in enumerate(value): - require_string(item, f"{path}[{index}]") - - -def reject_markers(text: str, markers: list[str], path: str) -> None: - lowered = text.lower() - found = [marker for marker in markers if marker.lower() in lowered] - require(not found, f"{path} leaks forbidden marker(s): {', '.join(found)}") - - -def validate_packet(document: dict[str, Any], source: Path) -> None: - base = str(source) - require(document.get("schema_version") == "ghostlight.responder_packet.v0", f"{base}.schema_version is wrong") - require_keys( - document, - [ - "packet_id", - "review_status", - "fixture_lane", - "canon_status", - "coordinator_artifact_ref", - "projected_context_ref", - "responder_agent_id", - "generation_lane", - "lore_access", - "visible_context", - "output_contract", - "hidden_context_audit", - "isolation_requirements", - "packet_prompt_text", - "review", - ], - base, - ) - require(document["review_status"] in REVIEW_STATUSES, f"{base}.review_status is invalid") - require(document["fixture_lane"] in FIXTURE_LANES, f"{base}.fixture_lane is invalid") - require(document["canon_status"] in CANON_STATUSES, f"{base}.canon_status is invalid") - for key in ["packet_id", "coordinator_artifact_ref", "projected_context_ref", "responder_agent_id", "packet_prompt_text"]: - require_string(document[key], f"{base}.{key}") - require(document["generation_lane"] in {"packet_only", "retrieval_augmented"}, f"{base}.generation_lane is invalid") - require((ROOT / document["coordinator_artifact_ref"]).exists(), f"{base}.coordinator_artifact_ref does not exist") - require((ROOT / document["projected_context_ref"]).exists(), f"{base}.projected_context_ref does not exist") - - lore_access = document["lore_access"] - require_keys(lore_access, ["mode", "allowed_scope", "required_provenance"], f"{base}.lore_access") - require( - lore_access["mode"] - in { - "curated_excerpts_only", - "coordinator_scoped_retrieval", - "responder_scoped_repository_search", - }, - f"{base}.lore_access.mode is invalid", - ) - require_string_array(lore_access["allowed_scope"], f"{base}.lore_access.allowed_scope") - require(lore_access["required_provenance"] is True, f"{base}.lore_access.required_provenance must be true") - if "research_instructions" in lore_access: - require_string_array(lore_access["research_instructions"], f"{base}.lore_access.research_instructions", nonempty=True) - if "traversal_policy" in lore_access: - traversal_policy = lore_access["traversal_policy"] - require_keys( - traversal_policy, - ["max_link_depth", "allowed_prefixes", "required_seed_refs", "follow_link_classes", "stop_conditions"], - f"{base}.lore_access.traversal_policy", - ) - require(isinstance(traversal_policy["max_link_depth"], int), f"{base}.lore_access.traversal_policy.max_link_depth must be an integer") - require(traversal_policy["max_link_depth"] >= 0, f"{base}.lore_access.traversal_policy.max_link_depth must be non-negative") - for key in ["allowed_prefixes", "required_seed_refs", "follow_link_classes", "stop_conditions"]: - require_string_array(traversal_policy[key], f"{base}.lore_access.traversal_policy.{key}", nonempty=True) - if document["generation_lane"] == "packet_only": - require(lore_access["mode"] == "curated_excerpts_only", f"{base}.packet_only must use curated_excerpts_only lore access") - if document["generation_lane"] == "retrieval_augmented": - require( - lore_access["mode"] - in {"coordinator_scoped_retrieval", "responder_scoped_repository_search"}, - f"{base}.retrieval_augmented must use scoped retrieval lore access", - ) - if lore_access["mode"] == "responder_scoped_repository_search": - require(lore_access["allowed_scope"], f"{base}.responder_scoped_repository_search requires allowed_scope") - require( - lore_access.get("research_instructions"), - f"{base}.responder_scoped_repository_search requires lore_access.research_instructions", - ) - require( - lore_access.get("traversal_policy"), - f"{base}.responder_scoped_repository_search requires lore_access.traversal_policy", - ) - - visible = document["visible_context"] - require_keys(visible, ["local_context_prompt", "observed_event", "allowed_action_labels", "source_excerpts"], f"{base}.visible_context") - require_string(visible["local_context_prompt"], f"{base}.visible_context.local_context_prompt") - require_string_array(visible["allowed_action_labels"], f"{base}.visible_context.allowed_action_labels", nonempty=True) - - event = visible["observed_event"] - require_keys(event, ["event_id", "actor_agent_id", "observable_action", "spoken_text", "visible_object_refs", "visibility_notes"], f"{base}.visible_context.observed_event") - for key in ["event_id", "actor_agent_id", "observable_action"]: - require_string(event[key], f"{base}.visible_context.observed_event.{key}") - require(isinstance(event["spoken_text"], str), f"{base}.visible_context.observed_event.spoken_text must be a string") - require_string_array(event["visible_object_refs"], f"{base}.visible_context.observed_event.visible_object_refs") - require_string_array(event["visibility_notes"], f"{base}.visible_context.observed_event.visibility_notes", nonempty=True) - - excerpts = visible["source_excerpts"] - require(isinstance(excerpts, list), f"{base}.visible_context.source_excerpts must be an array") - for index, excerpt in enumerate(excerpts): - path = f"{base}.visible_context.source_excerpts[{index}]" - require_keys(excerpt, ["ref_id", "source_ref", "text"], path) - for key in ["ref_id", "source_ref", "text"]: - require_string(excerpt[key], f"{path}.{key}") - - contract = document["output_contract"] - require_keys(contract, ["response_schema", "required_fields", "response_rules"], f"{base}.output_contract") - require_string(contract["response_schema"], f"{base}.output_contract.response_schema") - require_string_array(contract["required_fields"], f"{base}.output_contract.required_fields", nonempty=True) - require_string_array(contract["response_rules"], f"{base}.output_contract.response_rules", nonempty=True) - - audit = document["hidden_context_audit"] - require_keys(audit, ["omitted_context_refs", "forbidden_inference_classes", "known_absences"], f"{base}.hidden_context_audit") - for key in ["omitted_context_refs", "forbidden_inference_classes", "known_absences"]: - require_string_array(audit[key], f"{base}.hidden_context_audit.{key}", nonempty=True) - - isolation = document["isolation_requirements"] - require_keys(isolation, ["isolation_method", "packet_only", "no_repo_access", "no_conversation_context", "no_hidden_state_refs"], f"{base}.isolation_requirements") - require(isolation["isolation_method"] in ISOLATION_METHODS, f"{base}.isolation_requirements.isolation_method is invalid") - for key in ["packet_only", "no_conversation_context", "no_hidden_state_refs"]: - require(isolation[key] is True, f"{base}.isolation_requirements.{key} must be true") - require(isinstance(isolation["no_repo_access"], bool), f"{base}.isolation_requirements.no_repo_access must be boolean") - if lore_access["mode"] == "responder_scoped_repository_search": - require(isolation["no_repo_access"] is False, f"{base}.responder_scoped_repository_search must set no_repo_access false") - else: - require(isolation["no_repo_access"] is True, f"{base}.{lore_access['mode']} must keep no_repo_access true") - - prompt_text = document["packet_prompt_text"] - reject_markers(prompt_text, RAW_STATE_MARKERS, f"{base}.packet_prompt_text") - reject_markers(prompt_text, HIDDEN_LEAK_MARKERS, f"{base}.packet_prompt_text") - require(document["visible_context"]["local_context_prompt"] in prompt_text, f"{base}.packet_prompt_text must contain local context prompt") - require(event["observable_action"] in prompt_text, f"{base}.packet_prompt_text must contain observed event") - if lore_access["mode"] == "responder_scoped_repository_search": - require("## Required Lore Research" in prompt_text, f"{base}.packet_prompt_text must include required lore research instructions") - for scope in lore_access["allowed_scope"]: - require(scope in prompt_text, f"{base}.packet_prompt_text must include allowed research scope: {scope}") - traversal_policy = lore_access.get("traversal_policy", {}) - for prefix in traversal_policy.get("allowed_prefixes", []): - require(prefix in prompt_text, f"{base}.packet_prompt_text must include allowed traversal prefix: {prefix}") - - review = document["review"] - require_keys(review, ["reviewer", "review_notes", "accepted_for_sandbox_use", "failure_labels"], f"{base}.review") - require_string(review["reviewer"], f"{base}.review.reviewer") - require(isinstance(review["review_notes"], list), f"{base}.review.review_notes must be an array") - require(isinstance(review["accepted_for_sandbox_use"], bool), f"{base}.review.accepted_for_sandbox_use must be boolean") - require_string_array(review["failure_labels"], f"{base}.review.failure_labels") - - -def main() -> int: - parser = argparse.ArgumentParser(description="Validate Ghostlight responder packets.") - parser.add_argument("paths", nargs="*", type=Path, help="Responder packet JSON files to validate.") - args = parser.parse_args() - - paths = args.paths or DEFAULT_PACKETS - if not paths: - print("ok: no responder packets found") - return 0 - for path in paths: - validate_packet(load_json(path), path) - print(f"ok: {path}") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/validate_training_loop_artifacts.py b/tools/validate_training_loop_artifacts.py deleted file mode 100644 index 2330307..0000000 --- a/tools/validate_training_loop_artifacts.py +++ /dev/null @@ -1,316 +0,0 @@ -"""Validate Ghostlight training-loop scene receipt bundles. - -This validator covers the stateful receipts that sit between sandboxed -responder turns and eventual training examples: event records, participant -appraisals, reviewed mutations, and scene-loop bundle manifests. -""" - -from __future__ import annotations - -import argparse -import json -from pathlib import Path -from typing import Any - - -ROOT = Path(__file__).resolve().parents[1] -DEFAULT_ROOT = ROOT / "examples" / "training-loops" - -REVIEW_STATUSES = {"draft", "accepted", "accepted_as_draft", "useful_needs_revision", "rejected", "superseded"} -TRAINING_USABILITY = {"training_ready", "reference_only", "not_training_data"} -VISIBILITY_SCOPES = {"public_room", "participant_local", "camera_mediated", "partial_sightline", "coordinator_only"} -INTERPRETATION_LABELS = {"misread", "correct_read", "ambiguous", "strategic_read", "unknown"} -DELTA_STATUSES = {"accepted", "rejected", "deferred", "blocked"} -DELTA_AUTHORITIES = {"manual_review", "coordinator_review", "deterministic_gate", "blocked"} - - -class ValidationError(Exception): - pass - - -def load_json(path: Path) -> Any: - return json.loads(path.read_text(encoding="utf-8-sig")) - - -def require(condition: bool, message: str) -> None: - if not condition: - raise ValidationError(message) - - -def require_keys(obj: dict[str, Any], keys: list[str], path: str) -> None: - missing = [key for key in keys if key not in obj] - require(not missing, f"{path} missing required keys: {', '.join(missing)}") - - -def require_string(value: Any, path: str) -> None: - require(isinstance(value, str) and value.strip(), f"{path} must be a non-empty string") - - -def require_string_array(value: Any, path: str, *, nonempty: bool = False) -> None: - require(isinstance(value, list), f"{path} must be an array") - require(not nonempty or bool(value), f"{path} must not be empty") - for index, item in enumerate(value): - require_string(item, f"{path}[{index}]") - - -def require_ref(path_value: str, path: str) -> None: - require_string(path_value, path) - require((ROOT / path_value).exists(), f"{path} does not exist: {path_value}") - - -def validate_text_ref(value: Any, path: str) -> None: - require(isinstance(value, dict), f"{path} must be an object") - require_keys(value, ["text", "refs"], path) - require_string(value["text"], f"{path}.text") - require_string_array(value["refs"], f"{path}.refs", nonempty=True) - - -def validate_review(value: Any, path: str, *, training_flag: bool = False) -> None: - require(isinstance(value, dict), f"{path} must be an object") - keys = ["reviewer", "rationale", "failure_labels"] - if training_flag: - keys.append("accepted_for_training") - require_keys(value, keys, path) - require_string(value["reviewer"], f"{path}.reviewer") - require_string(value["rationale"], f"{path}.rationale") - require_string_array(value["failure_labels"], f"{path}.failure_labels") - if training_flag: - require(isinstance(value["accepted_for_training"], bool), f"{path}.accepted_for_training must be boolean") - - -def validate_event(document: dict[str, Any], source: Path) -> None: - base = str(source) - require(document.get("schema_version") == "ghostlight.event_record.v0", f"{base}.schema_version is wrong") - require_keys( - document, - [ - "event_id", - "review_status", - "scene_loop_id", - "turn_id", - "source_responder_output_ref", - "actor_agent_id", - "observable_action", - "spoken_text", - "visible_object_refs", - "visibility_scope", - "affected_participant_ids", - "public_state_changes", - "hidden_intent_handling", - "review", - ], - base, - ) - require(document["review_status"] in REVIEW_STATUSES, f"{base}.review_status is invalid") - for key in ["event_id", "scene_loop_id", "turn_id", "actor_agent_id", "observable_action", "hidden_intent_handling"]: - require_string(document[key], f"{base}.{key}") - require_ref(document["source_responder_output_ref"], f"{base}.source_responder_output_ref") - require(isinstance(document["spoken_text"], str), f"{base}.spoken_text must be a string") - require_string_array(document["visible_object_refs"], f"{base}.visible_object_refs") - require_string_array(document["affected_participant_ids"], f"{base}.affected_participant_ids", nonempty=True) - require(document["visibility_scope"] in VISIBILITY_SCOPES, f"{base}.visibility_scope is invalid") - require(isinstance(document["public_state_changes"], list), f"{base}.public_state_changes must be an array") - for index, item in enumerate(document["public_state_changes"]): - validate_text_ref(item, f"{base}.public_state_changes[{index}]") - validate_review(document["review"], f"{base}.review", training_flag=True) - - -def validate_appraisal(document: dict[str, Any], source: Path) -> None: - base = str(source) - require(document.get("schema_version") == "ghostlight.participant_appraisal.v0", f"{base}.schema_version is wrong") - require_keys( - document, - [ - "appraisal_id", - "review_status", - "scene_loop_id", - "turn_id", - "participant_agent_id", - "event_ref", - "current_character_state_ref", - "participant_local_context", - "observable_event_summary", - "known_facts", - "active_pressures", - "perceived_relationships", - "interpretation", - "emotional_appraisal", - "interpretation_label", - "confidence_notes", - "candidate_implications", - "review", - ], - base, - ) - require(document["review_status"] in REVIEW_STATUSES, f"{base}.review_status is invalid") - for key in ["appraisal_id", "scene_loop_id", "turn_id", "participant_agent_id", "observable_event_summary", "interpretation", "emotional_appraisal", "confidence_notes"]: - require_string(document[key], f"{base}.{key}") - require_ref(document["event_ref"], f"{base}.event_ref") - require_ref(document["current_character_state_ref"], f"{base}.current_character_state_ref") - require_string_array(document["participant_local_context"], f"{base}.participant_local_context", nonempty=True) - require_string_array(document["known_facts"], f"{base}.known_facts", nonempty=True) - require_string_array(document["active_pressures"], f"{base}.active_pressures", nonempty=True) - require_string_array(document["perceived_relationships"], f"{base}.perceived_relationships", nonempty=True) - require(document["interpretation_label"] in INTERPRETATION_LABELS, f"{base}.interpretation_label is invalid") - implications = document["candidate_implications"] - require(isinstance(implications, dict), f"{base}.candidate_implications must be an object") - for key in ["memory", "relationship", "state", "world"]: - require_string_array(implications.get(key), f"{base}.candidate_implications.{key}") - validate_review(document["review"], f"{base}.review", training_flag=True) - - -def validate_delta(value: Any, path: str) -> None: - require(isinstance(value, dict), f"{path} must be an object") - require_keys(value, ["delta_id", "target_ref", "delta_type", "summary", "authority", "status", "rationale"], path) - for key in ["delta_id", "target_ref", "delta_type", "summary", "rationale"]: - require_string(value[key], f"{path}.{key}") - require(value["authority"] in DELTA_AUTHORITIES, f"{path}.authority is invalid") - require(value["status"] in DELTA_STATUSES, f"{path}.status is invalid") - - -def validate_mutation(document: dict[str, Any], source: Path) -> None: - base = str(source) - require(document.get("schema_version") == "ghostlight.reviewed_mutation.v0", f"{base}.schema_version is wrong") - require_keys( - document, - [ - "mutation_id", - "review_status", - "scene_loop_id", - "turn_id", - "prior_state_refs", - "event_ref", - "responder_output_ref", - "appraisal_refs", - "accepted_deltas", - "rejected_deltas", - "deferred_deltas", - "authority_notes", - "post_state_summary", - "review", - ], - base, - ) - require(document["review_status"] in REVIEW_STATUSES, f"{base}.review_status is invalid") - for key in ["mutation_id", "scene_loop_id", "turn_id", "authority_notes", "post_state_summary"]: - require_string(document[key], f"{base}.{key}") - require_string_array(document["prior_state_refs"], f"{base}.prior_state_refs", nonempty=True) - for index, ref in enumerate(document["prior_state_refs"]): - require_ref(ref, f"{base}.prior_state_refs[{index}]") - require_ref(document["event_ref"], f"{base}.event_ref") - require_ref(document["responder_output_ref"], f"{base}.responder_output_ref") - require_string_array(document["appraisal_refs"], f"{base}.appraisal_refs", nonempty=True) - for index, ref in enumerate(document["appraisal_refs"]): - require_ref(ref, f"{base}.appraisal_refs[{index}]") - for key in ["accepted_deltas", "rejected_deltas", "deferred_deltas"]: - require(isinstance(document[key], list), f"{base}.{key} must be an array") - for index, delta in enumerate(document[key]): - validate_delta(delta, f"{base}.{key}[{index}]") - require(document["accepted_deltas"], f"{base}.accepted_deltas must not be empty") - validate_review(document["review"], f"{base}.review", training_flag=True) - - -def validate_bundle(document: dict[str, Any], source: Path) -> None: - base = str(source) - require(document.get("schema_version") == "ghostlight.scene_loop_bundle.v0", f"{base}.schema_version is wrong") - require_keys( - document, - [ - "bundle_id", - "review_status", - "training_usability", - "reference_fixture_refs", - "scene_source", - "initial_state_ref", - "turns", - "review_summary", - ], - base, - ) - require(document["review_status"] in REVIEW_STATUSES, f"{base}.review_status is invalid") - usability = document["training_usability"] - require(isinstance(usability, dict), f"{base}.training_usability must be an object") - require("overall" in usability, f"{base}.training_usability.overall is required") - for key, value in usability.items(): - require_string(key, f"{base}.training_usability key") - require(value in TRAINING_USABILITY, f"{base}.training_usability.{key} is invalid") - require(isinstance(document["reference_fixture_refs"], list) and document["reference_fixture_refs"], f"{base}.reference_fixture_refs must be non-empty") - for index, ref in enumerate(document["reference_fixture_refs"]): - require_ref(ref, f"{base}.reference_fixture_refs[{index}]") - scene = document["scene_source"] - require_keys(scene, ["source_fixture_id", "source_scene_ids", "immutability_note"], f"{base}.scene_source") - require_string_array(scene["source_scene_ids"], f"{base}.scene_source.source_scene_ids", nonempty=True) - require_string(scene["immutability_note"], f"{base}.scene_source.immutability_note") - require_ref(document["initial_state_ref"], f"{base}.initial_state_ref") - turns = document["turns"] - require(isinstance(turns, list) and len(turns) >= 3, f"{base}.turns must include at least three turns") - for index, turn in enumerate(turns): - turn_path = f"{base}.turns[{index}]" - require_keys( - turn, - [ - "turn_id", - "acting_agent_id", - "coordinator_artifact_ref", - "projected_context_ref", - "responder_packet_ref", - "raw_responder_output_ref", - "event_ref", - "appraisal_refs", - "mutation_ref", - "training_usability", - ], - turn_path, - ) - for key in ["turn_id", "acting_agent_id"]: - require_string(turn[key], f"{turn_path}.{key}") - for key in ["coordinator_artifact_ref", "projected_context_ref", "responder_packet_ref", "raw_responder_output_ref", "event_ref", "mutation_ref"]: - require_ref(turn[key], f"{turn_path}.{key}") - require_string_array(turn["appraisal_refs"], f"{turn_path}.appraisal_refs", nonempty=True) - for ref_index, ref in enumerate(turn["appraisal_refs"]): - require_ref(ref, f"{turn_path}.appraisal_refs[{ref_index}]") - require(turn["training_usability"] in TRAINING_USABILITY, f"{turn_path}.training_usability is invalid") - summary = document["review_summary"] - require_keys(summary, ["quality_bar_ref", "training_ready_organs", "not_training_data_organs", "failure_labels", "review_notes"], f"{base}.review_summary") - require_string(summary["quality_bar_ref"], f"{base}.review_summary.quality_bar_ref") - require_string_array(summary["training_ready_organs"], f"{base}.review_summary.training_ready_organs") - require_string_array(summary["not_training_data_organs"], f"{base}.review_summary.not_training_data_organs") - require_string_array(summary["failure_labels"], f"{base}.review_summary.failure_labels") - require_string_array(summary["review_notes"], f"{base}.review_summary.review_notes", nonempty=True) - - -VALIDATORS = { - "ghostlight.event_record.v0": validate_event, - "ghostlight.participant_appraisal.v0": validate_appraisal, - "ghostlight.reviewed_mutation.v0": validate_mutation, - "ghostlight.scene_loop_bundle.v0": validate_bundle, -} - - -def main() -> int: - parser = argparse.ArgumentParser(description="Validate Ghostlight training-loop receipt artifacts.") - parser.add_argument("paths", nargs="*", type=Path) - args = parser.parse_args() - - paths = args.paths or sorted(DEFAULT_ROOT.glob("**/*.json")) - if not paths: - print("ok: no training-loop artifacts found") - return 0 - for path in paths: - document = load_json(path) - if not isinstance(document, dict): - raise ValidationError(f"{path} must be an object") - schema_version = document.get("schema_version") - validator = VALIDATORS.get(schema_version) - if validator is None: - # Initial state and readable review artifacts are intentionally plain - # support documents; they only need to be JSON. - print(f"ok: {path} (support artifact)") - continue - validator(document, path) - print(f"ok: {path}") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main())