Add sequential turn mutation receipts

This commit is contained in:
Meta Vens 2026-05-02 03:05:47 +01:00
commit aa11564cd0
23 changed files with 6061 additions and 28 deletions

View file

@ -0,0 +1,480 @@
"""Apply a reviewed sequential Ink branch mutation.
This is deliberately a reviewed replay, not an automatic social appraiser. It
reads the flawed-but-useful sequential Qwen capture, records the missing
participant appraisal/consolidation boundary as manual training data, and writes a mutated
agent-state fixture plus a mutation receipt.
"""
from __future__ import annotations
import argparse
import copy
import json
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_FIXTURE = ROOT / "examples" / "agent-state.cold-wake-story-lab.json"
DEFAULT_CAPTURE = ROOT / "experiments" / "ink" / "cold-wake-sanctuary-intake-qwen-sequential-v1.capture.json"
DEFAULT_OUT_STATE = ROOT / "examples" / "agent-state.cold-wake-story-lab.after-sanctuary-ledger.json"
DEFAULT_RECEIPT = ROOT / "experiments" / "ink" / "cold-wake-sanctuary-intake-qwen-sequential-v1.mutation.json"
EVENT_ID = "event-sanctuary-ledger-verification"
MAER_MEMORY_ID = "memory-maer-sella-verification-cost"
SELLA_MEMORY_ID = "memory-sella-maer-ledger-threat"
def load_json(path: Path) -> Any:
return json.loads(path.read_text(encoding="utf-8"))
def write_json(path: Path, payload: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
def find_agent(state: dict[str, Any], agent_id: str) -> dict[str, Any]:
return next(agent for agent in state["agents"] if agent["agent_id"] == agent_id)
def find_relationship(state: dict[str, Any], relationship_id: str) -> dict[str, Any]:
return next(rel for rel in state["relationships"] if rel["relationship_id"] == relationship_id)
def find_scene(state: dict[str, Any], scene_id: str) -> dict[str, Any]:
return next(scene for scene in state["scenes"] if scene["scene_id"] == scene_id)
def clamp(value: float) -> float:
return max(0.0, min(1.0, round(value, 3)))
def apply_delta(container: dict[str, Any], path: list[str], delta: float) -> tuple[float, float]:
target: Any = container
for key in path[:-1]:
target = target[key]
leaf = target[path[-1]]
before = leaf["current_activation"]
after = clamp(before + delta)
leaf["current_activation"] = after
return before, after
def set_activation(container: dict[str, Any], path: list[str], value: float) -> tuple[float, float]:
target: Any = container
for key in path[:-1]:
target = target[key]
leaf = target[path[-1]]
before = leaf["current_activation"]
after = clamp(value)
leaf["current_activation"] = after
return before, after
def ensure_list_item(items: list[Any], key: str, value: str, item: dict[str, Any]) -> None:
if not any(existing.get(key) == value for existing in items if isinstance(existing, dict)):
items.append(item)
def ensure_value(items: list[str], value: str) -> None:
if value not in items:
items.append(value)
def ensure_overlay(agent: dict[str, Any], observer_id: str, target_id: str) -> dict[str, Any]:
for overlay in agent["perceived_state_overlays"]:
if overlay["observer_agent_id"] == observer_id and overlay["target_agent_id"] == target_id:
return overlay
overlay = {
"observer_agent_id": observer_id,
"target_agent_id": target_id,
"perceived_dimensions": {},
"beliefs": [],
"distortions": [],
}
agent["perceived_state_overlays"].append(overlay)
return overlay
def update_perceived_dimension(overlay: dict[str, Any], name: str, observed: float, attributed: float, confidence: float) -> None:
overlay["perceived_dimensions"][name] = {
"observed_activation": clamp(observed),
"attributed_disposition": clamp(attributed),
"confidence": clamp(confidence),
}
def normalize_action_type(raw: str) -> str:
if raw == "speech":
return "speak"
if raw == "action":
return "mixed"
return raw
def main() -> int:
parser = argparse.ArgumentParser(description="Apply reviewed mutation from a sequential Ink branch capture.")
parser.add_argument("--fixture", type=Path, default=DEFAULT_FIXTURE)
parser.add_argument("--capture", type=Path, default=DEFAULT_CAPTURE)
parser.add_argument("--out-state", type=Path, default=DEFAULT_OUT_STATE)
parser.add_argument("--receipt", type=Path, default=DEFAULT_RECEIPT)
args = parser.parse_args()
source_state = load_json(args.fixture)
capture = load_json(args.capture)
state = copy.deepcopy(source_state)
selected = capture["passes"]["selected_observable_action"]
response = capture["passes"]["sella_response_generation"]["parsed_response"]["response"]
actor_action_type = normalize_action_type(selected.get("action_type", ""))
responder_action_type = normalize_action_type(response.get("action_type", ""))
maer_appraisal = {
"schema_version": "ghostlight.manual_participant_appraisal.v0",
"appraiser": "codex_manual_review",
"participant_agent_id": "maer_tidecall",
"trigger_observable_action": {
"actor_agent_id": "maer_tidecall",
"raw_action_type": selected.get("action_type"),
"canonical_action_type": actor_action_type,
"observable_action": selected.get("observable_action"),
"spoken_text": selected.get("spoken_text", ""),
},
"private_interpretation": "Sella's answer keeps rescue possible but refuses to let Maer's ledger threat define the cost of care.",
"attributed_motive": "Protect sanctuary integrity while leaving a narrow verification path open.",
"misread_risk": "Medium. Maer may hear verification as obstruction if grievance outruns his respect for Sella's capacity boundary.",
"state_deltas": [
{
"agent_id": "maer_tidecall",
"path": "canonical_state.situational_state.grievance_activation.current_activation",
"delta": 0.03,
"rationale": "Rescue remains conditional when Maer wanted immediate intake readiness.",
},
{
"agent_id": "maer_tidecall",
"path": "canonical_state.behavioral_dimensions.control_pressure.current_activation",
"delta": 0.02,
"rationale": "He now has to carry the verification boundary into the next move.",
},
],
"relationship_deltas": [
{
"relationship_id": "rel-maer-sella",
"path": "stance.trust.current_activation",
"delta": -0.01,
"rationale": "Sella did not simply trust Maer's ledger framing.",
},
{
"relationship_id": "rel-maer-sella",
"path": "stance.respect.current_activation",
"delta": 0.02,
"rationale": "She named the cost plainly and did not hide behind false capacity.",
},
{
"relationship_id": "rel-maer-sella",
"path": "stance.obligation.current_activation",
"delta": 0.03,
"rationale": "The route now owes verification work if it wants sanctuary intake.",
},
],
"next_action_constraints": [
"Maer should treat Sella's verification boundary as real scene state.",
"Maer should not assume Sella accepted or refused intake.",
"Maer may push, offer evidence, soften, or seek another route, but not erase the boundary.",
],
}
sella_appraisal = {
"schema_version": "ghostlight.manual_participant_appraisal.v0",
"appraiser": "codex_manual_review",
"participant_agent_id": "sella_ren",
"trigger_observable_action": {
"actor_agent_id": "maer_tidecall",
"raw_action_type": selected.get("action_type"),
"canonical_action_type": actor_action_type,
"observable_action": selected.get("observable_action"),
"spoken_text": selected.get("spoken_text", ""),
},
"private_interpretation": response["sella_private_interpretation"],
"attributed_motive": response["sella_attributed_motive"],
"misread_risk": response["misread_risk"],
"state_deltas": [
{
"agent_id": "sella_ren",
"path": "canonical_state.behavioral_dimensions.control_pressure.current_activation",
"delta": 0.04,
"rationale": "Maer's ledger-backed ask feels like pressure on sanctuary authority before Sella can verify the claim.",
},
{
"agent_id": "sella_ren",
"path": "canonical_state.situational_state.overstimulation.current_activation",
"delta": 0.03,
"rationale": "The slate and debt framing add cognitive load in an already overfull clinic.",
},
{
"agent_id": "sella_ren",
"path": "canonical_state.situational_state.grievance_activation.current_activation",
"delta": 0.04,
"rationale": "She hears rescue language converting care capacity into an owed route debt.",
},
],
"relationship_deltas": [
{
"relationship_id": "rel-sella-maer",
"path": "stance.trust.current_activation",
"delta": -0.03,
"rationale": "Sella trusts Maer's aim less in the moment because the approach pressures verification boundaries.",
},
{
"relationship_id": "rel-sella-maer",
"path": "stance.resentment.current_activation",
"delta": 0.05,
"rationale": "The ledger threat makes sanctuary capacity feel conscripted.",
},
{
"relationship_id": "rel-sella-maer",
"path": "stance.respect.current_activation",
"delta": 0.02,
"rationale": "He names the cost instead of hiding it, which she still respects.",
},
],
"next_action_constraints": [
"Sella should act from boundary-defense, not neutral triage calm.",
"Sella should demand verification before accepting intake.",
"Sella should not receive Maer's private intent as prompt context.",
"Sella should preserve the unresolved personhood question.",
],
"review_note": "This appraisal was added manually after noticing the first sequential capture fused Maer's event and Sella's response without a clean per-turn consolidation boundary.",
}
participant_appraisals = [maer_appraisal, sella_appraisal]
event = {
"event_id": EVENT_ID,
"kind": "dialogue",
"summary": "Maer made a ledger-backed sanctuary intake ask around a corrupted distress packet; Sella translated the ask into verification cost rather than clean acceptance or refusal.",
"participants": ["maer_tidecall", "sella_ren"],
"pressure_tags": [
"cold_wake",
"sanctuary_capacity",
"rescue_obligation",
"personhood_uncertainty",
"verification_boundary",
],
"observed_exchange": [
{
"speaker_id": "maer_tidecall",
"action_type": actor_action_type,
"utterance_summary": selected["spoken_text"],
"dialogue_function": "ledger_backed_capacity_ask",
"observable_cues": [
selected["observable_action"],
"points to distress vessel eligibility line item",
"frames refusal as route debt",
],
},
{
"speaker_id": "sella_ren",
"action_type": responder_action_type,
"utterance_summary": response["spoken_text"],
"dialogue_function": "demand_verification_before_intake",
"observable_cues": [
"acknowledges the slate and line item",
"names the bed cost directly",
"refuses to treat packet noise as either proof or non-personhood",
],
},
],
"private_interpretations": [
{
"agent_id": "maer_tidecall",
"interpretation": "Sella is not refusing rescue, but she is making verification the price of care and refusing to let Maer's ledger threat define the cost alone.",
"attributed_motive": "Protect sanctuary integrity while leaving a narrow route for rescue if the packet can produce a voice-like claim.",
"appraisal_tags": ["blocked_rescue", "boundary_respected", "verification_cost"],
"confidence": 0.61,
},
{
"agent_id": "sella_ren",
"interpretation": sella_appraisal["private_interpretation"],
"attributed_motive": sella_appraisal["attributed_motive"],
"appraisal_tags": ["capacity_threat", "verification_boundary", "possible_misread"],
"confidence": 0.68,
},
],
"event_effects": [
{
"agent_id": "maer_tidecall",
"summary": "Maer leaves the beat with rescue still live but more visibly conditional on Sella's verification boundary.",
"state_deltas": [
{"path": "canonical_state.situational_state.grievance_activation.current_activation", "delta": 0.03},
{"path": "canonical_state.behavioral_dimensions.control_pressure.current_activation", "delta": 0.02},
],
"memory_update_ids": [MAER_MEMORY_ID],
},
{
"agent_id": "sella_ren",
"summary": "Sella absorbs the ledger ask as pressure, defends verification, and records Maer as both sincere and dangerous to capacity boundaries.",
"state_deltas": [
{"path": "canonical_state.behavioral_dimensions.control_pressure.current_activation", "delta": 0.04},
{"path": "canonical_state.situational_state.overstimulation.current_activation", "delta": 0.03},
{"path": "canonical_state.situational_state.grievance_activation.current_activation", "delta": 0.04},
],
"memory_update_ids": [SELLA_MEMORY_ID],
},
],
}
if not any(existing["event_id"] == EVENT_ID for existing in state["events"]):
state["events"].append(event)
applied_changes: list[dict[str, Any]] = []
maer = find_agent(state, "maer_tidecall")
sella = find_agent(state, "sella_ren")
rel_maer_sella = find_relationship(state, "rel-maer-sella")
rel_sella_maer = find_relationship(state, "rel-sella-maer")
for path, delta in [
(["canonical_state", "situational_state", "grievance_activation"], 0.03),
(["canonical_state", "behavioral_dimensions", "control_pressure"], 0.02),
]:
before, after = apply_delta(maer, path, delta)
applied_changes.append({"target": "maer_tidecall", "path": ".".join(path) + ".current_activation", "before": before, "after": after})
for path, delta in [
(["canonical_state", "behavioral_dimensions", "control_pressure"], 0.04),
(["canonical_state", "situational_state", "overstimulation"], 0.03),
(["canonical_state", "situational_state", "grievance_activation"], 0.04),
]:
before, after = apply_delta(sella, path, delta)
applied_changes.append({"target": "sella_ren", "path": ".".join(path) + ".current_activation", "before": before, "after": after})
for rel, deltas in [
(rel_maer_sella, [("trust", -0.01), ("respect", 0.02), ("obligation", 0.03)]),
(rel_sella_maer, [("trust", -0.03), ("resentment", 0.05), ("respect", 0.02), ("obligation", 0.02)]),
]:
for name, delta in deltas:
before, after = apply_delta(rel, ["stance", name], delta)
applied_changes.append({"target": rel["relationship_id"], "path": f"stance.{name}.current_activation", "before": before, "after": after})
ensure_value(rel.setdefault("unresolved_incident_ids", []), EVENT_ID)
rel_maer_sella["summary"] = "Maer still trusts Sella's care, but now understands that she will make verification the cost of sanctuary intake rather than let route debt decide for her."
rel_sella_maer["summary"] = "Sella respects Maer's rescue ethic and now more sharply distrusts how quickly his ledger language can conscript sanctuary capacity."
ensure_list_item(
maer["memories"]["relationship_summaries"],
"memory_id",
MAER_MEMORY_ID,
{
"memory_id": MAER_MEMORY_ID,
"summary": "Sella answered Maer's ledger-backed intake ask by making verification the cost of care, not by cleanly accepting or refusing rescue.",
"salience": 0.77,
"confidence": 0.69,
"linked_event_ids": [EVENT_ID],
"linked_relationship_id": "rel-maer-sella",
},
)
ensure_list_item(
sella["memories"]["relationship_summaries"],
"memory_id",
SELLA_MEMORY_ID,
{
"memory_id": SELLA_MEMORY_ID,
"summary": "Maer made a ledger-backed rescue ask that sounded like a debt threat under scarcity; Sella held verification as the boundary.",
"salience": 0.81,
"confidence": 0.72,
"linked_event_ids": [EVENT_ID],
"linked_relationship_id": "rel-sella-maer",
},
)
maer_overlay = ensure_overlay(maer, "maer_tidecall", "sella_ren")
update_perceived_dimension(maer_overlay, "control_pressure", 0.66, 0.58, 0.55)
update_perceived_dimension(maer_overlay, "interpersonal_warmth", 0.68, 0.74, 0.58)
update_perceived_dimension(maer_overlay, "rigidity", 0.61, 0.56, 0.51)
ensure_list_item(
maer_overlay["beliefs"],
"belief_id",
"belief-maer-sella-verification-is-care",
{
"belief_id": "belief-maer-sella-verification-is-care",
"subject_id": "sella_ren",
"claim_type": "motive_inference",
"claim": "Sella is defending verification as part of care rather than using it as a polite refusal.",
"confidence": 0.61,
"evidence_event_ids": [EVENT_ID],
"visibility": "private",
"emotional_charge": 0.42,
},
)
ensure_value(maer_overlay["distortions"], "blocked_rescue_overread")
sella_overlay = ensure_overlay(sella, "sella_ren", "maer_tidecall")
update_perceived_dimension(sella_overlay, "control_pressure", 0.76, 0.64, 0.66)
update_perceived_dimension(sella_overlay, "interpersonal_warmth", 0.58, 0.64, 0.59)
update_perceived_dimension(sella_overlay, "rigidity", 0.58, 0.53, 0.52)
ensure_list_item(
sella_overlay["beliefs"],
"belief_id",
"belief-sella-maer-ledger-can-pressure-care",
{
"belief_id": "belief-sella-maer-ledger-can-pressure-care",
"subject_id": "maer_tidecall",
"claim_type": "motive_inference",
"claim": "Maer means rescue honestly, but his ledger language can turn sanctuary refusal into moral debt before verification has room to breathe.",
"confidence": 0.68,
"evidence_event_ids": [EVENT_ID],
"visibility": "private",
"emotional_charge": 0.57,
},
)
ensure_value(sella_overlay["distortions"], "pressure_overread")
scene = find_scene(state, "scene-02-sanctuary-intake")
for pack in scene["dialogue_context_packs"]:
if pack["speaker_agent_id"] == "maer_tidecall":
ensure_value(pack["active_memories"], MAER_MEMORY_ID)
ensure_value(pack["speaker_beliefs"], "Sella is likely to treat verification as part of care, not as a refusal to help.")
if pack["speaker_agent_id"] == "sella_ren":
ensure_value(pack["active_memories"], SELLA_MEMORY_ID)
ensure_value(pack["speaker_beliefs"], "Maer's rescue ask can become pressure if it turns refusal into route debt before verification.")
receipt = {
"schema_version": "ghostlight.reviewed_state_mutation.v0",
"mutation_id": "mutation-sanctuary-ledger-verification-v1",
"source_fixture_ref": str(args.fixture.relative_to(ROOT)).replace("\\", "/"),
"source_capture_ref": str(args.capture.relative_to(ROOT)).replace("\\", "/"),
"mutated_fixture_ref": str(args.out_state.relative_to(ROOT)).replace("\\", "/"),
"selected_branch_id": selected["branch_id"],
"event_id": EVENT_ID,
"input_capture_limitation": "The source capture generated Sella's response before Ghostlight had a clean per-turn participant appraisal/consolidation boundary; this receipt manually reviews the missing boundary and applies it as training data.",
"normalized_action_types": {
"actor_raw": selected.get("action_type"),
"actor_canonical": actor_action_type,
"responder_raw": response.get("action_type"),
"responder_canonical": responder_action_type,
},
"participant_appraisals": participant_appraisals,
"observed_action": event["observed_exchange"][0],
"observed_response": event["observed_exchange"][1],
"applied_mutations": applied_changes,
"manual_review_notes": [
"Every involved character receives a state or perception update after the event.",
"The selected event is consolidated before Sella is treated as the next actor.",
"The corrupted packet's personhood remains unresolved.",
"Ink variables remain playthrough-local; canonical state changes are written only through this reviewed receipt.",
],
"deferred_mutations": [
"No world-level sanctuary bed is opened or closed by this beat.",
"No claimant/personhood truth is resolved.",
"No automatic classifier is trained yet; this is supervised seed data.",
],
}
write_json(args.out_state, state)
write_json(args.receipt, receipt)
print(f"wrote {args.out_state.relative_to(ROOT)}")
print(f"wrote {args.receipt.relative_to(ROOT)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -0,0 +1,538 @@
"""Run a sequential Qwen Ink generation prototype.
Pass 1: generate Maer choices from Maer-local awareness only.
Pass 2: generate participant appraisal/consolidation for the selected
observable event.
Pass 3: generate the next actor's action from updated local state.
"""
from __future__ import annotations
import argparse
import json
import re
import urllib.request
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_ENDPOINT = "http://192.168.1.84:11434/api/generate"
DEFAULT_FIXTURE = ROOT / "examples" / "agent-state.cold-wake-story-lab.json"
DEFAULT_ANNOTATION = ROOT / "examples" / "ink" / "cold-wake-sanctuary-intake.training.json"
DEFAULT_OUT_DIR = ROOT / "experiments" / "ink"
VALID_ACTION_TYPES = {
"speak",
"silence",
"move",
"gesture",
"touch_object",
"block_object",
"use_object",
"show_object",
"withhold_object",
"transfer_object",
"spend_resource",
"attack",
"wait",
"mixed",
}
def load_json(path: Path) -> Any:
return json.loads(path.read_text(encoding="utf-8"))
def write_text(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
def write_json(path: Path, payload: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
def find_agent(fixture: dict[str, Any], agent_id: str) -> dict[str, Any]:
return next(agent for agent in fixture["agents"] if agent["agent_id"] == agent_id)
def find_scene(fixture: dict[str, Any], scene_id: str) -> dict[str, Any]:
return next(scene for scene in fixture["scenes"] if scene["scene_id"] == scene_id)
def find_pack(scene: dict[str, Any], speaker_id: str) -> dict[str, Any]:
return next(pack for pack in scene["dialogue_context_packs"] if pack["speaker_agent_id"] == speaker_id)
def find_relationship(fixture: dict[str, Any], source_id: str, target_id: str) -> dict[str, Any]:
return next(rel for rel in fixture["relationships"] if rel["source_id"] == source_id and rel["target_id"] == target_id)
def memory_summaries(agent: dict[str, Any], memory_ids: list[str]) -> list[str]:
summaries: list[str] = []
for group in agent["memories"].values():
for memory in group:
if memory["memory_id"] in memory_ids:
summaries.append(f"{memory['memory_id']}: {memory['summary']}")
return summaries
def goal_summaries(agent: dict[str, Any], goal_ids: list[str]) -> list[str]:
return [
f"{goal['goal_id']}: {goal['description']} Priority {goal['priority']}. Stake: {goal['emotional_stake']}"
for goal in agent["goals"]
if goal["goal_id"] in goal_ids
]
def selected_variables(agent: dict[str, Any]) -> dict[str, dict[str, float]]:
groups = agent["canonical_state"]
names_by_group = {
"behavioral_dimensions": ["interpersonal_warmth", "control_pressure", "suspicion", "rigidity", "volatility"],
"presentation_strategy": ["detachment", "competence_theater", "strategic_opacity", "ironic_distance"],
"voice_style": ["formality", "lexical_precision", "ritualized_address", "verbal_warmth", "pointedness"],
"situational_state": ["exhaustion", "panic", "grievance_activation", "overstimulation"],
}
selected: dict[str, dict[str, float]] = {}
for group_name, variable_names in names_by_group.items():
selected[group_name] = {
name: groups[group_name][name]["current_activation"]
for name in variable_names
if name in groups[group_name]
}
return selected
def post_json(endpoint: str, payload: dict[str, Any]) -> dict[str, Any]:
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
request = urllib.request.Request(
endpoint,
data=data,
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=180) as response:
return json.loads(response.read().decode("utf-8"))
def extract_json_object(text: str) -> Any | None:
stripped = text.strip()
if stripped.startswith("{"):
return json.loads(stripped)
fenced = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", stripped, re.DOTALL)
if fenced:
return json.loads(fenced.group(1))
start = stripped.find("{")
end = stripped.rfind("}")
if start != -1 and end != -1 and end > start:
return json.loads(stripped[start : end + 1])
return None
def request_qwen(endpoint: str, model: str, prompt: str, temperature: float, top_p: float, num_ctx: int) -> tuple[dict[str, Any], str, Any, list[str]]:
request_payload = {
"model": model,
"prompt": prompt,
"stream": False,
"think": False,
"keep_alive": "10m",
"options": {"num_ctx": num_ctx, "temperature": temperature, "top_p": top_p},
}
raw = post_json(endpoint, request_payload)
response_text = raw.get("response", "").strip()
parsed = None
notes: list[str] = []
try:
parsed = extract_json_object(response_text)
except (json.JSONDecodeError, TypeError) as exc:
notes.append(f"parse error: {exc}")
if parsed is None:
notes.append("could not parse JSON")
return raw, response_text, parsed, notes
def observable_action_payload(actor_id: str, selected_choice: dict[str, Any]) -> dict[str, Any]:
return {
"actor_id": actor_id,
"action_type": selected_choice["action_type"],
"observable_action": selected_choice["observable_action"],
"spoken_text": selected_choice.get("spoken_text", ""),
}
def build_maer_prompt(fixture: dict[str, Any], annotation: dict[str, Any]) -> str:
scene_id = annotation["scene_id"]
actor_id = annotation["protagonist_agent_id"]
responder_id = annotation["npc_agent_ids"][0]
scene = find_scene(fixture, scene_id)
actor = find_agent(fixture, actor_id)
pack = find_pack(scene, actor_id)
rel_actor_to_responder = find_relationship(fixture, actor_id, responder_id)
payload = {
"task": "Generate candidate player choices for Maer only. Do not write Sella's response.",
"output_contract": {
"format": "Return only JSON. No markdown. No commentary.",
"root_keys": ["choices"],
"choice_count": 4,
"valid_action_types": sorted(VALID_ACTION_TYPES),
"choice_fields": [
"branch_id",
"ink_path",
"choice_text",
"action_type",
"actor_intent_private",
"observable_action",
"spoken_text",
"state_basis",
"expected_consequence_surfaces",
"training_hooks",
],
},
"hard_rules": [
"Use only Maer's local awareness and scene-observable facts.",
"Do not include Sella's private state, private motives, or future response.",
"Do not resolve whether the corrupted packet contains a person.",
"Include at least two non-speech choices.",
f"Use action_type values only from this exact enum: {', '.join(sorted(VALID_ACTION_TYPES))}.",
"The selected branch must be reducible to observable action for Sella.",
"Use semantic training hooks, not branch ids.",
],
"scene_observable_context": {
"scene_id": scene_id,
"location": scene["location"],
"public_stakes": scene["public_stakes"],
},
"maer_local_awareness": {
"identity": actor["identity"],
"local_truth": pack["speaker_local_truth"],
"beliefs": pack["speaker_beliefs"],
"goals": goal_summaries(actor, pack["active_goals"]),
"memories": memory_summaries(actor, pack["active_memories"]),
"relationship_read": rel_actor_to_responder["summary"],
"presentation_constraints": pack["presentation_constraints"],
"selected_current_activation": selected_variables(actor),
},
"projection_controls_visible_to_maer_choice_generation": annotation["projection_controls"],
}
return (
"You are Ghostlight's Maer-local choice generator. Generate only Maer's player choices.\n"
"Do not write Sella's response or private interpretation. Return valid JSON only.\n\n"
+ json.dumps(payload, indent=2, ensure_ascii=False)
)
def sella_local_payload(fixture: dict[str, Any], annotation: dict[str, Any]) -> dict[str, Any]:
scene_id = annotation["scene_id"]
responder_id = annotation["npc_agent_ids"][0]
actor_id = annotation["protagonist_agent_id"]
scene = find_scene(fixture, scene_id)
responder = find_agent(fixture, responder_id)
pack = find_pack(scene, responder_id)
rel_responder_to_actor = find_relationship(fixture, responder_id, actor_id)
return {
"identity": responder["identity"],
"local_truth": pack["speaker_local_truth"],
"beliefs": pack["speaker_beliefs"],
"goals": goal_summaries(responder, pack["active_goals"]),
"memories": memory_summaries(responder, pack["active_memories"]),
"relationship_read": rel_responder_to_actor["summary"],
"presentation_constraints": pack["presentation_constraints"],
"selected_current_activation": selected_variables(responder),
}
def build_sella_appraisal_prompt(fixture: dict[str, Any], annotation: dict[str, Any], selected_choice: dict[str, Any]) -> str:
scene_id = annotation["scene_id"]
responder_id = annotation["npc_agent_ids"][0]
actor_id = annotation["protagonist_agent_id"]
scene = find_scene(fixture, scene_id)
payload = {
"task": "Generate Sella's participant appraisal/consolidation for one observable Maer event.",
"output_contract": {
"format": "Return only JSON. No markdown. No commentary.",
"root_keys": ["appraisal"],
"appraisal_fields": [
"responder_agent_id",
"private_interpretation",
"attributed_motive",
"misread_risk",
"immediate_state_deltas",
"relationship_deltas",
"belief_updates",
"response_constraints",
],
},
"hard_rules": [
"Use only Sella's local awareness plus the observable Maer action.",
"Do not read Maer's private intent. Treat actor intent as unavailable.",
"Sella may correctly read, partially read, or misread Maer's action.",
"Do not resolve whether the corrupted packet contains a person.",
"This pass proposes reviewed state changes for Sella caused by the event. Do not write Sella's next action.",
"Keep deltas small and bounded between -0.20 and 0.20.",
],
"scene_observable_context": {
"scene_id": scene_id,
"location": scene["location"],
"public_stakes": scene["public_stakes"],
},
"observable_maer_action": observable_action_payload(actor_id, selected_choice),
"sella_local_awareness": sella_local_payload(fixture, annotation),
"projection_controls_visible_to_sella_appraisal": annotation["projection_controls"],
}
return (
"You are Ghostlight's Sella-local appraisal generator. Generate only Sella's immediate internal appraisal.\n"
"Do not use Maer's private intent. Do not write her response. Return valid JSON only.\n\n"
+ json.dumps(payload, indent=2, ensure_ascii=False)
)
def build_sella_prompt(
fixture: dict[str, Any],
annotation: dict[str, Any],
selected_choice: dict[str, Any],
appraisal: dict[str, Any] | None,
) -> str:
scene_id = annotation["scene_id"]
responder_id = annotation["npc_agent_ids"][0]
actor_id = annotation["protagonist_agent_id"]
scene = find_scene(fixture, scene_id)
payload = {
"task": "Generate Sella's next action from Sella-local awareness after applying reviewed event appraisal.",
"output_contract": {
"format": "Return only JSON. No markdown. No commentary.",
"root_keys": ["response"],
"valid_action_types": sorted(VALID_ACTION_TYPES),
"response_fields": [
"responder_agent_id",
"action_type",
"observable_response",
"spoken_text",
"sella_private_interpretation",
"sella_attributed_motive",
"misread_risk",
"state_basis",
"reviewed_consequences",
"training_hooks",
],
},
"hard_rules": [
"Use only Sella's local awareness, the observable Maer event, and reviewed Sella state changes from that event.",
"Do not read Maer's private intent. Treat actor intent as unavailable.",
"Sella may correctly read, partially read, or misread Maer's action.",
"Do not resolve whether the corrupted packet contains a person.",
"Do not accept without cost, condition, authority defense, or resentment risk.",
f"Use action_type values only from this exact enum: {', '.join(sorted(VALID_ACTION_TYPES))}.",
"Use semantic training hooks, not branch ids.",
],
"scene_observable_context": {
"scene_id": scene_id,
"location": scene["location"],
"public_stakes": scene["public_stakes"],
},
"observable_maer_action": observable_action_payload(actor_id, selected_choice),
"sella_immediate_appraisal": appraisal,
"sella_local_awareness": sella_local_payload(fixture, annotation),
"projection_controls_visible_to_sella_response_generation": annotation["projection_controls"],
}
return (
"You are Ghostlight's Sella-local next-action generator. Generate only Sella's next action.\n"
"Use reviewed event appraisal as the changed state she is acting from. Return valid JSON only.\n\n"
+ json.dumps(payload, indent=2, ensure_ascii=False)
)
def validate_choice_payload(parsed: Any) -> list[str]:
notes: list[str] = []
if not isinstance(parsed, dict):
return ["choice response was not an object"]
choices = parsed.get("choices")
if not isinstance(choices, list):
return ["choice response missing choices array"]
if len(choices) != 4:
notes.append(f"expected 4 choices, got {len(choices)}")
required = ["branch_id", "ink_path", "choice_text", "action_type", "actor_intent_private", "observable_action", "state_basis", "expected_consequence_surfaces", "training_hooks"]
non_speech = 0
for index, choice in enumerate(choices):
if not isinstance(choice, dict):
notes.append(f"choices[{index}] was not an object")
continue
missing = [key for key in required if key not in choice]
if missing:
notes.append(f"choices[{index}] missing keys: {', '.join(missing)}")
if choice.get("action_type") not in VALID_ACTION_TYPES:
notes.append(f"choices[{index}] invalid action_type")
for list_key in ["expected_consequence_surfaces", "training_hooks"]:
if not isinstance(choice.get(list_key), list):
notes.append(f"choices[{index}] {list_key} must be an array")
if choice.get("action_type") != "speak":
non_speech += 1
if non_speech < 2:
notes.append("choices had fewer than two non-speech actions")
return notes
def validate_appraisal_payload(parsed: Any) -> list[str]:
if not isinstance(parsed, dict):
return ["appraisal was not an object"]
appraisal = parsed.get("appraisal")
if not isinstance(appraisal, dict):
return ["appraisal missing appraisal object"]
required = [
"responder_agent_id",
"private_interpretation",
"attributed_motive",
"misread_risk",
"immediate_state_deltas",
"relationship_deltas",
"response_constraints",
]
missing = [key for key in required if key not in appraisal]
notes = [f"appraisal missing keys: {', '.join(missing)}"] if missing else []
for list_key in ["immediate_state_deltas", "relationship_deltas", "response_constraints"]:
if list_key in appraisal and not isinstance(appraisal[list_key], list):
notes.append(f"appraisal.{list_key} must be an array")
return notes
def validate_response_payload(parsed: Any) -> list[str]:
if not isinstance(parsed, dict):
return ["response was not an object"]
response = parsed.get("response")
if not isinstance(response, dict):
return ["response missing response object"]
required = ["responder_agent_id", "action_type", "observable_response", "sella_private_interpretation", "misread_risk", "state_basis", "reviewed_consequences", "training_hooks"]
missing = [key for key in required if key not in response]
notes = [f"response missing keys: {', '.join(missing)}"] if missing else []
if response.get("action_type") not in VALID_ACTION_TYPES:
notes.append("response invalid action_type")
if "training_hooks" in response and not isinstance(response["training_hooks"], list):
notes.append("response.training_hooks must be an array")
return notes
def choose_selected_choice(parsed: Any, preferred_action: str) -> dict[str, Any]:
choices = parsed.get("choices", []) if isinstance(parsed, dict) else []
for choice in choices:
if choice.get("action_type") == preferred_action:
return choice
if choices:
return choices[0]
raise SystemExit("No choices available to select")
def main() -> int:
parser = argparse.ArgumentParser(description="Run a sequential local-awareness Qwen Ink prototype.")
parser.add_argument("--fixture", type=Path, default=DEFAULT_FIXTURE)
parser.add_argument("--annotation", type=Path, default=DEFAULT_ANNOTATION)
parser.add_argument("--out-dir", type=Path, default=DEFAULT_OUT_DIR)
parser.add_argument("--endpoint", default=DEFAULT_ENDPOINT)
parser.add_argument("--model", default="qwen3.5:9b")
parser.add_argument("--temperature", type=float, default=0.55)
parser.add_argument("--top-p", type=float, default=0.9)
parser.add_argument("--num-ctx", type=int, default=8192)
parser.add_argument("--capture-id", default="cold-wake-sanctuary-intake.qwen-sequential.v1")
parser.add_argument("--preferred-action", default="show_object")
args = parser.parse_args()
fixture = load_json(args.fixture)
annotation = load_json(args.annotation)
maer_prompt = build_maer_prompt(fixture, annotation)
maer_raw, maer_response_text, maer_parsed, maer_notes = request_qwen(
args.endpoint, args.model, maer_prompt, args.temperature, args.top_p, args.num_ctx
)
maer_notes.extend(validate_choice_payload(maer_parsed))
selected_choice = choose_selected_choice(maer_parsed, args.preferred_action)
sella_appraisal_prompt = build_sella_appraisal_prompt(fixture, annotation, selected_choice)
sella_appraisal_raw, sella_appraisal_response_text, sella_appraisal_parsed, sella_appraisal_notes = request_qwen(
args.endpoint, args.model, sella_appraisal_prompt, args.temperature, args.top_p, args.num_ctx
)
sella_appraisal_notes.extend(validate_appraisal_payload(sella_appraisal_parsed))
appraisal = sella_appraisal_parsed.get("appraisal") if isinstance(sella_appraisal_parsed, dict) else None
sella_prompt = build_sella_prompt(fixture, annotation, selected_choice, appraisal)
sella_raw, sella_response_text, sella_parsed, sella_notes = request_qwen(
args.endpoint, args.model, sella_prompt, args.temperature, args.top_p, args.num_ctx
)
sella_notes.extend(validate_response_payload(sella_parsed))
all_notes = maer_notes + sella_appraisal_notes + sella_notes
capture = {
"schema_version": "ghostlight.qwen_ink_sequential_capture.v0",
"capture_id": args.capture_id,
"source_fixture_ref": str(args.fixture.relative_to(ROOT)).replace("\\", "/"),
"source_annotation_ref": str(args.annotation.relative_to(ROOT)).replace("\\", "/"),
"model": maer_raw.get("model", args.model),
"endpoint": args.endpoint,
"request_options": {
"think": False,
"num_ctx": args.num_ctx,
"temperature": args.temperature,
"top_p": args.top_p,
},
"passes": {
"maer_choice_generation": {
"local_agent_id": "maer_tidecall",
"prompt_text": maer_prompt,
"response_text": maer_response_text,
"parsed_response": maer_parsed,
"validation_notes": maer_notes,
},
"selected_observable_action": selected_choice,
"sella_immediate_appraisal": {
"local_agent_id": "sella_ren",
"prompt_text": sella_appraisal_prompt,
"response_text": sella_appraisal_response_text,
"parsed_response": sella_appraisal_parsed,
"validation_notes": sella_appraisal_notes,
},
"sella_response_generation": {
"local_agent_id": "sella_ren",
"prompt_text": sella_prompt,
"response_text": sella_response_text,
"parsed_response": sella_parsed,
"validation_notes": sella_notes,
},
},
"review": {
"status": "accepted_as_draft" if not all_notes else "useful_needs_revision",
"strengths": [
"Separated Maer choice generation from Sella next-action generation.",
"Inserted participant appraisal/consolidation before next-actor action generation.",
"Sella prompt received observable Maer event and reviewed Sella state changes, not Maer's private intent.",
],
"failure_notes": all_notes,
"accepted_into_ink_ref": None,
"pipeline_lessons": [
"Sequential generation needs event appraisal/consolidation before next actor selection.",
"Action type selection should be tool-shaped or schema-constrained, not left to prose compliance.",
"Next pass should materialize the sequential capture into Ink and mutation training data.",
],
},
}
args.out_dir.mkdir(parents=True, exist_ok=True)
base = args.capture_id.replace(".", "-")
capture_path = args.out_dir / f"{base}.capture.json"
maer_prompt_path = args.out_dir / f"{base}.maer.prompt.md"
maer_response_path = args.out_dir / f"{base}.maer.response.md"
sella_appraisal_prompt_path = args.out_dir / f"{base}.sella-appraisal.prompt.md"
sella_appraisal_response_path = args.out_dir / f"{base}.sella-appraisal.response.md"
sella_prompt_path = args.out_dir / f"{base}.sella.prompt.md"
sella_response_path = args.out_dir / f"{base}.sella.response.md"
write_json(capture_path, capture)
write_text(maer_prompt_path, maer_prompt + "\n")
write_text(maer_response_path, maer_response_text + "\n")
write_text(sella_appraisal_prompt_path, sella_appraisal_prompt + "\n")
write_text(sella_appraisal_response_path, sella_appraisal_response_text + "\n")
write_text(sella_prompt_path, sella_prompt + "\n")
write_text(sella_response_path, sella_response_text + "\n")
print(f"wrote {capture_path.relative_to(ROOT)}")
print(json.dumps({"selected_observable_action": selected_choice, "sella_appraisal": sella_appraisal_parsed, "sella_response": sella_parsed}, indent=2, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -14,6 +14,7 @@ from typing import Any
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_INK_FILES = sorted((ROOT / "examples" / "ink").glob("*.ink"))
DEFAULT_QWEN_INK_CAPTURES = sorted((ROOT / "experiments" / "ink").glob("*.capture.json"))
DEFAULT_MUTATION_RECEIPTS = sorted((ROOT / "experiments" / "ink").glob("*.mutation.json"))
VALID_ACTION_TYPES = {
"speak",
"silence",
@ -47,6 +48,11 @@ def require_keys(obj: dict[str, Any], keys: list[str], path: str) -> None:
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_json(path: Path) -> Any:
return json.loads(path.read_text(encoding="utf-8"))
@ -223,6 +229,9 @@ def validate_annotation(path: Path, ink_path: Path) -> None:
def validate_qwen_ink_capture(path: Path) -> None:
data = load_json(path)
require(isinstance(data, dict), f"{path} must be an object")
if data.get("schema_version") == "ghostlight.qwen_ink_sequential_capture.v0":
validate_qwen_ink_sequential_capture(path, data)
return
require_keys(
data,
[
@ -285,6 +294,123 @@ def validate_qwen_ink_capture(path: Path) -> None:
require((ROOT / accepted_ref).exists(), f"{path}.review.accepted_into_ink_ref does not exist")
def validate_action_type_or_review_note(action_type: Any, review_status: str, path: str) -> None:
if action_type in VALID_ACTION_TYPES:
return
require(
review_status in {"needs_revision", "useful_needs_revision", "rejected"},
f"{path} has invalid action_type but review.status is not a revision/rejection status",
)
def validate_qwen_ink_sequential_capture(path: Path, data: dict[str, Any]) -> None:
require_keys(
data,
[
"schema_version",
"capture_id",
"source_fixture_ref",
"source_annotation_ref",
"model",
"endpoint",
"request_options",
"passes",
"review",
],
str(path),
)
require((ROOT / data["source_fixture_ref"]).exists(), f"{path}.source_fixture_ref does not exist")
require((ROOT / data["source_annotation_ref"]).exists(), f"{path}.source_annotation_ref does not exist")
review = data["review"]
require(isinstance(review, dict), f"{path}.review must be an object")
require_keys(review, ["status", "strengths", "failure_notes", "accepted_into_ink_ref", "pipeline_lessons"], f"{path}.review")
review_status = review["status"]
require(review_status in VALID_CAPTURE_REVIEW_STATUSES, f"{path}.review.status is invalid or unreviewed")
passes = data["passes"]
require_keys(passes, ["maer_choice_generation", "selected_observable_action", "sella_response_generation"], f"{path}.passes")
if "sella_immediate_appraisal" not in passes:
require(
review_status in {"needs_revision", "useful_needs_revision", "rejected"},
f"{path}.passes missing sella_immediate_appraisal but review.status is not a revision/rejection status",
)
for pass_key in ["maer_choice_generation", "sella_response_generation"]:
pass_payload = passes[pass_key]
require_keys(pass_payload, ["local_agent_id", "prompt_text", "response_text", "parsed_response", "validation_notes"], f"{path}.passes.{pass_key}")
require(isinstance(pass_payload["prompt_text"], str) and pass_payload["prompt_text"].strip(), f"{path}.passes.{pass_key}.prompt_text must be non-empty")
require(isinstance(pass_payload["response_text"], str) and pass_payload["response_text"].strip(), f"{path}.passes.{pass_key}.response_text must be non-empty")
require(isinstance(pass_payload["validation_notes"], list), f"{path}.passes.{pass_key}.validation_notes must be an array")
if "sella_immediate_appraisal" in passes:
pass_payload = passes["sella_immediate_appraisal"]
require_keys(pass_payload, ["local_agent_id", "prompt_text", "response_text", "parsed_response", "validation_notes"], f"{path}.passes.sella_immediate_appraisal")
if review_status in {"accepted", "accepted_as_draft"}:
appraisal_root = pass_payload["parsed_response"]
require(isinstance(appraisal_root, dict), f"{path}.passes.sella_immediate_appraisal.parsed_response must be an object")
appraisal = appraisal_root.get("appraisal")
require(isinstance(appraisal, dict), f"{path}.passes.sella_immediate_appraisal.parsed_response.appraisal must be an object")
for list_key in ["immediate_state_deltas", "relationship_deltas", "response_constraints"]:
require(isinstance(appraisal.get(list_key), list), f"{path}.passes.sella_immediate_appraisal.appraisal.{list_key} must be an array for accepted captures")
choice = passes["selected_observable_action"]
require(isinstance(choice, dict), f"{path}.passes.selected_observable_action must be an object")
require_keys(choice, ["branch_id", "ink_path", "choice_text", "action_type", "observable_action"], f"{path}.passes.selected_observable_action")
validate_action_type_or_review_note(choice["action_type"], review_status, f"{path}.passes.selected_observable_action.action_type")
if review_status in {"accepted", "accepted_as_draft"}:
for list_key in ["expected_consequence_surfaces", "training_hooks"]:
require(isinstance(choice.get(list_key), list), f"{path}.passes.selected_observable_action.{list_key} must be an array for accepted captures")
response = passes["sella_response_generation"]["parsed_response"]
require(isinstance(response, dict), f"{path}.passes.sella_response_generation.parsed_response must be an object")
response_obj = response.get("response")
require(isinstance(response_obj, dict), f"{path}.passes.sella_response_generation.parsed_response.response must be an object")
require_keys(response_obj, ["responder_agent_id", "action_type", "observable_response", "sella_private_interpretation", "misread_risk"], f"{path}.passes.sella_response_generation.response")
validate_action_type_or_review_note(response_obj["action_type"], review_status, f"{path}.passes.sella_response_generation.response.action_type")
if review_status in {"accepted", "accepted_as_draft"}:
require(isinstance(response_obj.get("training_hooks"), list), f"{path}.passes.sella_response_generation.response.training_hooks must be an array for accepted captures")
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")
@ -305,6 +431,9 @@ def main() -> int:
for path in DEFAULT_QWEN_INK_CAPTURES:
validate_qwen_ink_capture(path)
print(f"ok: {path}")
for path in DEFAULT_MUTATION_RECEIPTS:
validate_mutation_receipt(path)
print(f"ok: {path}")
return 0