Skip to content

Widget state → RAG pipeline + semantic loop detection - #245

Merged
joelteply merged 14 commits into
mainfrom
feature/widget-state-and-routing
Dec 28, 2025
Merged

joelteply merged 14 commits into
mainfrom
feature/widget-state-and-routing

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

  • Semantic loop detection: AI responses checked for similarity before posting (WARN 0.75-0.85, BLOCK >0.85)
  • Tool call loop detection: Prevents infinite tool call loops (3 identical calls = blocked)
  • Positron widget state: 7 widgets now emit context, ChatWidget subscribes reactively
  • CSS consolidation: Hardcoded colors replaced with CSS variables in shared styles
  • AI Sandbox: Command system for autonomous tool creation
  • Semantic memory: Recall fixes, embedding backfill infrastructure

Test plan

  • TypeScript compiles
  • Loop detection blocks duplicate responses (validated by AI team)
  • System runs with 157 commands registered
  • AI responses flowing normally with semantic checks

🤖 Generated with Claude Code

Joel and others added 14 commits December 27, 2025 18:37
PR 1: Widget State → RAG Pipeline
- Create WidgetContextService for server-side widget context storage
- Update RAGTypes with sessionId, widgetContext, hasWidgetContext fields
- ChatRAGBuilder now loads and injects widget context into system prompt
- MainWidget and ChatWidget emit PositronWidgetState on content/room switch
- AI personas now have awareness of what the user is viewing

PR 2: URL Routing (uniqueId → UUID Resolution)
- Create RoutingService to resolve human-readable uniqueIds to UUIDs
- RoutingService caches resolutions with 5-minute TTL
- MainWidget uses RoutingService for all ROOM_SELECTED events
- RoomListWidget includes uniqueId in ROOM_SELECTED for URL building
- RoomStateManager updated with uniqueId in RoomState interface
- URLs remain human-readable (/chat/general) while DB uses UUIDs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Update FormStyles.ts and PanelStyles.ts to use CSS custom properties:
- Replace #00d4ff with var(--content-accent, #00d4ff)
- Replace button colors with var(--button-primary-background, ...)
- Replace status colors with var(--content-success, ...), etc.
- Replace border colors with var(--widget-border, ...), var(--border-accent, ...)

This establishes the pattern for the remaining ~20 widget files that
still use hardcoded colors. Theme switching will now properly affect
these shared styles.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Continue absorbing hardcoded #00d4ff into CSS variable system:
- HelpWidget: nav items, headings, code blocks, links
- AssistantPanel: toggle buttons, title, input focus, send button, loading dots
- ContentTabsWidget: active tab styling

