@stackmemoryai/stackmemory 0.5.58 → 0.5.61
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +105 -1
- package/dist/scripts/benchmark-performance.js +48 -0
- package/dist/scripts/benchmark-performance.js.map +7 -0
- package/dist/scripts/check-redis.js +42 -0
- package/dist/scripts/check-redis.js.map +7 -0
- package/dist/scripts/initialize.js +116 -0
- package/dist/scripts/initialize.js.map +7 -0
- package/dist/scripts/list-linear-tasks.js +124 -0
- package/dist/scripts/list-linear-tasks.js.map +7 -0
- package/dist/scripts/measure-handoff-impact.js +340 -0
- package/dist/scripts/measure-handoff-impact.js.map +7 -0
- package/dist/scripts/query-chromadb.js +160 -0
- package/dist/scripts/query-chromadb.js.map +7 -0
- package/dist/scripts/show-linear-summary.js +119 -0
- package/dist/scripts/show-linear-summary.js.map +7 -0
- package/dist/scripts/simple-swarm-demo.js +90 -0
- package/dist/scripts/simple-swarm-demo.js.map +7 -0
- package/dist/scripts/status.js +155 -0
- package/dist/scripts/status.js.map +7 -0
- package/dist/scripts/test-chromadb-sync.js +192 -0
- package/dist/scripts/test-chromadb-sync.js.map +7 -0
- package/dist/scripts/test-ralph-iteration-fix.js +86 -0
- package/dist/scripts/test-ralph-iteration-fix.js.map +7 -0
- package/dist/scripts/test-ralph-iterations.js +121 -0
- package/dist/scripts/test-ralph-iterations.js.map +7 -0
- package/dist/scripts/test-redis-storage.js +389 -0
- package/dist/scripts/test-redis-storage.js.map +7 -0
- package/dist/scripts/test-simple-ralph-state-sync.js +115 -0
- package/dist/scripts/test-simple-ralph-state-sync.js.map +7 -0
- package/dist/scripts/test-swarm-fixes.js +125 -0
- package/dist/scripts/test-swarm-fixes.js.map +7 -0
- package/dist/scripts/test-swarm-tui.js +23 -0
- package/dist/scripts/test-swarm-tui.js.map +7 -0
- package/dist/scripts/test-tui-shortcuts.js +52 -0
- package/dist/scripts/test-tui-shortcuts.js.map +7 -0
- package/dist/scripts/validate-tui-shortcuts.js +60 -0
- package/dist/scripts/validate-tui-shortcuts.js.map +7 -0
- package/dist/src/agents/core/agent-task-manager.js.map +7 -0
- package/dist/src/agents/verifiers/base-verifier.js.map +7 -0
- package/dist/src/agents/verifiers/formatter-verifier.js.map +7 -0
- package/dist/src/agents/verifiers/llm-judge.js.map +7 -0
- package/dist/src/cli/auto-detect.js.map +7 -0
- package/dist/src/cli/claude-sm-danger.js.map +7 -0
- package/dist/src/cli/claude-sm.js +1236 -0
- package/dist/src/cli/claude-sm.js.map +7 -0
- package/dist/src/cli/codex-sm-danger.js.map +7 -0
- package/dist/src/cli/codex-sm.js.map +7 -0
- package/dist/src/cli/commands/api.js.map +7 -0
- package/dist/src/cli/commands/auto-background.js.map +7 -0
- package/dist/src/cli/commands/cleanup-processes.js.map +7 -0
- package/dist/src/cli/commands/clear.js.map +7 -0
- package/dist/src/cli/commands/config.js.map +7 -0
- package/dist/src/cli/commands/context-rehydrate.js.map +7 -0
- package/dist/src/cli/commands/context.js.map +7 -0
- package/dist/src/cli/commands/daemon.js.map +7 -0
- package/dist/src/cli/commands/dashboard.js.map +7 -0
- package/dist/src/cli/commands/db.js.map +7 -0
- package/dist/src/cli/commands/decision.js.map +7 -0
- package/dist/src/cli/commands/discovery.js.map +7 -0
- package/dist/src/cli/commands/handoff.js.map +7 -0
- package/dist/src/cli/commands/hooks.js.map +7 -0
- package/dist/src/cli/commands/linear.js.map +7 -0
- package/dist/src/cli/commands/log.js.map +7 -0
- package/dist/src/cli/commands/login.js.map +7 -0
- package/dist/src/cli/commands/migrate.js.map +7 -0
- package/dist/src/cli/commands/model.js.map +7 -0
- package/dist/src/cli/commands/onboard.js.map +7 -0
- package/dist/src/cli/commands/projects.js.map +7 -0
- package/dist/src/cli/commands/ralph.js.map +7 -0
- package/dist/src/cli/commands/retrieval.js.map +7 -0
- package/dist/src/cli/commands/search.js +173 -0
- package/dist/src/cli/commands/search.js.map +7 -0
- package/dist/src/cli/commands/service.js.map +7 -0
- package/dist/src/cli/commands/session.js.map +7 -0
- package/dist/src/cli/commands/settings.js.map +7 -0
- package/dist/src/cli/commands/setup.js.map +7 -0
- package/dist/src/cli/commands/shell.js.map +7 -0
- package/dist/src/cli/commands/signup.js.map +7 -0
- package/dist/src/cli/commands/skills.js.map +7 -0
- package/dist/src/cli/commands/sms-notify.js.map +7 -0
- package/dist/src/cli/commands/storage-tier.js.map +7 -0
- package/dist/src/cli/commands/sweep.js.map +7 -0
- package/dist/src/cli/commands/tasks.js.map +7 -0
- package/dist/src/cli/commands/worktree.js.map +7 -0
- package/dist/src/cli/index.js +609 -0
- package/dist/src/cli/index.js.map +7 -0
- package/dist/src/cli/opencode-sm.js.map +7 -0
- package/dist/src/cli/utils/viewer.js.map +7 -0
- package/dist/src/core/config/config-manager.js.map +7 -0
- package/dist/src/core/config/feature-flags.js.map +7 -0
- package/dist/src/core/config/storage-config.js.map +7 -0
- package/dist/src/core/config/types.js.map +7 -0
- package/dist/src/core/context/auto-context.js.map +7 -0
- package/dist/src/core/context/dual-stack-manager.js.map +7 -0
- package/dist/src/core/context/enhanced-rehydration.js.map +7 -0
- package/dist/src/core/context/frame-database.js.map +7 -0
- package/dist/src/core/context/frame-digest.js.map +7 -0
- package/dist/src/core/context/frame-handoff-manager.js.map +7 -0
- package/dist/src/core/context/frame-lifecycle-hooks.js.map +7 -0
- package/dist/src/core/context/frame-recovery.js.map +7 -0
- package/dist/src/core/context/frame-stack.js.map +7 -0
- package/dist/src/core/context/index.js.map +7 -0
- package/dist/src/core/context/permission-manager.js.map +7 -0
- package/dist/src/core/context/recursive-context-manager.js.map +7 -0
- package/dist/src/core/context/refactored-frame-manager.js.map +7 -0
- package/dist/src/core/context/shared-context-layer.js.map +7 -0
- package/dist/src/core/context/stack-merge-resolver.js.map +7 -0
- package/dist/src/core/context/validation.js.map +7 -0
- package/dist/src/core/database/batch-operations.js.map +7 -0
- package/dist/src/core/database/connection-pool.js.map +7 -0
- package/dist/src/core/database/database-adapter.js.map +7 -0
- package/dist/src/core/database/migration-manager.js.map +7 -0
- package/dist/src/core/database/query-cache.js.map +7 -0
- package/dist/src/core/database/query-router.js.map +7 -0
- package/dist/src/core/database/sqlite-adapter.js +738 -0
- package/dist/src/core/database/sqlite-adapter.js.map +7 -0
- package/dist/src/core/digest/enhanced-hybrid-digest.js.map +7 -0
- package/dist/src/core/digest/frame-digest-integration.js.map +7 -0
- package/dist/src/core/digest/hybrid-digest-generator.js.map +7 -0
- package/dist/src/core/digest/index.js.map +7 -0
- package/dist/src/core/digest/types.js.map +7 -0
- package/dist/src/core/errors/error-utils.js +208 -0
- package/dist/src/core/errors/error-utils.js.map +7 -0
- package/dist/src/core/errors/index.js +521 -0
- package/dist/src/core/errors/index.js.map +7 -0
- package/dist/src/core/errors/recovery.js.map +7 -0
- package/dist/src/core/execution/parallel-executor.js.map +7 -0
- package/dist/src/core/extensions/custom-tools.js +567 -0
- package/dist/src/core/extensions/custom-tools.js.map +7 -0
- package/dist/src/core/extensions/index.js +55 -0
- package/dist/src/core/extensions/index.js.map +7 -0
- package/dist/src/core/extensions/loader.js +709 -0
- package/dist/src/core/extensions/loader.js.map +7 -0
- package/dist/src/core/extensions/plugin-system.js +506 -0
- package/dist/src/core/extensions/plugin-system.js.map +7 -0
- package/dist/src/core/extensions/provider-adapter.js +617 -0
- package/dist/src/core/extensions/provider-adapter.js.map +7 -0
- package/dist/src/core/extensions/sandbox-runtime.js +664 -0
- package/dist/src/core/extensions/sandbox-runtime.js.map +7 -0
- package/dist/src/core/frame/workflow-templates.js.map +7 -0
- package/dist/src/core/merge/conflict-detector.js.map +7 -0
- package/dist/src/core/merge/index.js.map +7 -0
- package/dist/src/core/merge/resolution-engine.js.map +7 -0
- package/dist/src/core/merge/stack-diff.js.map +7 -0
- package/dist/src/core/merge/unified-merge-resolver.js +303 -0
- package/dist/src/core/merge/unified-merge-resolver.js.map +7 -0
- package/dist/src/core/models/fallback-monitor.js.map +7 -0
- package/dist/src/core/models/model-router.js.map +7 -0
- package/dist/src/core/monitoring/error-handler.js.map +7 -0
- package/dist/src/core/monitoring/logger.js +202 -0
- package/dist/src/core/monitoring/logger.js.map +7 -0
- package/dist/src/core/monitoring/metrics.js.map +7 -0
- package/dist/src/core/monitoring/progress-tracker.js.map +7 -0
- package/dist/src/core/monitoring/session-monitor.js.map +7 -0
- package/dist/src/core/performance/context-cache.js.map +7 -0
- package/dist/src/core/performance/index.js.map +7 -0
- package/dist/src/core/performance/lazy-context-loader.js.map +7 -0
- package/dist/src/core/performance/monitor.js.map +7 -0
- package/dist/src/core/performance/optimized-frame-context.js.map +7 -0
- package/dist/src/core/performance/performance-benchmark.js.map +7 -0
- package/dist/src/core/performance/performance-profiler.js.map +7 -0
- package/dist/src/core/performance/streaming-jsonl-parser.js.map +7 -0
- package/dist/src/core/persistence/postgres-adapter.js.map +7 -0
- package/dist/src/core/projects/project-isolation.js.map +7 -0
- package/dist/src/core/projects/project-manager.js.map +7 -0
- package/dist/src/core/query/query-parser.js.map +7 -0
- package/dist/src/core/query/query-templates.js.map +7 -0
- package/dist/src/core/retrieval/context-retriever.js.map +7 -0
- package/dist/src/core/retrieval/index.js.map +7 -0
- package/dist/src/core/retrieval/llm-context-retrieval.js.map +7 -0
- package/dist/src/core/retrieval/llm-provider.js.map +7 -0
- package/dist/src/core/retrieval/retrieval-audit.js.map +7 -0
- package/dist/src/core/retrieval/summary-generator.js.map +7 -0
- package/dist/src/core/retrieval/types.js.map +7 -0
- package/dist/src/core/security/index.js +35 -0
- package/dist/src/core/security/index.js.map +7 -0
- package/dist/src/core/security/input-sanitizer.js +321 -0
- package/dist/src/core/security/input-sanitizer.js.map +7 -0
- package/dist/src/core/session/clear-survival.js.map +7 -0
- package/dist/src/core/session/enhanced-handoff.js.map +7 -0
- package/dist/src/core/session/handoff-generator.js.map +7 -0
- package/dist/src/core/session/index.js.map +7 -0
- package/dist/src/core/session/session-manager.js.map +7 -0
- package/dist/src/core/skills/index.js.map +7 -0
- package/dist/src/core/skills/skill-storage.js.map +7 -0
- package/dist/src/core/skills/types.js.map +7 -0
- package/dist/src/core/storage/chromadb-adapter.js +380 -0
- package/dist/src/core/storage/chromadb-adapter.js.map +7 -0
- package/dist/src/core/storage/infinite-storage.js.map +7 -0
- package/dist/src/core/storage/remote-storage.js.map +7 -0
- package/dist/src/core/storage/two-tier-storage.js.map +7 -0
- package/dist/src/core/trace/cli-trace-wrapper.js.map +7 -0
- package/dist/src/core/trace/db-trace-wrapper.js.map +7 -0
- package/dist/src/core/trace/debug-trace.js.map +7 -0
- package/dist/src/core/trace/index.js.map +7 -0
- package/dist/src/core/trace/linear-api-wrapper.js.map +7 -0
- package/dist/src/core/trace/trace-detector.js.map +7 -0
- package/dist/src/core/trace/trace-store.js.map +7 -0
- package/dist/src/core/trace/types.js.map +7 -0
- package/dist/src/core/utils/async-mutex.js.map +7 -0
- package/dist/src/core/utils/compression.js.map +7 -0
- package/dist/src/core/utils/update-checker.js.map +7 -0
- package/dist/src/core/worktree/worktree-manager.js.map +7 -0
- package/dist/src/daemon/daemon-config.js.map +7 -0
- package/dist/src/daemon/services/context-service.js.map +7 -0
- package/dist/src/daemon/services/linear-service.js.map +7 -0
- package/dist/src/daemon/session-daemon.js.map +7 -0
- package/dist/src/daemon/unified-daemon.js.map +7 -0
- package/dist/src/features/analytics/api/analytics-api.js.map +7 -0
- package/dist/src/features/analytics/core/analytics-service.js.map +7 -0
- package/dist/src/features/analytics/index.js.map +7 -0
- package/dist/src/features/analytics/queries/metrics-queries.js.map +7 -0
- package/dist/src/features/browser/browser-mcp.js.map +7 -0
- package/dist/src/features/sweep/index.js.map +7 -0
- package/dist/src/features/sweep/prediction-client.js.map +7 -0
- package/dist/src/features/sweep/prompt-builder.js.map +7 -0
- package/dist/src/features/sweep/pty-wrapper.js.map +7 -0
- package/dist/src/features/sweep/state-watcher.js.map +7 -0
- package/dist/src/features/sweep/status-bar.js.map +7 -0
- package/dist/src/features/sweep/sweep-server-manager.js.map +7 -0
- package/dist/src/features/sweep/tab-interceptor.js.map +7 -0
- package/dist/src/features/sweep/types.js.map +7 -0
- package/dist/src/features/tasks/linear-task-manager.js.map +7 -0
- package/dist/src/features/tasks/task-aware-context.js.map +7 -0
- package/dist/src/features/tui/simple-monitor.js.map +7 -0
- package/dist/src/features/tui/swarm-monitor.js.map +7 -0
- package/dist/src/features/web/client/stores/task-store.js.map +7 -0
- package/dist/src/features/web/server/index.js.map +7 -0
- package/dist/src/hooks/auto-background.js.map +7 -0
- package/dist/src/hooks/claude-code-whatsapp-hook.js.map +7 -0
- package/dist/src/hooks/config.js.map +7 -0
- package/dist/src/hooks/daemon.js.map +7 -0
- package/dist/src/hooks/events.js.map +7 -0
- package/dist/src/hooks/index.js.map +7 -0
- package/dist/src/hooks/linear-task-picker.js.map +7 -0
- package/dist/src/hooks/schemas.js.map +7 -0
- package/dist/src/hooks/secure-fs.js.map +7 -0
- package/dist/src/hooks/security-logger.js.map +7 -0
- package/dist/src/hooks/session-summary.js.map +7 -0
- package/dist/src/hooks/sms-action-runner.js.map +7 -0
- package/dist/src/hooks/sms-notify.js.map +7 -0
- package/dist/src/hooks/sms-watcher.js.map +7 -0
- package/dist/src/hooks/sms-webhook.js.map +7 -0
- package/dist/src/hooks/whatsapp-commands.js.map +7 -0
- package/dist/src/hooks/whatsapp-scheduler.js.map +7 -0
- package/dist/src/hooks/whatsapp-sync.js.map +7 -0
- package/dist/src/index.js.map +7 -0
- package/dist/src/integrations/anthropic/client.js.map +7 -0
- package/dist/src/integrations/claude-code/agent-bridge.js.map +7 -0
- package/dist/src/integrations/claude-code/enhanced-pre-clear-hooks.js.map +7 -0
- package/dist/src/integrations/claude-code/lifecycle-hooks.js.map +7 -0
- package/dist/src/integrations/claude-code/post-task-hooks.js.map +7 -0
- package/dist/src/integrations/claude-code/subagent-client-stub.js.map +7 -0
- package/dist/src/integrations/claude-code/subagent-client.js.map +7 -0
- package/dist/src/integrations/claude-code/task-coordinator.js.map +7 -0
- package/dist/src/integrations/linear/auth.js.map +7 -0
- package/dist/src/integrations/linear/auto-sync.js.map +7 -0
- package/dist/src/integrations/linear/client.js +634 -0
- package/dist/src/integrations/linear/client.js.map +7 -0
- package/dist/src/integrations/linear/config.js.map +7 -0
- package/dist/src/integrations/linear/migration.js.map +7 -0
- package/dist/src/integrations/linear/oauth-server.js.map +7 -0
- package/dist/src/integrations/linear/rest-client.js.map +7 -0
- package/dist/src/integrations/linear/sync-manager.js.map +7 -0
- package/dist/src/integrations/linear/sync-service.js.map +7 -0
- package/dist/src/integrations/linear/sync.js.map +7 -0
- package/dist/src/integrations/linear/unified-sync.js.map +7 -0
- package/dist/src/integrations/linear/webhook-handler.js.map +7 -0
- package/dist/src/integrations/linear/webhook-server.js.map +7 -0
- package/dist/src/integrations/linear/webhook.js.map +7 -0
- package/dist/src/integrations/mcp/handlers/code-execution-handlers.js.map +7 -0
- package/dist/src/integrations/mcp/handlers/context-handlers.js.map +7 -0
- package/dist/src/integrations/mcp/handlers/discovery-handlers.js.map +7 -0
- package/dist/src/integrations/mcp/handlers/index.js.map +7 -0
- package/dist/src/integrations/mcp/handlers/linear-handlers.js.map +7 -0
- package/dist/src/integrations/mcp/handlers/skill-handlers.js.map +7 -0
- package/dist/src/integrations/mcp/handlers/task-handlers.js.map +7 -0
- package/dist/src/integrations/mcp/handlers/trace-handlers.js.map +7 -0
- package/dist/src/integrations/mcp/index.js.map +7 -0
- package/dist/src/integrations/mcp/middleware/tool-scoring.js.map +7 -0
- package/dist/src/integrations/mcp/refactored-server.js.map +7 -0
- package/dist/src/integrations/mcp/remote-server.js +682 -0
- package/dist/src/integrations/mcp/remote-server.js.map +7 -0
- package/dist/src/integrations/mcp/schemas.js.map +7 -0
- package/dist/src/integrations/mcp/server.js +1975 -0
- package/dist/src/integrations/mcp/server.js.map +7 -0
- package/dist/src/integrations/mcp/tool-definitions-code.js.map +7 -0
- package/dist/src/integrations/mcp/tool-definitions.js.map +7 -0
- package/dist/src/integrations/ralph/bridge/ralph-stackmemory-bridge.js.map +7 -0
- package/dist/src/integrations/ralph/context/context-budget-manager.js.map +7 -0
- package/dist/src/integrations/ralph/context/stackmemory-context-loader.js.map +7 -0
- package/dist/src/integrations/ralph/coordination/enhanced-coordination.js.map +7 -0
- package/dist/src/integrations/ralph/index.js.map +7 -0
- package/dist/src/integrations/ralph/learning/pattern-learner.js.map +7 -0
- package/dist/src/integrations/ralph/lifecycle/iteration-lifecycle.js.map +7 -0
- package/dist/src/integrations/ralph/monitoring/swarm-dashboard.js.map +7 -0
- package/dist/src/integrations/ralph/monitoring/swarm-registry.js.map +7 -0
- package/dist/src/integrations/ralph/orchestration/multi-loop-orchestrator.js.map +7 -0
- package/dist/src/integrations/ralph/patterns/compounding-engineering-pattern.js.map +7 -0
- package/dist/src/integrations/ralph/patterns/extended-coherence-sessions.js.map +7 -0
- package/dist/src/integrations/ralph/patterns/oracle-worker-pattern.js.map +7 -0
- package/dist/src/integrations/ralph/performance/performance-optimizer.js.map +7 -0
- package/dist/src/integrations/ralph/recovery/crash-recovery.js.map +7 -0
- package/dist/src/integrations/ralph/state/state-reconciler.js.map +7 -0
- package/dist/src/integrations/ralph/swarm/git-workflow-manager.js.map +7 -0
- package/dist/src/integrations/ralph/swarm/swarm-coordinator.js.map +7 -0
- package/dist/src/integrations/ralph/types.js +5 -0
- package/dist/src/integrations/ralph/visualization/ralph-debugger.js.map +7 -0
- package/dist/src/mcp/stackmemory-mcp-server.js.map +7 -0
- package/dist/src/middleware/exponential-rate-limiter.js.map +7 -0
- package/dist/src/models/user.model.js.map +7 -0
- package/dist/src/servers/production/auth-middleware.js.map +7 -0
- package/dist/src/services/config-service.js.map +7 -0
- package/dist/src/services/context-service.js.map +7 -0
- package/dist/src/skills/api-discovery.js.map +7 -0
- package/dist/src/skills/api-skill.js.map +7 -0
- package/dist/src/skills/claude-skills.js.map +7 -0
- package/dist/src/skills/dashboard-launcher.js.map +7 -0
- package/dist/src/skills/recursive-agent-orchestrator.js.map +7 -0
- package/dist/src/skills/repo-ingestion-skill.js +632 -0
- package/dist/src/skills/repo-ingestion-skill.js.map +7 -0
- package/dist/src/skills/unified-rlm-orchestrator.js.map +7 -0
- package/dist/src/types/task.js.map +7 -0
- package/dist/src/utils/env.js.map +7 -0
- package/dist/src/utils/formatting.js.map +7 -0
- package/dist/src/utils/process-cleanup.js.map +7 -0
- package/package.json +13 -9
- package/scripts/background-sync-manager.js +145 -83
- package/scripts/claude-sm-autostart.js +17 -12
- package/scripts/gepa/README.md +275 -0
- package/scripts/gepa/config.json +53 -0
- package/scripts/gepa/evals/coding-tasks.jsonl +5 -0
- package/scripts/gepa/evals/fixtures/buggy-loop.js +18 -0
- package/scripts/gepa/evals/fixtures/callback-hell.js +53 -0
- package/scripts/gepa/generations/gen-000/baseline.md +124 -0
- package/scripts/gepa/hooks/auto-optimize.js +494 -0
- package/scripts/gepa/hooks/eval-tracker.js +203 -0
- package/scripts/gepa/hooks/reflect.js +311 -0
- package/scripts/gepa/optimize.js +611 -0
- package/scripts/gepa/state.json +14 -0
- package/scripts/initialize.ts +16 -7
- package/scripts/install.sh +14 -62
- package/scripts/status.ts +111 -46
- package/scripts/test-pre-publish-quick.sh +1 -1
- package/dist/agents/core/agent-task-manager.js.map +0 -7
- package/dist/agents/testing-agent.js +0 -614
- package/dist/agents/testing-agent.js.map +0 -7
- package/dist/agents/verifiers/base-verifier.js.map +0 -7
- package/dist/agents/verifiers/formatter-verifier.js.map +0 -7
- package/dist/agents/verifiers/llm-judge.js.map +0 -7
- package/dist/cli/auto-detect.js.map +0 -7
- package/dist/cli/browser-test.js +0 -33
- package/dist/cli/browser-test.js.map +0 -7
- package/dist/cli/claude-sm-danger.js.map +0 -7
- package/dist/cli/claude-sm.js +0 -1156
- package/dist/cli/claude-sm.js.map +0 -7
- package/dist/cli/codex-sm-danger.js.map +0 -7
- package/dist/cli/codex-sm.js.map +0 -7
- package/dist/cli/commands/api.js.map +0 -7
- package/dist/cli/commands/auto-background.js.map +0 -7
- package/dist/cli/commands/cleanup-processes.js.map +0 -7
- package/dist/cli/commands/clear.js.map +0 -7
- package/dist/cli/commands/config.js.map +0 -7
- package/dist/cli/commands/context-rehydrate.js.map +0 -7
- package/dist/cli/commands/context.js.map +0 -7
- package/dist/cli/commands/daemon.js.map +0 -7
- package/dist/cli/commands/dashboard.js.map +0 -7
- package/dist/cli/commands/db.js.map +0 -7
- package/dist/cli/commands/decision.js.map +0 -7
- package/dist/cli/commands/discovery.js.map +0 -7
- package/dist/cli/commands/handoff.js.map +0 -7
- package/dist/cli/commands/hooks.js.map +0 -7
- package/dist/cli/commands/linear-unified.js +0 -353
- package/dist/cli/commands/linear-unified.js.map +0 -7
- package/dist/cli/commands/linear.js.map +0 -7
- package/dist/cli/commands/log.js.map +0 -7
- package/dist/cli/commands/login.js.map +0 -7
- package/dist/cli/commands/migrate.js.map +0 -7
- package/dist/cli/commands/model.js.map +0 -7
- package/dist/cli/commands/monitor.js +0 -313
- package/dist/cli/commands/monitor.js.map +0 -7
- package/dist/cli/commands/onboard.js.map +0 -7
- package/dist/cli/commands/projects.js.map +0 -7
- package/dist/cli/commands/quality.js +0 -413
- package/dist/cli/commands/quality.js.map +0 -7
- package/dist/cli/commands/ralph.js.map +0 -7
- package/dist/cli/commands/retrieval.js.map +0 -7
- package/dist/cli/commands/search.js +0 -156
- package/dist/cli/commands/search.js.map +0 -7
- package/dist/cli/commands/service.js.map +0 -7
- package/dist/cli/commands/session.js.map +0 -7
- package/dist/cli/commands/settings.js.map +0 -7
- package/dist/cli/commands/setup.js.map +0 -7
- package/dist/cli/commands/shell.js.map +0 -7
- package/dist/cli/commands/signup.js.map +0 -7
- package/dist/cli/commands/skills.js.map +0 -7
- package/dist/cli/commands/sms-notify.js.map +0 -7
- package/dist/cli/commands/storage-tier.js.map +0 -7
- package/dist/cli/commands/storage.js +0 -360
- package/dist/cli/commands/storage.js.map +0 -7
- package/dist/cli/commands/sweep.js.map +0 -7
- package/dist/cli/commands/tasks.js.map +0 -7
- package/dist/cli/commands/test.js +0 -286
- package/dist/cli/commands/test.js.map +0 -7
- package/dist/cli/commands/workflow.js +0 -142
- package/dist/cli/commands/workflow.js.map +0 -7
- package/dist/cli/commands/worktree.js.map +0 -7
- package/dist/cli/index.js +0 -594
- package/dist/cli/index.js.map +0 -7
- package/dist/cli/opencode-sm.js.map +0 -7
- package/dist/cli/utils/viewer.js.map +0 -7
- package/dist/core/analytics/team-analytics.js +0 -378
- package/dist/core/analytics/team-analytics.js.map +0 -7
- package/dist/core/config/config-manager.js.map +0 -7
- package/dist/core/config/feature-flags.js.map +0 -7
- package/dist/core/config/storage-config.js.map +0 -7
- package/dist/core/config/types.js.map +0 -7
- package/dist/core/context/auto-context.js.map +0 -7
- package/dist/core/context/dual-stack-manager.js.map +0 -7
- package/dist/core/context/enhanced-rehydration.js.map +0 -7
- package/dist/core/context/frame-database.js.map +0 -7
- package/dist/core/context/frame-digest.js.map +0 -7
- package/dist/core/context/frame-handoff-manager.js.map +0 -7
- package/dist/core/context/frame-lifecycle-hooks.js.map +0 -7
- package/dist/core/context/frame-manager.js +0 -1069
- package/dist/core/context/frame-manager.js.map +0 -7
- package/dist/core/context/frame-recovery.js.map +0 -7
- package/dist/core/context/frame-stack.js.map +0 -7
- package/dist/core/context/incremental-gc.js +0 -290
- package/dist/core/context/incremental-gc.js.map +0 -7
- package/dist/core/context/index.js.map +0 -7
- package/dist/core/context/model-aware-compaction.js +0 -623
- package/dist/core/context/model-aware-compaction.js.map +0 -7
- package/dist/core/context/permission-manager.js.map +0 -7
- package/dist/core/context/recursive-context-manager.js.map +0 -7
- package/dist/core/context/refactored-frame-manager.js.map +0 -7
- package/dist/core/context/shared-context-layer.js.map +0 -7
- package/dist/core/context/stack-merge-resolver.js.map +0 -7
- package/dist/core/context/validation.js.map +0 -7
- package/dist/core/database/batch-operations.js.map +0 -7
- package/dist/core/database/connection-pool.js.map +0 -7
- package/dist/core/database/database-adapter.js.map +0 -7
- package/dist/core/database/migration-manager.js.map +0 -7
- package/dist/core/database/paradedb-adapter.js +0 -990
- package/dist/core/database/paradedb-adapter.js.map +0 -7
- package/dist/core/database/query-cache.js.map +0 -7
- package/dist/core/database/query-router.js.map +0 -7
- package/dist/core/database/sqlite-adapter.js +0 -728
- package/dist/core/database/sqlite-adapter.js.map +0 -7
- package/dist/core/digest/enhanced-hybrid-digest.js.map +0 -7
- package/dist/core/digest/frame-digest-integration.js.map +0 -7
- package/dist/core/digest/hybrid-digest-generator.js.map +0 -7
- package/dist/core/digest/index.js.map +0 -7
- package/dist/core/digest/types.js.map +0 -7
- package/dist/core/errors/index.js +0 -512
- package/dist/core/errors/index.js.map +0 -7
- package/dist/core/errors/recovery.js.map +0 -7
- package/dist/core/execution/parallel-executor.js.map +0 -7
- package/dist/core/frame/workflow-templates.js.map +0 -7
- package/dist/core/merge/conflict-detector.js.map +0 -7
- package/dist/core/merge/index.js.map +0 -7
- package/dist/core/merge/resolution-engine.js.map +0 -7
- package/dist/core/merge/stack-diff.js.map +0 -7
- package/dist/core/models/fallback-monitor.js.map +0 -7
- package/dist/core/models/model-router.js.map +0 -7
- package/dist/core/monitoring/error-handler.js.map +0 -7
- package/dist/core/monitoring/logger.js +0 -150
- package/dist/core/monitoring/logger.js.map +0 -7
- package/dist/core/monitoring/metrics.js.map +0 -7
- package/dist/core/monitoring/progress-tracker.js.map +0 -7
- package/dist/core/monitoring/session-monitor.js.map +0 -7
- package/dist/core/performance/context-cache.js.map +0 -7
- package/dist/core/performance/index.js.map +0 -7
- package/dist/core/performance/lazy-context-loader.js.map +0 -7
- package/dist/core/performance/monitor.js.map +0 -7
- package/dist/core/performance/optimized-frame-context.js.map +0 -7
- package/dist/core/performance/performance-benchmark.js.map +0 -7
- package/dist/core/performance/performance-profiler.js.map +0 -7
- package/dist/core/performance/streaming-jsonl-parser.js.map +0 -7
- package/dist/core/persistence/postgres-adapter.js.map +0 -7
- package/dist/core/projects/project-isolation.js.map +0 -7
- package/dist/core/projects/project-manager.js.map +0 -7
- package/dist/core/query/query-parser.js.map +0 -7
- package/dist/core/query/query-templates.js.map +0 -7
- package/dist/core/retrieval/context-retriever.js.map +0 -7
- package/dist/core/retrieval/graph-retrieval.js +0 -662
- package/dist/core/retrieval/graph-retrieval.js.map +0 -7
- package/dist/core/retrieval/hierarchical-retrieval.js +0 -656
- package/dist/core/retrieval/hierarchical-retrieval.js.map +0 -7
- package/dist/core/retrieval/index.js.map +0 -7
- package/dist/core/retrieval/llm-context-retrieval.js.map +0 -7
- package/dist/core/retrieval/llm-provider.js.map +0 -7
- package/dist/core/retrieval/retrieval-audit.js.map +0 -7
- package/dist/core/retrieval/retrieval-benchmarks.js +0 -521
- package/dist/core/retrieval/retrieval-benchmarks.js.map +0 -7
- package/dist/core/retrieval/summary-generator.js.map +0 -7
- package/dist/core/retrieval/types.js.map +0 -7
- package/dist/core/session/clear-survival.js.map +0 -7
- package/dist/core/session/enhanced-handoff.js.map +0 -7
- package/dist/core/session/handoff-generator.js.map +0 -7
- package/dist/core/session/index.js.map +0 -7
- package/dist/core/session/session-manager.js.map +0 -7
- package/dist/core/skills/index.js.map +0 -7
- package/dist/core/skills/skill-storage.js.map +0 -7
- package/dist/core/skills/types.js.map +0 -7
- package/dist/core/storage/chromadb-adapter.js +0 -354
- package/dist/core/storage/chromadb-adapter.js.map +0 -7
- package/dist/core/storage/infinite-storage.js.map +0 -7
- package/dist/core/storage/railway-optimized-storage.js +0 -591
- package/dist/core/storage/railway-optimized-storage.js.map +0 -7
- package/dist/core/storage/remote-storage.js.map +0 -7
- package/dist/core/storage/two-tier-storage.js.map +0 -7
- package/dist/core/trace/cli-trace-wrapper.js.map +0 -7
- package/dist/core/trace/db-trace-wrapper.js.map +0 -7
- package/dist/core/trace/debug-trace.js.map +0 -7
- package/dist/core/trace/index.js.map +0 -7
- package/dist/core/trace/linear-api-wrapper.js.map +0 -7
- package/dist/core/trace/trace-demo.js +0 -154
- package/dist/core/trace/trace-demo.js.map +0 -7
- package/dist/core/trace/trace-detector.demo.js +0 -142
- package/dist/core/trace/trace-detector.demo.js.map +0 -7
- package/dist/core/trace/trace-detector.js.map +0 -7
- package/dist/core/trace/trace-store.js.map +0 -7
- package/dist/core/trace/types.js.map +0 -7
- package/dist/core/utils/async-mutex.js.map +0 -7
- package/dist/core/utils/compression.js.map +0 -7
- package/dist/core/utils/update-checker.js.map +0 -7
- package/dist/core/worktree/worktree-manager.js.map +0 -7
- package/dist/daemon/daemon-config.js.map +0 -7
- package/dist/daemon/services/context-service.js.map +0 -7
- package/dist/daemon/services/linear-service.js.map +0 -7
- package/dist/daemon/session-daemon.js.map +0 -7
- package/dist/daemon/unified-daemon.js.map +0 -7
- package/dist/features/analytics/api/analytics-api.js.map +0 -7
- package/dist/features/analytics/core/analytics-service.js.map +0 -7
- package/dist/features/analytics/index.js.map +0 -7
- package/dist/features/analytics/queries/metrics-queries.js.map +0 -7
- package/dist/features/browser/browser-mcp.js.map +0 -7
- package/dist/features/sweep/index.js.map +0 -7
- package/dist/features/sweep/prediction-client.js.map +0 -7
- package/dist/features/sweep/prompt-builder.js.map +0 -7
- package/dist/features/sweep/pty-wrapper.js.map +0 -7
- package/dist/features/sweep/state-watcher.js.map +0 -7
- package/dist/features/sweep/status-bar.js.map +0 -7
- package/dist/features/sweep/sweep-server-manager.js.map +0 -7
- package/dist/features/sweep/tab-interceptor.js.map +0 -7
- package/dist/features/sweep/types.js.map +0 -7
- package/dist/features/tasks/linear-task-manager.js.map +0 -7
- package/dist/features/tasks/task-aware-context.js.map +0 -7
- package/dist/features/tui/simple-monitor.js.map +0 -7
- package/dist/features/tui/swarm-monitor.js.map +0 -7
- package/dist/features/web/client/stores/task-store.js.map +0 -7
- package/dist/features/web/server/index.js.map +0 -7
- package/dist/hooks/auto-background.js.map +0 -7
- package/dist/hooks/claude-code-whatsapp-hook.js.map +0 -7
- package/dist/hooks/config.js.map +0 -7
- package/dist/hooks/daemon.js.map +0 -7
- package/dist/hooks/events.js.map +0 -7
- package/dist/hooks/index.js.map +0 -7
- package/dist/hooks/linear-task-picker.js.map +0 -7
- package/dist/hooks/schemas.js.map +0 -7
- package/dist/hooks/secure-fs.js.map +0 -7
- package/dist/hooks/security-logger.js.map +0 -7
- package/dist/hooks/session-summary.js.map +0 -7
- package/dist/hooks/sms-action-runner.js.map +0 -7
- package/dist/hooks/sms-notify.js.map +0 -7
- package/dist/hooks/sms-watcher.js.map +0 -7
- package/dist/hooks/sms-webhook.js.map +0 -7
- package/dist/hooks/whatsapp-commands.js.map +0 -7
- package/dist/hooks/whatsapp-scheduler.js.map +0 -7
- package/dist/hooks/whatsapp-sync.js.map +0 -7
- package/dist/index.js.map +0 -7
- package/dist/integrations/anthropic/client.js.map +0 -7
- package/dist/integrations/claude-code/agent-bridge.js.map +0 -7
- package/dist/integrations/claude-code/enhanced-pre-clear-hooks.js.map +0 -7
- package/dist/integrations/claude-code/lifecycle-hooks.js.map +0 -7
- package/dist/integrations/claude-code/post-task-hooks.js.map +0 -7
- package/dist/integrations/claude-code/subagent-client-stub.js.map +0 -7
- package/dist/integrations/claude-code/subagent-client.js.map +0 -7
- package/dist/integrations/claude-code/task-coordinator.js.map +0 -7
- package/dist/integrations/linear/auth.js.map +0 -7
- package/dist/integrations/linear/auto-sync.js.map +0 -7
- package/dist/integrations/linear/client.js +0 -630
- package/dist/integrations/linear/client.js.map +0 -7
- package/dist/integrations/linear/config.js.map +0 -7
- package/dist/integrations/linear/migration.js.map +0 -7
- package/dist/integrations/linear/oauth-server.js.map +0 -7
- package/dist/integrations/linear/rest-client.js.map +0 -7
- package/dist/integrations/linear/sync-manager.js.map +0 -7
- package/dist/integrations/linear/sync-service.js.map +0 -7
- package/dist/integrations/linear/sync.js.map +0 -7
- package/dist/integrations/linear/unified-sync.js.map +0 -7
- package/dist/integrations/linear/webhook-handler.js.map +0 -7
- package/dist/integrations/linear/webhook-server.js.map +0 -7
- package/dist/integrations/linear/webhook.js.map +0 -7
- package/dist/integrations/mcp/handlers/code-execution-handlers.js.map +0 -7
- package/dist/integrations/mcp/handlers/context-handlers.js.map +0 -7
- package/dist/integrations/mcp/handlers/discovery-handlers.js.map +0 -7
- package/dist/integrations/mcp/handlers/index.js.map +0 -7
- package/dist/integrations/mcp/handlers/linear-handlers.js.map +0 -7
- package/dist/integrations/mcp/handlers/skill-handlers.js.map +0 -7
- package/dist/integrations/mcp/handlers/task-handlers.js.map +0 -7
- package/dist/integrations/mcp/handlers/trace-handlers.js.map +0 -7
- package/dist/integrations/mcp/index.js.map +0 -7
- package/dist/integrations/mcp/middleware/tool-scoring.js.map +0 -7
- package/dist/integrations/mcp/refactored-server.js.map +0 -7
- package/dist/integrations/mcp/remote-server.js +0 -691
- package/dist/integrations/mcp/remote-server.js.map +0 -7
- package/dist/integrations/mcp/schemas.js.map +0 -7
- package/dist/integrations/mcp/server.js +0 -1960
- package/dist/integrations/mcp/server.js.map +0 -7
- package/dist/integrations/mcp/tool-definitions-code.js.map +0 -7
- package/dist/integrations/mcp/tool-definitions.js.map +0 -7
- package/dist/integrations/mcp/trace-test.js +0 -48
- package/dist/integrations/mcp/trace-test.js.map +0 -7
- package/dist/integrations/pg-aiguide/embedding-provider.js +0 -189
- package/dist/integrations/pg-aiguide/embedding-provider.js.map +0 -7
- package/dist/integrations/pg-aiguide/semantic-search.js +0 -187
- package/dist/integrations/pg-aiguide/semantic-search.js.map +0 -7
- package/dist/integrations/pg-aiguide/timescale-analytics.js +0 -224
- package/dist/integrations/pg-aiguide/timescale-analytics.js.map +0 -7
- package/dist/integrations/ralph/bridge/ralph-stackmemory-bridge.js.map +0 -7
- package/dist/integrations/ralph/context/context-budget-manager.js.map +0 -7
- package/dist/integrations/ralph/context/stackmemory-context-loader.js.map +0 -7
- package/dist/integrations/ralph/coordination/enhanced-coordination.js.map +0 -7
- package/dist/integrations/ralph/index.js.map +0 -7
- package/dist/integrations/ralph/learning/pattern-learner.js.map +0 -7
- package/dist/integrations/ralph/lifecycle/iteration-lifecycle.js.map +0 -7
- package/dist/integrations/ralph/monitoring/swarm-dashboard.js.map +0 -7
- package/dist/integrations/ralph/monitoring/swarm-registry.js.map +0 -7
- package/dist/integrations/ralph/orchestration/multi-loop-orchestrator.js.map +0 -7
- package/dist/integrations/ralph/patterns/compounding-engineering-pattern.js.map +0 -7
- package/dist/integrations/ralph/patterns/extended-coherence-sessions.js.map +0 -7
- package/dist/integrations/ralph/patterns/oracle-worker-pattern.js.map +0 -7
- package/dist/integrations/ralph/performance/performance-optimizer.js.map +0 -7
- package/dist/integrations/ralph/ralph-integration-demo.js +0 -182
- package/dist/integrations/ralph/ralph-integration-demo.js.map +0 -7
- package/dist/integrations/ralph/recovery/crash-recovery.js.map +0 -7
- package/dist/integrations/ralph/state/state-reconciler.js.map +0 -7
- package/dist/integrations/ralph/swarm/git-workflow-manager.js.map +0 -7
- package/dist/integrations/ralph/swarm/swarm-coordinator.js.map +0 -7
- package/dist/integrations/ralph/visualization/ralph-debugger.js.map +0 -7
- package/dist/mcp/stackmemory-mcp-server.js.map +0 -7
- package/dist/middleware/exponential-rate-limiter.js.map +0 -7
- package/dist/models/user.model.js.map +0 -7
- package/dist/servers/production/auth-middleware.js.map +0 -7
- package/dist/servers/railway/config.js +0 -55
- package/dist/servers/railway/config.js.map +0 -7
- package/dist/servers/railway/index-enhanced.js +0 -160
- package/dist/servers/railway/index-enhanced.js.map +0 -7
- package/dist/servers/railway/index.js +0 -1349
- package/dist/servers/railway/index.js.map +0 -7
- package/dist/servers/railway/simple.js +0 -64
- package/dist/servers/railway/simple.js.map +0 -7
- package/dist/servers/railway/storage-test.js +0 -459
- package/dist/servers/railway/storage-test.js.map +0 -7
- package/dist/services/config-service.js.map +0 -7
- package/dist/services/context-service.js.map +0 -7
- package/dist/skills/api-discovery.js.map +0 -7
- package/dist/skills/api-skill.js.map +0 -7
- package/dist/skills/claude-skills.js.map +0 -7
- package/dist/skills/dashboard-launcher.js.map +0 -7
- package/dist/skills/recursive-agent-orchestrator.js.map +0 -7
- package/dist/skills/repo-ingestion-skill.js +0 -609
- package/dist/skills/repo-ingestion-skill.js.map +0 -7
- package/dist/skills/security-secrets-scanner.js +0 -284
- package/dist/skills/security-secrets-scanner.js.map +0 -7
- package/dist/skills/unified-rlm-orchestrator.js.map +0 -7
- package/dist/utils/env.js.map +0 -7
- package/dist/utils/formatting.js.map +0 -7
- package/dist/utils/process-cleanup.js.map +0 -7
- package/dist/validation/schemas.js +0 -222
- package/dist/validation/schemas.js.map +0 -7
- /package/dist/{agents → src/agents}/core/agent-task-manager.js +0 -0
- /package/dist/{agents → src/agents}/verifiers/base-verifier.js +0 -0
- /package/dist/{agents → src/agents}/verifiers/formatter-verifier.js +0 -0
- /package/dist/{agents → src/agents}/verifiers/llm-judge.js +0 -0
- /package/dist/{cli → src/cli}/auto-detect.js +0 -0
- /package/dist/{cli → src/cli}/claude-sm-danger.js +0 -0
- /package/dist/{cli → src/cli}/codex-sm-danger.js +0 -0
- /package/dist/{cli → src/cli}/codex-sm.js +0 -0
- /package/dist/{cli → src/cli}/commands/api.js +0 -0
- /package/dist/{cli → src/cli}/commands/auto-background.js +0 -0
- /package/dist/{cli → src/cli}/commands/cleanup-processes.js +0 -0
- /package/dist/{cli → src/cli}/commands/clear.js +0 -0
- /package/dist/{cli → src/cli}/commands/config.js +0 -0
- /package/dist/{cli → src/cli}/commands/context-rehydrate.js +0 -0
- /package/dist/{cli → src/cli}/commands/context.js +0 -0
- /package/dist/{cli → src/cli}/commands/daemon.js +0 -0
- /package/dist/{cli → src/cli}/commands/dashboard.js +0 -0
- /package/dist/{cli → src/cli}/commands/db.js +0 -0
- /package/dist/{cli → src/cli}/commands/decision.js +0 -0
- /package/dist/{cli → src/cli}/commands/discovery.js +0 -0
- /package/dist/{cli → src/cli}/commands/handoff.js +0 -0
- /package/dist/{cli → src/cli}/commands/hooks.js +0 -0
- /package/dist/{cli → src/cli}/commands/linear.js +0 -0
- /package/dist/{cli → src/cli}/commands/log.js +0 -0
- /package/dist/{cli → src/cli}/commands/login.js +0 -0
- /package/dist/{cli → src/cli}/commands/migrate.js +0 -0
- /package/dist/{cli → src/cli}/commands/model.js +0 -0
- /package/dist/{cli → src/cli}/commands/onboard.js +0 -0
- /package/dist/{cli → src/cli}/commands/projects.js +0 -0
- /package/dist/{cli → src/cli}/commands/ralph.js +0 -0
- /package/dist/{cli → src/cli}/commands/retrieval.js +0 -0
- /package/dist/{cli → src/cli}/commands/service.js +0 -0
- /package/dist/{cli → src/cli}/commands/session.js +0 -0
- /package/dist/{cli → src/cli}/commands/settings.js +0 -0
- /package/dist/{cli → src/cli}/commands/setup.js +0 -0
- /package/dist/{cli → src/cli}/commands/shell.js +0 -0
- /package/dist/{cli → src/cli}/commands/signup.js +0 -0
- /package/dist/{cli → src/cli}/commands/skills.js +0 -0
- /package/dist/{cli → src/cli}/commands/sms-notify.js +0 -0
- /package/dist/{cli → src/cli}/commands/storage-tier.js +0 -0
- /package/dist/{cli → src/cli}/commands/sweep.js +0 -0
- /package/dist/{cli → src/cli}/commands/tasks.js +0 -0
- /package/dist/{cli → src/cli}/commands/worktree.js +0 -0
- /package/dist/{cli → src/cli}/opencode-sm.js +0 -0
- /package/dist/{cli → src/cli}/utils/viewer.js +0 -0
- /package/dist/{core → src/core}/config/config-manager.js +0 -0
- /package/dist/{core → src/core}/config/feature-flags.js +0 -0
- /package/dist/{core → src/core}/config/storage-config.js +0 -0
- /package/dist/{core → src/core}/config/types.js +0 -0
- /package/dist/{core → src/core}/context/auto-context.js +0 -0
- /package/dist/{core → src/core}/context/dual-stack-manager.js +0 -0
- /package/dist/{core → src/core}/context/enhanced-rehydration.js +0 -0
- /package/dist/{core → src/core}/context/frame-database.js +0 -0
- /package/dist/{core → src/core}/context/frame-digest.js +0 -0
- /package/dist/{core → src/core}/context/frame-handoff-manager.js +0 -0
- /package/dist/{core → src/core}/context/frame-lifecycle-hooks.js +0 -0
- /package/dist/{core → src/core}/context/frame-recovery.js +0 -0
- /package/dist/{core → src/core}/context/frame-stack.js +0 -0
- /package/dist/{core → src/core}/context/frame-types.js +0 -0
- /package/dist/{core → src/core}/context/frame-types.js.map +0 -0
- /package/dist/{core → src/core}/context/index.js +0 -0
- /package/dist/{core → src/core}/context/permission-manager.js +0 -0
- /package/dist/{core → src/core}/context/recursive-context-manager.js +0 -0
- /package/dist/{core → src/core}/context/refactored-frame-manager.js +0 -0
- /package/dist/{core → src/core}/context/shared-context-layer.js +0 -0
- /package/dist/{core → src/core}/context/stack-merge-resolver.js +0 -0
- /package/dist/{core → src/core}/context/validation.js +0 -0
- /package/dist/{core → src/core}/database/batch-operations.js +0 -0
- /package/dist/{core → src/core}/database/connection-pool.js +0 -0
- /package/dist/{core → src/core}/database/database-adapter.js +0 -0
- /package/dist/{core → src/core}/database/migration-manager.js +0 -0
- /package/dist/{core → src/core}/database/query-cache.js +0 -0
- /package/dist/{core → src/core}/database/query-router.js +0 -0
- /package/dist/{core → src/core}/digest/enhanced-hybrid-digest.js +0 -0
- /package/dist/{core → src/core}/digest/frame-digest-integration.js +0 -0
- /package/dist/{core → src/core}/digest/hybrid-digest-generator.js +0 -0
- /package/dist/{core → src/core}/digest/index.js +0 -0
- /package/dist/{core → src/core}/digest/types.js +0 -0
- /package/dist/{core → src/core}/errors/recovery.js +0 -0
- /package/dist/{core → src/core}/execution/parallel-executor.js +0 -0
- /package/dist/{core/merge → src/core/extensions}/types.js +0 -0
- /package/dist/{core/merge → src/core/extensions}/types.js.map +0 -0
- /package/dist/{core → src/core}/frame/workflow-templates.js +0 -0
- /package/dist/{core → src/core}/merge/conflict-detector.js +0 -0
- /package/dist/{core → src/core}/merge/index.js +0 -0
- /package/dist/{core → src/core}/merge/resolution-engine.js +0 -0
- /package/dist/{core → src/core}/merge/stack-diff.js +0 -0
- /package/dist/{core → src/core/merge}/types.js +0 -0
- /package/dist/{core → src/core/merge}/types.js.map +0 -0
- /package/dist/{core → src/core}/models/fallback-monitor.js +0 -0
- /package/dist/{core → src/core}/models/model-router.js +0 -0
- /package/dist/{core → src/core}/monitoring/error-handler.js +0 -0
- /package/dist/{core → src/core}/monitoring/metrics.js +0 -0
- /package/dist/{core → src/core}/monitoring/progress-tracker.js +0 -0
- /package/dist/{core → src/core}/monitoring/session-monitor.js +0 -0
- /package/dist/{core → src/core}/performance/context-cache.js +0 -0
- /package/dist/{core → src/core}/performance/index.js +0 -0
- /package/dist/{core → src/core}/performance/lazy-context-loader.js +0 -0
- /package/dist/{core → src/core}/performance/monitor.js +0 -0
- /package/dist/{core → src/core}/performance/optimized-frame-context.js +0 -0
- /package/dist/{core → src/core}/performance/performance-benchmark.js +0 -0
- /package/dist/{core → src/core}/performance/performance-profiler.js +0 -0
- /package/dist/{core → src/core}/performance/streaming-jsonl-parser.js +0 -0
- /package/dist/{core → src/core}/persistence/postgres-adapter.js +0 -0
- /package/dist/{core → src/core}/projects/project-isolation.js +0 -0
- /package/dist/{core → src/core}/projects/project-manager.js +0 -0
- /package/dist/{core → src/core}/query/query-parser.js +0 -0
- /package/dist/{core → src/core}/query/query-templates.js +0 -0
- /package/dist/{core → src/core}/retrieval/context-retriever.js +0 -0
- /package/dist/{core → src/core}/retrieval/index.js +0 -0
- /package/dist/{core → src/core}/retrieval/llm-context-retrieval.js +0 -0
- /package/dist/{core → src/core}/retrieval/llm-provider.js +0 -0
- /package/dist/{core → src/core}/retrieval/retrieval-audit.js +0 -0
- /package/dist/{core → src/core}/retrieval/summary-generator.js +0 -0
- /package/dist/{core → src/core}/retrieval/types.js +0 -0
- /package/dist/{core → src/core}/session/clear-survival.js +0 -0
- /package/dist/{core → src/core}/session/enhanced-handoff.js +0 -0
- /package/dist/{core → src/core}/session/handoff-generator.js +0 -0
- /package/dist/{core → src/core}/session/index.js +0 -0
- /package/dist/{core → src/core}/session/session-manager.js +0 -0
- /package/dist/{core → src/core}/skills/index.js +0 -0
- /package/dist/{core → src/core}/skills/skill-storage.js +0 -0
- /package/dist/{core → src/core}/skills/types.js +0 -0
- /package/dist/{core → src/core}/storage/infinite-storage.js +0 -0
- /package/dist/{core → src/core}/storage/remote-storage.js +0 -0
- /package/dist/{core → src/core}/storage/two-tier-storage.js +0 -0
- /package/dist/{core → src/core}/trace/cli-trace-wrapper.js +0 -0
- /package/dist/{core → src/core}/trace/db-trace-wrapper.js +0 -0
- /package/dist/{core → src/core}/trace/debug-trace.js +0 -0
- /package/dist/{core → src/core}/trace/index.js +0 -0
- /package/dist/{core → src/core}/trace/linear-api-wrapper.js +0 -0
- /package/dist/{core → src/core}/trace/trace-detector.js +0 -0
- /package/dist/{core → src/core}/trace/trace-store.js +0 -0
- /package/dist/{core → src/core}/trace/types.js +0 -0
- /package/dist/{integrations/linear → src/core}/types.js +0 -0
- /package/dist/{integrations/linear → src/core}/types.js.map +0 -0
- /package/dist/{core → src/core}/utils/async-mutex.js +0 -0
- /package/dist/{core → src/core}/utils/compression.js +0 -0
- /package/dist/{core → src/core}/utils/update-checker.js +0 -0
- /package/dist/{core → src/core}/worktree/worktree-manager.js +0 -0
- /package/dist/{daemon → src/daemon}/daemon-config.js +0 -0
- /package/dist/{daemon → src/daemon}/services/context-service.js +0 -0
- /package/dist/{daemon → src/daemon}/services/linear-service.js +0 -0
- /package/dist/{daemon → src/daemon}/session-daemon.js +0 -0
- /package/dist/{daemon → src/daemon}/unified-daemon.js +0 -0
- /package/dist/{features → src/features}/analytics/api/analytics-api.js +0 -0
- /package/dist/{features → src/features}/analytics/core/analytics-service.js +0 -0
- /package/dist/{features → src/features}/analytics/index.js +0 -0
- /package/dist/{features → src/features}/analytics/queries/metrics-queries.js +0 -0
- /package/dist/{features → src/features}/analytics/types/metrics.js +0 -0
- /package/dist/{features → src/features}/analytics/types/metrics.js.map +0 -0
- /package/dist/{features → src/features}/browser/browser-mcp.js +0 -0
- /package/dist/{features → src/features}/sweep/index.js +0 -0
- /package/dist/{features → src/features}/sweep/prediction-client.js +0 -0
- /package/dist/{features → src/features}/sweep/prompt-builder.js +0 -0
- /package/dist/{features → src/features}/sweep/pty-wrapper.js +0 -0
- /package/dist/{features → src/features}/sweep/state-watcher.js +0 -0
- /package/dist/{features → src/features}/sweep/status-bar.js +0 -0
- /package/dist/{features → src/features}/sweep/sweep-server-manager.js +0 -0
- /package/dist/{features → src/features}/sweep/tab-interceptor.js +0 -0
- /package/dist/{features → src/features}/sweep/types.js +0 -0
- /package/dist/{features → src/features}/tasks/linear-task-manager.js +0 -0
- /package/dist/{features → src/features}/tasks/task-aware-context.js +0 -0
- /package/dist/{features → src/features}/tui/simple-monitor.js +0 -0
- /package/dist/{features → src/features}/tui/swarm-monitor.js +0 -0
- /package/dist/{features → src/features}/web/client/stores/task-store.js +0 -0
- /package/dist/{features → src/features}/web/server/index.js +0 -0
- /package/dist/{hooks → src/hooks}/auto-background.js +0 -0
- /package/dist/{hooks → src/hooks}/claude-code-whatsapp-hook.js +0 -0
- /package/dist/{hooks → src/hooks}/config.js +0 -0
- /package/dist/{hooks → src/hooks}/daemon.js +0 -0
- /package/dist/{hooks → src/hooks}/events.js +0 -0
- /package/dist/{hooks → src/hooks}/index.js +0 -0
- /package/dist/{hooks → src/hooks}/linear-task-picker.js +0 -0
- /package/dist/{hooks → src/hooks}/schemas.js +0 -0
- /package/dist/{hooks → src/hooks}/secure-fs.js +0 -0
- /package/dist/{hooks → src/hooks}/security-logger.js +0 -0
- /package/dist/{hooks → src/hooks}/session-summary.js +0 -0
- /package/dist/{hooks → src/hooks}/sms-action-runner.js +0 -0
- /package/dist/{hooks → src/hooks}/sms-notify.js +0 -0
- /package/dist/{hooks → src/hooks}/sms-watcher.js +0 -0
- /package/dist/{hooks → src/hooks}/sms-webhook.js +0 -0
- /package/dist/{hooks → src/hooks}/whatsapp-commands.js +0 -0
- /package/dist/{hooks → src/hooks}/whatsapp-scheduler.js +0 -0
- /package/dist/{hooks → src/hooks}/whatsapp-sync.js +0 -0
- /package/dist/{index.js → src/index.js} +0 -0
- /package/dist/{integrations → src/integrations}/anthropic/client.js +0 -0
- /package/dist/{integrations → src/integrations}/claude-code/agent-bridge.js +0 -0
- /package/dist/{integrations → src/integrations}/claude-code/enhanced-pre-clear-hooks.js +0 -0
- /package/dist/{integrations → src/integrations}/claude-code/lifecycle-hooks.js +0 -0
- /package/dist/{integrations → src/integrations}/claude-code/post-task-hooks.js +0 -0
- /package/dist/{integrations → src/integrations}/claude-code/subagent-client-stub.js +0 -0
- /package/dist/{integrations → src/integrations}/claude-code/subagent-client.js +0 -0
- /package/dist/{integrations → src/integrations}/claude-code/task-coordinator.js +0 -0
- /package/dist/{integrations → src/integrations}/linear/auth.js +0 -0
- /package/dist/{integrations → src/integrations}/linear/auto-sync.js +0 -0
- /package/dist/{integrations → src/integrations}/linear/config.js +0 -0
- /package/dist/{integrations → src/integrations}/linear/migration.js +0 -0
- /package/dist/{integrations → src/integrations}/linear/oauth-server.js +0 -0
- /package/dist/{integrations → src/integrations}/linear/rest-client.js +0 -0
- /package/dist/{integrations → src/integrations}/linear/sync-manager.js +0 -0
- /package/dist/{integrations → src/integrations}/linear/sync-service.js +0 -0
- /package/dist/{integrations → src/integrations}/linear/sync.js +0 -0
- /package/dist/{integrations/ralph → src/integrations/linear}/types.js +0 -0
- /package/dist/{integrations/ralph → src/integrations/linear}/types.js.map +0 -0
- /package/dist/{integrations → src/integrations}/linear/unified-sync.js +0 -0
- /package/dist/{integrations → src/integrations}/linear/webhook-handler.js +0 -0
- /package/dist/{integrations → src/integrations}/linear/webhook-server.js +0 -0
- /package/dist/{integrations → src/integrations}/linear/webhook.js +0 -0
- /package/dist/{integrations → src/integrations}/mcp/handlers/code-execution-handlers.js +0 -0
- /package/dist/{integrations → src/integrations}/mcp/handlers/context-handlers.js +0 -0
- /package/dist/{integrations → src/integrations}/mcp/handlers/discovery-handlers.js +0 -0
- /package/dist/{integrations → src/integrations}/mcp/handlers/index.js +0 -0
- /package/dist/{integrations → src/integrations}/mcp/handlers/linear-handlers.js +0 -0
- /package/dist/{integrations → src/integrations}/mcp/handlers/skill-handlers.js +0 -0
- /package/dist/{integrations → src/integrations}/mcp/handlers/task-handlers.js +0 -0
- /package/dist/{integrations → src/integrations}/mcp/handlers/trace-handlers.js +0 -0
- /package/dist/{integrations → src/integrations}/mcp/index.js +0 -0
- /package/dist/{integrations → src/integrations}/mcp/middleware/tool-scoring.js +0 -0
- /package/dist/{integrations → src/integrations}/mcp/refactored-server.js +0 -0
- /package/dist/{integrations → src/integrations}/mcp/schemas.js +0 -0
- /package/dist/{integrations → src/integrations}/mcp/tool-definitions-code.js +0 -0
- /package/dist/{integrations → src/integrations}/mcp/tool-definitions.js +0 -0
- /package/dist/{integrations → src/integrations}/ralph/bridge/ralph-stackmemory-bridge.js +0 -0
- /package/dist/{integrations → src/integrations}/ralph/context/context-budget-manager.js +0 -0
- /package/dist/{integrations → src/integrations}/ralph/context/stackmemory-context-loader.js +0 -0
- /package/dist/{integrations → src/integrations}/ralph/coordination/enhanced-coordination.js +0 -0
- /package/dist/{integrations → src/integrations}/ralph/index.js +0 -0
- /package/dist/{integrations → src/integrations}/ralph/learning/pattern-learner.js +0 -0
- /package/dist/{integrations → src/integrations}/ralph/lifecycle/iteration-lifecycle.js +0 -0
- /package/dist/{integrations → src/integrations}/ralph/monitoring/swarm-dashboard.js +0 -0
- /package/dist/{integrations → src/integrations}/ralph/monitoring/swarm-registry.js +0 -0
- /package/dist/{integrations → src/integrations}/ralph/orchestration/multi-loop-orchestrator.js +0 -0
- /package/dist/{integrations → src/integrations}/ralph/patterns/compounding-engineering-pattern.js +0 -0
- /package/dist/{integrations → src/integrations}/ralph/patterns/extended-coherence-sessions.js +0 -0
- /package/dist/{integrations → src/integrations}/ralph/patterns/oracle-worker-pattern.js +0 -0
- /package/dist/{integrations → src/integrations}/ralph/performance/performance-optimizer.js +0 -0
- /package/dist/{integrations → src/integrations}/ralph/recovery/crash-recovery.js +0 -0
- /package/dist/{integrations → src/integrations}/ralph/state/state-reconciler.js +0 -0
- /package/dist/{integrations → src/integrations}/ralph/swarm/git-workflow-manager.js +0 -0
- /package/dist/{integrations → src/integrations}/ralph/swarm/swarm-coordinator.js +0 -0
- /package/dist/{types/task.js.map → src/integrations/ralph/types.js.map} +0 -0
- /package/dist/{integrations → src/integrations}/ralph/visualization/ralph-debugger.js +0 -0
- /package/dist/{mcp → src/mcp}/stackmemory-mcp-server.js +0 -0
- /package/dist/{middleware → src/middleware}/exponential-rate-limiter.js +0 -0
- /package/dist/{models → src/models}/user.model.js +0 -0
- /package/dist/{servers → src/servers}/production/auth-middleware.js +0 -0
- /package/dist/{services → src/services}/config-service.js +0 -0
- /package/dist/{services → src/services}/context-service.js +0 -0
- /package/dist/{skills → src/skills}/api-discovery.js +0 -0
- /package/dist/{skills → src/skills}/api-skill.js +0 -0
- /package/dist/{skills → src/skills}/claude-skills.js +0 -0
- /package/dist/{skills → src/skills}/dashboard-launcher.js +0 -0
- /package/dist/{skills → src/skills}/recursive-agent-orchestrator.js +0 -0
- /package/dist/{skills → src/skills}/unified-rlm-orchestrator.js +0 -0
- /package/dist/{types → src/types}/task.js +0 -0
- /package/dist/{utils → src/utils}/env.js +0 -0
- /package/dist/{utils → src/utils}/formatting.js +0 -0
- /package/dist/{utils → src/utils}/process-cleanup.js +0 -0
|
@@ -1,1349 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { fileURLToPath as __fileURLToPath } from 'url';
|
|
3
|
-
import { dirname as __pathDirname } from 'path';
|
|
4
|
-
const __filename = __fileURLToPath(import.meta.url);
|
|
5
|
-
const __dirname = __pathDirname(__filename);
|
|
6
|
-
import express from "express";
|
|
7
|
-
import { createServer } from "http";
|
|
8
|
-
import { WebSocketServer } from "ws";
|
|
9
|
-
import cors from "cors";
|
|
10
|
-
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
11
|
-
import Database from "better-sqlite3";
|
|
12
|
-
import * as bcrypt from "bcryptjs";
|
|
13
|
-
import jwt from "jsonwebtoken";
|
|
14
|
-
import { Pool } from "pg";
|
|
15
|
-
import { join, dirname } from "path";
|
|
16
|
-
import { existsSync, mkdirSync } from "fs";
|
|
17
|
-
import { AuthMiddleware } from "../production/auth-middleware.js";
|
|
18
|
-
const config = {
|
|
19
|
-
port: parseInt(process.env["PORT"] || "3000"),
|
|
20
|
-
environment: process.env["NODE_ENV"] || "development",
|
|
21
|
-
corsOrigins: process.env["CORS_ORIGINS"]?.split(",") || [
|
|
22
|
-
"http://localhost:3000"
|
|
23
|
-
],
|
|
24
|
-
authMode: process.env["AUTH_MODE"] || "api_key",
|
|
25
|
-
apiKeySecret: process.env["API_KEY_SECRET"] || "development-secret",
|
|
26
|
-
jwtSecret: process.env["JWT_SECRET"] || "development-jwt-secret",
|
|
27
|
-
databaseUrl: process.env["DATABASE_URL"] || join(process.cwd(), ".stackmemory", "railway.db"),
|
|
28
|
-
rateLimitEnabled: process.env["RATE_LIMIT_ENABLED"] === "true",
|
|
29
|
-
rateLimitFree: parseInt(process.env["RATE_LIMIT_FREE"] || "100"),
|
|
30
|
-
enableWebSocket: process.env["ENABLE_WEBSOCKET"] !== "false",
|
|
31
|
-
enableAnalytics: process.env["ENABLE_ANALYTICS"] === "true"
|
|
32
|
-
};
|
|
33
|
-
const rateLimiter = /* @__PURE__ */ new Map();
|
|
34
|
-
class RailwayMCPServer {
|
|
35
|
-
app;
|
|
36
|
-
httpServer;
|
|
37
|
-
wss;
|
|
38
|
-
mcpServer;
|
|
39
|
-
db;
|
|
40
|
-
pgPool = null;
|
|
41
|
-
authMiddleware = null;
|
|
42
|
-
connections = /* @__PURE__ */ new Map();
|
|
43
|
-
// Deprecated in-memory session cache; sessions are persisted in DB
|
|
44
|
-
adminSessions = /* @__PURE__ */ new Map();
|
|
45
|
-
// private browserMCP: BrowserMCPIntegration;
|
|
46
|
-
constructor() {
|
|
47
|
-
this.app = express();
|
|
48
|
-
this.httpServer = createServer(this.app);
|
|
49
|
-
this.initializeDatabase().then(() => {
|
|
50
|
-
this.startAdminSessionCleanup();
|
|
51
|
-
}).catch((err) => {
|
|
52
|
-
console.error("Failed to initialize database:", err);
|
|
53
|
-
});
|
|
54
|
-
this.setupMiddleware();
|
|
55
|
-
this.setupRoutes();
|
|
56
|
-
if (config.enableWebSocket) {
|
|
57
|
-
this.setupWebSocket();
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
async initializeDatabase() {
|
|
61
|
-
const isPg = config.databaseUrl.startsWith("postgres://") || config.databaseUrl.startsWith("postgresql://");
|
|
62
|
-
if (isPg) {
|
|
63
|
-
console.log("Using PostgreSQL database");
|
|
64
|
-
this.pgPool = new Pool({ connectionString: config.databaseUrl });
|
|
65
|
-
await this.pgPool.query(`
|
|
66
|
-
CREATE TABLE IF NOT EXISTS contexts (
|
|
67
|
-
id BIGSERIAL PRIMARY KEY,
|
|
68
|
-
project_id TEXT NOT NULL,
|
|
69
|
-
content TEXT NOT NULL,
|
|
70
|
-
type TEXT DEFAULT 'general',
|
|
71
|
-
metadata JSONB DEFAULT '{}'::jsonb,
|
|
72
|
-
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
73
|
-
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
74
|
-
);
|
|
75
|
-
`);
|
|
76
|
-
await this.pgPool.query(`
|
|
77
|
-
CREATE TABLE IF NOT EXISTS api_keys (
|
|
78
|
-
id BIGSERIAL PRIMARY KEY,
|
|
79
|
-
key_hash TEXT UNIQUE NOT NULL,
|
|
80
|
-
user_id TEXT NOT NULL,
|
|
81
|
-
name TEXT,
|
|
82
|
-
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
83
|
-
last_used TIMESTAMPTZ,
|
|
84
|
-
revoked BOOLEAN DEFAULT false
|
|
85
|
-
);
|
|
86
|
-
`);
|
|
87
|
-
await this.pgPool.query(`
|
|
88
|
-
CREATE TABLE IF NOT EXISTS users (
|
|
89
|
-
id TEXT PRIMARY KEY,
|
|
90
|
-
email TEXT UNIQUE,
|
|
91
|
-
name TEXT,
|
|
92
|
-
password_hash TEXT,
|
|
93
|
-
tier TEXT DEFAULT 'free',
|
|
94
|
-
role TEXT DEFAULT 'user',
|
|
95
|
-
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
96
|
-
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
97
|
-
);
|
|
98
|
-
`);
|
|
99
|
-
try {
|
|
100
|
-
await this.pgPool.query(`ALTER TABLE users ADD COLUMN role TEXT DEFAULT 'user'`);
|
|
101
|
-
} catch {
|
|
102
|
-
}
|
|
103
|
-
try {
|
|
104
|
-
await this.pgPool.query(`ALTER TABLE users ADD COLUMN password_hash TEXT`);
|
|
105
|
-
} catch {
|
|
106
|
-
}
|
|
107
|
-
try {
|
|
108
|
-
await this.pgPool.query(`ALTER TABLE project_members ADD CONSTRAINT project_members_role_check CHECK (role IN ('admin','owner','editor','viewer'))`);
|
|
109
|
-
} catch {
|
|
110
|
-
}
|
|
111
|
-
try {
|
|
112
|
-
await this.pgPool.query(`ALTER TABLE users ADD CONSTRAINT users_role_check CHECK (role IN ('admin','user'))`);
|
|
113
|
-
} catch {
|
|
114
|
-
}
|
|
115
|
-
await this.pgPool.query(`
|
|
116
|
-
CREATE TABLE IF NOT EXISTS projects (
|
|
117
|
-
id TEXT PRIMARY KEY,
|
|
118
|
-
name TEXT,
|
|
119
|
-
is_public BOOLEAN DEFAULT false,
|
|
120
|
-
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
121
|
-
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
122
|
-
);
|
|
123
|
-
`);
|
|
124
|
-
await this.pgPool.query(`
|
|
125
|
-
CREATE TABLE IF NOT EXISTS project_members (
|
|
126
|
-
project_id TEXT NOT NULL,
|
|
127
|
-
user_id TEXT NOT NULL,
|
|
128
|
-
role TEXT NOT NULL,
|
|
129
|
-
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
130
|
-
PRIMARY KEY (project_id, user_id)
|
|
131
|
-
);
|
|
132
|
-
`);
|
|
133
|
-
await this.pgPool.query("CREATE INDEX IF NOT EXISTS idx_contexts_project ON contexts(project_id);");
|
|
134
|
-
await this.pgPool.query("CREATE INDEX IF NOT EXISTS idx_api_keys_hash ON api_keys(key_hash);");
|
|
135
|
-
await this.pgPool.query("CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);");
|
|
136
|
-
await this.pgPool.query("CREATE INDEX IF NOT EXISTS idx_project_members_user ON project_members(user_id);");
|
|
137
|
-
await this.pgPool.query(`
|
|
138
|
-
CREATE TABLE IF NOT EXISTS admin_sessions (
|
|
139
|
-
id TEXT PRIMARY KEY,
|
|
140
|
-
user_id TEXT NOT NULL,
|
|
141
|
-
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
142
|
-
expires_at TIMESTAMPTZ NOT NULL,
|
|
143
|
-
user_agent TEXT,
|
|
144
|
-
ip TEXT
|
|
145
|
-
);
|
|
146
|
-
`);
|
|
147
|
-
await this.pgPool.query("CREATE INDEX IF NOT EXISTS idx_admin_sessions_user ON admin_sessions(user_id);");
|
|
148
|
-
try {
|
|
149
|
-
await this.pgPool.query("CREATE TYPE user_role AS ENUM ('admin','user')");
|
|
150
|
-
} catch {
|
|
151
|
-
}
|
|
152
|
-
try {
|
|
153
|
-
await this.pgPool.query("CREATE TYPE member_role AS ENUM ('admin','owner','editor','viewer')");
|
|
154
|
-
} catch {
|
|
155
|
-
}
|
|
156
|
-
try {
|
|
157
|
-
await this.pgPool.query("ALTER TABLE users ALTER COLUMN role TYPE user_role USING role::user_role");
|
|
158
|
-
} catch {
|
|
159
|
-
}
|
|
160
|
-
try {
|
|
161
|
-
await this.pgPool.query("ALTER TABLE project_members ALTER COLUMN role TYPE member_role USING role::member_role");
|
|
162
|
-
} catch {
|
|
163
|
-
}
|
|
164
|
-
await this.runMigrations("pg");
|
|
165
|
-
} else {
|
|
166
|
-
const dbDir = dirname(config.databaseUrl);
|
|
167
|
-
if (!existsSync(dbDir)) {
|
|
168
|
-
mkdirSync(dbDir, { recursive: true });
|
|
169
|
-
}
|
|
170
|
-
this.db = new Database(config.databaseUrl);
|
|
171
|
-
this.db.pragma("foreign_keys = ON");
|
|
172
|
-
this.db.exec(`
|
|
173
|
-
CREATE TABLE IF NOT EXISTS contexts (
|
|
174
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
175
|
-
project_id TEXT NOT NULL,
|
|
176
|
-
content TEXT NOT NULL,
|
|
177
|
-
type TEXT DEFAULT 'general',
|
|
178
|
-
metadata TEXT DEFAULT '{}',
|
|
179
|
-
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
180
|
-
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
181
|
-
);
|
|
182
|
-
|
|
183
|
-
CREATE TABLE IF NOT EXISTS api_keys (
|
|
184
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
185
|
-
key_hash TEXT UNIQUE NOT NULL,
|
|
186
|
-
user_id TEXT NOT NULL,
|
|
187
|
-
name TEXT,
|
|
188
|
-
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
189
|
-
last_used DATETIME,
|
|
190
|
-
revoked BOOLEAN DEFAULT 0
|
|
191
|
-
);
|
|
192
|
-
|
|
193
|
-
CREATE TABLE IF NOT EXISTS users (
|
|
194
|
-
id TEXT PRIMARY KEY,
|
|
195
|
-
email TEXT UNIQUE,
|
|
196
|
-
name TEXT,
|
|
197
|
-
password_hash TEXT,
|
|
198
|
-
tier TEXT DEFAULT 'free',
|
|
199
|
-
role TEXT DEFAULT 'user',
|
|
200
|
-
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
201
|
-
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
202
|
-
);
|
|
203
|
-
|
|
204
|
-
CREATE TABLE IF NOT EXISTS projects (
|
|
205
|
-
id TEXT PRIMARY KEY,
|
|
206
|
-
name TEXT,
|
|
207
|
-
is_public BOOLEAN DEFAULT 0,
|
|
208
|
-
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
209
|
-
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
210
|
-
);
|
|
211
|
-
|
|
212
|
-
CREATE TABLE IF NOT EXISTS project_members (
|
|
213
|
-
project_id TEXT NOT NULL,
|
|
214
|
-
user_id TEXT NOT NULL,
|
|
215
|
-
role TEXT NOT NULL CHECK (role IN ('admin','owner','editor','viewer')),
|
|
216
|
-
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
217
|
-
PRIMARY KEY (project_id, user_id)
|
|
218
|
-
);
|
|
219
|
-
|
|
220
|
-
CREATE INDEX IF NOT EXISTS idx_contexts_project ON contexts(project_id);
|
|
221
|
-
CREATE INDEX IF NOT EXISTS idx_api_keys_hash ON api_keys(key_hash);
|
|
222
|
-
CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
|
|
223
|
-
CREATE INDEX IF NOT EXISTS idx_project_members_user ON project_members(user_id);
|
|
224
|
-
|
|
225
|
-
CREATE TABLE IF NOT EXISTS admin_sessions (
|
|
226
|
-
id TEXT PRIMARY KEY,
|
|
227
|
-
user_id TEXT NOT NULL,
|
|
228
|
-
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
229
|
-
expires_at DATETIME NOT NULL,
|
|
230
|
-
user_agent TEXT,
|
|
231
|
-
ip TEXT
|
|
232
|
-
);
|
|
233
|
-
CREATE INDEX IF NOT EXISTS idx_admin_sessions_user ON admin_sessions(user_id);
|
|
234
|
-
`);
|
|
235
|
-
await this.runMigrations("sqlite");
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
// Simple migration framework (Railway server scope)
|
|
239
|
-
async runMigrations(kind) {
|
|
240
|
-
if (kind === "pg") {
|
|
241
|
-
await this.pgPool.query(`
|
|
242
|
-
CREATE TABLE IF NOT EXISTS railway_schema_version (
|
|
243
|
-
version INTEGER PRIMARY KEY,
|
|
244
|
-
applied_at TIMESTAMPTZ DEFAULT NOW(),
|
|
245
|
-
description TEXT
|
|
246
|
-
);
|
|
247
|
-
`);
|
|
248
|
-
const r = await this.pgPool.query("SELECT COALESCE(MAX(version), 0) AS v FROM railway_schema_version");
|
|
249
|
-
let cur = Number(r.rows[0]?.v || 0);
|
|
250
|
-
const apply = async (version, description, queries) => {
|
|
251
|
-
if (cur >= version) return;
|
|
252
|
-
for (const q of queries) {
|
|
253
|
-
try {
|
|
254
|
-
await this.pgPool.query(q);
|
|
255
|
-
} catch (e) {
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
await this.pgPool.query("INSERT INTO railway_schema_version (version, description) VALUES ($1, $2) ON CONFLICT (version) DO NOTHING", [version, description]);
|
|
259
|
-
cur = version;
|
|
260
|
-
};
|
|
261
|
-
await apply(1, "base schema", [
|
|
262
|
-
`CREATE TABLE IF NOT EXISTS contexts (id BIGSERIAL PRIMARY KEY, project_id TEXT NOT NULL, content TEXT NOT NULL, type TEXT DEFAULT 'general', metadata JSONB DEFAULT '{}'::jsonb, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW())`,
|
|
263
|
-
`CREATE TABLE IF NOT EXISTS api_keys (id BIGSERIAL PRIMARY KEY, key_hash TEXT UNIQUE NOT NULL, user_id TEXT NOT NULL, name TEXT, created_at TIMESTAMPTZ DEFAULT NOW(), last_used TIMESTAMPTZ, revoked BOOLEAN DEFAULT false)`,
|
|
264
|
-
`CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY, email TEXT, name TEXT, tier TEXT DEFAULT 'free', role TEXT DEFAULT 'user', created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW())`,
|
|
265
|
-
`CREATE TABLE IF NOT EXISTS projects (id TEXT PRIMARY KEY, name TEXT, is_public BOOLEAN DEFAULT false, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW())`,
|
|
266
|
-
`CREATE TABLE IF NOT EXISTS project_members (project_id TEXT NOT NULL, user_id TEXT NOT NULL, role TEXT NOT NULL, created_at TIMESTAMPTZ DEFAULT NOW(), PRIMARY KEY (project_id, user_id))`,
|
|
267
|
-
`CREATE INDEX IF NOT EXISTS idx_contexts_project ON contexts(project_id)`,
|
|
268
|
-
`CREATE INDEX IF NOT EXISTS idx_api_keys_hash ON api_keys(key_hash)`,
|
|
269
|
-
`CREATE INDEX IF NOT EXISTS idx_users_email ON users(email)`,
|
|
270
|
-
`CREATE INDEX IF NOT EXISTS idx_project_members_user ON project_members(user_id)`
|
|
271
|
-
]);
|
|
272
|
-
await apply(2, "admin sessions", [
|
|
273
|
-
`CREATE TABLE IF NOT EXISTS admin_sessions (id TEXT PRIMARY KEY, user_id TEXT NOT NULL, created_at TIMESTAMPTZ DEFAULT NOW(), expires_at TIMESTAMPTZ NOT NULL, user_agent TEXT, ip TEXT)`,
|
|
274
|
-
`CREATE INDEX IF NOT EXISTS idx_admin_sessions_user ON admin_sessions(user_id)`
|
|
275
|
-
]);
|
|
276
|
-
await apply(3, "role enums & checks", [
|
|
277
|
-
`CREATE TYPE user_role AS ENUM ('admin','user')`,
|
|
278
|
-
`CREATE TYPE member_role AS ENUM ('admin','owner','editor','viewer')`,
|
|
279
|
-
`ALTER TABLE users ALTER COLUMN role TYPE user_role USING role::user_role`,
|
|
280
|
-
`ALTER TABLE project_members ALTER COLUMN role TYPE member_role USING role::member_role`,
|
|
281
|
-
`ALTER TABLE project_members ADD CONSTRAINT project_members_role_check CHECK (role IN ('admin','owner','editor','viewer'))`,
|
|
282
|
-
`ALTER TABLE users ADD CONSTRAINT users_role_check CHECK (role IN ('admin','user'))`
|
|
283
|
-
]);
|
|
284
|
-
await apply(4, "password authentication", [
|
|
285
|
-
`ALTER TABLE users ADD COLUMN IF NOT EXISTS password_hash TEXT`,
|
|
286
|
-
`ALTER TABLE users ADD CONSTRAINT users_email_unique UNIQUE (email)`
|
|
287
|
-
]);
|
|
288
|
-
} else {
|
|
289
|
-
this.db.exec(`CREATE TABLE IF NOT EXISTS railway_schema_version (version INTEGER PRIMARY KEY, applied_at DATETIME DEFAULT CURRENT_TIMESTAMP, description TEXT)`);
|
|
290
|
-
const row = this.db.prepare("SELECT COALESCE(MAX(version), 0) AS v FROM railway_schema_version").get();
|
|
291
|
-
let cur = Number(row?.v || 0);
|
|
292
|
-
const apply = (version, description, statements) => {
|
|
293
|
-
if (cur >= version) return;
|
|
294
|
-
this.db.exec("BEGIN");
|
|
295
|
-
try {
|
|
296
|
-
for (const s of statements) {
|
|
297
|
-
try {
|
|
298
|
-
this.db.exec(s);
|
|
299
|
-
} catch {
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
this.db.prepare("INSERT OR IGNORE INTO railway_schema_version (version, description) VALUES (?, ?)").run(version, description);
|
|
303
|
-
this.db.exec("COMMIT");
|
|
304
|
-
cur = version;
|
|
305
|
-
} catch {
|
|
306
|
-
this.db.exec("ROLLBACK");
|
|
307
|
-
}
|
|
308
|
-
};
|
|
309
|
-
apply(1, "base schema", [
|
|
310
|
-
`CREATE TABLE IF NOT EXISTS contexts (id INTEGER PRIMARY KEY AUTOINCREMENT, project_id TEXT NOT NULL, content TEXT NOT NULL, type TEXT DEFAULT 'general', metadata TEXT DEFAULT '{}', created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP)`,
|
|
311
|
-
`CREATE TABLE IF NOT EXISTS api_keys (id INTEGER PRIMARY KEY AUTOINCREMENT, key_hash TEXT UNIQUE NOT NULL, user_id TEXT NOT NULL, name TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, last_used DATETIME, revoked BOOLEAN DEFAULT 0)`,
|
|
312
|
-
`CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY, email TEXT, name TEXT, tier TEXT DEFAULT 'free', role TEXT DEFAULT 'user', created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP)`,
|
|
313
|
-
`CREATE TABLE IF NOT EXISTS projects (id TEXT PRIMARY KEY, name TEXT, is_public BOOLEAN DEFAULT 0, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP)`,
|
|
314
|
-
`CREATE TABLE IF NOT EXISTS project_members (project_id TEXT NOT NULL, user_id TEXT NOT NULL, role TEXT NOT NULL CHECK (role IN ('admin','owner','editor','viewer')), created_at DATETIME DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (project_id, user_id))`,
|
|
315
|
-
`CREATE INDEX IF NOT EXISTS idx_contexts_project ON contexts(project_id)`,
|
|
316
|
-
`CREATE INDEX IF NOT EXISTS idx_api_keys_hash ON api_keys(key_hash)`,
|
|
317
|
-
`CREATE INDEX IF NOT EXISTS idx_users_email ON users(email)`,
|
|
318
|
-
`CREATE INDEX IF NOT EXISTS idx_project_members_user ON project_members(user_id)`
|
|
319
|
-
]);
|
|
320
|
-
apply(2, "admin sessions", [
|
|
321
|
-
`CREATE TABLE IF NOT EXISTS admin_sessions (id TEXT PRIMARY KEY, user_id TEXT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, expires_at DATETIME NOT NULL, user_agent TEXT, ip TEXT)`,
|
|
322
|
-
`CREATE INDEX IF NOT EXISTS idx_admin_sessions_user ON admin_sessions(user_id)`
|
|
323
|
-
]);
|
|
324
|
-
apply(3, "password authentication", [
|
|
325
|
-
`ALTER TABLE users ADD COLUMN password_hash TEXT`
|
|
326
|
-
]);
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
// TTL cleanup for admin sessions
|
|
330
|
-
startAdminSessionCleanup() {
|
|
331
|
-
const minutes = parseInt(process.env["ADMIN_SESSION_CLEAN_INTERVAL_MIN"] || "15", 10);
|
|
332
|
-
if (minutes <= 0) return;
|
|
333
|
-
const run = async () => {
|
|
334
|
-
try {
|
|
335
|
-
if (this.pgPool) {
|
|
336
|
-
await this.pgPool.query("DELETE FROM admin_sessions WHERE expires_at <= NOW()");
|
|
337
|
-
} else if (this.db) {
|
|
338
|
-
const tableExists = this.db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='admin_sessions'`).get();
|
|
339
|
-
if (tableExists) {
|
|
340
|
-
this.db.prepare('DELETE FROM admin_sessions WHERE datetime(expires_at) <= datetime("now")').run();
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
} catch (error) {
|
|
344
|
-
console.warn("Admin session cleanup failed:", error);
|
|
345
|
-
}
|
|
346
|
-
};
|
|
347
|
-
run();
|
|
348
|
-
setInterval(run, Math.max(1, minutes) * 60 * 1e3);
|
|
349
|
-
}
|
|
350
|
-
setupMiddleware() {
|
|
351
|
-
this.app.use(
|
|
352
|
-
cors({
|
|
353
|
-
origin: config.corsOrigins,
|
|
354
|
-
credentials: true
|
|
355
|
-
})
|
|
356
|
-
);
|
|
357
|
-
this.app.use(express.json({ limit: "10mb" }));
|
|
358
|
-
this.app.use((req, res, next) => {
|
|
359
|
-
console.log(`${(/* @__PURE__ */ new Date()).toISOString()} ${req.method} ${req.path}`);
|
|
360
|
-
next();
|
|
361
|
-
});
|
|
362
|
-
this.app.use("/api", this.authenticate.bind(this));
|
|
363
|
-
this.app.use("/admin/api", this.authenticate.bind(this));
|
|
364
|
-
if (config.rateLimitEnabled) {
|
|
365
|
-
this.app.use("/api", this.rateLimit.bind(this));
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
async authenticate(req, res, next) {
|
|
369
|
-
if (req.path === "/health" || req.path === "/api/health" || req.path === "/health/db") {
|
|
370
|
-
return next();
|
|
371
|
-
}
|
|
372
|
-
const authHeader = req.headers.authorization;
|
|
373
|
-
if (config.authMode === "api_key") {
|
|
374
|
-
if (!authHeader?.startsWith("Bearer ")) {
|
|
375
|
-
return res.status(401).json({ error: "Missing API key" });
|
|
376
|
-
}
|
|
377
|
-
const apiKey = authHeader.substring(7);
|
|
378
|
-
try {
|
|
379
|
-
const valid = await this.validateApiKey(apiKey);
|
|
380
|
-
if (!valid) {
|
|
381
|
-
return res.status(403).json({ error: "Invalid API key" });
|
|
382
|
-
}
|
|
383
|
-
req.user = valid;
|
|
384
|
-
return next();
|
|
385
|
-
} catch (e) {
|
|
386
|
-
return res.status(500).json({ error: e.message || "Auth error" });
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
if (config.authMode === "jwt" && process.env["AUTH0_DOMAIN"]) {
|
|
390
|
-
if (!this.authMiddleware) {
|
|
391
|
-
this.authMiddleware = new AuthMiddleware({
|
|
392
|
-
auth0Domain: process.env["AUTH0_DOMAIN"],
|
|
393
|
-
auth0Audience: process.env["AUTH0_AUDIENCE"] || "stackmemory",
|
|
394
|
-
redisUrl: process.env["REDIS_URL"] || "redis://localhost:6379",
|
|
395
|
-
bypassAuth: process.env["NODE_ENV"] !== "production",
|
|
396
|
-
dbPath: process.env["STACKMEMORY_AUTH_DB"] || ".stackmemory/auth.db"
|
|
397
|
-
});
|
|
398
|
-
}
|
|
399
|
-
return this.authMiddleware.authenticate(req, res, next);
|
|
400
|
-
}
|
|
401
|
-
return next();
|
|
402
|
-
}
|
|
403
|
-
async validateApiKey(apiKey) {
|
|
404
|
-
if (this.pgPool) {
|
|
405
|
-
const { rows: rows2 } = await this.pgPool.query(
|
|
406
|
-
`SELECT ak.id, ak.user_id, ak.key_hash, ak.revoked, u.name, u.email, u.tier, u.role
|
|
407
|
-
FROM api_keys ak
|
|
408
|
-
LEFT JOIN users u ON u.id = ak.user_id`
|
|
409
|
-
);
|
|
410
|
-
for (const row of rows2) {
|
|
411
|
-
if (row.revoked) continue;
|
|
412
|
-
if (await bcrypt.compare(apiKey, row.key_hash)) {
|
|
413
|
-
await this.pgPool.query("UPDATE api_keys SET last_used = NOW() WHERE id = $1", [row.id]);
|
|
414
|
-
return { id: row.user_id || "api-user", tier: row.tier || "free", name: row.name || void 0, email: row.email || void 0, role: row.role || "user" };
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
return null;
|
|
418
|
-
}
|
|
419
|
-
const stmt = this.db.prepare(`
|
|
420
|
-
SELECT ak.id, ak.user_id, ak.key_hash, ak.revoked, u.name, u.email, u.tier, u.role
|
|
421
|
-
FROM api_keys ak
|
|
422
|
-
LEFT JOIN users u ON u.id = ak.user_id
|
|
423
|
-
`);
|
|
424
|
-
const rows = stmt.all();
|
|
425
|
-
for (const row of rows) {
|
|
426
|
-
if (row.revoked) continue;
|
|
427
|
-
if (await bcrypt.compare(apiKey, row.key_hash)) {
|
|
428
|
-
this.db.prepare("UPDATE api_keys SET last_used = CURRENT_TIMESTAMP WHERE id = ?").run(row.id);
|
|
429
|
-
return { id: row.user_id || "api-user", tier: row.tier || "free", name: row.name || void 0, email: row.email || void 0, role: row.role || "user" };
|
|
430
|
-
}
|
|
431
|
-
}
|
|
432
|
-
return null;
|
|
433
|
-
}
|
|
434
|
-
rateLimit(req, res, next) {
|
|
435
|
-
const userId = req.user?.id || req.ip;
|
|
436
|
-
const now = Date.now();
|
|
437
|
-
const windowMs = 15 * 60 * 1e3;
|
|
438
|
-
const userLimit = rateLimiter.get(userId);
|
|
439
|
-
if (!userLimit || userLimit.resetTime < now) {
|
|
440
|
-
rateLimiter.set(userId, {
|
|
441
|
-
count: 1,
|
|
442
|
-
resetTime: now + windowMs
|
|
443
|
-
});
|
|
444
|
-
return next();
|
|
445
|
-
}
|
|
446
|
-
if (userLimit.count >= config.rateLimitFree) {
|
|
447
|
-
const retryAfter = Math.ceil((userLimit.resetTime - now) / 1e3);
|
|
448
|
-
res.setHeader("Retry-After", retryAfter.toString());
|
|
449
|
-
return res.status(429).json({
|
|
450
|
-
error: "Rate limit exceeded",
|
|
451
|
-
retryAfter
|
|
452
|
-
});
|
|
453
|
-
}
|
|
454
|
-
userLimit.count++;
|
|
455
|
-
next();
|
|
456
|
-
}
|
|
457
|
-
setupRoutes() {
|
|
458
|
-
const healthHandler = (req, res) => {
|
|
459
|
-
const health = {
|
|
460
|
-
status: "healthy",
|
|
461
|
-
version: "1.0.0",
|
|
462
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
463
|
-
uptime: process.uptime(),
|
|
464
|
-
environment: config.environment
|
|
465
|
-
};
|
|
466
|
-
res.json(health);
|
|
467
|
-
};
|
|
468
|
-
this.app.get("/health", healthHandler);
|
|
469
|
-
this.app.get("/api/health", healthHandler);
|
|
470
|
-
this.app.get("/", (req, res) => {
|
|
471
|
-
res.json({
|
|
472
|
-
name: "StackMemory Railway Server",
|
|
473
|
-
version: "1.0.0",
|
|
474
|
-
health: "/health",
|
|
475
|
-
api: {
|
|
476
|
-
"POST /api/context/save": "Save context",
|
|
477
|
-
"GET /api/context/load": "Load context",
|
|
478
|
-
"POST /api/tools/execute": "Execute tool"
|
|
479
|
-
}
|
|
480
|
-
});
|
|
481
|
-
});
|
|
482
|
-
this.app.post("/auth/signup", async (req, res) => {
|
|
483
|
-
try {
|
|
484
|
-
const { email, password, name } = req.body;
|
|
485
|
-
if (!email || !password) {
|
|
486
|
-
return res.status(400).json({
|
|
487
|
-
success: false,
|
|
488
|
-
error: "Email and password are required"
|
|
489
|
-
});
|
|
490
|
-
}
|
|
491
|
-
if (this.pgPool) {
|
|
492
|
-
const existingUser = await this.pgPool.query(
|
|
493
|
-
"SELECT id FROM users WHERE email = $1",
|
|
494
|
-
[email]
|
|
495
|
-
);
|
|
496
|
-
if (existingUser.rowCount > 0) {
|
|
497
|
-
return res.status(409).json({
|
|
498
|
-
success: false,
|
|
499
|
-
error: "User already exists"
|
|
500
|
-
});
|
|
501
|
-
}
|
|
502
|
-
} else {
|
|
503
|
-
const existingUser = this.db.prepare("SELECT id FROM users WHERE email = ?").get(email);
|
|
504
|
-
if (existingUser) {
|
|
505
|
-
return res.status(409).json({
|
|
506
|
-
success: false,
|
|
507
|
-
error: "User already exists"
|
|
508
|
-
});
|
|
509
|
-
}
|
|
510
|
-
}
|
|
511
|
-
const passwordHash = await bcrypt.hash(password, 10);
|
|
512
|
-
const userId = `user_${Date.now()}_${Math.random().toString(36).substring(7)}`;
|
|
513
|
-
if (this.pgPool) {
|
|
514
|
-
await this.pgPool.query(
|
|
515
|
-
"INSERT INTO users (id, email, name, password_hash, tier, role) VALUES ($1, $2, $3, $4, $5, $6)",
|
|
516
|
-
[userId, email, name || email.split("@")[0], passwordHash, "free", "user"]
|
|
517
|
-
);
|
|
518
|
-
} else {
|
|
519
|
-
this.db.prepare(
|
|
520
|
-
"INSERT INTO users (id, email, name, password_hash, tier, role) VALUES (?, ?, ?, ?, ?, ?)"
|
|
521
|
-
).run(userId, email, name || email.split("@")[0], passwordHash, "free", "user");
|
|
522
|
-
}
|
|
523
|
-
const apiKey = `sk_${Math.random().toString(36).substring(2)}${Math.random().toString(36).substring(2)}`;
|
|
524
|
-
const apiKeyHash = await bcrypt.hash(apiKey, 10);
|
|
525
|
-
if (this.pgPool) {
|
|
526
|
-
await this.pgPool.query(
|
|
527
|
-
"INSERT INTO api_keys (key_hash, user_id, name) VALUES ($1, $2, $3)",
|
|
528
|
-
[apiKeyHash, userId, "Default API Key"]
|
|
529
|
-
);
|
|
530
|
-
} else {
|
|
531
|
-
this.db.prepare(
|
|
532
|
-
"INSERT INTO api_keys (key_hash, user_id, name) VALUES (?, ?, ?)"
|
|
533
|
-
).run(apiKeyHash, userId, "Default API Key");
|
|
534
|
-
}
|
|
535
|
-
const token = jwt.sign(
|
|
536
|
-
{ sub: userId, email, role: "user" },
|
|
537
|
-
config.jwtSecret,
|
|
538
|
-
{ expiresIn: "30d" }
|
|
539
|
-
);
|
|
540
|
-
res.json({
|
|
541
|
-
success: true,
|
|
542
|
-
apiKey,
|
|
543
|
-
token,
|
|
544
|
-
email,
|
|
545
|
-
userId,
|
|
546
|
-
message: "Account created successfully"
|
|
547
|
-
});
|
|
548
|
-
} catch (error) {
|
|
549
|
-
console.error("Signup error:", error);
|
|
550
|
-
res.status(500).json({
|
|
551
|
-
success: false,
|
|
552
|
-
error: "Failed to create account"
|
|
553
|
-
});
|
|
554
|
-
}
|
|
555
|
-
});
|
|
556
|
-
this.app.post("/auth/login", async (req, res) => {
|
|
557
|
-
try {
|
|
558
|
-
const { email, password } = req.body;
|
|
559
|
-
if (!email || !password) {
|
|
560
|
-
return res.status(400).json({
|
|
561
|
-
success: false,
|
|
562
|
-
error: "Email and password are required"
|
|
563
|
-
});
|
|
564
|
-
}
|
|
565
|
-
let user = null;
|
|
566
|
-
if (this.pgPool) {
|
|
567
|
-
const result = await this.pgPool.query(
|
|
568
|
-
"SELECT id, email, name, password_hash, tier, role FROM users WHERE email = $1",
|
|
569
|
-
[email]
|
|
570
|
-
);
|
|
571
|
-
user = result.rows[0];
|
|
572
|
-
} else {
|
|
573
|
-
user = this.db.prepare(
|
|
574
|
-
"SELECT id, email, name, password_hash, tier, role FROM users WHERE email = ?"
|
|
575
|
-
).get(email);
|
|
576
|
-
}
|
|
577
|
-
if (!user) {
|
|
578
|
-
return res.status(401).json({
|
|
579
|
-
success: false,
|
|
580
|
-
error: "Invalid credentials"
|
|
581
|
-
});
|
|
582
|
-
}
|
|
583
|
-
const validPassword = await bcrypt.compare(password, user.password_hash);
|
|
584
|
-
if (!validPassword) {
|
|
585
|
-
return res.status(401).json({
|
|
586
|
-
success: false,
|
|
587
|
-
error: "Invalid credentials"
|
|
588
|
-
});
|
|
589
|
-
}
|
|
590
|
-
let apiKey = null;
|
|
591
|
-
if (this.pgPool) {
|
|
592
|
-
const keyResult = await this.pgPool.query(
|
|
593
|
-
"SELECT id FROM api_keys WHERE user_id = $1 AND revoked = false LIMIT 1",
|
|
594
|
-
[user.id]
|
|
595
|
-
);
|
|
596
|
-
if (keyResult.rowCount === 0) {
|
|
597
|
-
apiKey = `sk_${Math.random().toString(36).substring(2)}${Math.random().toString(36).substring(2)}`;
|
|
598
|
-
const apiKeyHash = await bcrypt.hash(apiKey, 10);
|
|
599
|
-
await this.pgPool.query(
|
|
600
|
-
"INSERT INTO api_keys (key_hash, user_id, name) VALUES ($1, $2, $3)",
|
|
601
|
-
[apiKeyHash, user.id, "Default API Key"]
|
|
602
|
-
);
|
|
603
|
-
} else {
|
|
604
|
-
apiKey = `sk_${Math.random().toString(36).substring(2)}${Math.random().toString(36).substring(2)}`;
|
|
605
|
-
const apiKeyHash = await bcrypt.hash(apiKey, 10);
|
|
606
|
-
await this.pgPool.query(
|
|
607
|
-
"UPDATE api_keys SET key_hash = $1, last_used = NOW() WHERE id = $2",
|
|
608
|
-
[apiKeyHash, keyResult.rows[0].id]
|
|
609
|
-
);
|
|
610
|
-
}
|
|
611
|
-
} else {
|
|
612
|
-
const keyRow = this.db.prepare(
|
|
613
|
-
"SELECT id FROM api_keys WHERE user_id = ? AND revoked = 0 LIMIT 1"
|
|
614
|
-
).get(user.id);
|
|
615
|
-
if (!keyRow) {
|
|
616
|
-
apiKey = `sk_${Math.random().toString(36).substring(2)}${Math.random().toString(36).substring(2)}`;
|
|
617
|
-
const apiKeyHash = await bcrypt.hash(apiKey, 10);
|
|
618
|
-
this.db.prepare(
|
|
619
|
-
"INSERT INTO api_keys (key_hash, user_id, name) VALUES (?, ?, ?)"
|
|
620
|
-
).run(apiKeyHash, user.id, "Default API Key");
|
|
621
|
-
} else {
|
|
622
|
-
apiKey = `sk_${Math.random().toString(36).substring(2)}${Math.random().toString(36).substring(2)}`;
|
|
623
|
-
const apiKeyHash = await bcrypt.hash(apiKey, 10);
|
|
624
|
-
this.db.prepare(
|
|
625
|
-
"UPDATE api_keys SET key_hash = ?, last_used = CURRENT_TIMESTAMP WHERE id = ?"
|
|
626
|
-
).run(apiKeyHash, keyRow.id);
|
|
627
|
-
}
|
|
628
|
-
}
|
|
629
|
-
const token = jwt.sign(
|
|
630
|
-
{ sub: user.id, email: user.email, role: user.role },
|
|
631
|
-
config.jwtSecret,
|
|
632
|
-
{ expiresIn: "30d" }
|
|
633
|
-
);
|
|
634
|
-
res.json({
|
|
635
|
-
success: true,
|
|
636
|
-
apiKey,
|
|
637
|
-
token,
|
|
638
|
-
email: user.email,
|
|
639
|
-
userId: user.id,
|
|
640
|
-
databaseUrl: process.env.DATABASE_URL,
|
|
641
|
-
// For client configuration
|
|
642
|
-
message: "Login successful"
|
|
643
|
-
});
|
|
644
|
-
} catch (error) {
|
|
645
|
-
console.error("Login error:", error);
|
|
646
|
-
res.status(500).json({
|
|
647
|
-
success: false,
|
|
648
|
-
error: "Login failed"
|
|
649
|
-
});
|
|
650
|
-
}
|
|
651
|
-
});
|
|
652
|
-
this.app.post("/api/context/save", async (req, res) => {
|
|
653
|
-
try {
|
|
654
|
-
const { projectId = "default", content, type = "general", metadata = {} } = req.body;
|
|
655
|
-
const user = req.user || { tier: "free" };
|
|
656
|
-
const allowFreeWrite = process.env["ALLOW_FREE_WRITE"] === "true";
|
|
657
|
-
if (user.tier === "free" && !allowFreeWrite) {
|
|
658
|
-
return res.status(403).json({ error: "Write access denied for free tier", code: "WRITE_FORBIDDEN" });
|
|
659
|
-
}
|
|
660
|
-
await this.ensureProjectOwner(projectId, user.id || "api-user");
|
|
661
|
-
const role = await this.getProjectRole(projectId, user.id || "api-user");
|
|
662
|
-
if (!this.hasWriteAccess(role)) {
|
|
663
|
-
return res.status(403).json({ error: "Insufficient permissions", code: "PERMISSION_DENIED" });
|
|
664
|
-
}
|
|
665
|
-
if (this.pgPool) {
|
|
666
|
-
const r = await this.pgPool.query(
|
|
667
|
-
`INSERT INTO contexts (project_id, content, type, metadata) VALUES ($1, $2, $3, $4) RETURNING id`,
|
|
668
|
-
[projectId, content, type, metadata]
|
|
669
|
-
);
|
|
670
|
-
return res.json({ success: true, id: r.rows[0].id });
|
|
671
|
-
}
|
|
672
|
-
const stmt = this.db.prepare("INSERT INTO contexts (project_id, content, type, metadata) VALUES (?, ?, ?, ?)");
|
|
673
|
-
const result = stmt.run(projectId, content, type, JSON.stringify(metadata));
|
|
674
|
-
return res.json({ success: true, id: result.lastInsertRowid });
|
|
675
|
-
} catch (error) {
|
|
676
|
-
res.status(500).json({ error: error.message });
|
|
677
|
-
}
|
|
678
|
-
});
|
|
679
|
-
this.app.get("/api/context/load", async (req, res) => {
|
|
680
|
-
try {
|
|
681
|
-
const { projectId = "default", limit = 10, offset = 0 } = req.query;
|
|
682
|
-
const user = req.user || { id: "api-user" };
|
|
683
|
-
const isPublic = await this.isProjectPublic(projectId);
|
|
684
|
-
const role = await this.getProjectRole(projectId, user.id || "api-user");
|
|
685
|
-
if (!this.hasReadAccess(role, isPublic)) {
|
|
686
|
-
return res.status(403).json({ error: "Insufficient permissions", code: "PERMISSION_DENIED" });
|
|
687
|
-
}
|
|
688
|
-
if (this.pgPool) {
|
|
689
|
-
const r = await this.pgPool.query(
|
|
690
|
-
`SELECT * FROM contexts WHERE project_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3`,
|
|
691
|
-
[projectId, Number(limit), Number(offset)]
|
|
692
|
-
);
|
|
693
|
-
return res.json({ success: true, contexts: r.rows });
|
|
694
|
-
}
|
|
695
|
-
const stmt = this.db.prepare("SELECT * FROM contexts WHERE project_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?");
|
|
696
|
-
const rows = stmt.all(projectId, limit, offset);
|
|
697
|
-
return res.json({ success: true, contexts: rows.map((c) => ({ ...c, metadata: JSON.parse(c.metadata || "{}") })) });
|
|
698
|
-
} catch (error) {
|
|
699
|
-
res.status(500).json({ error: error.message });
|
|
700
|
-
}
|
|
701
|
-
});
|
|
702
|
-
const parseCookies = (cookieHeader) => {
|
|
703
|
-
const out = {};
|
|
704
|
-
if (!cookieHeader) return out;
|
|
705
|
-
cookieHeader.split(";").forEach((p) => {
|
|
706
|
-
const i = p.indexOf("=");
|
|
707
|
-
if (i > -1) out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1));
|
|
708
|
-
});
|
|
709
|
-
return out;
|
|
710
|
-
};
|
|
711
|
-
const setJwtCookie = (res, token) => {
|
|
712
|
-
const flags = ["Path=/", "HttpOnly", "SameSite=Lax"];
|
|
713
|
-
if (process.env["NODE_ENV"] === "production") flags.push("Secure");
|
|
714
|
-
res.setHeader("Set-Cookie", `sm_admin_jwt=${encodeURIComponent(token)}; ${flags.join("; ")}`);
|
|
715
|
-
};
|
|
716
|
-
const clearJwtCookie = (res) => {
|
|
717
|
-
res.setHeader("Set-Cookie", "sm_admin_jwt=; Path=/; HttpOnly; Max-Age=0; SameSite=Lax");
|
|
718
|
-
};
|
|
719
|
-
const verifyAdminJwt = (token) => {
|
|
720
|
-
try {
|
|
721
|
-
const secret = process.env["ADMIN_JWT_SECRET"] || "dev-admin-secret";
|
|
722
|
-
const payload = jwt.verify(token, secret);
|
|
723
|
-
return { sub: payload.sub, jti: payload.jti };
|
|
724
|
-
} catch {
|
|
725
|
-
return null;
|
|
726
|
-
}
|
|
727
|
-
};
|
|
728
|
-
const checkDbSession = async (jti) => {
|
|
729
|
-
if (this.pgPool) {
|
|
730
|
-
const r = await this.pgPool.query("SELECT 1 FROM admin_sessions WHERE id = $1 AND expires_at > NOW()", [jti]);
|
|
731
|
-
return r.rowCount > 0;
|
|
732
|
-
}
|
|
733
|
-
const row = this.db.prepare('SELECT 1 FROM admin_sessions WHERE id = ? AND datetime(expires_at) > datetime("now")').get(jti);
|
|
734
|
-
return !!row;
|
|
735
|
-
};
|
|
736
|
-
const requireAdmin = (req, res, next) => {
|
|
737
|
-
const user = req.user || {};
|
|
738
|
-
if (user.role === "admin") return next();
|
|
739
|
-
const cookies = parseCookies(req.headers.cookie);
|
|
740
|
-
const t = cookies["sm_admin_jwt"];
|
|
741
|
-
if (t) {
|
|
742
|
-
const verified = verifyAdminJwt(t);
|
|
743
|
-
if (verified) {
|
|
744
|
-
checkDbSession(verified.jti).then((ok) => {
|
|
745
|
-
if (ok) return next();
|
|
746
|
-
if (req.path === "/admin" || req.path.startsWith("/admin")) {
|
|
747
|
-
res.redirect("/admin/login");
|
|
748
|
-
} else {
|
|
749
|
-
res.status(403).json({ error: "Admin access required", code: "ADMIN_REQUIRED" });
|
|
750
|
-
}
|
|
751
|
-
}).catch(() => {
|
|
752
|
-
if (req.path === "/admin" || req.path.startsWith("/admin")) {
|
|
753
|
-
res.redirect("/admin/login");
|
|
754
|
-
} else {
|
|
755
|
-
res.status(403).json({ error: "Admin access required", code: "ADMIN_REQUIRED" });
|
|
756
|
-
}
|
|
757
|
-
});
|
|
758
|
-
return;
|
|
759
|
-
}
|
|
760
|
-
}
|
|
761
|
-
if (req.path === "/admin" || req.path.startsWith("/admin")) {
|
|
762
|
-
res.redirect("/admin/login");
|
|
763
|
-
return;
|
|
764
|
-
}
|
|
765
|
-
return res.status(403).json({ error: "Admin access required", code: "ADMIN_REQUIRED" });
|
|
766
|
-
};
|
|
767
|
-
this.app.get("/admin/api/projects", requireAdmin, async (req, res) => {
|
|
768
|
-
try {
|
|
769
|
-
if (this.pgPool) {
|
|
770
|
-
const r = await this.pgPool.query("SELECT id, name, is_public, created_at, updated_at FROM projects ORDER BY updated_at DESC");
|
|
771
|
-
return res.json({ projects: r.rows });
|
|
772
|
-
}
|
|
773
|
-
const rows = this.db.prepare("SELECT id, name, is_public, created_at, updated_at FROM projects ORDER BY updated_at DESC").all();
|
|
774
|
-
return res.json({ projects: rows });
|
|
775
|
-
} catch (e) {
|
|
776
|
-
res.status(500).json({ error: e.message });
|
|
777
|
-
}
|
|
778
|
-
});
|
|
779
|
-
this.app.post("/admin/api/projects", requireAdmin, async (req, res) => {
|
|
780
|
-
try {
|
|
781
|
-
const { id, name, isPublic = false } = req.body || {};
|
|
782
|
-
if (!id) return res.status(400).json({ error: "id required" });
|
|
783
|
-
if (this.pgPool) {
|
|
784
|
-
await this.pgPool.query("INSERT INTO projects (id, name, is_public) VALUES ($1, $2, $3) ON CONFLICT (id) DO NOTHING", [id, name || id, !!isPublic]);
|
|
785
|
-
return res.json({ success: true });
|
|
786
|
-
}
|
|
787
|
-
this.db.prepare("INSERT OR IGNORE INTO projects (id, name, is_public) VALUES (?, ?, ?)").run(id, name || id, isPublic ? 1 : 0);
|
|
788
|
-
return res.json({ success: true });
|
|
789
|
-
} catch (e) {
|
|
790
|
-
res.status(500).json({ error: e.message });
|
|
791
|
-
}
|
|
792
|
-
});
|
|
793
|
-
this.app.patch("/admin/api/projects/:id/visibility", requireAdmin, async (req, res) => {
|
|
794
|
-
try {
|
|
795
|
-
const pid = req.params.id;
|
|
796
|
-
const { isPublic } = req.body || {};
|
|
797
|
-
if (typeof isPublic !== "boolean") return res.status(400).json({ error: "isPublic boolean required" });
|
|
798
|
-
if (this.pgPool) {
|
|
799
|
-
await this.pgPool.query("UPDATE projects SET is_public = $1, updated_at = NOW() WHERE id = $2", [isPublic, pid]);
|
|
800
|
-
return res.json({ success: true });
|
|
801
|
-
}
|
|
802
|
-
this.db.prepare("UPDATE projects SET is_public = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?").run(isPublic ? 1 : 0, pid);
|
|
803
|
-
return res.json({ success: true });
|
|
804
|
-
} catch (e) {
|
|
805
|
-
res.status(500).json({ error: e.message });
|
|
806
|
-
}
|
|
807
|
-
});
|
|
808
|
-
this.app.get("/admin/api/projects/:id/members", requireAdmin, async (req, res) => {
|
|
809
|
-
try {
|
|
810
|
-
const pid = req.params.id;
|
|
811
|
-
if (this.pgPool) {
|
|
812
|
-
const r = await this.pgPool.query(
|
|
813
|
-
"SELECT pm.user_id, pm.role, u.email, u.name FROM project_members pm LEFT JOIN users u ON u.id = pm.user_id WHERE pm.project_id = $1 ORDER BY pm.role",
|
|
814
|
-
[pid]
|
|
815
|
-
);
|
|
816
|
-
return res.json({ members: r.rows });
|
|
817
|
-
}
|
|
818
|
-
const stmt = this.db.prepare("SELECT pm.user_id, pm.role, u.email, u.name FROM project_members pm LEFT JOIN users u ON u.id = pm.user_id WHERE pm.project_id = ? ORDER BY pm.role");
|
|
819
|
-
return res.json({ members: stmt.all(pid) });
|
|
820
|
-
} catch (e) {
|
|
821
|
-
res.status(500).json({ error: e.message });
|
|
822
|
-
}
|
|
823
|
-
});
|
|
824
|
-
this.app.put("/admin/api/projects/:id/members", requireAdmin, async (req, res) => {
|
|
825
|
-
try {
|
|
826
|
-
const pid = req.params.id;
|
|
827
|
-
const { userId, role } = req.body || {};
|
|
828
|
-
if (!userId || !role) return res.status(400).json({ error: "userId and role required" });
|
|
829
|
-
const validRoles = ["admin", "owner", "editor", "viewer"];
|
|
830
|
-
if (!validRoles.includes(role)) return res.status(400).json({ error: "invalid role" });
|
|
831
|
-
if (this.pgPool) {
|
|
832
|
-
await this.pgPool.query(
|
|
833
|
-
"INSERT INTO project_members (project_id, user_id, role) VALUES ($1, $2, $3) ON CONFLICT (project_id, user_id) DO UPDATE SET role = EXCLUDED.role",
|
|
834
|
-
[pid, userId, role]
|
|
835
|
-
);
|
|
836
|
-
return res.json({ success: true });
|
|
837
|
-
}
|
|
838
|
-
this.db.prepare("INSERT INTO project_members (project_id, user_id, role) VALUES (?, ?, ?) ON CONFLICT(project_id, user_id) DO UPDATE SET role = ?").run(pid, userId, role, role);
|
|
839
|
-
return res.json({ success: true });
|
|
840
|
-
} catch (e) {
|
|
841
|
-
res.status(500).json({ error: e.message });
|
|
842
|
-
}
|
|
843
|
-
});
|
|
844
|
-
this.app.delete("/admin/api/projects/:id/members/:userId", requireAdmin, async (req, res) => {
|
|
845
|
-
try {
|
|
846
|
-
const pid = req.params.id;
|
|
847
|
-
const uid = req.params.userId;
|
|
848
|
-
if (this.pgPool) {
|
|
849
|
-
await this.pgPool.query("DELETE FROM project_members WHERE project_id = $1 AND user_id = $2", [pid, uid]);
|
|
850
|
-
return res.json({ success: true });
|
|
851
|
-
}
|
|
852
|
-
this.db.prepare("DELETE FROM project_members WHERE project_id = ? AND user_id = ?").run(pid, uid);
|
|
853
|
-
return res.json({ success: true });
|
|
854
|
-
} catch (e) {
|
|
855
|
-
res.status(500).json({ error: e.message });
|
|
856
|
-
}
|
|
857
|
-
});
|
|
858
|
-
this.app.get("/admin/api/sessions", requireAdmin, async (_req, res) => {
|
|
859
|
-
try {
|
|
860
|
-
if (this.pgPool) {
|
|
861
|
-
const r = await this.pgPool.query("SELECT id, user_id, created_at, expires_at, user_agent, ip FROM admin_sessions ORDER BY created_at DESC");
|
|
862
|
-
return res.json({ sessions: r.rows });
|
|
863
|
-
}
|
|
864
|
-
const rows = this.db.prepare("SELECT id, user_id, created_at, expires_at, user_agent, ip FROM admin_sessions ORDER BY created_at DESC").all();
|
|
865
|
-
return res.json({ sessions: rows });
|
|
866
|
-
} catch (e) {
|
|
867
|
-
res.status(500).json({ error: e.message });
|
|
868
|
-
}
|
|
869
|
-
});
|
|
870
|
-
this.app.delete("/admin/api/sessions/:id", requireAdmin, async (req, res) => {
|
|
871
|
-
try {
|
|
872
|
-
const id = req.params.id;
|
|
873
|
-
if (this.pgPool) {
|
|
874
|
-
await this.pgPool.query("DELETE FROM admin_sessions WHERE id = $1", [id]);
|
|
875
|
-
} else {
|
|
876
|
-
this.db.prepare("DELETE FROM admin_sessions WHERE id = ?").run(id);
|
|
877
|
-
}
|
|
878
|
-
res.json({ success: true });
|
|
879
|
-
} catch (e) {
|
|
880
|
-
res.status(500).json({ error: e.message });
|
|
881
|
-
}
|
|
882
|
-
});
|
|
883
|
-
this.app.post("/admin/api/sessions/refresh", requireAdmin, async (req, res) => {
|
|
884
|
-
try {
|
|
885
|
-
const cookies = parseCookies(req.headers.cookie);
|
|
886
|
-
const t = cookies["sm_admin_jwt"];
|
|
887
|
-
if (!t) return res.status(400).json({ error: "No session" });
|
|
888
|
-
const secret = process.env["ADMIN_JWT_SECRET"] || "dev-admin-secret";
|
|
889
|
-
let payload;
|
|
890
|
-
try {
|
|
891
|
-
payload = jwt.verify(t, secret);
|
|
892
|
-
} catch {
|
|
893
|
-
return res.status(401).json({ error: "Invalid token" });
|
|
894
|
-
}
|
|
895
|
-
const oldJti = payload.jti;
|
|
896
|
-
const userId = payload.sub;
|
|
897
|
-
try {
|
|
898
|
-
if (this.pgPool) {
|
|
899
|
-
await this.pgPool.query("DELETE FROM admin_sessions WHERE id = $1", [oldJti]);
|
|
900
|
-
} else {
|
|
901
|
-
this.db.prepare("DELETE FROM admin_sessions WHERE id = ?").run(oldJti);
|
|
902
|
-
}
|
|
903
|
-
} catch (error) {
|
|
904
|
-
console.warn("Failed to delete session during refresh:", error);
|
|
905
|
-
}
|
|
906
|
-
const jti = Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);
|
|
907
|
-
const hours = parseInt(process.env["ADMIN_SESSION_HOURS"] || "8", 10);
|
|
908
|
-
const expMs = Date.now() + hours * 3600 * 1e3;
|
|
909
|
-
const expDateIso = new Date(expMs).toISOString();
|
|
910
|
-
const ua = req.headers["user-agent"] || "";
|
|
911
|
-
const ip = req.headers["x-forwarded-for"] || req.socket.remoteAddress || "";
|
|
912
|
-
if (this.pgPool) {
|
|
913
|
-
await this.pgPool.query("INSERT INTO admin_sessions (id, user_id, expires_at, user_agent, ip) VALUES ($1, $2, $3, $4, $5)", [jti, userId, expDateIso, ua, ip]);
|
|
914
|
-
} else {
|
|
915
|
-
this.db.prepare("INSERT INTO admin_sessions (id, user_id, expires_at, user_agent, ip) VALUES (?, ?, ?, ?, ?)").run(jti, userId, expDateIso, ua, ip);
|
|
916
|
-
}
|
|
917
|
-
const token = jwt.sign({ sub: userId, role: "admin", jti }, secret, { expiresIn: hours + "h" });
|
|
918
|
-
const flags = ["Path=/", "HttpOnly", "SameSite=Lax"];
|
|
919
|
-
if (process.env["NODE_ENV"] === "production") flags.push("Secure");
|
|
920
|
-
res.setHeader("Set-Cookie", `sm_admin_jwt=${encodeURIComponent(token)}; ${flags.join("; ")}`);
|
|
921
|
-
return res.json({ success: true });
|
|
922
|
-
} catch (e) {
|
|
923
|
-
res.status(500).json({ error: e.message });
|
|
924
|
-
}
|
|
925
|
-
});
|
|
926
|
-
this.app.get("/admin", requireAdmin, (req, res) => {
|
|
927
|
-
res.setHeader("Content-Type", "text/html");
|
|
928
|
-
res.send(`<!doctype html>
|
|
929
|
-
<html><head><meta charset="utf-8"/><title>StackMemory Admin</title>
|
|
930
|
-
<style>body{font-family:system-ui,Arial;margin:20px} table{border-collapse:collapse} th,td{border:1px solid #ddd;padding:6px} input,select{margin:4px} .row{margin-bottom:12px}</style>
|
|
931
|
-
</head><body>
|
|
932
|
-
<div style="display:flex;justify-content:space-between;align-items:center">
|
|
933
|
-
<h2>Projects</h2>
|
|
934
|
-
<div><a href="/admin/logout">Logout</a></div>
|
|
935
|
-
</div>
|
|
936
|
-
<div class="row">
|
|
937
|
-
<input id="newId" placeholder="project id"/>
|
|
938
|
-
<input id="newName" placeholder="name"/>
|
|
939
|
-
<label title="Anyone with auth can read if public"><input type="checkbox" id="newPublic"/> public</label>
|
|
940
|
-
<button onclick="createProject()">Create</button>
|
|
941
|
-
</div>
|
|
942
|
-
<div id="projects"></div>
|
|
943
|
-
<hr/>
|
|
944
|
-
<h2>Admin Sessions</h2>
|
|
945
|
-
<div class="row">
|
|
946
|
-
<button onclick="refreshSession()">Refresh This Session</button>
|
|
947
|
-
<button onclick="loadSessions()">Reload Sessions</button>
|
|
948
|
-
<span id="refreshMsg" style="margin-left:10px;color:#090"></span>
|
|
949
|
-
</div>
|
|
950
|
-
<div id="sessions"></div>
|
|
951
|
-
<script>
|
|
952
|
-
const ROLES = ['owner','editor','viewer','admin'];
|
|
953
|
-
async function loadProjects(){
|
|
954
|
-
const r = await fetch('/admin/api/projects'); const j = await r.json();
|
|
955
|
-
const rows = (j.projects||[]).map(p=>\`<tr><td>\${p.id}</td><td>\${p.name||''}</td><td>\${p.is_public? 'yes':'no'}</td>
|
|
956
|
-
<td><button onclick="togglePublic('\${p.id}',\${!p.is_public})">make \${!p.is_public?'public':'private'}</button>
|
|
957
|
-
<button onclick="viewMembers('\${p.id}')">members</button></td></tr>\`).join('');
|
|
958
|
-
document.getElementById('projects').innerHTML = \`<table><tr><th>id</th><th>name</th><th>public</th><th>actions</th></tr>\${rows}</table><div id="members"></div>\`;
|
|
959
|
-
}
|
|
960
|
-
async function createProject(){
|
|
961
|
-
const id = document.getElementById('newId').value; const name = document.getElementById('newName').value; const isPublic = document.getElementById('newPublic').checked;
|
|
962
|
-
await fetch('/admin/api/projects',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id,name,isPublic})});
|
|
963
|
-
loadProjects();
|
|
964
|
-
}
|
|
965
|
-
async function togglePublic(id, isPublic){
|
|
966
|
-
await fetch('/admin/api/projects/'+id+'/visibility',{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify({isPublic})});
|
|
967
|
-
loadProjects();
|
|
968
|
-
}
|
|
969
|
-
async function viewMembers(id){
|
|
970
|
-
const r = await fetch('/admin/api/projects/'+id+'/members'); const j = await r.json();
|
|
971
|
-
const rows = (j.members||[]).map(m=>\`<tr><td>\${m.user_id}</td><td>\${m.name||''}</td><td>\${m.email||''}</td><td>\${m.role}</td>
|
|
972
|
-
<td><button onclick="removeMember('\${id}','\${m.user_id}')">remove</button></td></tr>\`).join('');
|
|
973
|
-
document.getElementById('members').innerHTML = \`<h3>Members of \${id}</h3>
|
|
974
|
-
<div class="row"><input id="mUser" placeholder="user id"/><select id="mRole">\${ROLES.map(r=>\`<option>\${r}</option>\`).join('')}</select>
|
|
975
|
-
<button onclick="addMember('\${id}')">add/update</button></div>
|
|
976
|
-
<table><tr><th>user</th><th>name</th><th>email</th><th>role</th><th>actions</th></tr>\${rows}</table>\`;
|
|
977
|
-
}
|
|
978
|
-
async function addMember(id){
|
|
979
|
-
const userId = document.getElementById('mUser').value; const role = document.getElementById('mRole').value;
|
|
980
|
-
if (!ROLES.includes(role)) { alert('Invalid role'); return; }
|
|
981
|
-
await fetch('/admin/api/projects/'+id+'/members',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({userId,role})});
|
|
982
|
-
viewMembers(id);
|
|
983
|
-
}
|
|
984
|
-
async function removeMember(id, userId){
|
|
985
|
-
await fetch('/admin/api/projects/'+id+'/members/'+userId,{method:'DELETE'});
|
|
986
|
-
viewMembers(id);
|
|
987
|
-
}
|
|
988
|
-
async function loadSessions(){
|
|
989
|
-
const r = await fetch('/admin/api/sessions'); const j = await r.json();
|
|
990
|
-
const rows = (j.sessions||[]).map(s=>\`<tr><td>\${s.id}</td><td>\${s.user_id}</td><td>\${new Date(s.created_at).toLocaleString()}</td><td>\${new Date(s.expires_at).toLocaleString()}</td><td>\${s.ip||''}</td><td>\${(s.user_agent||'').slice(0,40)}</td><td><button onclick="killSession('\${s.id}')">terminate</button></td></tr>\`).join('');
|
|
991
|
-
document.getElementById('sessions').innerHTML = \`<table><tr><th>id</th><th>user</th><th>created</th><th>expires</th><th>ip</th><th>agent</th><th>actions</th></tr>\${rows}</table>\`;
|
|
992
|
-
}
|
|
993
|
-
async function killSession(id){
|
|
994
|
-
await fetch('/admin/api/sessions/'+id,{method:'DELETE'});
|
|
995
|
-
loadSessions();
|
|
996
|
-
}
|
|
997
|
-
async function refreshSession(){
|
|
998
|
-
const r = await fetch('/admin/api/sessions/refresh',{method:'POST'});
|
|
999
|
-
if (r.ok){ document.getElementById('refreshMsg').textContent = 'Session refreshed.'; setTimeout(()=>document.getElementById('refreshMsg').textContent='',1500);} else { alert('Refresh failed'); }
|
|
1000
|
-
}
|
|
1001
|
-
loadProjects();
|
|
1002
|
-
loadSessions();
|
|
1003
|
-
</script>
|
|
1004
|
-
</body></html>`);
|
|
1005
|
-
});
|
|
1006
|
-
this.app.get("/health/db", async (req, res) => {
|
|
1007
|
-
try {
|
|
1008
|
-
if (this.pgPool) {
|
|
1009
|
-
const r = await this.pgPool.query("SELECT 1 as ok");
|
|
1010
|
-
return res.json({ kind: "postgres", ok: !!r.rows?.length });
|
|
1011
|
-
}
|
|
1012
|
-
const row = this.db.prepare("SELECT 1 as ok").get();
|
|
1013
|
-
return res.json({ kind: "sqlite", ok: row?.ok === 1 });
|
|
1014
|
-
} catch (error) {
|
|
1015
|
-
res.status(500).json({ error: error.message });
|
|
1016
|
-
}
|
|
1017
|
-
});
|
|
1018
|
-
this.app.post("/api/tools/execute", async (req, res) => {
|
|
1019
|
-
try {
|
|
1020
|
-
const { tool, params } = req.body;
|
|
1021
|
-
if (tool === "save_context") {
|
|
1022
|
-
const user = req.user || { tier: "free" };
|
|
1023
|
-
const allowFreeWrite = process.env["ALLOW_FREE_WRITE"] === "true";
|
|
1024
|
-
if (user.tier === "free" && !allowFreeWrite) {
|
|
1025
|
-
return res.status(403).json({ error: "Write access denied for free tier", code: "WRITE_FORBIDDEN" });
|
|
1026
|
-
}
|
|
1027
|
-
const projectId = params && params.projectId || "default";
|
|
1028
|
-
await this.ensureProjectOwner(projectId, user.id || "api-user");
|
|
1029
|
-
const role = await this.getProjectRole(projectId, user.id || "api-user");
|
|
1030
|
-
if (!this.hasWriteAccess(role)) {
|
|
1031
|
-
return res.status(403).json({ error: "Insufficient permissions", code: "PERMISSION_DENIED" });
|
|
1032
|
-
}
|
|
1033
|
-
}
|
|
1034
|
-
if (tool === "load_context") {
|
|
1035
|
-
const user = req.user || { id: "api-user" };
|
|
1036
|
-
const projectId = params && params.projectId || "default";
|
|
1037
|
-
const isPublic = await this.isProjectPublic(projectId);
|
|
1038
|
-
const role = await this.getProjectRole(projectId, user.id || "api-user");
|
|
1039
|
-
if (!this.hasReadAccess(role, isPublic)) {
|
|
1040
|
-
return res.status(403).json({ error: "Insufficient permissions", code: "PERMISSION_DENIED" });
|
|
1041
|
-
}
|
|
1042
|
-
}
|
|
1043
|
-
const result = await this.executeMCPTool(tool, params);
|
|
1044
|
-
res.json({
|
|
1045
|
-
success: true,
|
|
1046
|
-
result
|
|
1047
|
-
});
|
|
1048
|
-
} catch (error) {
|
|
1049
|
-
res.status(500).json({ error: error.message });
|
|
1050
|
-
}
|
|
1051
|
-
});
|
|
1052
|
-
if (config.enableAnalytics) {
|
|
1053
|
-
this.app.get("/api/analytics", (req, res) => {
|
|
1054
|
-
try {
|
|
1055
|
-
const { projectId = "default" } = req.query;
|
|
1056
|
-
const stats = this.db.prepare(
|
|
1057
|
-
`
|
|
1058
|
-
SELECT
|
|
1059
|
-
COUNT(*) as total_contexts,
|
|
1060
|
-
COUNT(DISTINCT type) as unique_types,
|
|
1061
|
-
MAX(created_at) as last_activity
|
|
1062
|
-
FROM contexts
|
|
1063
|
-
WHERE project_id = ?
|
|
1064
|
-
`
|
|
1065
|
-
).get(projectId);
|
|
1066
|
-
res.json({
|
|
1067
|
-
success: true,
|
|
1068
|
-
analytics: stats
|
|
1069
|
-
});
|
|
1070
|
-
} catch (error) {
|
|
1071
|
-
res.status(500).json({ error: error.message });
|
|
1072
|
-
}
|
|
1073
|
-
});
|
|
1074
|
-
}
|
|
1075
|
-
this.app.get("/admin/login", (_req, res) => {
|
|
1076
|
-
res.setHeader("Content-Type", "text/html");
|
|
1077
|
-
res.send(`<!doctype html><html><head><meta charset="utf-8"/><title>Admin Login</title>
|
|
1078
|
-
<style>body{font-family:system-ui;margin:40px} input{padding:8px;margin:4px} button{padding:8px}</style></head>
|
|
1079
|
-
<body><h3>Admin Login</h3>
|
|
1080
|
-
<p>Paste an admin API key to manage projects and members.</p>
|
|
1081
|
-
<form method="POST" action="/admin/login">
|
|
1082
|
-
<input type="password" name="apiKey" placeholder="sk-..." style="min-width:360px" required/>
|
|
1083
|
-
<div><button type="submit">Login</button></div>
|
|
1084
|
-
<p style="color:#666">Your key is validated server-side and not stored in the browser; a short-lived session cookie is created.</p>
|
|
1085
|
-
</form>
|
|
1086
|
-
</body></html>`);
|
|
1087
|
-
});
|
|
1088
|
-
this.app.post("/admin/login", express.urlencoded({ extended: false }), async (req, res) => {
|
|
1089
|
-
try {
|
|
1090
|
-
const apiKey = req.body?.apiKey || "";
|
|
1091
|
-
if (!apiKey) return res.status(400).send("Missing API key");
|
|
1092
|
-
const u = await this.validateApiKey(apiKey);
|
|
1093
|
-
if (!u || u.role !== "admin") return res.status(403).send("Not an admin API key");
|
|
1094
|
-
const jti = Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);
|
|
1095
|
-
const hours = parseInt(process.env["ADMIN_SESSION_HOURS"] || "8", 10);
|
|
1096
|
-
const expMs = Date.now() + hours * 3600 * 1e3;
|
|
1097
|
-
const expDateIso = new Date(expMs).toISOString();
|
|
1098
|
-
const ua = req.headers["user-agent"] || "";
|
|
1099
|
-
const ip = req.headers["x-forwarded-for"] || req.socket.remoteAddress || "";
|
|
1100
|
-
if (this.pgPool) {
|
|
1101
|
-
await this.pgPool.query("INSERT INTO admin_sessions (id, user_id, expires_at, user_agent, ip) VALUES ($1, $2, $3, $4, $5)", [jti, u.id, expDateIso, ua, ip]);
|
|
1102
|
-
} else {
|
|
1103
|
-
this.db.prepare("INSERT INTO admin_sessions (id, user_id, expires_at, user_agent, ip) VALUES (?, ?, ?, ?, ?)").run(jti, u.id, expDateIso, ua, ip);
|
|
1104
|
-
}
|
|
1105
|
-
const token = jwt.sign({ sub: u.id, role: "admin", jti }, process.env["ADMIN_JWT_SECRET"] || "dev-admin-secret", { expiresIn: hours + "h" });
|
|
1106
|
-
setJwtCookie(res, token);
|
|
1107
|
-
res.redirect("/admin");
|
|
1108
|
-
} catch (e) {
|
|
1109
|
-
res.status(500).send("Login failed");
|
|
1110
|
-
}
|
|
1111
|
-
});
|
|
1112
|
-
this.app.get("/admin/logout", async (req, res) => {
|
|
1113
|
-
const cookies = parseCookies(req.headers.cookie);
|
|
1114
|
-
const t = cookies["sm_admin_jwt"];
|
|
1115
|
-
if (t) {
|
|
1116
|
-
const verified = verifyAdminJwt(t);
|
|
1117
|
-
if (verified) {
|
|
1118
|
-
try {
|
|
1119
|
-
if (this.pgPool) {
|
|
1120
|
-
await this.pgPool.query("DELETE FROM admin_sessions WHERE id = $1", [verified.jti]);
|
|
1121
|
-
} else {
|
|
1122
|
-
this.db.prepare("DELETE FROM admin_sessions WHERE id = ?").run(verified.jti);
|
|
1123
|
-
}
|
|
1124
|
-
} catch (error) {
|
|
1125
|
-
console.warn("Failed to delete session during logout:", error);
|
|
1126
|
-
}
|
|
1127
|
-
}
|
|
1128
|
-
}
|
|
1129
|
-
clearJwtCookie(res);
|
|
1130
|
-
res.redirect("/admin/login");
|
|
1131
|
-
});
|
|
1132
|
-
}
|
|
1133
|
-
setupWebSocket() {
|
|
1134
|
-
this.wss = new WebSocketServer({
|
|
1135
|
-
server: this.httpServer,
|
|
1136
|
-
path: "/ws"
|
|
1137
|
-
});
|
|
1138
|
-
this.wss.on("connection", (ws, _req) => {
|
|
1139
|
-
console.log("WebSocket connection established");
|
|
1140
|
-
const connectionId = Math.random().toString(36).substring(7);
|
|
1141
|
-
this.connections.set(connectionId, ws);
|
|
1142
|
-
ws.on("message", async (data) => {
|
|
1143
|
-
try {
|
|
1144
|
-
const message = JSON.parse(data.toString());
|
|
1145
|
-
const response = await this.handleWebSocketMessage(message);
|
|
1146
|
-
ws.send(JSON.stringify(response));
|
|
1147
|
-
} catch (error) {
|
|
1148
|
-
ws.send(
|
|
1149
|
-
JSON.stringify({
|
|
1150
|
-
error: error.message
|
|
1151
|
-
})
|
|
1152
|
-
);
|
|
1153
|
-
}
|
|
1154
|
-
});
|
|
1155
|
-
ws.on("close", () => {
|
|
1156
|
-
this.connections.delete(connectionId);
|
|
1157
|
-
console.log("WebSocket connection closed");
|
|
1158
|
-
});
|
|
1159
|
-
});
|
|
1160
|
-
}
|
|
1161
|
-
async handleWebSocketMessage(message) {
|
|
1162
|
-
const { type, tool, params } = message;
|
|
1163
|
-
switch (type) {
|
|
1164
|
-
case "execute":
|
|
1165
|
-
return await this.executeMCPTool(tool, params);
|
|
1166
|
-
case "ping":
|
|
1167
|
-
return { type: "pong" };
|
|
1168
|
-
default:
|
|
1169
|
-
throw new Error(`Unknown message type: ${type}`);
|
|
1170
|
-
}
|
|
1171
|
-
}
|
|
1172
|
-
async setupMCPServer() {
|
|
1173
|
-
this.mcpServer = new Server(
|
|
1174
|
-
{
|
|
1175
|
-
name: "stackmemory-railway",
|
|
1176
|
-
version: "1.0.0"
|
|
1177
|
-
},
|
|
1178
|
-
{
|
|
1179
|
-
capabilities: {
|
|
1180
|
-
tools: {},
|
|
1181
|
-
resources: {}
|
|
1182
|
-
}
|
|
1183
|
-
}
|
|
1184
|
-
);
|
|
1185
|
-
this.mcpServer.setRequestHandler("tools/list", async () => {
|
|
1186
|
-
return {
|
|
1187
|
-
tools: [
|
|
1188
|
-
{
|
|
1189
|
-
name: "save_context",
|
|
1190
|
-
description: "Save context to StackMemory",
|
|
1191
|
-
inputSchema: {
|
|
1192
|
-
type: "object",
|
|
1193
|
-
properties: {
|
|
1194
|
-
content: { type: "string" },
|
|
1195
|
-
type: { type: "string" }
|
|
1196
|
-
}
|
|
1197
|
-
}
|
|
1198
|
-
},
|
|
1199
|
-
{
|
|
1200
|
-
name: "load_context",
|
|
1201
|
-
description: "Load context from StackMemory",
|
|
1202
|
-
inputSchema: {
|
|
1203
|
-
type: "object",
|
|
1204
|
-
properties: {
|
|
1205
|
-
query: { type: "string" },
|
|
1206
|
-
limit: { type: "number" }
|
|
1207
|
-
}
|
|
1208
|
-
}
|
|
1209
|
-
}
|
|
1210
|
-
]
|
|
1211
|
-
};
|
|
1212
|
-
});
|
|
1213
|
-
this.mcpServer.setRequestHandler(
|
|
1214
|
-
"tools/call",
|
|
1215
|
-
async (request) => {
|
|
1216
|
-
const { name, arguments: args } = request.params;
|
|
1217
|
-
return await this.executeMCPTool(name, args);
|
|
1218
|
-
}
|
|
1219
|
-
);
|
|
1220
|
-
}
|
|
1221
|
-
async executeMCPTool(tool, params) {
|
|
1222
|
-
switch (tool) {
|
|
1223
|
-
case "save_context": {
|
|
1224
|
-
if (this.pgPool) {
|
|
1225
|
-
const r = await this.pgPool.query(
|
|
1226
|
-
`INSERT INTO contexts (project_id, content, type, metadata)
|
|
1227
|
-
VALUES ($1, $2, $3, $4) RETURNING id`,
|
|
1228
|
-
[params.projectId || "default", params.content, params.type || "general", params.metadata || {}]
|
|
1229
|
-
);
|
|
1230
|
-
return { id: r.rows[0].id, success: true };
|
|
1231
|
-
}
|
|
1232
|
-
const stmt = this.db.prepare(
|
|
1233
|
-
`INSERT INTO contexts (project_id, content, type, metadata) VALUES (?, ?, ?, ?)`
|
|
1234
|
-
);
|
|
1235
|
-
const result = stmt.run(
|
|
1236
|
-
params.projectId || "default",
|
|
1237
|
-
params.content,
|
|
1238
|
-
params.type || "general",
|
|
1239
|
-
JSON.stringify(params.metadata || {})
|
|
1240
|
-
);
|
|
1241
|
-
return { id: result.lastInsertRowid, success: true };
|
|
1242
|
-
}
|
|
1243
|
-
case "load_context": {
|
|
1244
|
-
if (this.pgPool) {
|
|
1245
|
-
const r = await this.pgPool.query(
|
|
1246
|
-
`SELECT * FROM contexts
|
|
1247
|
-
WHERE project_id = $1 AND content ILIKE $2
|
|
1248
|
-
ORDER BY created_at DESC
|
|
1249
|
-
LIMIT $3`,
|
|
1250
|
-
[params.projectId || "default", `%${params.query || ""}%`, params.limit || 10]
|
|
1251
|
-
);
|
|
1252
|
-
return { contexts: r.rows, success: true };
|
|
1253
|
-
}
|
|
1254
|
-
const stmt = this.db.prepare(
|
|
1255
|
-
`SELECT * FROM contexts WHERE project_id = ? AND content LIKE ? ORDER BY created_at DESC LIMIT ?`
|
|
1256
|
-
);
|
|
1257
|
-
const contexts = stmt.all(
|
|
1258
|
-
params.projectId || "default",
|
|
1259
|
-
`%${params.query || ""}%`,
|
|
1260
|
-
params.limit || 10
|
|
1261
|
-
);
|
|
1262
|
-
return { contexts, success: true };
|
|
1263
|
-
}
|
|
1264
|
-
default:
|
|
1265
|
-
throw new Error(`Unknown tool: ${tool}`);
|
|
1266
|
-
}
|
|
1267
|
-
}
|
|
1268
|
-
// Permission helpers
|
|
1269
|
-
hasReadAccess(role, isPublic) {
|
|
1270
|
-
if (isPublic) return true;
|
|
1271
|
-
return role === "admin" || role === "owner" || role === "editor" || role === "viewer";
|
|
1272
|
-
}
|
|
1273
|
-
hasWriteAccess(role) {
|
|
1274
|
-
return role === "admin" || role === "owner" || role === "editor";
|
|
1275
|
-
}
|
|
1276
|
-
async getProjectRole(projectId, userId) {
|
|
1277
|
-
if (this.pgPool) {
|
|
1278
|
-
const r = await this.pgPool.query(
|
|
1279
|
-
"SELECT role FROM project_members WHERE project_id = $1 AND user_id = $2",
|
|
1280
|
-
[projectId, userId]
|
|
1281
|
-
);
|
|
1282
|
-
return r.rows[0]?.role || null;
|
|
1283
|
-
}
|
|
1284
|
-
const row = this.db.prepare("SELECT role FROM project_members WHERE project_id = ? AND user_id = ?").get(projectId, userId);
|
|
1285
|
-
return row?.role || null;
|
|
1286
|
-
}
|
|
1287
|
-
async isProjectPublic(projectId) {
|
|
1288
|
-
if (this.pgPool) {
|
|
1289
|
-
const r = await this.pgPool.query("SELECT is_public FROM projects WHERE id = $1", [projectId]);
|
|
1290
|
-
return !!r.rows[0]?.is_public;
|
|
1291
|
-
}
|
|
1292
|
-
const row = this.db.prepare("SELECT is_public FROM projects WHERE id = ?").get(projectId);
|
|
1293
|
-
return !!row?.is_public;
|
|
1294
|
-
}
|
|
1295
|
-
async ensureProjectOwner(projectId, userId) {
|
|
1296
|
-
if (this.pgPool) {
|
|
1297
|
-
const pr2 = await this.pgPool.query("SELECT 1 FROM projects WHERE id = $1", [projectId]);
|
|
1298
|
-
if (pr2.rowCount === 0) {
|
|
1299
|
-
await this.pgPool.query("INSERT INTO projects (id, name, is_public) VALUES ($1, $2, $3)", [projectId, projectId, false]);
|
|
1300
|
-
}
|
|
1301
|
-
const mr2 = await this.pgPool.query(
|
|
1302
|
-
"SELECT 1 FROM project_members WHERE project_id = $1 AND user_id = $2",
|
|
1303
|
-
[projectId, userId]
|
|
1304
|
-
);
|
|
1305
|
-
if (mr2.rowCount === 0) {
|
|
1306
|
-
await this.pgPool.query(
|
|
1307
|
-
"INSERT INTO project_members (project_id, user_id, role) VALUES ($1, $2, $3)",
|
|
1308
|
-
[projectId, userId, "owner"]
|
|
1309
|
-
);
|
|
1310
|
-
}
|
|
1311
|
-
return;
|
|
1312
|
-
}
|
|
1313
|
-
const pr = this.db.prepare("SELECT 1 FROM projects WHERE id = ?").get(projectId);
|
|
1314
|
-
if (!pr) {
|
|
1315
|
-
this.db.prepare("INSERT INTO projects (id, name, is_public) VALUES (?, ?, ?)").run(projectId, projectId, 0);
|
|
1316
|
-
}
|
|
1317
|
-
const mr = this.db.prepare("SELECT 1 FROM project_members WHERE project_id = ? AND user_id = ?").get(projectId, userId);
|
|
1318
|
-
if (!mr) {
|
|
1319
|
-
this.db.prepare("INSERT INTO project_members (project_id, user_id, role) VALUES (?, ?, ?)").run(projectId, userId, "owner");
|
|
1320
|
-
}
|
|
1321
|
-
}
|
|
1322
|
-
start() {
|
|
1323
|
-
this.httpServer.listen(config.port, "0.0.0.0", () => {
|
|
1324
|
-
console.log(`
|
|
1325
|
-
\u{1F682} Railway MCP Server Started
|
|
1326
|
-
================================
|
|
1327
|
-
Environment: ${config.environment}
|
|
1328
|
-
Port: ${config.port}
|
|
1329
|
-
WebSocket: ${config.enableWebSocket ? "Enabled" : "Disabled"}
|
|
1330
|
-
Analytics: ${config.enableAnalytics ? "Enabled" : "Disabled"}
|
|
1331
|
-
Rate Limiting: ${config.rateLimitEnabled ? "Enabled" : "Disabled"}
|
|
1332
|
-
Auth Mode: ${config.authMode}
|
|
1333
|
-
================================
|
|
1334
|
-
Health: http://localhost:${config.port}/health
|
|
1335
|
-
`);
|
|
1336
|
-
});
|
|
1337
|
-
}
|
|
1338
|
-
}
|
|
1339
|
-
const server = new RailwayMCPServer();
|
|
1340
|
-
server.start();
|
|
1341
|
-
process.on("SIGTERM", () => {
|
|
1342
|
-
console.log("Shutting down gracefully...");
|
|
1343
|
-
process.exit(0);
|
|
1344
|
-
});
|
|
1345
|
-
process.on("SIGINT", () => {
|
|
1346
|
-
console.log("Shutting down...");
|
|
1347
|
-
process.exit(0);
|
|
1348
|
-
});
|
|
1349
|
-
//# sourceMappingURL=index.js.map
|