Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions src/ai/__tests__/design-to-sim-integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 13 additions & 9 deletions src/ai/design/__tests__/design-workflow.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {
continueDesignConversation,
generateImage,
getDesignSpecificationByVersion
getDesignByVersion
} from "../design-workflow.js";

let conversationId = `test-conversation-${Date.now()}`;
Expand Down Expand Up @@ -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");

Expand All @@ -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
);
Expand All @@ -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}`);
Expand Down
174 changes: 65 additions & 109 deletions src/ai/design/design-workflow.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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<string, string>;
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,
Expand Down Expand Up @@ -115,7 +113,7 @@ export async function generateImage(
): Promise<string> {
// 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(
Expand Down Expand Up @@ -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<string, string>;
pendingSpecChanges?: string[];
consolidationThreshold?: number;
consolidationCharLimit?: number;
}) | undefined> {
): Promise<DesignState | undefined> {
// Check if conversation exists
if (!(await isActiveConversation(conversationId))) {
throw new Error(`Conversation ${conversationId} not found`);
Expand All @@ -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
);

Expand All @@ -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;
}

Expand All @@ -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<string, string> | 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);
}

/**
Expand All @@ -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`);
Expand Down Expand Up @@ -363,10 +299,7 @@ export async function getDesignSpecificationByVersion(
title || "no title"
);

return {
...currentGameSpec,
title: title || "Untitled Game",
};
return getDesignFromCheckpoint(checkpoint.checkpoint);
}
}

Expand All @@ -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,
Expand Down Expand Up @@ -574,6 +496,44 @@ export async function isActiveConversation(
return _isActiveConversation(graphType, conversationId);
}

async function getDesignFromCheckpoint(
checkpoint: Checkpoint
): Promise<DesignState | undefined> {
// 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<string, string> | 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<
Expand Down Expand Up @@ -668,6 +628,7 @@ async function _processMessage(
specification: updatedSpec,
specNarratives: responseNarratives,
updatedTitle: lastTitle,
title: lastTitle,
systemPromptVersion: lastPromptVersion,
specDiff: specDiffSummary,

Expand All @@ -683,8 +644,3 @@ async function _processMessage(
: undefined,
};
}

function _extractGameTitle(content: string): string {
const titleMatch = content.match(gameTitleRegex);
return titleMatch ? titleMatch[1].trim() : "";
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ export function createMockState(overrides?: Partial<typeof GameDesignState.State
forceSpecGeneration: false,
consolidationThreshold: 5,
consolidationCharLimit: 2000,
narrativeStyleGuidance: undefined,
specNarratives: undefined,
narrativesNeedingUpdate: [],
...overrides,
};
}
Expand Down
Loading
Loading