From caa9f08e38de383ccd60c15b2a16ca55748d784d Mon Sep 17 00:00:00 2001 From: ewood Date: Mon, 26 Jan 2026 20:12:23 -0500 Subject: [PATCH 1/2] Ensure narratives are input to spec-processing graph to support validation and to runtime graph for use in instructions. --- package.json | 2 +- .../design-to-sim-integration.test.ts | 1 + .../design/__tests__/design-workflow.test.ts | 22 +- src/ai/design/design-workflow.ts | 174 +++----- .../nodes/__tests__/test-utils.ts | 3 + .../__tests__/conversational-agent.test.ts | 22 +- .../__tests__/manual-test.ts | 3 + .../__tests__/spec-execute.test.ts | 4 + .../spec-plan/__tests__/spec-plan.test.ts | 5 +- .../__tests__/coin-flip-workflow.test.ts | 1 + .../graphs/spec-processing-graph/index.ts | 3 +- .../__tests__/extract-schema.test.ts | 79 +--- src/ai/simulate/simulate-workflow.ts | 60 +-- src/api/design/handler.ts | 42 +- src/api/design/routes.ts | 33 -- src/api/simulate/handler.ts | 29 -- src/api/simulate/routes.ts | 20 - src/api/simulate/schemas.ts | 16 - .../clients/discord/chaincraft-design.ts | 1 + .../clients/discord/chaincraft-simulate.ts | 4 +- .../specs/westward-peril-narratives.json | 6 + .../specs/westward-peril-with-narratives.md | 422 ++++++++++++++++++ tests/games/specs/westward-peril.md | 8 +- tests/games/westward-peril.test.ts | 3 +- tests/harness/executor.ts | 50 ++- tests/harness/helpers.ts | 41 ++ tests/harness/run-tests.test.ts | 80 ++-- .../specs/westward-peril-narratives.json | 12 + tests/harness/types.ts | 12 + 29 files changed, 753 insertions(+), 405 deletions(-) create mode 100644 tests/games/specs/westward-peril-narratives.json create mode 100644 tests/games/specs/westward-peril-with-narratives.md create mode 100644 tests/harness/specs/westward-peril-narratives.json diff --git a/package.json b/package.json index 78b331e..fd1ee08 100644 --- a/package.json +++ b/package.json @@ -28,7 +28,7 @@ "test:generate": "npm run build && node --experimental-vm-modules node_modules/jest/bin/jest.js src/gen/generators/__tests__/state-machine-generator.test.ts", "test:action-queues": "npm run build && node --experimental-vm-modules node_modules/jest/bin/jest.js src/ai/simulate/__tests__/action-queues.test.ts", "test:harness": "npm run build && node --experimental-vm-modules node_modules/jest/bin/jest.js tests/harness/run-tests.test.ts", - "test:game": "npm run build && node dist/tests/harness/run-game-test.js", + "test:game": "npm run build && node --loader ts-node/esm tests/harness/run-game-test.ts", "pm2:start": "npm run build && pm2 start ecosystem.config.cjs", "pm2:start:dev": "npm run build && pm2 start ecosystem.config.cjs --env development", "pm2:start:prod": "npm run build && pm2 start ecosystem.config.cjs --env production", diff --git a/src/ai/__tests__/design-to-sim-integration.test.ts b/src/ai/__tests__/design-to-sim-integration.test.ts index d42b4a8..76708e6 100644 --- a/src/ai/__tests__/design-to-sim-integration.test.ts +++ b/src/ai/__tests__/design-to-sim-integration.test.ts @@ -73,6 +73,7 @@ describe("Design-to-Sim Integration", () => { // This should retrieve the spec from the design workflow const { gameRules } = await createSimulation( + `sim-${gameId}`, gameId, specVersion // NOTE: No third parameter - should retrieve from design workflow diff --git a/src/ai/design/__tests__/design-workflow.test.ts b/src/ai/design/__tests__/design-workflow.test.ts index b48f318..cdad084 100644 --- a/src/ai/design/__tests__/design-workflow.test.ts +++ b/src/ai/design/__tests__/design-workflow.test.ts @@ -1,7 +1,7 @@ import { continueDesignConversation, generateImage, - getDesignSpecificationByVersion + getDesignByVersion } from "../design-workflow.js"; let conversationId = `test-conversation-${Date.now()}`; @@ -159,17 +159,21 @@ async function testVersionRetrieval() { // Test 1: Retrieve the final version console.log("\n--- TEST 1: Retrieve Specific Version ---"); - const retrievedSpec = await getDesignSpecificationByVersion( + const retrievedDesign = await getDesignByVersion( conversationId, finalSpecVersion - ); + ) - if (!retrievedSpec) { + if (!retrievedDesign) { throw new Error(`Failed to retrieve version ${finalSpecVersion}`); } + const retrievedSpec = retrievedDesign.specification; + if (!retrievedSpec) { + throw new Error(`Retrieved design does not contain specification for version ${finalSpecVersion}`); + } console.log("✓ Retrieved spec version:", retrievedSpec.version); - console.log("✓ Title:", retrievedSpec.title); + console.log("✓ Title:", retrievedDesign.title); console.log("✓ Summary:", retrievedSpec.summary.substring(0, 100) + "..."); console.log("✓ Spec length:", retrievedSpec.designSpecification.length, "characters"); @@ -182,7 +186,7 @@ async function testVersionRetrieval() { // Test 2: Try to retrieve non-existent version console.log("\n--- TEST 2: Non-existent Version Returns Undefined ---"); const nonExistentVersion = 99999; - const missingSpec = await getDesignSpecificationByVersion( + const missingSpec = await getDesignByVersion( conversationId, nonExistentVersion ); @@ -197,14 +201,14 @@ async function testVersionRetrieval() { // Test 3: Retrieve earlier version if available (version 1) console.log("\n--- TEST 3: Retrieve Earlier Version ---"); - const earlierSpec = await getDesignSpecificationByVersion( + const earlierDesign = await getDesignByVersion( conversationId, 1 ); - + const earlierSpec = earlierDesign?.specification; if (earlierSpec) { console.log("✓ Retrieved earlier spec version:", earlierSpec.version); - console.log("✓ Earlier spec title:", earlierSpec.title); + console.log("✓ Earlier spec title:", earlierDesign?.title); if (earlierSpec.version !== 1) { throw new Error(`Expected version 1, got ${earlierSpec.version}`); diff --git a/src/ai/design/design-workflow.ts b/src/ai/design/design-workflow.ts index 76fbe93..a0110af 100644 --- a/src/ai/design/design-workflow.ts +++ b/src/ai/design/design-workflow.ts @@ -1,7 +1,7 @@ import "dotenv/config.js"; import { SystemMessagePromptTemplate } from "@langchain/core/prompts"; -import { CompiledStateGraph } from "@langchain/langgraph"; +import { Checkpoint, CompiledStateGraph } from "@langchain/langgraph"; import { AIMessage, HumanMessage, @@ -66,26 +66,24 @@ const gameTitleRegex = new RegExp( "s" ); -export type DesignResponse = { - designResponse: string; +/** The state of the game design conversation. */ +export interface DesignState { updatedTitle?: string; - systemPromptVersion?: string; - specification?: { - summary: string; - playerCount: { - min: number; - max: number; - }; - designSpecification: string; - version: number; - }; + title: string; + specification?: GameDesignSpecification specNarratives?: Record; - specDiff?: string; pendingSpecChanges?: string[]; consolidationThreshold?: number; consolidationCharLimit?: number; }; +/** A response from the design workflow. */ +export interface DesignResponse extends DesignState { + designResponse: string; + systemPromptVersion?: string; + specDiff?: string; +} + export async function continueDesignConversation( conversationId: string, userMessage: string, @@ -115,7 +113,7 @@ export async function generateImage( ): Promise { // Retrieve cached specification to avoid regenerating it // Image generation is triggered after conversation continues, so the spec should already exist - const specAndTitle = await getCachedDesignSpecification(conversationId); + const specAndTitle = await getCachedDesign(conversationId); if (!specAndTitle || !specAndTitle.specification) { throw new Error( @@ -210,43 +208,12 @@ export async function generateImage( } } -export async function getFullDesignSpecification( - conversationId: string -): Promise<(GameDesignSpecification & { - title: string; - pendingSpecChanges?: string[]; - consolidationThreshold?: number; - consolidationCharLimit?: number; -}) | undefined> { - const designResponse = await continueDesignConversation( - conversationId, - produceFullGameDesignPrompt - ); - - if (!designResponse.specification) { - return undefined; - } - return { - ...designResponse.specification, - title: designResponse.updatedTitle ?? "", - pendingSpecChanges: designResponse.pendingSpecChanges, - consolidationThreshold: designResponse.consolidationThreshold, - consolidationCharLimit: designResponse.consolidationCharLimit, - }; -} -// Read-only version that gets cached specification without creating checkpoints -export async function getCachedDesignSpecification( +// Read-only version that gets cached design state without creating checkpoints +export async function getCachedDesign( conversationId: string -): Promise<({ - title: string; - specification?: GameDesignSpecification - specNarratives?: Record; - pendingSpecChanges?: string[]; - consolidationThreshold?: number; - consolidationCharLimit?: number; -}) | undefined> { +): Promise { // Check if conversation exists if (!(await isActiveConversation(conversationId))) { throw new Error(`Conversation ${conversationId} not found`); @@ -257,7 +224,7 @@ export async function getCachedDesignSpecification( const config = { configurable: { thread_id: conversationId } }; console.log( - "[getCachedDesignSpecification] Getting latest checkpoint for conversation:", + "[getCachedDesign] Getting latest checkpoint for conversation:", conversationId ); @@ -266,7 +233,7 @@ export async function getCachedDesignSpecification( const firstCheckpoint = await checkpointIterator.next(); if (firstCheckpoint.done) { - console.log("[getCachedDesignSpecification] No checkpoints found"); + console.log("[getCachedDesign] No checkpoints found"); return undefined; } @@ -279,42 +246,7 @@ export async function getCachedDesignSpecification( return undefined; } - // Extract state from the checkpoint - const channelValues = latestCheckpoint.checkpoint.channel_values as any; - const currentGameSpec = channelValues.currentSpec; - const title = channelValues.title; - const specNarratives = channelValues.specNarratives as Record | undefined; - const pendingSpecChanges = channelValues.pendingSpecChanges as SpecPlan[] | undefined; - const consolidationThreshold = channelValues.consolidationThreshold as number | undefined; - const consolidationCharLimit = channelValues.consolidationCharLimit as number | undefined; - - console.log( - "[getCachedDesignSpecification] Found cached spec:", - currentGameSpec ? "yes" : "no", - "title:", - title || "no title", - "pending changes:", - pendingSpecChanges?.length || 0 - ); - - // If we have a cached spec, return it with pending changes - // if (currentGameSpec && currentGameSpec.designSpecification) { - return { - specification: currentGameSpec?.designSpecification ? currentGameSpec : undefined, - title: title || "Untitled Game", - specNarratives, - // Convert SpecPlan[] to string[] (extract changes field) - pendingSpecChanges: pendingSpecChanges && pendingSpecChanges.length > 0 - ? pendingSpecChanges.map(plan => plan.changes) - : undefined, - consolidationThreshold, - consolidationCharLimit, - }; - // } - - // No cached spec available - // console.log("[getCachedDesignSpecification] No cached specification found"); - // return undefined; + return getDesignFromCheckpoint(latestCheckpoint.checkpoint); } /** @@ -325,10 +257,14 @@ export async function getCachedDesignSpecification( * @param version - The specific version number to retrieve * @returns The specification with matching version, or undefined if not found */ -export async function getDesignSpecificationByVersion( +export async function getDesignByVersion( conversationId: string, version: number -): Promise<(GameDesignSpecification & { title: string }) | undefined> { +): Promise<(DesignState | undefined)> { + // Check if conversation exists + if (!(await isActiveConversation(conversationId))) { + throw new Error(`Conversation ${conversationId} not found`); + } // Check if conversation exists if (!(await isActiveConversation(conversationId))) { throw new Error(`Conversation ${conversationId} not found`); @@ -363,10 +299,7 @@ export async function getDesignSpecificationByVersion( title || "no title" ); - return { - ...currentGameSpec, - title: title || "Untitled Game", - }; + return getDesignFromCheckpoint(checkpoint.checkpoint); } } @@ -380,17 +313,6 @@ export async function getDesignSpecificationByVersion( return undefined; } -// Function to generate a new specification (creates checkpoints) -export async function generateNewDesignSpecification( - conversationId: string -): Promise<(GameDesignSpecification & { title: string }) | undefined> { - console.log( - "[generateNewDesignSpecification] Generating new specification for:", - conversationId - ); - return await getFullDesignSpecification(conversationId); -} - export async function getConversationHistory( conversationId: string, page: number = 1, @@ -574,6 +496,44 @@ export async function isActiveConversation( return _isActiveConversation(graphType, conversationId); } +async function getDesignFromCheckpoint( + checkpoint: Checkpoint +): Promise { + // Extract state from the checkpoint + const channelValues = checkpoint.channel_values as any; + const currentGameSpec = channelValues.currentSpec; + const title = channelValues.title; + const specNarratives = channelValues.specNarratives as Record | undefined; + const pendingSpecChanges = channelValues.pendingSpecChanges as SpecPlan[] | undefined; + const consolidationThreshold = channelValues.consolidationThreshold as number | undefined; + const consolidationCharLimit = channelValues.consolidationCharLimit as number | undefined; + + console.log( + "[getCachedDesignSpecification] Found cached spec:", + currentGameSpec ? "yes" : "no", + "title:", + title || "no title", + "pending changes:", + pendingSpecChanges?.length || 0 + ); + + // If we have a cached spec, return it with pending changes + // if (currentGameSpec && currentGameSpec.designSpecification) { + return { + specification: currentGameSpec?.designSpecification ? currentGameSpec : undefined, + title: title || "Untitled Game", + specNarratives, + // Convert SpecPlan[] to string[] (extract changes field) + pendingSpecChanges: pendingSpecChanges && pendingSpecChanges.length > 0 + ? pendingSpecChanges.map(plan => plan.changes) + : undefined, + consolidationThreshold, + consolidationCharLimit, + }; + // } +} + + async function createDesignGraph( conversationId: string ): Promise< @@ -668,6 +628,7 @@ async function _processMessage( specification: updatedSpec, specNarratives: responseNarratives, updatedTitle: lastTitle, + title: lastTitle, systemPromptVersion: lastPromptVersion, specDiff: specDiffSummary, @@ -683,8 +644,3 @@ async function _processMessage( : undefined, }; } - -function _extractGameTitle(content: string): string { - const titleMatch = content.match(gameTitleRegex); - return titleMatch ? titleMatch[1].trim() : ""; -} diff --git a/src/ai/design/graphs/main-design-graph/nodes/__tests__/test-utils.ts b/src/ai/design/graphs/main-design-graph/nodes/__tests__/test-utils.ts index c27d808..a712a70 100644 --- a/src/ai/design/graphs/main-design-graph/nodes/__tests__/test-utils.ts +++ b/src/ai/design/graphs/main-design-graph/nodes/__tests__/test-utils.ts @@ -33,6 +33,9 @@ export function createMockState(overrides?: Partial { // Initial conversation typically doesn't need updates yet // (though agent might decide to set flags - that's okay) - console.log("Response:", result.messages[0].content); + const content = typeof result.messages[0].content === 'string' ? result.messages[0].content : JSON.stringify(result.messages[0].content); + console.log("Response:", content); console.log("Spec update needed:", result.specUpdateNeeded); console.log("Metadata update needed:", result.metadataUpdateNeeded); }, 30000); // 30 second timeout @@ -230,7 +234,8 @@ describe("Conversational Agent - Integration", () => { const result = await agent(state); - console.log("Response:", result.messages[0].content); + const content = typeof result.messages[0].content === 'string' ? result.messages[0].content : JSON.stringify(result.messages[0].content); + console.log("Response:", content); console.log("Spec update needed:", result.specUpdateNeeded); // After a full Q&A exchange with clear rules, should update spec @@ -256,7 +261,8 @@ describe("Conversational Agent - Integration", () => { const result = await agent(state); - console.log("Response:", result.messages[0].content); + const content = typeof result.messages[0].content === 'string' ? result.messages[0].content : JSON.stringify(result.messages[0].content); + console.log("Response:", content); console.log("Metadata update needed:", result.metadataUpdateNeeded); // Should recognize game components and set metadata flag @@ -284,7 +290,8 @@ describe("Conversational Agent - Integration", () => { const result = await agent(state); - console.log("Response:", result.messages[0].content); + const content = typeof result.messages[0].content === 'string' ? result.messages[0].content : JSON.stringify(result.messages[0].content); + console.log("Response:", content); console.log("Spec update needed:", result.specUpdateNeeded); console.log("Metadata update needed:", result.metadataUpdateNeeded); @@ -316,8 +323,8 @@ describe("Conversational Agent - Integration", () => { const result = await agent(state); - console.log("Response:", result.messages[0].content); - console.log("Spec update needed:", result.specUpdateNeeded); + const content = typeof result.messages[0].content === 'string' ? result.messages[0].content : JSON.stringify(result.messages[0].content); + console.log("Response:", content); // Should set spec flag for explicit request after conversation expect(result.specUpdateNeeded).toBe(true); @@ -440,7 +447,8 @@ Reach turn 8 alive.`, // Should respond (asking for clarification or confirming which section) expect(result.messages[0].content).toBeDefined(); - const response = result.messages[0].content.toLowerCase(); + const content = typeof result.messages[0].content === 'string' ? result.messages[0].content : JSON.stringify(result.messages[0].content); + const response = content.toLowerCase(); // Should either: // 1. Ask which narrative section (TURN_1_GUIDE), or diff --git a/src/ai/design/graphs/main-design-graph/nodes/conversational-agent/__tests__/manual-test.ts b/src/ai/design/graphs/main-design-graph/nodes/conversational-agent/__tests__/manual-test.ts index e4295d9..7df849b 100644 --- a/src/ai/design/graphs/main-design-graph/nodes/conversational-agent/__tests__/manual-test.ts +++ b/src/ai/design/graphs/main-design-graph/nodes/conversational-agent/__tests__/manual-test.ts @@ -61,6 +61,9 @@ async function runTest(testName: string, messages: any[], expectedFlags: any) { lastMetadataUpdate: undefined, lastSpecMessageCount: undefined, metadataPlan: undefined, + narrativeStyleGuidance: undefined, + specNarratives: undefined, + narrativesNeedingUpdate: [], pendingSpecChanges: [], forceSpecGeneration: false, consolidationThreshold: 5, diff --git a/src/ai/design/graphs/main-design-graph/nodes/spec-execute/__tests__/spec-execute.test.ts b/src/ai/design/graphs/main-design-graph/nodes/spec-execute/__tests__/spec-execute.test.ts index 574281f..914e921 100644 --- a/src/ai/design/graphs/main-design-graph/nodes/spec-execute/__tests__/spec-execute.test.ts +++ b/src/ai/design/graphs/main-design-graph/nodes/spec-execute/__tests__/spec-execute.test.ts @@ -27,6 +27,7 @@ function createTestState(overrides: { currentSpec?: GameDesignSpecification; pendingSpecChanges?: SpecPlan[]; specVersion?: number; + narrativeStyleGuidance?: string; } = {}) { return { messages: overrides.messages || [], @@ -48,6 +49,9 @@ function createTestState(overrides: { lastMetadataUpdate: undefined, lastSpecMessageCount: undefined, metadataPlan: undefined, + narrativeStyleGuidance: overrides.narrativeStyleGuidance || undefined, + specNarratives: undefined, + narrativesNeedingUpdate: [], pendingSpecChanges: overrides.pendingSpecChanges || [], forceSpecGeneration: false, consolidationThreshold: 5, diff --git a/src/ai/design/graphs/main-design-graph/nodes/spec-plan/__tests__/spec-plan.test.ts b/src/ai/design/graphs/main-design-graph/nodes/spec-plan/__tests__/spec-plan.test.ts index 237d86d..d977d3a 100644 --- a/src/ai/design/graphs/main-design-graph/nodes/spec-plan/__tests__/spec-plan.test.ts +++ b/src/ai/design/graphs/main-design-graph/nodes/spec-plan/__tests__/spec-plan.test.ts @@ -45,12 +45,12 @@ function createTestState(overrides: { currentSpec?: GameDesignSpecification; lastSpecMessageCount?: number; pendingSpecChanges?: SpecPlan[]; + narrativeStyleGuidance?: string; } = {}) { return { messages: overrides.messages || [], title: overrides.title || "", systemPromptVersion: "1.0", - specRequested: false, currentSpec: overrides.currentSpec || undefined, specVersion: 0, specUpdateNeeded: false, @@ -71,6 +71,9 @@ function createTestState(overrides: { forceSpecGeneration: false, consolidationThreshold: 5, consolidationCharLimit: 2000, + narrativeStyleGuidance: overrides.narrativeStyleGuidance || undefined, + specNarratives: undefined, + narrativesNeedingUpdate: [], }; } diff --git a/src/ai/simulate/__tests__/coin-flip-workflow.test.ts b/src/ai/simulate/__tests__/coin-flip-workflow.test.ts index 1f169d2..e730ccb 100644 --- a/src/ai/simulate/__tests__/coin-flip-workflow.test.ts +++ b/src/ai/simulate/__tests__/coin-flip-workflow.test.ts @@ -30,6 +30,7 @@ describe("Coin Flip Simulation", () => { test("should create coin flip simulation and return game rules", async () => { const { gameRules } = await createSimulation( + "test-session-1", // sessionId gameId, 1, // Initial version coinFlipSpec // Optional override for testing diff --git a/src/ai/simulate/graphs/spec-processing-graph/index.ts b/src/ai/simulate/graphs/spec-processing-graph/index.ts index 4179437..5383dd4 100644 --- a/src/ai/simulate/graphs/spec-processing-graph/index.ts +++ b/src/ai/simulate/graphs/spec-processing-graph/index.ts @@ -52,6 +52,7 @@ export async function createSpecProcessingGraph( }); // Define flow with validation error checks + // Route START directly to schema extraction workflow.addEdge(START, "extract_schema" as any); // After schema: check for validation errors before continuing @@ -92,7 +93,5 @@ export async function createSpecProcessingGraph( workflow.addEdge("extract_instructions" as any, END); console.log("[SpecProcessingGraph] Graph compiled successfully"); - console.log(`[SpecProcessingGraph] Using NodeConfig-based subgraphs for all extraction nodes`); - return workflow.compile({ checkpointer }); } diff --git a/src/ai/simulate/graphs/spec-processing-graph/nodes/extract-schema/__tests__/extract-schema.test.ts b/src/ai/simulate/graphs/spec-processing-graph/nodes/extract-schema/__tests__/extract-schema.test.ts index 70964b3..2493832 100644 --- a/src/ai/simulate/graphs/spec-processing-graph/nodes/extract-schema/__tests__/extract-schema.test.ts +++ b/src/ai/simulate/graphs/spec-processing-graph/nodes/extract-schema/__tests__/extract-schema.test.ts @@ -42,89 +42,38 @@ describe.skip("validatePlannerFieldsInSchema", () => { }; it("should validate game fields with 'game.' prefix when path is 'game'", () => { - const plannerFields = [ - { name: "game.turnNumber", path: "game" }, - { name: "game.score", path: "game" } - ]; - - const result = validatePlannerFieldsInSchema(plannerFields, mockSchema); - - expect(result.valid).toBe(true); - expect(result.missingFields).toEqual([]); + // Test is skipped, but was calling old validator signature + // const plannerFields = [ + // { name: "game.turnNumber", path: "game" }, + // { name: "game.score", path: "game" } + // ]; + // const result = validatePlannerFieldsInSchema(plannerFields, mockSchema); + // expect(result.valid).toBe(true); + // expect(result.missingFields).toEqual([]); }); it("should validate player fields with 'players..' prefix when path is 'player'", () => { - const plannerFields = [ - { name: "players..selectedChoice", path: "player" }, - { name: "players..ready", path: "player" } - ]; - - const result = validatePlannerFieldsInSchema(plannerFields, mockSchema); - - expect(result.valid).toBe(true); - expect(result.missingFields).toEqual([]); + // Test is skipped }); it("should validate bare field names without prefix", () => { - const plannerFields = [ - { name: "turnNumber", path: "game" }, - { name: "selectedChoice", path: "player" } - ]; - - const result = validatePlannerFieldsInSchema(plannerFields, mockSchema); - - expect(result.valid).toBe(true); - expect(result.missingFields).toEqual([]); + // Test is skipped }); it("should fail validation when game field has wrong prefix (player. instead of game.)", () => { - const plannerFields = [ - { name: "player.turnNumber", path: "game" } - ]; - - const result = validatePlannerFieldsInSchema(plannerFields, mockSchema); - - expect(result.valid).toBe(false); - expect(result.missingFields).toEqual(["player.turnNumber"]); + // Test is skipped }); it("should fail validation when player field has wrong prefix (game. instead of players.)", () => { - const plannerFields = [ - { name: "game.selectedChoice", path: "player" } - ]; - - const result = validatePlannerFieldsInSchema(plannerFields, mockSchema); - - expect(result.valid).toBe(false); - expect(result.missingFields).toEqual(["game.selectedChoice"]); + // Test is skipped }); it("should fail validation for missing fields", () => { - const plannerFields = [ - { name: "game.nonExistentField", path: "game" }, - { name: "players..missingField", path: "player" } - ]; - - const result = validatePlannerFieldsInSchema(plannerFields, mockSchema); - - expect(result.valid).toBe(false); - expect(result.missingFields).toContain("game.nonExistentField"); - expect(result.missingFields).toContain("players..missingField"); - expect(result.missingFields).toHaveLength(2); + // Test is skipped }); it("should pass validation for mixed valid fields with and without prefixes", () => { - const plannerFields = [ - { name: "game.turnNumber", path: "game" }, - { name: "score", path: "game" }, - { name: "players..selectedChoice", path: "player" }, - { name: "ready", path: "player" } - ]; - - const result = validatePlannerFieldsInSchema(plannerFields, mockSchema); - - expect(result.valid).toBe(true); - expect(result.missingFields).toEqual([]); + // Test is skipped }); }); diff --git a/src/ai/simulate/simulate-workflow.ts b/src/ai/simulate/simulate-workflow.ts index a27a0f3..b03059a 100644 --- a/src/ai/simulate/simulate-workflow.ts +++ b/src/ai/simulate/simulate-workflow.ts @@ -8,8 +8,8 @@ import { SpecProcessingStateType } from "#chaincraft/ai/simulate/graphs/spec-pro import { createRuntimeGraph } from "#chaincraft/ai/simulate/graphs/runtime-graph/index.js"; import { RuntimeStateType } from "#chaincraft/ai/simulate/graphs/runtime-graph/runtime-state.js"; import { - getDesignSpecificationByVersion, - getCachedDesignSpecification + getDesignByVersion, + getCachedDesign as getCachedDesign } from "#chaincraft/ai/design/design-workflow.js"; import { getConfig } from "#chaincraft/config.js"; @@ -103,6 +103,7 @@ export interface SpecArtifacts { stateTransitions: string; playerPhaseInstructions: Record; transitionInstructions: Record; + specNarratives?: Record; } /** @@ -258,7 +259,8 @@ function getRuntimeResponse(state: RuntimeStateType): SimResponse { * @param gameSpecificationVersion - Optional: The version number of the specification * to use. If omitted, uses latest version. * @param gameSpecification - Optional override: if provided, uses this spec directly - * instead of retrieving from design workflow + * instead of retrieving from design workflow. Deprecated in favor of gameId. Do not + * use. * @param preGeneratedArtifacts - Optional pre-generated artifacts (for testing) * @returns The extracted game rules */ @@ -268,8 +270,10 @@ export async function createSimulation( gameSpecificationVersion?: number, gameSpecification?: string, preGeneratedArtifacts?: SpecArtifacts, + specNarrativesOverride?: Record, ): Promise<{ gameRules: string; + specNarratives?: Record; }> { try { console.log("[simulate] Creating simulation for session %s", sessionId); @@ -290,16 +294,18 @@ export async function createSimulation( stateTransitions: preGeneratedArtifacts.stateTransitions, playerPhaseInstructions: preGeneratedArtifacts.playerPhaseInstructions, transitionInstructions: preGeneratedArtifacts.transitionInstructions, + specNarratives: preGeneratedArtifacts.specNarratives, }, runtimeConfig); console.log("[simulate] Pre-generated artifacts stored successfully"); - return { gameRules: preGeneratedArtifacts.gameRules }; + return { gameRules: preGeneratedArtifacts.gameRules, specNarratives: preGeneratedArtifacts.specNarratives }; } // If gameSpecification not provided, retrieve it from design workflow let specToUse = gameSpecification; let versionToUse = gameSpecificationVersion; + let narrativesToUse: Record | undefined = specNarrativesOverride; if (!specToUse) { // We need to fetch spec from design workflow - gameId is required @@ -308,27 +314,26 @@ export async function createSimulation( `gameId is required when gameSpecification is not provided. sessionId (${sessionId}) cannot be used to fetch spec from design workflow.` ); } - } - - if (!specToUse) { + // If no version specified, get the latest if (!versionToUse) { console.log("[simulate] No version specified, retrieving latest spec from design workflow:", gameId); - const latestSpec = await getCachedDesignSpecification(gameId!); + const cachedDesign = await getCachedDesign(gameId!); - if (!latestSpec?.specification?.designSpecification) { + if (!cachedDesign?.specification?.designSpecification) { throw new Error( `Design specification not found for game ${gameId} (latest version)` ); } - specToUse = latestSpec.specification?.designSpecification; - versionToUse = latestSpec.specification?.version; - console.log("[simulate] Retrieved latest spec from design workflow, version:", versionToUse, "title:", latestSpec.title); + specToUse = cachedDesign.specification?.designSpecification; + versionToUse = cachedDesign.specification?.version; + narrativesToUse = cachedDesign.specNarratives; + console.log("[simulate] Retrieved latest spec from design workflow, version:", versionToUse, "title:", cachedDesign.title); } else { // Specific version requested console.log("[simulate] Retrieving spec from design workflow:", gameId, "version:", versionToUse); - const designSpec = await getDesignSpecificationByVersion(gameId!, versionToUse); + const designSpec = await getDesignByVersion(gameId!, versionToUse); if (!designSpec) { throw new Error( @@ -336,7 +341,8 @@ export async function createSimulation( ); } - specToUse = designSpec.designSpecification; + specToUse = designSpec.specification?.designSpecification; + narrativesToUse = designSpec.specNarratives; console.log("[simulate] Retrieved spec from design workflow, title:", designSpec.title); } } else { @@ -367,6 +373,7 @@ export async function createSimulation( // Invoke spec graph - results saved to checkpoint automatically (cached by specKey) const specResult = await specGraph.invoke({ gameSpecification: specToUse, + specNarratives: narrativesToUse, }, specConfig) as SpecProcessingStateType; // Check for validation errors before using artifacts @@ -395,6 +402,8 @@ export async function createSimulation( transitionInstructions: (specResult.transitionInstructions && typeof specResult.transitionInstructions === 'object') ? specResult.transitionInstructions as Record : {}, + // Persist spec narratives alongside artifacts so runtime checkpoints include them + specNarratives: narrativesToUse || undefined, }; console.log("[simulate] Spec processing complete, artifacts cached"); @@ -416,13 +425,19 @@ export async function createSimulation( // Store artifacts by invoking runtime graph with the artifacts // Don't pass isInitialized or players - this routes to END and saves artifacts to checkpoint - const storeResult = await runtimeGraph.invoke({ + const storePayload: Record = { gameRules: artifacts.gameRules, stateSchema: artifacts.stateSchema, stateTransitions: artifacts.stateTransitions, playerPhaseInstructions: artifacts.playerPhaseInstructions, transitionInstructions: artifacts.transitionInstructions, - }, runtimeConfig); + }; + + // Ensure we include specNarratives in the runtime checkpoint. Prefer persisted narratives + // from artifacts, but fall back to the override used when creating the simulation. + storePayload.specNarratives = artifacts.specNarratives || narrativesToUse || undefined; + + const storeResult = await runtimeGraph.invoke(storePayload, runtimeConfig); console.log("[simulate] Artifact storage invoke completed, result:", { hasGameRules: !!storeResult.gameRules, @@ -433,6 +448,8 @@ export async function createSimulation( return { gameRules: artifacts.gameRules, + // Expose specNarratives on the result for testability + specNarratives: artifacts.specNarratives || narrativesToUse || undefined, }; } catch (error) { handleError("Failed to create simulation", error); @@ -613,17 +630,6 @@ export async function getGameState(gameId: string): Promise<{ game: any; players } } -/** - * Updates a simulation with an updated game description. This will attempt to update the - * simulation state schema moving forward to reflect the new game description, while preserving - * the current simulation state. This should allow for the game design to be modified while - * the game is in progress without losing the current game state. - */ -export const updateSimulation = async ( - gameId: string, - gameSpecification: string -): Promise => {}; - const handleError = (message: string, error: unknown): never => { if (error instanceof z.ZodError) { throw new ValidationError(`[simulate] Invalid game state: ${error}`); diff --git a/src/api/design/handler.ts b/src/api/design/handler.ts index 2ccd163..c5715c7 100644 --- a/src/api/design/handler.ts +++ b/src/api/design/handler.ts @@ -22,8 +22,7 @@ import { import { continueDesignConversation, generateImage, - getFullDesignSpecification, - getCachedDesignSpecification, + getCachedDesign, getConversationHistory, isActiveConversation, } from "#chaincraft/ai/design/design-workflow.js"; @@ -117,43 +116,6 @@ export async function handleGenerateImage( } } -export async function handleGetFullSpecification( - request: FastifyRequest<{ Body: GetFullSpecificationRequest }>, - reply: FastifyReply -): Promise { - const result = GetFullSpecificationRequestSchema.safeParse(request.body); - - if (!result.success) { - reply.code(400).send({ error: "Invalid request", details: result.error }); - return Promise.reject(); - } - - try { - const { conversationId } = result.data; - const specification = await getFullDesignSpecification(conversationId); - - if (!specification) { - reply.code(404).send({ error: "Specification not found" }); - return Promise.reject(); - } - - return { - title: specification.title, - summary: specification.summary, - playerCount: specification.playerCount, - designSpecification: specification.designSpecification, - version: specification.version, - pendingSpecChanges: specification.pendingSpecChanges, - consolidationThreshold: specification.consolidationThreshold, - consolidationCharLimit: specification.consolidationCharLimit, - }; - } catch (error) { - console.error("Error in getFullSpecification:", error); - reply.code(500).send({ error: "Internal server error" }); - return Promise.reject(); - } -} - export async function handleGetCachedSpecification( request: FastifyRequest<{ Body: GetFullSpecificationRequest }>, reply: FastifyReply @@ -167,7 +129,7 @@ export async function handleGetCachedSpecification( try { const { conversationId } = result.data; - const specification = await getCachedDesignSpecification(conversationId); + const specification = await getCachedDesign(conversationId); // If no specification data at all, return 404 if (!specification) { diff --git a/src/api/design/routes.ts b/src/api/design/routes.ts index 7d18583..04ccb65 100644 --- a/src/api/design/routes.ts +++ b/src/api/design/routes.ts @@ -3,10 +3,8 @@ import { handleContinueDesignConversation, handleGenerateImage, handleGenerateSpec, - handleGetFullSpecification, handleGetCachedSpecification, handleGetConversationHistory, - handlePublishGame, } from "./handler.js"; import { ContinueDesignConversationRequestSchema, @@ -19,8 +17,6 @@ import { GetFullSpecificationResponseSchema, GetConversationHistoryRequestSchema, GetConversationHistoryResponseSchema, - PublishGameRequestSchema, - PublishGameResponseSchema, } from "#chaincraft/api/design/schemas.js"; import { zodToJsonSchema } from "zod-to-json-schema"; @@ -70,23 +66,6 @@ export async function registerDesignRoutes(server: FastifyInstance) { handler: handleGenerateImage, }); - // Get full specification - server.post("/conversation/specification", { - schema: { - body: zodToJsonSchema( - GetFullSpecificationRequestSchema, - "getFullSpecificationRequest" - ), - response: { - 200: zodToJsonSchema( - GetFullSpecificationResponseSchema, - "getFullSpecificationResponse" - ), - }, - }, - handler: handleGetFullSpecification, - }); - // Get cached specification (no recomputation) server.post("/conversation/specification/cached", { schema: { @@ -120,16 +99,4 @@ export async function registerDesignRoutes(server: FastifyInstance) { }, handler: handleGetConversationHistory, }); - - - // Publish game to IPFS - server.post("/publish", { - schema: { - body: zodToJsonSchema(PublishGameRequestSchema, "publishGameRequest"), - response: { - 200: zodToJsonSchema(PublishGameResponseSchema, "publishGameResponse"), - }, - }, - handler: handlePublishGame, - }); } diff --git a/src/api/simulate/handler.ts b/src/api/simulate/handler.ts index 3e876fa..ea075f6 100644 --- a/src/api/simulate/handler.ts +++ b/src/api/simulate/handler.ts @@ -12,16 +12,12 @@ import { GetSimulationStateRequest, GetSimulationStateRequestSchema, GetSimulationStateResponse, - UpdateSimulationRequest, - UpdateSimulationRequestSchema, - UpdateSimulationResponse, } from "#chaincraft/api/simulate/schemas.js"; import { createSimulation, initializeSimulation, processAction, getSimulationState, - updateSimulation, } from "#chaincraft/ai/simulate/simulate-workflow.js"; export async function handleCreateSimulation( @@ -154,28 +150,3 @@ export async function handleGetSimulationState( return Promise.reject(); } } - -export async function handleUpdateSimulation( - request: FastifyRequest<{ Body: UpdateSimulationRequest }>, - reply: FastifyReply -): Promise { - const result = UpdateSimulationRequestSchema.safeParse(request.body); - - if (!result.success) { - reply.code(400).send({ error: "Invalid request", details: result.error }); - return Promise.reject(); - } - - try { - const { gameId, gameSpecification } = result.data; - await updateSimulation(gameId, gameSpecification); - - return { - success: true, - }; - } catch (error) { - console.error("Error in updateSimulation:", error); - reply.code(500).send({ error: "Internal server error" }); - return Promise.reject(); - } -} diff --git a/src/api/simulate/routes.ts b/src/api/simulate/routes.ts index 3896d90..8aaf594 100644 --- a/src/api/simulate/routes.ts +++ b/src/api/simulate/routes.ts @@ -4,7 +4,6 @@ import { handleInitializeSimulation, handleProcessAction, handleGetSimulationState, - handleUpdateSimulation, } from "./handler.js"; import { CreateSimulationRequestSchema, @@ -15,8 +14,6 @@ import { ProcessActionResponseSchema, GetSimulationStateRequestSchema, GetSimulationStateResponseSchema, - UpdateSimulationRequestSchema, - UpdateSimulationResponseSchema, } from "#chaincraft/api/simulate/schemas.js"; import { zodToJsonSchema } from "zod-to-json-schema"; @@ -85,21 +82,4 @@ export async function registerSimulateRoutes(server: FastifyInstance) { }, handler: handleGetSimulationState, }); - - // Update simulation - server.post("/update", { - schema: { - body: zodToJsonSchema( - UpdateSimulationRequestSchema, - "updateSimulationRequest" - ), - response: { - 200: zodToJsonSchema( - UpdateSimulationResponseSchema, - "updateSimulationResponse" - ), - }, - }, - handler: handleUpdateSimulation, - }); } diff --git a/src/api/simulate/schemas.ts b/src/api/simulate/schemas.ts index 588b527..ff8569c 100644 --- a/src/api/simulate/schemas.ts +++ b/src/api/simulate/schemas.ts @@ -73,16 +73,6 @@ export const GetSimulationStateRequestSchema = z.object({ export const GetSimulationStateResponseSchema = SimResponseSchema; -// Update simulation schemas -export const UpdateSimulationRequestSchema = z.object({ - gameId: z.string().min(1), - gameSpecification: z.string().min(1), -}); - -export const UpdateSimulationResponseSchema = z.object({ - success: z.boolean(), -}); - // Type exports export type RuntimePlayerState = z.infer; export type PlayerStates = z.infer; @@ -107,9 +97,3 @@ export type GetSimulationStateRequest = z.infer< export type GetSimulationStateResponse = z.infer< typeof GetSimulationStateResponseSchema >; -export type UpdateSimulationRequest = z.infer< - typeof UpdateSimulationRequestSchema ->; -export type UpdateSimulationResponse = z.infer< - typeof UpdateSimulationResponseSchema ->; diff --git a/src/integrations/clients/discord/chaincraft-design.ts b/src/integrations/clients/discord/chaincraft-design.ts index dadfba1..ec8b6b5 100644 --- a/src/integrations/clients/discord/chaincraft-design.ts +++ b/src/integrations/clients/discord/chaincraft-design.ts @@ -20,6 +20,7 @@ import { import { continueDesignConversation, DesignResponse, + DesignState, generateImage, isActiveConversation, } from "#chaincraft/ai/design/design-workflow.js"; diff --git a/src/integrations/clients/discord/chaincraft-simulate.ts b/src/integrations/clients/discord/chaincraft-simulate.ts index 751102b..2bba214 100644 --- a/src/integrations/clients/discord/chaincraft-simulate.ts +++ b/src/integrations/clients/discord/chaincraft-simulate.ts @@ -90,8 +90,8 @@ export async function initializeSimulation( // We don't pass gameSpec.designSpecification - it will be retrieved from design workflow //TODO session d needs to be unique otherwise multiple sessions iof the same game will update each others state. const { gameRules } = await createSimulation( - simThread.id, - simThread.id, // gameId (same as sessionId for this integration) + `sim-${simThread.id}`, + simThread.id, // gameId specVersion // gameSpec.designSpecification omitted - retrieved from design graph automatically ); diff --git a/tests/games/specs/westward-peril-narratives.json b/tests/games/specs/westward-peril-narratives.json new file mode 100644 index 0000000..d164691 --- /dev/null +++ b/tests/games/specs/westward-peril-narratives.json @@ -0,0 +1,6 @@ +{ + "TONE_STYLE": "**Tone**: Westward Peril maintains a gritty, atmospheric tone that captures the harsh realities and mortal dangers of 1840s-1880s American frontier expansion. The narrative voice should be serious but not overly dramatic, grounded in the practical concerns of survival while acknowledging the romance and mystique of the untamed West.\n\n**Atmospheric Elements**:\n- Emphasize the vastness, isolation, and unforgiving nature of frontier landscapes\n- Weather, terrain, and natural hazards are constant threats requiring respect\n- Human settlements are sparse, lawless, and often dangerous in their own right\n- Death is common, sudden, and often comes from seemingly minor miscalculations\n- Resources are scarce, help is distant, and self-reliance is paramount\n\n**Language Style**:\n- Use period-appropriate vocabulary and phrasing without archaic density that impedes readability\n- Favor concrete, sensory descriptions over abstract or flowery prose\n- Maintain informal but respectful tone - neither too casual nor overly formal\n- Avoid modern slang, technology references, or anachronistic concepts\n- Keep sentences direct and purposeful, matching the practical mindset of frontier survival\n\n**Narrative Perspective**:\n- Write from third-person limited perspective focused on the player character\n- Maintain immersive present-tense descriptions that put player in immediate danger\n- Balance objective environmental description with subjective character experience\n- Show consequences through specific, physical details rather than emotional abstractions\n\n**Danger Communication**:\n- Present threats as serious but not melodramatic\n- Deadly choices should feel consequential through context, not through obvious warning signs\n- Use environmental cues and situational tension to communicate risk levels\n- Avoid horror-game shock tactics or survival-porn gratuitousness\n- Frame danger as natural result of frontier conditions, not arbitrary narrative punishment\n\n**Character Voice**:\n- Character thoughts and reactions should reflect their specific motivation and frontier pragmatism\n- Maintain consistency with revealed motivation throughout all generated content\n- Balance determination with appropriate caution and uncertainty\n- Show character growth through accumulated experience of frontier hardships\n\n**Cultural Authenticity**:\n- Respect historical realities of westward expansion while avoiding graphic depictions of period's darkest aspects\n- Focus on individual survival story rather than broader historical conflicts\n- Include period-appropriate references to tools, transportation, landmarks, and settlements\n- Maintain folklore and legend elements appropriate to frontier mythology\n- When supernatural motivations appear, ground them in frontier folk beliefs and storytelling traditions", + "TURN_1_GUIDE": "**Setting and Atmosphere for Turn 1**:\nTurn 1 scenarios should establish the character's departure from civilization and their first taste of frontier dangers. Common settings include:\n- Frontier towns with saloons, general stores, and rough characters\n- Trading posts where travelers gather supplies and information\n- River crossings with ferries or fords\n- Early trail segments just beyond settled territories\n- Military outposts or way stations on established routes\n\nThe atmosphere should convey both anticipation and underlying menace. Characters are still close enough to civilization to potentially turn back, making their commitment to continue westward meaningful. Dangers at this stage often involve human threats (con artists, thieves, corrupt officials) or basic wilderness challenges (river crossings, equipment failures, wrong turns).\n\n**Scenario Generation Guidelines**:\n- Introduce immediate practical challenges that test frontier readiness\n- Present situations where character's specific motivation could influence their approach\n- Include environmental details that establish the harsh frontier setting\n- Create scenarios where all four choices seem reasonable to someone unfamiliar with frontier dangers\n- Avoid overwhelming complexity - this is the player's introduction to the game's decision-making\n\n**Choice Design for Turn 1**:\nThe deadly choice should represent a classic \"greenhorn mistake\" - something that seems sensible to someone unfamiliar with frontier realities but proves fatal due to inexperience. Examples include:\n- Trusting the wrong guide or stranger\n- Taking shortcuts through unknown terrain\n- Underestimating weather or natural hazards\n- Making deals that seem advantageous but hide deadly traps\n\nSafe choices should demonstrate frontier wisdom: being cautious with strangers, respecting natural dangers, taking time to gather proper information, or relying on established (if difficult) routes.\n\nThe motivation-aligned choice should show how the character's specific reason for traveling west influences their decision-making, even in early encounters that aren't directly related to their goal.\n\n**Narrative Tone for Turn 1**:\nStrike a balance between adventure and foreboding. The character is embarking on a dangerous journey but hasn't yet faced its worst challenges. Use sensory details to establish the frontier environment - dust, wind, distant horizons, sparse settlements, and the constant awareness that help is far away and getting farther.", + "TURN_2_GUIDE": "**Setting and Atmosphere for Turn 2**:\nTurn 2 scenarios should establish that the character has crossed the threshold from settled territories into the true frontier. The safety net of civilization is now behind them, and they're committed to their westward path. Common settings include:\n- Vast prairie expanses with distant horizons and sparse landmarks\n- River crossings where ferries are unreliable or absent\n- Small frontier settlements with suspicious locals who distrust strangers\n- Trading posts serving as last stops before deeper wilderness\n- Early encounters with weather systems that sweep across open plains\n- Trail junctions where wrong choices lead to trackless wilderness\n\nThe atmosphere should emphasize isolation and the character's growing awareness that they're now dependent on their own judgment. The landscape itself becomes a character - beautiful but indifferent to human survival. Dangers shift from primarily human threats to natural hazards and the consequences of poor navigation or preparation.\n\n**Scenario Generation Guidelines**:\n- Present challenges that require frontier skills: reading weather, judging distances, managing resources\n- Introduce scenarios where the character's motivation might conflict with immediate survival needs\n- Create situations where local knowledge is crucial but hard to obtain or verify\n- Include encounters with other travelers who may be allies, competitors, or threats\n- Establish the rhythm of frontier travel: early starts, long days, careful camping\n\n**Choice Design for Turn 2**:\nThe deadly choice should represent overconfidence or misunderstanding of frontier realities. Characters might underestimate distances, trust unreliable guides, attempt dangerous shortcuts, or ignore warning signs from weather or terrain. Examples include:\n- Following an unmarked trail that promises to save time\n- Attempting river crossings at dangerous points or times\n- Trusting strangers who offer deals that seem too good to be true\n- Ignoring signs of approaching severe weather\n- Pushing travel beyond safe limits to make better time\n\nSafe choices should demonstrate growing frontier wisdom: respecting natural dangers, taking time to verify information, following established routes even when they're longer, and maintaining equipment and supplies properly.\n\nThe motivation-aligned choice should show how the character's driving purpose influences their approach to frontier challenges, perhaps making them more cautious (if fleeing danger) or more aggressive (if pursuing someone or something).\n\n**Narrative Tone for Turn 2**:\nEmphasize the vastness and beauty of the frontier while highlighting its dangers. This is where many characters realize the true scope of their undertaking. Use environmental details to show the transition from settled lands to wilderness: changing vegetation, wider skies, different sounds, and the growing sense of being a small figure in an immense landscape. The character should feel both liberated by the open country and sobered by its challenges.", + "TURN_3_GUIDE": "**Setting and Atmosphere for Turn 3**:\nTurn 3 marks the deep frontier - the character is now truly alone in dangerous territory, far from any semblance of safety or law. Common settings include:\n- Remote mountain passes where weather can trap travelers\n- Desert regions with scarce water and brutal heat or cold\n- Native American territories where cultural misunderstanding can prove fatal\n- Lawless frontier zones controlled by outlaws and brigands\n- Remote wilderness areas with dangerous wildlife\n- Isolated trading posts run by unscrupulous merchants\n\nThe atmosphere should emphasize the character's complete dependence on their own judgment and resources. Society is now a distant memory. The landscape is indifferent and often hostile. Other people encountered are as likely to be dangerous as helpful. This is where survival becomes an all-consuming focus.\n\n**Scenario Generation Guidelines**:\n- Present scenarios that demand accumulated frontier knowledge and instinct\n- Include situations where character must read danger from subtle environmental or social cues\n- Introduce scenarios where the character's specific motivation becomes a liability rather than asset\n- Create encounters with other frontier travelers, each with their own dangerous agendas\n- Establish that the character is now skilled enough to survive, but not experienced enough to predict all dangers\n\n**Choice Design for Turn 3**:\nThe deadly choice should represent a critical judgment error born of cumulative fatigue, desperation, or false confidence. Characters have survived this far but might now assume they're invincible or overlook warning signs. Examples include:\n- Ignoring warnings about dangerous terrain or hostile individuals\n- Taking desperate risks to make better time or gain supplies\n- Trusting someone who reminds them of an earlier ally, not realizing the danger\n- Pushing physical limits beyond what the body can endure\n- Failing to maintain equipment or supplies in deteriorating conditions\n\nSafe choices should demonstrate hard-won frontier wisdom: maintaining supplies and equipment despite hardship, trusting instinct over desperation, seeking information before action, and respecting the environment's unpredictability.\n\nThe motivation-aligned choice should show how the character's driving purpose might push them toward dangerous choices, but they ultimately make the wiser decision.\n\n**Narrative Tone for Turn 3**:\nThis is the midpoint where adventure gives way to grimness. The character has proven they can survive but now faces the psychological toll of frontier hardship. Use descriptions of weariness, damaged equipment, questionable food and water, and the constant awareness of danger. The landscape becomes harsher - mountains loom, deserts stretch endlessly, forests grow darker. Encounters with other travelers should feel tense and unpredictable. The character should feel both toughened by experience and frayed by cumulative stress." +} diff --git a/tests/games/specs/westward-peril-with-narratives.md b/tests/games/specs/westward-peril-with-narratives.md new file mode 100644 index 0000000..6e25445 --- /dev/null +++ b/tests/games/specs/westward-peril-with-narratives.md @@ -0,0 +1,422 @@ +# Westward Peril: Game Specification (Skeleton) + +## Game Overview + +Westward Peril is a single-player narrative adventure game where you journey westward across dangerous frontier territories. Your goal is to survive 5 critical encounters by making wise choices, avoiding deadly outcomes, and ultimately reaching the western coast alive. + +**Core Objective**: Successfully navigate all 5 turns of your westward journey by choosing non-deadly options at each critical juncture. Reach the west coast to achieve victory. One wrong choice means death and immediate game over. + +**Narrative Generation**: Each playthrough generates a unique story driven by your character's random motivation for traveling west. Every scenario, choice description, and outcome is created fresh by AI each playthrough. + +## Tone & Narrative Style + + + +## Game Setup + +### Starting a New Game + +1. **Generate Random Motivation**: At the start of each new game, the system randomly selects one motivation from the following list: + - Fleeing the law after a crime + - Seeking fortune in gold or opportunity + - Escaping a supernatural curse or haunting + - Rescuing a captured loved one + - Running from debt collectors or criminals + - Chasing a person who wronged you + - Seeking religious sanctuary or freedom + - Starting over after personal tragedy + - Following a treasure map or legend + - Fulfilling a dying person's final wish + +2. **Reveal Motivation to Player**: The chosen motivation is displayed to the player immediately at game start, before Turn 1 begins. This motivation remains visible throughout gameplay. + +3. **Initialize Journey Progress**: Journey begins at Turn 1 of 5. Current turn number is always visible. + +4. **Generate First Encounter**: AI procedurally generates the first narrative scenario based on the player's specific motivation and westward journey themes. + +## Gameplay Structure + +### Turn Sequence + +The game consists of exactly **5 turns**. Each turn follows this sequence: + +1. **Situation Description**: AI generates unique narrative scenario describing current circumstances, location, and immediate challenge. + +2. **Choice Presentation**: AI generates exactly **4 distinct choices**, each as **a single sentence**: + - 1 deadly choice (leads to death if selected) + - 3 safe choices (allow continuation) + - 1 motivation-aligned choice (always among the 3 safe choices) + +3. **Choice Selection**: Player selects one of four choices without indicators, warnings, or hints. + +4. **Outcome Resolution**: AI generates narrative consequence: + - **Safe Choice**: 1-2 sentences describing successful navigation and continuation + - **Deadly Choice**: Full paragraph (3-4 sentences minimum) explaining causal chain from choice to death, resulting in immediate game over + +5. **Turn Advancement**: If player survived, game increments to next turn and AI generates new scenario. + +### Turn Progression Details + +- Turns advance sequentially (1 → 2 → 3 → 4 → 5) +- No skipping or returning to previous turns +- Each turn in different location, progressively further west +- Geographic progression: eastern settlements → prairies → mountains → deserts → western territories → coast +- Later turns may reference earlier choices for narrative coherence + +## Choice System + +### Choice Structure + +Each turn presents exactly 4 choices with these properties: + +**Deadly Choice (1 per turn)**: +- Exactly 1 choice per turn is deadly +- Position randomized each turn (no learnable pattern) +- Not marked or indicated during presentation +- Appears narratively plausible and reasonable +- Represents action leading to fatal consequences through clear causal chain + +**Safe Choices (3 per turn)**: +- Remaining 3 choices allow continuation +- May have varying narrative consequences but none result in death +- May involve hardship but player survives to next turn + +**Motivation-Aligned Choice (1 per turn)**: +- Exactly 1 choice per turn aligns with revealed motivation +- Directly serves, relates to, or advances character's reason for going west +- Always one of the 3 safe choices (never the deadly choice) +- Not explicitly marked but recognizable through narrative context + +### Choice Design Principles + +**Procedural Generation via AI**: + + +**Choice Formatting**: +- Each choice written as single sentence describing action +- Choices are clear, direct, and action-oriented +- Choices distinct from one another in description and implied consequence + +**Narrative Quality**: + + +**Fair Challenge**: +- All 4 choices appear plausible, reasonable, worth considering +- Deadly choice not obviously suicidal, nonsensical, or illogical +- Players succeed through consideration, narrative intuition, and luck + +**Motivation Integration**: +- AI considers specific motivation when generating scenario and choices +- Motivation-aligned choice must authentically connect to character's goal +- Not every scenario must center on motivation, but it remains background element + +## Failure System + +### Game Over Conditions + +The game ends immediately in failure when: +- Player selects the deadly choice during any turn (1-5) +- This is the **only** way to lose the game +- No other failure conditions exist + +### Death & Deadly Choice Resolution + +When player selects deadly choice: + +1. **Causal Death Narrative**: AI generates full paragraph (3-4 sentences minimum) describing: + - How chosen action led to death (specific causal chain) + - Why this particular choice was fatal vs alternatives + - Logical connection between action and lethal consequence + +2. **Game Over Display**: Game clearly indicates death, journey ended, game over + +3. **Progress Loss**: Current game progress completely lost + +4. **Final Statistics**: Game displays: + - Turn of Death (Turn 1-5) + - Character Motivation + - Brief Epitaph + +### Restart Options + +After failure, player may restart by: +- **Manually Exiting and Relaunching**: Must completely exit game and launch again. No "New Game" button exists within game interface. + +**New Game Properties**: +- Each relaunched game begins with completely fresh, newly generated random motivation +- All scenarios, choices, and outcomes procedurally generated anew +- No content, knowledge, or progress from previous games carries over + +## Victory Condition + +### Winning the Game + +Player achieves victory by: +- Successfully making non-deadly choices on all 5 turns +- Completing Turn 5 without selecting deadly choice +- Reaching western coast alive + +### Victory Requirements + +**Mandatory**: +- Survive all 5 turns by avoiding deadly choice each turn +- Make final choice on Turn 5 successfully + +**Not Required for Victory**: +- Does NOT need to select motivation-aligned choice every turn +- Does NOT need to optimize narrative outcomes +- Does NOT need to fulfill character's motivation +- Simply surviving and reaching coast is sufficient + +### Victory Resolution + +When player successfully completes Turn 5 without dying: + +1. **Final Arrival Narrative**: AI generates paragraph-length narrative describing arrival at western coast and conclusion of journey + +2. **Motivation Resolution**: Narrative addresses whether player achieved original motivation or is positioned to pursue it + +3. **Victory Display**: Game clearly indicates win and journey complete + +4. **Concluding Statement**: AI generates paragraph-length final statement about character's fate or future at western coast + +### Victory as Binary Outcome + +Victory is **binary** - reach west coast alive (win) or die during journey (lose). There are no: +- Graduated success levels or partial victories +- Quality ratings or performance scores +- Metrics tracking choice quality or optimal paths + +**Narrative Quality Variations**: While victory is binary, narrative content and quality varies based on specific safe choices made and whether motivation-aligned choices were selected. These variations affect only narrative content, not mechanical victory. + +### Post-Victory Restart + +After victory, player may start new game by: +- **Manually Exiting and Relaunching**: Same as failure restart mechanism + +## Procedural Narrative System + +### AI-Generated Content + +Game uses AI to generate all narrative content fresh for each playthrough. **No content is pre-written, templated, or selected from fixed pool.** + +**What AI Generates Each Turn**: + +1. **Scenario Description**: Unique narrative describing current situation, location, challenge, and context + +2. **Four Choice Descriptions**: Four distinct single-sentence descriptions of different actions + +3. **Outcome Narrative**: After choice selection: + - **Safe Choices**: 1-2 sentences explaining immediate consequences + - **Deadly Choices**: Full paragraph (3-4 sentences minimum) explaining causal chain to death + - **Victory**: Paragraph-length narratives for arrival and conclusion + +**AI Generation Parameters**: + + + +### Replayability + +Each new game provides completely unique content: +- Different random motivation (1 of 10 selected randomly) +- Fresh procedural scenarios (all 5 scenarios AI-generated anew) +- Unique choice descriptions (all 20 choices freshly written) +- Randomized deadly choices (position and nature change each playthrough) +- Varied narrative paths based on decisions +- No repeated content from previous playthroughs + +## Turn Details & Gameplay Flow + +### Turn 1: The Journey Begins + +**Context**: Player just begun westward journey, in eastern territories or recently departed civilization. + +**Required Elements**: +- Setting: Towns, settlements, outposts, departure points, early trails +- 4 choices (1 deadly, 3 safe, 1 motivation-aligned among safe) +- Deadly choice leads to death + game over +- Safe choice leads to Turn 2 + +**Narrative Guidance**: + + +### Turn 2: The Open Frontier + +**Context**: Entered open frontier - prairies, grasslands, early wilderness. Civilization behind, committed to journey. + +**Required Elements**: +- Setting: Prairies, grasslands, plains, river crossings, sparse settlements +- 4 choices with same deadly/safe structure + +**Narrative Guidance**: + + +### Turn 3: Major Obstacles + +**Context**: Significant geographic or situational challenges - mountains, rivers, dangerous territories. Journey becomes most difficult. + +**Required Elements**: +- Setting: Mountains, deep wilderness, major rivers, canyons, hostile territories +- 4 choices with same deadly/safe structure + +**Narrative Guidance**: + + +### Turn 4: The Lawless West + +**Context**: Deep in western territories where rules barely apply. Close to goal but maximum danger. + +**Required Elements**: +- Setting: Deserts, lawless territories, outlaw havens, extreme western wilderness +- 4 choices with same deadly/safe structure + +**Narrative Guidance**: + + +### Turn 5: Journey's End + +**Context**: Western coast within reach. Last major obstacle before goal. Victory or death determined by this choice. + +**Required Elements**: +- Setting: Western territories, coast approach, final frontier, Pacific territories +- 4 choices with same deadly/safe structure +- Survive this choice = reach coast and win +- Choose wrongly = entire journey ends in death + +**Narrative Guidance**: + + +## Constraints & Special Rules + +### Mandatory Game Elements + +**Fixed Turn Count**: +- Game is always exactly 5 turns +- No scenarios can extend or shorten journey length +- Turn count does not vary between playthroughs + +**Fixed Choice Count**: +- Every turn presents exactly 4 choices +- No scenarios offer more or fewer options +- Choice count never changes + +**One Deadly Choice Per Turn**: +- Each turn has exactly 1 deadly choice and exactly 3 safe choices +- This ratio is fixed and never changes + +**Single Life System**: +- Player has exactly 1 life per playthrough +- No respawns, continues, extra lives, or second chances +- Death is permanent and ends game immediately + +### Gameplay Constraints + +**No Take-Backs**: +- Once choice selected, cannot be undone, reversed, or changed +- Outcome immediately revealed and permanently locked in + +**No Save/Load System**: +- Game does not save progress mid-game +- No checkpoints, save points, or progress markers +- Each playthrough completed in one continuous session +- Closing/quitting game ends current attempt permanently + +**No Hints, Warnings, or Indicators**: +- Game does not mark, flag, or indicate which choice is deadly +- No warnings, alerts, or hints before selecting any choice +- No visual cues or meta-information distinguish deadly from safe choices +- No indication which choice aligns with motivation + +**Linear Progression**: +- Cannot skip turns or jump ahead +- Cannot return to or replay previous turns +- Journey only moves forward (Turn 1 → 2 → 3 → 4 → 5) +- No branching paths affecting turn order or count + +**No Player History or Statistics**: +- Game does not track or display outcomes from previous playthroughs +- No history, statistics, records, or archives +- Each new game has no reference to previous attempts + +**Manual Restart Mechanism**: +- After game ends (death or victory), no "New Game" button in game interface +- Must completely exit game instance and launch again to start new game + +### Narrative Constraints + +**Motivation Consistency**: +- Character's motivation never changes during playthrough +- All scenarios must respect established motivation +- Motivation-aligned choice must be thematically authentic +- Motivation remains consistent from start to end + +**Western Frontier Theme**: +- All content fits historical/mythological American western frontier (roughly 1840s-1880s) +- Technology and culture match period (no anachronisms) +- Supernatural elements allowed only when tied to specific motivations involving them +- Supernatural content maintains frontier folklore tone, not fantasy/horror + +**Death Plausibility**: +- Deadly choices must result in narratively justified deaths +- Deaths feel like reasonable, logical consequences of chosen action +- Causal link between choice and death must be explainable in full paragraph +- No arbitrary, illogical, or nonsensical deaths + +**AI Content Quality**: +- Generated scenarios specific, detailed, unique (not generic or vague) +- Choice descriptions distinct single sentences describing clear actions +- Outcomes logically follow from choices made +- Narrative prose maintains consistent tone and quality +- Safe outcomes: 1-2 sentences; deadly outcomes: full paragraphs (3-4+ sentences) +- Victory narratives: paragraph-length for both arrival and conclusion + +## Edge Cases & Clarifications + + + +## Summary of Win/Loss Conditions + +### You Win When: +- Successfully complete all 5 turns without dying +- Make final choice on Turn 5 and it is not the deadly choice +- Reach western coast alive + +### You Lose When: +- Select deadly choice on any turn (1-5) +- Character dies from selecting deadly choice +- Journey ends prematurely before Turn 5 completion + +### Victory is Determined By: +- **Survival only** - reaching coast alive +- **NOT** by narrative quality, optimal choices, selecting motivation-aligned choices, achieving personal goal, or performance metrics + +### No Other Outcomes: +- No draws, stalemates, ties, partial victories, or alternative endings +- Game complete when either victory or failure conditions met + +## Implementation Guidance + +### State Management for Deadly Options + +**CRITICAL**: Game must store which choice index is deadly for each turn in game state to enable deterministic precondition checking. + +**Required State Field**: +- Game state MUST include: `game.deadlyChoiceIndexPerTurn: number[]` (5 elements, one per turn) +- Array MUST be initialized during game setup with 5 randomly selected indices (0-3) +- Each turn's deadly choice index determined once and stored, not recalculated + +**Initialization**: +- During game initialization, generate 5 random numbers (each 0-3) representing deadly choice for turns 1-5 +- Store in deadly choice array: `[deadlyTurn1, deadlyTurn2, deadlyTurn3, deadlyTurn4, deadlyTurn5]` +- Example: `[2, 1, 3, 0, 2]` means turn 1's deadly choice is index 2, turn 2's is index 1, etc. + +**Precondition Usage**: +- Transitions checking if choice was deadly MUST use `lookup` operation to access array +- Example: `{"lookup": [{"var": "game.deadlyChoiceIndexPerTurn"}, {"-": [{"var": "game.currentTurn"}, 1]}]}` +- Retrieves deadly choice index for current turn (using turn-1 for 0-based array indexing) +- Compare player's selected choice index against retrieved deadly index + +**Why This Is Required**: +- Preconditions must be deterministic (cannot rely on AI generation or randomness at transition time) +- Storing deadly indices once allows transitions to check "was this choice deadly?" using pure logic +- The `lookup` operation enables dynamic array access using current turn number as index diff --git a/tests/games/specs/westward-peril.md b/tests/games/specs/westward-peril.md index 6aa237c..3ac18a2 100644 --- a/tests/games/specs/westward-peril.md +++ b/tests/games/specs/westward-peril.md @@ -10,6 +10,8 @@ Each playthrough generates a unique story driven by your character's random moti ## Tone & Narrative Style +!___ NARRATIVE:TONE_STYLE ___! + Westward Peril balances dramatic peril with the dark humor and grim fatalism characteristic of frontier survival stories. The game presents genuinely dangerous situations where death is always a possibility, but maintains narrative engagement rather than descending into pure melodrama or comedy. **Narrative Approach**: @@ -50,7 +52,7 @@ The game acknowledges that westward pioneers faced genuine mortal threats (disea The game consists of exactly **3 turns**, each representing a major encounter or decision point during your westward journey. Each turn follows this sequence: -1. **Situation Description**: The AI generates and presents a unique narrative scenario describing your current circumstances, location, and immediate challenge. This description is created fresh for this specific playthrough, incorporating elements tied to your particular motivation when thematically appropriate. The scenario feels like a natural progression of your westward journey and reflects your current geographic position. +1. **Situation Description**: !___ NARRATIVE:SCENARIO_GENERATION_GUIDE ___! The AI generates and presents a unique narrative scenario describing your current circumstances, location, and immediate challenge. This description is created fresh for this specific playthrough, incorporating elements tied to your particular motivation when thematically appropriate. The scenario feels like a natural progression of your westward journey and reflects your current geographic position. 2. **Choice Presentation**: The AI generates exactly **4 distinct choices** representing different approaches to the situation. Each choice is presented as **a single sentence** describing what action your character will take. The four choices include: - 1 deadly choice (leads to death if selected) @@ -60,8 +62,8 @@ The game consists of exactly **3 turns**, each representing a major encounter or 3. **Choice Selection**: You select one of the four choices. You make this selection without any indicators, warnings, or hints about which choice is deadly or which aligns with your motivation. You must rely on narrative context, your judgment, and consideration of your character's motivation. 4. **Outcome Resolution**: The AI generates a narrative consequence for your specific choice: - - **Safe Choice Selected**: The AI generates **1-2 sentences** describing how you successfully navigate the situation and continue your journey. This brief narrative is unique to the choice you made and explains the immediate and relevant consequences. The outcome may be better or worse in narrative quality, but you survive. The turn ends and you proceed to the next turn. - - **Deadly Choice Selected**: The AI generates **a full paragraph (3-4 sentences minimum)** explaining how and why your specific choice led to death or catastrophic failure. This detailed narrative creates a clear causal chain between the action you chose and the fatal outcome - it is not an arbitrary death. The explanation makes narrative sense within the context of the scenario and your choice, fully describing the sequence of events that led to your demise. The game ends immediately in defeat. + - **Safe Choice Selected**: !___ NARRATIVE:SAFE_OUTCOME_GUIDE ___! The AI generates **1-2 sentences** describing how you successfully navigate the situation and continue your journey. This brief narrative is unique to the choice you made and explains the immediate and relevant consequences. The outcome may be better or worse in narrative quality, but you survive. The turn ends and you proceed to the next turn. + - **Deadly Choice Selected**: !___ NARRATIVE:DEADLY_OUTCOME_GUIDE ___! The AI generates **a full paragraph (3-4 sentences minimum)** explaining how and why your specific choice led to death or catastrophic failure. This detailed narrative creates a clear causal chain between the action you chose and the fatal outcome - it is not an arbitrary death. The explanation makes narrative sense within the context of the scenario and your choice, fully describing the sequence of events that led to your demise. The game ends immediately in defeat. 5. **Turn Advancement**: If you survived by selecting a safe choice, the game increments to the next turn (Turn 2, 3, 4, or 5) and the AI generates a completely new procedural scenario for that turn. diff --git a/tests/games/westward-peril.test.ts b/tests/games/westward-peril.test.ts index 1beb03b..454b8b1 100644 --- a/tests/games/westward-peril.test.ts +++ b/tests/games/westward-peril.test.ts @@ -12,7 +12,8 @@ const [playerId] = createPlayerIds(1); export const westwardPerilTest: GameTest = { name: "Westward Peril", - spec: readFileSync(join(__dirname, "specs", "westward-peril.md"), "utf-8"), + spec: readFileSync(join(__dirname, "specs", "westward-peril-with-narratives.md"), "utf-8"), + narrativesFile: "specs/westward-peril-narratives.json", scenarios: [ { diff --git a/tests/harness/executor.ts b/tests/harness/executor.ts index 7aa9a01..87b1ba0 100644 --- a/tests/harness/executor.ts +++ b/tests/harness/executor.ts @@ -7,9 +7,13 @@ import { readFileSync } from "fs"; import { resolve, dirname } from "path"; import { fileURLToPath } from "url"; + +// ESM-safe __filename and __dirname +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); import type { GameTest, Scenario, TestResult, FailurePhase } from "./types.js"; import { createSimulation, initializeSimulation, processAction, getGameState } from "#chaincraft/ai/simulate/simulate-workflow.js"; -import { injectPreGeneratedArtifacts, type SpecArtifacts } from "./helpers.js"; +import { injectPreGeneratedArtifacts, type SpecArtifacts, extractSpecNarratives } from "./helpers.js"; /** * Execute a single game test scenario @@ -75,7 +79,26 @@ export async function executeGameTest( } else { // Step 1: Generate artifacts from spec (or reuse if gameId was provided) console.log(`[${test.name}] ${gameId ? 'Using existing' : 'Generating'} artifacts...`); - const artifacts = await generateArtifacts(test.spec, sessionId, testGameId); + + // Try to load narratives JSON file if test specifies one + let specNarrativesOverride: Record | undefined; + if (test.narrativesFile) { + const specDir = testFileDir || __dirname; + const narrativesPath = resolve(specDir, test.narrativesFile); + + try { + const narrativesJson = readFileSync(narrativesPath, 'utf-8'); + specNarrativesOverride = JSON.parse(narrativesJson); + console.log(`[${test.name}] Loaded narratives from: ${test.narrativesFile}`); + } catch (error) { + const msg = `[${test.name}] Failed to load narratives from ${test.narrativesFile}: ${error instanceof Error ? error.message : String(error)}`; + console.error(msg); + // Fail loudly when a narratives file is explicitly requested so tests don't silently continue + throw new Error(msg); + } + } + + const artifacts = await generateArtifacts(test.spec, sessionId, testGameId, specNarrativesOverride); result.artifactsGenerated = true; // Step 2: Validate artifacts @@ -166,11 +189,26 @@ export async function executeGameTest( /** * Generate artifacts from game specification */ -async function generateArtifacts(spec: string, sessionId: string, gameId?: string): Promise { +async function generateArtifacts( + spec: string, + sessionId: string, + gameId?: string, + specNarrativesOverride?: Record +): Promise { + // Use provided narrative override or extract from spec + let specNarratives = specNarrativesOverride; + + if (!specNarratives) { + specNarratives = extractSpecNarratives(spec); + } + + // If narratives present, we pass them through to the simulation; no debug log. + void specNarratives; + // Use createSimulation which calls spec-processing-graph - // Pass spec directly (no gameId since we're providing the spec, not fetching from design workflow) - // Signature: createSimulation(sessionId, gameId?, version?, spec?) - const result = await createSimulation(sessionId, gameId, 1, spec); + // Pass spec directly with extracted or overridden narratives + // Signature: createSimulation(sessionId, gameId?, version?, spec?, preGeneratedArtifacts?, specNarrativesOverride?) + const result = await createSimulation(sessionId, gameId, 1, spec, undefined, specNarratives); return result; } diff --git a/tests/harness/helpers.ts b/tests/harness/helpers.ts index 9afb656..5a9be07 100644 --- a/tests/harness/helpers.ts +++ b/tests/harness/helpers.ts @@ -37,6 +37,47 @@ export function createGameId(testName?: string): string { return `${prefix}-${timestamp}-${random}`; } +/** + * Extract narrative markers and content from a game specification. + * + * Extracts both: + * 1. Expanded narratives: !___ NARRATIVE_START:KEY ___! ... !___ NARRATIVE_END:KEY ___! + * 2. Inline narratives: ...content... + * + * @param spec - The game specification markdown + * @returns Record mapping marker keys to narrative content + */ +export function extractSpecNarratives(spec: string): Record { + const narratives: Record = {}; + + // Pattern 1: Expanded narratives (from design workflow) + // !___ NARRATIVE_START:KEY ___! + // ...content... + // !___ NARRATIVE_END:KEY ___! + const expandedPattern = /!___ NARRATIVE_START:(\w+) ___!([\s\S]*?)!___ NARRATIVE_END:\1 ___!/g; + let match; + + while ((match = expandedPattern.exec(spec)) !== null) { + const key = match[1]; + const content = match[2].trim(); + narratives[key] = content; + } + + // Pattern 2: Inline narratives (from injected specs) + // + // ...content... + // + const inlinePattern = /([\s\S]*?)/g; + + while ((match = inlinePattern.exec(spec)) !== null) { + const key = match[1]; + const content = match[2].trim(); + narratives[key] = content; + } + + return narratives; +} + /** * Inject pre-generated artifacts into checkpoint storage. * This allows tests to bypass spec processing and use known artifact sets. diff --git a/tests/harness/run-tests.test.ts b/tests/harness/run-tests.test.ts index c51e63a..8bb131d 100644 --- a/tests/harness/run-tests.test.ts +++ b/tests/harness/run-tests.test.ts @@ -22,41 +22,53 @@ const isReliabilityMode = reliabilityIterations > 1; describe("Game Test Harness", () => { // Configure to use test simulation graph setConfig("simulation-graph-type", "test-game-simulation"); - - if (isReliabilityMode) { - // Reliability mode - run multiple iterations - it(`should run RPS reliability test (${reliabilityIterations} iterations, scenario ${reliabilityScenario ?? 'all'})`, async () => { - const report = await runReliabilityTest("rps", reliabilityScenario, reliabilityIterations); - - // Assert at least 80% success rate - if (report.successRate < 0.8) { - throw new Error(`Reliability too low: ${(report.successRate * 100).toFixed(1)}% (expected >= 80%)`); - } - }, reliabilityIterations * 4 * 60 * 1000); // 4 minutes per iteration - - it(`should run Westward Peril reliability test (${reliabilityIterations} iterations, scenario ${reliabilityScenario ?? 'all'})`, async () => { - const report = await runReliabilityTest("westward-peril", reliabilityScenario, reliabilityIterations); - - // Assert at least 80% success rate - if (report.successRate < 0.8) { - throw new Error(`Reliability too low: ${(report.successRate * 100).toFixed(1)}% (expected >= 80%)`); - } - }, reliabilityIterations * 10 * 60 * 1000); // 10 minutes per iteration - } else { - // Normal mode - single run per scenario - it("should run RPS test - scenario 1", async () => { - const result = await runGameTestScenario("rps", 0); - assertTestSuccess(result); - }, 4 * 60 * 1000); // 4 minutes timeout - it("should run Westward Peril test - scenario 1", async () => { - const result = await runGameTestScenario("westward-peril", 0); - assertTestSuccess(result); - }, 10 * 60 * 1000); // 10 minutes timeout for complex narrative games + // Support filtering by GAME env var + const GAME = process.env.GAME && process.env.GAME.toLowerCase(); - it("should run Wacky Weapons Router Bug test - scenario 1", async () => { - const result = await runGameTestScenario("wacky-weapons-router-bug", 0); - assertTestSuccess(result); - }, 4 * 60 * 1000); // 4 minutes timeout + if (isReliabilityMode) { + if (!GAME || GAME === "rps") { + it(`should run RPS reliability test (${reliabilityIterations} iterations, scenario ${reliabilityScenario ?? 'all'})`, async () => { + const report = await runReliabilityTest("rps", reliabilityScenario, reliabilityIterations); + if (report.successRate < 0.8) { + throw new Error(`Reliability too low: ${(report.successRate * 100).toFixed(1)}% (expected >= 80%)`); + } + }, reliabilityIterations * 4 * 60 * 1000); + } + if (!GAME || GAME === "westward-peril") { + it(`should run Westward Peril reliability test (${reliabilityIterations} iterations, scenario ${reliabilityScenario ?? 'all'})`, async () => { + const report = await runReliabilityTest("westward-peril", reliabilityScenario, reliabilityIterations); + if (report.successRate < 0.8) { + throw new Error(`Reliability too low: ${(report.successRate * 100).toFixed(1)}% (expected >= 80%)`); + } + }, reliabilityIterations * 10 * 60 * 1000); + } + if (!GAME || GAME === "wacky-weapons-router-bug") { + it(`should run Wacky Weapons Router Bug reliability test (${reliabilityIterations} iterations, scenario ${reliabilityScenario ?? 'all'})`, async () => { + const report = await runReliabilityTest("wacky-weapons-router-bug", reliabilityScenario, reliabilityIterations); + if (report.successRate < 0.8) { + throw new Error(`Reliability too low: ${(report.successRate * 100).toFixed(1)}% (expected >= 80%)`); + } + }, reliabilityIterations * 4 * 60 * 1000); + } + } else { + if (!GAME || GAME === "rps") { + it("should run RPS test - scenario 1", async () => { + const result = await runGameTestScenario("rps", 0); + assertTestSuccess(result); + }, 4 * 60 * 1000); + } + if (!GAME || GAME === "westward-peril") { + it("should run Westward Peril test - scenario 1", async () => { + const result = await runGameTestScenario("westward-peril", 0); + assertTestSuccess(result); + }, 10 * 60 * 1000); + } + if (!GAME || GAME === "wacky-weapons-router-bug") { + it("should run Wacky Weapons Router Bug test - scenario 1", async () => { + const result = await runGameTestScenario("wacky-weapons-router-bug", 0); + assertTestSuccess(result); + }, 4 * 60 * 1000); + } } }); diff --git a/tests/harness/specs/westward-peril-narratives.json b/tests/harness/specs/westward-peril-narratives.json new file mode 100644 index 0000000..81a2f13 --- /dev/null +++ b/tests/harness/specs/westward-peril-narratives.json @@ -0,0 +1,12 @@ +{ + "TONE_STYLE": "Use a gritty western frontier tone: terse, atmospheric, occasionally darkly ironic.", + "PROCEDURAL_GENERATION": "AI must procedurally generate scenario, choice, and outcome text each turn using the game's random motivation and current turn context.", + "CHOICE_QUALITY": "Choices must be single-sentence, distinct, plausible, and include exactly one motivation-aligned safe option per turn.", + "AI_GENERATION_PARAMETERS": "Preferred lengths: scenarios 2-4 sentences, safe outcomes 1-2 sentences, deadly outcomes 3-4 sentences. Emphasize concrete details and causal clarity.", + "TURN_1_GUIDE": "Turn 1: introduce the departure setting (town, outpost), present four choices (1 deadly, 3 safe), and include one motivation-aligned choice among the safe options.", + "TURN_2_GUIDE": "Turn 2: open frontier setting (prairies, river crossings); generate four choices consistent with escalating stakes.", + "TURN_3_GUIDE": "Turn 3: major obstacles (mountains, deep wilderness); choices should reflect heightened danger and logistical challenges.", + "TURN_4_GUIDE": "Turn 4: lawless west (deserts, outlaw settlements); create tense, morally ambiguous choices that could plausibly lead to death.", + "TURN_5_GUIDE": "Turn 5: final approach to the coast; produce a decisive scenario where surviving the choice results in victory and arrival narrative.", + "EDGE_CASES": "If motivation is missing or contradictory, default to 'seeking fortune' and ensure choices remain clear; avoid supernatural content unless motivation specifies it." +} diff --git a/tests/harness/types.ts b/tests/harness/types.ts index d457d92..4f5d5f8 100644 --- a/tests/harness/types.ts +++ b/tests/harness/types.ts @@ -18,6 +18,18 @@ export interface GameTest { * - Faster test iteration by skipping artifact generation */ artifactsFile?: string; + + /** + * Optional path to narratives JSON file. + * If provided, narratives will be loaded from this file and passed to spec processing. + * Path is relative to the test file location. + * + * Use this for: + * - Injecting pre-generated narratives into the spec processing + * - Testing specific narrative guidance for consistent scenario generation + * - Validating that narratives are properly used by the instruction planner + */ + narrativesFile?: string; } export interface Scenario { From b7b19610c745a651e4ab085c76ffd7fc42594c66 Mon Sep 17 00:00:00 2001 From: ewood Date: Thu, 29 Jan 2026 23:04:07 -0500 Subject: [PATCH 2/2] Regen artifacts if any are missing when creating sim and fix spec narrative validation --- .../__tests__/coin-flip-workflow.test.ts | 6 +- .../graphs/spec-processing-graph/index.ts | 26 +- src/ai/simulate/simulate-workflow.ts | 426 +++++++++++------- src/api/design/handler.ts | 53 --- src/api/design/schemas.ts | 22 +- src/api/simulate/handler.ts | 23 +- src/api/simulate/schemas.ts | 1 + .../clients/discord/specification_manager.ts | 19 +- tests/games/TEST_GENERATION_GUIDE.md | 44 ++ 9 files changed, 360 insertions(+), 260 deletions(-) diff --git a/src/ai/simulate/__tests__/coin-flip-workflow.test.ts b/src/ai/simulate/__tests__/coin-flip-workflow.test.ts index e730ccb..eda5d97 100644 --- a/src/ai/simulate/__tests__/coin-flip-workflow.test.ts +++ b/src/ai/simulate/__tests__/coin-flip-workflow.test.ts @@ -32,8 +32,10 @@ describe("Coin Flip Simulation", () => { const { gameRules } = await createSimulation( "test-session-1", // sessionId gameId, - 1, // Initial version - coinFlipSpec // Optional override for testing + 1, // version + { + overrideSpecification: coinFlipSpec, + } ); expect(gameRules).toBeDefined(); diff --git a/src/ai/simulate/graphs/spec-processing-graph/index.ts b/src/ai/simulate/graphs/spec-processing-graph/index.ts index 5383dd4..5039b58 100644 --- a/src/ai/simulate/graphs/spec-processing-graph/index.ts +++ b/src/ai/simulate/graphs/spec-processing-graph/index.ts @@ -53,7 +53,31 @@ export async function createSpecProcessingGraph( // Define flow with validation error checks // Route START directly to schema extraction - workflow.addEdge(START, "extract_schema" as any); + // Decide where to start based on any existing artifacts and the atomic regen flag. + // If schema is missing -> schema. If transitions or instructions missing and + // `atomicArtifactRegen` is true -> go back to schema to regenerate whole set. + // Otherwise route to the missing subgraph directly. + workflow.addConditionalEdges( + START, + (state: any) => { + const atomic = !!state.atomicArtifactRegen; + const hasSchema = state.stateSchema && state.stateSchema.length > 0; + const hasTransitions = state.stateTransitions && state.stateTransitions.length > 0; + const hasPlayerPhaseInstructions = state.playerPhaseInstructions && Object.keys(state.playerPhaseInstructions || {}).length > 0; + const hasTransitionInstructions = state.transitionInstructions && Object.keys(state.transitionInstructions || {}).length > 0; + + if (!hasSchema) return "schema"; + if (!hasTransitions) return atomic ? "schema" : "transitions"; + if (!hasPlayerPhaseInstructions || !hasTransitionInstructions) return atomic ? "schema" : "instructions"; + return "end"; + }, + { + schema: "extract_schema" as any, + transitions: "extract_transitions" as any, + instructions: "extract_instructions" as any, + end: END, + } + ); // After schema: check for validation errors before continuing workflow.addConditionalEdges( diff --git a/src/ai/simulate/simulate-workflow.ts b/src/ai/simulate/simulate-workflow.ts index b03059a..d33aa4b 100644 --- a/src/ai/simulate/simulate-workflow.ts +++ b/src/ai/simulate/simulate-workflow.ts @@ -7,9 +7,9 @@ import { createSpecProcessingGraph } from "#chaincraft/ai/simulate/graphs/spec-p import { SpecProcessingStateType } from "#chaincraft/ai/simulate/graphs/spec-processing-graph/spec-processing-state.js"; import { createRuntimeGraph } from "#chaincraft/ai/simulate/graphs/runtime-graph/index.js"; import { RuntimeStateType } from "#chaincraft/ai/simulate/graphs/runtime-graph/runtime-state.js"; -import { +import { getDesignByVersion, - getCachedDesign as getCachedDesign + getCachedDesign as getCachedDesign, } from "#chaincraft/ai/design/design-workflow.js"; import { getConfig } from "#chaincraft/config.js"; @@ -21,25 +21,32 @@ import { InMemoryStore } from "@langchain/langgraph"; /** * Replace player aliases (player1, player2, etc.) with real UUIDs in message text. * Case-insensitive but requires exact pattern match (e.g., "Player 1" won't match). - * + * * @param message - Message text containing player aliases * @param playerMapping - Mapping from aliases (player1, player2) to UUIDs * @returns Message with aliases replaced by UUIDs */ -function replacePlayerAliasesWithUUIDs(message: string, playerMapping: Record): string { +function replacePlayerAliasesWithUUIDs( + message: string, + playerMapping: Record, +): string { // Match player1, player2, etc. (case-insensitive, word boundaries) return message.replace(/\bplayer(\d+)\b/gi, (match) => { // Normalize to lowercase to look up in mapping const alias = match.toLowerCase(); const uuid = playerMapping[alias]; - + if (uuid) { - console.debug(`[simulate_workflow] Replaced ${match} with ${uuid} in message`); + console.debug( + `[simulate_workflow] Replaced ${match} with ${uuid} in message`, + ); return uuid; } - + // If no mapping found, return original (shouldn't happen but safe fallback) - console.warn(`[simulate_workflow] No UUID found for player alias: ${match}`); + console.warn( + `[simulate_workflow] No UUID found for player alias: ${match}`, + ); return match; }); } @@ -50,7 +57,7 @@ const runtimeGraphCache = new GraphCache( const saver = await getSaver(threadId, getConfig("simulation-graph-type")); return await createRuntimeGraph(saver); }, - parseInt(process.env.CHAINCRAFT_RUNTIME_GRAPH_CACHE_SIZE ?? "100") + parseInt(process.env.CHAINCRAFT_RUNTIME_GRAPH_CACHE_SIZE ?? "100"), ); // Cache for spec processing graphs to avoid reprocessing specs @@ -59,7 +66,7 @@ const specGraphCache = new GraphCache( const saver = await getSaver(specKey, getConfig("simulation-graph-type")); return await createSpecProcessingGraph(saver); }, - parseInt(process.env.CHAINCRAFT_SPEC_GRAPH_CACHE_SIZE ?? "50") + parseInt(process.env.CHAINCRAFT_SPEC_GRAPH_CACHE_SIZE ?? "50"), ); export interface RuntimePlayerState { @@ -73,23 +80,29 @@ export interface RuntimePlayerState { * Get effective actionsAllowed value for a player. * If actionsAllowed is explicitly set, use that value. * Otherwise, default to match actionRequired. - * + * * Also validates and warns if actionRequired is true but actionsAllowed is false. */ export function getActionsAllowed(playerState: RuntimePlayerState): boolean { // If explicitly set (not null/undefined), use that value - if (playerState.actionsAllowed !== null && playerState.actionsAllowed !== undefined) { + if ( + playerState.actionsAllowed !== null && + playerState.actionsAllowed !== undefined + ) { // Validate: if actionRequired is true, actionsAllowed cannot be false - if (playerState.actionRequired === true && playerState.actionsAllowed === false) { + if ( + playerState.actionRequired === true && + playerState.actionsAllowed === false + ) { console.warn( - '[getActionsAllowed] Invalid state: actionRequired is true but actionsAllowed is false. ' + - 'Forcing actionsAllowed to true to match actionRequired.' + "[getActionsAllowed] Invalid state: actionRequired is true but actionsAllowed is false. " + + "Forcing actionsAllowed to true to match actionRequired.", ); return true; } return playerState.actionsAllowed; } - + // Default to match actionRequired return playerState.actionRequired; } @@ -111,7 +124,7 @@ export interface SpecArtifacts { * Similar to getCachedDesignSpecification in design-workflow. */ async function getCachedSpecArtifacts( - specKey: string + specKey: string, ): Promise { const saver = await getSaver(specKey, getConfig("simulation-graph-type")); const config = { configurable: { thread_id: specKey } }; @@ -133,25 +146,13 @@ async function getCachedSpecArtifacts( } const channelValues = latestCheckpoint.checkpoint.channel_values as any; - - // Check if we have all required artifacts - if (channelValues.gameRules && - channelValues.stateSchema && - channelValues.stateTransitions && - channelValues.playerPhaseInstructions && - channelValues.transitionInstructions) { - console.log("[simulate] Found cached spec artifacts"); - return { - gameRules: channelValues.gameRules, - stateSchema: channelValues.stateSchema, - stateTransitions: channelValues.stateTransitions, - playerPhaseInstructions: channelValues.playerPhaseInstructions, - transitionInstructions: channelValues.transitionInstructions, - }; - } - - console.log("[simulate] Incomplete artifacts in checkpoint"); - return undefined; + return { + gameRules: channelValues.gameRules, + stateSchema: channelValues.stateSchema, + stateTransitions: channelValues.stateTransitions, + playerPhaseInstructions: channelValues.playerPhaseInstructions, + transitionInstructions: channelValues.transitionInstructions, + }; } export type SimResponse = { @@ -159,7 +160,11 @@ export type SimResponse = { playerStates: PlayerStates; gameEnded: boolean; gameError?: { - errorType: 'deadlock' | 'invalid_state' | 'rule_violation' | 'transition_failed'; + errorType: + | "deadlock" + | "invalid_state" + | "rule_violation" + | "transition_failed"; errorMessage: string; errorContext?: any; timestamp: string; @@ -199,47 +204,48 @@ function getRuntimeResponse(state: RuntimeStateType): SimResponse { gameError: undefined, }; } - + const gameState = JSON.parse(state.gameState); - + // Extract game and players from parsed state const { game, players } = gameState; - + // Get player mapping for alias replacement in messages const playerMapping = deserializePlayerMapping(state.playerMapping || "{}"); - + // Replace player aliases with UUIDs in public message - const publicMessage = game?.publicMessage + const publicMessage = game?.publicMessage ? replacePlayerAliasesWithUUIDs(game.publicMessage, playerMapping) : undefined; - + const gameEnded = game?.gameEnded ?? false; const gameError = game?.gameError || undefined; const playerStates: PlayerStates = new Map(); - + for (const playerId in players) { const rawPrivateMessage = players[playerId].privateMessage; const actionRequired = players[playerId].actionRequired ?? false; const actionsAllowed = players[playerId].actionsAllowed; - + // Replace player aliases with UUIDs in private message const privateMessage = rawPrivateMessage ? replacePlayerAliasesWithUUIDs(rawPrivateMessage, playerMapping) : undefined; - + // Build player state with actionsAllowed defaulted to actionRequired const playerState: RuntimePlayerState = { privateMessage, actionRequired, illegalActionCount: players[playerId].illegalActionCount ?? 0, - actionsAllowed: actionsAllowed !== undefined && actionsAllowed !== null - ? actionsAllowed - : actionRequired, // Default to actionRequired if not explicitly set + actionsAllowed: + actionsAllowed !== undefined && actionsAllowed !== null + ? actionsAllowed + : actionRequired, // Default to actionRequired if not explicitly set }; - + playerStates.set(playerId, playerState); } - + return { publicMessage, playerStates, @@ -250,179 +256,259 @@ function getRuntimeResponse(state: RuntimeStateType): SimResponse { /** * Creates a simulation by processing game specification and storing artifacts. - * - * @param sessionId - The ID of the game session. The same id should be used for + * + * @param sessionId - The ID of the game session. The same id should be used for * subsequent calls to initialize and process actions. This id must be unique across * all simulation sessions. - * @param gameId - Optional: The game ID (conversationId) to fetch spec from design + * @param gameId - Optional: The game ID (conversationId) to fetch spec from design * workflow. If not provided, the specification must be provided directly. - * @param gameSpecificationVersion - Optional: The version number of the specification + * @param gameSpecificationVersion - Optional: The version number of the specification * to use. If omitted, uses latest version. - * @param gameSpecification - Optional override: if provided, uses this spec directly + * @param gameSpecification - Optional override: if provided, uses this spec directly * instead of retrieving from design workflow. Deprecated in favor of gameId. Do not * use. * @param preGeneratedArtifacts - Optional pre-generated artifacts (for testing) * @returns The extracted game rules */ +export type CreateSimulationOptions = { + overrideSpecification?: string; + preGeneratedArtifacts?: SpecArtifacts; + specNarrativesOverride?: Record; + atomicArtifactRegen?: boolean; +}; + export async function createSimulation( sessionId: string, gameId?: string, gameSpecificationVersion?: number, - gameSpecification?: string, - preGeneratedArtifacts?: SpecArtifacts, - specNarrativesOverride?: Record, + options?: CreateSimulationOptions, ): Promise<{ gameRules: string; specNarratives?: Record; }> { try { console.log("[simulate] Creating simulation for session %s", sessionId); - + const { + overrideSpecification, + preGeneratedArtifacts, + specNarrativesOverride, + atomicArtifactRegen, + } = options || {}; + // If pre-generated artifacts provided (testing mode), use them directly if (preGeneratedArtifacts) { console.log("[simulate] Using pre-generated artifacts (test mode)"); - + // Store artifacts in runtime graph checkpoint using sessionId const runtimeGraph = await runtimeGraphCache.getGraph(sessionId); const runtimeConfig = { configurable: { thread_id: sessionId } }; - - console.log("[simulate] Storing pre-generated artifacts in runtime graph with sessionId:", sessionId); - - await runtimeGraph.invoke({ + + console.log( + "[simulate] Storing pre-generated artifacts in runtime graph with sessionId:", + sessionId, + ); + + await runtimeGraph.invoke( + { + gameRules: preGeneratedArtifacts.gameRules, + stateSchema: preGeneratedArtifacts.stateSchema, + stateTransitions: preGeneratedArtifacts.stateTransitions, + playerPhaseInstructions: + preGeneratedArtifacts.playerPhaseInstructions, + transitionInstructions: preGeneratedArtifacts.transitionInstructions, + specNarratives: preGeneratedArtifacts.specNarratives, + }, + runtimeConfig, + ); + + console.log("[simulate] Pre-generated artifacts stored successfully"); + + return { gameRules: preGeneratedArtifacts.gameRules, - stateSchema: preGeneratedArtifacts.stateSchema, - stateTransitions: preGeneratedArtifacts.stateTransitions, - playerPhaseInstructions: preGeneratedArtifacts.playerPhaseInstructions, - transitionInstructions: preGeneratedArtifacts.transitionInstructions, specNarratives: preGeneratedArtifacts.specNarratives, - }, runtimeConfig); - - console.log("[simulate] Pre-generated artifacts stored successfully"); - - return { gameRules: preGeneratedArtifacts.gameRules, specNarratives: preGeneratedArtifacts.specNarratives }; + }; } - - // If gameSpecification not provided, retrieve it from design workflow - let specToUse = gameSpecification; + + // If overrideSpecification not provided, retrieve it from design workflow + let specToUse = overrideSpecification as string | undefined; let versionToUse = gameSpecificationVersion; - let narrativesToUse: Record | undefined = specNarrativesOverride; - + let narrativesToUse: Record | undefined = + specNarrativesOverride; + if (!specToUse) { // We need to fetch spec from design workflow - gameId is required if (!gameId) { throw new Error( - `gameId is required when gameSpecification is not provided. sessionId (${sessionId}) cannot be used to fetch spec from design workflow.` + `gameId is required when gameSpecification is not provided. sessionId (${sessionId}) cannot be used to fetch spec from design workflow.`, ); } // If no version specified, get the latest if (!versionToUse) { - console.log("[simulate] No version specified, retrieving latest spec from design workflow:", gameId); + console.log( + "[simulate] No version specified, retrieving latest spec from design workflow:", + gameId, + ); const cachedDesign = await getCachedDesign(gameId!); - + if (!cachedDesign?.specification?.designSpecification) { throw new Error( - `Design specification not found for game ${gameId} (latest version)` + `Design specification not found for game ${gameId} (latest version)`, ); } - + specToUse = cachedDesign.specification?.designSpecification; versionToUse = cachedDesign.specification?.version; narrativesToUse = cachedDesign.specNarratives; - console.log("[simulate] Retrieved latest spec from design workflow, version:", versionToUse, "title:", cachedDesign.title); + console.log( + "[simulate] Retrieved latest spec from design workflow, version:", + versionToUse, + "title:", + cachedDesign.title, + ); } else { // Specific version requested - console.log("[simulate] Retrieving spec from design workflow:", gameId, "version:", versionToUse); + console.log( + "[simulate] Retrieving spec from design workflow:", + gameId, + "version:", + versionToUse, + ); const designSpec = await getDesignByVersion(gameId!, versionToUse); - + if (!designSpec) { throw new Error( - `Design specification not found for game ${gameId} version ${versionToUse}` + `Design specification not found for game ${gameId} version ${versionToUse}`, ); } - + specToUse = designSpec.specification?.designSpecification; narrativesToUse = designSpec.specNarratives; - console.log("[simulate] Retrieved spec from design workflow, title:", designSpec.title); + console.log( + "[simulate] Retrieved spec from design workflow, title:", + designSpec.title, + ); } } else { - console.log("[simulate] Using provided game specification (override mode)"); + console.log( + "[simulate] Using provided game specification (override mode)", + ); // If version not provided with override, default to 1 for testing if (!versionToUse) { versionToUse = 1; - console.log("[simulate] No version provided with override, defaulting to version 1"); + console.log( + "[simulate] No version provided with override, defaulting to version 1", + ); } } - + // Create spec key from conversation ID and version (for caching spec artifacts) const specKey = `${gameId}-v${versionToUse}`; - + // Step 1: Check for cached spec artifacts or generate new ones let artifacts = await getCachedSpecArtifacts(specKey); - - if (!artifacts) { + console.log("[simulate] Cached artifacts: %o", artifacts); + + if ( + !artifacts?.stateSchema || + artifacts?.stateSchema?.length === 0 || + !artifacts?.stateTransitions || + artifacts?.stateTransitions?.length === 0 || + !artifacts?.playerPhaseInstructions || + Object.keys(artifacts?.playerPhaseInstructions).length === 0 || + !artifacts?.transitionInstructions || + Object.keys(artifacts?.transitionInstructions).length === 0 + ) { console.log("[simulate] Processing game specification (not cached)"); - + // Get or create spec processing graph for this spec const specGraph = await specGraphCache.getGraph(specKey); - const specConfig = { + const specConfig = { configurable: { thread_id: specKey }, - store: new InMemoryStore() + store: new InMemoryStore(), }; - + // Invoke spec graph - results saved to checkpoint automatically (cached by specKey) - const specResult = await specGraph.invoke({ - gameSpecification: specToUse, - specNarratives: narrativesToUse, - }, specConfig) as SpecProcessingStateType; - + // Clear validation errors to prevent accumulation from previous failed runs + const specResult = (await specGraph.invoke( + { + gameSpecification: specToUse, + specNarratives: narrativesToUse, + atomicArtifactRegen: atomicArtifactRegen !== false, // Default to true + // Explicitly clear validation errors to start fresh + schemaValidationErrors: undefined, + transitionsValidationErrors: undefined, + instructionsValidationErrors: undefined, + }, + specConfig, + )) as SpecProcessingStateType; + // Check for validation errors before using artifacts - const schemaErrors = Array.isArray(specResult.schemaValidationErrors) ? specResult.schemaValidationErrors : []; - const transitionsErrors = Array.isArray(specResult.transitionsValidationErrors) ? specResult.transitionsValidationErrors : []; - const instructionsErrors = Array.isArray(specResult.instructionsValidationErrors) ? specResult.instructionsValidationErrors : []; + const schemaErrors = Array.isArray(specResult.schemaValidationErrors) + ? specResult.schemaValidationErrors + : []; + const transitionsErrors = Array.isArray( + specResult.transitionsValidationErrors, + ) + ? specResult.transitionsValidationErrors + : []; + const instructionsErrors = Array.isArray( + specResult.instructionsValidationErrors, + ) + ? specResult.instructionsValidationErrors + : []; const validationErrors = [ ...schemaErrors, ...transitionsErrors, ...instructionsErrors, ]; - + if (validationErrors.length > 0) { - const errorMessage = `Spec processing failed validation with ${validationErrors.length} error(s):\n${validationErrors.join('\n')}`; + const errorMessage = `Spec processing failed validation with ${validationErrors.length} error(s):\n${validationErrors.join("\n")}`; console.error("[simulate]", errorMessage); throw new Error(errorMessage); } - + artifacts = { gameRules: String(specResult.gameRules || ""), stateSchema: String(specResult.stateSchema || ""), stateTransitions: String(specResult.stateTransitions || ""), - playerPhaseInstructions: (specResult.playerPhaseInstructions && typeof specResult.playerPhaseInstructions === 'object') - ? specResult.playerPhaseInstructions as Record - : {}, - transitionInstructions: (specResult.transitionInstructions && typeof specResult.transitionInstructions === 'object') - ? specResult.transitionInstructions as Record - : {}, + playerPhaseInstructions: + specResult.playerPhaseInstructions && + typeof specResult.playerPhaseInstructions === "object" + ? (specResult.playerPhaseInstructions as Record) + : {}, + transitionInstructions: + specResult.transitionInstructions && + typeof specResult.transitionInstructions === "object" + ? (specResult.transitionInstructions as Record) + : {}, // Persist spec narratives alongside artifacts so runtime checkpoints include them specNarratives: narrativesToUse || undefined, }; - + console.log("[simulate] Spec processing complete, artifacts cached"); } else { console.log("[simulate] Using cached spec artifacts"); } - + // Step 2: Store artifacts in runtime graph checkpoint using sessionId // Get cached runtime graph for this session const runtimeGraph = await runtimeGraphCache.getGraph(sessionId); const runtimeConfig = { configurable: { thread_id: sessionId } }; - - console.log("[simulate] Storing artifacts in runtime graph with sessionId:", sessionId); - + + console.log( + "[simulate] Storing artifacts in runtime graph with sessionId:", + sessionId, + ); + // Ensure artifacts is defined before using it if (!artifacts) { - throw new Error("[simulate] Artifacts not available - cannot store in runtime graph"); + throw new Error( + "[simulate] Artifacts not available - cannot store in runtime graph", + ); } - + // Store artifacts by invoking runtime graph with the artifacts // Don't pass isInitialized or players - this routes to END and saves artifacts to checkpoint const storePayload: Record = { @@ -435,17 +521,21 @@ export async function createSimulation( // Ensure we include specNarratives in the runtime checkpoint. Prefer persisted narratives // from artifacts, but fall back to the override used when creating the simulation. - storePayload.specNarratives = artifacts.specNarratives || narrativesToUse || undefined; + storePayload.specNarratives = + artifacts.specNarratives || narrativesToUse || undefined; const storeResult = await runtimeGraph.invoke(storePayload, runtimeConfig); - + console.log("[simulate] Artifact storage invoke completed, result:", { hasGameRules: !!storeResult.gameRules, hasStateSchema: !!storeResult.stateSchema, }); - - console.log("[simulate] Runtime graph initialized with artifacts for session %s", sessionId); - + + console.log( + "[simulate] Runtime graph initialized with artifacts for session %s", + sessionId, + ); + return { gameRules: artifacts.gameRules, // Expose specNarratives on the result for testability @@ -459,21 +549,21 @@ export async function createSimulation( export async function initializeSimulation( gameId: string, - players: string[] + players: string[], ): Promise<{ publicMessage?: string; playerStates: PlayerStates; }> { try { console.log("[simulate] Initializing simulation for game %s", gameId); - + // Normalize player IDs to lowercase for consistent handling - const normalizedPlayers = players.map(p => p.toLowerCase()); - + const normalizedPlayers = players.map((p) => p.toLowerCase()); + // Get cached runtime graph with checkpointer const runtimeGraph = await runtimeGraphCache.getGraph(gameId); const config = { configurable: { thread_id: gameId } }; - + // Log checkpoint state to verify artifacts are present const saver = await getSaver(gameId, getConfig("simulation-graph-type")); const checkpoint = await saver.getTuple(config); @@ -491,19 +581,22 @@ export async function initializeSimulation( } else { console.log("[simulate] No checkpoint found before initialization"); } - + // Invoke runtime graph with players - artifacts loaded automatically from checkpoint - const result = await runtimeGraph.invoke({ - players: normalizedPlayers, - isInitialized: false, - }, config); - + const result = await runtimeGraph.invoke( + { + players: normalizedPlayers, + isInitialized: false, + }, + config, + ); + // Extract response from return value const simResponse = getRuntimeResponse(result as RuntimeStateType); - - return { - publicMessage: simResponse.publicMessage, - playerStates: simResponse.playerStates + + return { + publicMessage: simResponse.publicMessage, + playerStates: simResponse.playerStates, }; } catch (error) { handleError("Failed to initialize simulation", error); @@ -514,7 +607,7 @@ export async function initializeSimulation( export async function processAction( gameId: string, playerId: string, - action: string + action: string, ): Promise { // Queue the action to ensure sequential processing return queueAction(gameId, async () => { @@ -523,27 +616,30 @@ export async function processAction( "[simulate] Processing action for game %s player %s: %s", gameId, playerId, - action + action, ); - + // Normalize player ID to lowercase for consistent handling const normalizedPlayerId = playerId.toLowerCase(); - + // Get cached runtime graph with checkpointer const runtimeGraph = await runtimeGraphCache.getGraph(gameId); const config = { configurable: { thread_id: gameId } }; - + // Invoke runtime graph with player action - all state loaded automatically from checkpoint - const result = await runtimeGraph.invoke({ - playerAction: { - playerId: normalizedPlayerId, - playerAction: action, + const result = await runtimeGraph.invoke( + { + playerAction: { + playerId: normalizedPlayerId, + playerAction: action, + }, }, - }, config); - + config, + ); + // Extract response from return value const simResponse = getRuntimeResponse(result as RuntimeStateType); - + // Validate that we got a response if (!simResponse) { throw new Error("No response generated from game state"); @@ -570,7 +666,7 @@ export async function getSimulationState(gameId: string): Promise { // Load state directly from checkpoint without invoking graph const saver = await getSaver(gameId, getConfig("simulation-graph-type")); const config = { configurable: { thread_id: gameId } }; - + const checkpoint = await saver.getTuple(config); if (!checkpoint || !checkpoint.checkpoint) { throw new Error("No game state found for this game."); @@ -585,7 +681,7 @@ export async function getSimulationState(gameId: string): Promise { console.error( "[simulate] Error in getSimulationState for %s: %o", gameId, - error + error, ); handleError("Failed to get player messages", error); return Promise.reject(error); @@ -598,14 +694,16 @@ export async function getSimulationState(gameId: string): Promise { * @param gameId The ID of the game/conversation * @returns The parsed game state object { game: {...}, players: {...} } */ -export async function getGameState(gameId: string): Promise<{ game: any; players: any }> { +export async function getGameState( + gameId: string, +): Promise<{ game: any; players: any }> { try { console.log("[simulate] Getting full game state for %s", gameId); // Load state directly from checkpoint without invoking graph const saver = await getSaver(gameId, getConfig("simulation-graph-type")); const config = { configurable: { thread_id: gameId } }; - + const checkpoint = await saver.getTuple(config); if (!checkpoint?.checkpoint?.channel_values) { throw new Error("No checkpoint found for game"); @@ -620,11 +718,7 @@ export async function getGameState(gameId: string): Promise<{ game: any; players console.log("[simulate] Retrieved full game state for %s", gameId); return parsedState; } catch (error) { - console.error( - "[simulate] Error in getGameState for %s: %o", - gameId, - error - ); + console.error("[simulate] Error in getGameState for %s: %o", gameId, error); handleError("Failed to get game state", error); return Promise.reject(error); } @@ -635,6 +729,6 @@ const handleError = (message: string, error: unknown): never => { throw new ValidationError(`[simulate] Invalid game state: ${error}`); } throw new RuntimeError( - `${message}: ${error instanceof Error ? error.message : "Unknown error"}` + `${message}: ${error instanceof Error ? error.message : "Unknown error"}`, ); }; diff --git a/src/api/design/handler.ts b/src/api/design/handler.ts index c5715c7..91ecb09 100644 --- a/src/api/design/handler.ts +++ b/src/api/design/handler.ts @@ -15,9 +15,6 @@ import { GetConversationHistoryRequest, GetConversationHistoryRequestSchema, GetConversationHistoryResponse, - PublishGameRequest, - PublishGameRequestSchema, - PublishGameResponse, } from "#chaincraft/api/design/schemas.js"; import { continueDesignConversation, @@ -27,7 +24,6 @@ import { isActiveConversation, } from "#chaincraft/ai/design/design-workflow.js"; import { expandSpecification } from "#chaincraft/ai/design/expand-narratives.js"; -import { uploadToIpfs } from "#chaincraft/integrations/storage/pinata.js"; /** * Helper to expand narratives in a specification for API responses. @@ -199,55 +195,6 @@ export async function handleGetConversationHistory( } } -export async function handlePublishGame( - request: FastifyRequest<{ Body: PublishGameRequest }>, - reply: FastifyReply -): Promise { - const result = PublishGameRequestSchema.safeParse(request.body); - - if (!result.success) { - reply.code(400).send({ error: "Invalid request", details: result.error }); - return Promise.reject(); - } - - try { - const { conversationId, gameTitle, version, imageUrl, userId } = - result.data; - - // Get the full game specification - const specification = await getFullDesignSpecification(conversationId); - - if (!specification) { - reply.code(404).send({ error: "Game specification not found" }); - return Promise.reject(); - } - - // Create PAIT token (same format as Discord version) - const token = { - game_title: gameTitle, - game_specification: specification, - spec_version: version, - image_url: imageUrl, - }; - - // Upload to IPFS (reuse existing function) - const ipfsHash = await uploadToIpfs( - token, - `PAIT_${userId}_${gameTitle.replace(/\s/g, "_")}` - ); - - return { - ipfsHash, - gameTitle, - version, - }; - } catch (error) { - console.error("Error in publishGame:", error); - reply.code(500).send({ error: "Internal server error" }); - return Promise.reject(); - } -} - /** * Trigger specification generation for a conversation * This bypasses the conversation node and forces spec generation diff --git a/src/api/design/schemas.ts b/src/api/design/schemas.ts index 19f06e6..cebf014 100644 --- a/src/api/design/schemas.ts +++ b/src/api/design/schemas.ts @@ -1,5 +1,3 @@ -import { CONSOLIDATION_DEFAULTS } from "#chaincraft/ai/design/game-design-state.js"; -import { SpecPlanSchema } from "#chaincraft/ai/design/schemas.js"; import { z } from "zod"; // Player count schema @@ -109,22 +107,6 @@ export const GetConversationHistoryResponseSchema = z.object({ hasMore: z.boolean(), }); -// Get conversation metadata schemas - -export const PublishGameRequestSchema = z.object({ - conversationId: z.string().min(1), - gameTitle: z.string().min(1), - version: z.number().min(1).default(1), - imageUrl: z.string().optional(), - userId: z.string().min(1), -}); - -export const PublishGameResponseSchema = z.object({ - ipfsHash: z.string(), - gameTitle: z.string(), - version: z.number(), -}); - // Type exports export type PlayerCount = z.infer; export type GameSpecification = z.infer; @@ -150,6 +132,4 @@ export type GetConversationHistoryRequest = z.infer< export type GetConversationHistoryResponse = z.infer< typeof GetConversationHistoryResponseSchema >; -export type Message = z.infer; -export type PublishGameRequest = z.infer; -export type PublishGameResponse = z.infer; +export type Message = z.infer; \ No newline at end of file diff --git a/src/api/simulate/handler.ts b/src/api/simulate/handler.ts index ea075f6..12a1846 100644 --- a/src/api/simulate/handler.ts +++ b/src/api/simulate/handler.ts @@ -22,7 +22,7 @@ import { export async function handleCreateSimulation( request: FastifyRequest<{ Body: CreateSimulationRequest }>, - reply: FastifyReply + reply: FastifyReply, ): Promise { const result = CreateSimulationRequestSchema.safeParse(request.body); @@ -32,13 +32,22 @@ export async function handleCreateSimulation( } try { - const { sessionId, gameSpecificationVersion, gameSpecification, gameId } = - result.data; + const { + sessionId, + gameSpecificationVersion, + gameSpecification, + gameId, + atomicArtifactRegen, + } = result.data; + const response = await createSimulation( sessionId, gameId, gameSpecificationVersion, - gameSpecification + { + overrideSpecification: gameSpecification, + atomicArtifactRegen, + }, ); return { @@ -53,7 +62,7 @@ export async function handleCreateSimulation( export async function handleInitializeSimulation( request: FastifyRequest<{ Body: InitializeSimulationRequest }>, - reply: FastifyReply + reply: FastifyReply, ): Promise { const result = InitializeSimulationRequestSchema.safeParse(request.body); @@ -85,7 +94,7 @@ export async function handleInitializeSimulation( export async function handleProcessAction( request: FastifyRequest<{ Body: ProcessActionRequest }>, - reply: FastifyReply + reply: FastifyReply, ): Promise { const result = ProcessActionRequestSchema.safeParse(request.body); @@ -119,7 +128,7 @@ export async function handleProcessAction( export async function handleGetSimulationState( request: FastifyRequest<{ Body: GetSimulationStateRequest }>, - reply: FastifyReply + reply: FastifyReply, ): Promise { const result = GetSimulationStateRequestSchema.safeParse(request.body); diff --git a/src/api/simulate/schemas.ts b/src/api/simulate/schemas.ts index ff8569c..87ddce0 100644 --- a/src/api/simulate/schemas.ts +++ b/src/api/simulate/schemas.ts @@ -40,6 +40,7 @@ export const CreateSimulationRequestSchema = z.object({ gameSpecificationVersion: z.number().min(1).optional(), // Optional - if omitted, uses latest version from design workflow gameSpecification: z.string().min(1).optional(), // Optional override - if not provided, retrieves from design workflow gameId: z.string().min(1).optional(), // Optional - game ID (conversationId) to fetch spec from design workflow. If not provided, uses sessionId (backward compatibility) + atomicArtifactRegen: z.boolean().optional(), // Optional - whether to require atomic artifact regen (default true) }); export const CreateSimulationResponseSchema = z.object({ diff --git a/src/integrations/clients/discord/specification_manager.ts b/src/integrations/clients/discord/specification_manager.ts index 4510e79..2621cb1 100644 --- a/src/integrations/clients/discord/specification_manager.ts +++ b/src/integrations/clients/discord/specification_manager.ts @@ -1,5 +1,4 @@ import { ThreadChannel, Message, AttachmentBuilder } from "discord.js"; -import { getFullDesignSpecification } from "#chaincraft/ai/design/design-workflow.js"; import { GameDesignSpecification } from "#chaincraft/ai/design/game-design-state.js"; const specificationMessageRegex = /^Specification Version: (\d+)/; @@ -101,15 +100,15 @@ async function updateSpecification( console.debug( "[specification-manager] Getting updated specification from design agent." ); - const specification = await getFullDesignSpecification(thread.id); - if (specification) { - // Cache the specification - const message = await setSpecificationForThread(thread, specification); - if (message) { - const version = getSpecificationVersion(message); - return { specification, version }; - } - } + // const specification = await getFullDesignSpecification(thread.id); + // if (specification) { + // // Cache the specification + // const message = await setSpecificationForThread(thread, specification); + // if (message) { + // const version = getSpecificationVersion(message); + // return { specification, version }; + // } + // } } catch (error) { console.error("Error fetching specification from AI:", error); } diff --git a/tests/games/TEST_GENERATION_GUIDE.md b/tests/games/TEST_GENERATION_GUIDE.md index e947f9c..c880842 100644 --- a/tests/games/TEST_GENERATION_GUIDE.md +++ b/tests/games/TEST_GENERATION_GUIDE.md @@ -533,14 +533,58 @@ await executeGameTest(test, scenario2, gameId); // Reuses artifacts # Generate fresh artifacts and run all scenarios npm run test:game rps +# Run a specific scenario from a test file +npm run test:game rps -- --scenario="Happy path scenario name" + # Reuse existing artifacts for faster iteration/debugging npm run test:game rps -- --gameId=rps-1734480000000-abc123 +# Run specific scenario with reused artifacts +npm run test:game rps -- --scenario="Happy path scenario name" --gameId=rps-1734480000000-abc123 + # Run with Jest (single scenario) npm run test:harness # Run with Jest and reuse artifacts GAME_ID=rps-1734480000000-abc123 npm run test:harness + +# Run with Jest and specific scenario +SCENARIO="Happy path scenario name" npm run test:harness + +# Run with Jest, both scenario and gameId +GAME_ID=rps-1734480000000-abc123 SCENARIO="Happy path scenario name" npm run test:harness +``` + +**Specifying a Scenario:** + +Use the scenario's `name` property to specify which scenario to run: + +```typescript +scenarios: [ + { + name: "Player wins by reaching 10 points", // <- Use this value + description: "...", + ... + }, + { + name: "Player loses on illegal action", // <- Or this value + description: "...", + ... + } +] +``` + +**Examples:** + +```bash +# Run just the first scenario +npm run test:game rps -- --scenario="Player wins by reaching 10 points" + +# Run a specific scenario with existing artifacts (fast iteration) +npm run test:game rps -- --scenario="Edge case: tie game" --gameId=rps-1734480000000-abc123 + +# Debug a specific scenario with full logging +SCENARIO="Player loses on illegal action" npm run test:harness 2>&1 | tee debug.log ``` When asking Copilot to generate a test file: