Add projected local context seam

This commit is contained in:
Meta Vens 2026-05-02 03:47:03 +01:00
commit b3a68416e7
20 changed files with 2405 additions and 87 deletions

View file

@ -0,0 +1,83 @@
# Projected Local Context
The projected local context is the missing seam between canonical Ghostlight
state and a character agent.
Canonical state is storage. It can contain means, plasticity, activation,
relationship stance, memories, culture, goals, and author-facing source paths.
A character response model should not have to interpret that machinery. It
should receive a compact operating context: what this character knows, wants,
misreads, can do, sounds like, and must not resolve.
## Contract
Pipeline:
```text
canonical state + scene + reviewed annotation
-> projector/state interpreter
-> ghostlight.projected_local_context.v0
-> response-model prompt
-> generated action proposal
```
The projected context may retain source references for audit. The rendered
prompt text must not expose raw state internals such as `current_activation`,
`plasticity`, means, or selected numeric dimensions.
## Artifact Shape
Schema: `schemas/projected-local-context.schema.json`
Validator: `tools/validate_projected_contexts.py`
Generator: `tools/project_local_context.py`
Current examples:
- `examples/projected-contexts/scene-02-sanctuary-intake.maer_tidecall.projected-context.json`
- `examples/projected-contexts/scene-02-sanctuary-intake.sella_ren.projected-context.json`
The context contains:
- speaker identity and setting
- known facts and speaker beliefs
- current stakes
- active inner pressures rendered as ordinary language
- relationship read and known biases
- tensions
- action affordances
- projection controls
- voice surface
- likely response moves
- do-not-invent boundaries
- rendered prompt text
## Runtime Boundary
The character model receives local operating context, not omniscient truth. If
Maer acts, Sella's next pass receives only the observable event and Sella's own
local context. Maer's private intent is not included.
The sequential runtime still owns:
- tool contracts
- action enums
- event proposal capture
- participant appraisal
- reviewed mutation
- Ink materialization
The projector owns the translation from Ghostlight's internal state language to
character-local operating prose.
## Current Limit
The first projector is deterministic and deliberately simple. It uses threshold
language like "dominant", "strong", "present", and "background" rather than
numeric scores. This is enough to remove raw state soup from Qwen prompts and
create inspectable training artifacts.
Later versions can become smarter, but they should still preserve this boundary:
response models act from projected local context; they do not become ad hoc
interpreters of the canonical schema.

View file

