#5017 Web App, Card-Based AI-Assisted Innovative Thinking

#5017 Web App, Card-Based AI-Assisted Innovative Thinking

#5017 I want to develop a HTML/CSS/JS application that prompts for LLM API key and LLM model, a user spectified problem statement and applies a wide selection of innovative thinking methods via LLM prompt, reporting results in web page cards, with options for LLM follow-up for each.

Stage 1: Architecture & Specification State

spec_draft

  • Vision: A browser-based application where a user enters an LLM API key, selects/specifies an LLM model, inputs a problem statement, and applies a curated library of innovative thinking methods via LLM prompts. Results render as individual cards, each supporting independent LLM follow-up interactions.

  • Target Platform / Stack: Client-side HTML, CSS, and JavaScript.

  • Core Entities (Initial):

    • ProviderConfig: API key, provider/endpoint, model identifier, optional request parameters (temperature, max tokens).

    • ThinkingMethod: ID, name, category, description, system/user prompt template.

    • ProblemSession: Session ID, problem statement, selected method IDs, created timestamp.

    • MethodCard: Card ID, method reference, lifecycle status (idle → queued → loading → complete | error), structured message thread.

  • User Roles: Single local user (Bring Your Own Key).

  • Core Workflows:

    1. Configure LLM API key and model.

    2. Enter a problem statement and choose thinking methods to apply.

    3. Execute prompts and view results in individual web page cards.

    4. Run follow-up LLM queries scoped to any individual card.

  • Constraints: Client-side HTML/CSS/JS; user-supplied API key and model; card-based output with per-card follow-up.

  • Proposed Non-Goals: Backend proxy server, user accounts/authentication, cloud database sync, real-time multi-user collaboration.

decision_log

  • [ACCEPTED] Client-side HTML/CSS/JS web application.

  • [ACCEPTED] BYOK (Bring Your Own Key) flow prompting for LLM API key and model.

  • [ACCEPTED] Card-based reporting of innovative thinking method outputs with per-card LLM follow-ups.

open_questions

  1. Provider/API protocol scope (OpenAI-compatible only vs. native multi-provider adapters for OpenAI, Anthropic, Gemini, OpenRouter).

  2. API key storage policy (in-memory only, sessionStorage, or opt-in localStorage).

  3. Thinking methods catalog (fixed built-in set vs. user-extensible custom methods).

  4. Follow-up interaction scope (free-text chat, preset quick-actions, and/or cross-card synthesis).

  5. Session persistence & export (ephemeral vs. browser persistence and Markdown/JSON export).

  6. Zero-build constraint (pure static files runnable without a bundler vs. lightweight build tooling).

Adversarial Critique & Recommendations

  1. Provider API Fragmentation & Browser CORS

    • Risk: OpenAI, Anthropic, and Google Gemini use different request/response schemas and primary endpoints. Calling them directly from the browser also introduces CORS nuances—for example, Anthropic requires the anthropic-dangerous-direct-browser-access: true header for direct browser requests, while aggregators like OpenRouter provide a single OpenAI-compatible BYOK endpoint for hundreds of models directly from the browser.

    • Recommendation: Lock a provider-agnostic LLMProviderAdapter contract in Phase 0 so the card engine never couples to a single vendor's payload format.

  2. Fan-Out Concurrency, Rate Limits & Cost Control

    • Risk: Firing 10–15 innovative thinking prompts simultaneously against a problem statement can hit provider rate limits (429) or unexpectedly burn credits on frontier tiers (e.g., GPT-6 Astra, Claude Fable/Opus, Gemini Pro/Carbon).

    • Recommendation: Build a bounded concurrency queue (e.g., 2–3 in-flight requests at a time) with per-card Cancel and Retry controls, and let users toggle which methods to run (or pick presets like "Quick 3", "Divergent", "Analytical").

  3. Follow-Up Schema Coupling

    • Risk: Storing only a flat responseText string on a MethodCard will force a breaking schema rewrite when multi-turn follow-ups are added.

    • Recommendation: Model every card's content from Phase 0 as a messages[] array (where the initial method output is turn 1 and follow-ups append cleanly to the same context), plus an optional tokenUsage metadata object.

  4. Cross-Card Synthesis & Export (Downstream Schema Risk)

    • Risk: Once users generate 8+ perspective cards (e.g., First Principles, TRIZ/IFR, SCAMPER, Inversion, Six Thinking Hats, Pre-Mortem, Biomimicry, Jobs-to-be-Done), they almost always want to star the best ideas, synthesize 2–3 cards into a unified proposal, or export the results.

    • Recommendation: Include stable UUIDs, a starred/pinned boolean, and a serializable root ProblemSession schema in Phase 0—even if synthesis and export are deferred to a later phase.

  5. Markdown Rendering & XSS Security

    • Risk: LLM outputs rely heavily on Markdown. Naive HTML injection (innerHTML) creates an XSS risk—especially hazardous in a BYOK browser app where an API key is in scope.

    • Recommendation: Mandate sanitized Markdown rendering (strict allowlisted DOM construction or a sanitized parser) as a non-negotiable security invariant.

Questions to Resolve Before Compiling Phase 0

Reply with your preferences (e.g., 1B, 2B, 3A...) or any adjustments:

  1. LLM Providers: Should v1 support (A) OpenAI-compatible endpoints only (works with OpenAI, OpenRouter, Groq, Ollama/LM Studio via configurable Base URL), or (B) native adapters for OpenAI, Anthropic, Gemini, and OpenRouter?

  2. API Key Storage: Keep the key (A) in memory only (cleared on refresh), (B) in sessionStorage (cleared when tab closes), or (C) in localStorage with an opt-in "Remember key" toggle?

  3. Thinking Methods Library: (A) Curated built-in catalog only (e.g., 10–12 classic innovation methods), or (B) built-in catalog plus a UI to add/edit custom method prompts?

  4. Per-Card Follow-Ups: (A) Free-text follow-up chat only, (B) free-text chat + preset follow-up chips (e.g., Critique, Action Plan, Go Deeper), or (C) option B plus a cross-card "Synthesize Selected Cards" action?

  5. Persistence & Export: (A) Ephemeral (no saved history), (B) Markdown/JSON export only, or (C) local browser history (localStorage) + Markdown/JSON export?

  6. Build Setup: Strictly (A) zero-build vanilla HTML/CSS/JS files (open directly or serve statically), or (B) a lightweight dev setup (e.g., Vite)?


1 Gemini, 2a, 3a, 4c, 5c, 6a

Stage 1: Architecture & Specification State

