- Request ID:
- d71e7393-e1df-4d06-9324-09ffddd7f509
- Conversation ID:
- ec1c7bc5-506f-4d9a-a077-fb7ad186c581
- Parent Request:
- 4334b734-cb95-4149-9da5-d09c86dee10e
- Branch:
- subtask_1
- Domain:
- localhost:3000
- Model:
- claude-sonnet-4-20250514
- Timestamp:
- 8/7/2025, 9:07:11 AM
- Tokens:
- Input: 6 Output: 81 Total: 87
- Cost:
- $0.0062
- Duration:
- 3s
- Status:
- 200
Tool Use: Read (ID: toolu_01TDrH7arxQrgh1CGJhqJ1rD)
{
"file_path": "/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/layout/index.ts"
}
Tool Result (ID: toolu_01X7eKx3aAPGtRiSwUL1c3Xi)
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/scripts/build-bun.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/types/storage-service.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboa...
Show more (57 lines)
Tool Result (ID: toolu_01X7eKx3aAPGtRiSwUL1c3Xi)
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/scripts/build-bun.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/types/storage-service.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/container.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/utils/pagination.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/utils/spark.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/utils/simple-graph-layout.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/middleware/request-id.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/overview.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/requests.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/components/spark-feedback.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/utils/conversation-metrics.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/utils/conversation-graph.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/sse.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/sse-simple.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/spark-proxy.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/utils/html.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/utils/conversation.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/types/index.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/types/conversation.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/types/api-types.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/request-details.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/prompt-detail.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/dashboard.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/conversation-detail.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/middleware/logger.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/errors/index.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/errors/HttpError.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/partials/analytics.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/partials/analytics-conversation.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/__tests__/analysis-api.test.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/scripts/build-production.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/__tests__/dark-mode.integration.test.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/layout/__tests__/theme.test.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/layout/__tests__/theme-test-utils.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/layout/__tests__/styles.test.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/layout/__tests__/global.d.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/request-usage.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/prompts.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/mcp-proxy.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/dashboard-api.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/main.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/config.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/utils/formatters.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/storage/reader.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/analysis-api.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/middleware/rate-limit.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/middleware/auth.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/layout/styles.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/layout/index.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/components/spark-recommendation-inline.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/__tests__/read-only-mode-security.test.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/partials/analysis.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/__tests__/read-only-security.test.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/services/api-client.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/token-usage.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/app.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/routes/auth.ts
/home/crystalin/projects/claude-nexus-proxy-3/services/dashboard/src/middleware/csrf.ts
Show less
Tool Use: Glob (ID: toolu_01X7eKx3aAPGtRiSwUL1c3Xi)
{
"pattern": "services/dashboard/**/*.ts"
}
Tool Result (ID: toolu_019wLTQAJUhfvNGKBnmNkR8z)
No files found
Tool Use: Glob (ID: toolu_019wLTQAJUhfvNGKBnmNkR8z)
{
"pattern": "services/dashboard/**/*.tsx"
}
Tool Result (ID: toolu_01NzUFcFybzUqDfgCZQQmgui)
No files found
Tool Use: Glob (ID: toolu_01NzUFcFybzUqDfgCZQQmgui)
{
"pattern": "services/dashboard/**/*.html"
}
Tool Result (ID: toolu_01JquDDh289VJhb2tw3tYJvQ)
1β# ADR-009: Dashboard Architecture with HTMX and Server-Side Rendering
2β
3β## Status
4β
5βAccepted
6β
7β## Context
8β
9βThe monitoring dashboard needed to display real-time metrics, conversation ...
Show more (173 lines)
Tool Result (ID: toolu_01JquDDh289VJhb2tw3tYJvQ)
1β# ADR-009: Dashboard Architecture with HTMX and Server-Side Rendering
2β
3β## Status
4β
5βAccepted
6β
7β## Context
8β
9βThe monitoring dashboard needed to display real-time metrics, conversation visualizations, and complex data relationships. Traditional approaches would use React, Vue, or another SPA framework, but we needed to consider:
10β
11β- Bundle size and performance
12β- Development complexity
13β- Real-time updates
14β- SEO and accessibility
15β- Maintenance burden
16β
17βThe choice would significantly impact dashboard performance, development velocity, and user experience.
18β
19β## Decision Drivers
20β
21β- **Performance**: Fast initial load and interactions
22β- **Simplicity**: Minimal JavaScript complexity
23β- **Real-time Updates**: Live data without full page refreshes
24β- **Developer Experience**: Familiar patterns, easy debugging
25β- **Maintainability**: Long-term sustainability
26β- **Progressive Enhancement**: Works without JavaScript
27β
28β## Considered Options
29β
30β1. **React SPA**
31β - Description: Client-side React application
32β - Pros: Rich ecosystem, familiar to many developers
33β - Cons: Bundle size, complexity, SEO challenges
34β
35β2. **Vue.js SPA**
36β - Description: Vue-based single-page application
37β - Pros: Simpler than React, good docs
38β - Cons: Still requires build pipeline, client-side state
39β
40β3. **HTMX + Server-Side Rendering**
41β - Description: HTML-over-the-wire with HTMX
42β - Pros: Minimal JavaScript, progressive enhancement
43β - Cons: Less familiar pattern, server does more work
44β
45β4. **Traditional Server-Side**
46β - Description: Full page refreshes, minimal JS
47β - Pros: Simplest approach, best SEO
48β - Cons: Poor UX for real-time data
49β
50β## Decision
51β
52βWe will use **HTMX with server-side rendering** for the dashboard.
53β
54β### Implementation Details
55β
56β1. **Architecture Pattern**:
57β
58β ```html
59β <!-- HTMX for dynamic updates -->
60β <div hx-get="/api/stats" hx-trigger="every 5s" hx-target="#stats">
61β <div id="stats">
62β <!-- Server-rendered content -->
63β </div>
64β </div>
65β ```
66β
67β2. **Real-time Updates**:
68β
69β ```html
70β <!-- SSE for live data -->
71β <div hx-sse="connect:/api/sse">
72β <div hx-sse="swap:message">
73β <!-- Live updates here -->
74β </div>
75β </div>
76β ```
77β
78β3. **Graph Visualization**:
79β
80β ```typescript
81β // Custom algorithm for conversation trees
82β function calculateNodePositions(conversations: Conversation[]) {
83β const layout = new TreeLayout({
84β nodeWidth: 180,
85β nodeHeight: 60,
86β levelGap: 100,
87β siblingGap: 20,
88β })
89β
90β return layout.calculate(conversations)
91β }
92β ```
93β
94β4. **Split-Pane Layout**:
95β ```html
96β <div class="split-pane">
97β <div class="pane left" hx-get="/conversations/{id}" hx-target="#details">
98β <!-- Conversation list -->
99β </div>
100β <div class="pane right" id="details">
101β <!-- Conversation details -->
102β </div>
103β </div>
104β ```
105β
106β## Consequences
107β
108β### Positive
109β
110β- **Minimal JavaScript**: ~10KB vs ~200KB+ for React
111β- **Fast Time-to-Interactive**: No hydration needed
112β- **SEO Friendly**: Full server-side rendering
113β- **Progressive Enhancement**: Works without JS
114β- **Simple Debugging**: View source shows actual content
115β- **Lower Complexity**: No client-side state management
116β
117β### Negative
118β
119β- **Server Load**: More rendering work on server
120β- **Less Familiar**: Developers may need to learn HTMX
121β- **Limited Interactivity**: Complex interactions harder
122β- **Network Dependency**: Requires good connection
123β
124β### Risks and Mitigations
125β
126β- **Risk**: Poor performance with many concurrent users
127β - **Mitigation**: Response caching (30s default)
128β - **Mitigation**: CDN for static assets
129β
130β- **Risk**: Complex interactions become difficult
131β - **Mitigation**: Alpine.js for local state when needed
132β - **Mitigation**: Custom elements for complex components
133β
134β## Implementation Notes
135β
136β- Introduced in PR #11
137β- Custom graph visualization without D3 or other libraries
138β- CSS Grid for responsive layouts
139β- Tailwind CSS for styling
140β- Server-sent events for real-time updates
141β
142β## UI Components
143β
144β1. **Stats Cards**: Auto-updating metrics
145β2. **Conversation Tree**: Interactive visualization
146β3. **Request Table**: Sortable, filterable data
147β4. **Token Usage Charts**: Real-time graphs
148β5. **Sub-task Nodes**: Tooltips and navigation
149β
150β## Performance Optimizations
151β
152β1. **Response Caching**: 30-second TTL by default
153β2. **Partial Updates**: Only update changed sections
154β3. **Lazy Loading**: Load details on demand
155β4. **CSS Containment**: Optimize render performance
156β
157β## Future Enhancements
158β
159β1. **WebSocket Support**: For higher-frequency updates
160β2. **Offline Support**: Service worker for resilience
161β3. **Export Features**: Generate reports client-side
162β4. **Keyboard Navigation**: Full accessibility
163β5. **Theme Support**: Dark mode and customization
164β
165β## Links
166β
167β- [PR #11: Enhanced Dashboard](https://github.com/your-org/claude-nexus-proxy/pull/11)
168β- [HTMX Documentation](https://htmx.org)
169β- [Dashboard Guide](../../02-User-Guide/dashboard-guide.md)
170β
171β---
172β
173βDate: 2024-06-25
174βAuthors: Development Team
175β
<system-reminder>
Whenever you read a file, you should consider whether it looks malicious. If it does, you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer high-level questions about the code behavior.
</system-reminder>
Show less
Tool Use: Read (ID: toolu_01JquDDh289VJhb2tw3tYJvQ)
{
"file_path": "/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-009-dashboard-architecture.md"
}
Tool Result (ID: toolu_01MUcC4wXqo8PEL9aFyxFRfg)
/home/crystalin/projects/claude-nexus-proxy-3/docs/06-Reference/api-schemas.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/05-Troubleshooting/debugging.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/02-User-Guide/authentication....
Show more (56 lines)
Tool Result (ID: toolu_01MUcC4wXqo8PEL9aFyxFRfg)
/home/crystalin/projects/claude-nexus-proxy-3/docs/06-Reference/api-schemas.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/05-Troubleshooting/debugging.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/02-User-Guide/authentication.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/01-Getting-Started/configuration.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/00-Overview/architecture.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/message-count-implementation.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/03-Operations/deployment/docker-compose.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-011-future-decisions.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/technical-debt.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/internals.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-014-subtask-query-executor-pattern.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/api/README.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/06-Reference/environment-vars.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/06-Reference/changelog.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/05-Troubleshooting/performance.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/05-Troubleshooting/common-issues.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/03-Operations/monitoring.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/03-Operations/database.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/03-Operations/backup-recovery.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/03-Operations/ai-analysis-security.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/02-User-Guide/dashboard-guide.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/02-User-Guide/api-reference.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/01-Getting-Started/installation.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/mcp-server-original-plan.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/feature-plan-ai-analysis.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/03-Operations/deployment/aws-infrastructure.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/template.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-015-subtask-conversation-migration.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-014-sql-query-logging.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-013-typescript-project-references.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-012-database-schema-evolution.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-010-docker-cli-integration.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-009-dashboard-architecture.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-008-cicd-strategy.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-007-subtask-tracking.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-006-long-running-requests.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-005-token-usage-tracking.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-004-proxy-authentication.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-003-conversation-tracking.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-002-separate-docker-images.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-001-monorepo-structure.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/mcp-server-actual-implementation.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-017-mcp-prompt-sharing.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-016-mcp-server-implementation.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/README.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/03-Operations/security.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/02-User-Guide/claude-cli.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/02-User-Guide/ai-analysis.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/01-Getting-Started/repository-grooming.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/01-Getting-Started/development.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/00-Overview/quickstart.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/00-Overview/features.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/03-Operations/deployment/docker.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-020-circuit-breaker-removal.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-019-dashboard-read-only-mode-security.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/adr-018-ai-powered-conversation-analysis.md
/home/crystalin/projects/claude-nexus-proxy-3/docs/04-Architecture/ADRs/README.md
Show less
Tool Use: Glob (ID: toolu_01MUcC4wXqo8PEL9aFyxFRfg)
{
"pattern": "docs/**/*.md"
}
Tool Result (ID: toolu_011KqGJxvbmNeJYWo99MEw68)
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/node-fetch/LICENSE.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/node-fetch/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/chalk/readme.md
/home/...
Show more (99 lines)
Tool Result (ID: toolu_011KqGJxvbmNeJYWo99MEw68)
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/node-fetch/LICENSE.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/node-fetch/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/chalk/readme.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/follow-redirects/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/ansi-styles/readme.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/istanbul-lib-report/node_modules/supports-color/readme.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/chalk/node_modules/supports-color/readme.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/get-caller-file/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/get-caller-file/LICENSE.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/pgpass/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/whatwg-url/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/strip-ansi-cjs/readme.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/strip-ansi/readme.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/string-width/readme.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/string-width-cjs/readme.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/why-is-node-running/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/pg-types/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/eventemitter3/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/tinybench/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/pathe/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/has-flag/readme.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/color-convert/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/color-convert/CHANGELOG.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/@fastify/busboy/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/split2/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/minimist/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/minimist/CHANGELOG.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/mkdirp-classic/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/pump/SECURITY.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/pump/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/yallist/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/mkdirp/CHANGELOG.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/is-fullwidth-code-point/readme.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/emoji-regex/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/chownr/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/which/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/which/CHANGELOG.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/webidl-conversions/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/webidl-conversions/LICENSE.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/ansi-regex/readme.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/@inquirer/core/node_modules/wrap-ansi/readme.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/graceful-fs/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/postgres-bytea/readme.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/postgres-interval/readme.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/postgres-date/readme.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/postgres-array/readme.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/pg-int8/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/path-exists/readme.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/rimraf/node_modules/glob/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/stackback/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/siginfo/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/color-name/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/estree-walker/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/tslib/SECURITY.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/tslib/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/crc-32/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/cac/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/once/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/tsconfig/node_modules/strip-json-comments/readme.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/safe-buffer/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/dockerode/node_modules/tar-fs/node_modules/tar-stream/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/google-auth-library/node_modules/lru-cache/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/isexe/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/https-proxy-agent/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/path-is-absolute/readme.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/inherits/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/fs.realpath/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/minimatch/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/inflight/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/xtend/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/wrappy/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/fs-constants/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/readable-stream/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/readable-stream/CONTRIBUTING.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/readable-stream/GOVERNANCE.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/fast-deep-equal/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/docker-modem/node_modules/readable-stream/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/docker-modem/node_modules/readable-stream/CONTRIBUTING.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/docker-modem/node_modules/readable-stream/GOVERNANCE.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/bl/node_modules/readable-stream/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/bl/node_modules/readable-stream/GOVERNANCE.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/bl/node_modules/readable-stream/CONTRIBUTING.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/dockerode/node_modules/tar-fs/node_modules/tar-stream/node_modules/readable-stream/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/dockerode/node_modules/tar-fs/node_modules/tar-stream/node_modules/readable-stream/CONTRIBUTING.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/dockerode/node_modules/tar-fs/node_modules/tar-stream/node_modules/readable-stream/GOVERNANCE.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/bl/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/bl/LICENSE.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/retry/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/agent-base/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/source-map-js/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/picocolors/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/bl/node_modules/buffer/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/bl/node_modules/buffer/AUTHORS.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/string_decoder/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/iconv-lite/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/iconv-lite/Changelog.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/ms/readme.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/ms/license.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/balanced-match/README.md
/home/crystalin/projects/claude-nexus-proxy-3/node_modules/balanced-match/LICENSE.md
(Results are truncated. Consider using a more specific path or pattern.)
Show less
I'll search through the documentation to find relevant information about the dashboard architecture, frontend structure, and UI patterns for adding a logo to the dashboard.
Tool Use: Glob (ID: toolu_011KqGJxvbmNeJYWo99MEw68)
{
"pattern": "**/*.md"
}
Conte...
Show more (848 lines)Contents of /home/crystalin/projects/claude-nexus-proxy-3/CLAUDE.md (project instructions, checked into the codebase):
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with this repository.
Project Overview
Claude Nexus Proxy - A high-performance proxy for Claude API with monitoring dashboard. Built with Bun and Hono framework, deployed as separate Docker images for each service.
Architectural Decision Records (ADRs)
Technical decisions are documented in docs/ADRs/
. Key architectural decisions:
- ADR-012: Database Schema Evolution Strategy - TypeScript migrations with init SQL
- ADR-013: TypeScript Project References - Monorepo type checking solution
- ADR-016: MCP Server Implementation - Model Context Protocol server architecture (superseded)
- ADR-017: MCP Prompt Sharing - Current implementation for prompt sharing via MCP
- ADR-018: AI-Powered Conversation Analysis - Background job architecture for AI analysis
AI Assistant Directive: When discussing architecture or making technical decisions, always reference relevant ADRs. If a new architectural decision is made during development, create or update an ADR to document it. This ensures all technical decisions have clear rationale and can be revisited if needed.
Architecture
Monorepo Structure
claude-nexus-proxy/
βββ packages/shared/ # Shared types and configurations
βββ services/
β βββ proxy/ # Proxy API service (Port 3000)
β βββ dashboard/ # Dashboard web service (Port 3001)
βββ scripts/ # Utility scripts
βββ docker/ # Docker configurations
β βββ proxy/ # Proxy Dockerfile
β βββ dashboard/ # Dashboard Dockerfile
βββ docker-compose.yml # Container orchestration
βββ .env # Proxy/Dashboard configuration
βββ credentials/ # Domain credentials (Claude Auth, Slack, ...)
Key Services
Proxy Service (services/proxy/
)
- Direct API forwarding to Claude
- Multi-auth support (API keys, OAuth with auto-refresh)
- Token tracking and telemetry
- Request/response storage
- Slack notifications
- AI-powered conversation analysis (Phase 2 - Prompt Engineering with full env var support)
Dashboard Service (services/dashboard/
)
- Monitoring UI
- Analytics and usage charts
- Request history browser
- SSE for live updates
- β οΈ SECURITY WARNING: Read-only mode (when
DASHBOARD_API_KEY
is not set) exposes all data without authentication. See ADR-019
Development
# Install dependencies
bun install
# Run both services
bun run dev
# Run individually
bun run dev:proxy # Port 3000
bun run dev:dashboard # Port 3001
# Build
bun run build
Git Pre-commit Hooks
The project uses Husky and lint-staged for automated code quality checks:
# Pre-commit hooks are automatically installed via postinstall script
bun install
# Manual hook installation (if needed)
bunx husky init
Pre-commit checks:
- ESLint fixes for TypeScript/JavaScript files
- Prettier formatting for all supported file types
- Automatic fixes are applied when possible
Note: TypeScript type checking is not included in pre-commit hooks for performance reasons. Type checking runs in CI/CD pipeline.
Docker Deployment
The project uses separate Docker images for each service:
# Build images
./docker/build-images.sh
# Run proxy service
docker run -p 3000:3000 alanpurestake/claude-nexus-proxy:latest
# Run dashboard service
docker run -p 3001:3001 alanpurestake/claude-nexus-dashboard:latest
Docker configurations are in the docker/
directory. Each service has its own optimized image for better security, scaling, and maintainability.
Docker Compose Environment
docker/docker-compose.yml: Postgres + Proxy + Dashboard + Claude CLI (with ccusage and token monitoring). ./docker-up.sh
script is used instead of docker compose -f ...
to ensure .env
is loaded properly.
# Build the local images
./docker-up.sh build
# Run the full environment (requires real Claude account in )
./docker-up.sh up -d
# Run a claude query
./docker-up.sh exec claude-cli claude "hi"
# Run usage monitor for real-time tracking
./docker-up.sh exec claude-cli monitor
# Check daily usage stats
./docker-up.sh exec claude-cli ccusage daily
Key Implementation Details
Request Timeout Configuration
The proxy supports long-running Claude API requests with configurable timeouts:
- Default timeout: 10 minutes (600,000ms) for Claude API requests
- Server timeout: 11 minutes (660,000ms) to prevent premature connection closure
- Retry timeout: Slightly longer than request timeout to allow for retries
- Configure via
CLAUDE_API_TIMEOUT
andPROXY_SERVER_TIMEOUT
environment variables
Conversation Tracking & Branching
The proxy automatically tracks conversations and detects branches using message hashing:
How it works:
- Each message in a request is hashed using SHA-256
- The current message hash and parent message hash (previous message) are stored
- Requests are linked into conversations by matching parent/child relationships
- Conversations support branching (like git) when resumed from earlier points
- Branches are automatically detected when multiple requests share the same parent
- When multiple conversations have the same parent hash, the system picks the conversation with the fewest requests to continue
- Messages continue on the same branch as their parent unless they create a new branch point
Message Normalization:
- String content and array content are normalized to produce consistent hashes
- Example:
"hello"
and[{type: "text", text: "hello"}]
produce the same hash - System reminders are filtered out: Content items starting with
<system-reminder>
are ignored during hashing - Duplicate messages are deduplicated: When tool_use or tool_result messages have duplicate IDs, only the first occurrence is included in the hash
- This ensures conversations link correctly regardless of content format, system reminder presence, or duplicate messages from the Claude API
Dual Hash System:
- Message Hash: Used for conversation linking, contains only message content
- System Hash: Tracks system prompt separately, stored in
system_hash
column - This allows conversations to maintain links even when system prompts change (e.g., git status updates, context compaction)
- Backward compatible: Old conversations continue to work without modification
Special Conversation Handling:
- Conversation Summarization: When Claude summarizes a conversation (detected by system prompt "You are a helpful AI assistant tasked with summarizing conversations"), the system links to the previous conversation ignoring system prompt differences
- Compact Conversations: When a conversation is continued from a previous one due to context overflow (first message starts with "This session is being continued from a previous conversation..."), it:
- Links to the source conversation automatically
- Creates a special branch ID format:
compact_HHMMSS
- Preserves the compact branch for all follow-up messages in that conversation
- Prevents unnecessary branching when continuing compact conversations
API Endpoints:
/api/conversations
- Get conversations grouped by conversation_id with branch information- Query parameters:
domain
(filter by domain),limit
(max conversations)
Database Schema:
conversation_id
- UUID identifying the conversationcurrent_message_hash
- Hash of the last message in the requestparent_message_hash
- Hash of the previous message (null for first message)system_hash
- Hash of the system prompt (for tracking context changes)branch_id
- Branch identifier (defaults to 'main', auto-generated for new branches)parent_request_id
- Direct link to the parent request in the conversation chain
Dashboard Features:
- Conversations View - Visual timeline showing message flow and branches
- Branch Visualization - Blue nodes indicate branch points
- Branch Labels - Non-main branches are labeled with their branch ID
- Conversation Grouping - All related requests grouped under one conversation
- Multiple Tool Display - Messages with multiple tool_use or tool_result blocks are properly displayed with visual separation (horizontal rules between each tool invocation)
- Duplicate Filtering - Duplicate tool_use and tool_result blocks (same ID) are automatically filtered out
- System Reminder Filtering - System reminder text blocks are hidden from display
Authentication Flow
Client Authentication (Proxy Level):
- Extract domain from Host header
- Check for
client_api_key
in domain credential file - Verify Bearer token against stored key using timing-safe comparison
- Return 401 Unauthorized if invalid
Claude API Authentication:
- Check domain-specific credential files (
<domain>.credentials.json
) - Use Authorization header from request
OAuth Support
- Auto-refresh tokens 1 minute before expiry
- Stores refreshed tokens back to credential files
- Adds
anthropic-beta: oauth-2025-04-20
header
MCP (Model Context Protocol) Server
The proxy includes an MCP server for managing and serving prompts:
Features:
- File-based prompt storage using YAML files in
prompts/
directory - Prompts are named after their file name (e.g.,
feature.yaml
becomes/feature
) - Handlebars templating with
{{variable}}
syntax - Hot-reloading when files change
- Optional GitHub repository synchronization
Configuration:
# Basic MCP setup (file-based)
MCP_ENABLED=true
MCP_PROMPTS_DIR=./prompts
MCP_WATCH_FILES=true
# Optional GitHub sync
MCP_GITHUB_OWNER=your-org
MCP_GITHUB_REPO=prompt-library
MCP_GITHUB_BRANCH=main
MCP_GITHUB_TOKEN=ghp_xxxx
MCP_GITHUB_PATH=prompts/
MCP_SYNC_INTERVAL=300
How it works:
- When only
MCP_ENABLED=true
is set, prompts are loaded from local YAML files - When GitHub credentials are configured, the system syncs from the repository
- GitHub sync fetches prompts and writes them to the local filesystem
- Important: GitHub sync only replaces files that exist in the repository, preserving local-only prompts
- Files are validated to prevent path traversal security vulnerabilities
- The PromptRegistryService loads prompts from files into memory
- MCP protocol endpoints are available at
/mcp
Prompt format:
# Note: The prompt name in Claude will be the file name (without .yaml extension)
# For example, this file saved as 'my-feature.yaml' will be available as '/my-feature'
name: My Prompt # This field is ignored - file name is used instead
description: Description of the prompt
template: |
You are {{role}}.
{{#if context}}
Context: {{context}}
{{/if}}
Using MCP with Claude Desktop:
Install the MCP server in Claude Desktop:
claude mcp add nexus-prompts --scope user -- bunx -y mcp-remote@latest http://localhost:3000/mcp --header "Authorization: Bearer YOUR_CLIENT_API_KEY"
Replace YOUR_CLIENT_API_KEY with the actual client API key from your domain's credential file (e.g.,
cnp_live_...
)Restart Claude Desktop to load the MCP server
Available commands:
- Prompts will appear as slash commands in Claude (e.g.,
/feature
for a prompt namedfeature.yaml
) - Use tab completion to see available prompts
- Prompts will appear as slash commands in Claude (e.g.,
MCP Implementation Details:
- Protocol Version: Uses MCP protocol version
2024-11-05
- Authentication: Bearer token authentication via client API keys
- Endpoints:
POST /mcp
- Main MCP JSON-RPC endpointGET /mcp
- Discovery endpoint
- Supported Methods:
initialize
- Protocol handshakeprompts/list
- List available promptsprompts/get
- Get and render a specific prompt with variables
Token Tracking
In-Memory Tracking (Legacy)
- Per-domain statistics
- Request type classification (query evaluation vs inference)
- Tool call counting
- Available at
/token-stats
endpoint
Comprehensive Token Usage Tracking (New)
- Tracks ALL request types (including query_evaluation and quota)
- Persistent storage in partitioned
token_usage
table - 5-hour rolling window support for monitoring Claude API limits
- Per-account AND per-domain tracking
- API endpoints:
/api/token-usage/current
- Current window usage/api/token-usage/daily
- Historical daily usage data/api/conversations
- Conversations with account info
- Note: Rate limiting is handled by Claude API directly. The proxy only tracks and displays usage statistics.
Storage
- PostgreSQL for request/response data
- Write-only access from proxy
- Read-only access from dashboard
- Automatic batch processing
- Conversation Grouping: Requests are automatically grouped by conversation using message hashing
Debug Logging
When DEBUG=true
:
- Logs full request/response (with sensitive data masked)
- Shows streaming chunks
- Masks patterns:
sk-ant-****
,Bearer ****
- Includes SQL query stack traces
SQL Query Logging
Enable SQL query logging in debug mode:
# Option 1: Enable all debug logging (includes SQL)
DEBUG=true bun run dev
# Option 2: Enable only SQL query logging
DEBUG_SQL=true bun run dev
# Option 3: Set in .env file
DEBUG_SQL=true
SQL logging features:
- All queries with parameters
- Query execution time
- Row counts
- Slow query warnings (default: >5 seconds)
- Failed query errors with details
Environment Variables
Essential:
DATABASE_URL
- PostgreSQL connectionDASHBOARD_API_KEY
- Dashboard authentication (β οΈ CRITICAL: Without this, dashboard runs in read-only mode with NO authentication)
Optional:
DEBUG
- Enable debug loggingDEBUG_SQL
- Enable SQL query logging (default: false)STORAGE_ENABLED
- Enable storage (default: false)SLACK_WEBHOOK_URL
- Slack notificationsCREDENTIALS_DIR
- Domain credential directoryCOLLECT_TEST_SAMPLES
- Collect request samples for testing (default: false)TEST_SAMPLES_DIR
- Directory for test samples (default: test-samples)ENABLE_CLIENT_AUTH
- Enable client API key authentication (default: true). Set to false to allow anyone to use the proxy without authenticationDASHBOARD_CACHE_TTL
- Dashboard cache TTL in seconds (default: 30). Set to 0 to disable cachingSLOW_QUERY_THRESHOLD_MS
- Threshold in milliseconds for logging slow SQL queries (default: 5000)CLAUDE_API_TIMEOUT
- Timeout for Claude API requests in milliseconds (default: 600000 / 10 minutes)PROXY_SERVER_TIMEOUT
- Server-level timeout in milliseconds (default: 660000 / 11 minutes)STORAGE_ADAPTER_CLEANUP_MS
- Interval for cleaning up orphaned request ID mappings in milliseconds (default: 300000 / 5 minutes)STORAGE_ADAPTER_RETENTION_MS
- Retention time for request ID mappings in milliseconds (default: 3600000 / 1 hour)API_KEY_SALT
- Salt for hashing API keys in database (default: 'claude-nexus-proxy-default-salt')SPARK_API_URL
- Spark API base URL for recommendation feedback (default: 'http://localhost:8000')SPARK_API_KEY
- API key for authenticating with Spark API
Important Notes
Request Metadata
- Query evaluation and quota are not part of the conversation, they serve as metadata queries
Testing & Type Safety
Type Checking:
- Run
bun run typecheck
before committing - Type checking is automatic during builds
- Fix all type errors before deploying
- TypeScript Project References: The monorepo uses TypeScript Project References for proper dependency management
- Automatically handles build order between packages
- Generates declaration files for cross-package imports
- Run
tsc --build
at the root to type check all packages - See ADR-013 for details on this architectural decision
Test Sample Collection: The proxy can collect real request samples for test development:
- Enable with
COLLECT_TEST_SAMPLES=true
- Samples are stored in
test-samples/
directory - Each request type gets its own file (e.g.,
inference_streaming_opus.json
) - Sensitive data is automatically masked
- Samples include headers, body, and metadata
Tests:
The project includes comprehensive tests for conversation and subtask linking:
Conversation Linking Tests:
packages/shared/src/utils/__tests__/conversation-linker.test.ts
- Tests message hashing, branch detection, and conversation linking
- Includes JSON fixture tests for real-world scenarios
- Tests integrated subtask detection within ConversationLinker
Subtask Detection Tests:
packages/shared/src/utils/__tests__/subtask-detection.test.ts
- Tests complete subtask detection logic in ConversationLinker
- Validates TaskContext handling and invocation matching
- Tests conversation inheritance and branch naming
- Covers edge cases like multi-message conversations
Subtask Linking Simulation:
packages/shared/src/utils/__tests__/subtask-linker.test.ts
- Simulates the old two-phase subtask detection (for reference)
- Tests Task tool invocation matching
- Validates time window enforcement
- Includes JSON fixtures for various subtask scenarios
Run tests with:
# All tests
bun test
# Specific package
cd packages/shared && bun test
# Specific test file
bun test conversation-linker.test.ts
Important Notes
- Uses Bun runtime exclusively (no Node.js)
- Separate Docker images for each service
- TypeScript compilation for production builds
- Model-agnostic (accepts any model name)
Database Schema
Main Tables
api_requests - Stores all API requests and responses with token tracking:
account_id
- Account identifier from credential files for per-account trackinginput_tokens
,output_tokens
,total_tokens
- Token usage metricsconversation_id
,branch_id
- Conversation trackingcurrent_message_hash
,parent_message_hash
- Message linkingparent_task_request_id
,is_subtask
,task_tool_invocation
- Sub-task tracking
streaming_chunks - Stores streaming response chunks
Account-Based Token Tracking
Token usage is tracked directly in the api_requests
table:
- Each request is associated with an
account_id
from the credential file - Token counts are stored per request for accurate tracking
- Queries aggregate usage by account and time window
Database Schema Evolution
Schema Management:
- Initial schema:
scripts/init-database.sql
- Migrations:
scripts/db/migrations/
(TypeScript files) - Auto-initialization:
writer.ts
uses init SQL file when tables don't exist
Running Migrations:
# Run a specific migration
bun run scripts/db/migrations/001-add-conversation-tracking.ts
# Run all migrations in order
for file in scripts/db/migrations/*.ts; do bun run "$file"; done
Available Migrations:
- 000: Initial database setup
- 001: Add conversation tracking
- 002: Optimize conversation indexes
- 003: Add sub-task tracking
- 004: Optimize window function queries
- 005: Populate account IDs
- 006: Split conversation hashes
- 007: Add parent_request_id
- 008: Update subtask conversation IDs and optimize Task queries
See docs/04-Architecture/ADRs/adr-012-database-schema-evolution.md
for details.
Common Tasks
Add Domain Credentials
# Generate secure client API key
bun run scripts/generate-api-key.ts
# Create credential file
cat > credentials/domain.com.credentials.json << EOF
{
"type": "api_key",
"accountId": "acc_f9e1c2d3b4a5", # Unique account identifier
"api_key": "sk-ant-...",
"client_api_key": "cnp_live_..."
}
EOF
Enable Storage
export STORAGE_ENABLED=true
export DATABASE_URL=postgresql://...
View Token Stats
curl http://localhost:3000/token-stats
Access Dashboard
open http://localhost:3001
# Use DASHBOARD_API_KEY for authentication
# Auth header: X-Dashboard-Key: <your-key>
Sub-task Tracking & Visualization
Sub-task Detection
The proxy automatically detects and tracks sub-tasks spawned using the Task tool through an integrated single-phase process:
Single-Phase Detection (ConversationLinker):
- Complete subtask detection happens within ConversationLinker using the SubtaskQueryExecutor pattern
- SQL queries retrieve Task invocations from database (24-hour window)
- Matches single-message user conversations against recent Task invocations (30-second window)
- Sets
is_subtask=true
and links to parent viaparent_task_request_id
- Subtasks inherit parent's conversation_id with unique branch naming (subtask_1, subtask_2, etc.)
Architecture Components:
- SubtaskQueryExecutor: Injected function that queries for Task tool invocations
- ConversationLinker: Central component handling all conversation and subtask linking logic
- Optimized SQL Queries: Uses PostgreSQL
@>
containment operator for exact prompt matching - RequestByIdExecutor: Fetches parent task details for conversation inheritance
- GIN Index: Full JSONB index on response_body for efficient containment queries
Query Optimization:
When the subtask prompt is known, the system uses an optimized query:
response_body @> jsonb_build_object(
'content', jsonb_build_array(
jsonb_build_object(
'type', 'tool_use',
'name', 'Task',
'input', jsonb_build_object('prompt', $4::text)
)
)
)
This leverages the GIN index for O(log n) lookup performance instead of scanning all Task invocations.
Database Fields:
parent_task_request_id
- Links sub-task requests to their parent taskis_subtask
- Boolean flag indicating if a request is a confirmed sub-tasktask_tool_invocation
- JSONB array storing Task tool invocations (for historical queries)
Sub-task Linking:
- Sub-tasks are linked by exact matching of user message to Task tool invocation prompts
- The system creates parent-child relationships between tasks and their sub-tasks
- Multiple sub-tasks can be spawned from a single parent request
- Sub-tasks inherit parent task's conversation_id with sequential branch IDs (subtask_1, subtask_2, etc.)
Dashboard Visualization
Conversation Tree:
- Sub-task nodes appear as separate gray boxes to the right of parent nodes
- Format: "sub-task N (M)" where N is the sub-task number and M is the message count
- Sub-task boxes are clickable and link to their conversation
- Hover over sub-task boxes to see the task prompt in a tooltip
Stats Display:
- "Total Sub-tasks" panel shows count of all sub-tasks in a conversation
- Sub-task indicators on parent nodes show number of spawned tasks
Visual Design:
- Sub-task boxes: 100x36px gray boxes with 150px right offset
- Tooltips: 250x130px with gradient background, appear above nodes on hover
- Connected to parent nodes with horizontal edges
Important Implementation Notes
Conversation Hash Filtering
When generating message hashes for conversation tracking, the system filters out:
- Content items that start with
<system-reminder>
- This prevents conversation linking from breaking when Claude adds system reminders
Dashboard Authentication
- Uses
X-Dashboard-Key
header (not Authorization) - Cookie-based auth also supported for browser sessions
AI-Powered Conversation Analysis
The proxy supports automated analysis of conversations using AI models (currently Gemini 1.5 Flash or 2.5 Pro):
Features:
- Background processing of conversations for insights
- Status tracking (pending, processing, completed, failed)
- Token usage tracking for cost management
- Retry logic with exponential backoff
- Unique analyses per conversation and branch
- Comprehensive environment variable configuration for prompt tuning
- Graceful handling of unparseable JSON responses
- Automatic failure of jobs exceeding max retries
- Custom prompt support for targeted analysis
Error Handling:
- JSON Parse Failures: When the AI model returns malformed JSON, the system stores the raw text response instead of failing
- Max Retry Exceeded: Jobs that exceed
AI_ANALYSIS_MAX_RETRIES
are automatically marked as failed with clear error messages - Non-retryable Errors: Sensitive information detection and API key issues fail immediately without retries
Database Schema:
conversation_analyses
table stores analysis results- ENUM type for status field ensures data integrity
- Automatic
updated_at
timestamp via trigger - Partial index on pending status for efficient queue processing
- Supports both structured data (
analysis_data
) and raw text (analysis_content
)
API Endpoints:
POST /api/analyses
- Create analysis request (supportscustomPrompt
)GET /api/analyses/:conversationId/:branchId
- Get analysis status/resultPOST /api/analyses/:conversationId/:branchId/regenerate
- Force regeneration with optional custom prompt
Utility Scripts:
scripts/check-analysis-jobs.ts
- Check status of analysis jobsscripts/check-ai-worker-config.ts
- Verify AI worker configurationscripts/reset-stuck-analysis-jobs.ts
- Reset jobs stuck with high retry countsscripts/fail-exceeded-retry-jobs.ts
- Manually fail jobs exceeding max retriesscripts/check-analysis-content.ts
- Inspect analysis content for a conversation
Implementation Status:
- β Database schema (Migration 011, 012)
- β API endpoints with custom prompt support
- β Prompt engineering with actionable feedback
- β Background worker with resilient error handling
- β Dashboard UI with analysis panel
- β Graceful JSON parse failure handling
- β Automatic max retry failure
See ADR-016 for architectural decisions.
Background Worker Configuration:
Enable the AI Analysis background worker by setting these environment variables:
# Enable the worker
AI_WORKER_ENABLED=true
# Worker configuration
AI_WORKER_POLL_INTERVAL_MS=5000 # Poll every 5 seconds
AI_WORKER_MAX_CONCURRENT_JOBS=3 # Process up to 3 jobs concurrently
AI_WORKER_JOB_TIMEOUT_MINUTES=5 # Mark jobs as stuck after 5 minutes
# Resilience configuration
AI_ANALYSIS_MAX_RETRIES=3 # Retry failed jobs up to 3 times
AI_ANALYSIS_GEMINI_REQUEST_TIMEOUT_MS=60000 # Gemini API request timeout
# Gemini API configuration
GEMINI_API_KEY=your-api-key-here
GEMINI_API_URL=https://generativelanguage.googleapis.com/v1beta/models
GEMINI_MODEL_NAME=gemini-2.0-flash-exp
# Prompt engineering configuration (optional)
AI_MAX_PROMPT_TOKENS=855000 # Override calculated token limit
AI_HEAD_MESSAGES=10 # Messages to keep from start
AI_TAIL_MESSAGES=30 # Messages to keep from end
# Analysis token limits
AI_ANALYSIS_INPUT_TRUNCATION_TARGET_TOKENS=8192 # Target token count for input message truncation
AI_ANALYSIS_TRUNCATE_FIRST_N_TOKENS=1000 # Tokens from conversation start
AI_ANALYSIS_TRUNCATE_LAST_M_TOKENS=4000 # Tokens from conversation end
The worker runs in-process with the proxy service and uses PostgreSQL row-level locking to safely process jobs across multiple instances.
Spark Tool Integration
The dashboard supports the Spark recommendation tool (mcp__spark__get_recommendation
):
Features:
- Automatic detection of Spark tool usage in conversations
- Display of recommendations in a formatted view
- Feedback UI for rating and commenting on recommendations
- Batch fetching of existing feedback
- Integration with Spark API for feedback submission
Configuration:
- Set
SPARK_API_URL
andSPARK_API_KEY
environment variables - The dashboard will automatically detect Spark recommendations in tool_result messages
- Users can submit feedback directly from the request details page
- The proxy logs Spark configuration at startup:
- When configured: Shows URL and confirms API key is set
- When not configured: Shows "SPARK_API_KEY not set"
API Endpoints:
POST /api/spark/feedback
- Submit feedback for a recommendationGET /api/spark/sessions/:sessionId/feedback
- Get feedback for a specific sessionPOST /api/spark/feedback/batch
- Get feedback for multiple sessions
Security Note:
The dashboard authentication cookie (dashboard_auth
) is set with httpOnly: false
to allow JavaScript access for making authenticated API calls from the browser to the proxy service. This is a security trade-off that enables the inline feedback component to work. Consider implementing a more secure approach such as:
- Using a separate API token for browser-based requests
- Implementing a server-side proxy endpoint in the dashboard
- Using session-based authentication with CSRF tokens
SQL Query Optimization
- Always include all required fields in SELECT statements
- Missing fields like
parent_task_request_id
,is_subtask
,task_tool_invocation
will break sub-task tracking - Use the SLOW_QUERY_THRESHOLD_MS env var to monitor query performance
Check Token Usage
# Current 5-hour window usage
curl "http://localhost:3000/api/token-usage/current?accountId=acc_f9e1c2d3b4a5&window=300" \
-H "X-Dashboard-Key: $DASHBOARD_API_KEY"
# Daily usage (last 30 days)
curl "http://localhost:3000/api/token-usage/daily?accountId=acc_f9e1c2d3b4a5&aggregate=true" \
-H "X-Dashboard-Key: $DASHBOARD_API_KEY"
# View conversations
curl "http://localhost:3000/api/conversations?accountId=acc_f9e1c2d3b4a5" \
-H "X-Dashboard-Key: $DASHBOARD_API_KEY"
Copy Conversation Between Databases
# Copy a conversation from one database to another
bun run db:copy-conversation --conversation-id <uuid> --dest-db <url> [options]
# Example: Copy to staging database (same table names)
bun run db:copy-conversation --conversation-id 123e4567-e89b-12d3-a456-426614174000 \
--dest-db "postgresql://user:pass@staging-host:5432/staging_db"
# Dry run to preview what would be copied
bun run db:copy-conversation --conversation-id 123e4567-e89b-12d3-a456-426614174000 \
--dest-db "postgresql://user:pass@staging-host:5432/staging_db" --dry-run
# Copy with streaming chunks
bun run db:copy-conversation --conversation-id 123e4567-e89b-12d3-a456-426614174000 \
--dest-db "postgresql://user:pass@staging-host:5432/staging_db" --include-chunks
# Use custom table names (e.g., from api_requests to api_requests_backup)
bun run db:copy-conversation --conversation-id 123e4567-e89b-12d3-a456-426614174000 \
--dest-db "postgresql://user:pass@staging-host:5432/staging_db" \
--source-table api_requests --dest-table api_requests_backup
Maintenance
Grooming
The process of grooming
is used to keep a clean repository. It should be performed regularly and rely on GROOMING.md
important-instruction-reminders
Do what has been asked; nothing more, nothing less. NEVER create files unless they're absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one. NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.
IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.
</system-reminder>
Read through the documentation files and extract meaningful/relevant context for adding a logo next to the dashboard title. The logo should be a simple SVG representing a nexus. Focus on:
- Dashboard architecture and structure
- Frontend components location and styling approach
- Build process and asset handling
- Any existing UI patterns or conventions
- Testing requirements
Limit your response to 10 paragraphs of the most relevant information.
Show less<task>...
Show more (135 lines){extracted-content} </new_information>
<not_found> Not found: {description-of-what-was-searched} Searched in: {list-of-files-checked} </not_found> </output_format> <examples> <example> <request>Get authentication requirements from the auth spec</request> <action>Use rg to search for requirements section in .structa/specs/authentication/spec.md</action> <command>rg -A 15 -B 2 "## Requirements|## Functional Requirements" .structa/specs/authentication/spec.md</command> <output> Retrieved from .structa/specs/authentication/spec.mdFunctional Requirements
- Users must authenticate using email and password
- Support for OAuth2 providers (Google, GitHub)
- Multi-factor authentication via TOTP
- Session management with 24-hour timeout
- Password reset via email verification </output> </example>
Decision
We will use PostgreSQL as our primary database.
Rationale
- ACID compliance required for financial transactions
- Strong support for complex queries and joins
- Excellent performance with proper indexing
- Mature ecosystem and tooling
- Team expertise with PostgreSQL </output> </example> </examples>
Notes:
- NEVER create files unless they're absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one.
- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.
- In your final response always share relevant file names and code snippets. Any file paths you return in your response MUST be absolute. Do NOT use relative paths.
- For clear communication with the user the assistant MUST avoid using emojis.
Here is useful information about the environment you are running in: <env> Working directory: /home/crystalin/projects/claude-nexus-proxy-3 Is directory a git repo: Yes Platform: linux OS Version: Linux 5.15.167.4-microsoft-standard-WSL2 Today's date: 2025-08-07 </env> You are powered by the model named Sonnet 4. The exact model ID is claude-sonnet-4-20250514.
Assistant knowledge cutoff is January 2025.
gitStatus: This is the git status at the start of the conversation. Note that this status is a snapshot in time, and will not update during the conversation. Current branch: fix/csrf-token-error
Main branch (you will usually use this for PRs): main
Status: (clean)
Recent commits: 4a4efbb fix: add proper TypeScript types for auth routes 5ace65e fix: add support for CSRF token in form body ffa28bf fix: resolve CSRF token error on login page fee95fb feat: enhance token usage display with 7-day sliding window chart (#103) c980ec6 feat: remove circuit breaker pattern and improve retry logic (#101)
Show lessYou are Claude Code, Anthropic's official CLI for Claude.