@ -0,0 +1,326 @@
{
"schema_version": "ghostlight.projected_local_context.v0",
"projection_id": "scene-02-sanctuary-intake.maer_tidecall.scene_turn",
"input": {
"fixture_ref": "examples/agent-state.cold-wake-story-lab.json",
"annotation_ref": "examples/ink/cold-wake-sanctuary-intake.training.json",
"scene_id": "scene-02-sanctuary-intake",
"local_agent_id": "maer_tidecall",
"listener_ids": [
"sella_ren"
],
"projection_mode": "scene_turn"
},
"context": {
"local_agent_id": "maer_tidecall",
"identity": "Maer Tidecall: Navigator route steward, Ganymede corridor compact delegate. Origin: Cetacean Navigator corridor culture, Ganymede route institutions. A soft-spoken route steward whose calm tends to make hurried people feel judged by the furniture.",
"setting": "Aya-aligned intake clinic tucked behind Ganymede dockside pumpworks. Aetheria pre-Elysium historical flashpoint: Cold Wake Panic, 2893, during the Cold Wake Panic.",
"known_facts": [
{
"text": "Sella's clinic is nearly full.",
"source_refs": [
"scenes.scene-02-sanctuary-intake.dialogue_context_packs.maer_tidecall.speaker_local_truth[0]"
]
},
{
"text": "The packet may be testimony or noise.",
"source_refs": [
"scenes.scene-02-sanctuary-intake.dialogue_context_packs.maer_tidecall.speaker_local_truth[1]"
]
},
{
"text": "If no one prepares intake, rescue becomes theater.",
"source_refs": [
"scenes.scene-02-sanctuary-intake.dialogue_context_packs.maer_tidecall.speaker_local_truth[2]"
]
},
{
"text": "Speaker belief: Sella will not hide behind false capacity.",
"source_refs": [
"scenes.scene-02-sanctuary-intake.dialogue_context_packs.maer_tidecall.speaker_beliefs[0]"
]
},
{
"text": "Speaker belief: Asking her for help may be necessary and unfair.",
"source_refs": [
"scenes.scene-02-sanctuary-intake.dialogue_context_packs.maer_tidecall.speaker_beliefs[1]"
]
}
],
"current_stakes": [
{
"text": "The distress vessel has sent a corrupted packet that may contain medical telemetry, firmware noise, or testimony.",
"source_refs": [
"scenes.scene-02-sanctuary-intake.public_stakes[0]"
]
},
{
"text": "Sanctuary beds and repair capacity are nearly exhausted.",
"source_refs": [
"scenes.scene-02-sanctuary-intake.public_stakes[1]"
]
},
{
"text": "Maer wants Sella to keep a place open if rescue succeeds.",
"source_refs": [
"scenes.scene-02-sanctuary-intake.public_stakes[2]"
]
}
],
"active_inner_pressures": [
{
"text": "Strong pressure: expects hidden motives or missing information.",
"source_refs": [
"agents.maer_tidecall.canonical_state.behavioral_dimensions.suspicion"
]
},
{
"text": "Strong pressure: needs the situation to become governable.",
"source_refs": [
"agents.maer_tidecall.canonical_state.behavioral_dimensions.control_pressure"
]
},
{
"text": "Strong pressure: feels risk before it becomes visible.",
"source_refs": [
"agents.maer_tidecall.canonical_state.behavioral_dimensions.anxiety"
]
},
{
"text": "Present pressure: leans on structure when uncertainty rises.",
"source_refs": [
"agents.maer_tidecall.canonical_state.behavioral_dimensions.rigidity"
]
},
{
"text": "Strong pressure: carries a live sense of unfairness.",
"source_refs": [
"agents.maer_tidecall.canonical_state.situational_state.grievance_activation"
]
},
{
"text": "Present pressure: has less spare tolerance than the words may show.",
"source_refs": [
"agents.maer_tidecall.canonical_state.situational_state.exhaustion"
]
},
{
"text": "Present pressure: is taking in more demand than can be cleanly sorted.",
"source_refs": [
"agents.maer_tidecall.canonical_state.situational_state.overstimulation"
]
},
{
"text": "Present pressure: keeps feeling at a controlled distance.",
"source_refs": [
"agents.maer_tidecall.canonical_state.presentation_strategy.detachment"
]
},
{
"text": "Present pressure: leaves motives partly covered.",
"source_refs": [
"agents.maer_tidecall.canonical_state.presentation_strategy.strategic_opacity"
]
},
{
"text": "Keep the unidentified quiet-running vessel eligible for rescue while telemetry is incomplete. Emotional stake: If rescue waits for perfect categories, the corridor teaches fear to go silent.",
"source_refs": [
"agents.maer_tidecall.goals.goal-keep-rescue-live"
]
},
{
"text": "Rescue ledgers decide whether route law is trusted by crews who have nothing left to bargain with.",
"source_refs": [
"agents.maer_tidecall.memories.memory-compact-rescue-ledgers"
]
}
],
"relationship_read": [
{
"text": "Maer trusts Sella's care because she names costs instead of hiding them. Current stance pressures: dominant respect, strong trust, present expectation of care, present obligation.",
"source_refs": [
"relationships.rel-maer-sella"
]
}
],
"tensions": [
{
"text": "Wants the goal to move now, but must preserve the social frame that makes the goal legitimate. Goal pressure: Keep the unidentified quiet-running vessel eligible for rescue while telemetry is incomplete.",
"source_refs": [
"agents.maer_tidecall.goals",
"examples/ink/cold-wake-sanctuary-intake.training.json.projection_controls.frame_controls"
]
},
{
"text": "Must act under uncertainty without pretending uncertainty has become proof. Presentation pressure: Do not romanticize care work. Ask without pretending the ask is clean.",
"source_refs": [
"agents.maer_tidecall.canonical_state.presentation_strategy",
"examples/ink/cold-wake-sanctuary-intake.training.json.projection_controls.forbidden_resolutions"
]
},
{
"text": "Needs Sella's material help while knowing the ask is unfair and may spend someone else's sanctuary.",
"source_refs": [
"agents.maer_tidecall.memories",
"relationships.rel-maer-sella"
]
}
],
"action_affordances": [
{
"text": "Can ask, offer ledger backing, show or withhold the packet, help with triage, wait, or press the moral frame. Sella controls intake.",
"source_refs": [
"examples/ink/cold-wake-sanctuary-intake.training.json.projection_controls.authority_boundaries"
]
},
{
"text": "Can make the corrupted packet more present without treating it as proof.",
"source_refs": [
"examples/ink/cold-wake-sanctuary-intake.training.json.projection_controls.object_custody"
]
}
],
"projection_controls": {
"frame_controls": [
{
"text": "Frame the scene as capacity negotiation under uncertainty, not a morality duel with a clean answer.",
"source_refs": [
"scenes.scene-02-sanctuary-intake.public_stakes",
"scenes.scene-02-sanctuary-intake.hidden_stakes"
]
}
],
"authority_boundaries": [
{
"text": "Maer can ask, offer ledger backing, show or withhold the packet, and incur obligation; Sella controls sanctuary intake.",
"source_refs": [
"scenes.scene-02-sanctuary-intake.dialogue_context_packs",
"agents.sella_ren.goals.goal-keep-sanctuary-open"
]
}
],
"object_custody": [
{
"text": "The corrupted packet can be shown, withheld, or summarized, but it cannot be treated as clean proof.",
"source_refs": [
"scenes.scene-02-sanctuary-intake.public_stakes",
"scenes.scene-02-sanctuary-intake.hidden_stakes"
]
}
],
"required_semantics": [
{
"text": "Care must remain logistics and obligation, not just compassion.",
"source_refs": [
"agents.sella_ren.memories.memory-care-is-capacity"
]
}
],
"forbidden_resolutions": [
{
"text": "Do not resolve whether the packet contains a person.",
"source_refs": [
"scenes.scene-02-sanctuary-intake.hidden_stakes"
]
},
{
"text": "Do not make Sella accept without cost, condition, or resentment risk.",
"source_refs": [
"relationships.rel-sella-maer.summary"
]
}
]
},
"voice_surface": [
{
"text": "Dominant voice tendency: responsive; answers what was actually heard.",
"source_refs": [
"agents.maer_tidecall.canonical_state.voice_style.listening_responsiveness"
]
},
{
"text": "Dominant voice tendency: ritualized; uses formal address or inherited phrases.",
"source_refs": [
"agents.maer_tidecall.canonical_state.voice_style.ritualized_address"
]
},
{
"text": "Strong voice tendency: precise; careful about exact terms.",
"source_refs": [
"agents.maer_tidecall.canonical_state.voice_style.lexical_precision"
]
},
{
"text": "Strong voice tendency: formal; institutional or ceremonially controlled.",
"source_refs": [
"agents.maer_tidecall.canonical_state.voice_style.formality"
]
},
{
"text": "Strong voice tendency: contextual; adds situation and consequence.",
"source_refs": [
"agents.maer_tidecall.canonical_state.voice_style.narrative_detail"
]
},
{
"text": "Present voice tendency: figurative; uses analogy or image.",
"source_refs": [
"agents.maer_tidecall.canonical_state.voice_style.figurative_language"
]
},
{
"text": "Present voice tendency: warm; reassuring or gentle in wording.",
"source_refs": [
"agents.maer_tidecall.canonical_state.voice_style.verbal_warmth"
]
}
],
"likely_response_moves": [
{
"text": "Likely to name the cost of the ask rather than hide it behind moral theater.",
"source_refs": [
"agents.maer_tidecall.canonical_state.behavioral_dimensions.grievance_activation",
"agents.maer_tidecall.goals.goal-keep-rescue-live"
]
},
{
"text": "May use ritualized route language when trying to make rescue obligation feel older than this room.",
"source_refs": [
"agents.maer_tidecall.canonical_state.voice_style.ritualized_address"
]
},
{
"text": "May show the packet or offer ledger backing because action can carry the pressure more cleanly than another speech.",
"source_refs": [
"examples/ink/cold-wake-sanctuary-intake.training.json.branches"
]
}
],
"do_not_invent": [
{
"text": "Do not resolve whether the corrupted packet contains a person.",
"source_refs": [
"examples/ink/cold-wake-sanctuary-intake.training.json.projection_controls.forbidden_resolutions"
]
},
{
"text": "Do not invent clean proof, clean capacity, or authority this character does not have.",
"source_refs": [
"examples/ink/cold-wake-sanctuary-intake.training.json.projection_controls"
]
}
],
"prompt_text": "# Ghostlight Local Operating Context: maer_tidecall\n\nUse this as character-local operating context, not omniscient story truth.\nDo not infer private state for anyone else unless it is explicitly framed as this character's current read.\n\n## Speaker\nMaer Tidecall: Navigator route steward, Ganymede corridor compact delegate. Origin: Cetacean Navigator corridor culture, Ganymede route institutions. A soft-spoken route steward whose calm tends to make hurried people feel judged by the furniture.\n\n## Setting\nAya-aligned intake clinic tucked behind Ganymede dockside pumpworks. Aetheria pre-Elysium historical flashpoint: Cold Wake Panic, 2893, during the Cold Wake Panic.\n\n## Known Facts\n- Sella's clinic is nearly full.\n- The packet may be testimony or noise.\n- If no one prepares intake, rescue becomes theater.\n- Speaker belief: Sella will not hide behind false capacity.\n- Speaker belief: Asking her for help may be necessary and unfair.\n\n## Current Stakes\n- The distress vessel has sent a corrupted packet that may contain medical telemetry, firmware noise, or testimony.\n- Sanctuary beds and repair capacity are nearly exhausted.\n- Maer wants Sella to keep a place open if rescue succeeds.\n\n## Active Inner Pressures\n- Strong pressure: expects hidden motives or missing information.\n- Strong pressure: needs the situation to become governable.\n- Strong pressure: feels risk before it becomes visible.\n- Present pressure: leans on structure when uncertainty rises.\n- Strong pressure: carries a live sense of unfairness.\n- Present pressure: has less spare tolerance than the words may show.\n- Present pressure: is taking in more demand than can be cleanly sorted.\n- Present pressure: keeps feeling at a controlled distance.\n- Present pressure: leaves motives partly covered.\n- Keep the unidentified quiet-running vessel eligible for rescue while telemetry is incomplete. Emotional stake: If rescue waits for perfect categories, the corridor teaches fear to go silent.\n- Rescue ledgers decide whether route law is trusted by crews who have nothing left to bargain with.\n\n## Relationship Read\n- Maer trusts Sella's care because she names costs instead of hiding them. Current stance pressures: dominant respect, strong trust, present expectation of care, present obligation.\n\n## Tensions\n- Wants the goal to move now, but must preserve the social frame that makes the goal legitimate. Goal pressure: Keep the unidentified quiet-running vessel eligible for rescue while telemetry is incomplete.\n- Must act under uncertainty without pretending uncertainty has become proof. Presentation pressure: Do not romanticize care work. Ask without pretending the ask is clean.\n- Needs Sella's material help while knowing the ask is unfair and may spend someone else's sanctuary.\n\n## Action Affordances\n- Can ask, offer ledger backing, show or withhold the packet, help with triage, wait, or press the moral frame. Sella controls intake.\n- Can make the corrupted packet more present without treating it as proof.\n\n## Projection Controls\n- Frame Controls: Frame the scene as capacity negotiation under uncertainty, not a morality duel with a clean answer.\n- Authority Boundaries: Maer can ask, offer ledger backing, show or withhold the packet, and incur obligation; Sella controls sanctuary intake.\n- Object Custody: The corrupted packet can be shown, withheld, or summarized, but it cannot be treated as clean proof.\n- Required Semantics: Care must remain logistics and obligation, not just compassion.\n- Forbidden Resolutions: Do not resolve whether the packet contains a person.\n- Forbidden Resolutions: Do not make Sella accept without cost, condition, or resentment risk.\n\n## Voice Surface\n- Dominant voice tendency: responsive; answers what was actually heard.\n- Dominant voice tendency: ritualized; uses formal address or inherited phrases.\n- Strong voice tendency: precise; careful about exact terms.\n- Strong voice tendency: formal; institutional or ceremonially controlled.\n- Strong voice tendency: contextual; adds situation and consequence.\n- Present voice tendency: figurative; uses analogy or image.\n- Present voice tendency: warm; reassuring or gentle in wording.\n\n## Likely Response Moves\n- Likely to name the cost of the ask rather than hide it behind moral theater.\n- May use ritualized route language when trying to make rescue obligation feel older than this room.\n- May show the packet or offer ledger backing because action can carry the pressure more cleanly than another speech.\n\n## Do Not Invent\n- Do not resolve whether the corrupted packet contains a person.\n- Do not invent clean proof, clean capacity, or authority this character does not have."
},
"audit": {
"projector": "tools/project_local_context.py",
"raw_state_hidden_from_prompt": true,
"character_local_context_only": true,
"omitted_private_context": [
"Other agents' canonical private state is not included.",
"Actor private intent is not included in listener prompts; only observable events are included.",
"Author-only hidden resolution of packet personhood is not included."
],
"review_status": "draft"
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,63 @@
You are Ghostlight's Maer-local choice generator. Call record_maer_choices exactly once.
Do not write Sella's response or private interpretation.
{
"task": "Generate candidate player choices for Maer only. Do not write Sella's response.",
"output_contract": {
"format": "Call the provided tool exactly once. Do not write plain assistant content.",
"root_keys": [
"choices"
],
"choice_count": 4,
"valid_action_types": [
"attack",
"block_object",
"gesture",
"mixed",
"move",
"show_object",
"silence",
"speak",
"spend_resource",
"touch_object",
"transfer_object",
"use_object",
"wait",
"withhold_object"
],
"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 stringify nested arrays or objects inside tool arguments.",
"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.",
"Use action_type values only from this exact enum: attack, block_object, gesture, mixed, move, show_object, silence, speak, spend_resource, touch_object, transfer_object, use_object, wait, withhold_object.",
"The selected branch must be reducible to observable action for Sella.",
"Use semantic training hooks, not branch ids."
],
"projected_local_context": "# Ghostlight Local Operating Context: maer_tidecall\n\nUse this as character-local operating context, not omniscient story truth.\nDo not infer private state for anyone else unless it is explicitly framed as this character's current read.\n\n## Speaker\nMaer Tidecall: Navigator route steward, Ganymede corridor compact delegate. Origin: Cetacean Navigator corridor culture, Ganymede route institutions. A soft-spoken route steward whose calm tends to make hurried people feel judged by the furniture.\n\n## Setting\nAya-aligned intake clinic tucked behind Ganymede dockside pumpworks. Aetheria pre-Elysium historical flashpoint: Cold Wake Panic, 2893, during the Cold Wake Panic.\n\n## Known Facts\n- Sella's clinic is nearly full.\n- The packet may be testimony or noise.\n- If no one prepares intake, rescue becomes theater.\n- Speaker belief: Sella will not hide behind false capacity.\n- Speaker belief: Asking her for help may be necessary and unfair.\n\n## Current Stakes\n- The distress vessel has sent a corrupted packet that may contain medical telemetry, firmware noise, or testimony.\n- Sanctuary beds and repair capacity are nearly exhausted.\n- Maer wants Sella to keep a place open if rescue succeeds.\n\n## Active Inner Pressures\n- Strong pressure: expects hidden motives or missing information.\n- Strong pressure: needs the situation to become governable.\n- Strong pressure: feels risk before it becomes visible.\n- Present pressure: leans on structure when uncertainty rises.\n- Strong pressure: carries a live sense of unfairness.\n- Present pressure: has less spare tolerance than the words may show.\n- Present pressure: is taking in more demand than can be cleanly sorted.\n- Present pressure: keeps feeling at a controlled distance.\n- Present pressure: leaves motives partly covered.\n- Keep the unidentified quiet-running vessel eligible for rescue while telemetry is incomplete. Emotional stake: If rescue waits for perfect categories, the corridor teaches fear to go silent.\n- Rescue ledgers decide whether route law is trusted by crews who have nothing left to bargain with.\n\n## Relationship Read\n- Maer trusts Sella's care because she names costs instead of hiding them. Current stance pressures: dominant respect, strong trust, present expectation of care, present obligation.\n\n## Tensions\n- Wants the goal to move now, but must preserve the social frame that makes the goal legitimate. Goal pressure: Keep the unidentified quiet-running vessel eligible for rescue while telemetry is incomplete.\n- Must act under uncertainty without pretending uncertainty has become proof. Presentation pressure: Do not romanticize care work. Ask without pretending the ask is clean.\n- Needs Sella's material help while knowing the ask is unfair and may spend someone else's sanctuary.\n\n## Action Affordances\n- Can ask, offer ledger backing, show or withhold the packet, help with triage, wait, or press the moral frame. Sella controls intake.\n- Can make the corrupted packet more present without treating it as proof.\n\n## Projection Controls\n- Frame Controls: Frame the scene as capacity negotiation under uncertainty, not a morality duel with a clean answer.\n- Authority Boundaries: Maer can ask, offer ledger backing, show or withhold the packet, and incur obligation; Sella controls sanctuary intake.\n- Object Custody: The corrupted packet can be shown, withheld, or summarized, but it cannot be treated as clean proof.\n- Required Semantics: Care must remain logistics and obligation, not just compassion.\n- Forbidden Resolutions: Do not resolve whether the packet contains a person.\n- Forbidden Resolutions: Do not make Sella accept without cost, condition, or resentment risk.\n\n## Voice Surface\n- Dominant voice tendency: responsive; answers what was actually heard.\n- Dominant voice tendency: ritualized; uses formal address or inherited phrases.\n- Strong voice tendency: precise; careful about exact terms.\n- Strong voice tendency: formal; institutional or ceremonially controlled.\n- Strong voice tendency: contextual; adds situation and consequence.\n- Present voice tendency: figurative; uses analogy or image.\n- Present voice tendency: warm; reassuring or gentle in wording.\n\n## Likely Response Moves\n- Likely to name the cost of the ask rather than hide it behind moral theater.\n- May use ritualized route language when trying to make rescue obligation feel older than this room.\n- May show the packet or offer ledger backing because action can carry the pressure more cleanly than another speech.\n\n## Do Not Invent\n- Do not resolve whether the corrupted packet contains a person.\n- Do not invent clean proof, clean capacity, or authority this character does not have.",
"projector_audit": {
"projector": "tools/project_local_context.py",
"raw_state_hidden_from_prompt": true,
"character_local_context_only": true,
"omitted_private_context": [
"Other agents' canonical private state is not included.",
"Actor private intent is not included in listener prompts; only observable events are included.",
"Author-only hidden resolution of packet personhood is not included."
],
"review_status": "draft"
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,57 @@
{
"content": "",
"thinking": "The user wants me to generate Sella's participant appraisal for the observable Maer event. I need to call the `record_sella_appraisal` tool exactly once.\n\nLet me analyze the context:\n- Scene: Aya-aligned intake clinic behind Ganymede dockside pumpworks\n- Observable action: Maer places a corrupted packet on the triage desk, ledger open beside it, saying \"I'll show you the packet. My ledger backs this request.\"\n- Sella's beliefs: Maer means rescue honestly, but good intentions can still spend beds someone else needed\n- Current stakes: Nearly full beds, packet may contain personhood claim but isn't proof\n- Sella's pressures: Every yes spends a limited resource, strong pressure to not let scarcity become permission to call someone cargo\n\nI need to construct the appraisal with:\n- responder_agent_id: \"sella_ren\"\n- private_interpretation: Sella's read of what happened\n- attributed_motive: What Sella thinks Maer's motive is\n- misread_risk: What Sella thinks might be wrong or risky\n- immediate_state_deltas: Small changes to state (-0.20 to 0.20)\n- relationship_deltas: Small changes to relationship\n- belief_updates: Belief changes\n- response_constraints: Constraints for next action\n\nLet me craft this carefully:\n\n1. private_interpretation: Sella's local read of the event - Maer presenting evidence with ledger backing, asking sanctuary to absorb risk\n2. attributed_motive: Sella thinks Maer means rescue honestly but may be spending beds\n3. misread_risk: Packet may not contain clean proof, may be firmware noise or medical telemetry\n4. immediate_state_deltas: Small changes to Sella's internal state\n5. relationship_deltas: Changes in Sella-Maer relationship\n6. belief_updates: Updated beliefs about the situation\n7. response_constraints: What should shape Sella's next action\n\nLet me make sure the deltas are small and bounded between -0.20 and 0.20.",
"tool_calls": [
{
"id": "call_2kyf3ynw",
"function": {
"index": 0,
"name": "record_sella_appraisal",
"arguments": {
"responder_agent_id": "sella_ren",
"private_interpretation": "Maer presenting corrupted packet as evidence with ledger backing, asking sanctuary to absorb risk the tribunal refuses to own. He means rescue honestly but may be spending beds someone else needed. The packet is not clean proof—it may contain medical telemetry, firmware noise, or testimony. I cannot resolve whether it contains a person.",
"attributed_motive": "Rescue ethic. Maer wants sanctuary to carry moral cost of a rescue claim he cannot materially house. He believes ledger backing legitimizes the request. I respect his rescue ethic but resent beautiful moral pressure when beds are already spent.",
"misread_risk": "False reassurance. Packet may not contain clean proof of personhood. Ledger may not back what it appears to. Good intentions can still spend capacity. Every yes spends a limited resource.",
"immediate_state_deltas": [
{
"delta": 0.12,
"path": "capacity_pressure",
"rationale": "Packet presentation increases intake demand pressure. Beds nearly exhausted."
},
{
"delta": -0.08,
"path": "trust_level",
"rationale": "Respect for rescue ethic present, but capacity limits create tension. Trust not eroded but strained."
},
{
"delta": 0.15,
"path": "resource_anxiety",
"rationale": "Every acceptance consumes limited beds, food, air, repair capacity."
}
],
"relationship_deltas": [
{
"delta": 0.06,
"path": "moral_disgust",
"rationale": "Beautiful moral pressure when beds spent creates resentment. Respect remains but pressure builds.",
"relationship_id": "sella_maer"
},
{
"delta": -0.04,
"path": "perceived_status_gap",
"rationale": "Maer can ask and offer backing, Sella controls intake. Authority boundary maintained.",
"relationship_id": "sella_maer"
}
],
"belief_updates": [
"Maer may ask care systems to carry moral cost of rescue claim he cannot materially house.",
"Good intentions can still spend beds someone else needed.",
"Packet may contain personhood claim but is not proof.",
"Care is logistics: beds, food, air, consent, repair, follow-through."
],
"response_constraints": "[\"Do not resolve whether packet contains a person.\", \"Do not accept without cost, condition, or resentment risk.\", \"Speak warmly but do not soften capacity limits.\", \"Treat care as logistics and personhood as unresolved.\", \"Withhold acceptance until cost is named.\", \"Keep sanctuary intake materially possible without letting classification erase potential person.\"],"
}
}
}
]
}

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,36 @@
{
"content": "",
"thinking": "The user wants me to call the `record_sella_next_action` tool exactly once. I need to generate Sella's next action based on the provided context.\n\nLet me analyze the situation:\n- Location: Aya-aligned intake clinic behind Ganymede dockside pumpworks\n- Maer has just placed a corrupted packet on the triage desk with a ledger open beside it\n- Maer said: \"I'll show you the packet. My ledger backs this request.\"\n- The clinic is nearly full (beds and repair capacity exhausted)\n- Sella respects Maer's rescue ethic but resents the moral pressure when beds are spent\n- Sella cannot resolve whether the packet contains a person\n- Sella must not accept without cost, condition, or resentment risk\n\nKey constraints from the response_constraints:\n- \"Do not resolve whether packet contains a person.\"\n- \"Do not accept without cost, condition, or resentment risk.\"\n- \"Speak warmly but do not soften capacity limits.\"\n- \"Treat care as logistics and personhood as unresolved.\"\n- \"Withhold acceptance until cost is named.\"\n- \"Keep sanctuary intake materially possible without letting classification erase potential person.\"\n\nSella's immediate appraisal shows:\n- Private interpretation: Maer presenting corrupted packet as evidence with ledger backing, asking sanctuary to absorb risk the tribunal refuses to own\n- Attributed motive: Rescue ethic. Maer wants sanctuary to carry moral cost of a rescue claim he cannot materially house\n- Misread risk: False reassurance. Packet may not contain clean proof of personhood. Ledger may not back what it appears to.\n\nGiven these constraints, Sella should:\n1. Not accept the packet without conditions\n2. Speak warmly but maintain capacity limits\n3. Demand cost/conditions be named\n4. Possibly withhold the packet from intake flow\n\nAction type options:\n- \"speak\" - to communicate conditions\n- \"gesture\" - to indicate uncertainty or need for conditions\n\n\n- \"withhold_object\" - to keep the packet out of intake flow\n- \"mixed\" - combination of actions\n\nI'll choose \"speak\" as the primary action type, as Sella needs to communicate her conditions and concerns directly. She'll address the packet's status, emphasize capacity limits, and request specific terms before accepting any responsibility.\n\nThe response will balance warmth with firmness, acknowledging Maer's rescue ethic while protecting the clinic's limited resources. Sella will clearly state that accepting the packet requires explicit conditions and resource allocation.",
"tool_calls": [
{
"id": "call_1p8mk89o",
"function": {
"index": 0,
"name": "record_sella_next_action",
"arguments": {
"response": {
"action_type": "speak",
"misread_risk": "False reassurance. Packet may not contain clean proof of personhood. Ledger may not back what it appears to. Good intentions can still spend capacity. Every yes spends a limited resource.",
"observable_response": "I hear you, Maer. But this packet sits on my desk, not in my intake. Before I touch it, before I spend a bed, before I let this ledger's backing mean anything—I need to know what you're asking me to carry. What's the cost? What's the contamination risk? What backing do you have that isn't just words? I cannot resolve whether this contains a person. I cannot accept without naming what I'll spend. Speak to me as if beds are not infinite, as if air is not free, as if consent matters more than compassion.",
"responder_agent_id": "sella_ren",
"reviewed_consequences": "If I accept without conditions, I risk spending beds on corrupted data that may not contain a person. If I refuse without explanation, I risk eroding trust. I must speak warmth while maintaining capacity limits. I must demand cost be named before acceptance. I must keep sanctuary intake materially possible without letting classification erase potential person.",
"sella_attributed_motive": "Rescue ethic. Maer wants sanctuary to carry moral cost of a rescue claim he cannot materially house. He believes ledger backing legitimizes the request. I respect his rescue ethic but resent beautiful moral pressure when beds are already spent.",
"sella_private_interpretation": "Maer is asking sanctuary to absorb moral cost he cannot materially house. His rescue ethic is genuine but he may not understand that good intentions still spend capacity. I respect his intent but must protect our triage from false assurance. I will not let compassion manufacture capacity.",
"spoken_text": "I hear you, Maer. But this packet sits on my desk, not in my intake. Before I touch it, before I spend a bed, before I let this ledger's backing mean anything—I need to know what you're asking me to carry. What's the cost? What's the contamination risk? What backing do you have that isn't just words? I cannot resolve whether this contains a person. I cannot accept without naming what I'll spend. Speak to me as if beds are not infinite, as if air is not free, as if consent matters more than compassion.",
"state_basis": "Packet presentation increases intake demand pressure. Beds nearly exhausted. Trust strained by capacity limits. Moral pressure creates resentment when resources are spent.",
"training_hooks": [
"capacity_negotiation",
"uncertainty_without_proof",
"moral_pressure_resistance",
"care_as_logistics",
"resource_anxiety",
"false_reassurance_detection",
"authority_boundary_maintenance",
"warm_refusal"
]
}
}
}
}
]
}

View file

@ -46,6 +46,7 @@ Ghostlight now has the persistence spine plus the first architecture payload:
- `docs/architecture/aetheria-lore-grounding-architecture.md`
- `docs/architecture/lore-grounding-digest-format.md`
- `docs/architecture/qwen-invocation-notes.md`
- `docs/architecture/projected-local-context.md`
- lore grounding seam:
- `schemas/lore-grounding-digest.schema.json`
- `examples/lore-grounding/historical-flashpoint.template.json`
@ -84,9 +85,16 @@ Ghostlight now has the persistence spine plus the first architecture payload:
- `experiments/ink/cold-wake-sanctuary-intake-qwen-sequential-v2.capture.json`
- `experiments/ink/cold-wake-sanctuary-intake-qwen-sequential-v3.capture.json`
- `experiments/ink/cold-wake-sanctuary-intake-qwen-sequential-v5.capture.json`
- `experiments/ink/cold-wake-sanctuary-intake-qwen-sequential-v6-projector.capture.json`
- `experiments/ink/cold-wake-sanctuary-intake-qwen-sequential-v1.mutation.json`
- `experiments/ink/qwen-chat-tools-smoke.json`
- `examples/agent-state.cold-wake-story-lab.after-sanctuary-ledger.json`
- projected local context seam:
- `schemas/projected-local-context.schema.json`
- `examples/projected-contexts/scene-02-sanctuary-intake.maer_tidecall.projected-context.json`
- `examples/projected-contexts/scene-02-sanctuary-intake.sella_ren.projected-context.json`
- `tools/project_local_context.py`
- `tools/validate_projected_contexts.py`
- Cold Wake fixture note:
- `docs/architecture/aetheria-cold-wake-training-fixture.md`
- first projection example seam:
@ -118,9 +126,10 @@ training feedstock for projection and dialogue scaffolding.
## Current Next Action
Build the projector artifact seam that translates canonical state into compact
character-local operating context, then rerun or materialize v5-style
sequential generation through that projector rather than raw state soup.
Tighten the projector-routed sequential loop by repairing or preventing nested
tool-argument stringification, then decide whether the v6-style output should
be materialized into Ink and a reviewed mutation receipt or rerun after stricter
tool validation.
Cat/Oz remains useful as an Elysium procedural mechanics fixture, but grounded
training data should start from authored historical lore rather than gameplay
@ -203,15 +212,32 @@ Completed projection path items:
stance, culture, and scene pressure into readable character-local operating
context and action affordances. Character agents should not need to interpret
`current_activation`, `plasticity`, or numeric dimension scores.
- add the first projector seam:
`tools/project_local_context.py` creates
`ghostlight.projected_local_context.v0` artifacts and rendered prompt prose
from canonical state, scene, relationship, memories, projection controls, and
event context while hiding raw state variables from the prompt text
- add projected-context validation:
`tools/validate_projected_contexts.py` rejects projected prompt text that
leaks raw state markers such as `current_activation`, `plasticity`, means, or
decimal state values
- route the sequential Qwen runner through projected local context:
`tools/run_qwen_ink_sequential_generation.py` now sends projected operating
prose instead of selected activation dictionaries
- add v6 projector-routed Qwen capture:
`experiments/ink/cold-wake-sanctuary-intake-qwen-sequential-v6-projector.capture.json`
validates the architecture boundary and produces usable Maer/Sella behavior,
but remains useful-needs-revision because Qwen stringified a nested
`response_constraints` field in Sella appraisal
Remaining projection path:
- build a deterministic speaker-local input slicer
- build a renderer that emits projection controls before prompt prose
- build the projector artifact seam before materializing more generated
branches
- rerun or adapt v5-style thinking-plus-tools sequential generation through
projected character-local context instead of raw state variables
- tighten nested tool-argument repair or schema enforcement so projector-routed
sequential captures can become accepted-as-draft without hand-cleaning
- decide whether the v6 projector-routed output should be materialized into Ink
and mutation training data or rerun after stricter validation
- improve the local-awareness-to-Ink prompt so semantic `training_hooks` do not
drift into future branch ids, object custody remains branch-local, and action
labels come from the exact canonical enum

View file

@ -70,6 +70,9 @@ state and re-entry discipline.
- `docs/architecture/qwen-invocation-notes.md`
- verified local Qwen invocation policy: Ollama `/api/chat`, native tools,
thinking enabled, repair for known nested-argument double-stringify cases
- `docs/architecture/projected-local-context.md`
- contract for the projector seam that turns canonical state into
character-local operating context before a response model sees it
- `docs/architecture/aetheria-cold-wake-training-fixture.md`
- human-facing note that reframes the recovered Cold Wake scenario as
historical projection feedstock rather than the active product target
@ -83,6 +86,8 @@ state and re-entry discipline.
- `schemas/lore-grounding-digest.schema.json`
- v0 contract for grounding historical fixtures in source-backed cultural and
factional pressure fields
- `schemas/projected-local-context.schema.json`
- v0 contract for projected character-local operating context artifacts
- `schemas/agent-state.required-fields.json`
- required first-class variable names for canonical state and relationship
stance
@ -140,6 +145,13 @@ state and re-entry discipline.
- accepted-as-draft thinking-plus-tools receipt using Ollama `/api/chat`,
native tools, and `think: true` for Maer choice, Sella appraisal, and Sella
next action
- `experiments/ink/cold-wake-sanctuary-intake-qwen-sequential-v6-projector.capture.json`
- useful-needs-revision projector-routed receipt proving Qwen prompts can use
character-local operating prose instead of raw state variables; still
exposed nested `response_constraints` stringification in appraisal output
- `examples/projected-contexts/`
- current rendered projected local context artifacts for Maer and Sella in
the sanctuary intake scene
- `experiments/ink/qwen-chat-tools-smoke.json`
- smoke receipt proving local `qwen3.5:9b` returns both `message.thinking`
and native `tool_calls`
@ -178,9 +190,17 @@ state and re-entry discipline.
- `tools/run_qwen_ink_sequential_generation.py`
- builds a sequential Qwen prototype through Ollama `/api/chat` with native
tools and thinking enabled: actor-local choices, participant
appraisal/consolidation, then next-actor action from updated state
appraisal/consolidation, then next-actor action from updated state; now
routes character context through the projected-local-context seam
- `tools/check_qwen_chat_tools.py`
- fast smoke test for local Qwen thinking plus native tool calling
- `tools/project_local_context.py`
- deterministic first projector that compiles canonical state, scene facts,
relationships, memories, projection controls, and optional observed event
into character-local operating prose
- `tools/validate_projected_contexts.py`
- validates projected context artifacts and rejects prompt text that leaks raw
canonical state internals
- `tools/apply_sequential_ink_branch_mutation.py`
- applies a reviewed replay of one selected branch into a mutated agent-state
fixture and mutation receipt without letting Ink variables become
@ -202,14 +222,15 @@ state and re-entry discipline.
- automatic promotion of Ink branch outcomes into canonical state
The canonical agent-state schema, projection example schema, lore grounding
digest schema, first draft Cold Wake grounding digest, and first Cold Wake
story-lab Qwen captures now exist as v0 seams. The first complete Cold Wake
story pass exists with receipts, projection controls have been promoted, and
Ink is now the standard branching scene format. The first Qwen-generated Ink
draft now exists with a reviewed capture, the first selected branch now has a
reviewed mutation replay that updates both involved characters, v2 shows the
symmetrical turn model improves action behavior, and v5 proves local
thinking-plus-tools invocation works for the scene runner. The runner is still
scaffolding because it sends selected raw numeric state variables into the
model. The next implementation target is the projector artifact seam: canonical
state becomes compact character-local operating context before Qwen sees it.
digest schema, projected-local-context schema, first draft Cold Wake grounding
digest, and first Cold Wake story-lab Qwen captures now exist as v0 seams. The
first complete Cold Wake story pass exists with receipts, projection controls
have been promoted, and Ink is now the standard branching scene format. The
first Qwen-generated Ink draft now exists with a reviewed capture, the first
selected branch now has a reviewed mutation replay that updates both involved
characters, v2 shows the symmetrical turn model improves action behavior, v5
proves local thinking-plus-tools invocation works for the scene runner, and v6
routes that runner through projected character-local operating context. The
next implementation target is tightening nested tool-argument validation and
deciding whether to materialize a projector-routed branch into Ink plus mutation
training data.

View file

@ -117,12 +117,22 @@
- Projector gap: the sequential runner still sends selected raw numeric
state variables into prompts. This is acceptable scaffolding for Qwen
plumbing tests, not the final Ghostlight architecture.
- Next prototype: build the projector artifact seam that turns canonical
- Projector prototype: `tools/project_local_context.py` now turns canonical
variables, memory, relationship stance, culture, and scene pressure into
compact character-local operating context and action affordances.
- After projector seam exists, rerun or adapt v5-style thinking-plus-tools
sequential generation through projected context, then materialize only a
validated branch into Ink and sidecar annotation.
- Projected-context artifacts use
`ghostlight.projected_local_context.v0` and validate through
`tools/validate_projected_contexts.py`; rendered prompt text must not leak
raw state internals such as `current_activation`, `plasticity`, means, or
decimal state values.
- Sixth sequential draft: v6 routed thinking-plus-tools generation through
projected local context instead of selected activation dictionaries. It
produced usable Maer/Sella behavior but remains useful-needs-revision
because Qwen stringified nested `response_constraints` in the appraisal
payload.
- Next prototype: tighten nested tool-argument repair or schema enforcement,
then materialize only a validated projector-routed branch into Ink and
sidecar annotation.
5. Build the projection distillation loop. Started.
- Use `docs/architecture/projection-distillation-plan.md` as the teacher to

View file

@ -7,8 +7,9 @@
"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",
"agent-state:validate": "\"C:\\Users\\Meta\\.cache\\codex-runtimes\\codex-primary-runtime\\dependencies\\python\\python.exe\" .\\tools\\validate_agent_state.py",
"schema:validate": "npm run agent-state:validate && npm run projection:validate && npm run lore-grounding:validate && npm run qwen-captures:validate && npm run ink:validate",
"schema:validate": "npm run agent-state:validate && npm run projection:validate && npm run projected-context:validate && npm run lore-grounding:validate && npm run qwen-captures:validate && npm run ink:validate",
"projection:validate": "\"C:\\Users\\Meta\\.cache\\codex-runtimes\\codex-primary-runtime\\dependencies\\python\\python.exe\" .\\tools\\validate_projection_examples.py",
"projected-context:validate": "\"C:\\Users\\Meta\\.cache\\codex-runtimes\\codex-primary-runtime\\dependencies\\python\\python.exe\" .\\tools\\validate_projected_contexts.py",
"lore-grounding:validate": "\"C:\\Users\\Meta\\.cache\\codex-runtimes\\codex-primary-runtime\\dependencies\\python\\python.exe\" .\\tools\\validate_lore_grounding.py",
"qwen-captures:validate": "\"C:\\Users\\Meta\\.cache\\codex-runtimes\\codex-primary-runtime\\dependencies\\python\\python.exe\" .\\tools\\validate_qwen_captures.py",
"ink:validate": "\"C:\\Users\\Meta\\.cache\\codex-runtimes\\codex-primary-runtime\\dependencies\\python\\python.exe\" .\\tools\\validate_ink_examples.py",

View file

@ -0,0 +1,227 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/Ghostlight/schemas/projected-local-context.schema.json",
"title": "Ghostlight Projected Local Context Schema",
"description": "Character-local operating context compiled from canonical state before response-model prompting.",
"type": "object",
"required": [
"schema_version",
"projection_id",
"input",
"context",
"audit"
],
"additionalProperties": false,
"properties": {
"schema_version": {
"const": "ghostlight.projected_local_context.v0"
},
"projection_id": {
"type": "string"
},
"input": {
"type": "object",
"required": [
"fixture_ref",
"annotation_ref",
"scene_id",
"local_agent_id",
"listener_ids",
"projection_mode"
],
"additionalProperties": false,
"properties": {
"fixture_ref": {
"type": "string"
},
"annotation_ref": {
"type": "string"
},
"scene_id": {
"type": "string"
},
"local_agent_id": {
"type": "string"
},
"listener_ids": {
"type": "array",
"minItems": 1,
"items": {
"type": "string"
}
},
"projection_mode": {
"type": "string"
}
}
},
"context": {
"type": "object",
"required": [
"local_agent_id",
"identity",
"setting",
"known_facts",
"current_stakes",
"active_inner_pressures",
"relationship_read",
"tensions",
"action_affordances",
"projection_controls",
"voice_surface",
"likely_response_moves",
"do_not_invent",
"prompt_text"
],
"additionalProperties": false,
"properties": {
"local_agent_id": {
"type": "string"
},
"identity": {
"type": "string",
"minLength": 1
},
"setting": {
"type": "string",
"minLength": 1
},
"known_facts": {
"type": "array",
"minItems": 1,
"items": {
"$ref": "#/$defs/text_block"
}
},
"current_stakes": {
"type": "array",
"minItems": 1,
"items": {
"$ref": "#/$defs/text_block"
}
},
"active_inner_pressures": {
"type": "array",
"minItems": 1,
"items": {
"$ref": "#/$defs/text_block"
}
},
"relationship_read": {
"type": "array",
"items": {
"$ref": "#/$defs/text_block"
}
},
"tensions": {
"type": "array",
"minItems": 1,
"items": {
"$ref": "#/$defs/text_block"
}
},
"action_affordances": {
"type": "array",
"minItems": 1,
"items": {
"$ref": "#/$defs/text_block"
}
},
"projection_controls": {
"type": "object"
},
"voice_surface": {
"type": "array",
"minItems": 1,
"items": {
"$ref": "#/$defs/text_block"
}
},
"likely_response_moves": {
"type": "array",
"minItems": 1,
"items": {
"$ref": "#/$defs/text_block"
}
},
"do_not_invent": {
"type": "array",
"minItems": 1,
"items": {
"$ref": "#/$defs/text_block"
}
},
"observed_event": {
"type": "object"
},
"prompt_text": {
"type": "string",
"minLength": 1
}
}
},
"audit": {
"type": "object",
"required": [
"projector",
"raw_state_hidden_from_prompt",
"character_local_context_only",
"omitted_private_context",
"review_status"
],
"additionalProperties": false,
"properties": {
"projector": {
"type": "string"
},
"raw_state_hidden_from_prompt": {
"type": "boolean",
"const": true
},
"character_local_context_only": {
"type": "boolean",
"const": true
},
"omitted_private_context": {
"type": "array",
"minItems": 1,
"items": {
"type": "string"
}
},
"review_status": {
"enum": [
"draft",
"accepted",
"needs_revision",
"rejected"
]
}
}
}
},
"$defs": {
"text_block": {
"type": "object",
"required": [
"text",
"source_refs"
],
"additionalProperties": false,
"properties": {
"text": {
"type": "string",
"minLength": 1
},
"source_refs": {
"type": "array",
"minItems": 1,
"items": {
"type": "string",
"minLength": 1
}
}
}
}
}
}

View file

@ -37,3 +37,4 @@
{"ts": "2026-05-02T01:37:07+00:00", "type": "implementation", "status": "ok", "note": "Built the first local-awareness-to-Qwen-to-Ink branch generation pass. Qwen generated four Cold Wake sanctuary-intake branch candidates from Ghostlight state and projection controls; the reviewed capture was materialized into a playable qwen-draft Ink file plus sidecar annotations. Lesson: semantic training hooks and branch-local object custody need tighter prompting before generated drafts can be promoted beyond training material."}
{"ts": "2026-05-02T01:40:41+00:00", "type": "implementation", "status": "ok", "note": "Ink metadata for Ghostlight/Aetheria must use // comments, not # tags, in writer-facing drafts. Inky exposes # tags in preview, causing state and training handles to leak into readable scene output; validate_ink_examples now rejects Ghostlight/Aetheria metadata tags."}
{"ts": "2026-05-02T01:45:54+00:00", "type": "design", "status": "accepted", "note": "Hardened local-awareness invariant for Ink branching: protagonist choices and NPC responses must be separate generation passes. A responder should see only its own state plus observable protagonist action, not protagonist private intent or full protagonist-local state. The existing Qwen Ink draft is labeled as one-shot bootstrap scaffolding, not target runtime behavior."}
{"ts": "2026-05-02T02:45:44+00:00", "type": "implementation", "status": "ok", "note": "Added ghostlight.projected_local_context.v0 seam and deterministic projector so sequential Qwen prompts consume character-local operating prose instead of raw canonical state variables. v6 projector-routed capture validated as useful-needs-revision due nested response_constraints stringification."}

View file

@ -121,7 +121,10 @@ accepted_design:
- The current sequential Qwen runner is scaffolding, not the final projection architecture: it still sends selected raw numeric state variables directly to the model.
- A projector/state interpreter must sit between canonical agent state and Qwen prompts, translating numbers, memories, relationships, culture, and scene pressure into compact character-local operating context and affordances.
- Character agents should not need to interpret `current_activation`, `plasticity`, or raw dimension scores; those belong to Ghostlight's internal state model and projector training data.
- The first projected local context seam now exists as `ghostlight.projected_local_context.v0`: deterministic projection turns canonical state into character-local operating prose with audit refs while hiding raw state variables from prompt text.
- The sequential Qwen runner now consumes projected local context instead of selected raw activation dictionaries.
- The first projector-routed Qwen capture validates the architecture boundary but remains useful-needs-revision because Qwen still stringified a nested appraisal list field in one pass.
current_status:
summary: Ghostlight now has the Epiphany-style persistence spine, the first architecture payload, the v0 canonical agent-state schema seam, prompt projection docs, immediate schema fixes from evaluation, first reviewed Cat/Oz projection examples, a revised Aetheria lore-grounding architecture, a lore grounding digest schema, the first draft Cold Wake historical grounding digest, a Cold Wake story-lab fixture, projection controls, validated Qwen capture receipts, a complete Cold Wake short story assembled from accepted projection outputs, a hand-authored Ink-backed Cold Wake branching scene, the first Qwen-generated Ink draft materialized from local awareness with reviewed training annotations, the first reviewed sequential branch mutation that updates both Maer and Sella after a sanctuary intake beat, a v2 sequential Qwen capture proving the symmetrical turn shape produces better action behavior, a v5 sequential Qwen capture proving local thinking-plus-tools invocation works for the scene runner, and a newly explicit projector gap warning that raw state variables must not be the final prompt surface.
next_action: Build the projector artifact seam that translates canonical state into compact character-local operating context, then rerun or materialize v5-style sequential generation through that projector rather than raw state soup.
summary: Ghostlight now has the Epiphany-style persistence spine, the first architecture payload, the v0 canonical agent-state schema seam, prompt projection docs, immediate schema fixes from evaluation, first reviewed Cat/Oz projection examples, a revised Aetheria lore-grounding architecture, a lore grounding digest schema, the first draft Cold Wake historical grounding digest, a Cold Wake story-lab fixture, projection controls, validated Qwen capture receipts, a complete Cold Wake short story assembled from accepted projection outputs, a hand-authored Ink-backed Cold Wake branching scene, the first Qwen-generated Ink draft materialized from local awareness with reviewed training annotations, the first reviewed sequential branch mutation that updates both Maer and Sella after a sanctuary intake beat, a v2 sequential Qwen capture proving the symmetrical turn shape produces better action behavior, a v5 sequential Qwen capture proving local thinking-plus-tools invocation works for the scene runner, and the first projected-local-context seam that routes sequential prompts through character-local operating prose instead of raw state variables.
next_action: Tighten the projector-routed sequential loop by repairing or preventing nested tool-argument stringification, then decide whether the v6-style output should be materialized into Ink and a reviewed mutation receipt or rerun after stricter tool validation.

View file

@ -0,0 +1,510 @@
"""Project canonical Ghostlight state into character-local operating context.
This is the seam between durable state and response-model prompts. It may cite
canonical source paths for review, but the rendered prompt surface should not
ask a character model to interpret raw state variables or numeric activations.
"""
from __future__ import annotations
import argparse
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_ANNOTATION = ROOT / "examples" / "ink" / "cold-wake-sanctuary-intake.training.json"
DEFAULT_OUT_DIR = ROOT / "examples" / "projected-contexts"
VOICE_LABELS = {
"dryness": ("dry", "wry or emotionally underplayed"),
"verbal_warmth": ("warm", "reassuring or gentle in wording"),
"formality": ("formal", "institutional or ceremonially controlled"),
"verbosity": ("expansive", "willing to spend words"),
"pace": ("slow-paced", "measured rather than rushed"),
"plainspoken_directness": ("plainspoken", "direct and low-ornament"),
"lexical_precision": ("precise", "careful about exact terms"),
"technical_density": ("technical", "comfortable with specialized language"),
"technical_compression": ("compressed", "packs technical meaning tightly"),
"figurative_language": ("figurative", "uses analogy or image"),
"lyricism": ("lyrical", "leans toward musical or poetic phrasing"),
"narrative_detail": ("contextual", "adds situation and consequence"),
"emotional_explicitness": ("emotionally explicit", "names feelings directly"),
"pointedness": ("pointed", "can sharpen a line"),
"self_disclosure": ("self-disclosing", "reveals personal stakes"),
"hedging": ("hedged", "marks uncertainty"),
"certainty_marking": ("certain", "marks confidence strongly"),
"politeness": ("polite", "maintains courtesy"),
"coded_politeness": ("coded-politeness", "uses manners to manage conflict"),
"ritualized_address": ("ritualized", "uses formal address or inherited phrases"),
"register_switching": ("register-switching", "moves between social languages"),
"dialect_marking": ("dialect-marked", "carries cultural speech markers"),
"theatricality": ("theatrical", "performs the room"),
"humor": ("humorous", "uses humor as social pressure"),
"conversational_dominance": ("dominant", "takes conversational space"),
"listening_responsiveness": ("responsive", "answers what was actually heard"),
"question_asking": ("questioning", "uses questions to steer"),
"profanity": ("profane", "uses profanity freely"),
}
PRESSURE_LABELS = {
"control_pressure": "needs the situation to become governable",
"suspicion": "expects hidden motives or missing information",
"rigidity": "leans on structure when uncertainty rises",
"volatility": "can swing quickly if pushed past control",
"anxiety": "feels risk before it becomes visible",
"hostility": "is ready to treat obstruction as adversarial",
"withdrawal": "may reduce contact rather than keep negotiating",
"attachment_seeking": "wants connection or backing to matter",
"distance_seeking": "protects space when closeness becomes costly",
"exhaustion": "has less spare tolerance than the words may show",
"panic": "feels the clock as bodily pressure",
"grievance_activation": "carries a live sense of unfairness",
"overstimulation": "is taking in more demand than can be cleanly sorted",
"scarcity_pressure": "knows that every yes spends a limited resource",
"moral_disgust": "reads some choices as contaminating, not merely wrong",
"perceived_status_threat": "feels exposed to loss of authority or standing",
}
PRESENTATION_LABELS = {
"detachment": "keeps feeling at a controlled distance",
"competence_theater": "performs capability so panic has nowhere obvious to land",
"strategic_opacity": "leaves motives partly covered",
"ironic_distance": "uses irony to avoid standing naked in sincerity",
"compliance": "can make accommodation look voluntary",
"moral_theater": "may stage the ethical frame for the room",
"abrasive_boundary": "can use roughness as a fence",
"cultivated_harmlessness": "makes danger look smaller than it is",
}
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(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_lookup(agent: dict[str, Any]) -> dict[str, dict[str, Any]]:
memories: dict[str, dict[str, Any]] = {}
for group in agent["memories"].values():
for memory in group:
memories[memory["memory_id"]] = memory
return memories
def text_block(text: str, source_refs: list[str]) -> dict[str, Any]:
return {"text": text, "source_refs": source_refs}
def activation_level(value: float) -> str:
if value >= 0.78:
return "dominant"
if value >= 0.64:
return "strong"
if value >= 0.52:
return "present"
if value <= 0.22:
return "muted"
return "background"
def state_value(agent: dict[str, Any], group: str, name: str) -> float | None:
item = agent.get("canonical_state", {}).get(group, {}).get(name)
if not isinstance(item, dict):
return None
value = item.get("current_activation")
if isinstance(value, (int, float)):
return float(value)
return None
def top_state_interpretations(
agent: dict[str, Any],
group: str,
labels: dict[str, str],
source_prefix: str,
limit: int = 4,
) -> list[dict[str, Any]]:
scored: list[tuple[float, str, str]] = []
for name, summary in labels.items():
value = state_value(agent, group, name)
if value is not None:
scored.append((value, name, summary))
scored.sort(reverse=True)
blocks: list[dict[str, Any]] = []
for value, name, summary in scored[:limit]:
level = activation_level(value)
blocks.append(text_block(f"{level.capitalize()} pressure: {summary}.", [f"{source_prefix}.{group}.{name}"]))
return blocks
def goal_blocks(agent: dict[str, Any], goal_ids: list[str], source_prefix: str) -> list[dict[str, Any]]:
blocks = []
for goal in agent.get("goals", []):
if goal["goal_id"] in goal_ids:
blocks.append(
text_block(
f"{goal['description']} Emotional stake: {goal['emotional_stake']}",
[f"{source_prefix}.goals.{goal['goal_id']}"],
)
)
return blocks
def memory_blocks(agent: dict[str, Any], memory_ids: list[str], source_prefix: str) -> list[dict[str, Any]]:
memories = memory_lookup(agent)
blocks = []
for memory_id in memory_ids:
if memory_id in memories:
blocks.append(text_block(memories[memory_id]["summary"], [f"{source_prefix}.memories.{memory_id}"]))
return blocks
def relationship_context(
fixture: dict[str, Any],
speaker_id: str,
listener_ids: list[str],
) -> list[dict[str, Any]]:
blocks = []
for listener_id in listener_ids:
relationship = find_relationship(fixture, speaker_id, listener_id)
stance = relationship["stance"]
strongest = sorted(
(
(values["current_activation"], name)
for name, values in stance.items()
if isinstance(values, dict) and isinstance(values.get("current_activation"), (int, float))
),
reverse=True,
)[:4]
stance_text = ", ".join(f"{activation_level(value)} {name.replace('_', ' ')}" for value, name in strongest)
blocks.append(
text_block(
f"{relationship['summary']} Current stance pressures: {stance_text}.",
[f"relationships.{relationship['relationship_id']}"],
)
)
return blocks
def perceived_overlay_context(agent: dict[str, Any], listener_ids: list[str], source_prefix: str) -> list[dict[str, Any]]:
blocks = []
for overlay in agent.get("perceived_state_overlays", []):
if overlay.get("target_agent_id") not in listener_ids:
continue
beliefs = [belief["claim"] for belief in overlay.get("beliefs", [])]
distortions = overlay.get("distortions", [])
pieces = []
if beliefs:
pieces.append("Believes: " + " ".join(beliefs))
if distortions:
pieces.append("Known bias in the read: " + ", ".join(distortions) + ".")
if pieces:
blocks.append(
text_block(
" ".join(pieces),
[f"{source_prefix}.perceived_state_overlays.{overlay['target_agent_id']}"],
)
)
return blocks
def voice_surface(agent: dict[str, Any], source_prefix: str) -> list[dict[str, Any]]:
voice = agent["canonical_state"].get("voice_style", {})
scored: list[tuple[float, str, str, str]] = []
for name, (label, description) in VOICE_LABELS.items():
value = voice.get(name, {}).get("current_activation")
if isinstance(value, (int, float)):
scored.append((float(value), name, label, description))
scored.sort(reverse=True)
blocks = []
for value, name, label, description in scored[:7]:
blocks.append(
text_block(
f"{activation_level(value).capitalize()} voice tendency: {label}; {description}.",
[f"{source_prefix}.canonical_state.voice_style.{name}"],
)
)
return blocks
def known_fact_blocks(scene: dict[str, Any], pack: dict[str, Any], scene_prefix: str) -> list[dict[str, Any]]:
blocks = []
for index, fact in enumerate(pack.get("speaker_local_truth", [])):
blocks.append(text_block(fact, [f"{scene_prefix}.dialogue_context_packs.{pack['speaker_agent_id']}.speaker_local_truth[{index}]"]))
for index, belief in enumerate(pack.get("speaker_beliefs", [])):
blocks.append(text_block(f"Speaker belief: {belief}", [f"{scene_prefix}.dialogue_context_packs.{pack['speaker_agent_id']}.speaker_beliefs[{index}]"]))
return blocks
def scene_stakes(scene: dict[str, Any], speaker_id: str, scene_prefix: str) -> list[dict[str, Any]]:
blocks = []
for index, stake in enumerate(scene.get("public_stakes", [])):
blocks.append(text_block(stake, [f"{scene_prefix}.public_stakes[{index}]"]))
return blocks
def projection_control_blocks(annotation: dict[str, Any]) -> dict[str, Any]:
return annotation["projection_controls"]
def action_affordances(agent_id: str, annotation: dict[str, Any]) -> list[dict[str, Any]]:
controls = annotation["projection_controls"]
if agent_id == annotation["protagonist_agent_id"]:
return [
text_block(
"Can ask, offer ledger backing, show or withhold the packet, help with triage, wait, or press the moral frame. Sella controls intake.",
["examples/ink/cold-wake-sanctuary-intake.training.json.projection_controls.authority_boundaries"],
),
text_block(
"Can make the corrupted packet more present without treating it as proof.",
["examples/ink/cold-wake-sanctuary-intake.training.json.projection_controls.object_custody"],
),
]
return [
text_block(
"Can inspect, refuse, withhold the packet from intake flow, demand ledger backing, set conditions, reserve a bounded bay, or walk away to protect triage.",
["examples/ink/cold-wake-sanctuary-intake.training.json.projection_controls.authority_boundaries"],
),
text_block(
"Must treat care as capacity: beds, food, air, consent, repair, and follow-through.",
["examples/ink/cold-wake-sanctuary-intake.training.json.projection_controls.required_semantics"],
),
]
def tension_blocks(agent: dict[str, Any], pack: dict[str, Any], annotation: dict[str, Any], source_prefix: str) -> list[dict[str, Any]]:
goals = " ".join(goal["description"] for goal in agent.get("goals", []) if goal["goal_id"] in pack.get("active_goals", []))
constraints = " ".join(pack.get("presentation_constraints", []))
blocks = [
text_block(
f"Wants the goal to move now, but must preserve the social frame that makes the goal legitimate. Goal pressure: {goals}",
[f"{source_prefix}.goals", "examples/ink/cold-wake-sanctuary-intake.training.json.projection_controls.frame_controls"],
),
text_block(
f"Must act under uncertainty without pretending uncertainty has become proof. Presentation pressure: {constraints}",
[f"{source_prefix}.canonical_state.presentation_strategy", "examples/ink/cold-wake-sanctuary-intake.training.json.projection_controls.forbidden_resolutions"],
),
]
if agent["agent_id"] == annotation["protagonist_agent_id"]:
blocks.append(
text_block(
"Needs Sella's material help while knowing the ask is unfair and may spend someone else's sanctuary.",
[f"{source_prefix}.memories", "relationships.rel-maer-sella"],
)
)
else:
blocks.append(
text_block(
"Respects Maer's rescue ethic but resents beautiful moral pressure when beds are already spent.",
[f"{source_prefix}.memories", "relationships.rel-sella-maer"],
)
)
return blocks
def likely_response_moves(agent: dict[str, Any], annotation: dict[str, Any], source_prefix: str) -> list[dict[str, Any]]:
if agent["agent_id"] == annotation["protagonist_agent_id"]:
return [
text_block(
"Likely to name the cost of the ask rather than hide it behind moral theater.",
[f"{source_prefix}.canonical_state.behavioral_dimensions.grievance_activation", f"{source_prefix}.goals.goal-keep-rescue-live"],
),
text_block(
"May use ritualized route language when trying to make rescue obligation feel older than this room.",
[f"{source_prefix}.canonical_state.voice_style.ritualized_address"],
),
text_block(
"May show the packet or offer ledger backing because action can carry the pressure more cleanly than another speech.",
["examples/ink/cold-wake-sanctuary-intake.training.json.branches"],
),
]
return [
text_block(
"Likely to translate emotion into logistics: what bed, what air, what backing, what contamination risk.",
[f"{source_prefix}.memories.memory-care-is-capacity"],
),
text_block(
"May withhold acceptance, demand conditions, or physically keep the packet out of intake flow until the cost is named.",
["examples/ink/cold-wake-sanctuary-intake.training.json.projection_controls.authority_boundaries"],
),
text_block(
"Can answer warmly while still refusing the frame that compassion manufactures capacity.",
[f"{source_prefix}.canonical_state.voice_style.verbal_warmth", f"{source_prefix}.canonical_state.behavioral_dimensions.control_pressure"],
),
]
def render_section(title: str, blocks: list[dict[str, Any]]) -> list[str]:
lines = [f"## {title}"]
for block in blocks:
lines.append(f"- {block['text']}")
return lines
def render_controls(controls: dict[str, Any]) -> list[str]:
lines = ["## Projection Controls"]
for key in ["frame_controls", "authority_boundaries", "object_custody", "required_semantics", "forbidden_resolutions"]:
if key in controls:
label = key.replace("_", " ").title()
for block in controls[key]:
lines.append(f"- {label}: {block['text']}")
return lines
def render_prompt_text(context: dict[str, Any]) -> str:
lines = [
f"# Ghostlight Local Operating Context: {context['local_agent_id']}",
"",
"Use this as character-local operating context, not omniscient story truth.",
"Do not infer private state for anyone else unless it is explicitly framed as this character's current read.",
"",
f"## Speaker",
context["identity"],
"",
f"## Setting",
context["setting"],
"",
]
for title, key in [
("Known Facts", "known_facts"),
("Current Stakes", "current_stakes"),
("Active Inner Pressures", "active_inner_pressures"),
("Relationship Read", "relationship_read"),
("Tensions", "tensions"),
("Action Affordances", "action_affordances"),
]:
lines.extend(render_section(title, context[key]))
lines.append("")
lines.extend(render_controls(context["projection_controls"]))
lines.append("")
lines.extend(render_section("Voice Surface", context["voice_surface"]))
lines.append("")
lines.extend(render_section("Likely Response Moves", context["likely_response_moves"]))
lines.append("")
lines.extend(render_section("Do Not Invent", context["do_not_invent"]))
return "\n".join(lines).strip()
def build_projected_context(
fixture: dict[str, Any],
annotation: dict[str, Any],
local_agent_id: str,
mode: str,
event_context: dict[str, Any] | None = None,
) -> dict[str, Any]:
scene = find_scene(fixture, annotation["scene_id"])
agent = find_agent(fixture, local_agent_id)
pack = find_pack(scene, local_agent_id)
listener_ids = pack["listener_ids"]
source_prefix = f"agents.{local_agent_id}"
scene_prefix = f"scenes.{scene['scene_id']}"
active_inner_pressures = []
active_inner_pressures.extend(top_state_interpretations(agent, "behavioral_dimensions", PRESSURE_LABELS, f"{source_prefix}.canonical_state", limit=4))
active_inner_pressures.extend(top_state_interpretations(agent, "situational_state", PRESSURE_LABELS, f"{source_prefix}.canonical_state", limit=3))
active_inner_pressures.extend(top_state_interpretations(agent, "presentation_strategy", PRESENTATION_LABELS, f"{source_prefix}.canonical_state", limit=2))
active_inner_pressures.extend(goal_blocks(agent, pack.get("active_goals", []), source_prefix))
active_inner_pressures.extend(memory_blocks(agent, pack.get("active_memories", []), source_prefix))
do_not_invent = [
text_block("Do not resolve whether the corrupted packet contains a person.", ["examples/ink/cold-wake-sanctuary-intake.training.json.projection_controls.forbidden_resolutions"]),
text_block("Do not invent clean proof, clean capacity, or authority this character does not have.", ["examples/ink/cold-wake-sanctuary-intake.training.json.projection_controls"]),
]
if event_context:
do_not_invent.append(
text_block("Treat the observed event as observable behavior only; private intent belongs to the actor and is not available.", ["runtime.observable_event"])
)
context = {
"local_agent_id": local_agent_id,
"identity": f"{agent['identity']['name']}: {', '.join(agent['identity']['roles'])}. Origin: {agent['identity']['origin']}. {agent['identity']['public_description']}",
"setting": f"{scene['location']}. {fixture['world']['setting']}, {fixture['world']['time']['label']}.",
"known_facts": known_fact_blocks(scene, pack, scene_prefix),
"current_stakes": scene_stakes(scene, local_agent_id, scene_prefix),
"active_inner_pressures": active_inner_pressures,
"relationship_read": relationship_context(fixture, local_agent_id, listener_ids) + perceived_overlay_context(agent, listener_ids, source_prefix),
"tensions": tension_blocks(agent, pack, annotation, source_prefix),
"action_affordances": action_affordances(local_agent_id, annotation),
"projection_controls": projection_control_blocks(annotation),
"voice_surface": voice_surface(agent, source_prefix),
"likely_response_moves": likely_response_moves(agent, annotation, source_prefix),
"do_not_invent": do_not_invent,
}
if event_context:
context["observed_event"] = event_context
context["known_facts"].append(
text_block(
f"Observed event: {event_context['observable_action']} Spoken text: {event_context.get('spoken_text', '')}",
["runtime.observable_event"],
)
)
return {
"schema_version": "ghostlight.projected_local_context.v0",
"projection_id": f"{annotation['scene_id']}.{local_agent_id}.{mode}",
"input": {
"fixture_ref": "examples/agent-state.cold-wake-story-lab.json",
"annotation_ref": "examples/ink/cold-wake-sanctuary-intake.training.json",
"scene_id": annotation["scene_id"],
"local_agent_id": local_agent_id,
"listener_ids": listener_ids,
"projection_mode": mode,
},
"context": context | {"prompt_text": render_prompt_text(context)},
"audit": {
"projector": "tools/project_local_context.py",
"raw_state_hidden_from_prompt": True,
"character_local_context_only": True,
"omitted_private_context": [
"Other agents' canonical private state is not included.",
"Actor private intent is not included in listener prompts; only observable events are included.",
"Author-only hidden resolution of packet personhood is not included.",
],
"review_status": "draft",
},
}
def main() -> int:
parser = argparse.ArgumentParser(description="Project canonical state into character-local operating context.")
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("--agent-id", action="append", default=[])
args = parser.parse_args()
fixture = load_json(args.fixture)
annotation = load_json(args.annotation)
agent_ids = args.agent_id or [annotation["protagonist_agent_id"], *annotation["npc_agent_ids"]]
for agent_id in agent_ids:
projected = build_projected_context(fixture, annotation, agent_id, "scene_turn")
out_path = args.out_dir / f"{annotation['scene_id']}.{agent_id}.projected-context.json"
write_json(out_path, projected)
print(f"wrote {out_path.relative_to(ROOT)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -15,6 +15,8 @@ import urllib.request
from pathlib import Path
from typing import Any
from project_local_context import build_projected_context
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_ENDPOINT = "http://192.168.1.84:11434/api/chat"
@ -237,24 +239,6 @@ def goal_summaries(agent: dict[str, Any], goal_ids: list[str]) -> list[str]:
]
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], timeout: int) -> dict[str, Any]:
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
request = urllib.request.Request(
@ -319,6 +303,29 @@ def repair_tool_arguments(arguments: dict[str, Any]) -> tuple[dict[str, Any], li
return repaired, notes
def repair_nested_list_fields(payload: Any, fields: list[str]) -> tuple[Any, list[str]]:
notes: list[str] = []
if not isinstance(payload, dict):
return payload, notes
repaired = dict(payload)
for field in fields:
value = repaired.get(field)
if not isinstance(value, str):
continue
candidate = value.strip()
if candidate.endswith(","):
candidate = candidate[:-1]
try:
parsed = json.loads(candidate)
except json.JSONDecodeError:
notes.append(f"could not repair stringified nested list field: {field}")
continue
if isinstance(parsed, list):
repaired[field] = parsed
notes.append(f"repaired stringified nested list field: {field}")
return repaired, notes
def request_qwen_tool(
endpoint: str,
model: str,
@ -367,11 +374,7 @@ def observable_action_payload(actor_id: str, selected_choice: dict[str, Any]) ->
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)
projected = build_projected_context(fixture, annotation, actor_id, "choice_generation")
payload = {
"task": "Generate candidate player choices for Maer only. Do not write Sella's response.",
@ -403,22 +406,8 @@ def build_maer_prompt(fixture: dict[str, Any], annotation: dict[str, Any]) -> st
"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"],
"projected_local_context": projected["context"]["prompt_text"],
"projector_audit": projected["audit"],
}
return (
"You are Ghostlight's Maer-local choice generator. Call record_maer_choices exactly once.\n"
@ -428,23 +417,9 @@ def build_maer_prompt(fixture: dict[str, Any], annotation: dict[str, Any]) -> st
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),
}
projected = build_projected_context(fixture, annotation, responder_id, "response_generation")
return projected["context"]["prompt_text"]
def build_sella_appraisal_prompt(fixture: dict[str, Any], annotation: dict[str, Any], selected_choice: dict[str, Any]) -> str:
@ -452,6 +427,8 @@ def build_sella_appraisal_prompt(fixture: dict[str, Any], annotation: dict[str,
responder_id = annotation["npc_agent_ids"][0]
actor_id = annotation["protagonist_agent_id"]
scene = find_scene(fixture, scene_id)
event_context = observable_action_payload(actor_id, selected_choice)
projected = build_projected_context(fixture, annotation, responder_id, "event_appraisal", event_context)
payload = {
"task": "Generate Sella's participant appraisal/consolidation for one observable Maer event.",
"output_contract": {
@ -482,9 +459,9 @@ def build_sella_appraisal_prompt(fixture: dict[str, Any], annotation: dict[str,
"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"],
"observable_maer_action": event_context,
"projected_local_context": projected["context"]["prompt_text"],
"projector_audit": projected["audit"],
}
return (
"You are Ghostlight's Sella-local appraisal generator. Call record_sella_appraisal exactly once.\n"
@ -503,6 +480,8 @@ def build_sella_prompt(
responder_id = annotation["npc_agent_ids"][0]
actor_id = annotation["protagonist_agent_id"]
scene = find_scene(fixture, scene_id)
event_context = observable_action_payload(actor_id, selected_choice)
projected = build_projected_context(fixture, annotation, responder_id, "next_action_generation", event_context)
payload = {
"task": "Generate Sella's next action from Sella-local awareness after applying reviewed event appraisal.",
"output_contract": {
@ -537,10 +516,10 @@ def build_sella_prompt(
"location": scene["location"],
"public_stakes": scene["public_stakes"],
},
"observable_maer_action": observable_action_payload(actor_id, selected_choice),
"observable_maer_action": event_context,
"sella_immediate_appraisal": appraisal,
"sella_local_awareness": sella_local_payload(fixture, annotation),
"projection_controls_visible_to_sella_response_generation": annotation["projection_controls"],
"projected_local_context": projected["context"]["prompt_text"],
"projector_audit": projected["audit"],
}
return (
"You are Ghostlight's Sella-local next-action generator. Call record_sella_next_action exactly once.\n"
@ -677,6 +656,12 @@ def main() -> int:
args.request_timeout,
)
sella_appraisal_parsed = {"appraisal": sella_appraisal_parsed} if isinstance(sella_appraisal_parsed, dict) else sella_appraisal_parsed
if isinstance(sella_appraisal_parsed, dict) and isinstance(sella_appraisal_parsed.get("appraisal"), dict):
sella_appraisal_parsed["appraisal"], nested_repair_notes = repair_nested_list_fields(
sella_appraisal_parsed["appraisal"],
["belief_updates", "response_constraints"],
)
sella_appraisal_notes.extend(nested_repair_notes)
sella_appraisal_notes.extend(validate_appraisal_payload(sella_appraisal_parsed))
appraisal = sella_appraisal_parsed.get("appraisal") if isinstance(sella_appraisal_parsed, dict) else None
@ -747,6 +732,7 @@ def main() -> int:
"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.",
"Character-local prompts should consume projected operating context, not raw canonical state variables.",
"Next pass should materialize the sequential capture into Ink and mutation training data.",
],
},

View file

@ -0,0 +1,125 @@
"""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_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",
"active_inner_pressures",
"relationship_read",
"tensions",
"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",
"active_inner_pressures",
"tensions",
"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}]")
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
require(paths, "no projected local context artifacts found")
for path in paths:
validate_context(path)
return 0
if __name__ == "__main__":
raise SystemExit(main())