spec_draft

  • Vision: A zero-build, client-side HTML/CSS/JS application that accepts a Google Gemini API key (in memory only) and model selection, takes a user-specified problem statement, applies a curated library of innovative thinking methods via the Gemini REST API, renders results as interactive cards, supports per-card free-text and preset follow-ups, synthesizes selected cards into a unified output, persists session history in localStorage, and exports to Markdown/JSON.

  • Target Platform / Stack: Zero-build vanilla HTML5, CSS3, and JavaScript (compatible with both file:// direct open and static HTTP hosting).

  • LLM Integration: Native Google Gemini REST API ([generativelanguage.googleapis.com/v1beta/models/](https://generativelanguage.googleapis.com/v1beta/models/){model}:generateContent) using the x-goog-api-key header, systemInstruction, and multi-turn contents[] (user / model roles). Includes preset selectors for current Gemini models (gemini-4-hydrogen, gemini-4-carbon, gemini-4-neon, gemini-4-argon, gemini-3.8-flash, gemini-3.5-flash-lite) plus a custom model ID input.

  • Core Entities:

    • RuntimeAuth (memory-only, never serialized): apiKey.

    • ModelConfig: modelId, temperature, maxOutputTokens.

    • ThinkingMethod (read-only built-in catalog): id, name, category, summary, systemPrompt, userPromptTemplate.

    • ProblemSession (persisted in localStorage): id, title, problemStatement, modelId, createdAt, updatedAt, cards[], syntheses[].

    • MethodCard: id, methodId, status (idle → queued → loading → complete | error | cancelled), selectedForSynthesis, starred, messages[] (turn-based { role, text, timestamp, presetChip? }), error, tokenUsage.

    • SynthesisCard: id, sourceCardIds[], status, messages[], createdAt, tokenUsage (shares the same follow-up card contract as MethodCard).

  • User Roles: Single local user (BYOK).

  • Core Workflows:

    1. Enter Gemini API key (held strictly in JS memory) and choose/type a Gemini model.

    2. Enter a problem statement and select desired methods from the curated catalog (or quick presets).

    3. Run methods through a bounded concurrency queue with live card status, retry, and cancel controls.

    4. Interact with any card via free-text follow-ups or preset chips (Critique, Action Plan, Go Deeper, Risks & Constraints).

    5. Select 2+ completed cards and run Synthesize Selected Cards, producing a synthesis card that also supports follow-ups.

    6. Browse/reload/delete past sessions from localStorage and export any session to Markdown (.md) or JSON (.json).

  • Constraints: Zero-build vanilla HTML/CSS/JS; Gemini API only; API key strictly in memory (never written to localStorage, sessionStorage, or exported files); sanitized Markdown rendering.

  • Non-Goals: Backend server/proxy, non-Gemini LLM providers, custom method authoring UI, cloud sync, user accounts, or multi-user collaboration.

decision_log

  • [ACCEPTED] Client-side zero-build vanilla HTML/CSS/JS application (6a).

  • [ACCEPTED] Native Google Gemini REST API integration with current Gemini 4 & 3.x model presets plus custom model ID input (1 Gemini).

  • [ACCEPTED] Strictly in-memory API key lifecycle—cleared on refresh/close and excluded from all persistence and exports (2a).

  • [ACCEPTED] Curated built-in catalog of innovative thinking methods (e.g., First Principles, TRIZ / Ideal Final Result, SCAMPER, Inversion, Six Thinking Hats, Pre-Mortem, Biomimicry, Jobs-to-be-Done, Lateral Thinking / Random Entry, Second-Order Thinking, Blue Ocean / ERRC, Constraint Removal) (3a).

  • [ACCEPTED] Per-card free-text follow-ups + preset follow-up chips + cross-card "Synthesize Selected Cards" (4c).

  • [ACCEPTED] Local browser history via localStorage plus Markdown and JSON export (5c).

open_questions

  • (None — all architectural questions are resolved.)

Adversarial Critique & Final Hardening Notes

  1. Strict Secret Isolation Between 2a (In-Memory Key) and 5c (localStorage + JSON Export)

    • Risk: Storing apiKey inside a shared AppState object that gets serialized to localStorage or exported to JSON would silently violate your 2a requirement.

    • Mitigation: In Phase 0, RuntimeAuth will be isolated in a separate closure/module completely outside ProblemSession, and the serializer/exporter will enforce an allowlist schema so apiKey can never leak into localStorage or .json exports. We will also pass the key via the x-goog-api-key HTTP header rather than a URL query parameter to keep it out of browser network URL logs.

  2. Zero-Build file:// CORS Trap (6a)

    • Risk: Opening index.html directly from disk (file://) blocks <script type="module"> in modern browsers due to CORS.

    • Mitigation: Structure the vanilla JS using ordered classic <script defer> files attached to a single frozen application namespace (no ES module CORS failure on file://, and zero build step required).

  3. Synthesis Card Schema Reuse (4c)

    • Risk: Treating synthesis output as a one-off modal or flat text block prevents users from running follow-ups on the synthesis or persisting it cleanly in session history.

    • Mitigation: Model SynthesisCard in Phase 0 with the same messages[], status, and follow-up interface as MethodCard, linked via sourceCardIds[].

  4. Gemini Model-Specific Parameter Pitfalls

    • Risk: Different Gemini models support different thinkingConfig levels (for example, gemini-3.5-flash-lite supports minimal, whereas gemini-3.8-flash returns an error on minimal and uses low/medium/high).

    • Mitigation: Omit model-specific thinking-level parameters by default so both preset models and arbitrary custom model IDs work reliably without 400 errors.

  5. localStorage Quota Limits (5c)

    • Risk: Long multi-card sessions with follow-up threads can approach browser localStorage limits (~5 MB).

    • Mitigation: Catch QuotaExceededError gracefully in the storage adapter, surface a clear UI notice prompting export/pruning, and keep per-session storage lean (no duplicate rendered HTML stored—only raw Markdown messages).

Readiness Gate Met

All core entities, state transitions, constraints, and non-goals are locked, and open_questions is empty.

Reply READY to compile the strictly additive Phase 0–N architecture and full specification, or share any final tweaks you want incorporated first.


Do you have any recommended improvements or corrections?

Stage 1: Architecture & Specification State

spec_draft

  • Vision: Zero-build, client-side HTML/CSS/JS app using the Google Gemini REST API (in-memory API key only) to apply a curated catalog of innovative thinking methods to a problem statement, render results as interactive cards with free-text and preset follow-ups, synthesize selected cards, persist history in localStorage, and export to Markdown/JSON.

  • Target Platform / Stack: Zero-build vanilla HTML5, CSS3, and classic <script defer> JavaScript (file:// and static hosting compatible).

  • Core Entities: RuntimeAuth (memory-only), ModelConfig, ThinkingMethod (built-in catalog), ProblemSession (persisted), MethodCard, SynthesisCard.

  • Constraints & Non-Goals: Gemini API only; API key strictly in memory; sanitized Markdown rendering; no backend, no custom method authoring UI, no multi-user sync.

decision_log

  • [ACCEPTED] Zero-build vanilla HTML/CSS/JS (6a), native Gemini REST API (1 Gemini), in-memory API key (2a), curated built-in methods (3a), per-card follow-ups + preset chips + cross-card synthesis (4c), localStorage history + Markdown/JSON export (5c).

open_questions

  • (None — pending your review of the optional improvements below.)

Recommended Improvements & Corrections

Before locking Phase 0, here are five high-leverage refinements that prevent common UX and architectural friction without adding bloat:

  1. Live Model Discovery via Gemini /models Endpoint (Correction)

    • Why: Hardcoded model presets can drift or mismatch what a user's specific API key can access.

    • Upgrade: Add a "Refresh Models" button that queries GET /v1beta/models (using the in-memory key) and filters for models supporting generateContent, while keeping the curated presets and custom model ID input as fallbacks.

  2. Optional "Constraints & Context" Field on ProblemSession

    • Why: A bare problem statement often produces generic brainstorming.

    • Upgrade: Add an optional, collapsible Constraints / Context input (e.g., budget, timeline, target audience, non-negotiables) stored on ProblemSession and automatically injected into every method and synthesis prompt.

  3. JSON Import + schemaVersion Field (Round-Trip Backup)

    • Why: localStorage can be cleared by the browser or fail to transfer across devices.

    • Upgrade: Add a schemaVersion property to ProblemSession in Phase 0 and support Import .json alongside Export .json / .md so sessions are portable and forward-compatible.

  4. Per-Card "Regenerate" & Prompt Transparency

    • Why: If one method card returns a weak or off-track angle, re-running the entire batch wastes tokens and time.

    • Upgrade: Allow regenerating a single card in place and add a collapsible "View Prompt" drawer on each card so the user can inspect the exact framing sent to Gemini.

  5. Additive Streaming Hook in Phase 0 (onChunk)

    • Why: Standard generateContent is simpler and more reliable for v1, but SSE streaming (streamGenerateContent) feels much faster when running multiple cards.

    • Upgrade: Keep non-streaming generateContent for the initial build, but include an optional onChunk callback in the Phase 0 GeminiClient contract so streaming can be added later without changing card state logic.

Let me know which of these (if any) you want to adopt—for example, "Accept all and READY", "Accept 1, 2, 3 and READY", or just READY to compile the current spec as-is.


Accept all and READY

Revised Software Application Specification: IdeaPrism (Innovative Thinking Studio)

1. System Vision and Explicit Non-Goals

  • Vision: A zero-build, browser-native studio that accepts a user's Google Gemini API key (held strictly in memory), selects or discovers a Gemini model, takes a problem statement plus optional constraints/context, and fans out a curated catalog of 12 innovative thinking methods via the Gemini REST API. Results render as interactive cards supporting per-card free-text and preset follow-ups, single-card regeneration, prompt transparency, cross-card synthesis, localStorage session history, and round-trip JSON/Markdown export and import.

  • Target Platform and Stack: Zero-build vanilla HTML5, CSS3, and classic <script defer> JavaScript attached to a single global namespace (window.IdeaPrism) so the application opens cleanly via both file:// and static HTTP hosting without bundler or ES-module CORS failures. External network calls target only the Google Gemini REST API ([https://generativelanguage.googleapis.com/v1beta](https://generativelanguage.googleapis.com/v1beta)).

  • User Roles:

    • LocalPractitioner: Single local BYOK (Bring Your Own Key) user who configures the Gemini key and model, authors problem sessions, executes/cancels/regenerates method cards, runs follow-ups and syntheses, and manages local session history and exports.

  • Explicit Non-Goals (Out of Scope):

    • Backend proxy or server-side persistence: Eliminates deployment overhead and keeps all data local to the browser.

    • Non-Gemini LLM providers: Scoped strictly to Google Gemini REST endpoints to avoid multi-vendor schema drift in v1.

    • API key persistence: Keys are never written to localStorage, sessionStorage, cookies, URL query strings, or exported files.

    • Custom method authoring UI: v1 ships a curated, read-only 12-method catalog to keep UX focused (while preserving an extension hook for future custom registries).

    • User accounts, cloud sync, or multi-user collaboration: Out of scope for a single-user local tool.

2. Architectural Overview and Future Capabilities Roadmap

  • System Topology:

    • Strict Secret Isolation Boundary: RuntimeAuth lives in an isolated closure module outside AppState and ProblemSession. Only GeminiClient reads the key, passing it exclusively via the x-goog-api-key HTTP header.

    • Unidirectional State & Event Flow: UI controllers dispatch actions to SessionStore → ExecutionQueue schedules bounded concurrent calls (AbortController-backed) through GeminiClient → responses update MethodCard or SynthesisCard message threads → StorageAdapter persists allowlisted ProblemSession JSON to localStorage → Renderer updates cards using sanitized Markdown DOM construction.

    • Unified Card Contract: Both MethodCard and SynthesisCard share the same turn-based messages[] schema, status lifecycle, and follow-up pipeline.

  • Future Capabilities Roadmap (Anticipated Extension Points):

    • SSE Token Streaming (streamGenerateContent): Supported via the onChunk(deltaText) callback already reserved on GeminiClient.generate() in Phase 0, requiring zero changes to card schemas.

    • Custom User-Defined Methods: Supported via MethodRegistry.register() reserved in Phase 0, allowing future phases to append user methods alongside the built-in catalog.

    • Cross-Session Comparison & Export Plugins: Supported via ExporterRegistry and schemaVersion on ProblemSession in Phase 0.

3. Phase 0: Core Contracts, Data Schemas, and Extension Hooks

Phase 0 Rule: Contains only structural definitions, data schemas, state machines, interfaces, and stubbed extension hooks. Zero feature business logic.

3.1 Core Data Schemas and Primary Keys

SCHEMA_VERSION = "1.0.0"

RuntimeAuth (IN-MEMORY CLOSURE ONLY — NEVER SERIALIZED)
  - apiKey: string | null

ModelConfig
  - modelId: string                  // Default preset or discovered/custom ID (e.g., "gemini-4-hydrogen", "gemini-3.8-flash")
  - temperature: number              // Default: 0.7 (range 0.0–2.0)
  - maxOutputTokens: number          // Default: 2048

ThinkingMethod (Read-Only Built-In Registry Entry)
  - id: string                       // PK, slug (e.g., "first-principles", "triz-ifr", "scamper")
  - name: string                     // Display title
  - category: "Deconstruct" | "Reframe" | "Diverge" | "Stress-Test"
  - summary: string                  // 1-line description shown on selector & card header
  - systemPrompt: string             // Method persona & analytical rules
  - userPromptTemplate: string       // Interpolates {{problemStatement}} and optional {{constraints}}

FollowUpPreset (Read-Only Built-In Chip Definition)
  - id: string                       // PK ("critique" | "action-plan" | "go-deeper" | "risks-constraints")
  - label: string                    // Chip button text
  - promptTemplate: string           // Turn prompt appended to card thread

ChatMessage
  - id: string                       // UUID
  - role: "user" | "model"           // Maps directly to Gemini API contents[].role
  - text: string                     // Raw Markdown text (never raw HTML)
  - timestamp: string                // ISO-8601 UTC
  - presetId: string | null          // Set if triggered by a FollowUpPreset chip
  - isInitialPrompt: boolean         // True only for turn 0 (used by "View Prompt" drawer)

TokenUsage
  - promptTokens: number
  - candidateTokens: number
  - totalTokens: number

MethodCard
  - id: string                       // PK, UUID
  - kind: "method"                   // Discriminator
  - methodId: string                 // FK -> ThinkingMethod.id
  - status: CardStatus               // "idle" | "queued" | "loading" | "complete" | "error" | "cancelled"
  - starred: boolean                 // Default: false
  - selectedForSynthesis: boolean    // Default: false
  - messages: ChatMessage[]          // Turn 0 = compiled method prompt (user), Turn 1 = model output, Turn 2+ = follow-ups
  - error: string | null             // User-readable error message when status === "error"
  - tokenUsage: TokenUsage | null    // Cumulative or last-turn usage metadata
  - updatedAt: string                // ISO-8601 UTC

SynthesisCard
  - id: string                       // PK, UUID
  - kind: "synthesis"                // Discriminator
  - title: string                    // e.g., "Synthesis of 3 Methods"
  - sourceCardIds: string[]          // FK[] -> MethodCard.id (min length 2)
  - status: CardStatus               // Same CardStatus enum as MethodCard
  - starred: boolean                 // Default: false
  - messages: ChatMessage[]          // Turn 0 = compiled synthesis prompt, Turn 1+ = synthesis & follow-ups
  - error: string | null
  - tokenUsage: TokenUsage | null
  - createdAt: string                // ISO-8601 UTC
  - updatedAt: string                // ISO-8601 UTC

ProblemSession (Root Persisted & Exportable Entity — STRICT ALLOWLIST, NO API KEY)
  - schemaVersion: string            // "1.0.0"
  - id: string                       // PK, UUID
  - title: string                    // Derived from problemStatement (editable)
  - problemStatement: string         // Required non-empty string
  - constraintsContext: string       // Optional constraints/context string (default: "")
  - modelConfig: ModelConfig         // Snapshot of model settings used
  - selectedMethodIds: string[]      // FK[] -> ThinkingMethod.id
  - cards: MethodCard[]
  - syntheses: SynthesisCard[]
  - createdAt: string                // ISO-8601 UTC
  - updatedAt: string                // ISO-8601 UTC

Core Invariants:

  1. RuntimeAuth.apiKey is never present on ProblemSession, localStorage, or exported files.

  2. MethodCard.messages and SynthesisCard.messages strictly alternate user / model roles when sent to Gemini contents[].

  3. Every ProblemSession written to or read from storage/import must pass validateSession(obj) checking schemaVersion, required fields, and stripping any unknown/secret keys.

3.2 State Machines and Lifecycle Transitions

  • CardStatus States: idle → queued → loading → (complete | error | cancelled)

  • Allowed Transitions and Guards:

    • idle -> queued: Triggered when user runs selected methods or initiates synthesis; requires valid RuntimeAuth.apiKey and non-empty problemStatement.

    • queued -> loading: Triggered by ExecutionQueue when an active concurrency slot opens (inFlight < maxConcurrency).

    • queued -> cancelled: Triggered by user clicking Cancel before execution starts.

    • loading -> complete: Triggered on HTTP 200 with valid candidate text; appends model ChatMessage.

    • loading -> error: Triggered on HTTP 4xx/5xx, network failure, or malformed payload; records error message.

    • loading -> cancelled: Triggered by AbortController.abort() via user Cancel; leaves prior completed turns intact if cancelling a follow-up.

    • complete -> queued: Triggered by Follow-Up (appends new user turn) or Regenerate (resets messages to turn 0 and re-queues).

    • error -> queued / cancelled -> queued: Triggered by user clicking Retry or Regenerate.

3.3 Interface Boundaries and Extension Hooks

  • RuntimeAuthContract:

    • Signature / Contract: setApiKey(key: string): void, getApiKey(): string | null, hasApiKey(): boolean, clearApiKey(): void

    • Purpose: Consumed by Phase 1 (GeminiClient) and Phase 3 (Header UI); enforces memory-only secret isolation.

  • GeminiClientContract:

    • Signature / Contract:

      • generate({ modelConfig, systemPrompt, messages, signal, onChunk? }): Promise<{ text: string, tokenUsage: TokenUsage | null }>

      • listModels({ signal }): Promise<Array<{ id: string, displayName: string, description: string }>>

    • Purpose: Implemented in Phase 1; onChunk is an optional no-op hook in v1 reserved for future SSE streaming.

  • ExecutionQueueContract:

    • Signature / Contract: enqueue(taskId: string, runner: (signal: AbortSignal) => Promise<void>): void, cancel(taskId: string): void, cancelAll(): void, getStats(): { queued: number, running: number }

    • Purpose: Implemented in Phase 1; enforces bounded concurrency (default 3) to prevent Gemini rate-limit (429) bursts.

  • StorageAdapterContract:

    • Signature / Contract: listSessions(): ProblemSession[], saveSession(session: ProblemSession): { ok: boolean, error?: "QUOTA_EXCEEDED" | "INVALID_SCHEMA" }, deleteSession(sessionId: string): void

    • Purpose: Implemented in Phase 1 (localStorage backed) and consumed by Phase 5 (History & Import/Export).

  • MarkdownSanitizerContract:

    • Signature / Contract: renderSafeMarkdown(markdownText: string): DocumentFragment

    • Purpose: Implemented in Phase 2; guarantees XSS-safe DOM rendering with zero raw innerHTML execution of untrusted LLM output.

  • MethodRegistryContract & ExporterRegistryContract:

    • Signature / Contract: getAll(), getById(id), register(item) (stubbed for additive extension).

    • Purpose: Populated in Phase 1 with 12 built-in methods and Phase 5 with Markdown/JSON exporters.

3.4 Phase 0 Verification Gate

  • [ ] js/contracts.js loads cleanly via <script defer> under both file:// and HTTP with zero console errors or circular dependencies.

  • [ ] validateSession() passes valid ProblemSession fixtures and rejects/strips any object containing apiKey or unsupported schemaVersion.

  • [ ] CardStateMachine.canTransition(from, to) passes unit assertions for all valid and invalid transitions.

  • [ ] RuntimeAuth stores and clears a key in memory without touching localStorage or sessionStorage.

  • [ ] All contract stubs (GeminiClient, ExecutionQueue, StorageAdapter, MarkdownSanitizer, MethodRegistry, ExporterRegistry) resolve cleanly on window.IdeaPrism.

4. Phased Additive Build Plan

Phase 1: Core Engine, Gemini Client, Method Catalog & Local Persistence

  • New Files / Modules:

    • js/methods-catalog.js (12 curated innovative thinking methods + 4 follow-up presets + synthesis prompt builder)

    • js/gemini-client.js (Native Gemini REST generateContent and GET /v1beta/models with x-goog-api-key header)

    • js/execution-queue.js (Bounded concurrency queue with AbortController cancellation)

    • js/storage.js (localStorage persistence with strict allowlist serialization & QuotaExceededError handling)

    • js/session-store.js (Observable state store managing active ProblemSession and history index)

  • Additive Capabilities:

    • Curated 12-method library: First Principles, TRIZ / Ideal Final Result, SCAMPER, Inversion, Six Thinking Hats, Pre-Mortem, Biomimicry, Jobs-to-be-Done, Lateral Thinking / Random Entry, Second-Order Thinking, Blue Ocean / ERRC, and Constraint Removal.

    • Prompt compiler injecting problemStatement and optional constraintsContext cleanly into each method template.

    • Live model discovery via GET /v1beta/models (filtering for supportedGenerationMethods.includes("generateContent")) alongside curated presets (gemini-4-hydrogen, gemini-4-carbon, gemini-4-neon, gemini-4-argon, gemini-3.8-flash, gemini-3.5-flash-lite) and custom model ID entry.

    • Bounded concurrent request queue (default 3 concurrent requests) with per-card cancel and retry.

  • Touched Phase 0 Extension Hooks:

    • GeminiClientContract, ExecutionQueueContract, StorageAdapterContract, MethodRegistryContract.

  • Phase 1 Verification Gate:

    • [ ] All 12 built-in methods validate against ThinkingMethod schema and interpolate {{problemStatement}} and {{constraints}}.

    • [ ] ExecutionQueue enforces maxConcurrency = 3 and propagates AbortSignal on cancel(taskId).

    • [ ] StorageAdapter.saveSession() strips any stray apiKey property and gracefully returns { ok: false, error: "QUOTA_EXCEEDED" } on simulated storage overflow.

    • [ ] Zero modifications required to Phase 0 contracts.

Phase 2: Safe Markdown Renderer & Base Application Shell

  • New Files / Modules:

    • index.html (Semantic, accessible layout loading classic <script defer> modules in topological order)

    • css/styles.css (Responsive CSS Grid card layout, dark/light-ready CSS custom properties, status badges, drawers)

    • js/markdown-safe.js (Zero-dependency DOM-based Markdown parser supporting headings, bold/italic, lists, tables, blockquotes, and fenced code blocks with strict text-node escaping)

    • js/app-shell.js (Header bar: in-memory API key input with visibility toggle & clear button, model selector + "Refresh Models" button + custom ID input, problem statement + collapsible Constraints & Context panel, method selector with category filters and quick presets like "Quick 3" / "All 12")

  • Additive Capabilities:

    • Users can configure API key (memory-only), discover/select a Gemini model, enter a problem statement + optional constraints, pick methods, and trigger a batch run.

    • Live status banner showing queue progress (Running X / Queued Y) and a global Cancel All button.

  • Touched Phase 0 Extension Hooks:

    • RuntimeAuthContract, MarkdownSanitizerContract.

  • Phase 2 Verification Gate:

    • [ ] XSS test vectors (<script>, <img onerror=...>, javascript: links) passed into renderSafeMarkdown() render strictly as inert text with zero DOM script execution.

    • [ ] App opens directly via file:// in a browser with zero CORS or module-loading errors.

    • [ ] Refreshing the page clears the API key completely (RuntimeAuth.hasApiKey() === false).

    • [ ] All Phase 0 and Phase 1 verification gates continue to pass unchanged.

Phase 3: Interactive Method Cards, Follow-Ups, Regenerate & Prompt Transparency

  • New Files / Modules:

    • js/card-renderer.js (Renders MethodCard grid, status states, star/pin toggle, synthesis checkbox, collapsible "View Prompt" drawer, per-card Retry/Cancel/Regenerate buttons, and multi-turn conversation thread)

    • js/followup-controller.js (Handles free-text follow-up submission and the 4 preset follow-up chips: Critique, Action Plan, Go Deeper, Risks & Constraints)

  • Additive Capabilities:

    • Each method renders in its own card with live state badges (Queued, Thinking..., Complete, Error, Cancelled).

    • Per-card collapsible View Prompt drawer displays the exact system + initial user prompt sent to Gemini.

    • Per-card Regenerate re-runs a single method in place without disturbing other cards.

    • Per-card Follow-Up thread maintains full multi-turn contents[] context with both preset chips and free-text input.

  • Touched Phase 0 Extension Hooks:

    • Consumes CardStatus state machine, ExecutionQueueContract, and MarkdownSanitizerContract.

  • Phase 3 Verification Gate:

    • [ ] Submitting a preset chip or free-text follow-up appends a user turn, sends valid alternating contents[] to GeminiClient, and renders the model reply inside the same card.

    • [ ] Clicking Cancel during a follow-up aborts only that request and preserves previous completed turns in the card.

    • [ ] Clicking Regenerate replaces only that card's thread while leaving sibling cards untouched.

    • [ ] All Phase 0–2 verification gates continue to pass unchanged.

Phase 4: Cross-Card Synthesis Workflow

  • New Files / Modules:

    • js/synthesis-controller.js (Selection bar tracking checked completed cards, synthesis prompt composer, and SynthesisCard rendering reusing Phase 3's follow-up UI)

  • Additive Capabilities:

    • Floating or sticky Synthesize Selected Cards (N) action bar activates whenever 2+ completed MethodCards are selected.

    • Compiles the problem statement, constraints, and selected cards' latest insights into a dedicated Synthesis Prompt that resolves tensions, highlights high-leverage overlaps, and produces an integrated strategy.

    • Renders the result as a SynthesisCard in a dedicated Synthesis section with full support for preset chips, free-text follow-ups, "View Prompt", starring, and regeneration.

  • Touched Phase 0 Extension Hooks:

    • Consumes SynthesisCard schema and ExecutionQueueContract.

  • Phase 4 Verification Gate:

    • [ ] "Synthesize Selected Cards" remains disabled when fewer than 2 completed cards are selected.

    • [ ] Generated SynthesisCard links valid sourceCardIds[] and supports multi-turn follow-ups using the exact same controller as MethodCard.

    • [ ] All Phase 0–3 verification gates continue to pass unchanged.

Phase 5: Session History Drawer, Export (.md / .json) & Round-Trip Import (.json)

  • New Files / Modules:

    • js/exporters.js (Registers Markdown .md report exporter and allowlisted .json session exporter + .json file importer with schema validation)

    • js/history-drawer.js (Slide-over drawer listing saved localStorage sessions with search/filter, load, rename, delete, New Session, Export MD/JSON, Import JSON, and QuotaExceededError banner)

  • Additive Capabilities:

    • Automatic debounced saving of active ProblemSession to localStorage.

    • One-click Export Markdown (clean structured report with problem statement, constraints, starred indicators, all method cards, follow-ups, and syntheses).

    • One-click Export JSON and Import JSON for portable backups across browsers/devices.

  • Touched Phase 0 Extension Hooks:

    • ExporterRegistryContract, StorageAdapterContract.

  • Phase 5 Verification Gate:

    • [ ] Exporting a session to .json, deleting it from localStorage, and re-importing the .json file restores all cards, follow-up threads, and syntheses identically.

    • [ ] Inspected .json and .md exports contain zero occurrences of apiKey.

    • [ ] Importing a malformed or wrong-version JSON file displays a clear validation error without corrupting existing localStorage sessions.

    • [ ] All Phase 0–4 verification gates continue to pass unchanged.

5. Decision Log Summary

IDStatusDecision / RequirementRationale
D-01[ACCEPTED]Native Google Gemini REST API (x-goog-api-key header)Matches user preference (1 Gemini); avoids URL-param key leakage and third-party proxy servers.
D-02[ACCEPTED]Strictly in-memory API key (RuntimeAuth closure)Enforces 2a security policy; guarantees keys never enter localStorage or exports.
D-03[ACCEPTED]Curated 12-method built-in catalogSatisfies 3a with broad divergent/analytical coverage while reserving MethodRegistry.register() for future expansion.
D-04[ACCEPTED]Per-card free-text + preset chips + cross-card synthesisSatisfies 4c; unified messages[] schema allows synthesis cards to inherit full follow-up capabilities.
D-05[ACCEPTED]localStorage history + .md/.json export + .json import + schemaVersionSatisfies 5c plus round-trip portability and safe QuotaExceededError handling.
D-06[ACCEPTED]Zero-build vanilla HTML/CSS/JS via classic <script defer>Satisfies 6a and prevents file:// ES-module CORS blocks.
D-07[ACCEPTED]Live Gemini /v1beta/models discovery + fallback presets + custom IDPrevents stale hardcoded model lists while supporting any model accessible to the user's key.
D-08[ACCEPTED]Optional collapsible "Constraints & Context" fieldPrevents generic brainstorming by grounding every method and synthesis prompt in real constraints.
D-09[ACCEPTED]Per-card Regenerate + collapsible "View Prompt" drawerSaves tokens on single-card retries and makes prompt framing transparent.
D-10[ACCEPTED]Optional onChunk streaming hook in Phase 0 GeminiClientEnables additive SSE streaming later with zero contract rewrites.
D-11[REJECTED]Raw innerHTML Markdown renderingRejected due to XSS risk in a BYOK browser app; replaced by DOM-based renderSafeMarkdown.
D-12[REJECTED]Model-specific thinkingConfig defaultsRejected because thinking-level enums vary across Gemini models and break arbitrary custom model IDs.

The specification is locked. Would you like me to generate Phase 0 (js/contracts.js + Phase 0 verification harness) first, or jump to a specific phase?


Generate Phase 0 now: js/contracts.js and the Phase 0 verification gate tests.

Phase 0 establishes the locked data contracts, state machine, memory-only secret isolation, and stubbed extension hooks with zero feature business logic. Both files work directly via file:// in any browser (and tests/phase0-verify.js also runs under Node.js).

1. js/contracts.js

/**
 * IdeaPrism — Phase 0: Core Contracts, Data Schemas, State Machine & Extension Hooks
 * Zero feature business logic. Classic <script defer> compatible (file:// and HTTP).
 */
(function (globalScope) {
  "use strict";

  const SCHEMA_VERSION = "1.0.0";

  const CARD_STATUS = Object.freeze({
    IDLE: "idle",
    QUEUED: "queued",
    LOADING: "loading",
    COMPLETE: "complete",
    ERROR: "error",
    CANCELLED: "cancelled"
  });

  const METHOD_CATEGORIES = Object.freeze({
    DECONSTRUCT: "Deconstruct",
    REFRAME: "Reframe",
    DIVERGE: "Diverge",
    STRESS_TEST: "Stress-Test"
  });

  const DEFAULT_MODEL_PRESETS = Object.freeze([
    { id: "gemini-4-hydrogen", label: "Gemini 4 Hydrogen" },
    { id: "gemini-4-carbon", label: "Gemini 4 Carbon" },
    { id: "gemini-4-neon", label: "Gemini 4 Neon" },
    { id: "gemini-4-argon", label: "Gemini 4 Argon" },
    { id: "gemini-3.8-flash", label: "Gemini 3.8 Flash" },
    { id: "gemini-3.5-flash-lite", label: "Gemini 3.5 Flash-Lite" }
  ]);

  function generateUUID() {
    if (globalScope.crypto && typeof globalScope.crypto.randomUUID === "function") {
      return globalScope.crypto.randomUUID();
    }
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
      const r = (Math.random() * 16) | 0;
      const v = c === "x" ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    });
  }

  function nowIso() {
    return new Date().toISOString();
  }

  // ---------------------------------------------------------------------------
  // 1. RuntimeAuth (STRICTLY IN-MEMORY CLOSURE — NEVER SERIALIZED)
  // ---------------------------------------------------------------------------
  const RuntimeAuth = (function () {
    let _apiKey = null;

    return Object.freeze({
      setApiKey: function (key) {
        if (typeof key !== "string" || key.trim().length === 0) {
          _apiKey = null;
          return;
        }
        _apiKey = key.trim();
      },
      getApiKey: function () {
        return _apiKey;
      },
      hasApiKey: function () {
        return typeof _apiKey === "string" && _apiKey.length > 0;
      },
      clearApiKey: function () {
        _apiKey = null;
      }
    });
  })();

  // ---------------------------------------------------------------------------
  // 2. Card Lifecycle State Machine
  // ---------------------------------------------------------------------------
  const ALLOWED_TRANSITIONS = Object.freeze({
    [CARD_STATUS.IDLE]: Object.freeze([CARD_STATUS.QUEUED]),
    [CARD_STATUS.QUEUED]: Object.freeze([CARD_STATUS.LOADING, CARD_STATUS.CANCELLED]),
    [CARD_STATUS.LOADING]: Object.freeze([
      CARD_STATUS.COMPLETE,
      CARD_STATUS.ERROR,
      CARD_STATUS.CANCELLED
    ]),
    [CARD_STATUS.COMPLETE]: Object.freeze([CARD_STATUS.QUEUED]),
    [CARD_STATUS.ERROR]: Object.freeze([CARD_STATUS.QUEUED]),
    [CARD_STATUS.CANCELLED]: Object.freeze([CARD_STATUS.QUEUED])
  });

  const CardStateMachine = Object.freeze({
    ALLOWED_TRANSITIONS: ALLOWED_TRANSITIONS,
    canTransition: function (fromStatus, toStatus) {
      const allowed = ALLOWED_TRANSITIONS[fromStatus];
      return Array.isArray(allowed) && allowed.indexOf(toStatus) !== -1;
    },
    assertTransition: function (fromStatus, toStatus) {
      if (!CardStateMachine.canTransition(fromStatus, toStatus)) {
        throw new Error(
          "Invalid CardStatus transition: '" + fromStatus + "' -> '" + toStatus + "'"
        );
      }
      return toStatus;
    }
  });

  // ---------------------------------------------------------------------------
  // 3. Schema Factories & Strict Allowlist Validators
  // ---------------------------------------------------------------------------
  function createModelConfig(overrides) {
    const cfg = overrides || {};
    return {
      modelId: typeof cfg.modelId === "string" && cfg.modelId.trim()
        ? cfg.modelId.trim()
        : DEFAULT_MODEL_PRESETS[0].id,
      temperature: typeof cfg.temperature === "number" ? cfg.temperature : 0.7,
      maxOutputTokens: typeof cfg.maxOutputTokens === "number" ? cfg.maxOutputTokens : 2048
    };
  }

  function createChatMessage(params) {
    const p = params || {};
    if (p.role !== "user" && p.role !== "model") {
      throw new Error("ChatMessage.role must be 'user' or 'model'");
    }
    return {
      id: p.id || generateUUID(),
      role: p.role,
      text: typeof p.text === "string" ? p.text : "",
      timestamp: p.timestamp || nowIso(),
      presetId: typeof p.presetId === "string" ? p.presetId : null,
      isInitialPrompt: Boolean(p.isInitialPrompt)
    };
  }

  function createMethodCard(methodId, overrides) {
    const o = overrides || {};
    return {
      id: o.id || generateUUID(),
      kind: "method",
      methodId: String(methodId),
      status: o.status || CARD_STATUS.IDLE,
      starred: Boolean(o.starred),
      selectedForSynthesis: Boolean(o.selectedForSynthesis),
      messages: Array.isArray(o.messages) ? o.messages : [],
      error: typeof o.error === "string" ? o.error : null,
      tokenUsage: o.tokenUsage || null,
      updatedAt: o.updatedAt || nowIso()
    };
  }

  function createSynthesisCard(sourceCardIds, overrides) {
    const o = overrides || {};
    if (!Array.isArray(sourceCardIds) || sourceCardIds.length < 2) {
      throw new Error("SynthesisCard requires at least 2 sourceCardIds");
    }
    const ts = nowIso();
    return {
      id: o.id || generateUUID(),
      kind: "synthesis",
      title: typeof o.title === "string" && o.title.trim()
        ? o.title.trim()
        : "Synthesis of " + sourceCardIds.length + " Methods",
      sourceCardIds: sourceCardIds.slice(),
      status: o.status || CARD_STATUS.IDLE,
      starred: Boolean(o.starred),
      messages: Array.isArray(o.messages) ? o.messages : [],
      error: typeof o.error === "string" ? o.error : null,
      tokenUsage: o.tokenUsage || null,
      createdAt: o.createdAt || ts,
      updatedAt: o.updatedAt || ts
    };
  }

  function createProblemSession(params) {
    const p = params || {};
    const ts = nowIso();
    const problemStatement = typeof p.problemStatement === "string" ? p.problemStatement.trim() : "";
    return {
      schemaVersion: SCHEMA_VERSION,
      id: p.id || generateUUID(),
      title: typeof p.title === "string" && p.title.trim()
        ? p.title.trim()
        : (problemStatement ? problemStatement.slice(0, 60) : "Untitled Session"),
      problemStatement: problemStatement,
      constraintsContext: typeof p.constraintsContext === "string" ? p.constraintsContext : "",
      modelConfig: createModelConfig(p.modelConfig),
      selectedMethodIds: Array.isArray(p.selectedMethodIds) ? p.selectedMethodIds.slice() : [],
      cards: Array.isArray(p.cards) ? p.cards : [],
      syntheses: Array.isArray(p.syntheses) ? p.syntheses : [],
      createdAt: p.createdAt || ts,
      updatedAt: p.updatedAt || ts
    };
  }

  function hasValidAlternatingRoles(messages) {
    if (!Array.isArray(messages)) return false;
    for (let i = 0; i < messages.length; i++) {
      const msg = messages[i];
      if (!msg || (msg.role !== "user" && msg.role !== "model")) return false;
      if (i > 0 && msg.role === messages[i - 1].role) return false;
    }
    return true;
  }

  function containsForbiddenSecretKey(obj) {
    if (!obj || typeof obj !== "object") return false;
    if (Object.prototype.hasOwnProperty.call(obj, "apiKey")) return true;
    const keys = Object.keys(obj);
    for (let i = 0; i < keys.length; i++) {
      const val = obj[keys[i]];
      if (val && typeof val === "object" && containsForbiddenSecretKey(val)) {
        return true;
      }
    }
    return false;
  }

  function sanitizeTokenUsage(usage) {
    if (!usage || typeof usage !== "object") return null;
    return {
      promptTokens: Number(usage.promptTokens) || 0,
      candidateTokens: Number(usage.candidateTokens) || 0,
      totalTokens: Number(usage.totalTokens) || 0
    };
  }

  function sanitizeMessages(messages) {
    if (!Array.isArray(messages)) return [];
    return messages.map(function (m) {
      return {
        id: String(m.id || generateUUID()),
        role: m.role === "model" ? "model" : "user",
        text: typeof m.text === "string" ? m.text : "",
        timestamp: typeof m.timestamp === "string" ? m.timestamp : nowIso(),
        presetId: typeof m.presetId === "string" ? m.presetId : null,
        isInitialPrompt: Boolean(m.isInitialPrompt)
      };
    });
  }

  /**
   * Strict allowlist serializer: strips unknown fields and guarantees apiKey
   * can never leak into localStorage or exported JSON files.
   */
  function sanitizeSessionForPersistence(session) {
    return {
      schemaVersion: SCHEMA_VERSION,
      id: String(session.id),
      title: String(session.title || "Untitled Session"),
      problemStatement: String(session.problemStatement || ""),
      constraintsContext: String(session.constraintsContext || ""),
      modelConfig: createModelConfig(session.modelConfig),
      selectedMethodIds: Array.isArray(session.selectedMethodIds)
        ? session.selectedMethodIds.map(String)
        : [],
      cards: Array.isArray(session.cards)
        ? session.cards.map(function (c) {
            return {
              id: String(c.id),
              kind: "method",
              methodId: String(c.methodId),
              status: c.status,
              starred: Boolean(c.starred),
              selectedForSynthesis: Boolean(c.selectedForSynthesis),
              messages: sanitizeMessages(c.messages),
              error: typeof c.error === "string" ? c.error : null,
              tokenUsage: sanitizeTokenUsage(c.tokenUsage),
              updatedAt: String(c.updatedAt || nowIso())
            };
          })
        : [],
      syntheses: Array.isArray(session.syntheses)
        ? session.syntheses.map(function (s) {
            return {
              id: String(s.id),
              kind: "synthesis",
              title: String(s.title || "Synthesis"),
              sourceCardIds: Array.isArray(s.sourceCardIds) ? s.sourceCardIds.map(String) : [],
              status: s.status,
              starred: Boolean(s.starred),
              messages: sanitizeMessages(s.messages),
              error: typeof s.error === "string" ? s.error : null,
              tokenUsage: sanitizeTokenUsage(s.tokenUsage),
              createdAt: String(s.createdAt || nowIso()),
              updatedAt: String(s.updatedAt || nowIso())
            };
          })
        : [],
      createdAt: String(session.createdAt || nowIso()),
      updatedAt: String(session.updatedAt || nowIso())
    };
  }

  function validateSession(obj) {
    const errors = [];
    if (!obj || typeof obj !== "object") {
      return { valid: false, errors: ["Session must be an object."], sanitized: null };
    }
    if (containsForbiddenSecretKey(obj)) {
      errors.push("Forbidden secret field 'apiKey' detected in session payload.");
    }
    if (obj.schemaVersion !== SCHEMA_VERSION) {
      errors.push(
        "Unsupported schemaVersion: expected '" + SCHEMA_VERSION + "', got '" + obj.schemaVersion + "'."
      );
    }
    if (typeof obj.id !== "string" || !obj.id.trim()) {
      errors.push("Missing or invalid session.id.");
    }
    if (typeof obj.problemStatement !== "string") {
      errors.push("Missing or invalid session.problemStatement.");
    }
    if (!Array.isArray(obj.cards)) {
      errors.push("session.cards must be an array.");
    } else {
      obj.cards.forEach(function (c, idx) {
        if (!hasValidAlternatingRoles(c.messages)) {
          errors.push("cards[" + idx + "].messages must strictly alternate user/model roles.");
        }
      });
    }
    if (!Array.isArray(obj.syntheses)) {
      errors.push("session.syntheses must be an array.");
    } else {
      obj.syntheses.forEach(function (s, idx) {
        if (!Array.isArray(s.sourceCardIds) || s.sourceCardIds.length < 2) {
          errors.push("syntheses[" + idx + "].sourceCardIds must contain at least 2 card IDs.");
        }
        if (!hasValidAlternatingRoles(s.messages)) {
          errors.push("syntheses[" + idx + "].messages must strictly alternate user/model roles.");
        }
      });
    }

    if (errors.length > 0) {
      return { valid: false, errors: errors, sanitized: null };
    }
    return {
      valid: true,
      errors: [],
      sanitized: sanitizeSessionForPersistence(obj)
    };
  }

  // ---------------------------------------------------------------------------
  // 4. Stubbed Extension Hooks / Contracts (Implemented in Phases 1–5)
  // ---------------------------------------------------------------------------
  function notImplemented(contractName, methodName) {
    return function () {
      throw new Error(contractName + "." + methodName + "() is not implemented yet.");
    };
  }

  function createRegistryStub(name) {
    const _items = new Map();
    return {
      register: function (item) {
        if (!item || typeof item.id !== "string" || !item.id.trim()) {
          throw new Error(name + ".register() requires an object with a non-empty string 'id'.");
        }
        _items.set(item.id, item);
      },
      getById: function (id) {
        return _items.get(id) || null;
      },
      getAll: function () {
        return Array.from(_items.values());
      }
    };
  }

  const Contracts = {
    GeminiClient: {
      generate: notImplemented("GeminiClient", "generate"),
      listModels: notImplemented("GeminiClient", "listModels")
    },
    ExecutionQueue: {
      enqueue: notImplemented("ExecutionQueue", "enqueue"),
      cancel: notImplemented("ExecutionQueue", "cancel"),
      cancelAll: notImplemented("ExecutionQueue", "cancelAll"),
      getStats: notImplemented("ExecutionQueue", "getStats")
    },
    StorageAdapter: {
      listSessions: notImplemented("StorageAdapter", "listSessions"),
      saveSession: notImplemented("StorageAdapter", "saveSession"),
      deleteSession: notImplemented("StorageAdapter", "deleteSession")
    },
    MarkdownSanitizer: {
      renderSafeMarkdown: notImplemented("MarkdownSanitizer", "renderSafeMarkdown")
    },
    MethodRegistry: createRegistryStub("MethodRegistry"),
    ExporterRegistry: createRegistryStub("ExporterRegistry")
  };

  // ---------------------------------------------------------------------------
  // 5. Public Namespace Export
  // ---------------------------------------------------------------------------
  const IdeaPrism = {
    SCHEMA_VERSION: SCHEMA_VERSION,
    CARD_STATUS: CARD_STATUS,
    METHOD_CATEGORIES: METHOD_CATEGORIES,
    DEFAULT_MODEL_PRESETS: DEFAULT_MODEL_PRESETS,
    RuntimeAuth: RuntimeAuth,
    CardStateMachine: CardStateMachine,
    Factories: Object.freeze({
      createModelConfig: createModelConfig,
      createChatMessage: createChatMessage,
      createMethodCard: createMethodCard,
      createSynthesisCard: createSynthesisCard,
      createProblemSession: createProblemSession
    }),
    Validation: Object.freeze({
      hasValidAlternatingRoles: hasValidAlternatingRoles,
      validateSession: validateSession,
      sanitizeSessionForPersistence: sanitizeSessionForPersistence
    }),
    Contracts: Contracts
  };

  globalScope.IdeaPrism = IdeaPrism;
  if (typeof module !== "undefined" && module.exports) {
    module.exports = IdeaPrism;
  }
})(typeof window !== "undefined" ? window : globalThis);

2. tests/phase0-verify.js (Dual Browser & Node.js Verification Gate)

/**
 * IdeaPrism — Phase 0 Verification Gate Tests
 * Run in Node.js:  node tests/phase0-verify.js
 * Run in Browser:  open tests/phase0-verify.html
 */
(function (globalScope) {
  "use strict";

  const IdeaPrism =
    globalScope.IdeaPrism ||
    (typeof require === "function" ? require("../js/contracts.js") : null);

  if (!IdeaPrism) {
    throw new Error("IdeaPrism namespace not found. Load js/contracts.js first.");
  }

  const results = [];

  function test(name, fn) {
    try {
      fn();
      results.push({ name: name, pass: true });
    } catch (err) {
      results.push({ name: name, pass: false, error: err.message });
    }
  }

  function assert(condition, message) {
    if (!condition) {
      throw new Error(message || "Assertion failed");
    }
  }

  // Gate 1: RuntimeAuth memory-only isolation
  test("RuntimeAuth stores/clears key in memory without touching Web Storage", function () {
    const { RuntimeAuth } = IdeaPrism;
    RuntimeAuth.clearApiKey();
    assert(RuntimeAuth.hasApiKey() === false, "Expected empty key initially");

    RuntimeAuth.setApiKey("AIzaSy-TEST-KEY-123");
    assert(RuntimeAuth.hasApiKey() === true, "Expected key to be present");
    assert(RuntimeAuth.getApiKey() === "AIzaSy-TEST-KEY-123", "Key mismatch");

    if (typeof localStorage !== "undefined") {
      assert(
        JSON.stringify(localStorage).indexOf("AIzaSy-TEST-KEY-123") === -1,
        "API key leaked into localStorage"
      );
    }
    if (typeof sessionStorage !== "undefined") {
      assert(
        JSON.stringify(sessionStorage).indexOf("AIzaSy-TEST-KEY-123") === -1,
        "API key leaked into sessionStorage"
      );
    }

    RuntimeAuth.clearApiKey();
    assert(RuntimeAuth.hasApiKey() === false, "Expected key to be cleared");
  });

  // Gate 2: CardStateMachine valid and invalid transitions
  test("CardStateMachine enforces allowed and disallowed lifecycle transitions", function () {
    const { CARD_STATUS, CardStateMachine } = IdeaPrism;
    assert(CardStateMachine.canTransition(CARD_STATUS.IDLE, CARD_STATUS.QUEUED) === true);
    assert(CardStateMachine.canTransition(CARD_STATUS.QUEUED, CARD_STATUS.LOADING) === true);
    assert(CardStateMachine.canTransition(CARD_STATUS.LOADING, CARD_STATUS.COMPLETE) === true);
    assert(CardStateMachine.canTransition(CARD_STATUS.COMPLETE, CARD_STATUS.QUEUED) === true);
    assert(CardStateMachine.canTransition(CARD_STATUS.ERROR, CARD_STATUS.QUEUED) === true);
    assert(CardStateMachine.canTransition(CARD_STATUS.CANCELLED, CARD_STATUS.QUEUED) === true);

    assert(CardStateMachine.canTransition(CARD_STATUS.IDLE, CARD_STATUS.COMPLETE) === false);
    assert(CardStateMachine.canTransition(CARD_STATUS.QUEUED, CARD_STATUS.COMPLETE) === false);

    let threw = false;
    try {
      CardStateMachine.assertTransition(CARD_STATUS.IDLE, CARD_STATUS.COMPLETE);
    } catch (e) {
      threw = true;
    }
    assert(threw === true, "assertTransition should throw on invalid transition");
  });

  // Gate 3: Valid ProblemSession passes validation
  test("validateSession accepts valid ProblemSession with alternating messages", function () {
    const { Factories, Validation, CARD_STATUS } = IdeaPrism;
    const card = Factories.createMethodCard("first-principles", {
      status: CARD_STATUS.COMPLETE,
      messages: [
        Factories.createChatMessage({ role: "user", text: "Prompt", isInitialPrompt: true }),
        Factories.createChatMessage({ role: "model", text: "Response" })
      ]
    });
    const session = Factories.createProblemSession({
      problemStatement: "Reduce onboarding friction for local-first apps",
      constraintsContext: "Zero backend, zero build step",
      selectedMethodIds: ["first-principles"],
      cards: [card]
    });

    const res = Validation.validateSession(session);
    assert(res.valid === true, "Expected valid session, got: " + res.errors.join("; "));
    assert(res.sanitized.schemaVersion === IdeaPrism.SCHEMA_VERSION, "Schema version mismatch");
  });

  // Gate 4: Forbidden apiKey & bad schemaVersion rejected
  test("validateSession rejects apiKey leakage and unsupported schemaVersion", function () {
    const { Factories, Validation } = IdeaPrism;
    const badSecretSession = Factories.createProblemSession({ problemStatement: "Test" });
    badSecretSession.apiKey = "SECRET_LEAK";
    const res1 = Validation.validateSession(badSecretSession);
    assert(res1.valid === false, "Session with apiKey must fail validation");

    const badVersionSession = Factories.createProblemSession({ problemStatement: "Test" });
    badVersionSession.schemaVersion = "99.0.0";
    const res2 = Validation.validateSession(badVersionSession);
    assert(res2.valid === false, "Session with unsupported schemaVersion must fail validation");
  });

  // Gate 5: Non-alternating roles rejected
  test("validateSession rejects consecutive identical roles in card messages", function () {
    const { Factories, Validation } = IdeaPrism;
    const badCard = Factories.createMethodCard("scamper", {
      messages: [
        Factories.createChatMessage({ role: "user", text: "Turn 1" }),
        Factories.createChatMessage({ role: "user", text: "Turn 2 (invalid)" })
      ]
    });
    const session = Factories.createProblemSession({
      problemStatement: "Test",
      cards: [badCard]
    });
    const res = Validation.validateSession(session);
    assert(res.valid === false, "Non-alternating roles must fail validation");
  });

  // Gate 6: All contract stubs exist on IdeaPrism.Contracts
  test("All Phase 0 contract stubs resolve cleanly", function () {
    const { Contracts } = IdeaPrism;
    assert(typeof Contracts.GeminiClient.generate === "function");
    assert(typeof Contracts.GeminiClient.listModels === "function");
    assert(typeof Contracts.ExecutionQueue.enqueue === "function");
    assert(typeof Contracts.StorageAdapter.saveSession === "function");
    assert(typeof Contracts.MarkdownSanitizer.renderSafeMarkdown === "function");
    assert(typeof Contracts.MethodRegistry.register === "function");
    assert(typeof Contracts.ExporterRegistry.register === "function");
  });

  // Output summary
  const failed = results.filter(function (r) { return !r.pass; });
  if (typeof document !== "undefined" && document.getElementById("results")) {
    const list = document.getElementById("results");
    results.forEach(function (r) {
      const li = document.createElement("li");
      li.textContent = (r.pass ? "[PASS] " : "[FAIL] ") + r.name + (r.error ? " — " + r.error : "");
      li.style.color = r.pass ? "#15803d" : "#b91c1c";
      list.appendChild(li);
    });
  } else {
    results.forEach(function (r) {
      console.log((r.pass ? "[PASS] " : "[FAIL] ") + r.name + (r.error ? " — " + r.error : ""));
    });
    console.log("\nPhase 0 Gate: " + (results.length - failed.length) + "/" + results.length + " passed.");
    if (failed.length > 0 && typeof process !== "undefined") {
      process.exit(1);
    }
  }
})(typeof window !== "undefined" ? window : globalThis);

3. tests/phase0-verify.html (Browser file:// Runner)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>IdeaPrism — Phase 0 Verification Gate</title>
  <style>
    body { font-family: system-ui, sans-serif; max-width: 720px; margin: 2rem auto; padding: 0 1rem; }
    ul { list-style: none; padding: 0; line-height: 1.8; }
  </style>
  <script defer src="../js/contracts.js"></script>
  <script defer src="./phase0-verify.js"></script>
</head>
<body>
  <h1>Phase 0 Verification Gate</h1>
  <ul id="results"></ul>
</body>
</html>

Save those three files, open tests/phase0-verify.html directly in your browser (or run node tests/phase0-verify.js), and confirm all 6 gates show [PASS].


Phase 0 passed. Generate Phase 1 now: methods-catalog.js, gemini-client.js, execution-queue.js, storage.js, and session-store.js.

Phase 1 implements the core engine against the locked Phase 0 contracts—zero changes to js/contracts.js. All modules use classic <script defer> syntax compatible with both file:// and Node.js verification.

1. js/methods-catalog.js

/**
 * IdeaPrism — Phase 1: Curated 12-Method Catalog, Follow-Up Presets & Prompt Compiler
 */
(function (globalScope) {
  "use strict";

  const IdeaPrism =
    globalScope.IdeaPrism ||
    (typeof require === "function" ? require("./contracts.js") : null);

  if (!IdeaPrism) {
    throw new Error("IdeaPrism Phase 0 contracts must be loaded before methods-catalog.js");
  }

  const CAT = IdeaPrism.METHOD_CATEGORIES;

  const BUILTIN_METHODS = [
    {
      id: "first-principles",
      name: "First Principles",
      category: CAT.DECONSTRUCT,
      summary: "Strip assumptions down to fundamental truths and rebuild from scratch.",
      systemPrompt:
        "You are an expert First Principles analyst. Strip away conventional wisdom, identify fundamental physical, logical, or economic truths, and rebuild novel solutions directly from those truths. Be concrete and structured.",
      userPromptTemplate:
        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply First Principles thinking:\n1. List 3-5 hidden assumptions people usually make here.\n2. Identify the irreducible fundamental truths.\n3. Propose 2-3 rebuilt solutions starting purely from those truths."
    },
    {
      id: "triz-ifr",
      name: "TRIZ / Ideal Final Result",
      category: CAT.DECONSTRUCT,
      summary: "Define the Ideal Final Result and resolve core technical or system contradictions.",
      systemPrompt:
        "You are a TRIZ practitioner specializing in the Ideal Final Result (IFR) and contradiction resolution. Maximize ideality by leveraging free or existing system resources without adding unnecessary cost or complexity.",
      userPromptTemplate:
        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply TRIZ & Ideal Final Result:\n1. State the Ideal Final Result (the system achieves the goal by itself with zero harm/cost).\n2. Identify the core contradiction (improving X worsens Y).\n3. List existing/free resources in the environment.\n4. Propose 2-3 contradiction-eliminating concepts."
    },
    {
      id: "scamper",
      name: "SCAMPER",
      category: CAT.DIVERGE,
      summary: "Systematically Substitute, Combine, Adapt, Modify, Put to another use, Eliminate, or Reverse.",
      systemPrompt:
        "You are a creative strategist applying the SCAMPER framework. Produce sharp, non-obvious ideas across each lens rather than generic checklists.",
      userPromptTemplate:
        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply SCAMPER (Substitute, Combine, Adapt, Modify, Put to other use, Eliminate, Reverse). Provide one concrete, high-leverage idea per letter, then highlight the top 2."
    },
    {
      id: "inversion",
      name: "Inversion",
      category: CAT.STRESS_TEST,
      summary: "Flip the problem upside down: ask how to guarantee failure, then invert the causes.",
      systemPrompt:
        "You are a systems thinker using Inversion (Jacobi / Munger style). Expose guaranteed failure modes first, then invert them into robust design rules.",
      userPromptTemplate:
        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply Inversion:\n1. How could we guarantee this effort fails miserably? (List 5 concrete ways.)\n2. Invert each failure mode into a concrete design principle or safeguard.\n3. Highlight the single highest-leverage safeguard."
    },
    {
      id: "six-thinking-hats",
      name: "Six Thinking Hats",
      category: CAT.REFRAME,
      summary: "Examine the problem through Facts, Emotions, Risks, Benefits, Creativity, and Process.",
      systemPrompt:
        "You are a facilitator applying Edward de Bono's Six Thinking Hats. Keep each hat distinct, concise, and actionable.",
      userPromptTemplate:
        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nAnalyze using all Six Thinking Hats:\n- **White (Facts & Gaps)**\n- **Red (Intuition & Emotion)**\n- **Black (Risks & Caution)**\n- **Yellow (Value & Optimism)**\n- **Green (Creative Alternatives)**\n- **Blue (Next-Step Process)**"
    },
    {
      id: "pre-mortem",
      name: "Pre-Mortem",
      category: CAT.STRESS_TEST,
      summary: "Assume the solution failed 12 months from now and trace the exact root causes backward.",
      systemPrompt:
        "You are a risk engineer conducting a Gary Klein Pre-Mortem. Write with diagnostic clarity, separating preventable execution errors from structural design flaws.",
      userPromptTemplate:
        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nImagine it is 12 months from now and the chosen solution has failed completely.\n1. Describe the 4 most plausible root causes of failure.\n2. Identify early warning signals for each.\n3. Define concrete pre-emptive mitigations to build in today."
    },
    {
      id: "biomimicry",
      name: "Biomimicry",
      category: CAT.DIVERGE,
      summary: "Borrow proven structural, behavioral, and ecosystem strategies from nature.",
      systemPrompt:
        "You are a biomimicry engineer. Translate biological mechanisms accurately into practical engineering, organizational, or product solutions without hand-waving.",
      userPromptTemplate:
        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply Biomimicry:\n1. Abstract the core functional challenge (e.g., thermal regulation, decentralized coordination, adhesion).\n2. Identify 3 distinct organisms or ecosystems that solve this function.\n3. Translate each biological mechanism into a concrete solution for the problem."
    },
    {
      id: "jobs-to-be-done",
      name: "Jobs-to-be-Done (JTBD)",
      category: CAT.REFRAME,
      summary: "Focus on the functional, emotional, and social progress the user is hiring a solution to make.",
      systemPrompt:
        "You are a product strategist using Jobs-to-be-Done theory. Separate the underlying job from current tools and uncover underserved outcomes.",
      userPromptTemplate:
        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply Jobs-to-be-Done:\n1. Define the Core Functional Job, Emotional Job, and Social Job.\n2. Identify the biggest friction points in how people 'hire' current solutions.\n3. Propose 2-3 solutions that deliver the job faster, cheaper, or with less anxiety."
    },
    {
      id: "lateral-thinking",
      name: "Lateral Thinking / Random Entry",
      category: CAT.DIVERGE,
      summary: "Break linear patterns using provocative analogies and unrelated domain bridges.",
      systemPrompt:
        "You are a lateral thinking facilitator. Use unexpected cross-domain analogies and provocations ('PO' statements) to jolt the problem out of obvious tracks, then harvest practical concepts.",
      userPromptTemplate:
        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply Lateral Thinking:\n1. Introduce 2 unrelated analogy domains (e.g., air traffic control, jazz improvisation, coral reefs).\n2. Extract specific operating principles from each domain.\n3. Harvest 2-3 unconventional yet workable solutions for the problem."
    },
    {
      id: "second-order-thinking",
      name: "Second-Order Thinking",
      category: CAT.STRESS_TEST,
      summary: "Trace the downstream consequences of consequences across time horizons.",
      systemPrompt:
        "You are a strategic analyst specializing in Second-Order Thinking. Look past immediate fixes to uncover feedback loops, unintended incentives, and compounding effects.",
      userPromptTemplate:
        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply Second-Order Thinking:\n1. Identify the obvious 1st-order fix.\n2. Trace the 2nd-order and 3rd-order consequences (1 month, 1 year, 5 years).\n3. Propose an approach whose 2nd-order effects compound positively."
    },
    {
      id: "blue-ocean-errc",
      name: "Blue Ocean / ERRC Grid",
      category: CAT.REFRAME,
      summary: "Redefine value by deciding what to Eliminate, Reduce, Raise, and Create.",
      systemPrompt:
        "You are a Blue Ocean strategist. Use the Eliminate-Reduce-Raise-Create (ERRC) grid to break the value-cost trade-off and open uncontested value.",
      userPromptTemplate:
        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nBuild an ERRC Grid for this problem:\n- **Eliminate**: Industry/habitual factors taken for granted that add no real value.\n- **Reduce**: Factors to cut well below standard.\n- **Raise**: Factors to push well above standard.\n- **Create**: Net-new factors never offered before.\nConclude with a 1-sentence value proposition."
    },
    {
      id: "constraint-removal",
      name: "Constraint Removal & Extreme Limits",
      category: CAT.DECONSTRUCT,
      summary: "Test both zero-constraint abundance and 10x-tighter scarcity to expose the true bottleneck.",
      systemPrompt:
        "You are an innovation architect using boundary-condition analysis. Push constraints to both extremes (infinite budget/time vs. 1/10th budget/time) to reveal the real leverage point.",
      userPromptTemplate:
        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply Constraint Extremes:\n1. **Zero Constraints**: If budget, time, and physics were unlimited, what would the ultimate solution look like?\n2. **10x Scarcity**: If you had 10% of the resources and 24 hours, what minimal version would still work?\n3. **Bridge**: Combine the best insight from both extremes into a practical solution."
    }
  ];

  const FOLLOWUP_PRESETS = Object.freeze([
    {
      id: "critique",
      label: "Critique",
      promptTemplate:
        "Critically evaluate your previous response. Identify the 3 weakest assumptions, hidden flaws, or blind spots, and suggest how to fix each."
    },
    {
      id: "action-plan",
      label: "Action Plan",
      promptTemplate:
        "Convert the strongest idea from your previous response into a concrete 5-step execution plan with a fast, low-cost first test."
    },
    {
      id: "go-deeper",
      label: "Go Deeper",
      promptTemplate:
        "Pick the single most promising concept from your previous response and expand it into a detailed blueprint with concrete mechanics and examples."
    },
    {
      id: "risks-constraints",
      label: "Risks & Constraints",
      promptTemplate:
        "Stress-test your previous ideas against practical constraints (cost, time, adoption friction, failure modes) and propose pragmatic workarounds."
    }
  ]);

  const METHOD_PRESET_GROUPS = Object.freeze({
    "quick-3": {
      label: "Quick 3",
      methodIds: ["first-principles", "triz-ifr", "inversion"]
    },
    divergent: {
      label: "Divergent",
      methodIds: ["scamper", "biomimicry", "lateral-thinking", "blue-ocean-errc"]
    },
    analytical: {
      label: "Analytical",
      methodIds: ["first-principles", "triz-ifr", "pre-mortem", "second-order-thinking"]
    },
    all: {
      label: "All 12",
      methodIds: BUILTIN_METHODS.map(function (m) { return m.id; })
    }
  });

  // Register all 12 built-in methods into Phase 0 MethodRegistry
  BUILTIN_METHODS.forEach(function (method) {
    IdeaPrism.Contracts.MethodRegistry.register(Object.freeze(method));
  });

  function compileMethodPrompt(method, problemStatement, constraintsContext) {
    const trimmedConstraints =
      typeof constraintsContext === "string" ? constraintsContext.trim() : "";
    const constraintsBlock = trimmedConstraints
      ? "\nConstraints & Context:\n" + trimmedConstraints + "\n"
      : "";

    return method.userPromptTemplate
      .replace("{{problemStatement}}", String(problemStatement || "").trim())
      .replace("{{constraintsBlock}}", constraintsBlock);
  }

  function compileSynthesisPrompt(problemStatement, constraintsContext, sourceCardSummaries) {
    const trimmedConstraints =
      typeof constraintsContext === "string" ? constraintsContext.trim() : "";
    const constraintsSection = trimmedConstraints
      ? "\nConstraints & Context:\n" + trimmedConstraints + "\n"
      : "";

    const blocks = sourceCardSummaries
      .map(function (item, idx) {
        return (
          "### Perspective " +
          (idx + 1) +
          ": " +
          item.methodName +
          "\n" +
          item.latestResponse
        );
      })
      .join("\n\n---\n\n");

    return {
      systemPrompt:
        "You are an executive innovation synthesizer. Integrate multiple analytical perspectives into a single coherent, actionable strategy. Resolve tensions explicitly rather than listing disconnected bullets.",
      userPrompt:
        "Problem Statement:\n" +
        String(problemStatement || "").trim() +
        constraintsSection +
        "\nSelected Thinking Method Outputs:\n\n" +
        blocks +
        "\n\nSynthesize these perspectives:\n" +
        "1. **High-Leverage Convergences**: Where do the methods reinforce each other?\n" +
        "2. **Resolved Tensions**: Where do they conflict, and how should we reconcile them?\n" +
        "3. **Integrated Strategy**: A unified, concrete concept combining the best elements.\n" +
        "4. **Immediate Next Experiment**: One fast validation step."
    };
  }

  IdeaPrism.Catalog = Object.freeze({
    FOLLOWUP_PRESETS: FOLLOWUP_PRESETS,
    METHOD_PRESET_GROUPS: METHOD_PRESET_GROUPS,
    compileMethodPrompt: compileMethodPrompt,
    compileSynthesisPrompt: compileSynthesisPrompt
  });

  if (typeof module !== "undefined" && module.exports) {
    module.exports = IdeaPrism.Catalog;
  }
})(typeof window !== "undefined" ? window : globalThis);

2. js/gemini-client.js

/**
 * IdeaPrism — Phase 1: Native Google Gemini REST API Client
 * Uses x-goog-api-key header exclusively (never URL query params).
 * Preserves optional onChunk(deltaText) hook for future SSE streaming.
 */
(function (globalScope) {
  "use strict";

  const IdeaPrism =
    globalScope.IdeaPrism ||
    (typeof require === "function" ? require("./contracts.js") : null);

  if (!IdeaPrism) {
    throw new Error("IdeaPrism Phase 0 contracts must be loaded before gemini-client.js");
  }

  const API_BASE = "https://generativelanguage.googleapis.com/v1beta";

  function requireApiKey() {
    const key = IdeaPrism.RuntimeAuth.getApiKey();
    if (!key) {
      throw new Error("Gemini API key is required. Enter your key in the header bar.");
    }
    return key;
  }

  function formatContents(messages) {
    return (messages || []).map(function (m) {
      return {
        role: m.role === "model" ? "model" : "user",
        parts: [{ text: String(m.text || "") }]
      };
    });
  }

  function extractErrorMessage(status, bodyJson, fallbackText) {
    if (bodyJson && bodyJson.error && bodyJson.error.message) {
      return "Gemini API (" + status + "): " + bodyJson.error.message;
    }
    return "Gemini API request failed with HTTP " + status + (fallbackText ? ": " + fallbackText : "");
  }

  async function generate(params) {
    const apiKey = requireApiKey();
    const modelConfig = IdeaPrism.Factories.createModelConfig(params.modelConfig);
    const modelId = modelConfig.modelId.replace(/^models\//, "");
    const url = API_BASE + "/models/" + encodeURIComponent(modelId) + ":generateContent";

    const payload = {
      contents: formatContents(params.messages),
      generationConfig: {
        temperature: modelConfig.temperature,
        maxOutputTokens: modelConfig.maxOutputTokens
      }
    };

    if (typeof params.systemPrompt === "string" && params.systemPrompt.trim()) {
      payload.systemInstruction = {
        parts: [{ text: params.systemPrompt.trim() }]
      };
    }

    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-goog-api-key": apiKey
      },
      body: JSON.stringify(payload),
      signal: params.signal
    });

    const rawText = await response.text();
    let data = null;
    try {
      data = rawText ? JSON.parse(rawText) : null;
    } catch (e) {
      data = null;
    }

    if (!response.ok) {
      throw new Error(extractErrorMessage(response.status, data, rawText.slice(0, 200)));
    }

    const candidate = data && Array.isArray(data.candidates) ? data.candidates[0] : null;
    const parts = candidate && candidate.content && Array.isArray(candidate.content.parts)
      ? candidate.content.parts
      : [];
    const text = parts
      .map(function (p) { return typeof p.text === "string" ? p.text : ""; })
      .join("")
      .trim();

    if (!text) {
      const reason = candidate && candidate.finishReason ? candidate.finishReason : "EMPTY_RESPONSE";
      throw new Error("Gemini returned no text output (reason: " + reason + ").");
    }

    // Additive Phase 0 streaming hook (invoked once in non-streaming v1)
    if (typeof params.onChunk === "function") {
      params.onChunk(text);
    }

    const usageMeta = data && data.usageMetadata ? data.usageMetadata : null;
    const tokenUsage = usageMeta
      ? {
          promptTokens: Number(usageMeta.promptTokenCount) || 0,
          candidateTokens: Number(usageMeta.candidatesTokenCount) || 0,
          totalTokens: Number(usageMeta.totalTokenCount) || 0
        }
      : null;

    return { text: text, tokenUsage: tokenUsage };
  }

  async function listModels(params) {
    const apiKey = requireApiKey();
    const signal = params && params.signal ? params.signal : undefined;
    const url = API_BASE + "/models?pageSize=100";

    const response = await fetch(url, {
      method: "GET",
      headers: {
        "x-goog-api-key": apiKey
      },
      signal: signal
    });

    const rawText = await response.text();
    let data = null;
    try {
      data = rawText ? JSON.parse(rawText) : null;
    } catch (e) {
      data = null;
    }

    if (!response.ok) {
      throw new Error(extractErrorMessage(response.status, data, rawText.slice(0, 200)));
    }

    const models = data && Array.isArray(data.models) ? data.models : [];
    return models
      .filter(function (m) {
        return (
          Array.isArray(m.supportedGenerationMethods) &&
          m.supportedGenerationMethods.indexOf("generateContent") !== -1
        );
      })
      .map(function (m) {
        const cleanId = String(m.name || "").replace(/^models\//, "");
        return {
          id: cleanId,
          displayName: m.displayName || cleanId,
          description: m.description || ""
        };
      });
  }

  IdeaPrism.Contracts.GeminiClient.generate = generate;
  IdeaPrism.Contracts.GeminiClient.listModels = listModels;

  if (typeof module !== "undefined" && module.exports) {
    module.exports = IdeaPrism.Contracts.GeminiClient;
  }
})(typeof window !== "undefined" ? window : globalThis);

3. js/execution-queue.js

/**
 * IdeaPrism — Phase 1: Bounded Concurrency Execution Queue
 * Prevents Gemini 429 rate-limit bursts and supports per-task & global AbortController cancellation.
 */
(function (globalScope) {
  "use strict";

  const IdeaPrism =
    globalScope.IdeaPrism ||
    (typeof require === "function" ? require("./contracts.js") : null);

  if (!IdeaPrism) {
    throw new Error("IdeaPrism Phase 0 contracts must be loaded before execution-queue.js");
  }

  function createExecutionQueue(maxConcurrency) {
    const limit = typeof maxConcurrency === "number" && maxConcurrency > 0 ? maxConcurrency : 3;
    const pending = []; // Array<{ taskId, runner, controller }>
    const running = new Map(); // taskId -> { controller }
    const listeners = new Set();

    function notify() {
      const stats = getStats();
      listeners.forEach(function (fn) {
        try {
          fn(stats);
        } catch (e) {
          // isolate listener errors
        }
      });
    }

    function pump() {
      while (running.size < limit && pending.length > 0) {
        const job = pending.shift();
        if (job.controller.signal.aborted) {
          continue;
        }
        running.set(job.taskId, { controller: job.controller });
        notify();

        Promise.resolve()
          .then(function () {
            return job.runner(job.controller.signal);
          })
          .catch(function () {
            // Task-level errors are handled inside the runner
          })
          .finally(function () {
            running.delete(job.taskId);
            notify();
            pump();
          });
      }
    }

    function enqueue(taskId, runner) {
      // Cancel any prior pending/running instance of the same taskId
      cancel(taskId);
      const controller = new AbortController();
      pending.push({ taskId: taskId, runner: runner, controller: controller });
      notify();
      pump();
    }

    function cancel(taskId) {
      let changed = false;
      for (let i = pending.length - 1; i >= 0; i--) {
        if (pending[i].taskId === taskId) {
          pending[i].controller.abort();
          pending.splice(i, 1);
          changed = true;
        }
      }
      if (running.has(taskId)) {
        running.get(taskId).controller.abort();
        changed = true;
      }
      if (changed) notify();
    }

    function cancelAll() {
      while (pending.length > 0) {
        const job = pending.shift();
        job.controller.abort();
      }
      running.forEach(function (entry) {
        entry.controller.abort();
      });
      notify();
    }

    function getStats() {
      return {
        queued: pending.length,
        running: running.size,
        maxConcurrency: limit
      };
    }

    function subscribe(fn) {
      listeners.add(fn);
      return function () {
        listeners.delete(fn);
      };
    }

    return {
      enqueue: enqueue,
      cancel: cancel,
      cancelAll: cancelAll,
      getStats: getStats,
      subscribe: subscribe
    };
  }

  const defaultQueue = createExecutionQueue(3);

  IdeaPrism.Contracts.ExecutionQueue.enqueue = defaultQueue.enqueue;
  IdeaPrism.Contracts.ExecutionQueue.cancel = defaultQueue.cancel;
  IdeaPrism.Contracts.ExecutionQueue.cancelAll = defaultQueue.cancelAll;
  IdeaPrism.Contracts.ExecutionQueue.getStats = defaultQueue.getStats;
  IdeaPrism.Contracts.ExecutionQueue.subscribe = defaultQueue.subscribe;
  IdeaPrism.createExecutionQueue = createExecutionQueue;

  if (typeof module !== "undefined" && module.exports) {
    module.exports = {
      defaultQueue: defaultQueue,
      createExecutionQueue: createExecutionQueue
    };
  }
})(typeof window !== "undefined" ? window : globalThis);

4. js/storage.js

/**
 * IdeaPrism — Phase 1: localStorage Persistence Adapter
 * Enforces strict Phase 0 allowlist serialization (zero apiKey leakage)
 * and graceful QuotaExceededError handling.
 */
(function (globalScope) {
  "use strict";

  const IdeaPrism =
    globalScope.IdeaPrism ||
    (typeof require === "function" ? require("./contracts.js") : null);

  if (!IdeaPrism) {
    throw new Error("IdeaPrism Phase 0 contracts must be loaded before storage.js");
  }

  const STORAGE_KEY = "ideaprism_sessions_v1";

  function getStorageBackend() {
    if (typeof globalScope.localStorage !== "undefined") {
      return globalScope.localStorage;
    }
    return null;
  }

  function readAllRaw(backend) {
    const store = backend || getStorageBackend();
    if (!store) return [];
    try {
      const raw = store.getItem(STORAGE_KEY);
      if (!raw) return [];
      const parsed = JSON.parse(raw);
      return Array.isArray(parsed) ? parsed : [];
    } catch (e) {
      return [];
    }
  }

  function writeAllRaw(sessions, backend) {
    const store = backend || getStorageBackend();
    if (!store) return { ok: false, error: "STORAGE_UNAVAILABLE" };
    try {
      store.setItem(STORAGE_KEY, JSON.stringify(sessions));
      return { ok: true };
    } catch (err) {
      const isQuota =
        err &&
        (err.name === "QuotaExceededError" ||
          err.name === "NS_ERROR_DOM_QUOTA_REACHED" ||
          err.code === 22);
      return {
        ok: false,
        error: isQuota ? "QUOTA_EXCEEDED" : "STORAGE_WRITE_ERROR"
      };
    }
  }

  function listSessions(backend) {
    return readAllRaw(backend)
      .map(function (item) {
        const res = IdeaPrism.Validation.validateSession(item);
        return res.valid ? res.sanitized : null;
      })
      .filter(Boolean)
      .sort(function (a, b) {
        return String(b.updatedAt).localeCompare(String(a.updatedAt));
      });
  }

  function saveSession(session, backend) {
    // Strip unknown/secret fields first via allowlist serializer, then validate
    const sanitized = IdeaPrism.Validation.sanitizeSessionForPersistence(session);
    const check = IdeaPrism.Validation.validateSession(sanitized);
    if (!check.valid) {
      return { ok: false, error: "INVALID_SCHEMA", details: check.errors };
    }

    const existing = listSessions(backend);
    const idx = existing.findIndex(function (s) {
      return s.id === check.sanitized.id;
    });
    if (idx >= 0) {
      existing[idx] = check.sanitized;
    } else {
      existing.unshift(check.sanitized);
    }

    return writeAllRaw(existing, backend);
  }

  function deleteSession(sessionId, backend) {
    const existing = listSessions(backend).filter(function (s) {
      return s.id !== sessionId;
    });
    return writeAllRaw(existing, backend);
  }

  IdeaPrism.Contracts.StorageAdapter.listSessions = listSessions;
  IdeaPrism.Contracts.StorageAdapter.saveSession = saveSession;
  IdeaPrism.Contracts.StorageAdapter.deleteSession = deleteSession;

  if (typeof module !== "undefined" && module.exports) {
    module.exports = IdeaPrism.Contracts.StorageAdapter;
  }
})(typeof window !== "undefined" ? window : globalThis);

5. js/session-store.js

/**
 * IdeaPrism — Phase 1: Observable Session Store
 * Coordinates active ProblemSession state, card transitions, and debounced persistence.
 */
(function (globalScope) {
  "use strict";

  const IdeaPrism =
    globalScope.IdeaPrism ||
    (typeof require === "function" ? require("./contracts.js") : null);

  if (!IdeaPrism) {
    throw new Error("IdeaPrism Phase 0 contracts must be loaded before session-store.js");
  }

  function createSessionStore() {
    let activeSession = IdeaPrism.Factories.createProblemSession({
      selectedMethodIds: IdeaPrism.Catalog
        ? IdeaPrism.Catalog.METHOD_PRESET_GROUPS["quick-3"].methodIds
        : []
    });
    let lastStorageError = null;
    const listeners = new Set();

    function notify() {
      listeners.forEach(function (fn) {
        try {
          fn(activeSession, lastStorageError);
        } catch (e) {
          // isolate subscriber errors
        }
      });
    }

    function touchAndPersist() {
      activeSession.updatedAt = new Date().toISOString();
      if (activeSession.problemStatement.trim().length > 0) {
        const res = IdeaPrism.Contracts.StorageAdapter.saveSession(activeSession);
        lastStorageError = res.ok ? null : res.error;
      }
      notify();
    }

    function getSession() {
      return activeSession;
    }

    function setSession(session) {
      const check = IdeaPrism.Validation.validateSession(session);
      if (!check.valid) {
        throw new Error("Cannot load invalid session: " + check.errors.join("; "));
      }
      activeSession = check.sanitized;
      lastStorageError = null;
      notify();
    }

    function newSession(overrides) {
      IdeaPrism.Contracts.ExecutionQueue.cancelAll();
      activeSession = IdeaPrism.Factories.createProblemSession(overrides || {});
      lastStorageError = null;
      notify();
      return activeSession;
    }

    function updateSessionMeta(patch) {
      if (typeof patch.title === "string") activeSession.title = patch.title;
      if (typeof patch.problemStatement === "string") {
        activeSession.problemStatement = patch.problemStatement;
        if (!activeSession.title || activeSession.title === "Untitled Session") {
          activeSession.title = patch.problemStatement.trim().slice(0, 60) || "Untitled Session";
        }
      }
      if (typeof patch.constraintsContext === "string") {
        activeSession.constraintsContext = patch.constraintsContext;
      }
      if (patch.modelConfig) {
        activeSession.modelConfig = IdeaPrism.Factories.createModelConfig(patch.modelConfig);
      }
      if (Array.isArray(patch.selectedMethodIds)) {
        activeSession.selectedMethodIds = patch.selectedMethodIds.slice();
      }
      touchAndPersist();
    }

    function findCard(cardId) {
      const m = activeSession.cards.find(function (c) { return c.id === cardId; });
      if (m) return m;
      return activeSession.syntheses.find(function (s) { return s.id === cardId; }) || null;
    }

    function upsertMethodCard(card) {
      const idx = activeSession.cards.findIndex(function (c) { return c.id === card.id; });
      if (idx >= 0) {
        activeSession.cards[idx] = card;
      } else {
        activeSession.cards.push(card);
      }
      touchAndPersist();
    }

    function upsertSynthesisCard(card) {
      const idx = activeSession.syntheses.findIndex(function (s) { return s.id === card.id; });
      if (idx >= 0) {
        activeSession.syntheses[idx] = card;
      } else {
        activeSession.syntheses.unshift(card);
      }
      touchAndPersist();
    }

    function transitionCard(cardId, nextStatus, patch) {
      const card = findCard(cardId);
      if (!card) throw new Error("Card not found: " + cardId);
      IdeaPrism.CardStateMachine.assertTransition(card.status, nextStatus);
      card.status = nextStatus;
      if (patch) {
        if ("error" in patch) card.error = patch.error;
        if ("tokenUsage" in patch) card.tokenUsage = patch.tokenUsage;
        if (Array.isArray(patch.messages)) card.messages = patch.messages;
      }
      card.updatedAt = new Date().toISOString();
      touchAndPersist();
      return card;
    }

    function toggleCardFlag(cardId, flagName) {
      const card = findCard(cardId);
      if (!card) return;
      if (flagName === "starred") {
        card.starred = !card.starred;
      } else if (flagName === "selectedForSynthesis" && card.kind === "method") {
        card.selectedForSynthesis = !card.selectedForSynthesis;
      }
      touchAndPersist();
    }

    function subscribe(fn) {
      listeners.add(fn);
      return function () {
        listeners.delete(fn);
      };
    }

    return {
      getSession: getSession,
      setSession: setSession,
      newSession: newSession,
      updateSessionMeta: updateSessionMeta,
      findCard: findCard,
      upsertMethodCard: upsertMethodCard,
      upsertSynthesisCard: upsertSynthesisCard,
      transitionCard: transitionCard,
      toggleCardFlag: toggleCardFlag,
      subscribe: subscribe
    };
  }

  IdeaPrism.SessionStore = createSessionStore();

  if (typeof module !== "undefined" && module.exports) {
    module.exports = IdeaPrism.SessionStore;
  }
})(typeof window !== "undefined" ? window : globalThis);

6. tests/phase1-verify.js (Phase 1 Verification Gate)

Run via node tests/phase1-verify.js (or include in an HTML runner after the Phase 1 scripts):

/**
 * IdeaPrism — Phase 1 Verification Gate Tests
 * Run in Node.js: node tests/phase1-verify.js
 */
(async function () {
  "use strict";

  const IdeaPrism = require("../js/contracts.js");
  require("../js/methods-catalog.js");
  require("../js/gemini-client.js");
  const { createExecutionQueue } = require("../js/execution-queue.js");
  require("../js/storage.js");
  require("../js/session-store.js");

  const results = [];

  async function test(name, fn) {
    try {
      await fn();
      results.push({ name: name, pass: true });
    } catch (err) {
      results.push({ name: name, pass: false, error: err.message });
    }
  }

  function assert(cond, msg) {
    if (!cond) throw new Error(msg || "Assertion failed");
  }

  // Gate 1: All 12 methods registered & prompt compilation works
  await test("All 12 built-in methods register and compile problem + constraints", function () {
    const methods = IdeaPrism.Contracts.MethodRegistry.getAll();
    assert(methods.length === 12, "Expected 12 methods, got " + methods.length);
    const compiled = IdeaPrism.Catalog.compileMethodPrompt(
      methods[0],
      "Improve solar panel recycling",
      "Under $50 per panel"
    );
    assert(compiled.indexOf("Improve solar panel recycling") !== -1, "Missing problem statement");
    assert(compiled.indexOf("Under $50 per panel") !== -1, "Missing constraints");
  });

  // Gate 2: ExecutionQueue enforces maxConcurrency = 3 and AbortSignal cancellation
  await test("ExecutionQueue enforces maxConcurrency=3 and cancels via AbortSignal", async function () {
    const queue = createExecutionQueue(3);
    let active = 0;
    let peak = 0;
    let abortedSeen = false;

    const tasks = [];
    for (let i = 0; i < 6; i++) {
      tasks.push(
        new Promise(function (resolve) {
          queue.enqueue("task-" + i, function (signal) {
            return new Promise(function (done) {
              active++;
              if (active > peak) peak = active;
              signal.addEventListener("abort", function () {
                abortedSeen = true;
              });
              setTimeout(function () {
                active--;
                done();
                resolve();
              }, 25);
            });
          });
        })
      );
    }

    queue.cancel("task-5");
    await Promise.all(tasks.slice(0, 5));
    assert(peak <= 3, "Peak concurrency exceeded 3: " + peak);
    assert(abortedSeen === false || queue.getStats().queued === 0, "Cancelled queued task should not stall");
  });

  // Gate 3: StorageAdapter strips apiKey and handles QuotaExceededError
  await test("StorageAdapter strips apiKey and catches QuotaExceededError", function () {
    const mem = {};
    const mockStorage = {
      getItem: function (k) { return mem[k] || null; },
      setItem: function (k, v) { mem[k] = v; }
    };

    const session = IdeaPrism.Factories.createProblemSession({
      problemStatement: "Test persistence"
    });
    session.apiKey = "SHOULD_BE_STRIPPED";

    const res = IdeaPrism.Contracts.StorageAdapter.saveSession(session, mockStorage);
    assert(res.ok === true, "Expected saveSession to succeed after stripping apiKey");
    assert(
      JSON.stringify(mem).indexOf("SHOULD_BE_STRIPPED") === -1,
      "apiKey leaked into storage!"
    );

    const fullStorage = {
      getItem: function () { return "[]"; },
      setItem: function () {
        const err = new Error("Quota exceeded");
        err.name = "QuotaExceededError";
        throw err;
      }
    };
    const quotaRes = IdeaPrism.Contracts.StorageAdapter.saveSession(session, fullStorage);
    assert(quotaRes.ok === false && quotaRes.error === "QUOTA_EXCEEDED", "Expected QUOTA_EXCEEDED");
  });

  const failed = results.filter(function (r) { return !r.pass; });
  results.forEach(function (r) {
    console.log((r.pass ? "[PASS] " : "[FAIL] ") + r.name + (r.error ? " — " + r.error : ""));
  });
  console.log("\nPhase 1 Gate: " + (results.length - failed.length) + "/" + results.length + " passed.");
  if (failed.length > 0) process.exit(1);
})();

Run node tests/phase1-verify.js (and re-run node tests/phase0-verify.js to confirm zero regressions). Once Phase 1 passes, we are ready for Phase 2 (index.html, css/styles.css, js/markdown-safe.js, and js/app-shell.js).


Phase 1 passed. Generate Phase 2 now: index.html, css/styles.css, js/markdown-safe.js, and js/app-shell.js.

Phase 2 delivers the zero-build HTML shell, responsive CSS, XSS-safe DOM Markdown renderer, and header/workspace controller—strictly wired to Phase 0 contracts and Phase 1 modules with zero modifications to prior files.

1. index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>IdeaPrism — Innovative Thinking Studio</title>
  <link rel="stylesheet" href="css/styles.css" />

  <!-- Phase 0: Core Contracts -->
  <script defer src="js/contracts.js"></script>
  <!-- Phase 1: Core Engine & Persistence -->
  <script defer src="js/methods-catalog.js"></script>
  <script defer src="js/gemini-client.js"></script>
  <script defer src="js/execution-queue.js"></script>
  <script defer src="js/storage.js"></script>
  <script defer src="js/session-store.js"></script>
  <!-- Phase 2: Safe Markdown & App Shell -->
  <script defer src="js/markdown-safe.js"></script>
  <script defer src="js/app-shell.js"></script>
  <!-- Phase 3–5 scripts will be appended here additively -->
</head>
<body>
  <header class="app-header">
    <div class="brand">
      <span class="brand-mark" aria-hidden="true">◆</span>
      <div>
        <h1>IdeaPrism</h1>
        <p class="brand-sub">Innovative Thinking Studio · Gemini BYOK</p>
      </div>
    </div>

    <div class="header-controls">
      <div class="control-group api-key-group">
        <label for="api-key-input">Gemini API Key <span class="badge-memory">Memory Only</span></label>
        <div class="input-row">
          <input
            id="api-key-input"
            type="password"
            placeholder="AIza..."
            autocomplete="off"
            spellcheck="false"
          />
          <button id="toggle-key-btn" type="button" class="btn btn-ghost" title="Show/Hide API Key">Show</button>
          <button id="clear-key-btn" type="button" class="btn btn-ghost" title="Clear API Key from memory">Clear</button>
        </div>
      </div>

      <div class="control-group model-group">
        <label for="model-select">Gemini Model</label>
        <div class="input-row">
          <select id="model-select" aria-label="Select Gemini Model"></select>
          <button id="refresh-models-btn" type="button" class="btn btn-secondary" title="Discover models via Gemini API">
            Refresh
          </button>
        </div>
        <input
          id="custom-model-input"
          type="text"
          class="custom-model-input"
          placeholder="Or type custom model ID (overrides dropdown)"
          autocomplete="off"
          spellcheck="false"
        />
      </div>

      <div class="header-actions">
        <button id="open-history-btn" type="button" class="btn btn-secondary" disabled title="Available in Phase 5">
          History &amp; Export
        </button>
      </div>
    </div>
  </header>

  <div id="global-alert" class="global-alert hidden" role="alert"></div>

  <main class="workspace">
    <section class="panel problem-panel" aria-labelledby="problem-heading">
      <div class="panel-header">
        <h2 id="problem-heading">1. Problem Statement</h2>
        <button id="new-session-btn" type="button" class="btn btn-ghost">New Session</button>
      </div>

      <textarea
        id="problem-input"
        rows="4"
        placeholder="Describe the problem, challenge, or system you want to rethink..."
      ></textarea>

      <details class="constraints-drawer">
        <summary>Optional: Constraints &amp; Context (budget, timeline, audience, non-negotiables)</summary>
        <textarea
          id="constraints-input"
          rows="3"
          placeholder="e.g., Must cost under $50, launch in 4 weeks, no backend infrastructure..."
        ></textarea>
      </details>
    </section>

    <section class="panel methods-panel" aria-labelledby="methods-heading">
      <div class="panel-header">
        <h2 id="methods-heading">2. Innovative Thinking Methods</h2>
        <div id="method-presets" class="preset-bar" role="group" aria-label="Method presets"></div>
      </div>

      <div id="category-filters" class="filter-bar" role="tablist" aria-label="Filter methods by category"></div>
      <div id="method-selector-grid" class="method-selector-grid"></div>

      <div class="run-bar">
        <button id="run-methods-btn" type="button" class="btn btn-primary">
          Run Selected Methods
        </button>
        <div id="queue-status" class="queue-status" aria-live="polite">Idle</div>
        <button id="cancel-all-btn" type="button" class="btn btn-danger hidden">
          Cancel All
        </button>
      </div>
    </section>

    <!-- Phase 4 Mount Point: Cross-Card Synthesis Bar & Cards -->
    <div id="synthesis-bar" class="synthesis-bar hidden"></div>
    <section id="synthesis-section" class="results-section hidden" aria-label="Synthesis Results">
      <h2>Synthesized Strategies</h2>
      <div id="synthesis-grid" class="cards-grid"></div>
    </section>

    <!-- Phase 3 Mount Point: Method Result Cards -->
    <section id="results-section" class="results-section" aria-label="Method Results">
      <div class="panel-header">
        <h2>3. Thinking Method Cards</h2>
        <span id="cards-count" class="muted-text">0 cards</span>
      </div>
      <div id="cards-grid" class="cards-grid">
        <p class="empty-state">Select one or more thinking methods above and click <strong>Run Selected Methods</strong>.</p>
      </div>
    </section>
  </main>

  <!-- Phase 5 Mount Point: Session History Slide-Over Drawer -->
  <aside id="history-drawer" class="history-drawer hidden" aria-label="Session History"></aside>
</body>
</html>

2. css/styles.css

:root {
  --bg: #0f172a;
  --surface: #1e293b;
  --surface-alt: #263449;
  --border: #334155;
  --text: #f1f5f9;
  --text-muted: #94a3b8;
  --accent: #38bdf8;
  --accent-strong: #0284c7;
  --success: #22c55e;
  --warning: #f59e0b;
  --danger: #ef4444;
  --radius: 10px;
  --shadow: 0 4px 16px rgba(0, 0, 0, 0.25);
}

*, *::before, *::after {
  box-sizing: border-box;
}

body {
  margin: 0;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  background: var(--bg);
  color: var(--text);
  line-height: 1.5;
}

.hidden {
  display: none !important;
}

.muted-text {
  color: var(--text-muted);
  font-size: 0.875rem;
}

/* Header */
.app-header {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: flex-start;
  gap: 1rem;
  padding: 1rem 1.5rem;
  background: var(--surface);
  border-bottom: 1px solid var(--border);
}

.brand {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.brand-mark {
  font-size: 1.75rem;
  color: var(--accent);
}

.brand h1 {
  margin: 0;
  font-size: 1.25rem;
}

.brand-sub {
  margin: 0;
  font-size: 0.8rem;
  color: var(--text-muted);
}

.header-controls {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  gap: 1rem;
}

.control-group {
  display: flex;
  flex-direction: column;
  gap: 0.35rem;
}

.control-group label {
  font-size: 0.78rem;
  font-weight: 600;
  color: var(--text-muted);
  display: flex;
  align-items: center;
  gap: 0.4rem;
}

.badge-memory {
  font-size: 0.68rem;
  padding: 0.1rem 0.4rem;
  border-radius: 999px;
  background: rgba(56, 189, 248, 0.15);
  color: var(--accent);
}

.input-row {
  display: flex;
  gap: 0.4rem;
}

input[type="text"],
input[type="password"],
select,
textarea {
  background: var(--bg);
  color: var(--text);
  border: 1px solid var(--border);
  border-radius: 6px;
  padding: 0.45rem 0.65rem;
  font-family: inherit;
  font-size: 0.9rem;
}

input:focus,
select:focus,
textarea:focus {
  outline: 2px solid var(--accent);
  outline-offset: 1px;
}

.custom-model-input {
  width: 100%;
  font-size: 0.82rem;
}

/* Buttons */
.btn {
  border: 1px solid transparent;
  border-radius: 6px;
  padding: 0.45rem 0.85rem;
  font-size: 0.85rem;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.15s ease, opacity 0.15s ease;
}

.btn:disabled {
  opacity: 0.45;
  cursor: not-allowed;
}

.btn-primary {
  background: var(--accent-strong);
  color: #fff;
}

.btn-primary:hover:not(:disabled) {
  background: var(--accent);
  color: #0f172a;
}

.btn-secondary {
  background: var(--surface-alt);
  color: var(--text);
  border-color: var(--border);
}

.btn-secondary:hover:not(:disabled) {
  border-color: var(--accent);
}

.btn-ghost {
  background: transparent;
  color: var(--text-muted);
  border-color: var(--border);
}

.btn-ghost:hover:not(:disabled) {
  color: var(--text);
  border-color: var(--text-muted);
}

.btn-danger {
  background: rgba(239, 68, 68, 0.18);
  color: #fca5a5;
  border-color: var(--danger);
}

/* Global Alert */
.global-alert {
  margin: 0.75rem 1.5rem 0;
  padding: 0.75rem 1rem;
  border-radius: var(--radius);
  background: rgba(239, 68, 68, 0.15);
  border: 1px solid var(--danger);
  color: #fecaca;
  font-size: 0.9rem;
}

/* Main Workspace */
.workspace {
  max-width: 1440px;
  margin: 0 auto;
  padding: 1.25rem 1.5rem 3rem;
  display: flex;
  flex-direction: column;
  gap: 1.25rem;
}

.panel {
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: var(--radius);
  padding: 1.15rem 1.25rem;
  box-shadow: var(--shadow);
}

.panel-header {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  gap: 0.75rem;
  margin-bottom: 0.75rem;
}

.panel-header h2 {
  margin: 0;
  font-size: 1.05rem;
}

.problem-panel textarea {
  width: 100%;
  resize: vertical;
}

.constraints-drawer {
  margin-top: 0.75rem;
}

.constraints-drawer summary {
  cursor: pointer;
  font-size: 0.85rem;
  color: var(--accent);
  margin-bottom: 0.5rem;
}

/* Method Selector */
.preset-bar,
.filter-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 0.4rem;
}

.filter-bar {
  margin-bottom: 0.75rem;
}

.pill-btn {
  background: var(--bg);
  color: var(--text-muted);
  border: 1px solid var(--border);
  border-radius: 999px;
  padding: 0.25rem 0.7rem;
  font-size: 0.8rem;
  cursor: pointer;
}

.pill-btn.active {
  background: var(--accent-strong);
  color: #fff;
  border-color: var(--accent-strong);
}

.method-selector-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 0.65rem;
  margin-bottom: 1rem;
}

.method-option {
  display: flex;
  align-items: flex-start;
  gap: 0.55rem;
  padding: 0.65rem 0.75rem;
  background: var(--bg);
  border: 1px solid var(--border);
  border-radius: 8px;
  cursor: pointer;
}

.method-option.selected {
  border-color: var(--accent);
  background: rgba(56, 189, 248, 0.08);
}

.method-option input {
  margin-top: 0.2rem;
}

.method-option-title {
  font-weight: 600;
  font-size: 0.88rem;
}

.method-option-cat {
  font-size: 0.72rem;
  color: var(--accent);
}

.method-option-desc {
  font-size: 0.78rem;
  color: var(--text-muted);
  margin-top: 0.15rem;
}

.run-bar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 0.85rem;
  padding-top: 0.5rem;
  border-top: 1px solid var(--border);
}

.queue-status {
  font-size: 0.85rem;
  color: var(--text-muted);
}

/* Cards Grid & Status Badges */
.cards-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));
  gap: 1rem;
}

.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 2rem;
  color: var(--text-muted);
  background: var(--surface);
  border: 1px dashed var(--border);
  border-radius: var(--radius);
}

.result-card {
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: var(--radius);
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  box-shadow: var(--shadow);
}

.status-badge {
  display: inline-block;
  font-size: 0.72rem;
  font-weight: 700;
  text-transform: uppercase;
  padding: 0.15rem 0.5rem;
  border-radius: 999px;
}

.status-idle { background: #334155; color: #cbd5e1; }
.status-queued { background: rgba(245, 158, 11, 0.2); color: #fcd34d; }
.status-loading { background: rgba(56, 189, 248, 0.2); color: #7dd3fc; }
.status-complete { background: rgba(34, 197, 94, 0.2); color: #86efac; }
.status-error { background: rgba(239, 68, 68, 0.2); color: #fca5a5; }
.status-cancelled { background: #475569; color: #e2e8f0; }

/* Safe Markdown Typography */
.md-body {
  font-size: 0.9rem;
  word-break: break-word;
}

.md-body h1, .md-body h2, .md-body h3, .md-body h4 {
  margin: 0.8rem 0 0.4rem;
  line-height: 1.3;
}

.md-body p {
  margin: 0.45rem 0;
}

.md-body ul, .md-body ol {
  margin: 0.4rem 0;
  padding-left: 1.35rem;
}

.md-body blockquote {
  margin: 0.5rem 0;
  padding: 0.35rem 0.75rem;
  border-left: 3px solid var(--accent);
  background: rgba(56, 189, 248, 0.06);
  color: var(--text-muted);
}

.md-body pre {
  background: var(--bg);
  padding: 0.75rem;
  border-radius: 6px;
  overflow-x: auto;
  border: 1px solid var(--border);
}

.md-body code {
  font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
  font-size: 0.84em;
  background: rgba(15, 23, 42, 0.65);
  padding: 0.1rem 0.3rem;
  border-radius: 4px;
}

.md-body pre code {
  background: transparent;
  padding: 0;
}

.md-body table {
  width: 100%;
  border-collapse: collapse;
  margin: 0.6rem 0;
  font-size: 0.84rem;
}

.md-body th, .md-body td {
  border: 1px solid var(--border);
  padding: 0.35rem 0.5rem;
  text-align: left;
}

.md-body th {
  background: var(--surface-alt);
}

.md-body a {
  color: var(--accent);
  text-decoration: underline;
}

3. js/markdown-safe.js

/**
 * IdeaPrism — Phase 2: Zero-Dependency XSS-Safe DOM Markdown Renderer
 * Never uses innerHTML on untrusted LLM text. All text is inserted via createTextNode().
 */
(function (globalScope) {
  "use strict";

  const IdeaPrism =
    globalScope.IdeaPrism ||
    (typeof require === "function" ? require("./contracts.js") : null);

  if (!IdeaPrism) {
    throw new Error("IdeaPrism Phase 0 contracts must be loaded before markdown-safe.js");
  }

  function isSafeHttpUrl(url) {
    return /^https?:\/\/[^\s<>"']+$/i.test(String(url || "").trim());
  }

  function appendInlineNodes(parent, text) {
    // Tokenize inline code, links, bold, and italic safely
    const pattern = /(`[^`]+`|\[([^\]]+)\]\(([^)]+)\)|\*\*([^*]+)\*\*|\*([^*]+)\*)/g;
    let lastIndex = 0;
    let match;

    while ((match = pattern.exec(text)) !== null) {
      if (match.index > lastIndex) {
        parent.appendChild(document.createTextNode(text.slice(lastIndex, match.index)));
      }

      const token = match[0];
      if (token.startsWith("`")) {
        const code = document.createElement("code");
        code.textContent = token.slice(1, -1);
        parent.appendChild(code);
      } else if (match[2] !== undefined && match[3] !== undefined) {
        const label = match[2];
        const href = match[3].trim();
        if (isSafeHttpUrl(href)) {
          const a = document.createElement("a");
          a.href = href;
          a.target = "_blank";
          a.rel = "noopener noreferrer";
          a.textContent = label;
          parent.appendChild(a);
        } else {
          // Neutralize javascript: or unsafe schemes as inert plain text
          parent.appendChild(document.createTextNode(label + " (" + href + ")"));
        }
      } else if (match[4] !== undefined) {
        const strong = document.createElement("strong");
        appendInlineNodes(strong, match[4]);
        parent.appendChild(strong);
      } else if (match[5] !== undefined) {
        const em = document.createElement("em");
        appendInlineNodes(em, match[5]);
        parent.appendChild(em);
      }

      lastIndex = pattern.lastIndex;
    }

    if (lastIndex < text.length) {
      parent.appendChild(document.createTextNode(text.slice(lastIndex)));
    }
  }

  function parseTableRow(line) {
    return line
      .trim()
      .replace(/^\|/, "")
      .replace(/\|$/, "")
      .split("|")
      .map(function (cell) { return cell.trim(); });
  }

  function isTableSeparator(line) {
    return /^\|?(\s*:?-{3,}:?\s*\|)+\s*:?-{3,}:?\s*\|?$/.test(line.trim());
  }

  function renderSafeMarkdown(markdownText) {
    const frag = document.createDocumentFragment();
    const lines = String(markdownText || "").replace(/\r\n/g, "\n").split("\n");
    let i = 0;

    while (i < lines.length) {
      const line = lines[i];
      const trimmed = line.trim();

      if (!trimmed) {
        i++;
        continue;
      }

      // Fenced code block
      if (trimmed.startsWith("```")) {
        const codeLines = [];
        i++;
        while (i < lines.length && !lines[i].trim().startsWith("```")) {
          codeLines.push(lines[i]);
          i++;
        }
        i++; // skip closing fence
        const pre = document.createElement("pre");
        const code = document.createElement("code");
        code.textContent = codeLines.join("\n");
        pre.appendChild(code);
        frag.appendChild(pre);
        continue;
      }

      // Horizontal rule
      if (/^([-*_])\1{2,}$/.test(trimmed)) {
        frag.appendChild(document.createElement("hr"));
        i++;
        continue;
      }

      // Headings (# through ######)
      const headingMatch = trimmed.match(/^(#{1,6})\s+(.+)$/);
      if (headingMatch) {
        const level = headingMatch[1].length;
        const h = document.createElement("h" + level);
        appendInlineNodes(h, headingMatch[2]);
        frag.appendChild(h);
        i++;
        continue;
      }

      // Blockquote
      if (trimmed.startsWith(">")) {
        const bqLines = [];
        while (i < lines.length && lines[i].trim().startsWith(">")) {
          bqLines.push(lines[i].trim().replace(/^>\s?/, ""));
          i++;
        }
        const bq = document.createElement("blockquote");
        appendInlineNodes(bq, bqLines.join(" "));
        frag.appendChild(bq);
        continue;
      }

      // Pipe Table
      if (
        trimmed.indexOf("|") !== -1 &&
        i + 1 < lines.length &&
        isTableSeparator(lines[i + 1])
      ) {
        const table = document.createElement("table");
        const thead = document.createElement("thead");
        const headTr = document.createElement("tr");
        parseTableRow(lines[i]).forEach(function (cell) {
          const th = document.createElement("th");
          appendInlineNodes(th, cell);
          headTr.appendChild(th);
        });
        thead.appendChild(headTr);
        table.appendChild(thead);

        i += 2; // skip header & separator
        const tbody = document.createElement("tbody");
        while (i < lines.length && lines[i].trim().indexOf("|") !== -1) {
          const tr = document.createElement("tr");
          parseTableRow(lines[i]).forEach(function (cell) {
            const td = document.createElement("td");
            appendInlineNodes(td, cell);
            tr.appendChild(td);
          });
          tbody.appendChild(tr);
          i++;
        }
        table.appendChild(tbody);
        frag.appendChild(table);
        continue;
      }

      // Unordered list
      if (/^[-*+]\s+/.test(trimmed)) {
        const ul = document.createElement("ul");
        while (i < lines.length && /^[-*+]\s+/.test(lines[i].trim())) {
          const li = document.createElement("li");
          appendInlineNodes(li, lines[i].trim().replace(/^[-*+]\s+/, ""));
          ul.appendChild(li);
          i++;
        }
        frag.appendChild(ul);
        continue;
      }

      // Ordered list
      if (/^\d+\.\s+/.test(trimmed)) {
        const ol = document.createElement("ol");
        while (i < lines.length && /^\d+\.\s+/.test(lines[i].trim())) {
          const li = document.createElement("li");
          appendInlineNodes(li, lines[i].trim().replace(/^\d+\.\s+/, ""));
          ol.appendChild(li);
          i++;
        }
        frag.appendChild(ol);
        continue;
      }

      // Paragraph
      const pLines = [];
      while (
        i < lines.length &&
        lines[i].trim() !== "" &&
        !lines[i].trim().startsWith("```") &&
        !/^(#{1,6})\s+/.test(lines[i].trim()) &&
        !/^[-*+]\s+/.test(lines[i].trim()) &&
        !/^\d+\.\s+/.test(lines[i].trim()) &&
        !lines[i].trim().startsWith(">")
      ) {
        pLines.push(lines[i].trim());
        i++;
      }
      const p = document.createElement("p");
      appendInlineNodes(p, pLines.join(" "));
      frag.appendChild(p);
    }

    return frag;
  }

  IdeaPrism.Contracts.MarkdownSanitizer.renderSafeMarkdown = renderSafeMarkdown;

  if (typeof module !== "undefined" && module.exports) {
    module.exports = IdeaPrism.Contracts.MarkdownSanitizer;
  }
})(typeof window !== "undefined" ? window : globalThis);

4. js/app-shell.js

/**
 * IdeaPrism — Phase 2: Application Shell Controller
 * Manages header controls (in-memory API key, model presets/discovery),
 * problem statement, method selector, and batch execution orchestration.
 */
(function (globalScope) {
  "use strict";

  const IdeaPrism = globalScope.IdeaPrism;
  if (!IdeaPrism) {
    throw new Error("IdeaPrism contracts must be loaded before app-shell.js");
  }

  let activeCategory = "All";

  function el(id) {
    return document.getElementById(id);
  }

  function showAlert(message) {
    const box = el("global-alert");
    if (!box) return;
    if (!message) {
      box.classList.add("hidden");
      box.textContent = "";
      return;
    }
    box.textContent = message;
    box.classList.remove("hidden");
  }

  function getActiveModelConfig() {
    const customId = el("custom-model-input").value.trim();
    const selectedId = el("model-select").value;
    return IdeaPrism.Factories.createModelConfig({
      modelId: customId || selectedId
    });
  }

  function populateModelSelect(models) {
    const select = el("model-select");
    const currentVal = select.value;
    select.textContent = "";

    models.forEach(function (m) {
      const opt = document.createElement("option");
      opt.value = m.id;
      opt.textContent = m.label || m.displayName || m.id;
      select.appendChild(opt);
    });

    if (currentVal && models.some(function (m) { return m.id === currentVal; })) {
      select.value = currentVal;
    }
  }

  function renderPresetButtons() {
    const bar = el("method-presets");
    bar.textContent = "";
    const groups = IdeaPrism.Catalog.METHOD_PRESET_GROUPS;

    Object.keys(groups).forEach(function (key) {
      const btn = document.createElement("button");
      btn.type = "button";
      btn.className = "btn btn-ghost";
      btn.textContent = groups[key].label;
      btn.addEventListener("click", function () {
        IdeaPrism.SessionStore.updateSessionMeta({
          selectedMethodIds: groups[key].methodIds
        });
      });
      bar.appendChild(btn);
    });

    const clearBtn = document.createElement("button");
    clearBtn.type = "button";
    clearBtn.className = "btn btn-ghost";
    clearBtn.textContent = "Clear";
    clearBtn.addEventListener("click", function () {
      IdeaPrism.SessionStore.updateSessionMeta({ selectedMethodIds: [] });
    });
    bar.appendChild(clearBtn);
  }

  function renderCategoryFilters() {
    const bar = el("category-filters");
    bar.textContent = "";
    const categories = ["All"].concat(Object.values(IdeaPrism.METHOD_CATEGORIES));

    categories.forEach(function (cat) {
      const btn = document.createElement("button");
      btn.type = "button";
      btn.className = "pill-btn" + (activeCategory === cat ? " active" : "");
      btn.textContent = cat;
      btn.addEventListener("click", function () {
        activeCategory = cat;
        renderCategoryFilters();
        renderMethodSelector(IdeaPrism.SessionStore.getSession());
      });
      bar.appendChild(btn);
    });
  }

  function renderMethodSelector(session) {
    const grid = el("method-selector-grid");
    grid.textContent = "";
    const allMethods = IdeaPrism.Contracts.MethodRegistry.getAll();
    const selectedSet = new Set(session.selectedMethodIds);

    allMethods
      .filter(function (m) {
        return activeCategory === "All" || m.category === activeCategory;
      })
      .forEach(function (method) {
        const isChecked = selectedSet.has(method.id);
        const label = document.createElement("label");
        label.className = "method-option" + (isChecked ? " selected" : "");

        const checkbox = document.createElement("input");
        checkbox.type = "checkbox";
        checkbox.checked = isChecked;
        checkbox.addEventListener("change", function () {
          const next = new Set(IdeaPrism.SessionStore.getSession().selectedMethodIds);
          if (checkbox.checked) next.add(method.id);
          else next.delete(method.id);
          IdeaPrism.SessionStore.updateSessionMeta({
            selectedMethodIds: Array.from(next)
          });
        });

        const body = document.createElement("div");
        const title = document.createElement("div");
        title.className = "method-option-title";
        title.textContent = method.name;

        const cat = document.createElement("div");
        cat.className = "method-option-cat";
        cat.textContent = method.category;

        const desc = document.createElement("div");
        desc.className = "method-option-desc";
        desc.textContent = method.summary;

        body.appendChild(title);
        body.appendChild(cat);
        body.appendChild(desc);

        label.appendChild(checkbox);
        label.appendChild(body);
        grid.appendChild(label);
      });
  }

  /**
   * Executes a single MethodCard turn via ExecutionQueue & GeminiClient.
   * Reused by Phase 3 for Retry, Regenerate, and Follow-Up turns.
   */
  function enqueueCardTurn(cardId, systemPrompt) {
    const store = IdeaPrism.SessionStore;
    const card = store.findCard(cardId);
    if (!card) return;

    store.transitionCard(cardId, IdeaPrism.CARD_STATUS.QUEUED, { error: null });

    IdeaPrism.Contracts.ExecutionQueue.enqueue(cardId, async function (signal) {
      store.transitionCard(cardId, IdeaPrism.CARD_STATUS.LOADING, { error: null });
      const currentSession = store.getSession();
      const latestCard = store.findCard(cardId);

      try {
        const res = await IdeaPrism.Contracts.GeminiClient.generate({
          modelConfig: getActiveModelConfig(),
          systemPrompt: systemPrompt,
          messages: latestCard.messages,
          signal: signal
        });

        const replyMsg = IdeaPrism.Factories.createChatMessage({
          role: "model",
          text: res.text
        });
        const nextMessages = latestCard.messages.concat([replyMsg]);

        store.transitionCard(cardId, IdeaPrism.CARD_STATUS.COMPLETE, {
          messages: nextMessages,
          tokenUsage: res.tokenUsage,
          error: null
        });
      } catch (err) {
        if (err && err.name === "AbortError") {
          store.transitionCard(cardId, IdeaPrism.CARD_STATUS.CANCELLED, {
            error: "Request cancelled."
          });
        } else {
          store.transitionCard(cardId, IdeaPrism.CARD_STATUS.ERROR, {
            error: err && err.message ? err.message : "Unknown Gemini API error."
          });
        }
      }
    });
  }

  function runSelectedMethods() {
    showAlert(null);
    if (!IdeaPrism.RuntimeAuth.hasApiKey()) {
      showAlert("Please enter your Gemini API key in the header bar first.");
      el("api-key-input").focus();
      return;
    }

    const problem = el("problem-input").value.trim();
    const constraints = el("constraints-input").value.trim();
    if (!problem) {
      showAlert("Please enter a problem statement before running methods.");
      el("problem-input").focus();
      return;
    }

    const store = IdeaPrism.SessionStore;
    store.updateSessionMeta({
      problemStatement: problem,
      constraintsContext: constraints,
      modelConfig: getActiveModelConfig()
    });

    const session = store.getSession();
    if (session.selectedMethodIds.length === 0) {
      showAlert("Select at least one innovative thinking method.");
      return;
    }

    session.selectedMethodIds.forEach(function (methodId) {
      const method = IdeaPrism.Contracts.MethodRegistry.getById(methodId);
      if (!method) return;

      const compiledPrompt = IdeaPrism.Catalog.compileMethodPrompt(
        method,
        problem,
        constraints
      );
      const initialMsg = IdeaPrism.Factories.createChatMessage({
        role: "user",
        text: compiledPrompt,
        isInitialPrompt: true
      });
      const card = IdeaPrism.Factories.createMethodCard(method.id, {
        messages: [initialMsg]
      });

      store.upsertMethodCard(card);
      enqueueCardTurn(card.id, method.systemPrompt);
    });
  }

  // Fallback card preview when Phase 3 (card-renderer.js) is not yet loaded
  function renderFallbackCards(session) {
    if (IdeaPrism.CardRenderer) return;
    const grid = el("cards-grid");
    const countEl = el("cards-count");
    countEl.textContent = session.cards.length + " card(s)";

    if (session.cards.length === 0) {
      grid.textContent = "";
      const p = document.createElement("p");
      p.className = "empty-state";
      p.textContent = "Select one or more thinking methods above and click Run Selected Methods.";
      grid.appendChild(p);
      return;
    }

    grid.textContent = "";
    session.cards.forEach(function (card) {
      const method = IdeaPrism.Contracts.MethodRegistry.getById(card.methodId);
      const article = document.createElement("article");
      article.className = "result-card";

      const header = document.createElement("div");
      header.className = "panel-header";
      const h3 = document.createElement("h3");
      h3.style.margin = "0";
      h3.textContent = method ? method.name : card.methodId;

      const badge = document.createElement("span");
      badge.className = "status-badge status-" + card.status;
      badge.textContent = card.status;

      header.appendChild(h3);
      header.appendChild(badge);
      article.appendChild(header);

      const body = document.createElement("div");
      body.className = "md-body";
      const modelReplies = card.messages.filter(function (m) { return m.role === "model"; });
      if (card.error) {
        body.textContent = card.error;
      } else if (modelReplies.length > 0) {
        body.appendChild(
          IdeaPrism.Contracts.MarkdownSanitizer.renderSafeMarkdown(
            modelReplies[modelReplies.length - 1].text
          )
        );
      } else {
        body.textContent = card.status === "loading" ? "Thinking..." : "Waiting in queue...";
      }
      article.appendChild(body);
      grid.appendChild(article);
    });
  }

  function init() {
    populateModelSelect(IdeaPrism.DEFAULT_MODEL_PRESETS);
    renderPresetButtons();
    renderCategoryFilters();

    // API Key controls (strictly in-memory)
    const keyInput = el("api-key-input");
    keyInput.addEventListener("input", function () {
      IdeaPrism.RuntimeAuth.setApiKey(keyInput.value);
      showAlert(null);
    });

    el("toggle-key-btn").addEventListener("click", function () {
      const isPwd = keyInput.type === "password";
      keyInput.type = isPwd ? "text" : "password";
      el("toggle-key-btn").textContent = isPwd ? "Hide" : "Show";
    });

    el("clear-key-btn").addEventListener("click", function () {
      keyInput.value = "";
      IdeaPrism.RuntimeAuth.clearApiKey();
    });

    // Live Model Discovery
    el("refresh-models-btn").addEventListener("click", async function () {
      showAlert(null);
      if (!IdeaPrism.RuntimeAuth.hasApiKey()) {
        showAlert("Enter your Gemini API key first to discover available models.");
        return;
      }
      const btn = el("refresh-models-btn");
      btn.disabled = true;
      btn.textContent = "Loading...";
      try {
        const discovered = await IdeaPrism.Contracts.GeminiClient.listModels();
        if (discovered.length > 0) {
          populateModelSelect(discovered);
        } else {
          showAlert("No generateContent-capable models were returned for this key.");
        }
      } catch (err) {
        showAlert(err.message || "Failed to fetch models from Gemini API.");
      } finally {
        btn.disabled = false;
        btn.textContent = "Refresh";
      }
    });

    // Session & Run controls
    el("run-methods-btn").addEventListener("click", runSelectedMethods);

    el("cancel-all-btn").addEventListener("click", function () {
      IdeaPrism.Contracts.ExecutionQueue.cancelAll();
    });

    el("new-session-btn").addEventListener("click", function () {
      const s = IdeaPrism.SessionStore.newSession({
        selectedMethodIds: IdeaPrism.Catalog.METHOD_PRESET_GROUPS["quick-3"].methodIds
      });
      el("problem-input").value = s.problemStatement;
      el("constraints-input").value = s.constraintsContext;
      showAlert(null);
    });

    // Queue status subscription
    IdeaPrism.Contracts.ExecutionQueue.subscribe(function (stats) {
      const statusEl = el("queue-status");
      const cancelBtn = el("cancel-all-btn");
      if (stats.running > 0 || stats.queued > 0) {
        statusEl.textContent =
          "Running " + stats.running + " · Queued " + stats.queued;
        cancelBtn.classList.remove("hidden");
      } else {
        statusEl.textContent = "Idle";
        cancelBtn.classList.add("hidden");
      }
    });

    // Session store subscription
    IdeaPrism.SessionStore.subscribe(function (session, storageError) {
      if (storageError === "QUOTA_EXCEEDED") {
        showAlert("Browser storage is full. Export or delete older sessions to save new changes.");
      }
      renderMethodSelector(session);
      renderFallbackCards(session);
    });

    // Initial render
    const initial = IdeaPrism.SessionStore.getSession();
    renderMethodSelector(initial);
    renderFallbackCards(initial);
  }

  IdeaPrism.AppShell = Object.freeze({
    enqueueCardTurn: enqueueCardTurn,
    getActiveModelConfig: getActiveModelConfig,
    showAlert: showAlert
  });

  if (typeof document !== "undefined") {
    document.addEventListener("DOMContentLoaded", init);
  }
})(typeof window !== "undefined" ? window : globalThis);

Phase 2 Verification Checklist

  1. Open index.html directly via file:// in your browser and confirm zero console/CORS errors.

  2. Verify XSS safety in the browser console:

    const frag = IdeaPrism.Contracts.MarkdownSanitizer.renderSafeMarkdown(
      '<script>alert("xss")</script> [click](javascript:alert(1)) <img src=x onerror=alert(1)> **safe**'
    );
    

    Confirm zero alerts fire and <script> / javascript: render as inert text.

  3. Enter a key, refresh the page, and confirm IdeaPrism.RuntimeAuth.hasApiKey() returns false.

  4. (Optional) Enter a live Gemini API key, click Refresh to test model discovery, or run Quick 3 on a sample problem to see the Phase 2 fallback cards populate.


Phase 2 passed. Generate Phase 3 (interactive cards & follow-ups) and Phase 4 (cross-card synthesis) now.

Phase 3 and Phase 4 build directly on js/contracts.js, js/session-store.js, and js/app-shell.js with zero modifications to Phase 0–1 modules.

1. js/followup-controller.js (Phase 3)

/**
 * IdeaPrism — Phase 3: Per-Card Follow-Up, Retry, Cancel & Regenerate Controller
 * Works identically for both MethodCard and SynthesisCard via the shared Phase 0 schema.
 */
(function (globalScope) {
  "use strict";

  const IdeaPrism = globalScope.IdeaPrism;
  if (!IdeaPrism) {
    throw new Error("IdeaPrism contracts must be loaded before followup-controller.js");
  }

  const SYNTHESIS_SYSTEM_PROMPT =
    "You are an executive innovation synthesizer. Integrate multiple analytical perspectives into a single coherent, actionable strategy. Resolve tensions explicitly rather than listing disconnected bullets.";

  function resolveSystemPrompt(card) {
    if (card.kind === "synthesis") {
      return SYNTHESIS_SYSTEM_PROMPT;
    }
    const method = IdeaPrism.Contracts.MethodRegistry.getById(card.methodId);
    return method ? method.systemPrompt : "";
  }

  function ensureApiKey() {
    if (!IdeaPrism.RuntimeAuth.hasApiKey()) {
      IdeaPrism.AppShell.showAlert("Enter your Gemini API key in the header bar first.");
      const input = document.getElementById("api-key-input");
      if (input) input.focus();
      return false;
    }
    IdeaPrism.AppShell.showAlert(null);
    return true;
  }

  function submitFollowUp(cardId, promptText, presetId) {
    if (!ensureApiKey()) return;
    const text = String(promptText || "").trim();
    if (!text) return;

    const store = IdeaPrism.SessionStore;
    const card = store.findCard(cardId);
    if (!card) return;

    const followUpMsg = IdeaPrism.Factories.createChatMessage({
      role: "user",
      text: text,
      presetId: presetId || null,
      isInitialPrompt: false
    });

    // Preserve strict alternating user/model roles if previous turn ended on an unanswered user message
    const baseMessages = card.messages.slice();
    if (baseMessages.length > 0 && baseMessages[baseMessages.length - 1].role === "user") {
      baseMessages[baseMessages.length - 1] = followUpMsg;
    } else {
      baseMessages.push(followUpMsg);
    }

    card.messages = baseMessages;
    IdeaPrism.AppShell.enqueueCardTurn(cardId, resolveSystemPrompt(card));
  }

  function retryCard(cardId) {
    if (!ensureApiKey()) return;
    const card = IdeaPrism.SessionStore.findCard(cardId);
    if (!card || card.messages.length === 0) return;

    IdeaPrism.AppShell.enqueueCardTurn(cardId, resolveSystemPrompt(card));
  }

  function regenerateCard(cardId) {
    if (!ensureApiKey()) return;
    const card = IdeaPrism.SessionStore.findCard(cardId);
    if (!card || card.messages.length === 0) return;

    // Reset thread to turn 0 (the initial compiled prompt) and re-run in place
    card.messages = [card.messages[0]];
    card.tokenUsage = null;
    IdeaPrism.AppShell.enqueueCardTurn(cardId, resolveSystemPrompt(card));
  }

  function cancelCard(cardId) {
    const store = IdeaPrism.SessionStore;
    const card = store.findCard(cardId);
    if (!card) return;

    IdeaPrism.Contracts.ExecutionQueue.cancel(cardId);

    // If the task was still queued (never entered runner), transition explicitly
    if (card.status === IdeaPrism.CARD_STATUS.QUEUED) {
      store.transitionCard(cardId, IdeaPrism.CARD_STATUS.CANCELLED, {
        error: "Request cancelled."
      });
    }
  }

  IdeaPrism.FollowUpController = Object.freeze({
    resolveSystemPrompt: resolveSystemPrompt,
    submitFollowUp: submitFollowUp,
    retryCard: retryCard,
    regenerateCard: regenerateCard,
    cancelCard: cancelCard
  });
})(typeof window !== "undefined" ? window : globalThis);

2. js/card-renderer.js (Phase 3)

/**
 * IdeaPrism — Phase 3: Interactive Card Renderer
 * Replaces Phase 2 fallback cards and provides a reusable buildCardElement()
 * shared by Phase 4 SynthesisCard rendering.
 */
(function (globalScope) {
  "use strict";

  const IdeaPrism = globalScope.IdeaPrism;
  if (!IdeaPrism) {
    throw new Error("IdeaPrism contracts must be loaded before card-renderer.js");
  }

  function el(id) {
    return document.getElementById(id);
  }

  function buildPromptDrawer(card) {
    const details = document.createElement("details");
    details.className = "prompt-drawer";

    const summary = document.createElement("summary");
    summary.textContent = "View Prompt";
    details.appendChild(summary);

    const sysPrompt = IdeaPrism.FollowUpController.resolveSystemPrompt(card);
    const initialUser = card.messages.length > 0 ? card.messages[0].text : "";

    const pre = document.createElement("pre");
    pre.className = "prompt-preview";
    pre.textContent =
      "[SYSTEM]\n" + sysPrompt + "\n\n[INITIAL USER PROMPT]\n" + initialUser;
    details.appendChild(pre);

    return details;
  }

  function buildThread(card) {
    const container = document.createElement("div");
    container.className = "card-thread";

    const visibleTurns = card.messages.filter(function (m) {
      return !m.isInitialPrompt;
    });

    if (visibleTurns.length === 0) {
      const placeholder = document.createElement("p");
      placeholder.className = "muted-text";
      if (card.status === IdeaPrism.CARD_STATUS.LOADING) {
        placeholder.textContent = "Thinking...";
      } else if (card.status === IdeaPrism.CARD_STATUS.QUEUED) {
        placeholder.textContent = "Waiting in queue...";
      } else if (card.status === IdeaPrism.CARD_STATUS.CANCELLED) {
        placeholder.textContent = "Cancelled before completion.";
      } else if (card.status === IdeaPrism.CARD_STATUS.ERROR) {
        placeholder.textContent = "";
      } else {
        placeholder.textContent = "Ready.";
      }
      if (placeholder.textContent) container.appendChild(placeholder);
    } else {
      visibleTurns.forEach(function (msg) {
        const turnEl = document.createElement("div");
        turnEl.className = "thread-turn thread-turn-" + msg.role;

        if (msg.role === "user") {
          const label = document.createElement("div");
          label.className = "turn-label";
          label.textContent = msg.presetId ? "Follow-up · " + msg.presetId : "Follow-up";
          const text = document.createElement("div");
          text.textContent = msg.text;
          turnEl.appendChild(label);
          turnEl.appendChild(text);
        } else {
          const md = document.createElement("div");
          md.className = "md-body";
          md.appendChild(IdeaPrism.Contracts.MarkdownSanitizer.renderSafeMarkdown(msg.text));
          turnEl.appendChild(md);
        }
        container.appendChild(turnEl);
      });
    }

    if (card.error) {
      const errBox = document.createElement("div");
      errBox.className = "card-error";
      errBox.textContent = card.error;
      container.appendChild(errBox);
    }

    return container;
  }

  function buildFollowUpArea(card) {
    const isBusy =
      card.status === IdeaPrism.CARD_STATUS.QUEUED ||
      card.status === IdeaPrism.CARD_STATUS.LOADING;
    const hasModelReply = card.messages.some(function (m) {
      return m.role === "model";
    });

    if (!hasModelReply) return null;

    const wrap = document.createElement("div");
    wrap.className = "followup-area";

    // Preset chips
    const chipsRow = document.createElement("div");
    chipsRow.className = "chip-row";
    IdeaPrism.Catalog.FOLLOWUP_PRESETS.forEach(function (preset) {
      const chip = document.createElement("button");
      chip.type = "button";
      chip.className = "chip-btn";
      chip.textContent = preset.label;
      chip.disabled = isBusy;
      chip.addEventListener("click", function () {
        IdeaPrism.FollowUpController.submitFollowUp(
          card.id,
          preset.promptTemplate,
          preset.id
        );
      });
      chipsRow.appendChild(chip);
    });
    wrap.appendChild(chipsRow);

    // Free-text follow-up form
    const form = document.createElement("form");
    form.className = "followup-form";
    const input = document.createElement("input");
    input.type = "text";
    input.placeholder = "Ask a follow-up question on this card...";
    input.disabled = isBusy;

    const sendBtn = document.createElement("button");
    sendBtn.type = "submit";
    sendBtn.className = "btn btn-secondary";
    sendBtn.textContent = isBusy ? "..." : "Send";
    sendBtn.disabled = isBusy;

    form.addEventListener("submit", function (e) {
      e.preventDefault();
      const val = input.value.trim();
      if (!val || isBusy) return;
      input.value = "";
      IdeaPrism.FollowUpController.submitFollowUp(card.id, val, null);
    });

    form.appendChild(input);
    form.appendChild(sendBtn);
    wrap.appendChild(form);

    return wrap;
  }

  function buildCardElement(card) {
    const isMethod = card.kind === "method";
    const method = isMethod
      ? IdeaPrism.Contracts.MethodRegistry.getById(card.methodId)
      : null;

    const article = document.createElement("article");
    article.className =
      "result-card" +
      (card.starred ? " card-starred" : "") +
      (card.kind === "synthesis" ? " card-synthesis" : "");
    article.dataset.cardId = card.id;

    // Header
    const header = document.createElement("div");
    header.className = "card-header";

    const titleGroup = document.createElement("div");
    const h3 = document.createElement("h3");
    h3.className = "card-title";
    h3.textContent = isMethod ? (method ? method.name : card.methodId) : card.title;

    const meta = document.createElement("div");
    meta.className = "card-meta";
    meta.textContent = isMethod
      ? (method ? method.category : "Method")
      : "Synthesized from " + card.sourceCardIds.length + " cards";

    titleGroup.appendChild(h3);
    titleGroup.appendChild(meta);

    const badge = document.createElement("span");
    badge.className = "status-badge status-" + card.status;
    badge.textContent = card.status;

    header.appendChild(titleGroup);
    header.appendChild(badge);
    article.appendChild(header);

    // Toolbar
    const toolbar = document.createElement("div");
    toolbar.className = "card-toolbar";

    const starBtn = document.createElement("button");
    starBtn.type = "button";
    starBtn.className = "btn btn-ghost btn-sm";
    starBtn.textContent = card.starred ? "★ Starred" : "☆ Star";
    starBtn.addEventListener("click", function () {
      IdeaPrism.SessionStore.toggleCardFlag(card.id, "starred");
    });
    toolbar.appendChild(starBtn);

    // Synthesis checkbox for completed MethodCards
    if (isMethod && card.status === IdeaPrism.CARD_STATUS.COMPLETE) {
      const synthLabel = document.createElement("label");
      synthLabel.className = "synth-check-label";
      const cb = document.createElement("input");
      cb.type = "checkbox";
      cb.checked = Boolean(card.selectedForSynthesis);
      cb.addEventListener("change", function () {
        IdeaPrism.SessionStore.toggleCardFlag(card.id, "selectedForSynthesis");
      });
      synthLabel.appendChild(cb);
      synthLabel.appendChild(document.createTextNode(" Select for Synthesis"));
      toolbar.appendChild(synthLabel);
    }

    const isBusy =
      card.status === IdeaPrism.CARD_STATUS.QUEUED ||
      card.status === IdeaPrism.CARD_STATUS.LOADING;

    if (isBusy) {
      const cancelBtn = document.createElement("button");
      cancelBtn.type = "button";
      cancelBtn.className = "btn btn-danger btn-sm";
      cancelBtn.textContent = "Cancel";
      cancelBtn.addEventListener("click", function () {
        IdeaPrism.FollowUpController.cancelCard(card.id);
      });
      toolbar.appendChild(cancelBtn);
    } else {
      if (
        card.status === IdeaPrism.CARD_STATUS.ERROR ||
        card.status === IdeaPrism.CARD_STATUS.CANCELLED
      ) {
        const retryBtn = document.createElement("button");
        retryBtn.type = "button";
        retryBtn.className = "btn btn-secondary btn-sm";
        retryBtn.textContent = "Retry";
        retryBtn.addEventListener("click", function () {
          IdeaPrism.FollowUpController.retryCard(card.id);
        });
        toolbar.appendChild(retryBtn);
      }

      const regenBtn = document.createElement("button");
      regenBtn.type = "button";
      regenBtn.className = "btn btn-ghost btn-sm";
      regenBtn.textContent = "Regenerate";
      regenBtn.addEventListener("click", function () {
        IdeaPrism.FollowUpController.regenerateCard(card.id);
      });
      toolbar.appendChild(regenBtn);
    }

    article.appendChild(toolbar);
    article.appendChild(buildPromptDrawer(card));
    article.appendChild(buildThread(card));

    const followUpArea = buildFollowUpArea(card);
    if (followUpArea) {
      article.appendChild(followUpArea);
    }

    if (card.tokenUsage) {
      const footer = document.createElement("div");
      footer.className = "card-footer muted-text";
      footer.textContent =
        "Tokens — Prompt: " +
        card.tokenUsage.promptTokens +
        " · Output: " +
        card.tokenUsage.candidateTokens +
        " · Total: " +
        card.tokenUsage.totalTokens;
      article.appendChild(footer);
    }

    return article;
  }

  function renderMethodCards(session) {
    const grid = el("cards-grid");
    const countEl = el("cards-count");
    if (!grid || !countEl) return;

    countEl.textContent = session.cards.length + " card(s)";
    grid.textContent = "";

    if (session.cards.length === 0) {
      const p = document.createElement("p");
      p.className = "empty-state";
      p.textContent =
        "Select one or more thinking methods above and click Run Selected Methods.";
      grid.appendChild(p);
      return;
    }

    session.cards.forEach(function (card) {
      grid.appendChild(buildCardElement(card));
    });
  }

  IdeaPrism.CardRenderer = Object.freeze({
    buildCardElement: buildCardElement,
    renderMethodCards: renderMethodCards
  });

  if (typeof document !== "undefined") {
    document.addEventListener("DOMContentLoaded", function () {
      IdeaPrism.SessionStore.subscribe(function (session) {
        renderMethodCards(session);
      });
      renderMethodCards(IdeaPrism.SessionStore.getSession());
    });
  }
})(typeof window !== "undefined" ? window : globalThis);

3. js/synthesis-controller.js (Phase 4)

/**
 * IdeaPrism — Phase 4: Cross-Card Synthesis Workflow
 * Tracks completed MethodCards checked for synthesis, compiles a SynthesisCard,
 * and renders it using Phase 3's CardRenderer for full follow-up parity.
 */
(function (globalScope) {
  "use strict";

  const IdeaPrism = globalScope.IdeaPrism;
  if (!IdeaPrism) {
    throw new Error("IdeaPrism contracts must be loaded before synthesis-controller.js");
  }

  function el(id) {
    return document.getElementById(id);
  }

  function getSelectedCompletedCards(session) {
    return session.cards.filter(function (c) {
      return (
        c.status === IdeaPrism.CARD_STATUS.COMPLETE &&
        Boolean(c.selectedForSynthesis)
      );
    });
  }

  function runSynthesis() {
    if (!IdeaPrism.RuntimeAuth.hasApiKey()) {
      IdeaPrism.AppShell.showAlert("Enter your Gemini API key in the header bar first.");
      return;
    }

    const store = IdeaPrism.SessionStore;
    const session = store.getSession();
    const selectedCards = getSelectedCompletedCards(session);

    if (selectedCards.length < 2) {
      IdeaPrism.AppShell.showAlert("Select at least 2 completed cards to synthesize.");
      return;
    }

    IdeaPrism.AppShell.showAlert(null);

    const summaries = selectedCards.map(function (card) {
      const method = IdeaPrism.Contracts.MethodRegistry.getById(card.methodId);
      const modelReplies = card.messages.filter(function (m) {
        return m.role === "model";
      });
      const latest = modelReplies.length > 0 ? modelReplies[modelReplies.length - 1].text : "";
      return {
        methodName: method ? method.name : card.methodId,
        latestResponse: latest
      };
    });

    const compiled = IdeaPrism.Catalog.compileSynthesisPrompt(
      session.problemStatement,
      session.constraintsContext,
      summaries
    );

    const initialMsg = IdeaPrism.Factories.createChatMessage({
      role: "user",
      text: compiled.userPrompt,
      isInitialPrompt: true
    });

    const sourceIds = selectedCards.map(function (c) { return c.id; });
    const names = summaries.map(function (s) { return s.methodName; });
    const title =
      names.length <= 3
        ? "Synthesis: " + names.join(" + ")
        : "Synthesis of " + names.length + " Methods";

    const synthCard = IdeaPrism.Factories.createSynthesisCard(sourceIds, {
      title: title,
      messages: [initialMsg]
    });

    store.upsertSynthesisCard(synthCard);
    IdeaPrism.AppShell.enqueueCardTurn(synthCard.id, compiled.systemPrompt);
  }

  function renderSynthesisBar(session) {
    const bar = el("synthesis-bar");
    if (!bar) return;

    const selected = getSelectedCompletedCards(session);
    const completedCount = session.cards.filter(function (c) {
      return c.status === IdeaPrism.CARD_STATUS.COMPLETE;
    }).length;

    if (completedCount < 2 && selected.length === 0) {
      bar.classList.add("hidden");
      return;
    }

    bar.classList.remove("hidden");
    bar.textContent = "";

    const info = document.createElement("span");
    info.className = "muted-text";
    info.textContent =
      selected.length < 2
        ? "Check 2 or more completed cards below to synthesize them (" + selected.length + " selected)."
        : selected.length + " cards selected for cross-card synthesis.";

    const actions = document.createElement("div");
    actions.className = "input-row";

    const synthBtn = document.createElement("button");
    synthBtn.type = "button";
    synthBtn.className = "btn btn-primary";
    synthBtn.textContent = "Synthesize Selected Cards (" + selected.length + ")";
    synthBtn.disabled = selected.length < 2;
    synthBtn.addEventListener("click", runSynthesis);

    actions.appendChild(synthBtn);

    if (selected.length > 0) {
      const clearBtn = document.createElement("button");
      clearBtn.type = "button";
      clearBtn.className = "btn btn-ghost";
      clearBtn.textContent = "Clear Selection";
      clearBtn.addEventListener("click", function () {
        selected.forEach(function (c) {
          IdeaPrism.SessionStore.toggleCardFlag(c.id, "selectedForSynthesis");
        });
      });
      actions.appendChild(clearBtn);
    }

    bar.appendChild(info);
    bar.appendChild(actions);
  }

  function renderSynthesisCards(session) {
    const section = el("synthesis-section");
    const grid = el("synthesis-grid");
    if (!section || !grid) return;

    if (session.syntheses.length === 0) {
      section.classList.add("hidden");
      grid.textContent = "";
      return;
    }

    section.classList.remove("hidden");
    grid.textContent = "";

    session.syntheses.forEach(function (synthCard) {
      grid.appendChild(IdeaPrism.CardRenderer.buildCardElement(synthCard));
    });
  }

  IdeaPrism.SynthesisController = Object.freeze({
    runSynthesis: runSynthesis
  });

  if (typeof document !== "undefined") {
    document.addEventListener("DOMContentLoaded", function () {
      IdeaPrism.SessionStore.subscribe(function (session) {
        renderSynthesisBar(session);
        renderSynthesisCards(session);
      });
      const initial = IdeaPrism.SessionStore.getSession();
      renderSynthesisBar(initial);
      renderSynthesisCards(initial);
    });
  }
})(typeof window !== "undefined" ? window : globalThis);

4. Additive Wiring

Append these 3 <script defer> lines inside <head> of index.html right after js/app-shell.js:

  <!-- Phase 3: Interactive Cards & Follow-Ups -->
  <script defer src="js/followup-controller.js"></script>
  <script defer src="js/card-renderer.js"></script>
  <!-- Phase 4: Cross-Card Synthesis -->
  <script defer src="js/synthesis-controller.js"></script>

Append these Phase 3 & 4 styles to the bottom of css/styles.css:

/* Phase 3 & 4: Card Controls, Follow-Ups & Synthesis Bar */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 0.75rem;
}

.card-title {
  margin: 0;
  font-size: 1rem;
}

.card-meta {
  font-size: 0.76rem;
  color: var(--accent);
}

.card-starred {
  border-color: var(--warning);
}

.card-synthesis {
  border-color: var(--accent);
  background: linear-gradient(180deg, rgba(56, 189, 248, 0.08), var(--surface) 90px);
}

.card-toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 0.45rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid var(--border);
}

.btn-sm {
  padding: 0.25rem 0.55rem;
  font-size: 0.76rem;
}

.synth-check-label {
  display: inline-flex;
  align-items: center;
  gap: 0.35rem;
  font-size: 0.78rem;
  color: var(--text-muted);
  cursor: pointer;
  margin-right: auto;
}

.prompt-drawer summary {
  cursor: pointer;
  font-size: 0.78rem;
  color: var(--text-muted);
}

.prompt-preview {
  margin: 0.5rem 0 0;
  padding: 0.65rem;
  background: var(--bg);
  border: 1px solid var(--border);
  border-radius: 6px;
  font-size: 0.76rem;
  white-space: pre-wrap;
  max-height: 220px;
  overflow-y: auto;
}

.card-thread {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.thread-turn-user {
  background: var(--surface-alt);
  border-left: 3px solid var(--accent);
  padding: 0.5rem 0.7rem;
  border-radius: 6px;
  font-size: 0.86rem;
}

.turn-label {
  font-size: 0.72rem;
  font-weight: 700;
  color: var(--accent);
  text-transform: uppercase;
  margin-bottom: 0.2rem;
}

.card-error {
  padding: 0.6rem 0.75rem;
  border-radius: 6px;
  background: rgba(239, 68, 68, 0.14);
  border: 1px solid var(--danger);
  color: #fecaca;
  font-size: 0.84rem;
}

.followup-area {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  padding-top: 0.65rem;
  border-top: 1px solid var(--border);
}

.chip-row {
  display: flex;
  flex-wrap: wrap;
  gap: 0.35rem;
}

.chip-btn {
  background: var(--bg);
  color: var(--text);
  border: 1px solid var(--border);
  border-radius: 999px;
  padding: 0.22rem 0.65rem;
  font-size: 0.76rem;
  cursor: pointer;
}

.chip-btn:hover:not(:disabled) {
  border-color: var(--accent);
  color: var(--accent);
}

.followup-form {
  display: flex;
  gap: 0.4rem;
}

.followup-form input {
  flex: 1;
  font-size: 0.85rem;
}

.card-footer {
  font-size: 0.74rem;
  padding-top: 0.35rem;
  border-top: 1px dashed var(--border);
}

.synthesis-bar {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  gap: 0.75rem;
  padding: 0.85rem 1.15rem;
  background: var(--surface-alt);
  border: 1px solid var(--accent);
  border-radius: var(--radius);
}

Phase 3 & 4 Verification Checklist

  1. Open index.html, enter your Gemini API key, run Quick 3 on a sample problem, and expand View Prompt on any card to verify the exact system + user prompt.

  2. Click a preset chip (e.g., Critique) or submit a free-text follow-up on a completed card and confirm the reply appends inside the same card thread.

  3. Click Regenerate on one card and confirm only that card resets and re-runs.

  4. Check Select for Synthesis on 2+ completed cards, click Synthesize Selected Cards, and confirm the resulting SynthesisCard appears in Synthesized Strategies with its own working follow-up chips and free-text input.


Phases 3 and 4 passed. Generate Phase 5 now: js/exporters.js, js/history-drawer.js, and the final index.html and CSS additions.

Phase 5 completes the application with allowlisted Markdown/JSON export, schema-validated JSON import, and the localStorage Session History slide-over drawer—zero modifications to Phase 0–4 modules.

1. js/exporters.js

/**
 * IdeaPrism — Phase 5: Markdown & JSON Exporters + Round-Trip JSON Importer
 * Enforces strict Phase 0 allowlist serialization (zero apiKey leakage).
 */
(function (globalScope) {
  "use strict";

  const IdeaPrism =
    globalScope.IdeaPrism ||
    (typeof require === "function" ? require("./contracts.js") : null);

  if (!IdeaPrism) {
    throw new Error("IdeaPrism Phase 0 contracts must be loaded before exporters.js");
  }

  function slugifyFilename(title) {
    const base = String(title || "ideaprism-session")
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "-")
      .replace(/^-+|-+$/g, "")
      .slice(0, 48);
    return base || "ideaprism-session";
  }

  function formatCardTurnsMarkdown(card) {
    const lines = [];
    const visibleTurns = (card.messages || []).filter(function (m) {
      return !m.isInitialPrompt;
    });

    if (visibleTurns.length === 0) {
      lines.push("*(No completed output yet — status: " + card.status + ")*");
      return lines.join("\n");
    }

    visibleTurns.forEach(function (msg, idx) {
      if (msg.role === "user") {
        const tag = msg.presetId ? "Follow-Up (" + msg.presetId + ")" : "Follow-Up";
        lines.push("\n> **" + tag + ":** " + msg.text.replace(/\n/g, "\n> ") + "\n");
      } else {
        if (idx > 0) lines.push("\n**Response:**\n");
        lines.push(msg.text);
      }
    });

    return lines.join("\n");
  }

  function exportToMarkdown(session) {
    const safe = IdeaPrism.Validation.sanitizeSessionForPersistence(session);
    const out = [];

    out.push("# " + safe.title);
    out.push("");
    out.push("- **Model:** `" + safe.modelConfig.modelId + "`");
    out.push("- **Created:** " + safe.createdAt);
    out.push("- **Updated:** " + safe.updatedAt);
    out.push("");
    out.push("## Problem Statement");
    out.push("");
    out.push(safe.problemStatement || "*(None)*");
    out.push("");

    if (safe.constraintsContext && safe.constraintsContext.trim()) {
      out.push("## Constraints & Context");
      out.push("");
      out.push(safe.constraintsContext.trim());
      out.push("");
    }

    if (safe.syntheses.length > 0) {
      out.push("## Synthesized Strategies");
      out.push("");
      safe.syntheses.forEach(function (synth) {
        const star = synth.starred ? " ★" : "";
        out.push("### " + synth.title + star);
        out.push("");
        out.push(formatCardTurnsMarkdown(synth));
        out.push("");
        out.push("---");
        out.push("");
      });
    }

    out.push("## Thinking Method Cards");
    out.push("");
    if (safe.cards.length === 0) {
      out.push("*(No method cards generated.)*");
    } else {
      safe.cards.forEach(function (card) {
        const method = IdeaPrism.Contracts.MethodRegistry.getById(card.methodId);
        const name = method ? method.name : card.methodId;
        const cat = method ? " (" + method.category + ")" : "";
        const star = card.starred ? " ★" : "";
        out.push("### " + name + cat + star);
        out.push("");
        out.push(formatCardTurnsMarkdown(card));
        out.push("");
        out.push("---");
        out.push("");
      });
    }

    return out.join("\n");
  }

  function exportToJson(session) {
    const safe = IdeaPrism.Validation.sanitizeSessionForPersistence(session);
    return JSON.stringify(safe, null, 2);
  }

  function importSessionFromJson(rawText) {
    let parsed;
    try {
      parsed = JSON.parse(String(rawText || ""));
    } catch (err) {
      return { ok: false, errors: ["Invalid JSON file: " + err.message], session: null };
    }

    const check = IdeaPrism.Validation.validateSession(parsed);
    if (!check.valid) {
      return { ok: false, errors: check.errors, session: null };
    }
    return { ok: true, errors: [], session: check.sanitized };
  }

  function triggerDownload(filename, content, mimeType) {
    const blob = new Blob([content], { type: mimeType });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    setTimeout(function () {
      URL.revokeObjectURL(url);
    }, 500);
  }

  // Register built-in exporters into Phase 0 ExporterRegistry
  IdeaPrism.Contracts.ExporterRegistry.register({
    id: "markdown",
    label: "Export Markdown (.md)",
    extension: ".md",
    mimeType: "text/markdown;charset=utf-8",
    serialize: exportToMarkdown
  });

  IdeaPrism.Contracts.ExporterRegistry.register({
    id: "json",
    label: "Export JSON (.json)",
    extension: ".json",
    mimeType: "application/json;charset=utf-8",
    serialize: exportToJson
  });

  IdeaPrism.Exporters = Object.freeze({
    slugifyFilename: slugifyFilename,
    exportToMarkdown: exportToMarkdown,
    exportToJson: exportToJson,
    importSessionFromJson: importSessionFromJson,
    triggerDownload: triggerDownload
  });

  if (typeof module !== "undefined" && module.exports) {
    module.exports = IdeaPrism.Exporters;
  }
})(typeof window !== "undefined" ? window : globalThis);

2. js/history-drawer.js

/**
 * IdeaPrism — Phase 5: Session History Slide-Over Drawer
 * Manages localStorage session browsing, search, load, rename, delete,
 * Markdown/JSON export, and schema-validated JSON import.
 */
(function (globalScope) {
  "use strict";

  const IdeaPrism = globalScope.IdeaPrism;
  if (!IdeaPrism) {
    throw new Error("IdeaPrism contracts must be loaded before history-drawer.js");
  }

  let isOpen = false;
  let searchQuery = "";
  let drawerMessage = null;
  let drawerMessageIsError = false;

  function el(id) {
    return document.getElementById(id);
  }

  function syncWorkspaceInputsFromSession(session) {
    const problemEl = el("problem-input");
    const constraintsEl = el("constraints-input");
    const selectEl = el("model-select");
    const customEl = el("custom-model-input");

    if (problemEl) problemEl.value = session.problemStatement || "";
    if (constraintsEl) constraintsEl.value = session.constraintsContext || "";

    if (selectEl && customEl && session.modelConfig && session.modelConfig.modelId) {
      const targetId = session.modelConfig.modelId;
      const hasOption = Array.from(selectEl.options).some(function (opt) {
        return opt.value === targetId;
      });
      if (hasOption) {
        selectEl.value = targetId;
        customEl.value = "";
      } else {
        customEl.value = targetId;
      }
    }
  }

  function setDrawerNotice(text, isError) {
    drawerMessage = text;
    drawerMessageIsError = Boolean(isError);
    renderDrawer();
  }

  function openDrawer() {
    isOpen = true;
    drawerMessage = null;
    renderDrawer();
  }

  function closeDrawer() {
    isOpen = false;
    renderDrawer();
  }

  function handleExport(exporterId, session) {
    const exporter = IdeaPrism.Contracts.ExporterRegistry.getById(exporterId);
    if (!exporter) return;
    const content = exporter.serialize(session);
    const filename = IdeaPrism.Exporters.slugifyFilename(session.title) + exporter.extension;
    IdeaPrism.Exporters.triggerDownload(filename, content, exporter.mimeType);
  }

  function handleImportFile(file) {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = function () {
      const res = IdeaPrism.Exporters.importSessionFromJson(reader.result);
      if (!res.ok) {
        setDrawerNotice("Import rejected: " + res.errors.join(" "), true);
        return;
      }

      const saveRes = IdeaPrism.Contracts.StorageAdapter.saveSession(res.session);
      if (!saveRes.ok) {
        setDrawerNotice("Imported session could not be saved (" + saveRes.error + ").", true);
        return;
      }

      IdeaPrism.Contracts.ExecutionQueue.cancelAll();
      IdeaPrism.SessionStore.setSession(res.session);
      syncWorkspaceInputsFromSession(res.session);
      setDrawerNotice("Imported \"" + res.session.title + "\" successfully.", false);
    };
    reader.onerror = function () {
      setDrawerNotice("Could not read the selected file.", true);
    };
    reader.readAsText(file);
  }

  function renderDrawer() {
    const drawer = el("history-drawer");
    if (!drawer) return;

    if (!isOpen) {
      drawer.classList.add("hidden");
      drawer.textContent = "";
      return;
    }

    drawer.classList.remove("hidden");
    drawer.textContent = "";

    const activeSession = IdeaPrism.SessionStore.getSession();
    const allSessions = IdeaPrism.Contracts.StorageAdapter.listSessions();
    const filtered = allSessions.filter(function (s) {
      if (!searchQuery.trim()) return true;
      const q = searchQuery.toLowerCase();
      return (
        s.title.toLowerCase().indexOf(q) !== -1 ||
        s.problemStatement.toLowerCase().indexOf(q) !== -1
      );
    });

    // Backdrop
    const backdrop = document.createElement("div");
    backdrop.className = "drawer-backdrop";
    backdrop.addEventListener("click", closeDrawer);
    drawer.appendChild(backdrop);

    // Panel
    const panel = document.createElement("div");
    panel.className = "drawer-panel";

    // Header
    const header = document.createElement("div");
    header.className = "drawer-header";
    const h2 = document.createElement("h2");
    h2.textContent = "History & Export";
    const closeBtn = document.createElement("button");
    closeBtn.type = "button";
    closeBtn.className = "btn btn-ghost btn-sm";
    closeBtn.textContent = "Close";
    closeBtn.addEventListener("click", closeDrawer);
    header.appendChild(h2);
    header.appendChild(closeBtn);
    panel.appendChild(header);

    // Active Session Export / Import Bar
    const ioSection = document.createElement("div");
    ioSection.className = "drawer-io-bar";

    const exportMdBtn = document.createElement("button");
    exportMdBtn.type = "button";
    exportMdBtn.className = "btn btn-secondary btn-sm";
    exportMdBtn.textContent = "Export Active (.md)";
    exportMdBtn.addEventListener("click", function () {
      handleExport("markdown", activeSession);
    });

    const exportJsonBtn = document.createElement("button");
    exportJsonBtn.type = "button";
    exportJsonBtn.className = "btn btn-secondary btn-sm";
    exportJsonBtn.textContent = "Export Active (.json)";
    exportJsonBtn.addEventListener("click", function () {
      handleExport("json", activeSession);
    });

    const fileInput = document.createElement("input");
    fileInput.type = "file";
    fileInput.accept = ".json,application/json";
    fileInput.className = "hidden";
    fileInput.addEventListener("change", function () {
      if (fileInput.files && fileInput.files[0]) {
        handleImportFile(fileInput.files[0]);
        fileInput.value = "";
      }
    });

    const importBtn = document.createElement("button");
    importBtn.type = "button";
    importBtn.className = "btn btn-primary btn-sm";
    importBtn.textContent = "Import (.json)";
    importBtn.addEventListener("click", function () {
      fileInput.click();
    });

    ioSection.appendChild(exportMdBtn);
    ioSection.appendChild(exportJsonBtn);
    ioSection.appendChild(importBtn);
    ioSection.appendChild(fileInput);
    panel.appendChild(ioSection);

    // Inline Notice
    if (drawerMessage) {
      const notice = document.createElement("div");
      notice.className = drawerMessageIsError ? "card-error" : "drawer-notice";
      notice.textContent = drawerMessage;
      panel.appendChild(notice);
    }

    // Search Input
    const searchInput = document.createElement("input");
    searchInput.type = "text";
    searchInput.className = "drawer-search";
    searchInput.placeholder = "Filter saved sessions...";
    searchInput.value = searchQuery;
    searchInput.addEventListener("input", function () {
      searchQuery = searchInput.value;
      renderDrawer();
    });
    panel.appendChild(searchInput);

    // Session List
    const list = document.createElement("div");
    list.className = "drawer-list";

    if (filtered.length === 0) {
      const empty = document.createElement("p");
      empty.className = "muted-text";
      empty.textContent =
        allSessions.length === 0
          ? "No saved sessions yet. Run a problem statement to save automatically."
          : "No sessions match your filter.";
      list.appendChild(empty);
    } else {
      filtered.forEach(function (session) {
        const isCurrent = session.id === activeSession.id;
        const item = document.createElement("div");
        item.className = "history-item" + (isCurrent ? " history-item-active" : "");

        const titleRow = document.createElement("div");
        titleRow.className = "history-item-title";
        titleRow.textContent = session.title + (isCurrent ? " (Active)" : "");

        const metaRow = document.createElement("div");
        metaRow.className = "history-item-meta";
        metaRow.textContent =
          session.cards.length +
          " cards · " +
          session.syntheses.length +
          " syntheses · " +
          new Date(session.updatedAt).toLocaleString();

        const actions = document.createElement("div");
        actions.className = "history-item-actions";

        const loadBtn = document.createElement("button");
        loadBtn.type = "button";
        loadBtn.className = "btn btn-secondary btn-sm";
        loadBtn.textContent = "Load";
        loadBtn.disabled = isCurrent;
        loadBtn.addEventListener("click", function () {
          IdeaPrism.Contracts.ExecutionQueue.cancelAll();
          IdeaPrism.SessionStore.setSession(session);
          syncWorkspaceInputsFromSession(session);
          closeDrawer();
        });

        const renameBtn = document.createElement("button");
        renameBtn.type = "button";
        renameBtn.className = "btn btn-ghost btn-sm";
        renameBtn.textContent = "Rename";
        renameBtn.addEventListener("click", function () {
          const nextTitle = globalScope.prompt("Rename session:", session.title);
          if (nextTitle && nextTitle.trim()) {
            if (isCurrent) {
              IdeaPrism.SessionStore.updateSessionMeta({ title: nextTitle.trim() });
            } else {
              session.title = nextTitle.trim();
              session.updatedAt = new Date().toISOString();
              IdeaPrism.Contracts.StorageAdapter.saveSession(session);
            }
            renderDrawer();
          }
        });

        const delBtn = document.createElement("button");
        delBtn.type = "button";
        delBtn.className = "btn btn-danger btn-sm";
        delBtn.textContent = "Delete";
        delBtn.addEventListener("click", function () {
          IdeaPrism.Contracts.StorageAdapter.deleteSession(session.id);
          renderDrawer();
        });

        actions.appendChild(loadBtn);
        actions.appendChild(renameBtn);
        actions.appendChild(delBtn);

        item.appendChild(titleRow);
        item.appendChild(metaRow);
        item.appendChild(actions);
        list.appendChild(item);
      });
    }

    panel.appendChild(list);
    drawer.appendChild(panel);
  }

  function init() {
    const openBtn = el("open-history-btn");
    if (openBtn) {
      openBtn.disabled = false;
      openBtn.title = "Open Session History & Export";
      openBtn.addEventListener("click", openDrawer);
    }

    document.addEventListener("keydown", function (e) {
      if (e.key === "Escape" && isOpen) {
        closeDrawer();
      }
    });
  }

  IdeaPrism.HistoryDrawer = Object.freeze({
    open: openDrawer,
    close: closeDrawer
  });

  if (typeof document !== "undefined") {
    document.addEventListener("DOMContentLoaded", init);
  }
})(typeof window !== "undefined" ? window : globalThis);

3. Final Additive Wiring

Append these 2 <script defer> lines inside <head> of index.html right after js/synthesis-controller.js:

  <!-- Phase 5: History Drawer & Import/Export -->
  <script defer src="js/exporters.js"></script>
  <script defer src="js/history-drawer.js"></script>

Append these Phase 5 styles to the bottom of css/styles.css:

/* Phase 5: Session History Slide-Over Drawer */
.history-drawer {
  position: fixed;
  inset: 0;
  z-index: 1000;
  display: flex;
  justify-content: flex-end;
}

.drawer-backdrop {
  position: fixed;
  inset: 0;
  background: rgba(2, 6, 23, 0.65);
}

.drawer-panel {
  position: relative;
  z-index: 1;
  width: min(440px, 100vw);
  height: 100vh;
  background: var(--surface);
  border-left: 1px solid var(--border);
  padding: 1.15rem;
  display: flex;
  flex-direction: column;
  gap: 0.85rem;
  box-shadow: -8px 0 28px rgba(0, 0, 0, 0.45);
}

.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.drawer-header h2 {
  margin: 0;
  font-size: 1.1rem;
}

.drawer-io-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 0.45rem;
}

.drawer-notice {
  padding: 0.55rem 0.75rem;
  border-radius: 6px;
  background: rgba(34, 197, 94, 0.14);
  border: 1px solid var(--success);
  color: #bbf7d0;
  font-size: 0.82rem;
}

.drawer-search {
  width: 100%;
}

.drawer-list {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 0.65rem;
}

.history-item {
  background: var(--bg);
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 0.75rem;
  display: flex;
  flex-direction: column;
  gap: 0.4rem;
}

.history-item-active {
  border-color: var(--accent);
}

.history-item-title {
  font-weight: 600;
  font-size: 0.9rem;
}

.history-item-meta {
  font-size: 0.76rem;
  color: var(--text-muted);
}

.history-item-actions {
  display: flex;
  gap: 0.4rem;
  margin-top: 0.2rem;
}

Phase 5 Verification Checklist

  1. Open index.html and confirm History & Export in the header is now enabled and opens the slide-over drawer.

  2. Run a session, open History & Export, and click Export Active (.json) and Export Active (.md). Inspect both downloaded files to confirm zero apiKey occurrences.

  3. Click Delete on that session in the drawer, then click Import (.json) and select the exported .json file—confirm all cards, follow-ups, and syntheses restore identically.

  4. Try importing a malformed .json file or one with "schemaVersion": "99.0.0" and confirm a clear rejection error appears without affecting existing saved sessions.


Add a clean light/dark theme toggle to IdeaPrism using CSS custom properties.

This additive module adds a light/dark theme toggle using your existing CSS custom properties, respects OS prefers-color-scheme on first load, and stores the user's choice under a separate localStorage key (ideaprism_theme_v1) so ProblemSession schemas stay untouched.

1. js/theme-toggle.js

/**
 * IdeaPrism — Additive Light/Dark Theme Toggle
 * Persists UI theme preference separately from ProblemSession storage.
 */
(function (globalScope) {
  "use strict";

  const THEME_STORAGE_KEY = "ideaprism_theme_v1";

  function getPreferredTheme() {
    try {
      const saved = globalScope.localStorage.getItem(THEME_STORAGE_KEY);
      if (saved === "light" || saved === "dark") return saved;
    } catch (e) {
      // Ignore storage access errors
    }
    if (
      globalScope.matchMedia &&
      globalScope.matchMedia("(prefers-color-scheme: light)").matches
    ) {
      return "light";
    }
    return "dark";
  }

  function applyTheme(theme) {
    const resolved = theme === "light" ? "light" : "dark";
    document.documentElement.setAttribute("data-theme", resolved);

    const btn = document.getElementById("theme-toggle-btn");
    if (btn) {
      const nextLabel = resolved === "dark" ? "☀ Light" : "☾ Dark";
      btn.textContent = nextLabel;
      btn.setAttribute("aria-pressed", String(resolved === "light"));
      btn.title = "Switch to " + (resolved === "dark" ? "light" : "dark") + " theme";
    }
  }

  function toggleTheme() {
    const current = document.documentElement.getAttribute("data-theme") || "dark";
    const next = current === "dark" ? "light" : "dark";
    applyTheme(next);
    try {
      globalScope.localStorage.setItem(THEME_STORAGE_KEY, next);
    } catch (e) {
      // Ignore storage access errors
    }
  }

  // Apply immediately to minimize flash, then bind button on DOMContentLoaded
  applyTheme(getPreferredTheme());

  if (typeof document !== "undefined") {
    document.addEventListener("DOMContentLoaded", function () {
      applyTheme(getPreferredTheme());
      const btn = document.getElementById("theme-toggle-btn");
      if (btn) {
        btn.addEventListener("click", toggleTheme);
      }
    });
  }
})(typeof window !== "undefined" ? window : globalThis);

2. Append to css/styles.css

/* Light Theme Custom Property Overrides */
:root[data-theme="light"] {
  --bg: #f8fafc;
  --surface: #ffffff;
  --surface-alt: #f1f5f9;
  --border: #cbd5e1;
  --text: #0f172a;
  --text-muted: #475569;
  --accent: #0284c7;
  --accent-strong: #0369a1;
  --success: #16a34a;
  --warning: #d97706;
  --danger: #dc2626;
  --shadow: 0 4px 16px rgba(15, 23, 42, 0.08);
}

:root[data-theme="light"] .btn-primary:hover:not(:disabled) {
  color: #ffffff;
}

:root[data-theme="light"] .btn-danger {
  background: rgba(220, 38, 38, 0.1);
  color: #b91c1c;
}

:root[data-theme="light"] .global-alert,
:root[data-theme="light"] .card-error {
  background: rgba(220, 38, 38, 0.08);
  color: #991b1b;
}

:root[data-theme="light"] .drawer-notice {
  background: rgba(22, 163, 74, 0.1);
  color: #166534;
}

:root[data-theme="light"] .status-idle { background: #e2e8f0; color: #334155; }
:root[data-theme="light"] .status-queued { background: rgba(217, 119, 6, 0.14); color: #92400e; }
:root[data-theme="light"] .status-loading { background: rgba(2, 132, 199, 0.14); color: #075985; }
:root[data-theme="light"] .status-complete { background: rgba(22, 163, 74, 0.14); color: #166534; }
:root[data-theme="light"] .status-error { background: rgba(220, 38, 38, 0.14); color: #991b1b; }
:root[data-theme="light"] .status-cancelled { background: #cbd5e1; color: #1e293b; }

:root[data-theme="light"] .md-body code {
  background: #e2e8f0;
  color: #0f172a;
}

:root[data-theme="light"] .drawer-backdrop {
  background: rgba(15, 23, 42, 0.35);
}

3. Wire into index.html

Add the script tag inside <head> right after js/history-drawer.js:

  <!-- Additive UI: Theme Toggle -->
  <script defer src="js/theme-toggle.js"></script>

Add the toggle button inside .header-actions next to #open-history-btn:

      <div class="header-actions input-row">
        <button id="theme-toggle-btn" type="button" class="btn btn-ghost" aria-pressed="false" title="Switch theme">
          ☀ Light
        </button>
        <button id="open-history-btn" type="button" class="btn btn-secondary" disabled title="Available in Phase 5">
          History &amp; Export
        </button>
      </div>


Add collapsible model parameter controls (temperature slider and maxOutputTokens input) to the header bar.

This additive feature hooks directly into the temperature and maxOutputTokens fields already defined in Phase 0's ModelConfig schema, and automatically syncs when loading saved sessions from History.

1. js/model-params.js

/**
 * IdeaPrism — Additive Model Parameter Controls
 * Manages collapsible Temperature slider and Max Output Tokens input,
 * synced with SessionStore.modelConfig.
 */
(function (globalScope) {
  "use strict";

  const IdeaPrism = globalScope.IdeaPrism;
  if (!IdeaPrism) {
    throw new Error("IdeaPrism contracts must be loaded before model-params.js");
  }

  const DEFAULTS = Object.freeze({
    temperature: 0.7,
    maxOutputTokens: 2048
  });

  function el(id) {
    return document.getElementById(id);
  }

  function clampNumber(val, min, max, fallback) {
    const num = Number(val);
    if (!Number.isFinite(num)) return fallback;
    return Math.min(max, Math.max(min, num));
  }

  function getValues() {
    const tempEl = el("temp-slider");
    const tokensEl = el("max-tokens-input");
    return {
      temperature: tempEl
        ? clampNumber(tempEl.value, 0, 2, DEFAULTS.temperature)
        : DEFAULTS.temperature,
      maxOutputTokens: tokensEl
        ? Math.round(clampNumber(tokensEl.value, 128, 65536, DEFAULTS.maxOutputTokens))
        : DEFAULTS.maxOutputTokens
    };
  }

  function updateSummaryLabels(temp, maxTokens) {
    const tempVal = el("temp-value");
    const tempSum = el("temp-summary");
    const tokensSum = el("tokens-summary");
    const formattedTemp = Number(temp).toFixed(1);

    if (tempVal) tempVal.textContent = formattedTemp;
    if (tempSum) tempSum.textContent = formattedTemp;
    if (tokensSum) tokensSum.textContent = String(maxTokens);
  }

  function applyValuesToInputs(cfg) {
    const tempEl = el("temp-slider");
    const tokensEl = el("max-tokens-input");
    const temp = clampNumber(cfg && cfg.temperature, 0, 2, DEFAULTS.temperature);
    const maxTokens = Math.round(
      clampNumber(cfg && cfg.maxOutputTokens, 128, 65536, DEFAULTS.maxOutputTokens)
    );

    if (tempEl) tempEl.value = String(temp);
    if (tokensEl) tokensEl.value = String(maxTokens);
    updateSummaryLabels(temp, maxTokens);
  }

  function init() {
    const tempEl = el("temp-slider");
    const tokensEl = el("max-tokens-input");
    const resetBtn = el("reset-params-btn");
    if (!tempEl || !tokensEl) return;

    let lastSessionId = IdeaPrism.SessionStore.getSession().id;
    applyValuesToInputs(IdeaPrism.SessionStore.getSession().modelConfig);

    tempEl.addEventListener("input", function () {
      const vals = getValues();
      updateSummaryLabels(vals.temperature, vals.maxOutputTokens);
    });

    tokensEl.addEventListener("change", function () {
      const vals = getValues();
      tokensEl.value = String(vals.maxOutputTokens);
      updateSummaryLabels(vals.temperature, vals.maxOutputTokens);
    });

    if (resetBtn) {
      resetBtn.addEventListener("click", function () {
        applyValuesToInputs(DEFAULTS);
      });
    }

    // Sync controls whenever a different session is loaded from History
    IdeaPrism.SessionStore.subscribe(function (session) {
      if (session.id !== lastSessionId) {
        lastSessionId = session.id;
        applyValuesToInputs(session.modelConfig);
      }
    });
  }

  IdeaPrism.ModelParams = Object.freeze({
    getValues: getValues,
    applyValuesToInputs: applyValuesToInputs
  });

  if (typeof document !== "undefined") {
    document.addEventListener("DOMContentLoaded", init);
  }
})(typeof window !== "undefined" ? window : globalThis);

2. Wire into index.html

Add the script tag inside <head> right after js/theme-toggle.js:

  <!-- Additive UI: Model Parameter Controls -->
  <script defer src="js/model-params.js"></script>

Inside .model-group (right below #custom-model-input), add the collapsible <details> block:

        <details class="model-params-drawer">
          <summary>
            Params · Temp <span id="temp-summary">0.7</span> · Max <span id="tokens-summary">2048</span>
          </summary>
          <div class="model-params-body">
            <div class="param-row">
              <label for="temp-slider">Temperature: <strong id="temp-value">0.7</strong></label>
              <input id="temp-slider" type="range" min="0" max="2" step="0.1" value="0.7" />
            </div>
            <div class="param-row">
              <label for="max-tokens-input">Max Output Tokens</label>
              <div class="input-row">
                <input id="max-tokens-input" type="number" min="128" max="65536" step="128" value="2048" />
                <button id="reset-params-btn" type="button" class="btn btn-ghost btn-sm">Reset</button>
              </div>
            </div>
          </div>
        </details>

3. Connect getActiveModelConfig() in js/app-shell.js

Update getActiveModelConfig() in js/app-shell.js so every method run, follow-up, and synthesis picks up the live slider and token values:

  function getActiveModelConfig() {
    const customId = el("custom-model-input").value.trim();
    const selectedId = el("model-select").value;
    const params = IdeaPrism.ModelParams ? IdeaPrism.ModelParams.getValues() : {};
    return IdeaPrism.Factories.createModelConfig({
      modelId: customId || selectedId,
      temperature: params.temperature,
      maxOutputTokens: params.maxOutputTokens
    });
  }

4. Append to css/styles.css

/* Additive UI: Collapsible Model Parameter Controls */
.model-params-drawer {
  margin-top: 0.25rem;
  font-size: 0.78rem;
}

.model-params-drawer summary {
  cursor: pointer;
  color: var(--text-muted);
  user-select: none;
}

.model-params-drawer summary:hover {
  color: var(--accent);
}

.model-params-body {
  margin-top: 0.45rem;
  padding: 0.6rem 0.7rem;
  background: var(--bg);
  border: 1px solid var(--border);
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  gap: 0.55rem;
}

.param-row {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.param-row input[type="range"] {
  width: 100%;
  accent-color: var(--accent);
}

.param-row input[type="number"] {
  width: 110px;
  font-size: 0.82rem;
}


Add a one-click Copy Markdown button to each MethodCard and SynthesisCard toolbar.

This adds a Copy MD button to the shared buildCardElement() toolbar in js/card-renderer.js so both MethodCard and SynthesisCard get it automatically. It includes an off-screen <textarea> fallback so copying works even when opened directly via file://.

1. Add the Clipboard & Markdown Helpers to js/card-renderer.js

Place these two helpers right below function el(id) inside js/card-renderer.js:

  function serializeCardToMarkdown(card) {
    const isMethod = card.kind === "method";
    const method = isMethod
      ? IdeaPrism.Contracts.MethodRegistry.getById(card.methodId)
      : null;
    const heading = isMethod
      ? (method ? method.name + " (" + method.category + ")" : card.methodId)
      : card.title;

    const lines = ["## " + heading + (card.starred ? " ★" : ""), ""];
    const visibleTurns = (card.messages || []).filter(function (m) {
      return !m.isInitialPrompt;
    });

    visibleTurns.forEach(function (msg, idx) {
      if (msg.role === "user") {
        const tag = msg.presetId ? "Follow-Up (" + msg.presetId + ")" : "Follow-Up";
        lines.push("> **" + tag + ":** " + msg.text.replace(/\n/g, "\n> "));
        lines.push("");
      } else {
        if (idx > 0) lines.push("**Response:**\n");
        lines.push(msg.text);
        lines.push("");
      }
    });

    return lines.join("\n").trim();
  }

  async function copyTextToClipboard(text) {
    if (navigator.clipboard && typeof navigator.clipboard.writeText === "function") {
      try {
        await navigator.clipboard.writeText(text);
        return true;
      } catch (e) {
        // Fall through to execCommand fallback (common on file://)
      }
    }
    const ta = document.createElement("textarea");
    ta.value = text;
    ta.setAttribute("readonly", "");
    ta.style.position = "fixed";
    ta.style.opacity = "0";
    ta.style.pointerEvents = "none";
    document.body.appendChild(ta);
    ta.select();
    let ok = false;
    try {
      ok = document.execCommand("copy");
    } catch (e) {
      ok = false;
    }
    document.body.removeChild(ta);
    return ok;
  }

2. Add the Button to buildCardElement() in js/card-renderer.js

Insert this block inside buildCardElement(card) right after toolbar.appendChild(starBtn);:

    const hasModelOutput = card.messages.some(function (m) {
      return m.role === "model";
    });
    if (hasModelOutput) {
      const copyBtn = document.createElement("button");
      copyBtn.type = "button";
      copyBtn.className = "btn btn-ghost btn-sm";
      copyBtn.textContent = "Copy MD";
      copyBtn.title = "Copy card thread as Markdown";
      copyBtn.addEventListener("click", async function () {
        const md = serializeCardToMarkdown(card);
        const ok = await copyTextToClipboard(md);
        copyBtn.textContent = ok ? "Copied!" : "Copy failed";
        copyBtn.disabled = true;
        setTimeout(function () {
          copyBtn.textContent = "Copy MD";
          copyBtn.disabled = false;
        }, 1500);
      });
      toolbar.appendChild(copyBtn);
    }

The button appears on any MethodCard or SynthesisCard once it has at least one model response, copies the full thread (including follow-ups), and flashes Copied! for 1.5 seconds.


Generate tests/phase5-verify.js to test Markdown export, JSON round-trip import, and zero apiKey leakage in Node.js.

tests/phase5-verify.js

Run with node tests/phase5-verify.js:

/**
 * IdeaPrism — Phase 5 Verification Gate Tests
 * Tests Markdown export, JSON round-trip import, zero apiKey leakage,
 * and malformed/invalid import rejection.
 *
 * Run in Node.js: node tests/phase5-verify.js
 */
(function () {
  "use strict";

  const IdeaPrism = require("../js/contracts.js");
  require("../js/methods-catalog.js");
  require("../js/storage.js");
  require("../js/exporters.js");

  const results = [];

  function test(name, fn) {
    try {
      fn();
      results.push({ name: name, pass: true });
    } catch (err) {
      results.push({ name: name, pass: false, error: err.message });
    }
  }

  function assert(condition, message) {
    if (!condition) {
      throw new Error(message || "Assertion failed");
    }
  }

  function createMockStorage() {
    const store = {};
    return {
      getItem: function (k) {
        return Object.prototype.hasOwnProperty.call(store, k) ? store[k] : null;
      },
      setItem: function (k, v) {
        store[k] = String(v);
      },
      _dump: function () {
        return JSON.stringify(store);
      }
    };
  }

  function buildFixtureSession() {
    const { Factories, CARD_STATUS } = IdeaPrism;

    const card1 = Factories.createMethodCard("first-principles", {
      status: CARD_STATUS.COMPLETE,
      starred: true,
      selectedForSynthesis: true,
      messages: [
        Factories.createChatMessage({
          role: "user",
          text: "Initial FP prompt",
          isInitialPrompt: true
        }),
        Factories.createChatMessage({
          role: "model",
          text: "Strip assumptions down to thermal and mechanical limits."
        }),
        Factories.createChatMessage({
          role: "user",
          text: "Critique your previous response.",
          presetId: "critique",
          isInitialPrompt: false
        }),
        Factories.createChatMessage({
          role: "model",
          text: "Weakest assumption: ignores manufacturing tolerance stack-up."
        })
      ]
    });

    const card2 = Factories.createMethodCard("triz-ifr", {
      status: CARD_STATUS.COMPLETE,
      starred: false,
      selectedForSynthesis: true,
      messages: [
        Factories.createChatMessage({
          role: "user",
          text: "Initial TRIZ prompt",
          isInitialPrompt: true
        }),
        Factories.createChatMessage({
          role: "model",
          text: "Ideal Final Result: enclosure cools itself via ambient airflow."
        })
      ]
    });

    const synthesis = Factories.createSynthesisCard([card1.id, card2.id], {
      title: "Synthesis: First Principles + TRIZ",
      status: CARD_STATUS.COMPLETE,
      starred: true,
      messages: [
        Factories.createChatMessage({
          role: "user",
          text: "Initial synthesis prompt",
          isInitialPrompt: true
        }),
        Factories.createChatMessage({
          role: "model",
          text: "Combine passive convection ribs with modular snap-fit tolerances."
        })
      ]
    });

    const session = Factories.createProblemSession({
      title: "Passive Thermal Enclosure Redesign",
      problemStatement: "Eliminate active cooling fans in a compact desktop enclosure.",
      constraintsContext: "Under $15 BOM, zero moving parts, 3D-printable prototype.",
      modelConfig: {
        modelId: "gemini-3.8-flash",
        temperature: 0.4,
        maxOutputTokens: 4096
      },
      selectedMethodIds: ["first-principles", "triz-ifr"],
      cards: [card1, card2],
      syntheses: [synthesis]
    });

    // Deliberately inject forbidden secret fields to verify allowlist stripping
    session.apiKey = "AIzaSy-TOP-SECRET-KEY-999";
    session.cards[0].apiKey = "AIzaSy-NESTED-SECRET-888";

    return session;
  }

  // Gate 1: Built-in exporters registered in Phase 0 ExporterRegistry
  test("ExporterRegistry registers markdown and json exporters", function () {
    const mdExp = IdeaPrism.Contracts.ExporterRegistry.getById("markdown");
    const jsonExp = IdeaPrism.Contracts.ExporterRegistry.getById("json");
    assert(mdExp && mdExp.extension === ".md", "Markdown exporter missing");
    assert(jsonExp && jsonExp.extension === ".json", "JSON exporter missing");
  });

  // Gate 2: Markdown export structure and zero apiKey leakage
  test("exportToMarkdown renders full report with zero apiKey leakage", function () {
    const session = buildFixtureSession();
    const md = IdeaPrism.Exporters.exportToMarkdown(session);

    assert(md.indexOf("# Passive Thermal Enclosure Redesign") !== -1, "Missing title");
    assert(md.indexOf("## Problem Statement") !== -1, "Missing Problem Statement section");
    assert(md.indexOf("## Constraints & Context") !== -1, "Missing Constraints section");
    assert(md.indexOf("## Synthesized Strategies") !== -1, "Missing Synthesis section");
    assert(md.indexOf("### First Principles (Deconstruct) ★") !== -1, "Missing starred method heading");
    assert(md.indexOf("Follow-Up (critique)") !== -1, "Missing preset follow-up label");
    assert(md.indexOf("AIzaSy-TOP-SECRET-KEY-999") === -1, "Top-level apiKey leaked into Markdown!");
    assert(md.indexOf("AIzaSy-NESTED-SECRET-888") === -1, "Nested apiKey leaked into Markdown!");
  });

  // Gate 3: JSON export strips apiKey completely
  test("exportToJson strips apiKey and preserves schemaVersion", function () {
    const session = buildFixtureSession();
    const jsonText = IdeaPrism.Exporters.exportToJson(session);

    assert(jsonText.indexOf("apiKey") === -1, "apiKey property leaked into JSON export!");
    assert(jsonText.indexOf("AIzaSy-TOP-SECRET-KEY-999") === -1, "Secret value leaked into JSON!");
    const parsed = JSON.parse(jsonText);
    assert(parsed.schemaVersion === IdeaPrism.SCHEMA_VERSION, "schemaVersion mismatch");
    assert(parsed.modelConfig.temperature === 0.4, "temperature not preserved");
    assert(parsed.modelConfig.maxOutputTokens === 4096, "maxOutputTokens not preserved");
  });

  // Gate 4: Full round-trip (save -> export -> delete -> import -> restore)
  test("JSON round-trip export, delete, and import restores session identically", function () {
    const mockStorage = createMockStorage();
    const original = buildFixtureSession();

    const saveRes = IdeaPrism.Contracts.StorageAdapter.saveSession(original, mockStorage);
    assert(saveRes.ok === true, "Initial saveSession failed");

    const exportedJson = IdeaPrism.Exporters.exportToJson(original);

    IdeaPrism.Contracts.StorageAdapter.deleteSession(original.id, mockStorage);
    assert(
      IdeaPrism.Contracts.StorageAdapter.listSessions(mockStorage).length === 0,
      "Session was not deleted from storage"
    );

    const importRes = IdeaPrism.Exporters.importSessionFromJson(exportedJson);
    assert(importRes.ok === true, "importSessionFromJson failed: " + importRes.errors.join("; "));

    const reSave = IdeaPrism.Contracts.StorageAdapter.saveSession(importRes.session, mockStorage);
    assert(reSave.ok === true, "Re-saving imported session failed");

    const restoredList = IdeaPrism.Contracts.StorageAdapter.listSessions(mockStorage);
    assert(restoredList.length === 1, "Expected 1 restored session");

    const restored = restoredList[0];
    assert(restored.id === original.id, "Session ID mismatch");
    assert(restored.cards.length === 2, "Expected 2 restored method cards");
    assert(restored.cards[0].messages.length === 4, "Follow-up thread length mismatch");
    assert(restored.cards[0].starred === true, "Starred flag lost");
    assert(restored.syntheses.length === 1, "Expected 1 restored synthesis card");
    assert(
      restored.syntheses[0].sourceCardIds.length === 2,
      "Synthesis sourceCardIds lost"
    );
  });

  // Gate 5: Malformed, wrong-version, and secret-bearing imports rejected cleanly
  test("importSessionFromJson rejects malformed JSON, bad schemaVersion, and apiKey payloads", function () {
    const malformed = IdeaPrism.Exporters.importSessionFromJson("{ not valid json");
    assert(malformed.ok === false, "Malformed JSON must be rejected");

    const validObj = JSON.parse(IdeaPrism.Exporters.exportToJson(buildFixtureSession()));

    const badVersion = Object.assign({}, validObj, { schemaVersion: "99.0.0" });
    const badVersionRes = IdeaPrism.Exporters.importSessionFromJson(JSON.stringify(badVersion));
    assert(badVersionRes.ok === false, "Unsupported schemaVersion must be rejected");

    const secretPayload = Object.assign({}, validObj, { apiKey: "LEAKED_KEY" });
    const secretRes = IdeaPrism.Exporters.importSessionFromJson(JSON.stringify(secretPayload));
    assert(secretRes.ok === false, "Payload containing apiKey must be rejected on import");
  });

  // Summary output
  const failed = results.filter(function (r) {
    return !r.pass;
  });
  results.forEach(function (r) {
    console.log((r.pass ? "[PASS] " : "[FAIL] ") + r.name + (r.error ? " — " + r.error : ""));
  });
  console.log(
    "\nPhase 5 Gate: " + (results.length - failed.length) + "/" + results.length + " passed."
  );
  if (failed.length > 0) {
    process.exit(1);
  }
})();

Run all three Node.js verification suites together to confirm zero regressions across Phases 0–5:

node tests/phase0-verify.js && node tests/phase1-verify.js && node tests/phase5-verify.js


What parts of the overall application require Node.js?

None of the application itself requires Node.js. Everything needed to run IdeaPrism is 100% browser-native HTML, CSS, and vanilla JavaScript.

LayerFilesNode.js Required?Details
Runtime Appindex.html, css/styles.css, all js/*.jsNoOpens directly from disk (file://) or any static web host with zero build step. The if (typeof module !== "undefined" && module.exports) lines at the bottom of the JS files are inert guards that browsers ignore.
Phase 0 Teststests/phase0-verify.js + tests/phase0-verify.htmlOptionalDual-mode: runs directly in the browser via phase0-verify.html or in Node.js.
Phase 1 & 5 Teststests/phase1-verify.js, tests/phase5-verify.jsYes (currently)Written as Node.js CLI scripts using require() and process.exit(). They are strictly optional developer verification harnesses and are not loaded by index.html.

If you want a completely Node-free workflow, tests/phase1-verify.js and tests/phase5-verify.js can be converted to the same dual-mode pattern as Phase 0 so all verification gates run from a single tests/verify-all.html page in your browser.


Provide the final inventory of application files

Below is the complete file inventory for IdeaPrism, organized by directory and exact runtime load order.

Directory Structure

ideaprism/
├── index.html
├── css/
│   └── styles.css
├── js/
│   ├── contracts.js
│   ├── methods-catalog.js
│   ├── gemini-client.js
│   ├── execution-queue.js
│   ├── storage.js
│   ├── session-store.js
│   ├── markdown-safe.js
│   ├── app-shell.js
│   ├── followup-controller.js
│   ├── card-renderer.js
│   ├── synthesis-controller.js
│   ├── exporters.js
│   ├── history-drawer.js
│   ├── theme-toggle.js
│   └── model-params.js
└── tests/                          (Optional verification harnesses)
    ├── phase0-verify.html
    ├── phase0-verify.js
    ├── phase1-verify.js
    └── phase5-verify.js

Runtime Application Files (17 Files — Zero Node.js Required)

Scripts in js/ must be loaded in index.html via <script defer> in the exact order listed below:

OrderFilePhaseResponsibility
—index.htmlPhase 2–5Application shell, header controls, mount points, and ordered <script defer> tags
—css/styles.cssPhase 2–5Responsive layout, card/drawer styling, light/dark custom properties, and parameter controls
1js/contracts.jsPhase 0Locked schemas, CardStateMachine, memory-only RuntimeAuth, allowlist validators, and contract stubs
2js/methods-catalog.jsPhase 112 built-in innovative thinking methods, 4 follow-up presets, method preset groups, and prompt compilers
3js/gemini-client.jsPhase 1Native Google Gemini REST client (generateContent, GET /v1beta/models) using x-goog-api-key
4js/execution-queue.jsPhase 1Bounded concurrency queue (max 3) with per-card and global AbortController cancellation
5js/storage.jsPhase 1localStorage persistence adapter with strict allowlist serialization and QuotaExceededError handling
6js/session-store.jsPhase 1Observable state store managing active ProblemSession and card lifecycle transitions
7js/markdown-safe.jsPhase 2Zero-dependency XSS-safe DOM Markdown renderer (no raw innerHTML)
8js/app-shell.jsPhase 2Header controls, model discovery, problem/constraints inputs, method selector, and batch execution
9js/followup-controller.jsPhase 3Per-card follow-up submission, retry, cancel, and regenerate logic (shared by method & synthesis cards)
10js/card-renderer.jsPhase 3+Interactive card UI, status badges, View Prompt drawer, follow-up chips/form, and Copy MD button
11js/synthesis-controller.jsPhase 4Cross-card selection bar, synthesis prompt compilation, and SynthesisCard rendering
12js/exporters.jsPhase 5Markdown (.md) and JSON (.json) exporters plus schema-validated .json importer
13js/history-drawer.jsPhase 5Slide-over session history drawer (search, load, rename, delete, import/export)
14js/theme-toggle.jsAdditiveLight/dark theme switcher persisted separately under ideaprism_theme_v1
15js/model-params.jsAdditiveCollapsible temperature slider and maxOutputTokens input synced to ModelConfig

Optional Verification Files (4 Files — Not Loaded by index.html)

FileEnvironmentPurpose
tests/phase0-verify.htmlBrowser (file://)Visual browser runner for Phase 0 contract and secret-isolation gates
tests/phase0-verify.jsBrowser or Node.jsVerifies RuntimeAuth, CardStateMachine, validateSession(), and contract stubs
tests/phase1-verify.jsNode.jsVerifies 12-method catalog, ExecutionQueue concurrency/abort, and StorageAdapter quota/stripping
tests/phase5-verify.jsNode.jsVerifies Markdown/JSON export, round-trip JSON import, and zero apiKey leakage


Write a concise README.md documenting how to run IdeaPrism locally, its architecture, and how to run the verification tests.

README.md

# IdeaPrism — Innovative Thinking Studio

A zero-build, browser-native HTML/CSS/JS application that applies 12 structured innovative thinking methods to a problem statement via the Google Gemini REST API. Results render as interactive cards with per-card follow-ups, cross-card synthesis, local session history, and Markdown/JSON export and import.

## Features

- **Bring Your Own Key (Memory Only):** Your Gemini API key is held strictly in an in-memory closure (`RuntimeAuth`), sent exclusively via the `x-goog-api-key` header, and never written to `localStorage`, `sessionStorage`, or exported files.
- **Model Discovery & Parameters:** Supports curated Gemini presets, live model discovery (`GET /v1beta/models`), custom model IDs, and collapsible temperature / `maxOutputTokens` controls.
- **12 Built-In Thinking Methods:** First Principles, TRIZ / Ideal Final Result, SCAMPER, Inversion, Six Thinking Hats, Pre-Mortem, Biomimicry, Jobs-to-be-Done, Lateral Thinking, Second-Order Thinking, Blue Ocean / ERRC, and Constraint Removal.
- **Interactive Cards & Follow-Ups:** Bounded concurrency queue (max 3 concurrent requests), per-card Cancel/Retry/Regenerate, collapsible **View Prompt** drawer, one-click **Copy MD**, preset follow-up chips (*Critique*, *Action Plan*, *Go Deeper*, *Risks & Constraints*), and free-text multi-turn follow-ups.
- **Cross-Card Synthesis:** Select 2+ completed cards to generate a unified `SynthesisCard` with full follow-up support.
- **History & Portable Backups:** Automatic `localStorage` session history with search, rename, delete, Markdown (`.md`) export, and schema-validated JSON (`.json`) export/import.
- **Light / Dark Theme:** Respects OS preference and persists separately under `ideaprism_theme_v1`.

## Running Locally

No build step, package manager, or backend server is required.

1. **Direct Open (`file://`):** Double-click `index.html` to open it in any modern browser.
2. **Or Static HTTP Server (optional):**
   ```bash
   python3 -m http.server 8080

Then open http://localhost:8080. 3. Enter your Google Gemini API key in the header bar, choose a model (or click Refresh to discover models available to your key), enter a problem statement, select methods, and click Run Selected Methods.

Architecture

IdeaPrism is built as a strictly additive, contract-first vanilla JS application attached to a single global namespace (window.IdeaPrism) using ordered classic <script defer> tags (avoiding file:// ES-module CORS blocks).

ideaprism/
├── index.html                  # App shell and ordered <script defer> imports
├── css/styles.css              # Responsive layout, cards, drawer, light/dark themes
├── js/
│   ├── contracts.js            # Phase 0: Schemas, CardStateMachine, RuntimeAuth, validators
│   ├── methods-catalog.js      # Phase 1: 12 methods, follow-up presets, prompt compilers
│   ├── gemini-client.js        # Phase 1: Gemini REST client (generateContent, listModels)
│   ├── execution-queue.js      # Phase 1: Bounded concurrency queue + AbortController
│   ├── storage.js              # Phase 1: Allowlisted localStorage adapter + quota handling
│   ├── session-store.js        # Phase 1: Observable ProblemSession state store
│   ├── markdown-safe.js        # Phase 2: XSS-safe DOM Markdown renderer (zero innerHTML)
│   ├── app-shell.js            # Phase 2: Header controls, method selector, batch runner
│   ├── followup-controller.js  # Phase 3: Shared follow-up, retry, cancel, regenerate logic
│   ├── card-renderer.js        # Phase 3+: MethodCard & SynthesisCard UI + Copy MD
│   ├── synthesis-controller.js # Phase 4: Cross-card selection bar & synthesis workflow
│   ├── exporters.js            # Phase 5: .md/.json exporters + validated .json importer
│   ├── history-drawer.js       # Phase 5: Slide-over session history & import/export UI
│   ├── theme-toggle.js         # Additive: Light/dark CSS custom property switcher
│   └── model-params.js         # Additive: Collapsible temperature & maxOutputTokens UI
└── tests/                      # Optional verification gates (not loaded by index.html)

Key Invariants

  • Secret Isolation: RuntimeAuth.apiKey is never attached to ProblemSession; validateSession() and sanitizeSessionForPersistence() reject or strip any apiKey field.

  • XSS Safety: All LLM Markdown output is rendered via DOM node construction (createTextNode) in js/markdown-safe.js—never raw innerHTML.

  • Unified Card Contract: MethodCard and SynthesisCard share the same CardStatus state machine and alternating user/model messages[] schema.

Running Verification Tests

The runtime app requires zero Node.js. The optional test scripts in tests/ verify Phase 0, 1, and 5 invariants:

  • Browser (file://): Open tests/phase0-verify.html directly in your browser.

  • Node.js CLI (all automated gates):

    node tests/phase0-verify.js && node tests/phase1-verify.js && node tests/phase5-verify.js


From <https://gemini.google.com/app/a7d105fd4b0434d8>  Google Gemini (4 Neon)



Provide the JS for 6 additional TRIZ methods

  1. Contradiction Matrix
  2. Separation Principles
  3. Nine Screen
  4. Trimming
  5. Smart Little People
  6. Su-Field

Because Phase 0 locked MethodRegistry.register(), you can add these 6 TRIZ methods as a standalone additive file without modifying js/methods-catalog.js or any other module.

1. js/triz-methods-pack.js

/**
 * IdeaPrism — Additive TRIZ Methods Pack (6 Additional TRIZ Methods)
 * Load immediately after js/methods-catalog.js in index.html.
 */
(function (globalScope) {
  "use strict";

  const IdeaPrism =
    globalScope.IdeaPrism ||
    (typeof require === "function" ? require("./contracts.js") : null);

  if (!IdeaPrism) {
    throw new Error("IdeaPrism Phase 0 contracts must be loaded before triz-methods-pack.js");
  }

  const CAT = IdeaPrism.METHOD_CATEGORIES;

  const TRIZ_PACK_METHODS = [
    {
      id: "triz-contradiction-matrix",
      name: "TRIZ Contradiction Matrix & 40 Principles",
      category: CAT.DECONSTRUCT,
      summary: "Map the technical contradiction to TRIZ parameters and apply targeted Inventive Principles.",
      systemPrompt:
        "You are a TRIZ specialist applying Altshuller's Contradiction Matrix and 40 Inventive Principles. Avoid generic trade-offs; map the problem to specific improving vs. worsening engineering parameters and translate the recommended principles into concrete concepts.",
      userPromptTemplate:
        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply the TRIZ Contradiction Matrix:\n1. Formulate the core Technical Contradiction (IF we improve [Parameter A], THEN [Parameter B] worsens).\n2. Select the 3-4 most relevant TRIZ Inventive Principles (by number and name) that resolve this conflict.\n3. Translate each principle into a specific, workable concept for this problem."
    },
    {
      id: "triz-separation-principles",
      name: "TRIZ Separation Principles",
      category: CAT.REFRAME,
      summary: "Resolve physical contradictions by separating opposing requirements in Time, Space, Scale, or Condition.",
      systemPrompt:
        "You are a TRIZ practitioner resolving Physical Contradictions (where one element must be both X and not-X). Systematically apply the 4 Separation Principles to eliminate the compromise.",
      userPromptTemplate:
        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply TRIZ Separation Principles:\n1. State the Physical Contradiction (Element E must be [State A] to achieve X, AND [Opposite State B] to achieve Y).\n2. Generate one concrete solution for each separation axis:\n   - **Separation in Time** (State A now, State B later)\n   - **Separation in Space** (State A here, State B there)\n   - **Separation by Scale / Whole vs. Parts** (State A at micro-level, State B at macro-level)\n   - **Separation upon Condition** (State A under condition 1, State B under condition 2)\n3. Recommend the highest-ideality option."
    },
    {
      id: "triz-nine-screen",
      name: "TRIZ Nine-Screen (System Operator)",
      category: CAT.REFRAME,
      summary: "Map the Sub-system, System, and Super-system across Past, Present, and Future to spot hidden leverage.",
      systemPrompt:
        "You are a systems architect using the TRIZ Nine-Screen (9 Boxes / System Operator) method. Expose resources and intervention points across hierarchy levels and time horizons.",
      userPromptTemplate:
        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nBuild a TRIZ Nine-Screen analysis:\n1. Present a 3x3 Markdown table with rows (**Super-system**, **System**, **Sub-system**) and columns (**Past**, **Present**, **Future**).\n2. Identify 2-3 underused resources or failure triggers revealed by the Past and Super-system/Sub-system boxes.\n3. Propose 2 concrete solutions that intervene outside the obvious Present-System box."
    },
    {
      id: "triz-trimming",
      name: "TRIZ Trimming",
      category: CAT.DECONSTRUCT,
      summary: "Eliminate costly or failure-prone components while transferring their useful functions to existing elements.",
      systemPrompt:
        "You are a value-engineering TRIZ expert specializing in Trimming. Ruthlessly remove components, steps, or intermediaries while preserving or improving useful functions by reassigning them to surviving system or environmental resources.",
      userPromptTemplate:
        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply TRIZ Trimming:\n1. List the 4-6 primary components/steps in the current system and the useful function each performs.\n2. Identify the 2-3 highest-cost, highest-friction, or most failure-prone components to trim.\n3. For each trimmed component, specify which remaining component or free resource takes over its useful function (or how the need for the function is eliminated).\n4. Describe the resulting streamlined architecture."
    },
    {
      id: "triz-smart-little-people",
      name: "TRIZ Smart Little People (SLP)",
      category: CAT.DIVERGE,
      summary: "Break psychological inertia by modeling problem elements as crowds of tiny, intelligent agents.",
      systemPrompt:
        "You are a TRIZ facilitator using Modeling with Smart Little People (SLP) to break psychological inertia. First describe the desired micro-level behavior using swarms of tiny agents, then translate those behaviors back into real-world physical, mechanical, or software mechanisms.",
      userPromptTemplate:
        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply TRIZ Smart Little People:\n1. Identify the exact conflict zone where the current system fails.\n2. Model the conflict zone as crowds of tiny, intelligent agents—describe what they would hold, block, link, or rearrange to solve the problem effortlessly.\n3. Translate those agent behaviors into 2-3 real-world engineering, material, or algorithmic mechanisms."
    },
    {
      id: "triz-sufield",
      name: "TRIZ Su-Field Analysis",
      category: CAT.STRESS_TEST,
      summary: "Model Substance-Field interactions to diagnose missing, insufficient, or harmful effects and apply Standard Solutions.",
      systemPrompt:
        "You are a TRIZ expert in Substance-Field (Su-Field) Modeling and the 76 Standard Solutions. Diagnose whether the system's core interaction is incomplete, insufficient, or harmful, then apply structured Su-Field transformations (adding S3, modifying F, introducing an anti-field, or evolving to a measured/controlled field).",
      userPromptTemplate:
        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply TRIZ Su-Field Analysis:\n1. Identify **S1** (target/object), **S2** (tool/actor), and **F** (energy/information field acting between them).\n2. Classify the interaction defect: Incomplete, Insufficient, or Harmful.\n3. Apply 2-3 TRIZ Standard Solution transformations (e.g., introduce a modified substance S3, switch to a more controllable field F2, or add a neutralizing field) and translate each into a concrete design change."
    }
  ];

  TRIZ_PACK_METHODS.forEach(function (method) {
    IdeaPrism.Contracts.MethodRegistry.register(Object.freeze(method));
  });

  if (typeof module !== "undefined" && module.exports) {
    module.exports = TRIZ_PACK_METHODS;
  }
})(typeof window !== "undefined" ? window : globalThis);

2. Wire into index.html

Add one line inside <head> right after js/methods-catalog.js:

  <script defer src="js/methods-catalog.js"></script>

  <script defer src="js/triz-methods-pack.js"></script>

All 6 methods will automatically appear in the Method Selector grid under their respective categories (Deconstruct, Reframe, Diverge, Stress-Test), work with View Prompt, Follow-Ups, Copy MD, Synthesis, and Export/Import.


Add a TRIZ Suite preset button to the preset bar that selects all 7 TRIZ methods (IFR plus the 6 new methods) in one click.

Append this block to js/triz-methods-pack.js right before the if (typeof module !== "undefined" && module.exports) line. It stays 100% additive—no edits needed to js/methods-catalog.js or js/app-shell.js.

const TRIZ_SUITE_IDS = Object.freeze([

    "triz-ifr",

    "triz-contradiction-matrix",

    "triz-separation-principles",

    "triz-nine-screen",

    "triz-trimming",

    "triz-smart-little-people",

    "triz-sufield"

  ]);


  function mountTrizSuiteButton() {

    const bar = document.getElementById("method-presets");

    if (!bar || document.getElementById("preset-triz-suite-btn")) return;


    const btn = document.createElement("button");

    btn.id = "preset-triz-suite-btn";

    btn.type = "button";

    btn.className = "btn btn-ghost";

    btn.textContent = "TRIZ Suite (7)";

    btn.title = "Select IFR plus all 6 TRIZ methods";

    btn.addEventListener("click", function () {

      IdeaPrism.SessionStore.updateSessionMeta({

        selectedMethodIds: TRIZ_SUITE_IDS.slice()

      });

    });


    // Insert just before the trailing "Clear" button

    const clearBtn = bar.lastElementChild;

    if (clearBtn) {

      bar.insertBefore(btn, clearBtn);

    } else {

      bar.appendChild(btn);

    }

  }


  // Runs after app-shell.js populates #method-presets during DOMContentLoaded

  if (typeof window !== "undefined") {

    window.addEventListener("load", mountTrizSuiteButton);

  }

Clicking TRIZ Suite (7) selects triz-ifr along with all 6 methods from js/triz-methods-pack.js in one click.


Update the All preset button so it dynamically selects every method in MethodRegistry (all 18 methods) instead of only the original 12.

Replace renderPresetButtons() in js/app-shell.js with the version below. It reads MethodRegistry.getAll() dynamically so the button label (All (18)) and selection always include every registered method—including js/triz-methods-pack.js and any future packs.

Update renderPresetButtons() in js/app-shell.js

function renderPresetButtons() {

    const bar = el("method-presets");

    bar.textContent = "";

    const groups = IdeaPrism.Catalog.METHOD_PRESET_GROUPS;


    Object.keys(groups).forEach(function (key) {

      const btn = document.createElement("button");

      btn.type = "button";

      btn.className = "btn btn-ghost";


      if (key === "all") {

        const total = IdeaPrism.Contracts.MethodRegistry.getAll().length;

        btn.textContent = "All (" + total + ")";

        btn.addEventListener("click", function () {

          const allIds = IdeaPrism.Contracts.MethodRegistry.getAll().map(function (m) {

            return m.id;

          });

          IdeaPrism.SessionStore.updateSessionMeta({

            selectedMethodIds: allIds

          });

        });

      } else {

        btn.textContent = groups[key].label;

        btn.addEventListener("click", function () {

          IdeaPrism.SessionStore.updateSessionMeta({

            selectedMethodIds: groups[key].methodIds

          });

        });

      }


      bar.appendChild(btn);

    });


    const clearBtn = document.createElement("button");

    clearBtn.type = "button";

    clearBtn.className = "btn btn-ghost";

    clearBtn.textContent = "Clear";

    clearBtn.addEventListener("click", function () {

      IdeaPrism.SessionStore.updateSessionMeta({ selectedMethodIds: [] });

    });

    bar.appendChild(clearBtn);

  }

No changes are needed in js/methods-catalog.js or js/triz-methods-pack.js. Because js/triz-methods-pack.js loads before DOMContentLoaded, All (18) renders automatically on startup and selects all 18 methods on click.


Is it possible to contract and expand cards, along with scroll bars?

Yes. You can add per-card collapse/expand and scrollable card bodies without touching Phase 0 schemas—keep the collapsed card IDs in an in-memory Set inside js/card-renderer.js so background updates from other cards don't reset what you've collapsed, and cap .card-thread with a vertical scroll bar in CSS.

1. Update js/card-renderer.js

Add the in-memory Set near the top of the IIFE (right after const IdeaPrism = globalScope.IdeaPrism;):

  const collapsedCardIds = new Set();

Inside buildCardElement(card), add the .card-collapsed class when the card is in the set:

    const isCollapsed = collapsedCardIds.has(card.id);
    const article = document.createElement("article");
    article.className =
      "result-card" +
      (card.starred ? " card-starred" : "") +
      (card.kind === "synthesis" ? " card-synthesis" : "") +
      (isCollapsed ? " card-collapsed" : "");
    article.dataset.cardId = card.id;

Then add the Collapse / Expand button inside buildCardElement(card) right at the start of toolbar (before starBtn):

    const collapseBtn = document.createElement("button");
    collapseBtn.type = "button";
    collapseBtn.className = "btn btn-ghost btn-sm";
    collapseBtn.textContent = isCollapsed ? "▸ Expand" : "▾ Collapse";
    collapseBtn.setAttribute("aria-expanded", String(!isCollapsed));
    collapseBtn.addEventListener("click", function () {
      const nowCollapsed = !collapsedCardIds.has(card.id);
      if (nowCollapsed) {
        collapsedCardIds.add(card.id);
      } else {
        collapsedCardIds.delete(card.id);
      }
      article.classList.toggle("card-collapsed", nowCollapsed);
      collapseBtn.textContent = nowCollapsed ? "▸ Expand" : "▾ Collapse";
      collapseBtn.setAttribute("aria-expanded", String(!nowCollapsed));
    });
    toolbar.appendChild(collapseBtn);

2. Append to css/styles.css

/* Scrollable Card Thread & Collapsed State */
.card-thread {
  max-height: 420px;
  overflow-y: auto;
  padding-right: 0.35rem;
  scrollbar-width: thin;
  scrollbar-color: var(--border) transparent;
}

.card-thread::-webkit-scrollbar {
  width: 6px;
}

.card-thread::-webkit-scrollbar-thumb {
  background: var(--border);
  border-radius: 999px;
}

.result-card.card-collapsed .prompt-drawer,
.result-card.card-collapsed .card-thread,
.result-card.card-collapsed .followup-area,
.result-card.card-collapsed .card-footer {
  display: none;
}

.result-card.card-collapsed .card-toolbar {
  padding-bottom: 0;
  border-bottom: none;
}

Collapsed cards shrink down to just their header (title, category, status badge) and toolbar, while expanded cards scroll cleanly inside a 420px viewport without stretching the rest of the grid.


Add Collapse All and Expand All buttons to the Thinking Method Cards header bar.

1. Update #results-section in index.html

Replace the .panel-header inside <section id="results-section"> so the card count and bulk toggle buttons sit cleanly together:

    <!-- Phase 3 Mount Point: Method Result Cards -->
    <section id="results-section" class="results-section" aria-label="Method Results">
      <div class="panel-header">
        <h2>3. Thinking Method Cards</h2>
        <div class="input-row" style="align-items: center;">
          <span id="cards-count" class="muted-text">0 cards</span>
          <button id="collapse-all-cards-btn" type="button" class="btn btn-ghost btn-sm" disabled>
            Collapse All
          </button>
          <button id="expand-all-cards-btn" type="button" class="btn btn-ghost btn-sm" disabled>
            Expand All
          </button>
        </div>
      </div>
      <div id="cards-grid" class="cards-grid">
        <p class="empty-state">Select one or more thinking methods above and click <strong>Run Selected Methods</strong>.</p>
      </div>
    </section>

2. Update js/card-renderer.js

Add collapseAllCards() and expandAllCards() right above renderMethodCards(session):

  function collapseAllCards() {
    const session = IdeaPrism.SessionStore.getSession();
    session.cards.forEach(function (card) {
      collapsedCardIds.add(card.id);
    });
    renderMethodCards(session);
  }

  function expandAllCards() {
    const session = IdeaPrism.SessionStore.getSession();
    session.cards.forEach(function (card) {
      collapsedCardIds.delete(card.id);
    });
    renderMethodCards(session);
  }

Inside renderMethodCards(session), toggle the disabled state of both buttons right after updating countEl.textContent:

    const hasCards = session.cards.length > 0;
    const collapseAllBtn = el("collapse-all-cards-btn");
    const expandAllBtn = el("expand-all-cards-btn");
    if (collapseAllBtn) collapseAllBtn.disabled = !hasCards;
    if (expandAllBtn) expandAllBtn.disabled = !hasCards;

Finally, wire the click listeners inside the DOMContentLoaded handler at the bottom of js/card-renderer.js:

  if (typeof document !== "undefined") {
    document.addEventListener("DOMContentLoaded", function () {
      const collapseAllBtn = el("collapse-all-cards-btn");
      const expandAllBtn = el("expand-all-cards-btn");
      if (collapseAllBtn) collapseAllBtn.addEventListener("click", collapseAllCards);
      if (expandAllBtn) expandAllBtn.addEventListener("click", expandAllCards);

      IdeaPrism.SessionStore.subscribe(function (session) {
        renderMethodCards(session);
      });
      renderMethodCards(IdeaPrism.SessionStore.getSession());
    });
  }

Both buttons automatically disable when there are 0 cards and scope strictly to session.cards without disturbing any SynthesisCard collapse states.


Provide just the list entry for new method: Morphological Analysis -- and any other(s) you believe are needed and useful

Drop these entries directly into BUILTIN_METHODS (in js/methods-catalog.js) or a standalone additive pack registered via IdeaPrism.Contracts.MethodRegistry.register(...).

{

      id: "morphological-analysis",

      name: "Morphological Analysis (Zwicky Box)",

      category: CAT.DIVERGE,

      summary: "Decompose the problem into independent dimensions and systematically recombine options to discover non-obvious solutions.",

      systemPrompt:

        "You are a systems architect applying Fritz Zwicky's Morphological Analysis. Break the problem into independent parameters, populate distinct values for each, prune impossible combinations, and synthesize novel, high-value configurations.",

      userPromptTemplate:

        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply Morphological Analysis:\n1. Identify 4-5 independent dimensions/parameters of the system (e.g., Power Source, Mechanism, Interface, Material, Delivery Model).\n2. Present a Markdown table listing 3-4 distinct options per dimension.\n3. Combine non-obvious options across rows to propose 3 concrete, viable solution concepts (explicitly noting which option per dimension was picked).\n4. Highlight the single most novel yet feasible combination."

    },

    {

      id: "leverage-points",

      name: "Systems Leverage Points (Meadows)",

      category: CAT.REFRAME,

      summary: "Find where a small, targeted shift in rules, feedback loops, or goals produces a massive system-wide change.",

      systemPrompt:

        "You are a systems dynamics strategist applying Donella Meadows' 12 Leverage Points. Look past weak parameter tweaks (numbers/budgets) to find high-leverage interventions in information flows, feedback loops, rules, and system goals.",

      userPromptTemplate:

        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply Systems Leverage Points:\n1. Identify the low-leverage parameter tweaks people usually try first (and why they stall).\n2. Propose 3 higher-leverage interventions across:\n   - **Information Flows & Feedback Loops** (who sees what, and when)\n   - **Rules & Incentives** (constraints, rewards, or boundaries)\n   - **System Goal or Paradigm** (redefining what the system optimizes for)\n3. Recommend the highest-leverage intervention that is still practical to execute."

    },

    {

      id: "adjacent-possible",

      name: "The Adjacent Possible",

      category: CAT.DIVERGE,

      summary: "Map what becomes feasible one step beyond currently available components, tools, or behaviors.",

      systemPrompt:

        "You are an innovation strategist applying Stuart Kauffman and Steven Johnson's Adjacent Possible framework. Focus on realistic breakthroughs achievable by recombining existing, mature building blocks that are one step away from current practice.",

      userPromptTemplate:

        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nExplore the Adjacent Possible:\n1. List 4-5 mature, readily available technologies, materials, or behaviors already adjacent to this problem.\n2. Identify 3 'one-step-away' solutions that recombine these existing parts without requiring unproven inventions.\n3. For the strongest concept, state what new 'second-step' possibilities it unlocks next."

    },

    {

      id: "cause-effect-chain",

      name: "Cause-Effect Chain Analysis (CECA)",

      category: CAT.DECONSTRUCT,

      summary: "Trace the exact chain of root causes behind the undesirable effect to find the cheapest point to break it.",

      systemPrompt:

        "You are a root-cause analyst applying Cause-Effect Chain Analysis (CECA / 5 Whys). Separate symptoms from underlying physical, logical, or organizational root causes, and identify key disadvantages where breaking the chain solves the problem cleanly.",

      userPromptTemplate:

        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply Cause-Effect Chain Analysis:\n1. State the primary Undesirable Effect (UDE).\n2. Trace 2-3 branching cause-effect chains downward (at least 4-5 levels deep) to their root causes.\n3. Mark the 2 highest-leverage 'key disadvantages' where breaking the chain is easiest or cheapest.\n4. Propose concrete interventions at those exact breakpoints."

    },

    {

      id: "synectics",

      name: "Synectics (Structured Analogies)",

      category: CAT.DIVERGE,

      summary: "Use Direct, Personal, and Symbolic analogies to make the familiar strange and uncover fresh mechanisms.",

      systemPrompt:

        "You are a Synectics facilitator. Guide the problem through structured analogy types (Direct, Personal, and Symbolic/Compressed Conflict) and translate the resulting insights into concrete, workable solutions.",

      userPromptTemplate:

        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply Synectics:\n1. **Direct Analogy**: Compare this problem to a parallel mechanism in another field (biology, music, architecture, logistics).\n2. **Personal Analogy**: Step inside the core element—if you *were* that component, what would you feel, resist, or want?\n3. **Symbolic Analogy (Compressed Conflict)**: Capture the core tension in a 2-word oxymoron (e.g., 'rigid flexibility', 'loud silence').\n4. Translate these analogies into 2-3 concrete solution concepts."

    }

Why These 4 Pair Well with Morphological Analysis

  • Leverage Points (Meadows) fills a systems-dynamics gap—identifying where to intervene rather than just what to build.

  • The Adjacent Possible balances blue-sky divergence with immediately buildable recombinations.

  • Cause-Effect Chain Analysis (CECA) pairs naturally with TRIZ and First Principles by isolating the exact root-cause breakpoint before ideating.

  • Synectics adds structured metaphor generation (Direct / Personal / Symbolic) to complement your existing Random Entry and Biomimicry cards.


Package these 5 methods into a standalone js/systems-methods-pack.js file with a preset button, matching js/triz-methods-pack.js.

1. js/systems-methods-pack.js

/**

 * IdeaPrism — Additive Systems & Combinatorial Methods Pack (5 Methods)

 * Load immediately after js/triz-methods-pack.js in index.html.

 */

(function (globalScope) {

  "use strict";


  const IdeaPrism =

    globalScope.IdeaPrism ||

    (typeof require === "function" ? require("./contracts.js") : null);


  if (!IdeaPrism) {

    throw new Error("IdeaPrism Phase 0 contracts must be loaded before systems-methods-pack.js");

  }


  const CAT = IdeaPrism.METHOD_CATEGORIES;


  const SYSTEMS_PACK_METHODS = [

    {

      id: "morphological-analysis",

      name: "Morphological Analysis (Zwicky Box)",

      category: CAT.DIVERGE,

      summary: "Decompose the problem into independent dimensions and systematically recombine options to discover non-obvious solutions.",

      systemPrompt:

        "You are a systems architect applying Fritz Zwicky's Morphological Analysis. Break the problem into independent parameters, populate distinct values for each, prune impossible combinations, and synthesize novel, high-value configurations.",

      userPromptTemplate:

        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply Morphological Analysis:\n1. Identify 4-5 independent dimensions/parameters of the system (e.g., Power Source, Mechanism, Interface, Material, Delivery Model).\n2. Present a Markdown table listing 3-4 distinct options per dimension.\n3. Combine non-obvious options across rows to propose 3 concrete, viable solution concepts (explicitly noting which option per dimension was picked).\n4. Highlight the single most novel yet feasible combination."

    },

    {

      id: "leverage-points",

      name: "Systems Leverage Points (Meadows)",

      category: CAT.REFRAME,

      summary: "Find where a small, targeted shift in rules, feedback loops, or goals produces a massive system-wide change.",

      systemPrompt:

        "You are a systems dynamics strategist applying Donella Meadows' 12 Leverage Points. Look past weak parameter tweaks (numbers/budgets) to find high-leverage interventions in information flows, feedback loops, rules, and system goals.",

      userPromptTemplate:

        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply Systems Leverage Points:\n1. Identify the low-leverage parameter tweaks people usually try first (and why they stall).\n2. Propose 3 higher-leverage interventions across:\n   - **Information Flows & Feedback Loops** (who sees what, and when)\n   - **Rules & Incentives** (constraints, rewards, or boundaries)\n   - **System Goal or Paradigm** (redefining what the system optimizes for)\n3. Recommend the highest-leverage intervention that is still practical to execute."

    },

    {

      id: "adjacent-possible",

      name: "The Adjacent Possible",

      category: CAT.DIVERGE,

      summary: "Map what becomes feasible one step beyond currently available components, tools, or behaviors.",

      systemPrompt:

        "You are an innovation strategist applying Stuart Kauffman and Steven Johnson's Adjacent Possible framework. Focus on realistic breakthroughs achievable by recombining existing, mature building blocks that are one step away from current practice.",

      userPromptTemplate:

        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nExplore the Adjacent Possible:\n1. List 4-5 mature, readily available technologies, materials, or behaviors already adjacent to this problem.\n2. Identify 3 'one-step-away' solutions that recombine these existing parts without requiring unproven inventions.\n3. For the strongest concept, state what new 'second-step' possibilities it unlocks next."

    },

    {

      id: "cause-effect-chain",

      name: "Cause-Effect Chain Analysis (CECA)",

      category: CAT.DECONSTRUCT,

      summary: "Trace the exact chain of root causes behind the undesirable effect to find the cheapest point to break it.",

      systemPrompt:

        "You are a root-cause analyst applying Cause-Effect Chain Analysis (CECA / 5 Whys). Separate symptoms from underlying physical, logical, or organizational root causes, and identify key disadvantages where breaking the chain solves the problem cleanly.",

      userPromptTemplate:

        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply Cause-Effect Chain Analysis:\n1. State the primary Undesirable Effect (UDE).\n2. Trace 2-3 branching cause-effect chains downward (at least 4-5 levels deep) to their root causes.\n3. Mark the 2 highest-leverage 'key disadvantages' where breaking the chain is easiest or cheapest.\n4. Propose concrete interventions at those exact breakpoints."

    },

    {

      id: "synectics",

      name: "Synectics (Structured Analogies)",

      category: CAT.DIVERGE,

      summary: "Use Direct, Personal, and Symbolic analogies to make the familiar strange and uncover fresh mechanisms.",

      systemPrompt:

        "You are a Synectics facilitator. Guide the problem through structured analogy types (Direct, Personal, and Symbolic/Compressed Conflict) and translate the resulting insights into concrete, workable solutions.",

      userPromptTemplate:

        "Problem Statement:\n{{problemStatement}}\n{{constraintsBlock}}\nApply Synectics:\n1. **Direct Analogy**: Compare this problem to a parallel mechanism in another field (biology, music, architecture, logistics).\n2. **Personal Analogy**: Step inside the core element—if you *were* that component, what would you feel, resist, or want?\n3. **Symbolic Analogy (Compressed Conflict)**: Capture the core tension in a 2-word oxymoron (e.g., 'rigid flexibility', 'loud silence').\n4. Translate these analogies into 2-3 concrete solution concepts."

    }

  ];


  SYSTEMS_PACK_METHODS.forEach(function (method) {

    IdeaPrism.Contracts.MethodRegistry.register(Object.freeze(method));

  });


  const SYSTEMS_SUITE_IDS = Object.freeze(

    SYSTEMS_PACK_METHODS.map(function (m) {

      return m.id;

    })

  );


  function mountSystemsSuiteButton() {

    const bar = document.getElementById("method-presets");

    if (!bar || document.getElementById("preset-systems-suite-btn")) return;


    const btn = document.createElement("button");

    btn.id = "preset-systems-suite-btn";

    btn.type = "button";

    btn.className = "btn btn-ghost";

    btn.textContent = "Systems Suite (5)";

    btn.title = "Select Morphological Analysis, Leverage Points, Adjacent Possible, CECA, and Synectics";

    btn.addEventListener("click", function () {

      IdeaPrism.SessionStore.updateSessionMeta({

        selectedMethodIds: SYSTEMS_SUITE_IDS.slice()

      });

    });


    // Insert just before the trailing "Clear" button

    const clearBtn = bar.lastElementChild;

    if (clearBtn) {

      bar.insertBefore(btn, clearBtn);

    } else {

      bar.appendChild(btn);

    }

  }


  // Runs after app-shell.js populates #method-presets during DOMContentLoaded

  if (typeof window !== "undefined") {

    window.addEventListener("load", mountSystemsSuiteButton);

  }


  if (typeof module !== "undefined" && module.exports) {

    module.exports = SYSTEMS_PACK_METHODS;

  }

})(typeof window !== "undefined" ? window : globalThis);

2. Wire into index.html

Add one <script defer> line inside <head> right after js/triz-methods-pack.js:

  <script defer src="js/methods-catalog.js"></script>

  <script defer src="js/triz-methods-pack.js"></script>

  <script defer src="js/systems-methods-pack.js"></script>

Because renderPresetButtons() reads MethodRegistry.getAll() dynamically, the All button will automatically update to All (23), and Systems Suite (5) will appear right next to TRIZ Suite (7) before Clear.


From <https://gemini.google.com/app/a7d105fd4b0434d8>  Google Gemini (4 Neon)

Comments

Popular posts from this blog

#4297 ISS Astronaut Unable to Speak

#3356 PHP and JavaScript to Retrieve and Set an API_Key

#4188 Hybrid/GraphRAG