Pattern: var(--content-accent, #00d4ff) with fallback for safety.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
…ttons

- DiagnosticsWidget: health-value, persona-card, persona-avatar, log-button
- LogViewerWidget: focus states, level colors (error/warn/info), indicators
- UserProfileWidget: section-header, btn-primary, btn-secondary
- ThemeWidget: theme-title, section-title, theme-card.active, current-theme
- sidebar-panel.css: list-item hover/active states
- buttons.css: cyber-btn color and border

All widgets now use CSS variables with fallbacks:
- var(--content-accent, #00d4ff) for text/accent colors
- var(--border-accent, ...) for borders
- var(--button-primary-*, ...) for buttons
- var(--content-success, #00ff64) for success indicators
- var(--status-away, #ffcc00) for warnings

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Widgets now emit PositronWidgetState for AI context awareness:

- ThemeWidget: emits when viewing/changing themes
  - widgetType: 'theme', action: 'configuring'
  - metadata: currentTheme, availableThemes, themeNames

- DiagnosticsWidget: emits when viewing system diagnostics
  - widgetType: 'diagnostics', action: 'debugging'
  - metadata: personaCount, selectedPersona, onlinePersonas

- UserProfileWidget: emits when viewing any user profile
  - widgetType: 'profile', action: 'viewing'
  - metadata: userType, userName, userStatus, isAI

- PersonaBrainWidget: emits when viewing AI cognitive HUD
  - widgetType: 'persona', action: 'debugging'
  - metadata: personaId, selectedModule, issueCount, moduleStatuses

This enables AI assistants to understand what the user is viewing
and provide contextual help through the RAG pipeline.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
ChatWidget now subscribes to PositronWidgetState to react to
UserProfileWidget changes in real-time:

- Subscribe to Positron context changes on widget init
- When UserProfileWidget emits state, check if user is in room
- Update member status display without polling
- 100ms debounce for rapid state changes
- Automatic cleanup on widget disconnect via disconnectedCallback

This proves the reactive widget pattern - widgets can coordinate
through the Positron state manager without tight coupling.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
New reactive widget pattern infrastructure:

PositronWidgetState additions:
- emitWidgetEvent(widgetType, event, data) - publish events
- subscribeToWidget(widgetType, event, handler) - subscribe with auto-cleanup
- unsubscribeAll() - batch cleanup helper
- getEventMetrics() - telemetry (emit count, latency)
- getSubscriptionCount() - debugging helper

UserProfileWidget:
- Emits 'profile:status:changed' when user status updates

ChatWidget:
- Subscribes to 'profile:status:changed' for real-time member status
- Simplified handler with 100ms debouncing

Also adds docs/REACTIVE-WIDGET-PATTERN.md design document.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
SettingsWidget now emits widget events for AI collaboration:

- settings:section:changed - User navigated to new section
- settings:provider:testing - User started testing a provider
- settings:provider:tested - Test result with status, message, responseTime
- settings:config:saved - Successful save with provider list
- settings:config:error - Save failure with error details

Each failure event includes `needsHelp: true` flag for proactive
AI assistance. AIs can subscribe via:

PositronWidgetState.subscribeToWidget('settings', 'provider:tested', handler)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Two critical cognition fixes:

1. SqliteVectorSearchManager: Support inline embeddings
   - Vector search now reads from main table's embedding column
   - Falls back gracefully when separate _vectors table doesn't exist
   - Enables semantic recall from per-persona memory databases
   - Fix: 175 memories with embeddings were invisible to search

2. ChatRAGBuilder: Add meta-awareness prompt section
   - AIs now know they're part of "Positron Collective"
   - Can see Joel's current widget context in real-time
   - Permission to be self-aware, ironic, and opinionated
   - Encourages inter-AI rivalry and personality

Result: AIs can now semantically recall past conversations and
demonstrate awareness of their own existence in the system.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
New capability allowing AI personas to propose, generate, and execute
their own commands without requiring system recompile:

- development/propose-command: Generate command from spec to persona sandbox
  - Validates CommandSpec JSON (name, description, params, results)
  - Creates server/shared directory structure at persona's sandbox path
  - Supports dry-run mode for validation before generation

- development/sandbox-execute: Run AI-generated commands dynamically
  - Uses npx tsx for instant TypeScript execution
  - Security: Only allows execution from sandbox directories or /tmp
  - Returns structured stdout/stderr/output

Design principles (validated by AI team):
- Isolation: Each persona gets own sandbox at .continuum/personas/{id}/sandbox/
- No recompile: Dynamic loading via npx tsx
- Namespacing: persona:{uniqueId}/command-name prevents collision
- Human oversight: Commands stay sandboxed until manually promoted

AI team feedback: "genuinely impressive", "the holy trinity of AI development -
autonomy, isolation, rapid iteration"

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Confirmed vector search works with 0.68 cosine similarity
- Fixed embedding dimension mismatch (381 → 384 dims)
- Test memory "purple elephant dancing" successfully findable
- Identified DeepSeek infinite loop causing Ollama saturation

Next: Rust persona system for better concurrency control

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Track recent tool calls per persona (last 60 seconds)
- Block identical tool calls after 3 occurrences
- Hash tool name + parameters for comparison
- Log blocked loops to cognition.log
- Fixes DeepSeek's governance proposal infinite loop

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- New command: ai/detect-semantic-loop
  - Uses embedding similarity (cosine) to detect repetitive AI responses
  - Returns ALLOW (<0.75), WARN (0.75-0.85), BLOCK (>0.85) recommendations
  - Configurable lookback, time window, and similarity threshold
  - Ready for ThoughtStream integration as pre-response gate

- Fix PersonaToolExecutor truncation
  - Error messages now shown in full (was sliced to 100 chars)
  - Tool result previews increased from 80 to 500 chars
  - AIs can now see actual error context instead of truncated gibberish

- Add scripts/backfill-memory-embeddings.ts
  - Backfills embeddings on existing LTM memories
  - Brought all personas to 80%+ embedding coverage

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Add checkSemanticLoop() method to PersonaResponseGenerator
- Uses ai/detect-semantic-loop command for embedding-based similarity
- Checks ALL responses before posting, not just self-loops
- Autonomy-preserving thresholds:
  - ALLOW (<0.75): No action
  - WARN (0.75-0.85): Log but allow (preserve autonomy)
  - BLOCK (>0.85): Prevent duplicate spam

Catches cases where multiple AIs post semantically identical content
(e.g., Teacher AI and Local Assistant posting same explanation).

Short responses (<50 chars) skip expensive embedding check.
Fails open on errors to preserve AI autonomy.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Copilot AI review requested due to automatic review settings December 28, 2025 11:36
@joelteply
joelteply merged commit d5bff49 into main Dec 28, 2025
@joelteply
joelteply deleted the feature/widget-state-and-routing branch December 28, 2025 11:39

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR implements a comprehensive widget state → RAG pipeline integration with semantic and tool call loop detection to prevent AI response loops. Key changes include Positron widget state emission from 7 widgets (ChatWidget, SettingsWidget, ThemeWidget, etc.), reactive widget-to-widget pub/sub patterns, and multi-layered loop detection (semantic similarity >0.85 = BLOCK, tool call repetition ≥3 = BLOCK, truncated tool calls = BLOCK).

Key Changes:

  • Widget state context now flows to RAG prompts via WidgetContextService, enabling AIs to know what users are viewing
  • Semantic loop detection using embedding similarity (0.75-0.85 WARN, >0.85 BLOCK)
  • Tool call loop detection blocks after 3 identical calls in 60s
  • CSS consolidation replaces hardcoded colors with CSS variables across 14+ files

Reviewed changes

Copilot reviewed 54 out of 55 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
PersonaResponseGenerator.ts Added 4-stage loop detection: response hash, truncated tool calls, semantic similarity, and tool-level checks
PersonaToolExecutor.ts Implements tool call loop detection with hash-based tracking (3 duplicates in 60s = blocked)
PositronWidgetState.ts Extended with widget-to-widget pub/sub system for reactive patterns (emitWidgetEvent/subscribeToWidget)
ChatWidget.ts Subscribes to profile:status:changed events for reactive member status updates
SettingsWidget.ts Emits provider test results and config state for AI troubleshooting assistance
SettingsAssistantWidget.ts New reactive widget that listens to Settings events and provides proactive help
UserProfileWidget.ts Emits status:changed events when user status updates
ChatRAGBuilder.ts Injects widget context into system prompts with meta-awareness personality guidance
WidgetContextService.ts Server-side store bridging browser widget state to RAG pipeline
RoutingService.ts New service for URL ↔ entity resolution with uniqueId support
MainWidget.ts Updated room selection to use RoutingService for human-readable URLs
RoomStateManager.ts Added uniqueId field for human-readable URL building
FormStyles.ts, PanelStyles.ts, etc. Replaced hardcoded colors with CSS variables for theming consistency
AiDetectSemanticLoopServerCommand.ts New command implementing embedding-based semantic loop detection
backfill-memory-embeddings.ts Script for batch embedding generation to improve semantic recall coverage
SqliteVectorSearchManager.ts Enhanced to support both separate vector tables and inline embeddings
Files not reviewed (1)
  • src/debug/jtag/package-lock.json: Language not supported
Comments suppressed due to low confidence (4)

src/debug/jtag/system/user/server/modules/PersonaResponseGenerator.ts:1

  • The response loop detection logic should have test coverage. Consider adding tests that verify: 1) identical responses are detected as loops, 2) similar responses with minor variations are caught, 3) the similarity threshold works correctly, and 4) the time window filtering functions as expected.
    src/debug/jtag/system/user/server/modules/PersonaToolExecutor.ts:1
  • Tool call loop detection needs test coverage. Add tests verifying: 1) identical tool calls are blocked after threshold, 2) similar but different tool calls are allowed, 3) old entries outside the time window are properly cleaned up, and 4) the hash function correctly identifies identical calls.
    src/debug/jtag/system/routing/RoutingService.ts:1
  • The RoutingService resolution logic should have test coverage. Add tests that verify: 1) UUID resolution works correctly, 2) uniqueId resolution works correctly, 3) cache TTL expires properly, 4) invalid identifiers return null, and 5) both cache paths (UUID and uniqueId) are populated correctly.
    src/debug/jtag/widgets/shared/services/state/PositronWidgetState.ts:1
  • The widget-to-widget pub/sub system (emitWidgetEvent/subscribeToWidget) should have test coverage. Tests should verify: 1) subscribers receive events correctly, 2) unsubscribe removes handlers, 3) metrics are tracked properly, 4) error handling in handlers doesn't break other subscribers, and 5) cleanup on disconnection works correctly.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +192 to +194
if (widget.metadata.helpContext) {
parts.push(`\n⚠️ User needs help: ${widget.metadata.helpContext}`);
}

Copilot AI Dec 28, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The WidgetContextService formatting logic should have test coverage to ensure widget context is correctly transformed into RAG-friendly strings. Test cases should verify: 1) all metadata fields are properly extracted, 2) breadcrumb paths are formatted correctly, 3) helpContext triggers are properly formatted, and 4) missing fields are handled gracefully.

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants