Skip to content

Commit 152af46

Browse files
authored
Merge pull request #92 from chaincraftgames/generated-mechanics
Generated mechanics
2 parents b704b0f + a3751f3 commit 152af46

2 files changed

Lines changed: 116 additions & 61 deletions

File tree

‎docs/SIM_ASSISTANT_DESIGN.md‎

Lines changed: 100 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -12,19 +12,20 @@ The creator can interact with the sim assistant at any point before, during, or
1212

1313
| Capability | Description |
1414
|---|---|
15-
| **Explain behavior** | Answer "why did X happen?" by retrieving relevant artifacts, state history, and transition rationale |
15+
| **Explain behavior** | Answer "why did X happen?" by retrieving mechanic code, instructions, and before/after state snapshots from recent checkpoints |
1616
| **Diagnose issues** | Identify root cause: code bug, instruction gap, schema gap, or design issue |
1717
| **Repair artifacts** | On creator confirmation, invoke the artifact editor graph to fix instructions/mechanics/schema |
18-
| **Restart simulation** | After repair, start a fresh simulation with corrected artifacts |
18+
| **Restart simulation** | After repair, reset the runtime graph and re-initialize from corrected artifacts (no spec-processing re-run) |
1919
| **Block published edits** | If artifacts are published, redirect creator to design workflow for versioning |
2020

2121
### Future
2222

2323
| Capability | Description |
2424
|---|---|
2525
| **Design agent handoff** | Pass structured diagnosis to design agent for spec-level changes |
26-
| **Checkpoint replay** | Replay simulation from the last checkpoint before anomalous behavior |
27-
| **Persistent history** | Store-backed conversation history across sessions |
26+
| **Checkpoint replay** | Replay simulation from a specific checkpoint before anomalous behavior |
27+
| **Transition rationale capture** | Persist executor reasoning per transition for richer diagnosis |
28+
| **Persistent history** | Store-backed conversation history across page refreshes |
2829
| **Mechanic scoping** | `mechanicsToReview` filter on coordinator to limit context for large games |
2930

3031
## Architecture
@@ -44,8 +45,7 @@ POST /api/simulate/:sessionId/assistant/message
4445
│ │ - getGameSpec │
4546
│ │ - getArtifact │
4647
│ │ - getMechanicCode │
47-
│ │ - getStateAtStep │
48-
│ │ - getTransitionRationale │
48+
│ │ - getRecentStates │
4949
│ │ - getActionLog │
5050
│ │ │
5151
│ │ [action tools] │
@@ -78,12 +78,14 @@ SSE event flow:
7878
**Event types**:
7979

8080
```typescript
81+
type RepairOperation = 'patch' | 'reextract';
82+
8183
type SimAssistantEvent =
8284
| { type: 'connected'; sessionId: string }
8385
| { type: 'message'; content: string } // streamed response tokens
8486
| { type: 'message:complete'; content: string } // full final response
8587
| { type: 'repair:started'; description: string }
86-
| { type: 'repair:progress'; step: string }
88+
| { type: 'repair:progress'; step: string; operation?: RepairOperation; artifact?: string }
8789
| { type: 'repair:completed'; summary: string }
8890
| { type: 'repair:error'; error: string }
8991
| { type: 'error'; error: string };
@@ -120,30 +122,28 @@ Internally:
120122

121123
### System Prompt Manifest
122124

123-
A lightweight structural manifest injected into the system prompt (~300-500 tokens). Gives the LLM enough context to formulate targeted tool calls:
125+
A lightweight structural manifest injected into the system prompt (~300-500 tokens). Gives the LLM enough context to formulate targeted tool calls. Built from a single `getTuple()` call on the latest runtime checkpoint — no history iteration. The agent fetches action history on demand via retrieval tools.
124126

125127
```
126128
Game: "Weapon Inventor" (2 players)
127129
Phases: init → weapon_setup → round_start → weapon_selection → round_resolution → match_check → finished
128130
Transitions: 7 (initialize_game, both_weapons_ready, begin_round, both_weapons_submitted, resolve_round_outcome, player_wins_match, continue_to_next_round)
129131
Mechanics: 2 (resolve_round_outcome, both_weapons_ready)
130-
Sim status: running | completed | error
131-
Current step: 12 (phase: round_resolution, round 2)
132-
Last 3 actions: [player1: select_weapon "Banana Launcher", player2: select_weapon "Rubber Duck", auto: both_weapons_submitted]
132+
Sim status: running
133+
Current phase: round_resolution
133134
```
134135

135136
### Retrieval Tools
136137

137-
All tools are closures over the session's store — simple key lookups, no LLM intermediary.
138+
All tools read from the **runtime graph's checkpoints** via the session's `SqliteSaver`/`PostgresSaver`. They are closures over the checkpointer and sessionId — simple checkpoint lookups, no LLM intermediary.
138139

139140
| Tool | Input | Returns |
140141
|---|---|---|
141142
| `getGameSpec` | none | Full game specification text |
142143
| `getArtifact` | `{ type: 'schema' \| 'transitions' \| 'instructions', id?: string }` | Full artifact or specific fragment by ID |
143144
| `getMechanicCode` | `{ mechanicId: string }` | TypeScript source code + associated mechanicsGuidance |
144-
| `getStateAtStep` | `{ step: number }` | Game + player state snapshot from checkpoint |
145-
| `getTransitionRationale` | `{ transitionId: string, step?: number }` | The LLM executor's reasoning for a specific state change |
146-
| `getActionLog` | `{ playerId?: string, fromStep?: number, toStep?: number }` | Filtered action history |
145+
| `getRecentStates` | `{ count?: number }` | Last N game + player state snapshots from checkpoint history (default 5). Each entry includes phase, gameState, and the action that triggered it. The assistant can call again with a larger count to look further back. |
146+
| `getActionLog` | `{ playerId?: string, lastN?: number }` | Filtered action history from recent checkpoints |
147147

148148
### What the LLM Does NOT See by Default
149149

@@ -162,10 +162,8 @@ This keeps the base prompt small and the LLM in control of what context it needs
162162
Creator: "Player 2 won the round even though both chose rock"
163163
164164
Assistant (internal):
165-
→ calls getTransitionRationale("resolve_round_outcome", step=8)
166165
→ calls getMechanicCode("resolve_round_outcome")
167-
→ calls getStateAtStep(7) // before the transition
168-
→ calls getStateAtStep(8) // after the transition
166+
→ calls getRecentStates(5) // last 5 state snapshots including before/after the bad transition
169167
170168
Assistant (to creator):
171169
"The `resolve_round_outcome` mechanic doesn't handle ties. When both
@@ -188,8 +186,8 @@ Creator: "Yes, fix it"
188186
189187
SSE events:
190188
→ { type: "repair:started", description: "Fixing tie handling in resolve_round_outcome" }
191-
→ { type: "repair:progress", step: "Coordinator: patching instructions (computation field)" }
192-
→ { type: "repair:progress", step: "Regenerating mechanic from updated instructions" }
189+
→ { type: "repair:progress", step: "Coordinator: patching instructions (computation field)", operation: "patch", artifact: "instructions" }
190+
→ { type: "repair:progress", step: "Regenerating mechanic from updated instructions", operation: "reextract", artifact: "mechanics" }
193191
→ { type: "repair:progress", step: "tsc validation passed" }
194192
→ { type: "repair:completed", summary: "Patched instructions + regenerated mechanic" }
195193
@@ -223,35 +221,39 @@ const result = await artifactEditorGraph.invoke({
223221
});
224222
```
225223

226-
The `repairArtifacts` tool wraps this: it gathers current artifacts from the store, adds the formulated error, and calls the editor graph.
224+
The `repairArtifacts` tool wraps this: it loads current artifacts from the **runtime graph's latest checkpoint**, adds the formulated error, and calls the editor graph.
227225

228226
## Conversation State
229227

230-
### V1: Ephemeral
231-
232-
Message history is held in-memory for the duration of the session. Stored as a `BaseMessage[]` array in the graph state, following the standard LangGraph chat pattern.
228+
Follows the same pattern as the design conversation (`src/ai/design/`):
233229

234-
The sim assistant graph state:
230+
1. **LangGraph checkpointer**: Graph compiled with `SqliteSaver` or `PostgresSaver` (via `getSaver(sessionId, 'sim-assistant')`). Messages accumulate in checkpoints across invocations automatically.
231+
2. **GraphCache**: Compiled graph instances cached in an LRU `GraphCache` keyed by `sessionId`. Cache eviction doesn't lose state — checkpointed data persists in the database.
232+
3. **thread_id = sessionId**: Each `graph.stream()` call passes `{ configurable: { thread_id: sessionId } }`. The checkpointer loads prior messages, the reducer appends the new message.
233+
4. **Messages reducer**: Appends new messages, filters system messages, caps at a reasonable limit.
235234

236235
```typescript
237236
SimAssistantState = Annotation.Root({
238-
// Conversation
239-
messages: Annotation<BaseMessage[]>({ reducer: messagesReducer }),
237+
// Conversation (accumulated via checkpointer across invocations)
238+
messages: Annotation<BaseMessage[]>({
239+
reducer: (x, y) => {
240+
const combined = [...x, ...y];
241+
return combined.filter(msg => msg.type !== 'system').slice(-50);
242+
},
243+
}),
240244

241245
// Session context (set once at graph creation, read-only)
242246
sessionId: Annotation<string>(),
243247
gameId: Annotation<string>(),
244248

245-
// Manifest (rebuilt before each invocation from store)
249+
// Manifest (rebuilt before each invocation from runtime checkpoint)
246250
manifest: Annotation<string>(),
247251
});
248252
```
249253

250-
Conversation history is lost when the session ends. Changes made via the repair tool persist in the store.
254+
### Future: Persistent across page refreshes
251255

252-
### Future: Persistent
253-
254-
Store-backed message history, loadable across sessions. Enables "pick up where we left off" after page refresh.
256+
V1 conversation survives as long as the checkpointer's backing store is alive (SQLite file or Postgres rows). A future enhancement would add explicit session resume from the frontend after page refresh, loading the last checkpoint for the thread.
255257

256258
## Published Artifact Guard
257259

@@ -281,16 +283,19 @@ The sim assistant surfaces this to the creator and offers to summarize the neede
281283

282284
## File Structure
283285

286+
### game-builder (backend)
287+
284288
```
285289
src/
286290
ai/
287291
simulate/
288-
sim-assistant/
289-
sim-assistant-graph.ts # Graph definition (ReAct agent)
290-
sim-assistant-state.ts # Annotation.Root state
291-
tools.ts # Retrieval + action tool definitions
292-
prompts.ts # System prompt + manifest builder
293-
repair-bridge.ts # Error formulation for artifact editor
292+
graphs/
293+
sim-assistant-graph/
294+
index.ts # Graph definition (ReAct agent)
295+
sim-assistant-state.ts # Annotation.Root state
296+
tools.ts # Retrieval + action tool definitions
297+
prompts.ts # System prompt + manifest builder
298+
repair-bridge.ts # Error formulation for artifact editor
294299
api/
295300
simulate/
296301
assistant/
@@ -300,25 +305,69 @@ src/
300305
sim-assistant-bus.ts # SSE event bus (follows game-creation-status-bus pattern)
301306
```
302307

