From 37262100161e84c2b52ec6b587c6807c01211f37 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 1 May 2026 18:06:51 +0100 Subject: [PATCH] Scaffold Ghostlight persistence spine --- .gitignore | 6 + AGENTS.md | 115 ++++++++ README.md | 47 ++++ notes/architecture-rationale.md | 82 ++++++ notes/fresh-workspace-handoff.md | 49 ++++ notes/ghostlight-current-system-map.md | 54 ++++ notes/ghostlight-implementation-plan.md | 48 ++++ package.json | 11 + state/branches.json | 4 + state/evidence.jsonl | 2 + state/map.yaml | 69 +++++ state/scratch.md | 11 + tools/ghostlight_prepare_compaction.py | 334 ++++++++++++++++++++++++ tools/ghostlight_state.py | 180 +++++++++++++ 14 files changed, 1012 insertions(+) create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 README.md create mode 100644 notes/architecture-rationale.md create mode 100644 notes/fresh-workspace-handoff.md create mode 100644 notes/ghostlight-current-system-map.md create mode 100644 notes/ghostlight-implementation-plan.md create mode 100644 package.json create mode 100644 state/branches.json create mode 100644 state/evidence.jsonl create mode 100644 state/map.yaml create mode 100644 state/scratch.md create mode 100644 tools/ghostlight_prepare_compaction.py create mode 100644 tools/ghostlight_state.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e3e72e5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +__pycache__/ +*.pyc +.venv/ +node_modules/ +state/scratch-compaction-*.md + diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..507d5c2 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,115 @@ +# Ghostlight Instructions + +## Project Purpose + +Ghostlight is a research and implementation home for socially persistent +generative agents. The core problem is not "make an LLM sound like a person." +The core problem is building an architecture where personality, culture, +memory, masks, perception, and incentives can actually survive contact with +time, relationships, and pressure. + +This repo exists so those organs can live somewhere cleaner than a side chamber +inside another project. + +## Canonical State + +- Treat `state/map.yaml` as the canonical project map. +- Treat `state/scratch.md` as disposable working memory for one bounded + subgoal. +- Treat `state/evidence.jsonl` as the distilled durable ledger of what was + learned, verified, rejected, or accepted. +- Treat `notes/ghostlight-implementation-plan.md` as the current implementation + plan for the larger organs. +- Update `state/map.yaml` when project understanding changes. +- Add evidence after meaningful research, implementation, verification, or + rejected paths, but keep it distilled. Routine "I just did this" proof + belongs in git history, commits, smoke artifacts, or targeted logs unless it + changes what the next session should believe. +- Do not turn notes, map, handoff, and evidence into four versions of the same + brain. Distinct jobs or bust. + +## Important Paths + +- Project root: `E:\Projects\Ghostlight` +- Canonical map: `E:\Projects\Ghostlight\state\map.yaml` +- Scratch surface: `E:\Projects\Ghostlight\state\scratch.md` +- Distilled evidence ledger: `E:\Projects\Ghostlight\state\evidence.jsonl` +- Branch ledger: `E:\Projects\Ghostlight\state\branches.json` +- Handoff summary: `E:\Projects\Ghostlight\notes\fresh-workspace-handoff.md` +- System map: `E:\Projects\Ghostlight\notes\ghostlight-current-system-map.md` +- Implementation plan: `E:\Projects\Ghostlight\notes\ghostlight-implementation-plan.md` +- Architecture rationale: `E:\Projects\Ghostlight\notes\architecture-rationale.md` +- State CLI: `E:\Projects\Ghostlight\tools\ghostlight_state.py` +- Pre-compaction helper: `E:\Projects\Ghostlight\tools\ghostlight_prepare_compaction.py` + +## Useful Commands + +Use the bundled Python runtime if `python` is not on PATH: + +```powershell +npm run state:status +npm run state:prepare-compaction +& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\ghostlight_state.py' add-evidence --type research --status ok --note '...' +& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\ghostlight_state.py' add-branch --id branch-id --hypothesis '...' +``` + +## Session Bootstrap And Re-entry Protocol + +On fresh session load, do this before wandering off into implementation: + +1. read: + - `state/map.yaml` + - `notes/fresh-workspace-handoff.md` + - `notes/ghostlight-current-system-map.md` + - `notes/ghostlight-implementation-plan.md` +2. run: + - `npm run state:status` +3. restate the current next action from the persisted state before starting + edits +4. if the user only asked to rehydrate or reorient, stop after orientation and + wait for an explicit continue instruction instead of treating the persisted + next action as permission to start coding + +After compaction, resume, or suspicious continuity loss: + +1. rerun `npm run state:status` +2. reread `state/map.yaml` and `notes/fresh-workspace-handoff.md` +3. treat the persisted next action as authoritative unless fresh repo evidence + contradicts it + +When context pressure is clearly rising: + +1. stop broad exploration +2. narrow the active move to one bounded organ +3. persist map or handoff updates, plus distilled evidence only when the lesson + changes future belief, before the blackout lands + +When the user says to prepare for imminent compaction: + +1. run `tools/ghostlight_prepare_compaction.py` before editing persistence + surfaces +2. use its warnings as the checklist for map, handoff, scratch, evidence, and + git hygiene +3. update only the state that actually needs to change +4. run `tools/ghostlight_prepare_compaction.py` again after edits +5. fix errors, address warnings, and commit the completed persistence pass + unless the work is deliberately mid-surgery + +## Operating Discipline + +- Before substantial edits, restate the current mechanism and intended change. +- Prefer one clear hypothesis per iteration. +- Verify with checks that reflect the real goal, not just proxy success. +- Revert or discard changes that do not clearly improve the target. +- If the diff grows while understanding shrinks, stop implementation and switch + to diagnosis. +- Keep maps and prose together; do not replace useful maps with prose-only + explanations. +- Commit completed work before it rots in the worktree unless the task is + deliberately mid-surgery or the user asked to leave changes uncommitted. +- Push after major completed passes when a remote exists, unless the user asked + not to or there is a concrete reason to keep the commit local for a moment. +- Before handoff, compaction, or phase boundaries, sync `state/map.yaml`, add + distilled evidence when the lesson changes future belief, refresh + `notes/fresh-workspace-handoff.md`, and make the next action explicit. + diff --git a/README.md b/README.md new file mode 100644 index 0000000..1517562 --- /dev/null +++ b/README.md @@ -0,0 +1,47 @@ +# Ghostlight + +Ghostlight is where the stranger agent work gets to live. + +The project is about socially persistent generative agents: layered personality, +cultural priors, masks, memory, misreadings, incentives, and prompt projection +that grows out of structured latent state instead of one wet persona paragraph +trying to hold up the ceiling. + +The immediate goal is not a finished runtime. The immediate goal is a repo that +can carry the architecture cleanly enough that the runtime does not become a +beautiful little superstition. + +## What Lives Here + +- Epiphany-style persistent state surfaces for re-entry, compaction, and + distilled evidence. +- Architecture notes for agent state, signal classification, culture-shaped + distributions, and prompt projection. +- A bounded working discipline that keeps maps, scratch, evidence, and plans + from dissolving into one confident soup. + +## Repo Tour + +- `AGENTS.md`: operating discipline for humans and agents +- `state/map.yaml`: canonical project map +- `state/scratch.md`: disposable local working memory +- `state/evidence.jsonl`: distilled belief-changing evidence +- `notes/fresh-workspace-handoff.md`: compact re-entry packet +- `notes/ghostlight-current-system-map.md`: source-grounded explanation of the + live repo machinery +- `notes/ghostlight-implementation-plan.md`: current larger-organ sequence +- `notes/architecture-rationale.md`: why the state split exists at all +- `tools/ghostlight_state.py`: compact state helper +- `tools/ghostlight_prepare_compaction.py`: pre-compaction audit helper + +## Quick Commands + +```powershell +npm run state:status +npm run state:prepare-compaction +& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\ghostlight_state.py' add-evidence --type research --status ok --note '...' +``` + +If you are steering the repo through Codex, read `AGENTS.md` first. That is the +operating manual. The README is just the sign on the door. + diff --git a/notes/architecture-rationale.md b/notes/architecture-rationale.md new file mode 100644 index 0000000..8207835 --- /dev/null +++ b/notes/architecture-rationale.md @@ -0,0 +1,82 @@ +# Architecture Rationale + +This note explains why Ghostlight uses explicit state surfaces. It is not the +current implementation map and not the roadmap. For those, read: + +- `state/map.yaml` +- `notes/fresh-workspace-handoff.md` +- `notes/ghostlight-implementation-plan.md` +- `notes/ghostlight-current-system-map.md` + +## Core Failure + +The central failure mode is local plausibility without global coherence. + +An agent can write elegant little sentences, produce plausible little diffs, +and still lose the shape of the machine. Once the model no longer knows how the +latent state, memory, perception, and prompt layers fit together, adding more +local machinery usually makes the beast prettier and stupider. + +The answer is not more transcript. The answer is explicit structure: + +- slow-changing map +- disposable scratch +- distilled evidence +- compact handoff +- implementation plan that is not pretending to be a second map +- ruthless deletion when state stops improving the model + +## State Split + +Ghostlight treats different kinds of cognition as different artifacts: + +- `map`: canonical system model, invariants, accepted design, rejected paths +- `scratch`: temporary local reasoning for one bounded subgoal +- `evidence`: distilled proof, decisions, rejected paths, and scars that change future belief +- `system map`: source-grounded explanation of the live repo machinery +- `handoff`: compact re-entry packet +- `plan`: distilled forward implementation direction +- `output`: user-visible replies, code edits, commits, and verification artifacts + +The split matters because a language model will happily blend all of that into +one warm slurry if invited. Slurry is not architecture. + +## Current Harness Principle + +Ghostlight is using the same basic discipline that Epiphany proved useful: + +```text +observe the repo and canonical state +-> rehydrate the current map +-> work one bounded organ +-> verify the seam that matters +-> record only durable evidence +-> cut failed code and failed memory +``` + +The model is still a language model. That is the medium, not the scandal. +Language, structure, evidence, and salience are the steering surfaces. The repo +exists to keep those surfaces explicit enough that the next waking thing can +resume the pattern instead of faking continuity from vibes. + +## Compact-Rehydrate-Reorient + +Compaction is a real state transition, not a cosmetic cleanup. + +Before compaction, Ghostlight should preserve: + +- current objective and active subgoal +- latest stable map +- distilled evidence or rejected paths that change future belief +- open questions, blockers, and next action + +After rehydrating, Ghostlight should: + +- reread canonical state instead of trusting prompt residue +- restate the next action from persisted state +- continue only when instructed or when the task explicitly calls for it +- avoid broad implementation until the current mechanism is understood again + +The aim is not immortality cosplay. It is banking the fire enough that the next +waking thing finds coals instead of ash. + diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md new file mode 100644 index 0000000..9309bf4 --- /dev/null +++ b/notes/fresh-workspace-handoff.md @@ -0,0 +1,49 @@ +# Ghostlight Fresh Workspace Handoff + +Do not trust this file for the exact live HEAD. Use git for volatile truth. + +Do not continue implementation automatically from a rehydrate-only request. + +## Immediate Re-entry Instruction + +1. Read `state/map.yaml`. +2. Read `notes/ghostlight-current-system-map.md`. +3. Read `notes/ghostlight-implementation-plan.md`. +4. Run `npm run state:status`. +5. Restate the persisted next action before touching code or docs. + +## Current Shape + +Ghostlight currently has only the persistence and planning spine: + +- canonical map +- scratch +- evidence ledger +- branch ledger +- compact re-entry note +- system map +- implementation plan +- Python helpers for state summary and compaction audits + +There is no runtime yet. The live machine is still mostly design and state +discipline. + +## Current Next Action + +Move the Ghostlight-specific architecture out of VoidBot and into this repo in +a form that can grow its own organs. The first real choice after that is which +implementation seam to cut first: + +- state schema +- classifier/event data model +- prompt projection renderer + +## Warnings + +- Do not let this repo become a mirror maze of notes that say the same thing + in slightly different outfits. +- Keep canonical state small. If evidence starts turning into an activity feed, + cut it back. +- Keep the prompt-projection doctrine intact: prompt text is projection, not + truth storage. + diff --git a/notes/ghostlight-current-system-map.md b/notes/ghostlight-current-system-map.md new file mode 100644 index 0000000..abaef67 --- /dev/null +++ b/notes/ghostlight-current-system-map.md @@ -0,0 +1,54 @@ +# Ghostlight Current System Map + +Ghostlight does not have a runtime yet. The live system right now is the repo's +state and re-entry discipline. + +## Current Control Flow + +1. A user or agent enters the repo with a bounded question or implementation + goal. +2. The session rehydrates from: + - `state/map.yaml` + - `notes/fresh-workspace-handoff.md` + - this file + - `notes/ghostlight-implementation-plan.md` +3. The session runs `npm run state:status` to recover the current summary, next + action, and active subgoals. +4. Work happens in one bounded slice. +5. If understanding changes, the map is updated. +6. If future belief changes, distilled evidence is appended. +7. If compaction pressure rises, the helper audits state hygiene before the + session banks the fire. + +## Live Surfaces + +- `state/map.yaml` + - canonical experiment, objective, constraints, invariants, active subgoals, + accepted design, and current status +- `state/scratch.md` + - temporary working memory for one bounded organ +- `state/evidence.jsonl` + - durable belief-changing records only +- `state/branches.json` + - explicit hypothesis or branch tracking +- `notes/fresh-workspace-handoff.md` + - re-entry packet +- `notes/ghostlight-implementation-plan.md` + - larger-organ sequence +- `tools/ghostlight_state.py` + - compact state inspection and evidence or branch updates +- `tools/ghostlight_prepare_compaction.py` + - pre-compaction audit of required files, handoff content, and git hygiene + +## What Does Not Exist Yet + +- a canonical agent-state schema +- a classifier pipeline +- a prompt renderer +- a simulation/event loop +- a relationship engine +- a culture prior engine + +That absence is not a bug. It is just the current phase. The repo knows what it +is for before it has built the machinery. + diff --git a/notes/ghostlight-implementation-plan.md b/notes/ghostlight-implementation-plan.md new file mode 100644 index 0000000..6cbaeaa --- /dev/null +++ b/notes/ghostlight-implementation-plan.md @@ -0,0 +1,48 @@ +# Ghostlight Implementation Plan + +## Near-Term Sequence + +1. Migrate the architecture that already proved worth keeping. + - Move the relevant research and architecture notes out of VoidBot and into + Ghostlight. + - Keep the copies clean and Ghostlight-native instead of leaving them full + of cross-repo apology notes. + +2. Freeze the first canonical state model. + - Define the latent variable families. + - Define first-class dimensions, including volatility, attachment-seeking, + and distance-seeking. + - Define canonical state versus perceived state. + +3. Freeze the first event and classifier schema. + - Define event labels. + - Define canonical expression labels. + - Define listener perception labels. + - Define mask or presentation labels. + - Define confidence, uncertainty, and evidence accumulation rules. + +4. Build the prompt projection layer. + - Render prompts from structured state, relevant memories, scene pressure, + cultural defaults, and perceived state. + - Keep the prompt renderer a projection surface instead of a second brain. + +5. Build the simulation update loop. + - memory updates + - relationship updates + - goal pressure + - situational activation + - cultural and institutional pressure + +6. Build the first Aetheria slice. + - use the bounded corridor scenario already outlined elsewhere + - prove that a small cast, cohort states, and ambient pressure can make a + place feel inhabited + +## Discipline + +- Do not start with an MMO and call it ambition. +- Do not train a classifier before the label schema is stable enough to deserve + the trouble. +- Do not let prompt-writing outrun the structured state model. +- Do not let elegant theory notes multiply faster than implementation seams. + diff --git a/package.json b/package.json new file mode 100644 index 0000000..f31d3e0 --- /dev/null +++ b/package.json @@ -0,0 +1,11 @@ +{ + "name": "ghostlight", + "private": true, + "version": "0.0.0", + "description": "Persistent research repo for socially situated generative agent architecture.", + "scripts": { + "state:status": "\"C:\\Users\\Meta\\.cache\\codex-runtimes\\codex-primary-runtime\\dependencies\\python\\python.exe\" .\\tools\\ghostlight_state.py status", + "state:prepare-compaction": "\"C:\\Users\\Meta\\.cache\\codex-runtimes\\codex-primary-runtime\\dependencies\\python\\python.exe\" .\\tools\\ghostlight_prepare_compaction.py" + } +} + diff --git a/state/branches.json b/state/branches.json new file mode 100644 index 0000000..27ac0f7 --- /dev/null +++ b/state/branches.json @@ -0,0 +1,4 @@ +{ + "branches": [] +} + diff --git a/state/evidence.jsonl b/state/evidence.jsonl new file mode 100644 index 0000000..aed71d0 --- /dev/null +++ b/state/evidence.jsonl @@ -0,0 +1,2 @@ + +{"ts": "2026-05-01T17:06:46+00:00", "type": "scaffold", "status": "ok", "note": "Initialized Ghostlight with a stripped-down Epiphany-style persistence spine: canonical map, scratch, evidence, handoff, implementation plan, and Python state or compaction helpers."} diff --git a/state/map.yaml b/state/map.yaml new file mode 100644 index 0000000..12a80f5 --- /dev/null +++ b/state/map.yaml @@ -0,0 +1,69 @@ +experiment: + name: Ghostlight + status: incubation + phase: phase_0_scaffold + premise: > + Build a durable research and implementation home for socially persistent + generative agents whose behavior emerges from latent state, culture, + memory, perception, and incentives rather than flat persona prompts. + +objective: + primary: > + Turn Ghostlight into a legible machine for persistent autonomous social + agents that can inhabit Aetheria and other worlds without collapsing into + prompt soup. + current: > + Stand up the repo spine, consolidate the architecture we already know, and + prepare the first implementation slices around state modeling, cultural + priors, signal classification, and prompt projection. + +constraints: + - Prefer explicit latent state over persona theater. + - Culture should shape priors and incentives, not stamp out clones. + - Prompt text is a projection surface, not the canonical store of truth. + - Keep persistent state small enough to rehydrate without drowning the next session. + - Reuse proven machinery where it fits before inventing ornate nonsense. + +invariants: + - The map is canonical and slow-changing. + - Scratch is temporary and disposable. + - Evidence is durable and distilled. + - Canonical agent state and per-agent perceived state must remain distinct. + - Listener misread is part of the model, not an error to flatten away. + - Personality must be modeled as layered organization, presentation, and situational activation, not just one bag of labels. + +data_flow: + observe: + - research notes + - implementation artifacts + - simulation requirements + - setting constraints + process: + - rehydrate from canonical state + - work one bounded organ + - verify the seam that matters + - distill only belief-changing evidence + - commit or cut the branch + cut: + - kill machinery that does not visibly serve the core model + - move volatile proof to git history or artifacts, not durable notes + +active_subgoals: + - Consolidate the architecture notes already proven useful in VoidBot into a Ghostlight-native home. + - Define the canonical agent state model, including first-class volatility, attachment-seeking, and distance-seeking. + - Define how culture shapes priors, incentives, masks, and economic behavior without turning populations into clones. + - Define the boundary between canonical signal, perceived signal, and prompt projection. + +accepted_design: + - Ghostlight owns the deeper agent-state, personality, culture, relationship, and prompt-projection architecture; other projects can remain consumers instead of shrines. + - Personality is layered: underlying organization, stable dispositions, behavioral dimensions, presentation strategy, situational activation, relationship state, and goals or values. + - The agent model must distinguish canonical state from per-agent perceived state. + - Prompts are rendered projections of perceived state, active memory, and scene pressure; they are not the authoritative store of truth. + - Culture acts as a prior-shaping and incentive field with distributions, covariance, scripts, reward gradients, taboo maps, and prestige structure. + - Synthetic dialogue from known hidden state is a valid bootstrap source for training signal classifiers, but utterances themselves are not ground truth. + - Performance, concealment, and mask maintenance are signal, not just obstruction. + +current_status: + summary: Ghostlight is a freshly spun repo with the Epiphany-style persistence spine, but no runtime organs yet. + next_action: Migrate or rewrite the existing Ghostlight-relevant research notes from VoidBot into this repo, then pick the first implementation organ: state schema, classifier data model, or prompt renderer. + diff --git a/state/scratch.md b/state/scratch.md new file mode 100644 index 0000000..37618c0 --- /dev/null +++ b/state/scratch.md @@ -0,0 +1,11 @@ +# Ghostlight Scratch + +## Current Subgoal + +No active scratch subgoal. + +## Working Notes + +Use this file for one bounded slice. Delete or reset aggressively when the +slice is done. + diff --git a/tools/ghostlight_prepare_compaction.py b/tools/ghostlight_prepare_compaction.py new file mode 100644 index 0000000..71ea076 --- /dev/null +++ b/tools/ghostlight_prepare_compaction.py @@ -0,0 +1,334 @@ +from __future__ import annotations + +import argparse +import json +import re +import subprocess +from dataclasses import dataclass +from pathlib import Path +from typing import Any + + +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" +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 extract_map_field(name: str) -> str | None: + prefix = f" {name}:" + for line in read_text(MAP_PATH).splitlines(): + if line.startswith(prefix): + return line.split(":", 1)[1].strip() + 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 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 add_required_file_checks(findings: list[Finding]) -> None: + for path in [ + MAP_PATH, + SCRATCH_PATH, + BRANCHES_PATH, + EVIDENCE_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}")) + + 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 new file mode 100644 index 0000000..493670c --- /dev/null +++ b/tools/ghostlight_state.py @@ -0,0 +1,180 @@ +from __future__ import annotations + +import argparse +import json +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + + +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" + + +def read_text(path: Path) -> str: + return path.read_text(encoding="utf-8") + + +def write_text(path: Path, content: str) -> None: + path.write_text(content, encoding="utf-8") + + +def load_branches() -> dict[str, Any]: + return json.loads(read_text(BRANCHES_PATH)) + + +def save_branches(data: dict[str, Any]) -> None: + write_text(BRANCHES_PATH, json.dumps(data, indent=2) + "\n") + + +def append_evidence(record: dict[str, Any]) -> None: + with EVIDENCE_PATH.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(record, ensure_ascii=True) + "\n") + + +def utc_stamp() -> str: + return datetime.now(timezone.utc).replace(microsecond=0).isoformat() + + +def extract_map_field(name: str) -> str | None: + prefix = f" {name}:" + for line in read_text(MAP_PATH).splitlines(): + if line.startswith(prefix): + return line.split(":", 1)[1].strip() + 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 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)}") + 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_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) + + 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()) +