soigne-ci 0.0.0-stage → 1.0.0

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.
Files changed (168) hide show
  1. package/bin/soigne.js +223 -0
  2. package/git_heal_be/package.json +41 -0
  3. package/git_heal_be/prisma/migrations/20261025152401_first_migration/migration.sql +127 -0
  4. package/git_heal_be/prisma/migrations/migration_lock.toml +3 -0
  5. package/git_heal_be/prisma/schema.prisma +151 -0
  6. package/git_heal_be/prisma7.config.ts +14 -0
  7. package/git_heal_be/src/core/ai/gemini.ts +129 -0
  8. package/git_heal_be/src/core/db/index.ts +1 -0
  9. package/git_heal_be/src/core/db/prisma.ts +38 -0
  10. package/git_heal_be/src/core/events/sseManager.ts +86 -0
  11. package/git_heal_be/src/core/security/crypto.ts +82 -0
  12. package/git_heal_be/src/features/agents/patchAgents.ts +1001 -0
  13. package/git_heal_be/src/features/github/githubService.ts +375 -0
  14. package/git_heal_be/src/features/repos/routes.ts +138 -0
  15. package/git_heal_be/src/features/runs/routes.ts +346 -0
  16. package/git_heal_be/src/features/runs/runService.ts +233 -0
  17. package/git_heal_be/src/features/runs/scraper.ts +223 -0
  18. package/git_heal_be/src/features/runs/terminalLogger.ts +51 -0
  19. package/git_heal_be/src/features/sandbox/workspaceManager.ts +165 -0
  20. package/git_heal_be/src/features/sandbox/workspaceTools.ts +62 -0
  21. package/git_heal_be/src/features/settings/routes.ts +183 -0
  22. package/git_heal_be/src/features/usage/routes.ts +181 -0
  23. package/git_heal_be/src/features/webhooks/routes.ts +50 -0
  24. package/git_heal_be/src/features/webhooks/types.ts +47 -0
  25. package/git_heal_be/src/features/webhooks/verifySignature.ts +50 -0
  26. package/git_heal_be/src/features/webhooks/webHookHandler.ts +235 -0
  27. package/git_heal_be/src/generated/src/prisma/client/browser.ts +49 -0
  28. package/git_heal_be/src/generated/src/prisma/client/client.ts +71 -0
  29. package/git_heal_be/src/generated/src/prisma/client/commonInputTypes.ts +664 -0
  30. package/git_heal_be/src/generated/src/prisma/client/enums.ts +53 -0
  31. package/git_heal_be/src/generated/src/prisma/client/internal/class.ts +254 -0
  32. package/git_heal_be/src/generated/src/prisma/client/internal/prismaNamespace.ts +1418 -0
  33. package/git_heal_be/src/generated/src/prisma/client/internal/prismaNamespaceBrowser.ts +215 -0
  34. package/git_heal_be/src/generated/src/prisma/client/models/Repository.ts +1745 -0
  35. package/git_heal_be/src/generated/src/prisma/client/models/Run.ts +2066 -0
  36. package/git_heal_be/src/generated/src/prisma/client/models/RunStep.ts +1516 -0
  37. package/git_heal_be/src/generated/src/prisma/client/models/TokenUsage.ts +1516 -0
  38. package/git_heal_be/src/generated/src/prisma/client/models/User.ts +1367 -0
  39. package/git_heal_be/src/generated/src/prisma/client/models/UserSettings.ts +1458 -0
  40. package/git_heal_be/src/generated/src/prisma/client/models.ts +17 -0
  41. package/git_heal_be/src/index.ts +39 -0
  42. package/git_heal_be/tsconfig.json +37 -0
  43. package/git_heal_fe/index.html +20 -0
  44. package/git_heal_fe/package.json +39 -0
  45. package/git_heal_fe/public/GitHeal_AI_Health_Logo.png +0 -0
  46. package/git_heal_fe/public/apple-touch-icon.png +0 -0
  47. package/git_heal_fe/public/favicon-16x16.png +0 -0
  48. package/git_heal_fe/public/favicon-32x32.png +0 -0
  49. package/git_heal_fe/public/favicon.ico +0 -0
  50. package/git_heal_fe/public/favicon.png +0 -0
  51. package/git_heal_fe/public/favicon.svg +1 -0
  52. package/git_heal_fe/public/github_login_teddy_assets/README.txt +11 -0
  53. package/git_heal_fe/public/github_login_teddy_assets/bottom-agents/mini-bear-boba.png +0 -0
  54. package/git_heal_fe/public/github_login_teddy_assets/bottom-agents/mini-bear-branch-card.png +0 -0
  55. package/git_heal_fe/public/github_login_teddy_assets/bottom-agents/mini-bear-code-card.png +0 -0
  56. package/git_heal_fe/public/github_login_teddy_assets/bottom-agents/mini-bear-headphones-coding.png +0 -0
  57. package/git_heal_fe/public/github_login_teddy_assets/bottom-agents/mini-robot-coding.png +0 -0
  58. package/git_heal_fe/public/github_login_teddy_assets/bottom-agents/mini-robot-running.png +0 -0
  59. package/git_heal_fe/public/github_login_teddy_assets/bottom-agents/mini-robot-star.png +0 -0
  60. package/git_heal_fe/public/github_login_teddy_assets/full-mockup.png +0 -0
  61. package/git_heal_fe/public/github_login_teddy_assets/main-bears/bear-raising-pull-request-jwt.png +0 -0
  62. package/git_heal_fe/public/github_login_teddy_assets/main-bears/bear-raising-pull-request.png +0 -0
  63. package/git_heal_fe/public/github_login_teddy_assets/main-bears/bear-reading-repositories.png +0 -0
  64. package/git_heal_fe/public/github_login_teddy_assets/main-bears/bear-repo-eating.png +0 -0
  65. package/git_heal_fe/public/github_login_teddy_assets/ui-elements/github-book.png +0 -0
  66. package/git_heal_fe/public/github_login_teddy_assets/ui-elements/pull-request-card.png +0 -0
  67. package/git_heal_fe/public/github_login_teddy_assets/ui-elements/repository-card.png +0 -0
  68. package/git_heal_fe/public/icons.svg +24 -0
  69. package/git_heal_fe/src/App.css +184 -0
  70. package/git_heal_fe/src/App.tsx +145 -0
  71. package/git_heal_fe/src/assets/hero.png +0 -0
  72. package/git_heal_fe/src/assets/react.svg +1 -0
  73. package/git_heal_fe/src/assets/vite.svg +1 -0
  74. package/git_heal_fe/src/components/BearAnimation.tsx +124 -0
  75. package/git_heal_fe/src/components/DiffPreview.tsx +81 -0
  76. package/git_heal_fe/src/components/GitFlowGraph.css +341 -0
  77. package/git_heal_fe/src/components/GitFlowGraph.tsx +216 -0
  78. package/git_heal_fe/src/components/GitHubLoginPage.css +1097 -0
  79. package/git_heal_fe/src/components/GitHubLoginPage.tsx +171 -0
  80. package/git_heal_fe/src/components/PipelinePreview.tsx +156 -0
  81. package/git_heal_fe/src/components/auth/AuthCallbackPage.tsx +46 -0
  82. package/git_heal_fe/src/components/auth/ProtectedRoute.tsx +68 -0
  83. package/git_heal_fe/src/components/common/AppShell.css +154 -0
  84. package/git_heal_fe/src/components/common/AppShell.tsx +57 -0
  85. package/git_heal_fe/src/components/common/AvatarMenu.css +142 -0
  86. package/git_heal_fe/src/components/common/AvatarMenu.tsx +122 -0
  87. package/git_heal_fe/src/components/common/Breadcrumb.css +58 -0
  88. package/git_heal_fe/src/components/common/Breadcrumb.tsx +59 -0
  89. package/git_heal_fe/src/components/common/ConfirmDialog.css +108 -0
  90. package/git_heal_fe/src/components/common/ConfirmDialog.tsx +82 -0
  91. package/git_heal_fe/src/components/common/DiffCard.css +122 -0
  92. package/git_heal_fe/src/components/common/DiffCard.tsx +76 -0
  93. package/git_heal_fe/src/components/common/FloatingSidebar.css +487 -0
  94. package/git_heal_fe/src/components/common/FloatingSidebar.tsx +228 -0
  95. package/git_heal_fe/src/components/common/LimitBanner.css +65 -0
  96. package/git_heal_fe/src/components/common/LimitBanner.tsx +72 -0
  97. package/git_heal_fe/src/components/common/PageHeader.css +47 -0
  98. package/git_heal_fe/src/components/common/PageHeader.tsx +33 -0
  99. package/git_heal_fe/src/components/common/Skeleton.css +26 -0
  100. package/git_heal_fe/src/components/common/Skeleton.tsx +30 -0
  101. package/git_heal_fe/src/components/common/StatusPill.css +122 -0
  102. package/git_heal_fe/src/components/common/StatusPill.tsx +84 -0
  103. package/git_heal_fe/src/components/common/TokenMeter.css +150 -0
  104. package/git_heal_fe/src/components/common/TokenMeter.tsx +154 -0
  105. package/git_heal_fe/src/components/common/TokenPopover.css +375 -0
  106. package/git_heal_fe/src/components/common/TokenPopover.tsx +366 -0
  107. package/git_heal_fe/src/components/dashboard/DashboardPage.css +588 -0
  108. package/git_heal_fe/src/components/dashboard/DashboardPage.tsx +346 -0
  109. package/git_heal_fe/src/components/dashboard/HealingVelocityChart.css +255 -0
  110. package/git_heal_fe/src/components/dashboard/HealingVelocityChart.tsx +286 -0
  111. package/git_heal_fe/src/components/dashboard/LatestPrSpotlight.css +213 -0
  112. package/git_heal_fe/src/components/dashboard/LatestPrSpotlight.tsx +124 -0
  113. package/git_heal_fe/src/components/dashboard/RepoHealthWidget.css +142 -0
  114. package/git_heal_fe/src/components/dashboard/RepoHealthWidget.tsx +67 -0
  115. package/git_heal_fe/src/components/dashboard/RootCauseWidget.css +103 -0
  116. package/git_heal_fe/src/components/dashboard/RootCauseWidget.tsx +114 -0
  117. package/git_heal_fe/src/components/dashboard/RunRow.css +153 -0
  118. package/git_heal_fe/src/components/dashboard/RunRow.tsx +56 -0
  119. package/git_heal_fe/src/components/dashboard/SandboxFleetWidget.css +138 -0
  120. package/git_heal_fe/src/components/dashboard/SandboxFleetWidget.tsx +67 -0
  121. package/git_heal_fe/src/components/dashboard/StatCard.css +57 -0
  122. package/git_heal_fe/src/components/dashboard/StatCard.tsx +22 -0
  123. package/git_heal_fe/src/components/dashboard/UsageCard.css +65 -0
  124. package/git_heal_fe/src/components/dashboard/UsageCard.tsx +71 -0
  125. package/git_heal_fe/src/components/onboarding/OnboardingPage.css +921 -0
  126. package/git_heal_fe/src/components/onboarding/OnboardingPage.tsx +661 -0
  127. package/git_heal_fe/src/components/prs/HealedPrsPage.css +514 -0
  128. package/git_heal_fe/src/components/prs/HealedPrsPage.tsx +276 -0
  129. package/git_heal_fe/src/components/repos/RepoSettingsPage.css +774 -0
  130. package/git_heal_fe/src/components/repos/RepoSettingsPage.tsx +624 -0
  131. package/git_heal_fe/src/components/repos/RepositoriesPage.css +708 -0
  132. package/git_heal_fe/src/components/repos/RepositoriesPage.tsx +448 -0
  133. package/git_heal_fe/src/components/runs/PipelineTimeline.css +186 -0
  134. package/git_heal_fe/src/components/runs/PipelineTimeline.tsx +84 -0
  135. package/git_heal_fe/src/components/runs/RunDetailPage.css +727 -0
  136. package/git_heal_fe/src/components/runs/RunDetailPage.tsx +556 -0
  137. package/git_heal_fe/src/components/runs/TerminalStream.css +312 -0
  138. package/git_heal_fe/src/components/runs/TerminalStream.tsx +130 -0
  139. package/git_heal_fe/src/components/settings/SettingsPage.css +628 -0
  140. package/git_heal_fe/src/components/settings/SettingsPage.tsx +673 -0
  141. package/git_heal_fe/src/components/settings/ThemeCustomizer.css +379 -0
  142. package/git_heal_fe/src/components/settings/ThemeCustomizer.tsx +286 -0
  143. package/git_heal_fe/src/components/settings/TypedConfirmDialog.css +118 -0
  144. package/git_heal_fe/src/components/settings/TypedConfirmDialog.tsx +92 -0
  145. package/git_heal_fe/src/components/usage/StageBreakdown.css +116 -0
  146. package/git_heal_fe/src/components/usage/StageBreakdown.tsx +113 -0
  147. package/git_heal_fe/src/components/usage/UsageChart.css +129 -0
  148. package/git_heal_fe/src/components/usage/UsageChart.tsx +194 -0
  149. package/git_heal_fe/src/components/usage/UsagePage.css +655 -0
  150. package/git_heal_fe/src/components/usage/UsagePage.tsx +446 -0
  151. package/git_heal_fe/src/context/AuthContext.tsx +94 -0
  152. package/git_heal_fe/src/hooks/useRunPolling.ts +54 -0
  153. package/git_heal_fe/src/hooks/useSSE.ts +131 -0
  154. package/git_heal_fe/src/index.css +29 -0
  155. package/git_heal_fe/src/main.tsx +13 -0
  156. package/git_heal_fe/src/services/api.ts +593 -0
  157. package/git_heal_fe/src/test/guardsAndUtils.test.ts +100 -0
  158. package/git_heal_fe/src/test/stageD_tokenAndShell.test.ts +129 -0
  159. package/git_heal_fe/src/types/index.ts +183 -0
  160. package/git_heal_fe/src/utils/themeManager.ts +134 -0
  161. package/git_heal_fe/src/utils/tokenUtils.ts +110 -0
  162. package/git_heal_fe/tsconfig.app.json +26 -0
  163. package/git_heal_fe/tsconfig.json +7 -0
  164. package/git_heal_fe/tsconfig.node.json +23 -0
  165. package/git_heal_fe/vite.config.ts +24 -0
  166. package/package.json +32 -4
  167. package/soigne.config.json +11 -0
  168. package/README.md +0 -3