308+
### chaincraft-orchestrator (proxy)
309+
310+
```
311+
src/
312+
modules/
313+
simulation/
314+
simulation.routes.ts # Add assistant proxy routes
315+
simulation-service.ts # Add assistant methods
316+
infrastructure/
317+
game-builder/
318+
client.ts # Add assistant API methods
319+
```
320+
321+
### chaincraft-frontend (UI — already mocked)
322+
323+
The frontend UI is already built with a hardcoded stub backend. Files to update:
324+
325+
```
326+
src/
327+
contexts/
328+
simulation/
329+
AssistantContext.tsx # Replace stub with real API + SSE
330+
hooks/
331+
simulation/
332+
useAssistantStream.ts # NEW: SSE EventSource hook
333+
```
334+
335+
**Existing UI components (no changes needed):**
336+
- `SimulationChat.tsx` — dual-mode chat (player/assistant), renders assistant messages
337+
- `PlayersBar.tsx` — toggle button (Sim Assistant / sparkle icon)
338+
- `SessionContext.tsx` — `activeView: "player" | "assistant"` state
339+
- `AssistantContext.tsx` — `AssistantMessage` type, `sendAssistantMessage()`, `isAssistantLoading` (wiring exists, just needs real backend)
340+
303341
## Dependencies
304342

305343
| Component | Status | Notes |
306344
|---|---|---|
307-
| Artifact editor graph | ✅ Complete | Tasks 1-8 done, tested |
308-
| Coordinator with mechanics | ✅ Complete | 3 scenarios passing |
309-
| Edit mechanics node | ✅ Complete | Patch, reextract, cascade |
345+
| Artifact editor graph | ✅ Complete | Full coordinator-driven repair with mechanics |
346+
| Coordinator with mechanics | ✅ Complete | Patterns 11-13, upstream-first principle |
347+
| Edit mechanics node | ✅ Complete | Patch, reextract, cascade detection |
310348
| Revalidate with tsc | ✅ Complete | Layer 3 validation |
311-
| SSE infrastructure | ✅ Exists | `game-creation-status-bus.ts` pattern |
312-
| Store/checkpoint access | ✅ Exists | `InMemoryStore` + sqlite checkpointer |
313-
| State history retrieval | ⚠️ Needs verification | Check what's captured in checkpoints |
314-
| Transition rationale capture | ⚠️ Needs verification | Check if executor logs this to store |
315-
| Sim restart API | ⚠️ May need work | Verify `createSimulation` can re-init with existing artifacts |
349+
| SSE infrastructure | ✅ Exists | `game-creation-status-bus.ts` pattern to copy |
350+
| Runtime checkpoint access | ✅ Exists | `SqliteSaver`/`PostgresSaver` via `getSaver()`, `saver.list()` for history |
351+
| GraphCache | ✅ Exists | LRU graph cache pattern from design workflow |
352+
| Sim restart | ⚠️ Needs work | Need to reset runtime graph + call `initializeSimulation()` with repaired artifacts (no spec-processing re-run) |
316353

317354
## Implementation Order
318355

356+
### Phase 1: Backend Core (game-builder)
319357
1. **Event bus** — `SimAssistantBus` (copy pattern from `game-creation-status-bus.ts`)
320-
2. **Tools** — Retrieval tools (closures over store), verify data availability
321-
3. **Graph** — `createSimAssistantGraph()` with ReAct agent + tools
322-
4. **Repair bridge** — Error formulation + artifact editor invocation
323-
5. **Routes** — SSE endpoint + message endpoint
324-
6. **Integration test** — End-to-end: send message → diagnose → repair → verify fix
358+
2. **State + manifest** — `SimAssistantState`, manifest builder from runtime checkpoint
359+
3. **Retrieval tools** — `getGameSpec`, `getArtifact`, `getMechanicCode`, `getRecentStates`, `getActionLog` (closures over runtime checkpointer)
360+
4. **Graph** — `createSimAssistantGraph()` with ReAct agent + tools (diagnosis only, no repair yet)
361+
5. **Routes** — `GET .../assistant/stream` (SSE) + `POST .../assistant/message` (202 → background invoke)
362+
6. **Unit test** — Diagnosis flow: send message → tool calls → response
363+
364+
### Phase 2: Repair + Restart (game-builder)
365+
7. **Repair bridge** — `repairArtifacts` tool: error formulation + artifact editor invocation
366+
8. **Restart tool** — `restartSimulation`: reset runtime graph + re-initialize with repaired artifacts
367+
9. **Integration test** — End-to-end: message → diagnose → repair → restart → verify
368+
369+
### Phase 3: Frontend Wiring
370+
10. **Orchestrator proxy** — Add assistant routes to `simulation.routes.ts`, service methods, and `GameBuilderClient` methods
371+
11. **SSE hook** — `useAssistantStream.ts`: `EventSource` connection to orchestrator SSE endpoint, handles `message`, `repair:*`, `error` events
372+
12. **AssistantContext** — Replace stub `sendAssistantMessage()` with real API call + SSE streaming. Map SSE events to `AssistantMessage[]` state. Handle `repair:started/progress/completed` as system messages in the chat.
373+
13. **End-to-end test** — Frontend → orchestrator → game-builder → response via SSE

