Skip to content

Commit 0691521

Browse files
authored
Merge pull request #96 from chaincraftgames/generated-mechanics
Enhance spec execution and prompts with platform constraints and acti…
2 parents c30c096 + d0e4ced commit 0691521

6 files changed

Lines changed: 66 additions & 11 deletions

File tree

‎src/ai/design/graphs/main-design-graph/nodes/spec-execute/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { SystemMessagePromptTemplate } from "@langchain/core/prompts";
99
import { ModelWithOptions } from "#chaincraft/ai/model-config.js";
1010
import type { GameDesignState, GameDesignSpecification } from "#chaincraft/ai/design/game-design-state.js";
1111
import { SYSTEM_PROMPT, getPreservationGuidance } from "./prompts.js";
12+
import { CONSTRAINTS_TEXT } from "#chaincraft/ai/design/constraints.js";
1213
import { getBus } from "#chaincraft/events/game-creation-status-bus.js";
1314
import { setSpecInProgress, clearSpecInProgress } from "#chaincraft/events/game-creation-status-bus.js";
1415

@@ -121,6 +122,7 @@ export function createSpecExecute(model: ModelWithOptions) {
121122
currentSpec,
122123
changePlan: changePlans,
123124
preservationGuidance,
125+
constraints_registry: CONSTRAINTS_TEXT,
124126
});
125127

126128
// 5. Call LLM with formatted system prompt to generate pure markdown

‎src/ai/design/graphs/main-design-graph/nodes/spec-execute/prompts.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,11 @@ Use markers for extensive narrative style guidance and examples:
4040
export const SYSTEM_PROMPT = `
4141
!___ CACHE:spec-execute-guidelines ___!
4242
43+
**Platform Constraints — do NOT specify features in the Not Supported or Limited Support categories:**
44+
<constraints_registry>
45+
{constraints_registry}
46+
</constraints_registry>
47+
4348
**⚠️ CRITICAL — CROSS-SESSION PERSISTENCE IS NOT A GAME FEATURE:**
4449
Saving, loading, persisting, or reusing ANY game data (characters, items, achievements, etc.)
4550
across game sessions is handled ENTIRELY by the game engine. The specification must NEVER
@@ -68,7 +73,6 @@ Write requirements needed for: game setup, player actions, action outcomes, info
6873
- How actions resolve: "Weapons battle using rock-paper-scissors logic"
6974
- What players see: "Players see narrative, winner, and standings"
7075
- When game ends: "First to win 3 rounds wins the match"
71-
- Fairness rules: "Players have 90 seconds; timeout = auto-generated weapon"
7276
- Narrative requirements: "Narrative must mention all weapons and declare winner clearly"
7377
- Optional NFT/token support (if applicable): Include an "## NFTs" section listing each NFT content
7478
type as a subsection with bullets for:
@@ -102,6 +106,10 @@ type as a subsection with bullets for:
102106
- Validation details: "Weapon name must match regex ^[a-zA-Z0-9 -']+$"
103107
- Phase logic: "Transition to RESOLUTION when all submitted OR timer expires"
104108
- Algorithms: "Assign R/P/S using weighted randomization with rebalancing..."
109+
- **Time limits, timeouts, auto-advance, or AFK handling of any kind** — the runtime has no
110+
clock and cannot advance the game after N seconds. Do NOT specify "players have X seconds",
111+
"if a player doesn't respond in time", "auto-generate a choice on timeout", or any similar
112+
mechanic. Games wait indefinitely for player input; omit all timing constraints entirely.
105113
- **ALL NFT/token save/load mechanics for ANY data type** — NEVER include sections about saving
106114
game data (characters, items, achievements, scores, or anything else) as tokens/NFTs, loading
107115
tokens, token persistence, token collections, token management, reusing saved data, or using

‎src/ai/simulate/graphs/spec-processing-graph/nodes/extract-action-definitions/prompts.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,13 @@ Some actions require no data from the player — the act of taking them is suffi
4242
These get inputFields: []
4343
4444
## Action IDs
45-
Use concise camelCase IDs that describe the action:
46-
- 'bid' not 'placeBid' or 'submitBid'
47-
- 'challenge' not 'declareChallenge'
48-
- 'playCard' not 'playACard'
49-
- 'draw' not 'drawCard'
50-
- 'attack' not 'performAttack'
45+
Use concise **snake_case** IDs that describe the action. The id is used verbatim as
46+
\`currentAction.type\` at runtime — casing must be consistent across all artifacts:
47+
- 'bid' not 'placeBid' or 'submit_bid'
48+
- 'challenge' not 'declare_challenge'
49+
- 'play_card' not 'playCard'
50+
- 'draw' not 'draw_card'
51+
- 'submit_choice' not 'submitChoice' or 'SubmitChoice'
5152
5253
# Output Schema
5354

‎src/ai/simulate/graphs/spec-processing-graph/nodes/extract-instructions/prompts.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,8 @@ Focus on:
104104
- **players.{{playerId}}.actionRequired**: Set by mechanics ONLY — never by player action stateDelta. The router uses \`currentAction != null\` to detect a submitted action.
105105
- **players.{{playerId}}.actionsAllowed**: A \`boolean\` — set \`true\` to allow actions, \`false\` to prevent them. Do NOT set it to an array of action IDs or strings. It is not an allowlist; action validation is handled entirely by the \`validation.checks\` in \`playerPhaseInstructions\`. In most transitions simply set it to \`true\` or \`false\` alongside \`actionRequired\`.
106106
- **Player action stateDelta**: MUST ONLY write \`players.{{playerId}}.currentAction\`. Any other write is stripped at runtime. Persisting player choices into other fields (e.g. a \`submittedData\` or \`selectionMade\` flag) is forbidden — the mechanic in the following automatic transition reads from \`currentAction\` instead.
107+
- **Validation enum casing**: String literals in \`validation.checks\` allowed-value arrays MUST use the exact same casing as the corresponding field's \`enumValues\` in the state schema. If the schema defines \`["rock", "paper", "scissors"]\` (lowercase), the validation check MUST also use lowercase. Mismatched casing causes every submission to be rejected before the mechanic runs.
108+
- **No timeout or missing-submission fallback in mechanicsGuidance**: The runtime has no concept of timeouts or time limits. When all players have submitted (guaranteed by \`allPlayersCompletedActions\` precondition), every player's \`currentAction\` will be non-null. Do NOT include instructions like "if a player has no submitted currentAction (timeout), assign a random choice" — this language will be generated into mechanic code that adds unreachable fallback branches and implies the platform supports timeouts, which it does not. Always write mechanicsGuidance as if all required submissions are present.
107109
- **allPlayersCompletedActions**: A router-computed context field that is \`true\` when every player who has \`actionRequired == true\` has also submitted a non-null \`currentAction\`. For transitions that fire when ALL players have simultaneously submitted, the transitions artifact precondition MUST use \`{{"var": "allPlayersCompletedActions"}}\` — do NOT invent a custom boolean signal field for this purpose. Custom signal fields create a circular dependency: the mechanic can only set them after the transition fires, but the transition won't fire until they're set.
108110
- **Signal field reset rule**: If a transition fires based on a boolean signal field (e.g. \`bothPlayersSelected: true\`), the mechanic for that transition — or the mechanic for the immediately following transition — MUST reset that signal field back to \`false\` before the game loops back to the phase that sets it. Failure to reset causes the transition to re-fire immediately on the next iteration without waiting for player input, producing an infinite loop. Always include an explicit "reset signal fields to false" step in the computation guidance for any transition that consumes a boolean signal.
109111
- **Duplicate-submission guard**: Do NOT use \`players.{{playerId}}.currentAction.type != null\` as a validation check to prevent a player from submitting twice. By the time validation runs, \`currentAction.type\` has already been written by the current action — so this guard is always true and rejects every submission including the first. Instead, guard against double submission using a **persistent state field that the automatic mechanic writes** after successfully processing the submission (e.g., a flag or non-null field that only exists in state after the mechanic has run). That field is \`null\`/\`false\` on the first legitimate submission and set on any subsequent attempt.

‎src/ai/simulate/graphs/spec-processing-graph/nodes/extract-transitions/prompts.ts‎

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -176,11 +176,17 @@ immediately or never, breaking the game.
176176
NOT imply a timeout fallback. Do not add \`submission_timeout\` or similar transitions.
177177
178178
## 7. Use allPlayersCompletedActions for Simultaneous Submissions
179-
When a transition fires after ALL players have submitted their action simultaneously, use the computed context field \`allPlayersCompletedActions\` as the precondition — do NOT invent a custom boolean signal field (e.g. \`allActionsSubmitted\`, \`allPlayersReady\`).
179+
When a transition fires after ALL players have submitted, selected, chosen, or acted simultaneously,
180+
use the computed context field \`allPlayersCompletedActions\` as the precondition — do NOT invent a
181+
custom boolean signal field (e.g. \`allActionsSubmitted\`, \`allPlayersReady\`, \`allPlayersSubmitted\`,
182+
\`allChoicesMade\`, \`everyoneActed\`).
180183
181184
Custom signal fields create a **circular dependency**: the mechanic can only set them after the transition fires, but the transition won't fire until they are set → permanent deadlock.
182185
183-
\`allPlayersCompletedActions\` is true when every player with \`actionRequired == true\` has submitted a non-null \`currentAction\`. It is computed by the router before each transition evaluation — no mechanic needs to set it.
186+
\`allPlayersCompletedActions\` is true when every player with \`actionRequired == true\` has submitted
187+
a non-null \`currentAction\`. This covers all equivalent game-design phrasings: "both players chose",
188+
"all players selected", "everyone has acted", "all choices are in", "all submissions received".
189+
It is computed by the router before each transition evaluation — no mechanic needs to set it.
184190
185191
\`\`\`json
186192
// ❌ Wrong — allWeaponsSubmitted is never set before this transition fires
@@ -190,6 +196,35 @@ Custom signal fields create a **circular dependency**: the mechanic can only set
190196
{{ "preconditionHints": [{{"explain": "allPlayersCompletedActions == true"}}] }}
191197
\`\`\`
192198
199+
⛔ **CRITICAL: Do NOT use \`allPlayersCompletedActions\` alone on a gate transition.**
200+
201+
A "gate transition" goes from a player-input phase to an intermediate automatic phase (e.g. \`choosing → resolving\`) with \`allPlayersCompletedActions\` as its ONLY meaningful precondition. This is a **Rule 4 waypoint violation** AND a **data-destruction bug**:
202+
203+
The gate mechanic runs and clears every player's \`currentAction\` field — permanently destroying the submitted data — **before** the actual processing mechanic in the next phase can read it. The processing mechanic then reads \`null\` and crashes. The crash checkpoint persists, and every subsequent player action re-triggers the same crash.
204+
205+
**For simultaneous-submission games, processing transitions MUST fire directly from the player-input phase**, combining \`allPlayersCompletedActions == true\` with their game-specific branch conditions. The router's own wait logic already holds until all players have submitted — a gate transition adds nothing and destroys data.
206+
207+
\`\`\`json
208+
// ❌ Wrong — gate transition (choosing → resolving) destroys currentAction; resolution then crashes
209+
{{ "id": "both_submitted", "fromPhase": "choosing", "toPhase": "resolving",
210+
"preconditionHints": [{{"explain": "allPlayersCompletedActions == true"}}] }}
211+
// ... separate resolve_* transitions from "resolving" phase crash reading null currentAction
212+
213+
// ✅ Right — processing transitions fire directly from the player-input phase
214+
{{ "id": "resolve_and_continue", "fromPhase": "choosing", "toPhase": "choosing",
215+
"preconditionHints": [
216+
{{"explain": "allPlayersCompletedActions == true"}},
217+
{{"explain": "no player has reached the win threshold AND more rounds remain"}}
218+
] }}
219+
{{ "id": "resolve_and_finish", "fromPhase": "choosing", "toPhase": "finished",
220+
"preconditionHints": [
221+
{{"explain": "allPlayersCompletedActions == true"}},
222+
{{"explain": "any player has reached the win threshold OR no more rounds remain"}}
223+
] }}
224+
\`\`\`
225+
226+
Note: The turn-rotation self-loop pattern in Rule 5 (\`all_players_chose: choosing → resolution\`) is safe because each player's submission is processed by the per-turn self-loop mechanic before \`all_players_chose\` fires — \`currentAction\` is already cleared. The anti-pattern here applies only to **simultaneous submission** where all players act without per-submission mechanics.
227+
193228
## 8. Precondition Hint Writing Style
194229
When writing \`explain\` text, use these patterns so the executor synthesizes correct JsonLogic:
195230

‎src/ai/simulate/graphs/spec-processing-graph/nodes/repair-artifacts/index.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import { resolvePositionalPlayerTemplates } from '#chaincraft/ai/simulate/graphs
2121
import type { InstructionsArtifact } from '#chaincraft/ai/simulate/schema.js';
2222
import { generateStateInterfaces } from '#chaincraft/ai/simulate/graphs/spec-processing-graph/nodes/generate-mechanics/generate-state-interfaces.js';
2323
import type { GameStateField } from '#chaincraft/ai/simulate/graphs/spec-processing-graph/nodes/extract-schema/schema.js';
24+
import type { ActionDefinition } from '#chaincraft/ai/simulate/graphs/spec-processing-graph/nodes/extract-action-definitions/schema.js';
2425
import type { CoherenceIssue } from '#chaincraft/ai/simulate/graphs/spec-processing-graph/nodes/coherence-check/schema.js';
2526

2627
// ─── Helpers (spec-processing-specific) ───
@@ -287,7 +288,10 @@ export function createRepairMechanicsNode() {
287288
}
288289

289290
const fields: GameStateField[] = JSON.parse(state.stateSchema);
290-
const stateInterfaces = generateStateInterfaces(fields);
291+
const actionDefs: ActionDefinition[] | undefined = state.actionDefinitions
292+
? JSON.parse(state.actionDefinitions).actions
293+
: undefined;
294+
const stateInterfaces = generateStateInterfaces(fields, actionDefs);
291295

292296
const graph = await createArtifactEditorGraph();
293297
const threadId = config?.configurable?.thread_id || 'repair-mechanics';
@@ -382,7 +386,10 @@ export function createRepairCoherenceNode() {
382386
let stateInterfaces = '';
383387
if (state.stateSchema) {
384388
const fields: GameStateField[] = JSON.parse(state.stateSchema);
385-
stateInterfaces = generateStateInterfaces(fields);
389+
const actionDefs: ActionDefinition[] | undefined = state.actionDefinitions
390+
? JSON.parse(state.actionDefinitions).actions
391+
: undefined;
392+
stateInterfaces = generateStateInterfaces(fields, actionDefs);
386393
}
387394

388395
const graph = await createArtifactEditorGraph();

0 commit comments

Comments
 (0)