package/bin/soigne.js ADDED
@@ -0,0 +1,223 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import crypto from 'node:crypto';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { spawn, spawnSync } from 'node:child_process';
7
+ import { parseArgs } from 'node:util';
8
+
9
+ const __filename = fileURLToPath(import.meta.url);
10
+ const __dirname = path.dirname(__filename);
11
+ const PKG_ROOT = path.resolve(__dirname, '..');
12
+ const BE_DIR = path.join(PKG_ROOT, 'git_heal_be');
13
+ const FE_DIR = path.join(PKG_ROOT, 'git_heal_fe');
14
+
15
+ function printHelp() {
16
+ console.log(`
17
+ Soigné — Self-Hosted Autonomous CI/CD Healing Appliance
18
+
19
+ Usage:
20
+ soigne [command] [options]
21
+
22
+ Commands:
23
+ init Create a starter soigne.config.json in the current folder
24
+ (default) Start Soigné backend and frontend
25
+
26
+ Options:
27
+ --config <path> Path to a custom soigne.config.json
28
+ --ui-port <port> Frontend port (default: 5173)
29
+ --api-port <port> Backend API port (default: 3001)
30
+ --api-url <url> API URL passed to frontend (default: http://localhost:<apiPort>/api)
31
+ --db <url> PostgreSQL connection string
32
+ --skip-db Skip prisma generate & db push on startup
33
+ --force Overwrite existing soigne.config.json when running init
34
+ -h, --help Show this help message
35
+ `);
36
+ }
37
+
38
+ function readJsonIfExists(filePath) {
39
+ if (!filePath || !fs.existsSync(filePath)) return {};
40
+ try {
41
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
42
+ } catch (err) {
43
+ console.error(`[soigne] Failed to parse config file ${filePath}:`, err.message);
44
+ process.exit(1);
45
+ }
46
+ }
47
+
48
+ function resolveBin(name, searchDirs) {
49
+ const isWin = process.platform === 'win32';
50
+ const binName = isWin ? `${name}.cmd` : name;
51
+ for (const dir of searchDirs) {
52
+ const candidate = path.join(dir, 'node_modules', '.bin', binName);
53
+ if (fs.existsSync(candidate)) return candidate;
54
+ }
55
+ return binName;
56
+ }
57
+
58
+ function ensureInstalled(dir, label) {
59
+ if (fs.existsSync(path.join(dir, 'node_modules'))) return;
60
+ console.log(`[soigne] Installing ${label} dependencies...`);
61
+ const isWin = process.platform === 'win32';
62
+ const res = spawnSync(isWin ? 'npm.cmd' : 'npm', ['install'], {
63
+ cwd: dir,
64
+ stdio: 'inherit',
65
+ shell: isWin,
66
+ });
67
+ if (res.status !== 0) {
68
+ console.error(`[soigne] Failed to install ${label} dependencies.`);
69
+ process.exit(res.status || 1);
70
+ }
71
+ }
72
+
73
+ const { values, positionals } = parseArgs({
74
+ options: {
75
+ config: { type: 'string' },
76
+ 'ui-port': { type: 'string' },
77
+ 'api-port': { type: 'string' },
78
+ 'api-url': { type: 'string' },
79
+ db: { type: 'string' },
80
+ 'skip-db': { type: 'boolean', default: false },
81
+ force: { type: 'boolean', default: false },
82
+ help: { type: 'boolean', short: 'h', default: false },
83
+ },
84
+ allowPositionals: true,
85
+ });
86
+
87
+ if (values.help) {
88
+ printHelp();
89
+ process.exit(0);
90
+ }
91
+
92
+ if (positionals[0] === 'init') {
93
+ const targetPath = path.join(process.cwd(), 'soigne.config.json');
94
+ if (fs.existsSync(targetPath) && !values.force) {
95
+ console.error(`[soigne] ${targetPath} already exists. Use --force to overwrite.`);
96
+ process.exit(1);
97
+ }
98
+ const starterConfig = {
99
+ uiPort: 5173,
100
+ apiPort: 3001,
101
+ apiUrl: 'http://localhost:3001/api',
102
+ databaseUrl: 'postgresql://postgres:postgres@localhost:5432/soigne_db?schema=public',
103
+ encryptionKey: crypto.randomBytes(32).toString('hex'),
104
+ githubAppId: '',
105
+ githubPrivateKey: '',
106
+ githubWebhookSecret: '',
107
+ };
108
+ fs.writeFileSync(targetPath, JSON.stringify(starterConfig, null, 2) + '\n', 'utf8');
109
+ console.log(`[soigne] Created ${targetPath}`);
110
+ console.log('[soigne] Edit databaseUrl and GitHub App fields if needed, then run: soigne');
111
+ process.exit(0);
112
+ }
113
+
114
+ const defaultConfig = readJsonIfExists(path.join(PKG_ROOT, 'soigne.config.json'));
115
+ const cwdConfigPath = values.config
116
+ ? path.resolve(process.cwd(), values.config)
117
+ : path.join(process.cwd(), 'soigne.config.json');
118
+ const userConfig = cwdConfigPath !== path.join(PKG_ROOT, 'soigne.config.json')
119
+ ? readJsonIfExists(cwdConfigPath)
120
+ : {};
121
+
122
+ const config = { ...defaultConfig, ...userConfig };
123
+
124
+ if (values['ui-port']) config.uiPort = Number(values['ui-port']);
125
+ if (values['api-port']) {
126
+ config.apiPort = Number(values['api-port']);
127
+ if (!values['api-url'] && !userConfig.apiUrl) {
128
+ config.apiUrl = `http://localhost:${config.apiPort}/api`;
129
+ }
130
+ }
131
+ if (values['api-url']) config.apiUrl = values['api-url'];
132
+ if (values.db) config.databaseUrl = values.db;
133
+
134
+ const beEnv = {
135
+ ...process.env,
136
+ PORT: String(config.apiPort || 3001),
137
+ ...(config.databaseUrl ? { DATABASE_URL: config.databaseUrl } : {}),
138
+ ...(config.encryptionKey ? { ENCRYPTION_KEY: config.encryptionKey } : {}),
139
+ ...(config.geminiApiKey ? { GEMINI_API_KEY: config.geminiApiKey } : {}),
140
+ ...(config.githubAppId ? { GITHUB_APP_ID: config.githubAppId } : {}),
141
+ ...(config.githubPrivateKey ? { GITHUB_PRIVATE_KEY: config.githubPrivateKey } : {}),
142
+ ...(config.githubWebhookSecret ? { GITHUB_WEBHOOK_SECRET: config.githubWebhookSecret } : {}),
143
+ };
144
+
145
+ const feEnv = {
146
+ ...process.env,
147
+ VITE_API_BASE_URL: config.apiUrl,
148
+ VITE_API_URL: config.apiUrl,
149
+ };
150
+
151
+ const isWin = process.platform === 'win32';
152
+
153
+ ensureInstalled(BE_DIR, 'backend');
154
+ ensureInstalled(FE_DIR, 'frontend');
155
+
156
+ if (!values['skip-db']) {
157
+ console.log('[soigne] Generating Prisma client...');
158
+ const prismaBin = resolveBin('prisma', [BE_DIR, PKG_ROOT]);
159
+ const gen = spawnSync(prismaBin, ['generate', '--config', 'prisma7.config.ts'], {
160
+ cwd: BE_DIR,
161
+ env: beEnv,
162
+ stdio: 'inherit',
163
+ shell: isWin,
164
+ });
165
+ if (gen.status !== 0) {
166
+ console.warn('[soigne] prisma generate exited with non-zero status; continuing...');
167
+ }
168
+
169
+ console.log('[soigne] Pushing database schema...');
170
+ const push = spawnSync(prismaBin, ['db', 'push', '--config', 'prisma7.config.ts'], {
171
+ cwd: BE_DIR,
172
+ env: beEnv,
173
+ stdio: 'inherit',
174
+ shell: isWin,
175
+ });
176
+ if (push.status !== 0) {
177
+ console.warn('[soigne] prisma db push failed (is PostgreSQL running?). Continuing startup...');
178
+ }
179
+ }
180
+
181
+ console.log(`[soigne] Starting backend on port ${beEnv.PORT}...`);
182
+ const tsxBin = resolveBin('tsx', [BE_DIR, PKG_ROOT]);
183
+ const beProc = spawn(tsxBin, ['src/index.ts'], {
184
+ cwd: BE_DIR,
185
+ env: beEnv,
186
+ stdio: 'inherit',
187
+ shell: isWin,
188
+ });
189
+
190
+ console.log(`[soigne] Starting frontend on port ${config.uiPort} -> ${config.apiUrl}...`);
191
+ const viteBin = resolveBin('vite', [FE_DIR, PKG_ROOT]);
192
+ const feProc = spawn(viteBin, ['--port', String(config.uiPort), '--host'], {
193
+ cwd: FE_DIR,
194
+ env: feEnv,
195
+ stdio: 'inherit',
196
+ shell: isWin,
197
+ });
198
+
199
+ function shutdown(signal) {
200
+ console.log(`\n[soigne] Received ${signal}, shutting down...`);
201
+ if (!beProc.killed) beProc.kill('SIGTERM');
202
+ if (!feProc.killed) feProc.kill('SIGTERM');
203
+ process.exit(0);
204
+ }
205
+
206
+ process.on('SIGINT', () => shutdown('SIGINT'));
207
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
208
+
209
+ beProc.on('exit', (code) => {
210
+ if (code !== 0 && code !== null) {
211
+ console.error(`[soigne] Backend exited with code ${code}`);
212
+ if (!feProc.killed) feProc.kill('SIGTERM');
213
+ process.exit(code);
214
+ }
215
+ });
216
+
217
+ feProc.on('exit', (code) => {
218
+ if (code !== 0 && code !== null) {
219
+ console.error(`[soigne] Frontend exited with code ${code}`);
220
+ if (!beProc.killed) beProc.kill('SIGTERM');
221
+ process.exit(code);
222
+ }
223
+ });
@@ -0,0 +1,41 @@
1
+ {
2
+ "devDependencies": {
3
+ "@types/cors": "^2.8.19",
4
+ "@types/dotenv": "^6.1.1",
5
+ "@types/express": "^5.0.6",
6
+ "@types/node": "^26.6.5",
7
+ "prisma": "^7.10.1",
8
+ "tsx": "^4.23.15",
9
+ "typescript": "^7.0.2"
10
+ },
11
+ "dependencies": {
12
+ "@langchain/core": "^1.2.17",
13
+ "@langchain/google-genai": "^2.3.2",
14
+ "@langchain/langgraph": "^1.5.0",
15
+ "@prisma/adapter-pg": "^7.10.1",
16
+ "@prisma/client": "^7.10.1",
17
+ "cors": "^2.8.6",
18
+ "dotenv": "^18.0.7",
19
+ "express": "^5.3.0",
20
+ "jsonwebtoken": "^9.0.3",
21
+ "langchain": "^1.5.16",
22
+ "pg": "^8.23.1"
23
+ },
24
+ "name": "soigne_be",
25
+ "version": "1.0.0",
26
+ "description": "Soigné - Autonomous Self-Healing CI/CD Agent Backend",
27
+ "main": "index.js",
28
+ "scripts": {
29
+ "dev": "tsx watch src/index.ts",
30
+ "build": "tsc",
31
+ "start": "node dist/index.js",
32
+ "db:generate": "prisma generate",
33
+ "db:push": "prisma db push",
34
+ "db:migrate": "prisma migrate dev --config prisma7.config.ts",
35
+ "db:studio": "prisma studio --config prisma7.config.ts"
36
+ },
37
+ "keywords": [],
38
+ "author": "",
39
+ "license": "ISC",
40
+ "type": "module"
41
+ }
@@ -0,0 +1,127 @@
1
+ -- CreateEnum
2
+ CREATE TYPE "RunStatus" AS ENUM ('DETECTED', 'INVESTIGATING', 'PATCHING', 'VERIFYING', 'PR_OPENED', 'MERGED', 'FAILED_TO_FIX', 'QUEUED');
3
+
4
+ -- CreateEnum
5
+ CREATE TYPE "RunStepName" AS ENUM ('Detect', 'Investigate', 'Patch', 'Verify', 'Open_PR');
6
+
7
+ -- CreateEnum
8
+ CREATE TYPE "RunStepStatus" AS ENUM ('pending', 'in_progress', 'completed', 'failed');
9
+
10
+ -- CreateEnum
11
+ CREATE TYPE "TokenStage" AS ENUM ('detect', 'patch', 'critique');
12
+
13
+ -- CreateTable
14
+ CREATE TABLE "User" (
15
+ "id" TEXT NOT NULL,
16
+ "login" TEXT NOT NULL,
17
+ "name" TEXT,
18
+ "email" TEXT,
19
+ "avatarUrl" TEXT,
20
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
21
+ "updatedAt" TIMESTAMP(3) NOT NULL,
22
+
23
+ CONSTRAINT "User_pkey" PRIMARY KEY ("id")
24
+ );
25
+
26
+ -- CreateTable
27
+ CREATE TABLE "UserSettings" (
28
+ "id" TEXT NOT NULL,
29
+ "emailOnPrOpened" BOOLEAN NOT NULL DEFAULT true,
30
+ "emailOnFixFailed" BOOLEAN NOT NULL DEFAULT true,
31
+ "watchedBranches" TEXT[] DEFAULT ARRAY[]::TEXT[],
32
+ "onlyWatchedBranches" BOOLEAN NOT NULL DEFAULT false,
33
+ "pauseOnThresholdEnabled" BOOLEAN NOT NULL DEFAULT false,
34
+ "pauseThresholdPercent" DOUBLE PRECISION NOT NULL DEFAULT 80,
35
+ "emailOnTokenThreshold" BOOLEAN NOT NULL DEFAULT true,
36
+
37
+ CONSTRAINT "UserSettings_pkey" PRIMARY KEY ("id")
38
+ );
39
+
40
+ -- CreateTable
41
+ CREATE TABLE "Repository" (
42
+ "id" TEXT NOT NULL,
43
+ "name" TEXT NOT NULL,
44
+ "fullName" TEXT NOT NULL,
45
+ "isPrivate" BOOLEAN NOT NULL DEFAULT false,
46
+ "language" TEXT,
47
+ "hasWorkflows" BOOLEAN NOT NULL DEFAULT false,
48
+ "workFlowFile" TEXT,
49
+ "lastCiStatus" TEXT,
50
+ "monitored" BOOLEAN NOT NULL DEFAULT true,
51
+ "installationId" BIGINT NOT NULL,
52
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
53
+ "updatedAt" TIMESTAMP(3) NOT NULL,
54
+
55
+ CONSTRAINT "Repository_pkey" PRIMARY KEY ("id")
56
+ );
57
+
58
+ -- CreateTable
59
+ CREATE TABLE "Run" (
60
+ "id" TEXT NOT NULL,
61
+ "repoId" TEXT NOT NULL,
62
+ "branch" TEXT NOT NULL,
63
+ "commitHash" TEXT NOT NULL,
64
+ "commitMessage" TEXT,
65
+ "githubRunUrl" TEXT NOT NULL,
66
+ "duration" INTEGER,
67
+ "status" "RunStatus" NOT NULL DEFAULT 'QUEUED',
68
+ "prNumber" INTEGER,
69
+ "prUrl" TEXT,
70
+ "rootCause" TEXT,
71
+ "failureReason" TEXT,
72
+ "humanRecommendation" TEXT,
73
+ "failingLog" JSONB,
74
+ "patch" JSONB,
75
+ "sandbox" JSONB,
76
+ "reasoningSteps" JSONB,
77
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
78
+ "updatedAt" TIMESTAMP(3) NOT NULL,
79
+
80
+ CONSTRAINT "Run_pkey" PRIMARY KEY ("id")
81
+ );
82
+
83
+ -- CreateTable
84
+ CREATE TABLE "RunStep" (
85
+ "id" TEXT NOT NULL,
86
+ "runId" TEXT NOT NULL,
87
+ "name" "RunStepName" NOT NULL,
88
+ "status" "RunStepStatus" NOT NULL DEFAULT 'pending',
89
+ "tokens" INTEGER NOT NULL DEFAULT 0,
90
+ "duration" INTEGER,
91
+ "summary" TEXT,
92
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
93
+
94
+ CONSTRAINT "RunStep_pkey" PRIMARY KEY ("id")
95
+ );
96
+
97
+ -- CreateTable
98
+ CREATE TABLE "TokenUsage" (
99
+ "id" TEXT NOT NULL,
100
+ "repoId" TEXT NOT NULL,
101
+ "date" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
102
+ "stage" "TokenStage" NOT NULL,
103
+ "tokens" INTEGER NOT NULL,
104
+ "inputTokens" INTEGER NOT NULL DEFAULT 0,
105
+ "outputTokens" INTEGER NOT NULL DEFAULT 0,
106
+ "totalTokens" INTEGER NOT NULL DEFAULT 0,
107
+
108
+ CONSTRAINT "TokenUsage_pkey" PRIMARY KEY ("id")
109
+ );
110
+
111
+ -- CreateIndex
112
+ CREATE UNIQUE INDEX "User_login_key" ON "User"("login");
113
+
114
+ -- CreateIndex
115
+ CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
116
+
117
+ -- AddForeignKey
118
+ ALTER TABLE "UserSettings" ADD CONSTRAINT "UserSettings_id_fkey" FOREIGN KEY ("id") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
119
+
120
+ -- AddForeignKey
121
+ ALTER TABLE "Run" ADD CONSTRAINT "Run_repoId_fkey" FOREIGN KEY ("repoId") REFERENCES "Repository"("id") ON DELETE CASCADE ON UPDATE CASCADE;
122
+
123
+ -- AddForeignKey
124
+ ALTER TABLE "RunStep" ADD CONSTRAINT "RunStep_runId_fkey" FOREIGN KEY ("runId") REFERENCES "Run"("id") ON DELETE CASCADE ON UPDATE CASCADE;
125
+
126
+ -- AddForeignKey
127
+ ALTER TABLE "TokenUsage" ADD CONSTRAINT "TokenUsage_repoId_fkey" FOREIGN KEY ("repoId") REFERENCES "Repository"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,3 @@
1
+ # Please do not edit this file manually
2
+ # It should be added in your version-control system (e.g., Git)
3
+ provider = "postgresql"
@@ -0,0 +1,151 @@
1
+
2
+ generator client {
3
+ provider = "prisma-client"
4
+ output = "../src/generated/prisma/client"
5
+ }
6
+
7
+ datasource db {
8
+ provider = "postgresql"
9
+ }
10
+
11
+ model User {
12
+ id String @id @default(cuid())
13
+ login String @unique
14
+ name String?
15
+ email String? @unique
16
+ avatarUrl String?
17
+ createdAt DateTime @default(now())
18
+ updatedAt DateTime @updatedAt
19
+
20
+ settings UserSettings?
21
+ }
22
+
23
+ model UserSettings {
24
+ id String @id
25
+ geminiApiKey String?
26
+ geminiModel String? @default("gemini-2.5-flash")
27
+ dailyTokenLimit Int @default(500000)
28
+ emailOnPrOpened Boolean @default(true)
29
+ emailOnFixFailed Boolean @default(true)
30
+ watchedBranches String[] @default([])
31
+ onlyWatchedBranches Boolean @default(false)
32
+ pauseOnThresholdEnabled Boolean @default(false)
33
+ pauseThresholdPercent Float @default(80)
34
+ emailOnTokenThreshold Boolean @default(true)
35
+ envVars Json?
36
+ user User @relation(fields: [id], references: [id], onDelete: Cascade)
37
+ }
38
+
39
+ model Repository{
40
+ id String @id @default(cuid())
41
+ name String
42
+ fullName String
43
+ isPrivate Boolean @default(false)
44
+ language String?
45
+ hasWorkflows Boolean @default(false)
46
+ workFlowFile String? @default(".github/workflows/ci.yml")
47
+ lastCiStatus String?
48
+ monitored Boolean @default(true)
49
+ installationId BigInt
50
+ watchedBranches String[] @default(["main", "master", "release/*"])
51
+ onlyWatchedBranches Boolean @default(true)
52
+ envVars Json?
53
+ prPrefix String? @default("soigne/fix-")
54
+ autoLabels String? @default("soigne-verified, automated-fix")
55
+ testCommand String?
56
+ autoFixMode String? @default("auto_pr")
57
+ aiModel String? @default("gemini")
58
+ createdAt DateTime @default(now())
59
+ updatedAt DateTime @updatedAt
60
+
61
+ runs Run[]
62
+ tokenUsages TokenUsage[]
63
+ }
64
+
65
+ model Run {
66
+ id String @id @default(cuid())
67
+ repoId String
68
+ branch String
69
+ commitHash String
70
+ commitMessage String?
71
+ githubRunUrl String
72
+ duration Int?
73
+ status RunStatus @default(QUEUED)
74
+
75
+ prNumber Int?
76
+ prUrl String?
77
+ rootCause String?
78
+ failureReason String?
79
+ humanRecommendation String?
80
+
81
+ failingLog Json?
82
+ patch Json?
83
+ sandbox Json?
84
+ reasoningSteps Json?
85
+ terminalLogs Json?
86
+
87
+ createdAt DateTime @default(now())
88
+ updatedAt DateTime @updatedAt
89
+
90
+ repository Repository @relation(fields: [repoId], references: [id], onDelete: Cascade)
91
+ steps RunStep[]
92
+ }
93
+
94
+ enum RunStatus {
95
+ DETECTED
96
+ INVESTIGATING
97
+ PATCHING
98
+ VERIFYING
99
+ PR_OPENED
100
+ MERGED
101
+ FAILED_TO_FIX
102
+ QUEUED
103
+ SUPERSEDED
104
+ }
105
+
106
+ model RunStep {
107
+ id String @id @default(cuid())
108
+ runId String
109
+ name RunStepName
110
+ status RunStepStatus @default(pending)
111
+ tokens Int @default(0)
112
+ duration Int?
113
+ summary String?
114
+ createdAt DateTime @default(now())
115
+
116
+ run Run @relation(fields: [runId], references: [id], onDelete: Cascade)
117
+ }
118
+
119
+ enum RunStepName {
120
+ Detect
121
+ Investigate
122
+ Patch
123
+ Verify
124
+ Open_PR
125
+ }
126
+
127
+ enum RunStepStatus {
128
+ pending
129
+ in_progress
130
+ completed
131
+ failed
132
+ skipped
133
+ }
134
+
135
+ model TokenUsage {
136
+ id String @id @default(cuid())
137
+ repoId String
138
+ date DateTime @default(now())
139
+ stage TokenStage
140
+ tokens Int
141
+ inputTokens Int @default(0)
142
+ outputTokens Int @default(0)
143
+ totalTokens Int @default(0)
144
+ repository Repository @relation(fields: [repoId], references: [id], onDelete: Cascade)
145
+ }
146
+
147
+ enum TokenStage {
148
+ detect
149
+ patch
150
+ critique
151
+ }
@@ -0,0 +1,14 @@
1
+ // This file was generated by Prisma, and assumes you have installed the following:
2
+ // npm install --save-dev prisma dotenv
3
+ import "dotenv/config";
4
+ import { defineConfig, env } from "prisma/config";
5
+
6
+ export default defineConfig({
7
+ schema: "prisma/schema.prisma",
8
+ migrations: {
9
+ path: "prisma/migrations",
10
+ },
11
+ datasource: {
12
+ url: env("DATABASE_URL"),
13
+ },
14
+ });
@@ -0,0 +1,129 @@
1
+ import 'dotenv/config';
2
+ import { ChatGoogleGenerativeAI } from '@langchain/google-genai';
3
+
4
+ export interface GeminiTextModel {
5
+ id: string;
6
+ displayName: string;
7
+ description: string;
8
+ inputTokenLimit?: number;
9
+ }
10
+
11
+ const defaultApiKey = process.env.GEMINI_API_KEY || '';
12
+
13
+
14
+ export async function fetchAvailableGeminiModels(apiKey?: string): Promise<GeminiTextModel[]> {
15
+ const key = apiKey?.trim() || defaultApiKey;
16
+ if (!key) return [];
17
+
18
+ try {
19
+ const res = await fetch(`https://generativelanguage.googleapis.com/v1beta/models?key=${key}`);
20
+ if (!res.ok) {
21
+ console.warn(`[Gemini] Failed to fetch models from Google: ${res.statusText}`);
22
+ return [];
23
+ }
24
+
25
+ const data = (await res.json()) as { models?: any[] };
26
+ const allModels = data.models || [];
27
+
28
+ return allModels
29
+ .filter((m) => {
30
+ const hasGenerate = m.supportedGenerationMethods?.includes('generateContent');
31
+ const name = (m.name || '').toLowerCase();
32
+ const isNonText =
33
+ name.includes('tts') ||
34
+ name.includes('embedding') ||
35
+ name.includes('imagen') ||
36
+ name.includes('aqa');
37
+
38
+ return hasGenerate && !isNonText && name.includes('gemini');
39
+ })
40
+ .map((m) => ({
41
+ id: m.name.replace(/^models\//, ''),
42
+ displayName: m.displayName || m.name.replace(/^models\//, ''),
43
+ description: m.description || '',
44
+ inputTokenLimit: m.inputTokenLimit,
45
+ }));
46
+ } catch (err) {
47
+ console.error('[Gemini] Error fetching live models:', err);
48
+ return [];
49
+ }
50
+ }
51
+
52
+
53
+ /**
54
+ * Probes a specific Gemini model to check if it's accepting requests (returns 200 OK)
55
+ */
56
+ export async function probeGeminiModel(apiKey: string, modelName: string): Promise<boolean> {
57
+ try {
58
+ const res = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${modelName}:generateContent?key=${apiKey}`, {
59
+ method: 'POST',
60
+ headers: { 'Content-Type': 'application/json' },
61
+ body: JSON.stringify({ contents: [{ parts: [{ text: 'ping' }] }] }),
62
+ signal: AbortSignal.timeout(4000),
63
+ });
64
+ return res.status === 200;
65
+ } catch {
66
+ return false;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Finds an available, non-failing working model from Google's live models API
72
+ * if the preferred model suffers from 429 (quota), 503 (high demand), or 404 (retired).
73
+ */
74
+ export async function findWorkingGeminiModel(apiKey: string, preferredModel?: string): Promise<string> {
75
+ // 1. If preferred model is working, use it immediately
76
+ if (preferredModel && (await probeGeminiModel(apiKey, preferredModel))) {
77
+ return preferredModel;
78
+ }
79
+
80
+ // 2. Query available models dynamically from Google's live models API
81
+ const liveModels = await fetchAvailableGeminiModels(apiKey);
82
+
83
+ // 3. Sort candidates: prioritize flash-lite and flash models (accessible to free and new users)
84
+ const candidates = liveModels
85
+ .map((m) => m.id)
86
+ .filter((id) => id !== preferredModel)
87
+ .sort((a, b) => {
88
+ const score = (id: string) => {
89
+ if (id.includes('flash-lite')) return 3;
90
+ if (id.includes('flash')) return 2;
91
+ if (id.includes('pro')) return 1;
92
+ return 0;
93
+ };
94
+ return score(b) - score(a);
95
+ });
96
+
97
+ // 4. Probe candidates in priority order and return the first responsive one
98
+ for (const candidate of candidates) {
99
+ console.log(`[Gemini Probe] Probing candidate model '${candidate}'...`);
100
+ const isWorking = await probeGeminiModel(apiKey, candidate);
101
+ if (isWorking) {
102
+ console.log(`[Gemini Probe] Found responsive working model: '${candidate}'`);
103
+ return candidate;
104
+ }
105
+ }
106
+
107
+ // Fallback to gemini-3.1-flash-lite if probe list is exhausted
108
+ return 'gemini-3.1-flash-lite';
109
+ }
110
+
111
+ export function getGeminiModel(customApiKey?: string, customModelName?: string) {
112
+ const apiKey = customApiKey?.trim() || defaultApiKey;
113
+ if (!apiKey) {
114
+ throw new Error('No Gemini API key available. Please configure your key in Settings or server .env');
115
+ }
116
+
117
+ const model = customModelName?.trim() || 'gemini-3.8-flash';
118
+
119
+ return new ChatGoogleGenerativeAI({
120
+ model,
121
+ temperature: 0.1,
122
+ maxRetries: 1,
123
+ apiKey,
124
+ });
125
+ }
126
+
127
+ // Backward-compatible default instance
128
+ export const geminiModel = getGeminiModel();
129
+ export const gemini38Model = geminiModel;
@@ -0,0 +1 @@
1
+ export * from './prisma.js';