‎src/ai/simulate/graphs/spec-processing-graph/nodes/generate-mechanics/tsc-validator.ts‎

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -56,16 +56,19 @@ export function validateMechanics(
5656
const virtualFiles = new Map<string, string>();
5757
virtualFiles.set(INTERFACES_FILE, stateInterfaces);
5858

59+
// Count lines in stateInterfaces so error line numbers can be offset back to
60+
// 1-based lines within the mechanic source (used in the diagnostic loop below).
61+
const stateInterfaceLineCount = stateInterfaces.split('\n').length;
62+
5963
const mechanicFileNames: string[] = [];
6064
for (const [transitionId, source] of Object.entries(mechanicSources)) {
6165
const fileName = mechanicFileName(transitionId);
62-
// Prepend the import so mechanic code can reference state types.
63-
// Include GameState and PlayerState so mechanics can use them in type annotations
64-
// (e.g. `getPlayer('p', 'field') as PlayerState['field']`). The mechanic generator
65-
// prompt documents these patterns — they must be in scope for tsc to accept them.
66-
const fullSource =
67-
`import { GameState, PlayerState, MechanicState, CallLLM, RollDice, MechanicResult, setGame, getGame, setPlayer, getPlayer, setPublicMessage, setPrivateMessage, rejectAction, buildResult } from './state-interfaces';\n` +
68-
source;
66+
// Concatenate stateInterfaces directly into each mechanic compilation unit so
67+
// all generated types — including sub-interfaces like GameState_LastRoundChoices
68+
// produced from 'object'-typed schema fields — are in scope without needing an
69+
// explicit named import. A named import can only list statically-known symbols;
70+
// concatenation makes every exported declaration available automatically.
71+
const fullSource = stateInterfaces + '\n' + source;
6972
virtualFiles.set(fileName, fullSource);
7073
mechanicFileNames.push(fileName);
7174
}
@@ -151,9 +154,12 @@ export function validateMechanics(
151154

152155
if (diag.file && diag.start !== undefined) {
153156
const pos = diag.file.getLineAndCharacterOfPosition(diag.start);
154-
// Adjust for the prepended import line (line 0 in the virtual file
155-
// is our synthetic import, so subtract 1 from the reported line)
156-
line = pos.line; // 0-based, but line 0 is the import → mechanic starts at line 1
157+
// Convert the 0-based position in the concatenated virtual file back to
158+
// a 1-based line number within the mechanic source itself.
159+
// The mechanic starts at line index `stateInterfaceLineCount` (0-based)
160+
// because stateInterfaces occupies lines 0..stateInterfaceLineCount-1,
161+
// followed by a blank separator line, then the mechanic source.
162+
line = pos.line - stateInterfaceLineCount + 1;
157163
column = pos.character;
158164
}
159165

0 commit comments

Comments
 (0)