@codepulse-oss/web 0.0.0-stage → 3.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.
- package/dist/__tests__/github-app.test.d.ts +2 -0
- package/dist/__tests__/github-app.test.d.ts.map +1 -0
- package/dist/__tests__/github-app.test.js +91 -0
- package/dist/__tests__/github-app.test.js.map +1 -0
- package/dist/__tests__/i18n.test.d.ts +2 -0
- package/dist/__tests__/i18n.test.d.ts.map +1 -0
- package/dist/__tests__/i18n.test.js +76 -0
- package/dist/__tests__/i18n.test.js.map +1 -0
- package/dist/__tests__/onboarding-apis.test.d.ts +2 -0
- package/dist/__tests__/onboarding-apis.test.d.ts.map +1 -0
- package/dist/__tests__/onboarding-apis.test.js +152 -0
- package/dist/__tests__/onboarding-apis.test.js.map +1 -0
- package/dist/__tests__/phase5-web.test.d.ts +2 -0
- package/dist/__tests__/phase5-web.test.d.ts.map +1 -0
- package/dist/__tests__/phase5-web.test.js +72 -0
- package/dist/__tests__/phase5-web.test.js.map +1 -0
- package/dist/__tests__/poller-vault.test.d.ts +2 -0
- package/dist/__tests__/poller-vault.test.d.ts.map +1 -0
- package/dist/__tests__/poller-vault.test.js +150 -0
- package/dist/__tests__/poller-vault.test.js.map +1 -0
- package/dist/__tests__/v1-routes.test.d.ts +2 -0
- package/dist/__tests__/v1-routes.test.d.ts.map +1 -0
- package/dist/__tests__/v1-routes.test.js +133 -0
- package/dist/__tests__/v1-routes.test.js.map +1 -0
- package/dist/__tests__/v1.1-settings-telemetry.test.d.ts +2 -0
- package/dist/__tests__/v1.1-settings-telemetry.test.d.ts.map +1 -0
- package/dist/__tests__/v1.1-settings-telemetry.test.js +95 -0
- package/dist/__tests__/v1.1-settings-telemetry.test.js.map +1 -0
- package/dist/__tests__/v2-routes.test.d.ts +2 -0
- package/dist/__tests__/v2-routes.test.d.ts.map +1 -0
- package/dist/__tests__/v2-routes.test.js +61 -0
- package/dist/__tests__/v2-routes.test.js.map +1 -0
- package/dist/__tests__/v3-routes.test.d.ts +2 -0
- package/dist/__tests__/v3-routes.test.d.ts.map +1 -0
- package/dist/__tests__/v3-routes.test.js +120 -0
- package/dist/__tests__/v3-routes.test.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/dist/server.d.ts +84 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +2077 -0
- package/dist/server.js.map +1 -0
- package/package.json +49 -4
- package/public/dist/app.bundle.js +2346 -0
- package/public/dist/app.bundle.js.map +7 -0
- package/public/fonts/cairo-arabic-400-normal.woff2 +0 -0
- package/public/fonts/cairo-arabic-500-normal.woff2 +0 -0
- package/public/fonts/cairo-arabic-600-normal.woff2 +0 -0
- package/public/fonts/cairo-arabic-700-normal.woff2 +0 -0
- package/public/fonts/cairo-latin-400-normal.woff2 +0 -0
- package/public/fonts/cairo-latin-500-normal.woff2 +0 -0
- package/public/fonts/cairo-latin-600-normal.woff2 +0 -0
- package/public/fonts/cairo-latin-700-normal.woff2 +0 -0
- package/public/fonts/jetbrains-mono-latin-400-normal.woff2 +0 -0
- package/public/fonts/jetbrains-mono-latin-500-normal.woff2 +0 -0
- package/public/fonts/jetbrains-mono-latin-600-normal.woff2 +0 -0
- package/public/fonts/jetbrains-mono-latin-700-normal.woff2 +0 -0
- package/public/fonts/plus-jakarta-sans-latin-400-normal.woff2 +0 -0
- package/public/fonts/plus-jakarta-sans-latin-500-normal.woff2 +0 -0
- package/public/fonts/plus-jakarta-sans-latin-600-normal.woff2 +0 -0
- package/public/fonts/plus-jakarta-sans-latin-700-normal.woff2 +0 -0
- package/public/fonts/plus-jakarta-sans-latin-ext-400-normal.woff2 +0 -0
- package/public/fonts/plus-jakarta-sans-latin-ext-500-normal.woff2 +0 -0
- package/public/fonts/plus-jakarta-sans-latin-ext-600-normal.woff2 +0 -0
- package/public/fonts/plus-jakarta-sans-latin-ext-700-normal.woff2 +0 -0
- package/public/i18n.js +886 -0
- package/public/index.html +830 -0
- package/public/styles.css +923 -0
- package/public/vendor/mermaid.min.js +4329 -0
- package/README.md +0 -3
package/dist/server.js
ADDED
|
@@ -0,0 +1,2077 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import Fastify from 'fastify';
|
|
7
|
+
import fastifyRateLimit from '@fastify/rate-limit';
|
|
8
|
+
import fastifyStatic from '@fastify/static';
|
|
9
|
+
import fastifyWebsocket from '@fastify/websocket';
|
|
10
|
+
import { ByokAiClient, COMPLIANCE_PACKS, CodePulseDatabase, TreeSitterGraphIndexer, addIgnoredPattern, buildGuidedWalkthrough, computeHotspotMatrix, computePulseScore, estimateScanBudget, estimateScanPreFlight, generateProjectDocs, generateSmartContextPack, generateUnitTestsForTarget, loadCodePulseRepoConfig, loadFeedbackMemory, maskSecrets, persistEnvVariables, removeBaselineSuppression, removeIgnoredPattern, renderExecutiveAuditHtml, renderReviewMarkdown, renderSarifReport, resolveAiConfigFromEnv, revalidateFindings, runCommand, runControlledAutoFix, runCrossLayerDriftRadar, saveMarkdownReport, upsertBaselineSuppression, verifyTeamBaseline } from '@codepulse-oss/core';
|
|
11
|
+
import { GitHubRepoPoller, answerNaturalLanguagePrQuestion, babysitPrThreads, buildGitHubAppManifest, createOctokitClient, createWebhookRouter, detectStackedPrChains, ensureManagedRepoClone, exchangeGitHubAppManifestCode, listAccessibleBitbucketRepos, listAccessibleGitHubRepos, listAccessibleGitLabProjects, listOpenPullRequests, persistGitHubAppCredentialsToEnv, pollGitHubDeviceFlow, publishPrReview, pushGuardedCommitFixToPrBranch, renderGitHubManifestRedirectHtml, resolveGitHubAuth, startGitHubDeviceFlow, verifyGitHubWebhookSignature } from '@codepulse-oss/github';
|
|
12
|
+
import { JobQueueManager, detectInstalledPlatforms, handleMcpHttpRequest, installAgentBridges } from '@codepulse-oss/mcp';
|
|
13
|
+
import { safeResolveInside } from '@codepulse-oss/core';
|
|
14
|
+
function verifyAuthToken(provided, expected) {
|
|
15
|
+
if (!provided)
|
|
16
|
+
return false;
|
|
17
|
+
const a = crypto.createHash('sha256').update(provided).digest();
|
|
18
|
+
const b = crypto.createHash('sha256').update(expected).digest();
|
|
19
|
+
return crypto.timingSafeEqual(a, b);
|
|
20
|
+
}
|
|
21
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
22
|
+
export const CURATED_AI_MODELS = {
|
|
23
|
+
gemini: ['gemini-3.8-flash', 'gemini-2.5-flash', 'gemini-2.5-pro'],
|
|
24
|
+
openai: ['gpt-4.1', 'gpt-4.1-mini', 'o4-mini'],
|
|
25
|
+
anthropic: ['claude-sonnet-4-20250514', 'claude-3-5-haiku-20241022'],
|
|
26
|
+
openrouter: ['anthropic/claude-sonnet-4', 'google/gemini-2.5-pro', 'openai/gpt-4.1'],
|
|
27
|
+
ollama: ['qwen2.5-coder:14b', 'qwen2.5-coder:7b', 'llama3.3:70b'],
|
|
28
|
+
'openai-compatible': ['gpt-4o-mini']
|
|
29
|
+
};
|
|
30
|
+
export async function createCodePulseServer(options = {}) {
|
|
31
|
+
const port = options.port ?? Number(process.env.CODEPULSE_PORT ?? 4310);
|
|
32
|
+
const host = options.host ?? process.env.CODEPULSE_HOST ?? '127.0.0.1';
|
|
33
|
+
const dbPath = options.dbPath ?? process.env.CODEPULSE_DB_PATH ?? path.join(process.cwd(), '.codepulse', 'codepulse.db');
|
|
34
|
+
const envPath = options.envPath ?? path.join(process.cwd(), '.env');
|
|
35
|
+
const reposCacheRoot = dbPath === ':memory:'
|
|
36
|
+
? path.join(process.cwd(), '.codepulse', 'repos')
|
|
37
|
+
: path.join(path.dirname(path.resolve(dbPath)), 'repos');
|
|
38
|
+
const authToken = options.authToken ?? (process.env.CODEPULSE_AUTH_TOKEN || undefined);
|
|
39
|
+
const publicDir = options.publicDir ?? process.env.CODEPULSE_PUBLIC_DIR ?? path.resolve(__dirname, '../public');
|
|
40
|
+
const db = new CodePulseDatabase(dbPath);
|
|
41
|
+
const queue = new JobQueueManager(db, options.concurrency, options.appVersion ?? '3.0.0');
|
|
42
|
+
const app = Fastify({ logger: false });
|
|
43
|
+
function resolveHttpWorkspacePath(candidate, repoLocalPath) {
|
|
44
|
+
if (!candidate)
|
|
45
|
+
return repoLocalPath ?? undefined;
|
|
46
|
+
if (candidate.includes('\0'))
|
|
47
|
+
throw new Error('Invalid workspace path');
|
|
48
|
+
const resolved = path.resolve(candidate);
|
|
49
|
+
const allowedRoots = [process.cwd(), reposCacheRoot, os.tmpdir()];
|
|
50
|
+
for (const r of db.listRepos()) {
|
|
51
|
+
if (r.localPath)
|
|
52
|
+
allowedRoots.push(r.localPath);
|
|
53
|
+
}
|
|
54
|
+
for (const rawBase of allowedRoots) {
|
|
55
|
+
const base = path.resolve(rawBase);
|
|
56
|
+
const prefix = base.endsWith(path.sep) ? base : base + path.sep;
|
|
57
|
+
if (resolved === base || resolved.startsWith(prefix)) {
|
|
58
|
+
return resolved;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
throw new Error('Workspace path must reside within a registered repository, workspace root, cache, or temp directory.');
|
|
62
|
+
}
|
|
63
|
+
let activePoller = null;
|
|
64
|
+
let isClosing = false;
|
|
65
|
+
const inFlightTriggers = new Set();
|
|
66
|
+
const pendingPrNotices = new Map();
|
|
67
|
+
const wsClients = new Set();
|
|
68
|
+
let pollIntervalSeconds = options.pollIntervalSeconds ?? db.getSetting('github.pollSeconds') ?? Number(process.env.CODEPULSE_GITHUB_POLL_SECONDS ?? 60);
|
|
69
|
+
function broadcastWsPayload(payloadObj) {
|
|
70
|
+
const payload = JSON.stringify(payloadObj);
|
|
71
|
+
for (const client of wsClients) {
|
|
72
|
+
try {
|
|
73
|
+
client.send(payload);
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
wsClients.delete(client);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function trackBackgroundTask(promise) {
|
|
81
|
+
inFlightTriggers.add(promise);
|
|
82
|
+
void promise.finally(() => inFlightTriggers.delete(promise));
|
|
83
|
+
}
|
|
84
|
+
async function resolveRepoOctokit(installationId) {
|
|
85
|
+
if (options.octokitOverride) {
|
|
86
|
+
return { octokit: options.octokitOverride, token: process.env.GITHUB_TOKEN };
|
|
87
|
+
}
|
|
88
|
+
const auth = await resolveGitHubAuth({ installationId });
|
|
89
|
+
if (!auth)
|
|
90
|
+
return null;
|
|
91
|
+
try {
|
|
92
|
+
const octokit = await createOctokitClient(auth);
|
|
93
|
+
return { octokit, token: auth.token };
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
async function handlePrEventTrigger(trigger, opts = {}) {
|
|
100
|
+
const triggerKey = `${trigger.owner}/${trigger.repo}#${trigger.prNumber}`;
|
|
101
|
+
// Opt-in background scanning: by default (`autoScanOpenPrsOnPoll = false`), polling notifies the user instead of spending AI tokens silently
|
|
102
|
+
if (opts.source === 'poll' && trigger.type === 'pull_request' && !trigger.command) {
|
|
103
|
+
const autoScan = db.getSetting('github.autoScanOpenPrsOnPoll', false) === true;
|
|
104
|
+
if (!autoScan) {
|
|
105
|
+
pendingPrNotices.set(triggerKey, {
|
|
106
|
+
key: triggerKey,
|
|
107
|
+
owner: trigger.owner,
|
|
108
|
+
repo: trigger.repo,
|
|
109
|
+
prNumber: trigger.prNumber,
|
|
110
|
+
headSha: trigger.headSha,
|
|
111
|
+
baseRef: trigger.baseRef,
|
|
112
|
+
headRef: trigger.headRef,
|
|
113
|
+
title: trigger.prTitle,
|
|
114
|
+
installationId: trigger.installationId,
|
|
115
|
+
detectedAt: new Date().toISOString()
|
|
116
|
+
});
|
|
117
|
+
broadcastWsPayload({
|
|
118
|
+
type: 'pr_updates_detected',
|
|
119
|
+
pendingPrs: Array.from(pendingPrNotices.values())
|
|
120
|
+
});
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
pendingPrNotices.delete(triggerKey);
|
|
125
|
+
let repo = db
|
|
126
|
+
.listRepos()
|
|
127
|
+
.find((r) => r.githubOwner === trigger.owner && r.githubRepo === trigger.repo);
|
|
128
|
+
if (!repo) {
|
|
129
|
+
repo = db.upsertRepo({
|
|
130
|
+
name: `${trigger.owner}/${trigger.repo}`,
|
|
131
|
+
githubOwner: trigger.owner,
|
|
132
|
+
githubRepo: trigger.repo,
|
|
133
|
+
defaultBranch: trigger.baseRef || 'main',
|
|
134
|
+
authMode: 'pat'
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
const ghClient = await resolveRepoOctokit(trigger.installationId);
|
|
138
|
+
// Auto-clone remote GitHub repo into managed workspace cache if no localPath exists yet
|
|
139
|
+
if (!repo.localPath) {
|
|
140
|
+
if (options.skipRemoteSync || isClosing) {
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
try {
|
|
144
|
+
const clonedPath = await ensureManagedRepoClone({
|
|
145
|
+
reposCacheRoot,
|
|
146
|
+
owner: trigger.owner,
|
|
147
|
+
repo: trigger.repo,
|
|
148
|
+
token: ghClient?.token,
|
|
149
|
+
prNumber: trigger.prNumber,
|
|
150
|
+
baseRef: trigger.baseRef
|
|
151
|
+
});
|
|
152
|
+
repo = db.upsertRepo({
|
|
153
|
+
id: repo.id,
|
|
154
|
+
name: repo.name,
|
|
155
|
+
localPath: clonedPath,
|
|
156
|
+
githubOwner: repo.githubOwner,
|
|
157
|
+
githubRepo: repo.githubRepo,
|
|
158
|
+
defaultBranch: repo.defaultBranch,
|
|
159
|
+
authMode: repo.authMode,
|
|
160
|
+
autofixEnabled: repo.autofixEnabled
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
// If remote clone is unreachable, cannot enqueue local filesystem review
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const repoPath = repo.localPath;
|
|
169
|
+
const outputRule = db.getOutputRuleForRepo(repo.id);
|
|
170
|
+
const shouldPublishGithub = outputRule ? outputRule.postGithubComments : true;
|
|
171
|
+
const cmd = trigger.command?.command;
|
|
172
|
+
// Handle natural-language PR question, /explain, /describe, /add_docs, or /test
|
|
173
|
+
if (cmd === 'question' || cmd === 'explain' || cmd === 'describe' || cmd === 'add_docs' || cmd === 'test') {
|
|
174
|
+
if (ghClient && shouldPublishGithub) {
|
|
175
|
+
if (cmd === 'test') {
|
|
176
|
+
const aiClient = new ByokAiClient(resolveAiConfigFromEnv());
|
|
177
|
+
const latestJob = db.listJobs(10).find((j) => j.repoId === repo.id && j.resultJson?.findings.length);
|
|
178
|
+
const targetFinding = latestJob?.resultJson?.findings[0];
|
|
179
|
+
const targetFile = trigger.command?.args?.trim() ||
|
|
180
|
+
targetFinding?.file ||
|
|
181
|
+
db.getAstNodesForRepo(repo.id).find((n) => n.kind === 'function')?.file;
|
|
182
|
+
if (targetFile) {
|
|
183
|
+
const gen = await generateUnitTestsForTarget({
|
|
184
|
+
repoPath,
|
|
185
|
+
targetFile,
|
|
186
|
+
finding: targetFinding,
|
|
187
|
+
astNodes: db.getAstNodesForRepo(repo.id),
|
|
188
|
+
aiClient
|
|
189
|
+
});
|
|
190
|
+
await ghClient.octokit.issues.createComment({
|
|
191
|
+
owner: trigger.owner,
|
|
192
|
+
repo: trigger.repo,
|
|
193
|
+
issue_number: trigger.prNumber,
|
|
194
|
+
body: `### CodePulse Generated Unit Test (\`${gen.suggestedTestPath}\` · ${gen.framework})\n\n\`\`\`\n${gen.testCode.slice(0, 6000)}\n\`\`\``
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (cmd === 'add_docs') {
|
|
200
|
+
const aiClient = new ByokAiClient(resolveAiConfigFromEnv());
|
|
201
|
+
const docs = await generateProjectDocs({
|
|
202
|
+
db,
|
|
203
|
+
repoId: repo.id,
|
|
204
|
+
repoPath,
|
|
205
|
+
repoName: repo.name,
|
|
206
|
+
aiClient
|
|
207
|
+
});
|
|
208
|
+
await ghClient.octokit.issues.createComment({
|
|
209
|
+
owner: trigger.owner,
|
|
210
|
+
repo: trigger.repo,
|
|
211
|
+
issue_number: trigger.prNumber,
|
|
212
|
+
body: `### CodePulse Architecture Docs Updated\n\nGenerated ${docs.writtenFiles.length} doc artifact(s) from the AST graph.\n\n${docs.architectureMd.slice(0, 4000)}`
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
else {
|
|
216
|
+
const aiClient = new ByokAiClient(resolveAiConfigFromEnv());
|
|
217
|
+
const prompt = cmd === 'describe'
|
|
218
|
+
? 'Provide a structured PR Walkthrough summary grouped by module, key changes, and blast radius risks.'
|
|
219
|
+
: trigger.command?.args || trigger.command?.rawText || 'Explain this PR';
|
|
220
|
+
const replyBody = await answerNaturalLanguagePrQuestion({
|
|
221
|
+
question: prompt,
|
|
222
|
+
astNodes: db.getAstNodesForRepo(repo.id),
|
|
223
|
+
aiClient
|
|
224
|
+
});
|
|
225
|
+
await ghClient.octokit.issues.createComment({
|
|
226
|
+
owner: trigger.owner,
|
|
227
|
+
repo: trigger.repo,
|
|
228
|
+
issue_number: trigger.prNumber,
|
|
229
|
+
body: replyBody
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
const mode = cmd === 'comprehensive'
|
|
236
|
+
? 'comprehensive'
|
|
237
|
+
: cmd === 'ultrareview'
|
|
238
|
+
? 'ultrareview'
|
|
239
|
+
: cmd === 'adversarial'
|
|
240
|
+
? 'adversarial'
|
|
241
|
+
: cmd === 'security'
|
|
242
|
+
? 'security'
|
|
243
|
+
: cmd === 'fast'
|
|
244
|
+
? 'fast'
|
|
245
|
+
: 'debate';
|
|
246
|
+
const usesManagedPrRefs = repoPath.startsWith(path.resolve(reposCacheRoot));
|
|
247
|
+
const job = queue.enqueueScan({
|
|
248
|
+
repoId: repo.id,
|
|
249
|
+
repoPath,
|
|
250
|
+
target: cmd === 'scan-main' ? 'main_full' : 'branch_diff',
|
|
251
|
+
mode,
|
|
252
|
+
baseRef: usesManagedPrRefs && trigger.baseRef ? `origin/${trigger.baseRef}` : trigger.baseRef,
|
|
253
|
+
headRef: usesManagedPrRefs && trigger.prNumber ? `origin/pr-${trigger.prNumber}` : trigger.headRef || 'HEAD',
|
|
254
|
+
prNumber: trigger.prNumber
|
|
255
|
+
});
|
|
256
|
+
if (ghClient && shouldPublishGithub && trigger.prNumber) {
|
|
257
|
+
void queue
|
|
258
|
+
.waitForJob(job.id, 180_000)
|
|
259
|
+
.then(async (done) => {
|
|
260
|
+
if (!done.resultJson)
|
|
261
|
+
return;
|
|
262
|
+
const pr = await ghClient.octokit.pulls.get({
|
|
263
|
+
owner: trigger.owner,
|
|
264
|
+
repo: trigger.repo,
|
|
265
|
+
pull_number: trigger.prNumber
|
|
266
|
+
});
|
|
267
|
+
const diffRes = await ghClient.octokit.pulls.get({
|
|
268
|
+
owner: trigger.owner,
|
|
269
|
+
repo: trigger.repo,
|
|
270
|
+
pull_number: trigger.prNumber,
|
|
271
|
+
mediaType: { format: 'diff' }
|
|
272
|
+
});
|
|
273
|
+
const prDiffText = String(diffRes.data);
|
|
274
|
+
const repoCfg = await loadCodePulseRepoConfig(repoPath);
|
|
275
|
+
await publishPrReview({
|
|
276
|
+
octokit: ghClient.octokit,
|
|
277
|
+
owner: trigger.owner,
|
|
278
|
+
repo: trigger.repo,
|
|
279
|
+
prNumber: trigger.prNumber,
|
|
280
|
+
commitSha: pr.data.head.sha,
|
|
281
|
+
output: done.resultJson,
|
|
282
|
+
prDiffText,
|
|
283
|
+
commentPolicy: outputRule?.commentPolicy,
|
|
284
|
+
attribution: repoCfg.attribution
|
|
285
|
+
});
|
|
286
|
+
await babysitPrThreads({
|
|
287
|
+
db,
|
|
288
|
+
octokit: ghClient.octokit,
|
|
289
|
+
repoId: repo.id,
|
|
290
|
+
owner: trigger.owner,
|
|
291
|
+
repo: trigger.repo,
|
|
292
|
+
prNumber: trigger.prNumber,
|
|
293
|
+
headSha: pr.data.head.sha,
|
|
294
|
+
latestReview: done.resultJson,
|
|
295
|
+
prDiffText
|
|
296
|
+
});
|
|
297
|
+
})
|
|
298
|
+
.catch(() => undefined);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
async function refreshPoller() {
|
|
302
|
+
if (activePoller) {
|
|
303
|
+
activePoller.stop();
|
|
304
|
+
activePoller = null;
|
|
305
|
+
}
|
|
306
|
+
if (pollIntervalSeconds <= 0)
|
|
307
|
+
return;
|
|
308
|
+
const ghClient = await resolveRepoOctokit();
|
|
309
|
+
if (!ghClient)
|
|
310
|
+
return;
|
|
311
|
+
const ghRepos = db
|
|
312
|
+
.listRepos()
|
|
313
|
+
.filter((r) => Boolean(r.githubOwner && r.githubRepo))
|
|
314
|
+
.map((r) => ({ owner: r.githubOwner, repo: r.githubRepo }));
|
|
315
|
+
activePoller = new GitHubRepoPoller(ghClient.octokit, db, (trig) => handlePrEventTrigger(trig, { source: 'poll' }));
|
|
316
|
+
if (ghRepos.length > 0) {
|
|
317
|
+
activePoller.startPolling(ghRepos, pollIntervalSeconds);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
async function pollNow(opts = {}) {
|
|
321
|
+
const ghClient = await resolveRepoOctokit();
|
|
322
|
+
if (!ghClient) {
|
|
323
|
+
throw new Error('GitHub credentials not configured (set GITHUB_TOKEN or connect GitHub App).');
|
|
324
|
+
}
|
|
325
|
+
const sourceMode = opts.autoEnqueue ? 'manual' : 'poll';
|
|
326
|
+
const poller = new GitHubRepoPoller(ghClient.octokit, db, (trig) => handlePrEventTrigger(trig, { source: sourceMode }));
|
|
327
|
+
const ghRepos = db
|
|
328
|
+
.listRepos()
|
|
329
|
+
.filter((r) => Boolean(r.githubOwner && r.githubRepo))
|
|
330
|
+
.map((r) => ({ owner: r.githubOwner, repo: r.githubRepo }));
|
|
331
|
+
const allTriggers = [];
|
|
332
|
+
for (const r of ghRepos) {
|
|
333
|
+
const trigs = await poller.pollRepoOnce(r.owner, r.repo);
|
|
334
|
+
allTriggers.push(...trigs);
|
|
335
|
+
}
|
|
336
|
+
return {
|
|
337
|
+
polledRepos: ghRepos.length,
|
|
338
|
+
triggers: allTriggers,
|
|
339
|
+
pendingPrs: Array.from(pendingPrNotices.values())
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
// Preserve exact raw payload string for timing-safe GitHub HMAC signature verification
|
|
343
|
+
app.addContentTypeParser('application/json', { parseAs: 'string' }, (req, body, done) => {
|
|
344
|
+
const raw = typeof body === 'string' ? body : body.toString('utf8');
|
|
345
|
+
req.rawBody = raw;
|
|
346
|
+
try {
|
|
347
|
+
done(null, raw ? JSON.parse(raw) : {});
|
|
348
|
+
}
|
|
349
|
+
catch (err) {
|
|
350
|
+
done(err, undefined);
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
await app.register(fastifyRateLimit, {
|
|
354
|
+
global: true,
|
|
355
|
+
max: 1000,
|
|
356
|
+
timeWindow: '1 minute'
|
|
357
|
+
});
|
|
358
|
+
await app.register(fastifyWebsocket);
|
|
359
|
+
try {
|
|
360
|
+
await fs.access(publicDir);
|
|
361
|
+
await app.register(fastifyStatic, {
|
|
362
|
+
root: publicDir,
|
|
363
|
+
prefix: '/'
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
catch {
|
|
367
|
+
// Public dir optional in unit test mode
|
|
368
|
+
}
|
|
369
|
+
// Timing-safe API, MCP & WebSocket token guard for server/Docker deployments
|
|
370
|
+
app.addHook('onRequest', async (request, reply) => {
|
|
371
|
+
if (!authToken)
|
|
372
|
+
return;
|
|
373
|
+
const rawPath = request.url.split('?')[0] ?? request.url;
|
|
374
|
+
const isProtected = rawPath.startsWith('/api/') || rawPath === '/mcp' || rawPath.startsWith('/mcp/') || rawPath === '/ws';
|
|
375
|
+
if (!isProtected || rawPath === '/api/health' || rawPath === '/api/webhooks/github') {
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
const header = request.headers.authorization ?? '';
|
|
379
|
+
const bearer = header.replace(/^Bearer\s+/i, '').trim();
|
|
380
|
+
const queryToken = request.query?.token;
|
|
381
|
+
const candidate = bearer || queryToken || '';
|
|
382
|
+
if (!verifyAuthToken(candidate, authToken)) {
|
|
383
|
+
return reply.code(401).send({ error: 'Unauthorized: invalid or missing CODEPULSE_AUTH_TOKEN' });
|
|
384
|
+
}
|
|
385
|
+
});
|
|
386
|
+
// Streamable HTTP / SSE MCP Endpoint for Docker, Cloud & IDE agents
|
|
387
|
+
app.all('/mcp', async (request, reply) => {
|
|
388
|
+
reply.hijack();
|
|
389
|
+
await handleMcpHttpRequest({ db, queue }, request.raw, reply.raw, request.body);
|
|
390
|
+
});
|
|
391
|
+
// WebSocket live job stream
|
|
392
|
+
queue.subscribe((ev) => {
|
|
393
|
+
broadcastWsPayload(ev);
|
|
394
|
+
});
|
|
395
|
+
app.get('/ws', { websocket: true }, (socket, request) => {
|
|
396
|
+
if (authToken) {
|
|
397
|
+
const urlObj = new URL(request.url, 'http://localhost');
|
|
398
|
+
const header = request.headers.authorization ?? '';
|
|
399
|
+
const bearer = header.replace(/^Bearer\s+/i, '').trim();
|
|
400
|
+
const candidate = bearer || urlObj.searchParams.get('token') || '';
|
|
401
|
+
if (!verifyAuthToken(candidate, authToken)) {
|
|
402
|
+
socket.close(4001, 'Unauthorized');
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
wsClients.add(socket);
|
|
407
|
+
socket.on('close', () => wsClients.delete(socket));
|
|
408
|
+
});
|
|
409
|
+
// --- Health ---
|
|
410
|
+
app.get('/api/health', async () => {
|
|
411
|
+
const aiCfg = resolveAiConfigFromEnv({
|
|
412
|
+
provider: db.getSetting('ai.provider'),
|
|
413
|
+
model: db.getSetting('ai.model'),
|
|
414
|
+
baseUrl: db.getSetting('ai.baseUrl')
|
|
415
|
+
});
|
|
416
|
+
const aiClient = new ByokAiClient(aiCfg);
|
|
417
|
+
const ghAuth = await resolveGitHubAuth();
|
|
418
|
+
return {
|
|
419
|
+
ok: true,
|
|
420
|
+
version: options.appVersion ?? '3.0.0',
|
|
421
|
+
platform: process.platform,
|
|
422
|
+
node: process.version,
|
|
423
|
+
concurrency: queue.concurrency,
|
|
424
|
+
activeJobs: queue.getActiveCount(),
|
|
425
|
+
pendingJobs: queue.getPendingCount(),
|
|
426
|
+
aiProvider: aiCfg.provider,
|
|
427
|
+
aiModel: aiCfg.model,
|
|
428
|
+
aiConfigured: aiClient.isConfigured(),
|
|
429
|
+
githubConnected: Boolean(ghAuth || options.octokitOverride),
|
|
430
|
+
reposCount: db.listRepos().length,
|
|
431
|
+
isDesktop: Boolean(options.desktopBridge),
|
|
432
|
+
authRequired: Boolean(authToken)
|
|
433
|
+
};
|
|
434
|
+
});
|
|
435
|
+
// --- Repositories ---
|
|
436
|
+
app.get('/api/repos', async () => {
|
|
437
|
+
return { repos: db.listRepos() };
|
|
438
|
+
});
|
|
439
|
+
app.post('/api/repos', async (request, reply) => {
|
|
440
|
+
const body = (request.body ?? {});
|
|
441
|
+
if (!body.localPath && !(body.githubOwner && body.githubRepo)) {
|
|
442
|
+
return reply.code(400).send({ error: 'Provide localPath or githubOwner + githubRepo' });
|
|
443
|
+
}
|
|
444
|
+
const absLocal = body.localPath ? path.resolve(body.localPath) : null;
|
|
445
|
+
const name = body.name ?? (absLocal ? path.basename(absLocal) : `${body.githubOwner}/${body.githubRepo}`);
|
|
446
|
+
const repo = db.upsertRepo({
|
|
447
|
+
name,
|
|
448
|
+
localPath: absLocal,
|
|
449
|
+
githubOwner: body.githubOwner ?? null,
|
|
450
|
+
githubRepo: body.githubRepo ?? null,
|
|
451
|
+
defaultBranch: body.defaultBranch ?? 'main',
|
|
452
|
+
authMode: body.authMode ?? (body.githubOwner ? 'pat' : 'local'),
|
|
453
|
+
autofixEnabled: Boolean(body.autofixEnabled)
|
|
454
|
+
});
|
|
455
|
+
if (repo.githubOwner && repo.githubRepo) {
|
|
456
|
+
void refreshPoller().catch(() => undefined);
|
|
457
|
+
}
|
|
458
|
+
return { repo };
|
|
459
|
+
});
|
|
460
|
+
app.delete('/api/repos/:id', async (request, reply) => {
|
|
461
|
+
const { id } = request.params;
|
|
462
|
+
const deleted = db.deleteRepo(id);
|
|
463
|
+
if (!deleted)
|
|
464
|
+
return reply.code(404).send({ error: 'Repository not found' });
|
|
465
|
+
void refreshPoller().catch(() => undefined);
|
|
466
|
+
return { ok: true, deleted: true, repoId: id };
|
|
467
|
+
});
|
|
468
|
+
// --- Jobs & Concurrent Queue ---
|
|
469
|
+
app.get('/api/jobs', async () => {
|
|
470
|
+
return {
|
|
471
|
+
jobs: db.listJobSummaries(60),
|
|
472
|
+
activeCount: queue.getActiveCount(),
|
|
473
|
+
pendingCount: queue.getPendingCount(),
|
|
474
|
+
concurrency: queue.concurrency
|
|
475
|
+
};
|
|
476
|
+
});
|
|
477
|
+
app.delete('/api/jobs/history', async () => {
|
|
478
|
+
const cleared = queue.clearCompleted();
|
|
479
|
+
return { ok: true, cleared };
|
|
480
|
+
});
|
|
481
|
+
app.post('/api/jobs', async (request, reply) => {
|
|
482
|
+
const body = (request.body ?? {});
|
|
483
|
+
let repo = body.repoId ? db.getRepo(body.repoId) : null;
|
|
484
|
+
let repoPath;
|
|
485
|
+
try {
|
|
486
|
+
repoPath = resolveHttpWorkspacePath(body.repoPath, repo?.localPath);
|
|
487
|
+
}
|
|
488
|
+
catch (err) {
|
|
489
|
+
return reply.code(403).send({ error: err.message });
|
|
490
|
+
}
|
|
491
|
+
if (!repoPath && repo?.githubOwner && repo?.githubRepo && !options.skipRemoteSync) {
|
|
492
|
+
const ghClient = await resolveRepoOctokit();
|
|
493
|
+
repoPath = await ensureManagedRepoClone({
|
|
494
|
+
reposCacheRoot,
|
|
495
|
+
owner: repo.githubOwner,
|
|
496
|
+
repo: repo.githubRepo,
|
|
497
|
+
token: ghClient?.token,
|
|
498
|
+
prNumber: body.prNumber,
|
|
499
|
+
baseRef: body.baseRef ?? repo.defaultBranch
|
|
500
|
+
});
|
|
501
|
+
repo = db.upsertRepo({
|
|
502
|
+
id: repo.id,
|
|
503
|
+
name: repo.name,
|
|
504
|
+
localPath: repoPath,
|
|
505
|
+
githubOwner: repo.githubOwner,
|
|
506
|
+
githubRepo: repo.githubRepo,
|
|
507
|
+
defaultBranch: repo.defaultBranch,
|
|
508
|
+
authMode: repo.authMode,
|
|
509
|
+
autofixEnabled: repo.autofixEnabled
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
else if (repoPath && repo?.githubOwner && repo?.githubRepo && body.target === 'pr' && body.prNumber && !options.skipRemoteSync) {
|
|
513
|
+
const ghClient = await resolveRepoOctokit();
|
|
514
|
+
await ensureManagedRepoClone({
|
|
515
|
+
reposCacheRoot,
|
|
516
|
+
owner: repo.githubOwner,
|
|
517
|
+
repo: repo.githubRepo,
|
|
518
|
+
token: ghClient?.token,
|
|
519
|
+
prNumber: body.prNumber,
|
|
520
|
+
baseRef: body.baseRef ?? repo.defaultBranch
|
|
521
|
+
}).catch(() => undefined);
|
|
522
|
+
}
|
|
523
|
+
if (!repoPath) {
|
|
524
|
+
return reply.code(400).send({ error: 'Repository localPath or connected GitHub owner/repo is required to execute scan.' });
|
|
525
|
+
}
|
|
526
|
+
const usesManagedPrRefs = repoPath.startsWith(path.resolve(reposCacheRoot));
|
|
527
|
+
const effectiveTarget = body.target ?? 'local_uncommitted';
|
|
528
|
+
const effectiveBase = effectiveTarget === 'pr' && usesManagedPrRefs && (body.baseRef ?? repo?.defaultBranch)
|
|
529
|
+
? `origin/${body.baseRef ?? repo?.defaultBranch}`
|
|
530
|
+
: body.baseRef;
|
|
531
|
+
const effectiveHead = effectiveTarget === 'pr' && usesManagedPrRefs && body.prNumber
|
|
532
|
+
? `origin/pr-${body.prNumber}`
|
|
533
|
+
: body.headRef;
|
|
534
|
+
const job = queue.enqueueScan({
|
|
535
|
+
repoId: repo?.id,
|
|
536
|
+
repoPath,
|
|
537
|
+
target: effectiveTarget,
|
|
538
|
+
mode: body.mode ?? 'debate',
|
|
539
|
+
baseRef: effectiveBase,
|
|
540
|
+
headRef: effectiveHead,
|
|
541
|
+
prNumber: body.prNumber,
|
|
542
|
+
directoryPath: body.directoryPath,
|
|
543
|
+
saveMarkdownOnce: body.saveMarkdownOnce,
|
|
544
|
+
exportDir: body.exportDir
|
|
545
|
+
});
|
|
546
|
+
if (body.postToGithub && body.prNumber && repo?.githubOwner && repo?.githubRepo) {
|
|
547
|
+
const ghClient = await resolveRepoOctokit();
|
|
548
|
+
if (ghClient) {
|
|
549
|
+
const owner = repo.githubOwner;
|
|
550
|
+
const repoName = repo.githubRepo;
|
|
551
|
+
const prNumber = body.prNumber;
|
|
552
|
+
const targetPath = repoPath;
|
|
553
|
+
trackBackgroundTask(queue
|
|
554
|
+
.waitForJob(job.id, 180_000)
|
|
555
|
+
.then(async (done) => {
|
|
556
|
+
if (!done.resultJson)
|
|
557
|
+
return;
|
|
558
|
+
const pr = await ghClient.octokit.pulls.get({ owner, repo: repoName, pull_number: prNumber });
|
|
559
|
+
const diffRes = await ghClient.octokit.pulls.get({
|
|
560
|
+
owner,
|
|
561
|
+
repo: repoName,
|
|
562
|
+
pull_number: prNumber,
|
|
563
|
+
mediaType: { format: 'diff' }
|
|
564
|
+
});
|
|
565
|
+
const repoCfg = await loadCodePulseRepoConfig(targetPath);
|
|
566
|
+
await publishPrReview({
|
|
567
|
+
octokit: ghClient.octokit,
|
|
568
|
+
owner,
|
|
569
|
+
repo: repoName,
|
|
570
|
+
prNumber,
|
|
571
|
+
commitSha: pr.data.head.sha,
|
|
572
|
+
output: done.resultJson,
|
|
573
|
+
prDiffText: String(diffRes.data),
|
|
574
|
+
attribution: repoCfg.attribution
|
|
575
|
+
});
|
|
576
|
+
})
|
|
577
|
+
.catch(() => undefined));
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
return { job };
|
|
581
|
+
});
|
|
582
|
+
app.get('/api/jobs/:id', async (request, reply) => {
|
|
583
|
+
const { id } = request.params;
|
|
584
|
+
const job = db.getJob(id);
|
|
585
|
+
if (!job)
|
|
586
|
+
return reply.code(404).send({ error: 'Job not found' });
|
|
587
|
+
return { job };
|
|
588
|
+
});
|
|
589
|
+
app.post('/api/jobs/:id/cancel', async (request, reply) => {
|
|
590
|
+
const { id } = request.params;
|
|
591
|
+
const job = queue.cancelJob(id);
|
|
592
|
+
if (!job)
|
|
593
|
+
return reply.code(404).send({ error: 'Job not found' });
|
|
594
|
+
return { job };
|
|
595
|
+
});
|
|
596
|
+
app.post('/api/jobs/:id/retry', async (request, reply) => {
|
|
597
|
+
const { id } = request.params;
|
|
598
|
+
const prev = db.getJob(id);
|
|
599
|
+
if (!prev)
|
|
600
|
+
return reply.code(404).send({ error: 'Job not found' });
|
|
601
|
+
const repo = db.getRepo(prev.repoId);
|
|
602
|
+
if (!repo?.localPath)
|
|
603
|
+
return reply.code(400).send({ error: 'Repository localPath unavailable for retry' });
|
|
604
|
+
const retried = queue.enqueueScan({
|
|
605
|
+
repoId: repo.id,
|
|
606
|
+
repoPath: repo.localPath,
|
|
607
|
+
target: prev.target,
|
|
608
|
+
mode: prev.mode,
|
|
609
|
+
baseRef: prev.baseRef ?? undefined,
|
|
610
|
+
headRef: prev.headRef ?? undefined,
|
|
611
|
+
prNumber: prev.prNumber ?? undefined
|
|
612
|
+
});
|
|
613
|
+
return { job: retried };
|
|
614
|
+
});
|
|
615
|
+
app.post('/api/jobs/estimate', async (request, reply) => {
|
|
616
|
+
const body = (request.body ?? {});
|
|
617
|
+
const repo = body.repoId ? db.getRepo(body.repoId) : null;
|
|
618
|
+
let repoPath;
|
|
619
|
+
try {
|
|
620
|
+
repoPath = resolveHttpWorkspacePath(body.repoPath, repo?.localPath);
|
|
621
|
+
}
|
|
622
|
+
catch (err) {
|
|
623
|
+
return reply.code(403).send({ error: err.message });
|
|
624
|
+
}
|
|
625
|
+
if (!repoPath)
|
|
626
|
+
return reply.code(400).send({ error: 'repoId or repoPath required for pre-flight estimate' });
|
|
627
|
+
const aiCfg = resolveAiConfigFromEnv({
|
|
628
|
+
provider: db.getSetting('ai.provider'),
|
|
629
|
+
model: db.getSetting('ai.model')
|
|
630
|
+
});
|
|
631
|
+
const estimate = await estimateScanPreFlight({
|
|
632
|
+
db,
|
|
633
|
+
repoId: repo?.id ?? 'preview',
|
|
634
|
+
repoPath,
|
|
635
|
+
target: body.target ?? 'local_uncommitted',
|
|
636
|
+
baseRef: body.baseRef,
|
|
637
|
+
headRef: body.headRef,
|
|
638
|
+
model: body.model ?? aiCfg.model
|
|
639
|
+
});
|
|
640
|
+
const budget = estimateScanBudget({
|
|
641
|
+
filesCount: Math.max(1, estimate.fileCount),
|
|
642
|
+
totalBytes: Math.max(2048, estimate.fileCount * 3600),
|
|
643
|
+
mode: body.mode ?? 'debate',
|
|
644
|
+
provider: aiCfg.provider,
|
|
645
|
+
model: body.model ?? aiCfg.model,
|
|
646
|
+
fastModel: aiCfg.fastModel
|
|
647
|
+
});
|
|
648
|
+
return {
|
|
649
|
+
estimate: {
|
|
650
|
+
...estimate,
|
|
651
|
+
...budget
|
|
652
|
+
}
|
|
653
|
+
};
|
|
654
|
+
});
|
|
655
|
+
// Real-Time Server-Sent Events (SSE) job stream
|
|
656
|
+
app.get('/api/jobs/:id/stream', async (request, reply) => {
|
|
657
|
+
const { id } = request.params;
|
|
658
|
+
const job = db.getJob(id);
|
|
659
|
+
if (!job)
|
|
660
|
+
return reply.code(404).send({ error: 'Job not found' });
|
|
661
|
+
reply.raw.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
|
|
662
|
+
reply.raw.setHeader('Cache-Control', 'no-cache, no-transform');
|
|
663
|
+
reply.raw.setHeader('Connection', 'keep-alive');
|
|
664
|
+
reply.raw.flushHeaders?.();
|
|
665
|
+
const writeSse = (payload) => {
|
|
666
|
+
if (reply.raw.writableEnded)
|
|
667
|
+
return;
|
|
668
|
+
reply.raw.write(`data: ${JSON.stringify(payload)}\n\n`);
|
|
669
|
+
};
|
|
670
|
+
writeSse({ type: 'snapshot', jobId: id, job });
|
|
671
|
+
if (job.status === 'completed' || job.status === 'failed' || job.status === 'cancelled') {
|
|
672
|
+
reply.raw.end();
|
|
673
|
+
return reply;
|
|
674
|
+
}
|
|
675
|
+
const unsub = queue.subscribe((ev) => {
|
|
676
|
+
if (ev.jobId !== id)
|
|
677
|
+
return;
|
|
678
|
+
writeSse(ev);
|
|
679
|
+
if (ev.type === 'job_completed' || ev.type === 'job_failed' || ev.type === 'job_cancelled') {
|
|
680
|
+
unsub();
|
|
681
|
+
reply.raw.end();
|
|
682
|
+
}
|
|
683
|
+
});
|
|
684
|
+
request.raw.on('close', () => {
|
|
685
|
+
unsub();
|
|
686
|
+
});
|
|
687
|
+
return reply;
|
|
688
|
+
});
|
|
689
|
+
// Export SARIF v2.1.0 report for GitHub Security Code Scanning
|
|
690
|
+
app.get('/api/jobs/:id/sarif', async (request, reply) => {
|
|
691
|
+
const { id } = request.params;
|
|
692
|
+
const job = db.getJob(id);
|
|
693
|
+
if (!job?.resultJson)
|
|
694
|
+
return reply.code(404).send({ error: 'Completed job result not found' });
|
|
695
|
+
const sarif = renderSarifReport(job.resultJson, { toolVersion: options.appVersion ?? '3.0.0' });
|
|
696
|
+
return reply.type('application/sarif+json; charset=utf-8').send(sarif);
|
|
697
|
+
});
|
|
698
|
+
// Guided 30-Second PR Walkthrough Order ("Architectural Story Order")
|
|
699
|
+
app.get('/api/jobs/:id/walkthrough', async (request, reply) => {
|
|
700
|
+
const { id } = request.params;
|
|
701
|
+
const job = db.getJob(id);
|
|
702
|
+
if (!job?.resultJson)
|
|
703
|
+
return reply.code(404).send({ error: 'Completed job result not found' });
|
|
704
|
+
const uniqueFiles = Array.from(new Set(job.resultJson.findings.map((f) => f.file)));
|
|
705
|
+
const groups = buildGuidedWalkthrough(uniqueFiles);
|
|
706
|
+
return { jobId: id, totalFiles: uniqueFiles.length, groups };
|
|
707
|
+
});
|
|
708
|
+
app.get('/api/jobs/:id/print', async (request, reply) => {
|
|
709
|
+
const { id } = request.params;
|
|
710
|
+
const job = db.getJob(id);
|
|
711
|
+
if (!job?.resultJson)
|
|
712
|
+
return reply.code(404).send({ error: 'Completed job result not found' });
|
|
713
|
+
const repo = db.getRepo(job.repoId);
|
|
714
|
+
const compliancePacks = db.getSetting('audit.compliancePacks', []) ?? [];
|
|
715
|
+
const html = renderExecutiveAuditHtml(job.resultJson, {
|
|
716
|
+
repoName: repo?.name ?? 'repo',
|
|
717
|
+
branch: job.headRef ?? 'HEAD',
|
|
718
|
+
prNumber: job.prNumber ?? undefined,
|
|
719
|
+
mode: job.mode,
|
|
720
|
+
target: job.target,
|
|
721
|
+
createdAt: job.completedAt ?? job.createdAt,
|
|
722
|
+
compliancePacks
|
|
723
|
+
});
|
|
724
|
+
return reply.type('text/html; charset=utf-8').send(html);
|
|
725
|
+
});
|
|
726
|
+
app.post('/api/jobs/:id/export-pdf', async (request, reply) => {
|
|
727
|
+
const { id } = request.params;
|
|
728
|
+
const job = db.getJob(id);
|
|
729
|
+
if (!job?.resultJson)
|
|
730
|
+
return reply.code(404).send({ error: 'Completed job result not found' });
|
|
731
|
+
const repo = db.getRepo(job.repoId);
|
|
732
|
+
const compliancePacks = db.getSetting('audit.compliancePacks', []) ?? [];
|
|
733
|
+
const html = renderExecutiveAuditHtml(job.resultJson, {
|
|
734
|
+
repoName: repo?.name ?? 'repo',
|
|
735
|
+
branch: job.headRef ?? 'HEAD',
|
|
736
|
+
prNumber: job.prNumber ?? undefined,
|
|
737
|
+
mode: job.mode,
|
|
738
|
+
target: job.target,
|
|
739
|
+
createdAt: job.completedAt ?? job.createdAt,
|
|
740
|
+
compliancePacks
|
|
741
|
+
});
|
|
742
|
+
const safeName = `${(repo?.name ?? 'codepulse').replace(/[^A-Za-z0-9._-]+/g, '-')}-${job.mode}-${new Date().toISOString().slice(0, 10)}.pdf`;
|
|
743
|
+
if (options.desktopBridge?.exportPdf) {
|
|
744
|
+
const pdfRes = await options.desktopBridge.exportPdf(html, safeName);
|
|
745
|
+
return { ...pdfRes, printUrl: `/api/jobs/${encodeURIComponent(id)}/print` };
|
|
746
|
+
}
|
|
747
|
+
return { saved: false, fallbackPrint: true, printUrl: `/api/jobs/${encodeURIComponent(id)}/print` };
|
|
748
|
+
});
|
|
749
|
+
app.get('/api/jobs/:id/markdown', async (request, reply) => {
|
|
750
|
+
const { id } = request.params;
|
|
751
|
+
const job = db.getJob(id);
|
|
752
|
+
if (!job?.resultJson)
|
|
753
|
+
return reply.code(404).send({ error: 'Completed job result not found' });
|
|
754
|
+
const repo = db.getRepo(job.repoId);
|
|
755
|
+
const md = renderReviewMarkdown(job.resultJson, {
|
|
756
|
+
repoName: repo?.name ?? 'repo',
|
|
757
|
+
branch: job.headRef ?? 'HEAD',
|
|
758
|
+
prNumber: job.prNumber ?? undefined,
|
|
759
|
+
mode: job.mode,
|
|
760
|
+
target: job.target,
|
|
761
|
+
createdAt: job.completedAt ?? job.createdAt
|
|
762
|
+
});
|
|
763
|
+
return { markdown: md };
|
|
764
|
+
});
|
|
765
|
+
app.post('/api/jobs/:id/export-md', async (request, reply) => {
|
|
766
|
+
const { id } = request.params;
|
|
767
|
+
const body = (request.body ?? {});
|
|
768
|
+
const job = db.getJob(id);
|
|
769
|
+
if (!job?.resultJson)
|
|
770
|
+
return reply.code(404).send({ error: 'Completed job result not found' });
|
|
771
|
+
const repo = db.getRepo(job.repoId);
|
|
772
|
+
const rule = db.getOutputRuleForRepo(job.repoId);
|
|
773
|
+
const rawExportDir = body.exportDir ?? rule?.exportDir ?? process.env.CODEPULSE_EXPORT_ROOT ?? path.join(repo?.localPath ?? process.cwd(), 'reports');
|
|
774
|
+
const exportDir = path.isAbsolute(rawExportDir) ? rawExportDir : path.resolve(repo?.localPath ?? process.cwd(), rawExportDir);
|
|
775
|
+
try {
|
|
776
|
+
const writtenPath = await saveMarkdownReport({
|
|
777
|
+
exportRoot: exportDir,
|
|
778
|
+
relativeTarget: body.filename,
|
|
779
|
+
filenameTemplate: rule?.filenameTemplate,
|
|
780
|
+
output: job.resultJson,
|
|
781
|
+
context: {
|
|
782
|
+
repoName: repo?.name ?? 'repo',
|
|
783
|
+
branch: job.headRef ?? 'HEAD',
|
|
784
|
+
prNumber: job.prNumber ?? undefined,
|
|
785
|
+
mode: job.mode,
|
|
786
|
+
target: job.target
|
|
787
|
+
}
|
|
788
|
+
});
|
|
789
|
+
return { writtenPath };
|
|
790
|
+
}
|
|
791
|
+
catch (err) {
|
|
792
|
+
return reply.code(400).send({ error: err.message });
|
|
793
|
+
}
|
|
794
|
+
});
|
|
795
|
+
app.post('/api/jobs/:id/github', async (request, reply) => {
|
|
796
|
+
const { id } = request.params;
|
|
797
|
+
const body = (request.body ?? {});
|
|
798
|
+
const job = db.getJob(id);
|
|
799
|
+
if (!job?.resultJson)
|
|
800
|
+
return reply.code(404).send({ error: 'Completed job result not found' });
|
|
801
|
+
const repo = db.getRepo(job.repoId);
|
|
802
|
+
if (!repo?.githubOwner || !repo?.githubRepo) {
|
|
803
|
+
return reply.code(400).send({ error: 'Repository has no GitHub owner/repo configured' });
|
|
804
|
+
}
|
|
805
|
+
const prNumber = body.prNumber ?? job.prNumber;
|
|
806
|
+
if (!prNumber)
|
|
807
|
+
return reply.code(400).send({ error: 'prNumber is required' });
|
|
808
|
+
const auth = await resolveGitHubAuth();
|
|
809
|
+
if (!auth)
|
|
810
|
+
return reply.code(400).send({ error: 'GitHub PAT or App credentials not configured' });
|
|
811
|
+
const octokit = await createOctokitClient(auth);
|
|
812
|
+
const pr = await octokit.pulls.get({ owner: repo.githubOwner, repo: repo.githubRepo, pull_number: prNumber });
|
|
813
|
+
const diffRes = await octokit.pulls.get({
|
|
814
|
+
owner: repo.githubOwner,
|
|
815
|
+
repo: repo.githubRepo,
|
|
816
|
+
pull_number: prNumber,
|
|
817
|
+
mediaType: { format: 'diff' }
|
|
818
|
+
});
|
|
819
|
+
const repoCfg = await loadCodePulseRepoConfig(repo.localPath ?? process.cwd());
|
|
820
|
+
const published = await publishPrReview({
|
|
821
|
+
octokit,
|
|
822
|
+
owner: repo.githubOwner,
|
|
823
|
+
repo: repo.githubRepo,
|
|
824
|
+
prNumber,
|
|
825
|
+
commitSha: pr.data.head.sha,
|
|
826
|
+
output: job.resultJson,
|
|
827
|
+
prDiffText: String(diffRes.data),
|
|
828
|
+
attribution: repoCfg.attribution
|
|
829
|
+
});
|
|
830
|
+
return { published };
|
|
831
|
+
});
|
|
832
|
+
// --- Auto-Fix & Revalidate ---
|
|
833
|
+
app.post('/api/findings/:id/autofix', async (request, reply) => {
|
|
834
|
+
const { id } = request.params;
|
|
835
|
+
const body = (request.body ?? {});
|
|
836
|
+
const finding = db.getFinding(id);
|
|
837
|
+
if (!finding)
|
|
838
|
+
return reply.code(404).send({ error: 'Finding not found' });
|
|
839
|
+
const repo = db.getRepo(finding.repoId);
|
|
840
|
+
if (!repo?.localPath)
|
|
841
|
+
return reply.code(400).send({ error: 'Repo has no localPath' });
|
|
842
|
+
try {
|
|
843
|
+
const aiClient = new ByokAiClient(resolveAiConfigFromEnv());
|
|
844
|
+
const attempt = await runControlledAutoFix(db, {
|
|
845
|
+
repoId: repo.id,
|
|
846
|
+
repoPath: repo.localPath,
|
|
847
|
+
findingId: id,
|
|
848
|
+
optIn: body.optIn,
|
|
849
|
+
aiClient
|
|
850
|
+
});
|
|
851
|
+
return { attempt };
|
|
852
|
+
}
|
|
853
|
+
catch (err) {
|
|
854
|
+
return reply.code(400).send({ error: err.message });
|
|
855
|
+
}
|
|
856
|
+
});
|
|
857
|
+
app.post('/api/findings/:id/commit-fix', async (request, reply) => {
|
|
858
|
+
const { id } = request.params;
|
|
859
|
+
const body = (request.body ?? {});
|
|
860
|
+
const finding = db.getFinding(id);
|
|
861
|
+
if (!finding)
|
|
862
|
+
return reply.code(404).send({ error: 'Finding not found' });
|
|
863
|
+
const repo = db.getRepo(finding.repoId);
|
|
864
|
+
if (!repo?.localPath)
|
|
865
|
+
return reply.code(400).send({ error: 'Repo has no localPath' });
|
|
866
|
+
const job = db.getJob(finding.jobId);
|
|
867
|
+
const headRef = body.headRef || job?.headRef || '';
|
|
868
|
+
const res = await pushGuardedCommitFixToPrBranch({
|
|
869
|
+
repoPath: repo.localPath,
|
|
870
|
+
headRef,
|
|
871
|
+
defaultBranch: repo.defaultBranch,
|
|
872
|
+
findingId: id,
|
|
873
|
+
commitMessage: body.commitMessage,
|
|
874
|
+
optInPush: Boolean(body.optInPush)
|
|
875
|
+
});
|
|
876
|
+
return res.allowed ? res : reply.code(400).send(res);
|
|
877
|
+
});
|
|
878
|
+
// --- Linked Multi-Repo Workspace Groups ---
|
|
879
|
+
app.get('/api/repos/groups', async () => {
|
|
880
|
+
return { groups: db.listRepoGroups() };
|
|
881
|
+
});
|
|
882
|
+
app.post('/api/repos/groups', async (request, reply) => {
|
|
883
|
+
const body = (request.body ?? {});
|
|
884
|
+
if (!body.name?.trim())
|
|
885
|
+
return reply.code(400).send({ error: 'Group name is required' });
|
|
886
|
+
const group = db.upsertRepoGroup({
|
|
887
|
+
id: body.id,
|
|
888
|
+
name: body.name.trim(),
|
|
889
|
+
description: body.description?.trim(),
|
|
890
|
+
repoIds: Array.isArray(body.repoIds) ? body.repoIds : []
|
|
891
|
+
});
|
|
892
|
+
return { group };
|
|
893
|
+
});
|
|
894
|
+
app.delete('/api/repos/groups/:id', async (request) => {
|
|
895
|
+
const { id } = request.params;
|
|
896
|
+
return { deleted: db.deleteRepoGroup(id) };
|
|
897
|
+
});
|
|
898
|
+
app.post('/api/repos/groups/:id/radar', async (request, reply) => {
|
|
899
|
+
const { id } = request.params;
|
|
900
|
+
const group = db.listRepoGroups().find((g) => g.id === id);
|
|
901
|
+
if (!group)
|
|
902
|
+
return reply.code(404).send({ error: 'Repo group not found' });
|
|
903
|
+
const memberRepos = group.repoIds
|
|
904
|
+
.map((rid) => db.getRepo(rid))
|
|
905
|
+
.filter((r) => Boolean(r?.localPath));
|
|
906
|
+
const combinedNodes = memberRepos.flatMap((r) => db.getAstNodesForRepo(r.id));
|
|
907
|
+
const radarFindings = [];
|
|
908
|
+
for (const r of memberRepos) {
|
|
909
|
+
const f = await runCrossLayerDriftRadar(r.localPath, combinedNodes).catch(() => []);
|
|
910
|
+
radarFindings.push(...f);
|
|
911
|
+
}
|
|
912
|
+
return { groupId: id, memberCount: memberRepos.length, findings: radarFindings };
|
|
913
|
+
});
|
|
914
|
+
// --- GitLab, Bitbucket & Stacked PR Providers ---
|
|
915
|
+
app.get('/api/providers/gitlab/repos', async (_request, reply) => {
|
|
916
|
+
const token = process.env.GITLAB_TOKEN;
|
|
917
|
+
if (!token)
|
|
918
|
+
return reply.code(400).send({ error: 'GITLAB_TOKEN not configured' });
|
|
919
|
+
try {
|
|
920
|
+
const repos = await listAccessibleGitLabProjects({
|
|
921
|
+
baseUrl: process.env.GITLAB_BASE_URL || db.getSetting('gitHosting.gitlabBaseUrl') || undefined,
|
|
922
|
+
token,
|
|
923
|
+
fetchImpl: options.fetchImpl
|
|
924
|
+
});
|
|
925
|
+
return { repos };
|
|
926
|
+
}
|
|
927
|
+
catch (err) {
|
|
928
|
+
return reply.code(502).send({ error: err.message });
|
|
929
|
+
}
|
|
930
|
+
});
|
|
931
|
+
app.get('/api/providers/bitbucket/repos', async (_request, reply) => {
|
|
932
|
+
const token = process.env.BITBUCKET_TOKEN;
|
|
933
|
+
if (!token)
|
|
934
|
+
return reply.code(400).send({ error: 'BITBUCKET_TOKEN not configured' });
|
|
935
|
+
try {
|
|
936
|
+
const repos = await listAccessibleBitbucketRepos({
|
|
937
|
+
token,
|
|
938
|
+
username: process.env.BITBUCKET_USERNAME || undefined,
|
|
939
|
+
fetchImpl: options.fetchImpl
|
|
940
|
+
});
|
|
941
|
+
return { repos };
|
|
942
|
+
}
|
|
943
|
+
catch (err) {
|
|
944
|
+
return reply.code(502).send({ error: err.message });
|
|
945
|
+
}
|
|
946
|
+
});
|
|
947
|
+
app.get('/api/github/stacked-prs', async (request, reply) => {
|
|
948
|
+
const q = request.query;
|
|
949
|
+
let owner = q.owner;
|
|
950
|
+
let repoName = q.repo;
|
|
951
|
+
if ((!owner || !repoName) && q.repoId) {
|
|
952
|
+
const r = db.getRepo(q.repoId);
|
|
953
|
+
owner = r?.githubOwner ?? undefined;
|
|
954
|
+
repoName = r?.githubRepo ?? undefined;
|
|
955
|
+
}
|
|
956
|
+
if (!owner || !repoName)
|
|
957
|
+
return reply.code(400).send({ error: 'owner/repo or repoId required' });
|
|
958
|
+
const gh = await resolveRepoOctokit();
|
|
959
|
+
if (!gh)
|
|
960
|
+
return reply.code(400).send({ error: 'GitHub credentials not configured' });
|
|
961
|
+
const pulls = await listOpenPullRequests(gh.octokit, owner, repoName);
|
|
962
|
+
const stacked = detectStackedPrChains(pulls.map((p) => ({ number: p.number, title: p.title, headRef: p.headRef, baseRef: p.baseRef })));
|
|
963
|
+
return { pulls: stacked };
|
|
964
|
+
});
|
|
965
|
+
app.post('/api/revalidate', async (request, reply) => {
|
|
966
|
+
const body = (request.body ?? {});
|
|
967
|
+
const repo = db.getRepo(body.repoId);
|
|
968
|
+
if (!repo?.localPath)
|
|
969
|
+
return reply.code(404).send({ error: 'Repository with localPath not found' });
|
|
970
|
+
const aiClient = new ByokAiClient(resolveAiConfigFromEnv());
|
|
971
|
+
const result = await revalidateFindings(db, {
|
|
972
|
+
repoId: repo.id,
|
|
973
|
+
repoPath: repo.localPath,
|
|
974
|
+
target: body.target ?? 'local_uncommitted',
|
|
975
|
+
baseScanId: body.baseScanId,
|
|
976
|
+
findingIds: body.findingIds,
|
|
977
|
+
aiClient
|
|
978
|
+
});
|
|
979
|
+
return result;
|
|
980
|
+
});
|
|
981
|
+
// --- Docs & AST Graph ---
|
|
982
|
+
app.post('/api/docs/generate', async (request, reply) => {
|
|
983
|
+
const body = (request.body ?? {});
|
|
984
|
+
const repo = db.getRepo(body.repoId);
|
|
985
|
+
if (!repo?.localPath)
|
|
986
|
+
return reply.code(404).send({ error: 'Repository with localPath not found' });
|
|
987
|
+
const aiClient = new ByokAiClient(resolveAiConfigFromEnv());
|
|
988
|
+
let safeOutputDir;
|
|
989
|
+
if (body.outputDir) {
|
|
990
|
+
try {
|
|
991
|
+
safeOutputDir = safeResolveInside(repo.localPath, body.outputDir);
|
|
992
|
+
}
|
|
993
|
+
catch (err) {
|
|
994
|
+
return reply.code(403).send({ error: err.message });
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
const docs = await generateProjectDocs({
|
|
998
|
+
db,
|
|
999
|
+
repoId: repo.id,
|
|
1000
|
+
repoPath: repo.localPath,
|
|
1001
|
+
repoName: repo.name,
|
|
1002
|
+
outputDir: safeOutputDir,
|
|
1003
|
+
aiClient
|
|
1004
|
+
});
|
|
1005
|
+
return docs;
|
|
1006
|
+
});
|
|
1007
|
+
app.post('/api/testing/generate', async (request, reply) => {
|
|
1008
|
+
const body = (request.body ?? {});
|
|
1009
|
+
const repo = db.getRepo(body.repoId);
|
|
1010
|
+
if (!repo?.localPath)
|
|
1011
|
+
return reply.code(404).send({ error: 'Repository with localPath not found' });
|
|
1012
|
+
if (!body.targetFile)
|
|
1013
|
+
return reply.code(400).send({ error: 'targetFile is required' });
|
|
1014
|
+
let relSafeTarget;
|
|
1015
|
+
try {
|
|
1016
|
+
const absTarget = safeResolveInside(repo.localPath, body.targetFile);
|
|
1017
|
+
relSafeTarget = path.relative(path.resolve(repo.localPath), absTarget).replace(/\\/g, '/');
|
|
1018
|
+
}
|
|
1019
|
+
catch (err) {
|
|
1020
|
+
return reply.code(403).send({ error: err.message });
|
|
1021
|
+
}
|
|
1022
|
+
const aiClient = new ByokAiClient(resolveAiConfigFromEnv());
|
|
1023
|
+
const findingRecord = body.findingId ? db.getFinding(body.findingId) : null;
|
|
1024
|
+
const latestJob = db.listJobs(20).find((j) => j.repoId === repo.id && j.status === 'completed');
|
|
1025
|
+
const fullFinding = findingRecord
|
|
1026
|
+
? latestJob?.resultJson?.findings.find((f) => f.id === findingRecord.id)
|
|
1027
|
+
: undefined;
|
|
1028
|
+
const res = await generateUnitTestsForTarget({
|
|
1029
|
+
repoPath: repo.localPath,
|
|
1030
|
+
targetFile: relSafeTarget,
|
|
1031
|
+
finding: fullFinding,
|
|
1032
|
+
astNodes: db.getAstNodesForRepo(repo.id),
|
|
1033
|
+
aiClient,
|
|
1034
|
+
writeToDisk: Boolean(body.writeToDisk)
|
|
1035
|
+
});
|
|
1036
|
+
return res;
|
|
1037
|
+
});
|
|
1038
|
+
// --- Dismiss / Feedback Memory, Pulse Score & Smart Context Pack ---
|
|
1039
|
+
app.post('/api/findings/:id/ignore', async (request, reply) => {
|
|
1040
|
+
const { id } = request.params;
|
|
1041
|
+
const body = (request.body ?? {});
|
|
1042
|
+
const finding = db.getFinding(id);
|
|
1043
|
+
if (!finding)
|
|
1044
|
+
return reply.code(404).send({ error: 'Finding not found' });
|
|
1045
|
+
const repo = db.getRepo(finding.repoId);
|
|
1046
|
+
db.updateFindingStatus(id, 'dismissed');
|
|
1047
|
+
let rule = null;
|
|
1048
|
+
if (repo?.localPath) {
|
|
1049
|
+
rule = await addIgnoredPattern(repo.localPath, {
|
|
1050
|
+
finding,
|
|
1051
|
+
reason: body.reason || 'Dismissed via CodePulse Workbench'
|
|
1052
|
+
});
|
|
1053
|
+
}
|
|
1054
|
+
return { ok: true, findingId: id, rule };
|
|
1055
|
+
});
|
|
1056
|
+
app.get('/api/findings/:id/context', async (request, reply) => {
|
|
1057
|
+
const { id } = request.params;
|
|
1058
|
+
const finding = db.getFinding(id);
|
|
1059
|
+
if (!finding)
|
|
1060
|
+
return reply.code(404).send({ error: 'Finding not found' });
|
|
1061
|
+
const repo = db.getRepo(finding.repoId);
|
|
1062
|
+
if (!repo?.localPath)
|
|
1063
|
+
return { lines: [], startLine: 1, highlightStart: finding.line_start, highlightEnd: finding.line_end };
|
|
1064
|
+
try {
|
|
1065
|
+
const targetAbs = path.resolve(repo.localPath, finding.file);
|
|
1066
|
+
const repoRootAbs = path.resolve(repo.localPath);
|
|
1067
|
+
if (!targetAbs.startsWith(repoRootAbs + path.sep) && targetAbs !== repoRootAbs) {
|
|
1068
|
+
return reply.code(403).send({ error: 'Path traversal blocked' });
|
|
1069
|
+
}
|
|
1070
|
+
const raw = await fs.readFile(targetAbs, 'utf8');
|
|
1071
|
+
const allLines = raw.split(/\r?\n/);
|
|
1072
|
+
const start = Math.max(1, finding.line_start - 12);
|
|
1073
|
+
const end = Math.min(allLines.length, Math.max(finding.line_end, finding.line_start) + 12);
|
|
1074
|
+
const snippetLines = allLines.slice(start - 1, end).map((text, idx) => ({
|
|
1075
|
+
line: start + idx,
|
|
1076
|
+
text: maskSecrets(text)
|
|
1077
|
+
}));
|
|
1078
|
+
return {
|
|
1079
|
+
file: finding.file,
|
|
1080
|
+
startLine: start,
|
|
1081
|
+
highlightStart: finding.line_start,
|
|
1082
|
+
highlightEnd: finding.line_end,
|
|
1083
|
+
lines: snippetLines,
|
|
1084
|
+
patchSuggestion: finding.patch_suggestion ?? null
|
|
1085
|
+
};
|
|
1086
|
+
}
|
|
1087
|
+
catch {
|
|
1088
|
+
return { lines: [], startLine: 1, highlightStart: finding.line_start, highlightEnd: finding.line_end, patchSuggestion: finding.patch_suggestion ?? null };
|
|
1089
|
+
}
|
|
1090
|
+
});
|
|
1091
|
+
// Interactive Split Diff Viewer payload (`Before` vs `After` vs `Proposed Auto-Fix` + VS Code/Cursor URIs)
|
|
1092
|
+
app.get('/api/findings/:id/diff', async (request, reply) => {
|
|
1093
|
+
const { id } = request.params;
|
|
1094
|
+
const finding = db.getFinding(id);
|
|
1095
|
+
if (!finding)
|
|
1096
|
+
return reply.code(404).send({ error: 'Finding not found' });
|
|
1097
|
+
const repo = db.getRepo(finding.repoId);
|
|
1098
|
+
if (!repo?.localPath) {
|
|
1099
|
+
return {
|
|
1100
|
+
file: finding.file,
|
|
1101
|
+
startLine: finding.line_start,
|
|
1102
|
+
endLine: finding.line_end,
|
|
1103
|
+
beforeLines: [],
|
|
1104
|
+
afterLines: [],
|
|
1105
|
+
proposedAfterLines: [],
|
|
1106
|
+
patchSuggestion: finding.patch_suggestion ?? null
|
|
1107
|
+
};
|
|
1108
|
+
}
|
|
1109
|
+
const repoRootAbs = path.resolve(repo.localPath);
|
|
1110
|
+
const targetAbs = path.resolve(repoRootAbs, finding.file);
|
|
1111
|
+
if (!targetAbs.startsWith(repoRootAbs + path.sep) && targetAbs !== repoRootAbs) {
|
|
1112
|
+
return reply.code(403).send({ error: 'Path traversal blocked' });
|
|
1113
|
+
}
|
|
1114
|
+
const currentRaw = await fs.readFile(targetAbs, 'utf8').catch(() => '');
|
|
1115
|
+
const currentLines = currentRaw ? currentRaw.split(/\r?\n/) : [];
|
|
1116
|
+
const start = Math.max(1, finding.line_start - 10);
|
|
1117
|
+
const end = Math.min(Math.max(1, currentLines.length), Math.max(finding.line_end, finding.line_start) + 10);
|
|
1118
|
+
// Fetch HEAD version if git repo exists to show true Before vs After diff
|
|
1119
|
+
const headShow = await runCommand('git', ['show', `HEAD:${finding.file.replace(/\\/g, '/')}`], {
|
|
1120
|
+
cwd: repoRootAbs,
|
|
1121
|
+
timeoutMs: 3000
|
|
1122
|
+
});
|
|
1123
|
+
const headLines = headShow.exitCode === 0 ? headShow.stdout.split(/\r?\n/) : currentLines;
|
|
1124
|
+
const beforeLines = headLines.slice(start - 1, end).map((text, idx) => ({
|
|
1125
|
+
line: start + idx,
|
|
1126
|
+
text: maskSecrets(text),
|
|
1127
|
+
changed: currentLines[start - 1 + idx] !== text
|
|
1128
|
+
}));
|
|
1129
|
+
const afterLines = currentLines.slice(start - 1, end).map((text, idx) => ({
|
|
1130
|
+
line: start + idx,
|
|
1131
|
+
text: maskSecrets(text),
|
|
1132
|
+
highlight: start + idx >= finding.line_start && start + idx <= finding.line_end,
|
|
1133
|
+
changed: headLines[start - 1 + idx] !== text
|
|
1134
|
+
}));
|
|
1135
|
+
const normalizedUriPath = targetAbs.replace(/\\/g, '/');
|
|
1136
|
+
return {
|
|
1137
|
+
file: finding.file,
|
|
1138
|
+
absPath: targetAbs,
|
|
1139
|
+
vscodeUri: `vscode://file/${normalizedUriPath}:${finding.line_start}`,
|
|
1140
|
+
cursorUri: `cursor://file/${normalizedUriPath}:${finding.line_start}`,
|
|
1141
|
+
startLine: start,
|
|
1142
|
+
highlightStart: finding.line_start,
|
|
1143
|
+
highlightEnd: finding.line_end,
|
|
1144
|
+
beforeLines,
|
|
1145
|
+
afterLines,
|
|
1146
|
+
patchSuggestion: finding.patch_suggestion ?? null,
|
|
1147
|
+
archeology: finding.archeology ?? null,
|
|
1148
|
+
finding
|
|
1149
|
+
};
|
|
1150
|
+
});
|
|
1151
|
+
// --- Signed Team Baseline & Suppression Governance (`.codepulse/baseline.json`) ---
|
|
1152
|
+
app.get('/api/baseline/:repoId', async (request, reply) => {
|
|
1153
|
+
const { repoId } = request.params;
|
|
1154
|
+
const repo = db.getRepo(repoId);
|
|
1155
|
+
if (!repo?.localPath)
|
|
1156
|
+
return reply.code(404).send({ error: 'Repo with localPath not found' });
|
|
1157
|
+
const verification = await verifyTeamBaseline(repo.localPath);
|
|
1158
|
+
return verification;
|
|
1159
|
+
});
|
|
1160
|
+
app.post('/api/baseline/:repoId/suppress', async (request, reply) => {
|
|
1161
|
+
const { repoId } = request.params;
|
|
1162
|
+
const body = (request.body ?? {});
|
|
1163
|
+
const repo = db.getRepo(repoId);
|
|
1164
|
+
if (!repo?.localPath)
|
|
1165
|
+
return reply.code(404).send({ error: 'Repo with localPath not found' });
|
|
1166
|
+
const finding = body.findingId ? db.getFinding(body.findingId) : null;
|
|
1167
|
+
if (!finding)
|
|
1168
|
+
return reply.code(404).send({ error: 'Finding not found' });
|
|
1169
|
+
const saved = await upsertBaselineSuppression(repo.localPath, {
|
|
1170
|
+
finding,
|
|
1171
|
+
reason: body.reason ?? 'Accepted / suppressed via CodePulse Team Baseline',
|
|
1172
|
+
reviewer: body.reviewer ?? 'cockpit-user',
|
|
1173
|
+
expiryDate: body.expiryDate
|
|
1174
|
+
});
|
|
1175
|
+
db.updateFindingStatus(finding.id, 'dismissed');
|
|
1176
|
+
return { ok: true, baseline: saved };
|
|
1177
|
+
});
|
|
1178
|
+
app.delete('/api/baseline/:repoId/:fingerprint', async (request, reply) => {
|
|
1179
|
+
const { repoId, fingerprint } = request.params;
|
|
1180
|
+
const repo = db.getRepo(repoId);
|
|
1181
|
+
if (!repo?.localPath)
|
|
1182
|
+
return reply.code(404).send({ error: 'Repo with localPath not found' });
|
|
1183
|
+
const saved = await removeBaselineSuppression(repo.localPath, fingerprint);
|
|
1184
|
+
return { ok: true, baseline: saved };
|
|
1185
|
+
});
|
|
1186
|
+
// --- Security Velocity Trends (30/90d) & Hotspot Churn×Complexity Matrix ---
|
|
1187
|
+
app.get('/api/trends/:repoId', async (request, reply) => {
|
|
1188
|
+
const { repoId } = request.params;
|
|
1189
|
+
const q = request.query;
|
|
1190
|
+
const repo = db.getRepo(repoId);
|
|
1191
|
+
if (!repo)
|
|
1192
|
+
return reply.code(404).send({ error: 'Repo not found' });
|
|
1193
|
+
const days = Math.max(7, Math.min(365, Number(q.days ?? 90) || 90));
|
|
1194
|
+
const trends = db.getSecurityTrends(repoId, days);
|
|
1195
|
+
const nodes = db.getAstNodesForRepo(repoId);
|
|
1196
|
+
const hotspots = repo.localPath ? await computeHotspotMatrix(repo.localPath, nodes, 15) : [];
|
|
1197
|
+
const baseline = repo.localPath ? await verifyTeamBaseline(repo.localPath) : null;
|
|
1198
|
+
return { trends, hotspots, baseline };
|
|
1199
|
+
});
|
|
1200
|
+
app.get('/api/memory/:repoId', async (request, reply) => {
|
|
1201
|
+
const { repoId } = request.params;
|
|
1202
|
+
const repo = db.getRepo(repoId);
|
|
1203
|
+
if (!repo?.localPath)
|
|
1204
|
+
return reply.code(404).send({ error: 'Repo with localPath not found' });
|
|
1205
|
+
const memory = await loadFeedbackMemory(repo.localPath);
|
|
1206
|
+
return { memory };
|
|
1207
|
+
});
|
|
1208
|
+
app.delete('/api/memory/:repoId/:ruleId', async (request, reply) => {
|
|
1209
|
+
const { repoId, ruleId } = request.params;
|
|
1210
|
+
const repo = db.getRepo(repoId);
|
|
1211
|
+
if (!repo?.localPath)
|
|
1212
|
+
return reply.code(404).send({ error: 'Repo with localPath not found' });
|
|
1213
|
+
const removed = await removeIgnoredPattern(repo.localPath, ruleId);
|
|
1214
|
+
return { removed };
|
|
1215
|
+
});
|
|
1216
|
+
app.get('/api/pulse/:repoId', async (request, reply) => {
|
|
1217
|
+
const { repoId } = request.params;
|
|
1218
|
+
const repo = db.getRepo(repoId);
|
|
1219
|
+
if (!repo)
|
|
1220
|
+
return reply.code(404).send({ error: 'Repo not found' });
|
|
1221
|
+
const history = db.listPulseHistory(repoId, 30);
|
|
1222
|
+
const currentScore = history.length > 0
|
|
1223
|
+
? history[history.length - 1].pulseScore
|
|
1224
|
+
: computePulseScore({ critical: 0, high: 0, medium: 0, low: 0 });
|
|
1225
|
+
return { currentScore, history };
|
|
1226
|
+
});
|
|
1227
|
+
app.get('/api/context-pack/:repoId', async (request, reply) => {
|
|
1228
|
+
const { repoId } = request.params;
|
|
1229
|
+
const q = request.query;
|
|
1230
|
+
const repo = db.getRepo(repoId);
|
|
1231
|
+
if (!repo?.localPath)
|
|
1232
|
+
return reply.code(404).send({ error: 'Repo with localPath not found' });
|
|
1233
|
+
const pack = await generateSmartContextPack({
|
|
1234
|
+
db,
|
|
1235
|
+
repoId: repo.id,
|
|
1236
|
+
repoPath: repo.localPath,
|
|
1237
|
+
repoName: repo.name,
|
|
1238
|
+
format: q.format === 'xml' ? 'xml' : 'markdown'
|
|
1239
|
+
});
|
|
1240
|
+
return { pack };
|
|
1241
|
+
});
|
|
1242
|
+
app.get('/api/graph/:repoId', async (request, reply) => {
|
|
1243
|
+
const { repoId } = request.params;
|
|
1244
|
+
const repo = db.getRepo(repoId);
|
|
1245
|
+
if (!repo)
|
|
1246
|
+
return reply.code(404).send({ error: 'Repo not found' });
|
|
1247
|
+
if (repo.localPath && db.getAstNodesForRepo(repoId).length === 0) {
|
|
1248
|
+
const indexer = new TreeSitterGraphIndexer(db);
|
|
1249
|
+
await indexer.indexRepository(repoId, repo.localPath);
|
|
1250
|
+
}
|
|
1251
|
+
return {
|
|
1252
|
+
nodes: db.getAstNodesForRepo(repoId).slice(0, 300),
|
|
1253
|
+
edges: db.getAstEdgesForRepo(repoId).slice(0, 500),
|
|
1254
|
+
slices: db.listSlices(repoId)
|
|
1255
|
+
};
|
|
1256
|
+
});
|
|
1257
|
+
// "What-If" Breakage Simulator on Blast Radius Graph
|
|
1258
|
+
app.get('/api/graph/:repoId/simulate', async (request, reply) => {
|
|
1259
|
+
const { repoId } = request.params;
|
|
1260
|
+
const q = request.query;
|
|
1261
|
+
const repo = db.getRepo(repoId);
|
|
1262
|
+
if (!repo)
|
|
1263
|
+
return reply.code(404).send({ error: 'Repo not found' });
|
|
1264
|
+
const file = q.file?.trim();
|
|
1265
|
+
if (!file)
|
|
1266
|
+
return reply.code(400).send({ error: 'file query parameter required' });
|
|
1267
|
+
const indexer = new TreeSitterGraphIndexer(db);
|
|
1268
|
+
const blast = indexer.queryBlastRadius(repoId, [file], q.symbol ? [q.symbol] : []);
|
|
1269
|
+
const allNodes = db.getAstNodesForRepo(repoId);
|
|
1270
|
+
const affectedFileSet = new Set([file, ...blast.dependents]);
|
|
1271
|
+
const affectedRoutes = allNodes
|
|
1272
|
+
.filter((n) => n.kind === 'route' && affectedFileSet.has(n.file))
|
|
1273
|
+
.map((n) => ({ file: n.file, route: n.name, line: n.lineStart }));
|
|
1274
|
+
return {
|
|
1275
|
+
targetFile: file,
|
|
1276
|
+
symbol: q.symbol ?? null,
|
|
1277
|
+
...blast,
|
|
1278
|
+
affectedRoutes
|
|
1279
|
+
};
|
|
1280
|
+
});
|
|
1281
|
+
// 1-Click Run Affected Unit Tests from What-If Simulator
|
|
1282
|
+
app.post('/api/testing/run-affected', async (request, reply) => {
|
|
1283
|
+
const body = (request.body ?? {});
|
|
1284
|
+
const repo = body.repoId ? db.getRepo(body.repoId) : null;
|
|
1285
|
+
if (!repo?.localPath)
|
|
1286
|
+
return reply.code(404).send({ error: 'Repository with localPath not found' });
|
|
1287
|
+
const safeFiles = (body.testFiles ?? [])
|
|
1288
|
+
.filter((f) => typeof f === 'string' && !f.includes('..') && /\.(?:test|spec)\.[A-Za-z0-9]+$/i.test(f))
|
|
1289
|
+
.slice(0, 10);
|
|
1290
|
+
const args = safeFiles.length > 0 ? ['--test', ...safeFiles] : ['test'];
|
|
1291
|
+
const bin = safeFiles.length > 0 ? process.execPath : process.platform === 'win32' ? 'npm.cmd' : 'npm';
|
|
1292
|
+
const startedAt = performance.now();
|
|
1293
|
+
const res = await runCommand(bin, args, { cwd: repo.localPath, timeoutMs: 45_000 });
|
|
1294
|
+
return {
|
|
1295
|
+
passed: res.exitCode === 0,
|
|
1296
|
+
exitCode: res.exitCode,
|
|
1297
|
+
durationMs: Math.round(performance.now() - startedAt),
|
|
1298
|
+
testFiles: safeFiles,
|
|
1299
|
+
output: maskSecrets(`${res.stdout}\n${res.stderr}`).slice(0, 6000)
|
|
1300
|
+
};
|
|
1301
|
+
});
|
|
1302
|
+
// --- Output Rules & Settings ---
|
|
1303
|
+
app.get('/api/output-rules/:repoId', async (request) => {
|
|
1304
|
+
const { repoId } = request.params;
|
|
1305
|
+
return { rule: db.getOutputRuleForRepo(repoId === 'default' ? null : repoId) };
|
|
1306
|
+
});
|
|
1307
|
+
app.put('/api/output-rules/:repoId', async (request) => {
|
|
1308
|
+
const { repoId } = request.params;
|
|
1309
|
+
const body = (request.body ?? {});
|
|
1310
|
+
const normalizedRepoId = repoId === 'default' ? null : repoId;
|
|
1311
|
+
const rule = db.upsertOutputRule({
|
|
1312
|
+
id: `rule-${normalizedRepoId ?? 'default'}`,
|
|
1313
|
+
repoId: normalizedRepoId,
|
|
1314
|
+
exportDir: body.exportDir || './reports',
|
|
1315
|
+
filenameTemplate: body.filenameTemplate || '{repo}-{branch}-{date}-{mode}.md',
|
|
1316
|
+
autoSave: Boolean(body.autoSave),
|
|
1317
|
+
postGithubComments: body.postGithubComments ?? true,
|
|
1318
|
+
commentPolicy: body.commentPolicy ?? 'update_summary',
|
|
1319
|
+
minSeverity: body.minSeverity ?? 'low'
|
|
1320
|
+
});
|
|
1321
|
+
return { rule };
|
|
1322
|
+
});
|
|
1323
|
+
function maskSecretTail(val) {
|
|
1324
|
+
if (!val)
|
|
1325
|
+
return '';
|
|
1326
|
+
return val.length > 4 ? `****${val.slice(-4)}` : '****';
|
|
1327
|
+
}
|
|
1328
|
+
const SUPPORTED_LOCALES = new Set(['en', 'es', 'ar', 'fr']);
|
|
1329
|
+
const SUPPORTED_THEMES = new Set([
|
|
1330
|
+
'obsidian',
|
|
1331
|
+
'slate',
|
|
1332
|
+
'nord',
|
|
1333
|
+
'tokyo',
|
|
1334
|
+
'emerald',
|
|
1335
|
+
'rose',
|
|
1336
|
+
'dracula',
|
|
1337
|
+
'amber',
|
|
1338
|
+
'light',
|
|
1339
|
+
'paper'
|
|
1340
|
+
]);
|
|
1341
|
+
const SUPPORTED_PACKS = new Set(['owasp-asvs', 'pci-dss', 'hipaa', 'nca-ecc-gdpr']);
|
|
1342
|
+
app.get('/api/settings', async () => {
|
|
1343
|
+
const cfg = resolveAiConfigFromEnv({
|
|
1344
|
+
provider: db.getSetting('ai.provider'),
|
|
1345
|
+
model: db.getSetting('ai.model'),
|
|
1346
|
+
baseUrl: db.getSetting('ai.baseUrl')
|
|
1347
|
+
});
|
|
1348
|
+
const ghToken = process.env.GITHUB_TOKEN;
|
|
1349
|
+
const savedLang = db.getSetting('ui.language') ?? 'en';
|
|
1350
|
+
const savedTheme = db.getSetting('ui.theme') ?? 'obsidian';
|
|
1351
|
+
const desktopPrefs = options.desktopBridge?.getDesktopPrefs
|
|
1352
|
+
? await options.desktopBridge.getDesktopPrefs().catch(() => null)
|
|
1353
|
+
: null;
|
|
1354
|
+
return {
|
|
1355
|
+
provider: cfg.provider,
|
|
1356
|
+
model: cfg.model,
|
|
1357
|
+
fastModel: cfg.fastModel ?? '',
|
|
1358
|
+
baseUrl: cfg.baseUrl ?? '',
|
|
1359
|
+
language: SUPPORTED_LOCALES.has(savedLang) ? savedLang : 'en',
|
|
1360
|
+
theme: SUPPORTED_THEMES.has(savedTheme) ? savedTheme : 'obsidian',
|
|
1361
|
+
concurrency: queue.concurrency,
|
|
1362
|
+
hasApiKey: Boolean(cfg.apiKey && cfg.apiKey.length > 0),
|
|
1363
|
+
maskedKey: maskSecretTail(cfg.apiKey),
|
|
1364
|
+
hasGithubToken: Boolean(ghToken && ghToken.length > 0),
|
|
1365
|
+
maskedGithubToken: maskSecretTail(ghToken),
|
|
1366
|
+
hasGitlabToken: Boolean(process.env.GITLAB_TOKEN),
|
|
1367
|
+
gitlabBaseUrl: process.env.GITLAB_BASE_URL || db.getSetting('gitHosting.gitlabBaseUrl') || 'https://gitlab.com',
|
|
1368
|
+
hasBitbucketToken: Boolean(process.env.BITBUCKET_TOKEN),
|
|
1369
|
+
compliancePacks: db.getSetting('audit.compliancePacks', []) ?? [],
|
|
1370
|
+
availableCompliancePacks: COMPLIANCE_PACKS,
|
|
1371
|
+
starPromptDismissed: db.getSetting('ui.starPromptDismissed', false) === true,
|
|
1372
|
+
pollSeconds: pollIntervalSeconds,
|
|
1373
|
+
pollerActive: Boolean(activePoller),
|
|
1374
|
+
autoScanOpenPrsOnPoll: db.getSetting('github.autoScanOpenPrsOnPoll', false) === true,
|
|
1375
|
+
autofixDefault: db.getSetting('scan.autofixDefault', process.env.CODEPULSE_AUTOFIX_ENABLED === 'true') ?? false,
|
|
1376
|
+
enableOsv: db.getSetting('scan.enableOsv', true) !== false,
|
|
1377
|
+
enableRadar: db.getSetting('scan.enableRadar', true) !== false,
|
|
1378
|
+
includeSeoGeo: db.getSetting('scan.includeSeoGeo', true) !== false,
|
|
1379
|
+
privacyFirewall: db.getSetting('ai.privacyFirewall', true) !== false,
|
|
1380
|
+
fallbackProvider: db.getSetting('ai.fallbackProvider') ?? '',
|
|
1381
|
+
fallbackModel: db.getSetting('ai.fallbackModel') ?? '',
|
|
1382
|
+
tokenBudgetWarnUsd: db.getSetting('ai.tokenBudgetWarnUsd', 2),
|
|
1383
|
+
telemetryOptIn: queue.telemetry.isOptedIn(),
|
|
1384
|
+
consentCompleted: queue.telemetry.hasCompletedConsent(),
|
|
1385
|
+
closeAction: desktopPrefs?.closeAction ?? db.getSetting('desktop.closeAction', 'tray') ?? 'tray',
|
|
1386
|
+
openAtLogin: desktopPrefs?.openAtLogin ?? db.getSetting('desktop.openAtLogin', false) ?? false,
|
|
1387
|
+
checkUpdatesOnStartup: desktopPrefs?.checkUpdatesOnStartup ?? db.getSetting('desktop.checkUpdatesOnStartup', true) !== false,
|
|
1388
|
+
autoDownloadUpdates: desktopPrefs?.autoDownloadUpdates ?? db.getSetting('desktop.autoDownloadUpdates', false) === true
|
|
1389
|
+
};
|
|
1390
|
+
});
|
|
1391
|
+
app.put('/api/settings', async (request) => {
|
|
1392
|
+
const body = (request.body ?? {});
|
|
1393
|
+
if (body.provider)
|
|
1394
|
+
db.setSetting('ai.provider', body.provider);
|
|
1395
|
+
if (body.model)
|
|
1396
|
+
db.setSetting('ai.model', body.model);
|
|
1397
|
+
if (body.baseUrl !== undefined)
|
|
1398
|
+
db.setSetting('ai.baseUrl', body.baseUrl);
|
|
1399
|
+
if (body.gitlabBaseUrl !== undefined)
|
|
1400
|
+
db.setSetting('gitHosting.gitlabBaseUrl', body.gitlabBaseUrl);
|
|
1401
|
+
if (Array.isArray(body.compliancePacks)) {
|
|
1402
|
+
const cleanPacks = body.compliancePacks.filter((p) => SUPPORTED_PACKS.has(p));
|
|
1403
|
+
db.setSetting('audit.compliancePacks', cleanPacks);
|
|
1404
|
+
}
|
|
1405
|
+
if (body.starPromptDismissed !== undefined) {
|
|
1406
|
+
db.setSetting('ui.starPromptDismissed', Boolean(body.starPromptDismissed));
|
|
1407
|
+
}
|
|
1408
|
+
if (body.language && SUPPORTED_LOCALES.has(body.language)) {
|
|
1409
|
+
db.setSetting('ui.language', body.language);
|
|
1410
|
+
}
|
|
1411
|
+
if (body.theme && SUPPORTED_THEMES.has(body.theme)) {
|
|
1412
|
+
db.setSetting('ui.theme', body.theme);
|
|
1413
|
+
}
|
|
1414
|
+
if (typeof body.concurrency === 'number') {
|
|
1415
|
+
queue.setConcurrency(body.concurrency);
|
|
1416
|
+
}
|
|
1417
|
+
if (typeof body.pollSeconds === 'number' && body.pollSeconds >= 0 && body.pollSeconds <= 3600) {
|
|
1418
|
+
pollIntervalSeconds = Math.round(body.pollSeconds);
|
|
1419
|
+
db.setSetting('github.pollSeconds', pollIntervalSeconds);
|
|
1420
|
+
void refreshPoller().catch(() => undefined);
|
|
1421
|
+
}
|
|
1422
|
+
if (body.autoScanOpenPrsOnPoll !== undefined) {
|
|
1423
|
+
db.setSetting('github.autoScanOpenPrsOnPoll', Boolean(body.autoScanOpenPrsOnPoll));
|
|
1424
|
+
}
|
|
1425
|
+
if (body.autofixDefault !== undefined)
|
|
1426
|
+
db.setSetting('scan.autofixDefault', Boolean(body.autofixDefault));
|
|
1427
|
+
if (body.enableOsv !== undefined)
|
|
1428
|
+
db.setSetting('scan.enableOsv', Boolean(body.enableOsv));
|
|
1429
|
+
if (body.enableRadar !== undefined)
|
|
1430
|
+
db.setSetting('scan.enableRadar', Boolean(body.enableRadar));
|
|
1431
|
+
if (body.includeSeoGeo !== undefined)
|
|
1432
|
+
db.setSetting('scan.includeSeoGeo', Boolean(body.includeSeoGeo));
|
|
1433
|
+
if (body.privacyFirewall !== undefined)
|
|
1434
|
+
db.setSetting('ai.privacyFirewall', Boolean(body.privacyFirewall));
|
|
1435
|
+
if (body.fallbackProvider !== undefined)
|
|
1436
|
+
db.setSetting('ai.fallbackProvider', body.fallbackProvider);
|
|
1437
|
+
if (body.fallbackModel !== undefined)
|
|
1438
|
+
db.setSetting('ai.fallbackModel', body.fallbackModel);
|
|
1439
|
+
if (typeof body.tokenBudgetWarnUsd === 'number')
|
|
1440
|
+
db.setSetting('ai.tokenBudgetWarnUsd', body.tokenBudgetWarnUsd);
|
|
1441
|
+
if (body.telemetryOptIn !== undefined)
|
|
1442
|
+
queue.telemetry.setOptIn(Boolean(body.telemetryOptIn));
|
|
1443
|
+
if (body.consentCompleted !== undefined)
|
|
1444
|
+
queue.telemetry.setConsentCompleted(Boolean(body.consentCompleted));
|
|
1445
|
+
const desktopPatch = {};
|
|
1446
|
+
if (body.closeAction === 'tray' || body.closeAction === 'quit') {
|
|
1447
|
+
db.setSetting('desktop.closeAction', body.closeAction);
|
|
1448
|
+
desktopPatch.closeAction = body.closeAction;
|
|
1449
|
+
}
|
|
1450
|
+
if (body.openAtLogin !== undefined) {
|
|
1451
|
+
db.setSetting('desktop.openAtLogin', Boolean(body.openAtLogin));
|
|
1452
|
+
desktopPatch.openAtLogin = Boolean(body.openAtLogin);
|
|
1453
|
+
}
|
|
1454
|
+
if (body.checkUpdatesOnStartup !== undefined) {
|
|
1455
|
+
db.setSetting('desktop.checkUpdatesOnStartup', Boolean(body.checkUpdatesOnStartup));
|
|
1456
|
+
desktopPatch.checkUpdatesOnStartup = Boolean(body.checkUpdatesOnStartup);
|
|
1457
|
+
}
|
|
1458
|
+
if (body.autoDownloadUpdates !== undefined) {
|
|
1459
|
+
db.setSetting('desktop.autoDownloadUpdates', Boolean(body.autoDownloadUpdates));
|
|
1460
|
+
desktopPatch.autoDownloadUpdates = Boolean(body.autoDownloadUpdates);
|
|
1461
|
+
}
|
|
1462
|
+
if (Object.keys(desktopPatch).length > 0 && options.desktopBridge?.setDesktopPrefs) {
|
|
1463
|
+
await options.desktopBridge.setDesktopPrefs(desktopPatch).catch(() => undefined);
|
|
1464
|
+
}
|
|
1465
|
+
if (body.apiKey) {
|
|
1466
|
+
process.env.CODEPULSE_AI_API_KEY = body.apiKey;
|
|
1467
|
+
process.env.CODEPULSE_AI_PROVIDER = body.provider ?? process.env.CODEPULSE_AI_PROVIDER ?? 'gemini';
|
|
1468
|
+
}
|
|
1469
|
+
return {
|
|
1470
|
+
ok: true,
|
|
1471
|
+
language: db.getSetting('ui.language') ?? 'en',
|
|
1472
|
+
theme: db.getSetting('ui.theme') ?? 'obsidian',
|
|
1473
|
+
concurrency: queue.concurrency,
|
|
1474
|
+
autoScanOpenPrsOnPoll: db.getSetting('github.autoScanOpenPrsOnPoll', false) === true,
|
|
1475
|
+
telemetryOptIn: queue.telemetry.isOptedIn()
|
|
1476
|
+
};
|
|
1477
|
+
});
|
|
1478
|
+
app.get('/api/telemetry/preview', async () => {
|
|
1479
|
+
const ver = options.appVersion ?? '3.0.0';
|
|
1480
|
+
return {
|
|
1481
|
+
stats: queue.telemetry.getLocalStats(),
|
|
1482
|
+
samplePayload: queue.telemetry.buildSanitizedPayload({
|
|
1483
|
+
eventType: 'app_heartbeat',
|
|
1484
|
+
appVersion: ver
|
|
1485
|
+
})
|
|
1486
|
+
};
|
|
1487
|
+
});
|
|
1488
|
+
app.post('/api/telemetry/flush', async () => {
|
|
1489
|
+
const ver = options.appVersion ?? '3.0.0';
|
|
1490
|
+
return queue.telemetry.recordAndFlush({
|
|
1491
|
+
eventType: 'app_heartbeat',
|
|
1492
|
+
appVersion: ver
|
|
1493
|
+
});
|
|
1494
|
+
});
|
|
1495
|
+
app.get('/api/legal/docs', async () => {
|
|
1496
|
+
const repoRoot = path.resolve(__dirname, '../../..');
|
|
1497
|
+
const readDoc = async (name, fallback) => {
|
|
1498
|
+
try {
|
|
1499
|
+
return await fs.readFile(path.join(repoRoot, name), 'utf8');
|
|
1500
|
+
}
|
|
1501
|
+
catch {
|
|
1502
|
+
return fallback;
|
|
1503
|
+
}
|
|
1504
|
+
};
|
|
1505
|
+
const [termsMd, privacyMd, licenseTxt] = await Promise.all([
|
|
1506
|
+
readDoc('TERMS.md', '# Terms of Service\nAGPL-3.0-only core / MIT SDK & templates. Visit https://github.com/ymorningstar/CodePulse/blob/main/TERMS.md'),
|
|
1507
|
+
readDoc('PRIVACY.md', '# Privacy Policy\nLocal-first BYOK execution. Telemetry is opt-in only and never collects code or keys. Visit https://github.com/ymorningstar/CodePulse/blob/main/PRIVACY.md'),
|
|
1508
|
+
readDoc('LICENSE', 'GNU AFFERO GENERAL PUBLIC LICENSE Version 3 (AGPL-3.0-only)')
|
|
1509
|
+
]);
|
|
1510
|
+
return { termsMd, privacyMd, licenseTxt };
|
|
1511
|
+
});
|
|
1512
|
+
/**
|
|
1513
|
+
* In-App Key Vault: persist Single AI API Key and/or GITHUB_TOKEN locally into `.env`
|
|
1514
|
+
* (userData/.env in Desktop) ONLY — never written to SQLite or git, and strictly masked on GET.
|
|
1515
|
+
*/
|
|
1516
|
+
app.post('/api/settings/secrets', async (request) => {
|
|
1517
|
+
const body = (request.body ?? {});
|
|
1518
|
+
if (body.provider)
|
|
1519
|
+
db.setSetting('ai.provider', body.provider);
|
|
1520
|
+
if (body.model)
|
|
1521
|
+
db.setSetting('ai.model', body.model);
|
|
1522
|
+
if (body.baseUrl !== undefined)
|
|
1523
|
+
db.setSetting('ai.baseUrl', body.baseUrl);
|
|
1524
|
+
if (body.gitlabBaseUrl !== undefined)
|
|
1525
|
+
db.setSetting('gitHosting.gitlabBaseUrl', body.gitlabBaseUrl);
|
|
1526
|
+
const activeProvider = body.provider ?? db.getSetting('ai.provider') ?? process.env.CODEPULSE_AI_PROVIDER ?? 'gemini';
|
|
1527
|
+
const envUpdates = {};
|
|
1528
|
+
if (body.provider)
|
|
1529
|
+
envUpdates.CODEPULSE_AI_PROVIDER = body.provider;
|
|
1530
|
+
if (body.model)
|
|
1531
|
+
envUpdates.CODEPULSE_AI_MODEL = body.model;
|
|
1532
|
+
if (body.baseUrl !== undefined && body.baseUrl !== '')
|
|
1533
|
+
envUpdates.CODEPULSE_AI_BASE_URL = body.baseUrl;
|
|
1534
|
+
if (body.apiKey && body.apiKey.trim()) {
|
|
1535
|
+
const trimmedKey = body.apiKey.trim();
|
|
1536
|
+
const providerKeyEnv = {
|
|
1537
|
+
gemini: 'GEMINI_API_KEY',
|
|
1538
|
+
openai: 'OPENAI_API_KEY',
|
|
1539
|
+
anthropic: 'ANTHROPIC_API_KEY',
|
|
1540
|
+
openrouter: 'OPENROUTER_API_KEY',
|
|
1541
|
+
ollama: 'CODEPULSE_AI_API_KEY',
|
|
1542
|
+
'openai-compatible': 'CODEPULSE_AI_API_KEY'
|
|
1543
|
+
};
|
|
1544
|
+
envUpdates[providerKeyEnv[activeProvider]] = trimmedKey;
|
|
1545
|
+
envUpdates.CODEPULSE_AI_API_KEY = trimmedKey;
|
|
1546
|
+
}
|
|
1547
|
+
if (body.githubToken && body.githubToken.trim()) {
|
|
1548
|
+
envUpdates.GITHUB_TOKEN = body.githubToken.trim();
|
|
1549
|
+
}
|
|
1550
|
+
if (body.gitlabToken && body.gitlabToken.trim()) {
|
|
1551
|
+
envUpdates.GITLAB_TOKEN = body.gitlabToken.trim();
|
|
1552
|
+
}
|
|
1553
|
+
if (body.gitlabBaseUrl && body.gitlabBaseUrl.trim()) {
|
|
1554
|
+
envUpdates.GITLAB_BASE_URL = body.gitlabBaseUrl.trim();
|
|
1555
|
+
}
|
|
1556
|
+
if (body.bitbucketToken && body.bitbucketToken.trim()) {
|
|
1557
|
+
envUpdates.BITBUCKET_TOKEN = body.bitbucketToken.trim();
|
|
1558
|
+
}
|
|
1559
|
+
if (body.bitbucketUsername && body.bitbucketUsername.trim()) {
|
|
1560
|
+
envUpdates.BITBUCKET_USERNAME = body.bitbucketUsername.trim();
|
|
1561
|
+
}
|
|
1562
|
+
if (Object.keys(envUpdates).length > 0) {
|
|
1563
|
+
const cleanUpdates = {};
|
|
1564
|
+
for (const [k, v] of Object.entries(envUpdates)) {
|
|
1565
|
+
if (v !== undefined) {
|
|
1566
|
+
cleanUpdates[k] = v;
|
|
1567
|
+
process.env[k] = v;
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
if (options.secretVault) {
|
|
1571
|
+
await options.secretVault.saveSecrets(cleanUpdates);
|
|
1572
|
+
}
|
|
1573
|
+
else {
|
|
1574
|
+
await persistEnvVariables(envPath, cleanUpdates);
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
if (body.githubToken) {
|
|
1578
|
+
void refreshPoller().catch(() => undefined);
|
|
1579
|
+
}
|
|
1580
|
+
return {
|
|
1581
|
+
ok: true,
|
|
1582
|
+
hasApiKey: Boolean(process.env.CODEPULSE_AI_API_KEY || process.env.GEMINI_API_KEY || process.env.OPENAI_API_KEY || process.env.ANTHROPIC_API_KEY || process.env.OPENROUTER_API_KEY),
|
|
1583
|
+
hasGithubToken: Boolean(process.env.GITHUB_TOKEN),
|
|
1584
|
+
pollerActive: Boolean(activePoller)
|
|
1585
|
+
};
|
|
1586
|
+
});
|
|
1587
|
+
app.get('/api/settings/models', async () => {
|
|
1588
|
+
return { models: CURATED_AI_MODELS };
|
|
1589
|
+
});
|
|
1590
|
+
app.post('/api/settings/test-ai', async (request) => {
|
|
1591
|
+
const body = (request.body ?? {});
|
|
1592
|
+
const cfg = resolveAiConfigFromEnv({
|
|
1593
|
+
provider: body.provider ?? db.getSetting('ai.provider'),
|
|
1594
|
+
model: body.model || db.getSetting('ai.model'),
|
|
1595
|
+
baseUrl: body.baseUrl || db.getSetting('ai.baseUrl'),
|
|
1596
|
+
apiKey: body.apiKey || undefined,
|
|
1597
|
+
fetchImpl: options.fetchImpl
|
|
1598
|
+
});
|
|
1599
|
+
const client = new ByokAiClient(cfg);
|
|
1600
|
+
if (!client.isConfigured()) {
|
|
1601
|
+
return { ok: false, provider: cfg.provider, model: cfg.model, error: 'No API key configured for this provider.' };
|
|
1602
|
+
}
|
|
1603
|
+
const start = performance.now();
|
|
1604
|
+
try {
|
|
1605
|
+
await client.complete({
|
|
1606
|
+
systemPrompt: 'Reply with OK.',
|
|
1607
|
+
userPrompt: 'Ping',
|
|
1608
|
+
maxOutputTokens: 16,
|
|
1609
|
+
temperature: 0
|
|
1610
|
+
});
|
|
1611
|
+
return {
|
|
1612
|
+
ok: true,
|
|
1613
|
+
provider: cfg.provider,
|
|
1614
|
+
model: cfg.model,
|
|
1615
|
+
latencyMs: Math.round(performance.now() - start)
|
|
1616
|
+
};
|
|
1617
|
+
}
|
|
1618
|
+
catch (err) {
|
|
1619
|
+
return {
|
|
1620
|
+
ok: false,
|
|
1621
|
+
provider: cfg.provider,
|
|
1622
|
+
model: cfg.model,
|
|
1623
|
+
error: maskSecrets(err.message)
|
|
1624
|
+
};
|
|
1625
|
+
}
|
|
1626
|
+
});
|
|
1627
|
+
// --- GitHub Device Flow OAuth + Repo Picker + Open PRs ---
|
|
1628
|
+
const deviceSessions = new Map();
|
|
1629
|
+
app.post('/api/github/device/start', async (request, reply) => {
|
|
1630
|
+
const body = (request.body ?? {});
|
|
1631
|
+
try {
|
|
1632
|
+
const started = await startGitHubDeviceFlow({
|
|
1633
|
+
clientId: body.clientId,
|
|
1634
|
+
scope: body.scope,
|
|
1635
|
+
fetchImpl: options.fetchImpl
|
|
1636
|
+
});
|
|
1637
|
+
const sessionId = crypto.randomUUID();
|
|
1638
|
+
deviceSessions.set(sessionId, { deviceCode: started.deviceCode, interval: started.interval });
|
|
1639
|
+
return {
|
|
1640
|
+
sessionId,
|
|
1641
|
+
userCode: started.userCode,
|
|
1642
|
+
verificationUri: started.verificationUri,
|
|
1643
|
+
expiresIn: started.expiresIn,
|
|
1644
|
+
interval: started.interval
|
|
1645
|
+
};
|
|
1646
|
+
}
|
|
1647
|
+
catch (err) {
|
|
1648
|
+
return reply.code(502).send({ error: err.message });
|
|
1649
|
+
}
|
|
1650
|
+
});
|
|
1651
|
+
app.post('/api/github/device/poll', async (request, reply) => {
|
|
1652
|
+
const body = (request.body ?? {});
|
|
1653
|
+
const session = body.sessionId ? deviceSessions.get(body.sessionId) : undefined;
|
|
1654
|
+
const deviceCode = body.deviceCode ?? session?.deviceCode;
|
|
1655
|
+
if (!deviceCode) {
|
|
1656
|
+
return reply.code(400).send({ error: 'Missing deviceCode or valid sessionId' });
|
|
1657
|
+
}
|
|
1658
|
+
const result = await pollGitHubDeviceFlow({
|
|
1659
|
+
deviceCode,
|
|
1660
|
+
clientId: body.clientId,
|
|
1661
|
+
fetchImpl: options.fetchImpl
|
|
1662
|
+
});
|
|
1663
|
+
if (result.status === 'authorized' && result.accessToken) {
|
|
1664
|
+
if (body.sessionId)
|
|
1665
|
+
deviceSessions.delete(body.sessionId);
|
|
1666
|
+
process.env.GITHUB_TOKEN = result.accessToken;
|
|
1667
|
+
if (options.secretVault) {
|
|
1668
|
+
await options.secretVault.saveSecrets({ GITHUB_TOKEN: result.accessToken });
|
|
1669
|
+
}
|
|
1670
|
+
else {
|
|
1671
|
+
await persistEnvVariables(envPath, { GITHUB_TOKEN: result.accessToken });
|
|
1672
|
+
}
|
|
1673
|
+
// Run poller refresh in background so Device Flow wizard resolves instantly
|
|
1674
|
+
void refreshPoller().catch(() => undefined);
|
|
1675
|
+
return {
|
|
1676
|
+
status: 'authorized',
|
|
1677
|
+
hasGithubToken: true,
|
|
1678
|
+
maskedGithubToken: maskSecretTail(result.accessToken)
|
|
1679
|
+
};
|
|
1680
|
+
}
|
|
1681
|
+
return {
|
|
1682
|
+
status: result.status,
|
|
1683
|
+
interval: result.interval,
|
|
1684
|
+
error: result.error
|
|
1685
|
+
};
|
|
1686
|
+
});
|
|
1687
|
+
app.get('/api/github/repos', async (request, reply) => {
|
|
1688
|
+
const q = request.query;
|
|
1689
|
+
const ghClient = await resolveRepoOctokit();
|
|
1690
|
+
if (!ghClient) {
|
|
1691
|
+
return reply.code(401).send({ error: 'GitHub not signed in. Use Sign in with GitHub (Device Flow), gh CLI, or PAT.' });
|
|
1692
|
+
}
|
|
1693
|
+
try {
|
|
1694
|
+
const repos = await listAccessibleGitHubRepos(ghClient.octokit, Number(q.page ?? 1));
|
|
1695
|
+
return { repos };
|
|
1696
|
+
}
|
|
1697
|
+
catch (err) {
|
|
1698
|
+
return reply.code(502).send({ error: maskSecrets(err.message) });
|
|
1699
|
+
}
|
|
1700
|
+
});
|
|
1701
|
+
app.get('/api/github/repos/:owner/:repo/pulls', async (request, reply) => {
|
|
1702
|
+
const { owner, repo } = request.params;
|
|
1703
|
+
const ghClient = await resolveRepoOctokit();
|
|
1704
|
+
if (!ghClient) {
|
|
1705
|
+
return reply.code(401).send({ error: 'GitHub not signed in.' });
|
|
1706
|
+
}
|
|
1707
|
+
try {
|
|
1708
|
+
const pulls = await listOpenPullRequests(ghClient.octokit, owner, repo);
|
|
1709
|
+
return { pulls };
|
|
1710
|
+
}
|
|
1711
|
+
catch (err) {
|
|
1712
|
+
return reply.code(502).send({ error: maskSecrets(err.message) });
|
|
1713
|
+
}
|
|
1714
|
+
});
|
|
1715
|
+
// --- Desktop Native Controls & In-App Auto-Updater ---
|
|
1716
|
+
const currentVersion = options.appVersion ?? '3.0.0';
|
|
1717
|
+
app.get('/api/app/update-status', async () => {
|
|
1718
|
+
if (options.desktopBridge) {
|
|
1719
|
+
return options.desktopBridge.getUpdateStatus();
|
|
1720
|
+
}
|
|
1721
|
+
return {
|
|
1722
|
+
currentVersion,
|
|
1723
|
+
status: 'up-to-date',
|
|
1724
|
+
isDesktop: false
|
|
1725
|
+
};
|
|
1726
|
+
});
|
|
1727
|
+
app.post('/api/app/update-check', async () => {
|
|
1728
|
+
if (options.desktopBridge) {
|
|
1729
|
+
return options.desktopBridge.checkForUpdates();
|
|
1730
|
+
}
|
|
1731
|
+
return { currentVersion, status: 'up-to-date', isDesktop: false };
|
|
1732
|
+
});
|
|
1733
|
+
app.post('/api/app/update-download', async () => {
|
|
1734
|
+
if (options.desktopBridge) {
|
|
1735
|
+
return options.desktopBridge.downloadUpdate();
|
|
1736
|
+
}
|
|
1737
|
+
return { currentVersion, status: 'up-to-date', isDesktop: false };
|
|
1738
|
+
});
|
|
1739
|
+
app.post('/api/app/update-install', async () => {
|
|
1740
|
+
if (options.desktopBridge) {
|
|
1741
|
+
options.desktopBridge.installUpdateAndRestart();
|
|
1742
|
+
return { ok: true };
|
|
1743
|
+
}
|
|
1744
|
+
return { ok: false, error: 'Restart only supported in Desktop App.' };
|
|
1745
|
+
});
|
|
1746
|
+
app.post('/api/desktop/pick-folder', async () => {
|
|
1747
|
+
if (options.desktopBridge?.pickLocalFolder) {
|
|
1748
|
+
const folder = await options.desktopBridge.pickLocalFolder();
|
|
1749
|
+
return { folder };
|
|
1750
|
+
}
|
|
1751
|
+
return { folder: null };
|
|
1752
|
+
});
|
|
1753
|
+
app.post('/api/github/poll-now', async (request, reply) => {
|
|
1754
|
+
const body = (request.body ?? {});
|
|
1755
|
+
try {
|
|
1756
|
+
const result = await pollNow({ autoEnqueue: body.autoEnqueue });
|
|
1757
|
+
return {
|
|
1758
|
+
ok: true,
|
|
1759
|
+
polledRepos: result.polledRepos,
|
|
1760
|
+
triggersCount: result.triggers.length,
|
|
1761
|
+
triggers: result.triggers,
|
|
1762
|
+
pendingPrs: result.pendingPrs
|
|
1763
|
+
};
|
|
1764
|
+
}
|
|
1765
|
+
catch (err) {
|
|
1766
|
+
return reply.code(400).send({ error: err.message });
|
|
1767
|
+
}
|
|
1768
|
+
});
|
|
1769
|
+
app.get('/api/github/pending-prs', async () => {
|
|
1770
|
+
return { pendingPrs: Array.from(pendingPrNotices.values()) };
|
|
1771
|
+
});
|
|
1772
|
+
app.post('/api/github/pending-prs/review', async (request) => {
|
|
1773
|
+
const body = (request.body ?? {});
|
|
1774
|
+
const selected = body.all
|
|
1775
|
+
? Array.from(pendingPrNotices.values())
|
|
1776
|
+
: body.key && pendingPrNotices.has(body.key)
|
|
1777
|
+
? [pendingPrNotices.get(body.key)]
|
|
1778
|
+
: [];
|
|
1779
|
+
let enqueued = 0;
|
|
1780
|
+
for (const notice of selected) {
|
|
1781
|
+
pendingPrNotices.delete(notice.key);
|
|
1782
|
+
await handlePrEventTrigger({
|
|
1783
|
+
type: 'pull_request',
|
|
1784
|
+
owner: notice.owner,
|
|
1785
|
+
repo: notice.repo,
|
|
1786
|
+
prNumber: notice.prNumber,
|
|
1787
|
+
headSha: notice.headSha,
|
|
1788
|
+
baseRef: notice.baseRef,
|
|
1789
|
+
headRef: notice.headRef,
|
|
1790
|
+
prTitle: notice.title,
|
|
1791
|
+
installationId: notice.installationId
|
|
1792
|
+
}, { source: 'manual' });
|
|
1793
|
+
enqueued++;
|
|
1794
|
+
}
|
|
1795
|
+
broadcastWsPayload({
|
|
1796
|
+
type: 'pr_updates_detected',
|
|
1797
|
+
pendingPrs: Array.from(pendingPrNotices.values())
|
|
1798
|
+
});
|
|
1799
|
+
return { ok: true, enqueued, pendingPrs: Array.from(pendingPrNotices.values()) };
|
|
1800
|
+
});
|
|
1801
|
+
app.post('/api/github/pending-prs/dismiss', async (request) => {
|
|
1802
|
+
const body = (request.body ?? {});
|
|
1803
|
+
if (body.all || !body.key) {
|
|
1804
|
+
pendingPrNotices.clear();
|
|
1805
|
+
}
|
|
1806
|
+
else {
|
|
1807
|
+
pendingPrNotices.delete(body.key);
|
|
1808
|
+
}
|
|
1809
|
+
broadcastWsPayload({
|
|
1810
|
+
type: 'pr_updates_detected',
|
|
1811
|
+
pendingPrs: Array.from(pendingPrNotices.values())
|
|
1812
|
+
});
|
|
1813
|
+
return { ok: true, pendingPrs: Array.from(pendingPrNotices.values()) };
|
|
1814
|
+
});
|
|
1815
|
+
// --- Natural Language Commander (Arabic + English) ---
|
|
1816
|
+
app.post('/api/chat', async (request, reply) => {
|
|
1817
|
+
const body = (request.body ?? {});
|
|
1818
|
+
const msg = (body.message ?? '').trim();
|
|
1819
|
+
if (!msg)
|
|
1820
|
+
return reply.code(400).send({ error: 'Message is required' });
|
|
1821
|
+
const isArabic = /[\u0600-\u06FF]/.test(msg);
|
|
1822
|
+
const repo = body.repoId ? db.getRepo(body.repoId) : db.listRepos()[0] ?? null;
|
|
1823
|
+
// Detect folder export request in text (e.g. "save to reports" or "في مجلد reports")
|
|
1824
|
+
const folderMatch = /(?:in|to|مجلد|folder)\s+([A-Za-z0-9_./\\-]+)/i.exec(msg);
|
|
1825
|
+
const exportDir = folderMatch?.[1];
|
|
1826
|
+
const saveOnce = Boolean(exportDir || /(?:save|export|احفظ|تقرير)/i.test(msg));
|
|
1827
|
+
if (/(?:full\s*spectrum|comprehensive|all\s*engines|فحص\s*شامل|تدقيق\s*شامل)/i.test(msg) && repo?.localPath) {
|
|
1828
|
+
const job = queue.enqueueScan({
|
|
1829
|
+
repoId: repo.id,
|
|
1830
|
+
repoPath: repo.localPath,
|
|
1831
|
+
target: /main/i.test(msg) ? 'main_full' : 'directory',
|
|
1832
|
+
mode: 'comprehensive',
|
|
1833
|
+
saveMarkdownOnce: saveOnce,
|
|
1834
|
+
exportDir
|
|
1835
|
+
});
|
|
1836
|
+
return {
|
|
1837
|
+
action: 'started_job',
|
|
1838
|
+
job,
|
|
1839
|
+
reply: isArabic
|
|
1840
|
+
? `تم إطلاق التدقيق الشامل الكامل (\`comprehensive\`) للمشروع (رقم المهمة: \`${job.id}\`).`
|
|
1841
|
+
: `Started Full Spectrum Audit (\`comprehensive\`) across all engines (job \`${job.id}\`).`
|
|
1842
|
+
};
|
|
1843
|
+
}
|
|
1844
|
+
if ((/(?:scan|audit|برانش)\s+main/i.test(msg) || (msg.includes('افحص') && /\bmain\b/i.test(msg))) &&
|
|
1845
|
+
repo?.localPath) {
|
|
1846
|
+
const job = queue.enqueueScan({
|
|
1847
|
+
repoId: repo.id,
|
|
1848
|
+
repoPath: repo.localPath,
|
|
1849
|
+
target: 'main_full',
|
|
1850
|
+
mode: /(?:security|ثغرات|مالي|finance)/i.test(msg) ? 'security' : 'deep',
|
|
1851
|
+
saveMarkdownOnce: saveOnce,
|
|
1852
|
+
exportDir
|
|
1853
|
+
});
|
|
1854
|
+
return {
|
|
1855
|
+
action: 'started_job',
|
|
1856
|
+
job,
|
|
1857
|
+
reply: isArabic
|
|
1858
|
+
? `تم تشغيل فحص كامل لفرع \`main\` (${job.mode}) في الطابور المتوازي (رقم المهمة: \`${job.id}\`)${exportDir ? ` وسيتم حفظ التقرير في \`${exportDir}\`` : ''}.`
|
|
1859
|
+
: `Started full \`main\` branch scan (${job.mode}) in the parallel queue (job \`${job.id}\`)${exportDir ? ` — report will auto-save to \`${exportDir}\`` : ''}.`
|
|
1860
|
+
};
|
|
1861
|
+
}
|
|
1862
|
+
if ((/(?:revalidate|verify fix|حلت|تم حل)/i.test(msg) || (msg.includes('تحقق') && msg.includes('تعديلات'))) &&
|
|
1863
|
+
repo?.localPath) {
|
|
1864
|
+
const lastJob = db.listJobs(10).find((j) => j.repoId === repo.id && j.status === 'completed');
|
|
1865
|
+
const res = await revalidateFindings(db, {
|
|
1866
|
+
repoId: repo.id,
|
|
1867
|
+
repoPath: repo.localPath,
|
|
1868
|
+
target: 'local_uncommitted',
|
|
1869
|
+
baseScanId: lastJob?.id
|
|
1870
|
+
});
|
|
1871
|
+
return {
|
|
1872
|
+
action: 'revalidated',
|
|
1873
|
+
result: res,
|
|
1874
|
+
reply: isArabic
|
|
1875
|
+
? `تمت إعادة التحقق: ${res.verifiedFixedIds.length} مشكلة تم تأكيد حلها (\`verified_fixed\`)، و ${res.stillOpenIds.length} لا تزال مفتوحة، و ${res.newRegressions.length} انحدارات جديدة.`
|
|
1876
|
+
: `Revalidation complete: ${res.verifiedFixedIds.length} verified fixed, ${res.stillOpenIds.length} still open, ${res.newRegressions.length} new regressions.`
|
|
1877
|
+
};
|
|
1878
|
+
}
|
|
1879
|
+
if (/(?:review|debate|adversarial|افحص|راجع)/i.test(msg) && repo?.localPath) {
|
|
1880
|
+
const mode = /adversarial|هجومي/i.test(msg)
|
|
1881
|
+
? 'adversarial'
|
|
1882
|
+
: /security|أمني|ثغرات/i.test(msg)
|
|
1883
|
+
? 'security'
|
|
1884
|
+
: 'debate';
|
|
1885
|
+
const job = queue.enqueueScan({
|
|
1886
|
+
repoId: repo.id,
|
|
1887
|
+
repoPath: repo.localPath,
|
|
1888
|
+
target: 'local_uncommitted',
|
|
1889
|
+
mode,
|
|
1890
|
+
saveMarkdownOnce: saveOnce,
|
|
1891
|
+
exportDir
|
|
1892
|
+
});
|
|
1893
|
+
return {
|
|
1894
|
+
action: 'started_job',
|
|
1895
|
+
job,
|
|
1896
|
+
reply: isArabic
|
|
1897
|
+
? `تم بدء المراجعة بنمط \`${mode}\` (مهمة \`${job.id}\`).`
|
|
1898
|
+
: `Started \`${mode}\` review (job \`${job.id}\`).`
|
|
1899
|
+
};
|
|
1900
|
+
}
|
|
1901
|
+
const aiClient = new ByokAiClient(resolveAiConfigFromEnv({
|
|
1902
|
+
privacyFirewall: db.getSetting('ai.privacyFirewall', true) !== false
|
|
1903
|
+
}));
|
|
1904
|
+
const answer = await answerNaturalLanguagePrQuestion({
|
|
1905
|
+
question: maskSecrets(msg),
|
|
1906
|
+
astNodes: repo ? db.getAstNodesForRepo(repo.id) : [],
|
|
1907
|
+
aiClient
|
|
1908
|
+
});
|
|
1909
|
+
return { action: 'answered', reply: answer };
|
|
1910
|
+
});
|
|
1911
|
+
// Live SSE streaming endpoint for Natural Language Chat
|
|
1912
|
+
app.post('/api/chat/stream', async (request, reply) => {
|
|
1913
|
+
const body = (request.body ?? {});
|
|
1914
|
+
const msg = (body.message ?? '').trim();
|
|
1915
|
+
if (!msg)
|
|
1916
|
+
return reply.code(400).send({ error: 'Message is required' });
|
|
1917
|
+
reply.raw.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
|
|
1918
|
+
reply.raw.setHeader('Cache-Control', 'no-cache, no-transform');
|
|
1919
|
+
reply.raw.setHeader('Connection', 'keep-alive');
|
|
1920
|
+
reply.raw.flushHeaders?.();
|
|
1921
|
+
const write = (obj) => {
|
|
1922
|
+
if (!reply.raw.writableEnded)
|
|
1923
|
+
reply.raw.write(`data: ${JSON.stringify(obj)}\n\n`);
|
|
1924
|
+
};
|
|
1925
|
+
const repo = body.repoId ? db.getRepo(body.repoId) : db.listRepos()[0] ?? null;
|
|
1926
|
+
const aiCfg = resolveAiConfigFromEnv({
|
|
1927
|
+
provider: db.getSetting('ai.provider'),
|
|
1928
|
+
model: db.getSetting('ai.model'),
|
|
1929
|
+
privacyFirewall: db.getSetting('ai.privacyFirewall', true) !== false
|
|
1930
|
+
});
|
|
1931
|
+
const aiClient = new ByokAiClient(aiCfg);
|
|
1932
|
+
if (aiClient.isConfigured()) {
|
|
1933
|
+
const nodes = repo ? db.getAstNodesForRepo(repo.id).slice(0, 60) : [];
|
|
1934
|
+
const res = await aiClient.completeStream({
|
|
1935
|
+
systemPrompt: 'You are CodePulse, an interactive local-first AI code security & architecture assistant.',
|
|
1936
|
+
userPrompt: `Question: ${maskSecrets(msg)}\n\nKnown Symbols:\n${nodes.map((n) => `${n.file}:${n.lineStart} ${n.kind} ${n.name}`).join('\n')}`,
|
|
1937
|
+
temperature: 0.2
|
|
1938
|
+
}, (chunk) => write({ type: 'chunk', delta: chunk }));
|
|
1939
|
+
write({ type: 'done', reply: res.text, firewall: aiClient.getFirewallStats() });
|
|
1940
|
+
}
|
|
1941
|
+
else {
|
|
1942
|
+
const fallback = await answerNaturalLanguagePrQuestion({
|
|
1943
|
+
question: maskSecrets(msg),
|
|
1944
|
+
astNodes: repo ? db.getAstNodesForRepo(repo.id) : [],
|
|
1945
|
+
aiClient
|
|
1946
|
+
});
|
|
1947
|
+
write({ type: 'chunk', delta: fallback });
|
|
1948
|
+
write({ type: 'done', reply: fallback });
|
|
1949
|
+
}
|
|
1950
|
+
reply.raw.end();
|
|
1951
|
+
return reply;
|
|
1952
|
+
});
|
|
1953
|
+
// --- Universal Agent Bridge ---
|
|
1954
|
+
app.get('/api/bridge/detect', async (request, reply) => {
|
|
1955
|
+
const q = request.query;
|
|
1956
|
+
let safeWs;
|
|
1957
|
+
try {
|
|
1958
|
+
safeWs = resolveHttpWorkspacePath(q.workspacePath) ?? process.cwd();
|
|
1959
|
+
}
|
|
1960
|
+
catch (err) {
|
|
1961
|
+
return reply.code(403).send({ error: err.message });
|
|
1962
|
+
}
|
|
1963
|
+
const platforms = await detectInstalledPlatforms(safeWs);
|
|
1964
|
+
return { platforms };
|
|
1965
|
+
});
|
|
1966
|
+
app.post('/api/mcp/health', async () => {
|
|
1967
|
+
return {
|
|
1968
|
+
ok: true,
|
|
1969
|
+
endpoint: '/mcp',
|
|
1970
|
+
transport: 'streamable-http',
|
|
1971
|
+
toolsCount: 11,
|
|
1972
|
+
authProtected: Boolean(authToken),
|
|
1973
|
+
activeJobs: queue.getActiveCount()
|
|
1974
|
+
};
|
|
1975
|
+
});
|
|
1976
|
+
app.post('/api/bridge/install', async (request, reply) => {
|
|
1977
|
+
const body = (request.body ?? {});
|
|
1978
|
+
let safeWs;
|
|
1979
|
+
try {
|
|
1980
|
+
safeWs = resolveHttpWorkspacePath(body.workspacePath);
|
|
1981
|
+
}
|
|
1982
|
+
catch (err) {
|
|
1983
|
+
return reply.code(403).send({ error: err.message });
|
|
1984
|
+
}
|
|
1985
|
+
const results = await installAgentBridges({
|
|
1986
|
+
...body,
|
|
1987
|
+
...(safeWs ? { workspacePath: safeWs } : {})
|
|
1988
|
+
});
|
|
1989
|
+
return { results };
|
|
1990
|
+
});
|
|
1991
|
+
// --- GitHub App 1-Click Manifest Setup & Webhook Receiver ---
|
|
1992
|
+
app.get('/api/github/app-manifest', async (request, reply) => {
|
|
1993
|
+
const q = request.query;
|
|
1994
|
+
const reqProto = request.headers['x-forwarded-proto'] || 'http';
|
|
1995
|
+
const reqHost = request.headers['x-forwarded-host'] || request.headers.host || `${host}:${port}`;
|
|
1996
|
+
const baseUrl = q.baseUrl ?? `${reqProto}://${reqHost}`;
|
|
1997
|
+
if (q.format === 'json') {
|
|
1998
|
+
return buildGitHubAppManifest({
|
|
1999
|
+
baseUrl,
|
|
2000
|
+
org: q.org,
|
|
2001
|
+
appName: q.appName,
|
|
2002
|
+
webhookUrl: q.webhookUrl
|
|
2003
|
+
});
|
|
2004
|
+
}
|
|
2005
|
+
const html = renderGitHubManifestRedirectHtml({
|
|
2006
|
+
baseUrl,
|
|
2007
|
+
org: q.org,
|
|
2008
|
+
appName: q.appName,
|
|
2009
|
+
webhookUrl: q.webhookUrl
|
|
2010
|
+
});
|
|
2011
|
+
return reply.type('text/html; charset=utf-8').send(html);
|
|
2012
|
+
});
|
|
2013
|
+
app.get('/api/github/app-callback', async (request, reply) => {
|
|
2014
|
+
const q = request.query;
|
|
2015
|
+
if (!q.code) {
|
|
2016
|
+
return reply.code(400).send({ error: 'Missing ?code parameter from GitHub App Manifest callback.' });
|
|
2017
|
+
}
|
|
2018
|
+
try {
|
|
2019
|
+
const creds = await exchangeGitHubAppManifestCode(q.code, options.fetchImpl);
|
|
2020
|
+
await persistGitHubAppCredentialsToEnv(envPath, creds);
|
|
2021
|
+
const maskedId = `${creds.appId}`;
|
|
2022
|
+
return reply.type('text/html; charset=utf-8').send(`<!DOCTYPE html>
|
|
2023
|
+
<html lang="en"><body style="background:#0b0f17;color:#e6edf7;font-family:system-ui,sans-serif;padding:40px;">
|
|
2024
|
+
<h2>CodePulse GitHub App Connected</h2>
|
|
2025
|
+
<p>App ID: <code>${maskedId}</code>${creds.slug ? ` (<code>${creds.slug}[bot]</code>)` : ''}</p>
|
|
2026
|
+
<p>Credentials saved securely to local <code>.env</code> (masked in UI, never committed).</p>
|
|
2027
|
+
<p><a href="/" style="color:#60a5fa;">Return to CodePulse Cockpit</a></p>
|
|
2028
|
+
</body></html>`);
|
|
2029
|
+
}
|
|
2030
|
+
catch (err) {
|
|
2031
|
+
return reply.code(502).send({ error: err.message });
|
|
2032
|
+
}
|
|
2033
|
+
});
|
|
2034
|
+
app.post('/api/webhooks/github', async (request, reply) => {
|
|
2035
|
+
const secret = process.env.GITHUB_WEBHOOK_SECRET;
|
|
2036
|
+
if (!secret)
|
|
2037
|
+
return reply.code(400).send({ error: 'GITHUB_WEBHOOK_SECRET not configured' });
|
|
2038
|
+
const rawPayload = request.rawBody ?? JSON.stringify(request.body ?? {});
|
|
2039
|
+
const signatureHeader = request.headers['x-hub-signature-256'];
|
|
2040
|
+
if (!verifyGitHubWebhookSignature(secret, rawPayload, signatureHeader)) {
|
|
2041
|
+
return reply.code(401).send({ error: 'Invalid X-Hub-Signature-256 webhook signature' });
|
|
2042
|
+
}
|
|
2043
|
+
const webhooks = createWebhookRouter(secret, (trigger) => {
|
|
2044
|
+
if (isClosing)
|
|
2045
|
+
return;
|
|
2046
|
+
trackBackgroundTask(handlePrEventTrigger(trigger, { source: 'webhook' }).catch(() => undefined));
|
|
2047
|
+
});
|
|
2048
|
+
await webhooks.verifyAndReceive({
|
|
2049
|
+
id: String(request.headers['x-github-delivery'] ?? ''),
|
|
2050
|
+
name: String(request.headers['x-github-event'] ?? ''),
|
|
2051
|
+
signature: signatureHeader ?? '',
|
|
2052
|
+
payload: rawPayload
|
|
2053
|
+
});
|
|
2054
|
+
return { ok: true };
|
|
2055
|
+
});
|
|
2056
|
+
await refreshPoller();
|
|
2057
|
+
await app.listen({ port, host });
|
|
2058
|
+
const address = app.server.address();
|
|
2059
|
+
const actualPort = typeof address === 'object' && address ? address.port : port;
|
|
2060
|
+
const url = `http://${host === '0.0.0.0' ? '127.0.0.1' : host}:${actualPort}`;
|
|
2061
|
+
return {
|
|
2062
|
+
app,
|
|
2063
|
+
db,
|
|
2064
|
+
queue,
|
|
2065
|
+
url,
|
|
2066
|
+
pollNow,
|
|
2067
|
+
close: async () => {
|
|
2068
|
+
isClosing = true;
|
|
2069
|
+
activePoller?.stop();
|
|
2070
|
+
activePoller = null;
|
|
2071
|
+
await Promise.allSettled(Array.from(inFlightTriggers));
|
|
2072
|
+
await app.close();
|
|
2073
|
+
db.close();
|
|
2074
|
+
}
|
|
2075
|
+
};
|
|
2076
|
+
}
|
|
2077
|
+
//# sourceMappingURL=server.js.map
|