perfai-cloud-mcp 0.5.2 β†’ 0.7.2

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.
@@ -1,8 +1,10 @@
1
1
  import { getApp, getTask, getVulnerabilities } from "../../client/apiClient.js";
2
- import { isForbiddenError } from "../../client/errors.js";
2
+ import { findingsFailureText, isForbiddenError } from "../../client/errors.js";
3
3
  import { APP_NAME_PROPERTY, appName, resolveApp } from "../../utils/appResolver.js";
4
4
  import { formatVulnerabilityList } from "../../utils/formatters.js";
5
+ import { isLocked, lockedLine } from "../../utils/promptBuilder.js";
5
6
  import { describeStatus, stillOnboardingMessage } from "../../utils/runState.js";
7
+ import { issuesFirstLine, testRunningLine } from "../../utils/testInfo.js";
6
8
  export const DISMISSED_STAFF_ONLY = "πŸ”’ Dismissed findings are not listable on this account. To undo a dismissal, call reopen_vulnerability " +
7
9
  "with the ID from the dismiss reply.";
8
10
  const STATUS_FILTERS = {
@@ -45,6 +47,21 @@ async function isTestRunning(auth, appId) {
45
47
  return false;
46
48
  }
47
49
  }
50
+ async function runInProgress(auth, appId) {
51
+ try {
52
+ const result = await getVulnerabilities(auth, appId, { pageSize: 1 });
53
+ return result.status === "RUN_IN_PROGRESS" ? result : null;
54
+ }
55
+ catch (error) {
56
+ console.error(`Findings lookup failed for onboarding app ${appId}:`, error instanceof Error ? error.message : String(error));
57
+ return null;
58
+ }
59
+ }
60
+ function lockedCountOf(result, lockedOnPage) {
61
+ if (typeof result.lockedCount === "number")
62
+ return result.lockedCount;
63
+ return result.data.length >= result.total ? lockedOnPage : 0;
64
+ }
48
65
  export async function handleGetVulnerabilities(auth, args) {
49
66
  try {
50
67
  const resolved = await resolveApp(auth, args);
@@ -55,14 +72,13 @@ export async function handleGetVulnerabilities(auth, args) {
55
72
  const name = appName(app);
56
73
  const view = describeStatus(app.registrationStatus, app);
57
74
  if (view.outcome === "pending") {
58
- return { content: [{ type: "text", text: stillOnboardingMessage(name) }] };
75
+ const running = await runInProgress(auth, appId);
76
+ const text = running ? testRunningLine(running.lastRunCompletedAt ?? null) : stillOnboardingMessage(name);
77
+ return { content: [{ type: "text", text }] };
59
78
  }
60
79
  const notes = [];
61
80
  if (view.outcome === "needs_input")
62
81
  notes.push(`⏸️ ${name}: ${view.message}`);
63
- if (await isTestRunning(auth, appId)) {
64
- notes.push(`⏳ A security test is still running for ${name} β€” these are the issues found so far. Check again later.`);
65
- }
66
82
  const status = String(args?.status ?? "open").toLowerCase();
67
83
  const result = await getVulnerabilities(auth, appId, {
68
84
  ...(STATUS_FILTERS[status] ?? STATUS_FILTERS.open),
@@ -70,24 +86,48 @@ export async function handleGetVulnerabilities(auth, args) {
70
86
  pageSize: args?.pageSize,
71
87
  search: args?.search,
72
88
  });
73
- auth.cacheVulnerabilities(appId, result.data);
89
+ if (result.status === "RUN_IN_PROGRESS") {
90
+ const lastCompleted = "lastRunCompletedAt" in result ? (result.lastRunCompletedAt ?? null) : auth.lastTestOf(appId);
91
+ return { content: [{ type: "text", text: testRunningLine(lastCompleted) }] };
92
+ }
93
+ if (result.status === "NO_RUNS") {
94
+ auth.rememberLastTest(appId, null);
95
+ return { content: [{ type: "text", text: "No completed test yet." }] };
96
+ }
97
+ if (typeof result.lastRunCompletedAt === "string")
98
+ auth.rememberLastTest(appId, result.lastRunCompletedAt);
74
99
  const isOpenView = !(status in STATUS_FILTERS) || status === "open";
75
- const list = result.data.length === 0 && !isOpenView
76
- ? `No ${status} findings for ${name}.`
77
- : formatVulnerabilityList(result.data, result.total, result.page, result.pageSize);
100
+ const shown = result.data.filter((v) => !isLocked(v));
101
+ const lockedOnPage = result.data.length - shown.length;
102
+ const lockedTotal = isOpenView && !args?.search ? lockedCountOf(result, lockedOnPage) : lockedOnPage;
103
+ if (lockedOnPage > 0)
104
+ console.error(`get_vulnerabilities: app=${appId} ${lockedOnPage} locked row(s) left out, lockedCount=${result.lockedCount ?? "missing"}`);
105
+ auth.cacheVulnerabilities(appId, shown);
106
+ const firstLine = (await isTestRunning(auth, appId))
107
+ ? testRunningLine(typeof result.lastRunCompletedAt === "string" ? result.lastRunCompletedAt : auth.lastTestOf(appId))
108
+ : issuesFirstLine(result, isOpenView && !args?.search);
109
+ if (firstLine)
110
+ notes.unshift(firstLine);
111
+ const list = shown.length === 0 && lockedOnPage > 0
112
+ ? null
113
+ : shown.length === 0 && !isOpenView
114
+ ? `No ${status} findings for ${name}.`
115
+ : formatVulnerabilityList(shown, Math.max(shown.length, result.total - lockedTotal), result.page, result.pageSize);
116
+ const locked = isOpenView && !args?.search && lockedTotal > 0 ? [lockedLine(lockedTotal)] : [];
78
117
  const dismissedCount = result.dismissedCount;
79
118
  const hidden = isOpenView && typeof dismissedCount === "number" && dismissedCount > 0
80
119
  ? [`πŸ™ˆ ${dismissedCount} dismissed finding${dismissedCount === 1 ? "" : "s"} not shown. ` +
81
120
  "reopen_vulnerability with a finding's ID brings it back."]
82
121
  : [];
83
- return { content: [{ type: "text", text: [...notes, list, ...hidden].join("\n\n") }] };
122
+ const body = [...notes, ...(list ? [list] : []), ...locked, ...hidden];
123
+ return { content: [{ type: "text", text: body.join("\n\n") }] };
84
124
  }
85
125
  catch (error) {
86
126
  if (String(args?.status ?? "").toLowerCase() === "dismissed" && isForbiddenError(error)) {
87
127
  return { content: [{ type: "text", text: DISMISSED_STAFF_ONLY }] };
88
128
  }
89
129
  return {
90
- content: [{ type: "text", text: `❌ Failed to fetch vulnerabilities: ${error instanceof Error ? error.message : String(error)}` }],
130
+ content: [{ type: "text", text: findingsFailureText(error) }],
91
131
  };
92
132
  }
93
133
  }
@@ -2,6 +2,7 @@ import { registerApp, getApp } from "../../client/apiClient.js";
2
2
  import { ApiError } from "../../client/errors.js";
3
3
  import { appName } from "../../utils/appResolver.js";
4
4
  import { canStartSecurityTest, describeStatus, onboardingStartedMessage, stillOnboardingMessage } from "../../utils/runState.js";
5
+ import { withSchedule } from "../../utils/testInfo.js";
5
6
  export const registerAppTool = {
6
7
  name: "register_app",
7
8
  description: "πŸ“± Register an app by its deployed URL (POST /v1/apps). Perfai onboards it in the background, and " +
@@ -61,7 +62,8 @@ export async function handleRegisterApp(auth, args) {
61
62
  tenantOneCredentials,
62
63
  });
63
64
  auth.setCurrentApp(app.appId, args.appUrl);
64
- return { content: [{ type: "text", text: onboardingStartedMessage(appName({ ...app, appUrl: app.appUrl ?? args.appUrl })) }] };
65
+ const started = onboardingStartedMessage(appName({ ...app, appUrl: app.appUrl ?? args.appUrl }));
66
+ return { content: [{ type: "text", text: withSchedule(started, app.scheduleType) }] };
65
67
  }
66
68
  catch (error) {
67
69
  if (error instanceof ApiError && error.status === 409 && typeof error.data?.appId === "string") {
@@ -1,7 +1,8 @@
1
- import { getApp, registerApp, runSecurityAgent } from "../../client/apiClient.js";
1
+ import { getApp, getVulnerabilities, registerApp, runSecurityAgent } from "../../client/apiClient.js";
2
2
  import { ApiError, isAppNotRegisteredError } from "../../client/errors.js";
3
3
  import { APP_NAME_PROPERTY, appName, resolveApp } from "../../utils/appResolver.js";
4
- import { canStartSecurityTest, describeStatus, onboardingStartedMessage, PARTIAL_FINDINGS_NOTE, stillOnboardingMessage, } from "../../utils/runState.js";
4
+ import { canStartSecurityTest, describeStatus, PARTIAL_FINDINGS_NOTE, stillOnboardingMessage, } from "../../utils/runState.js";
5
+ import { openCount } from "../../utils/testInfo.js";
5
6
  export const runSecurityTestTool = {
6
7
  name: "run_security_test",
7
8
  description: 'πŸš€ "Perfai test": start a security test run (POST /v1/apps/{appId}/security-agent). A full URL that ' +
@@ -39,10 +40,54 @@ function refusedMessage(view) {
39
40
  return (`${view.label}: ${view.message}\n\nPerfai can't start a new security test on this app until its ` +
40
41
  `onboarding finishes β€” resolve what the message above asks, then try again. ${PARTIAL_FINDINGS_NOTE}`);
41
42
  }
43
+ async function lastTestBefore(auth, appId) {
44
+ try {
45
+ const list = await getVulnerabilities(auth, appId, { page: 1, pageSize: 1 });
46
+ if (list.status === "RUN_IN_PROGRESS")
47
+ return { open: null };
48
+ if (list.status === "NO_RUNS") {
49
+ auth.rememberLastTest(appId, null);
50
+ return { open: null };
51
+ }
52
+ if (typeof list.lastRunCompletedAt === "string")
53
+ auth.rememberLastTest(appId, list.lastRunCompletedAt);
54
+ return { open: openCount(list, true) };
55
+ }
56
+ catch (error) {
57
+ console.error(`run_security_test: app=${appId} last-test lookup failed: ${error instanceof Error ? error.message : String(error)}`);
58
+ return { open: null };
59
+ }
60
+ }
61
+ function knownEmail(auth) {
62
+ const email = auth.getAuthenticatedEmail();
63
+ return email && email.includes("@") ? email : undefined;
64
+ }
65
+ export function testStartedMessage(taskId, open) {
66
+ return [
67
+ `Test started β€” ID ${taskId}.`,
68
+ open === null ? null : `Open issues from the last test: ${open}`,
69
+ "Perfai emails the app's owner when it finishes.",
70
+ ]
71
+ .filter(Boolean)
72
+ .join("\n");
73
+ }
74
+ export function settingUpMessage(name, email) {
75
+ return (`Perfai is setting up ${name} and will run its first test automatically. This takes up to 20 minutes.\n` +
76
+ (email ? `You'll get an email at ${email} when the test finishes. ` : "") +
77
+ 'Say "perfai status" to check.');
78
+ }
42
79
  async function registerByUrl(auth, appUrl) {
43
80
  try {
44
81
  const app = await registerApp(auth, { appUrl });
45
82
  auth.setCurrentApp(app.appId, appUrl);
83
+ if (auth.getPlan() === undefined) {
84
+ try {
85
+ await getApp(auth, app.appId);
86
+ }
87
+ catch (error) {
88
+ console.error(`Plan lookup failed for new app ${app.appId}:`, error instanceof Error ? error.message : String(error));
89
+ }
90
+ }
46
91
  return { app, created: true };
47
92
  }
48
93
  catch (error) {
@@ -66,9 +111,8 @@ export async function handleRunSecurityTest(auth, args) {
66
111
  const registered = await registerByUrl(auth, appUrl);
67
112
  if (registered.created) {
68
113
  console.error(`run_security_test: registered ${appUrl} as app=${registered.app.appId}`);
69
- return {
70
- content: [{ type: "text", text: onboardingStartedMessage(appName({ ...registered.app, appUrl: registered.app.appUrl ?? appUrl })) }],
71
- };
114
+ const name = appName({ ...registered.app, appUrl: registered.app.appUrl ?? appUrl });
115
+ return { content: [{ type: "text", text: settingUpMessage(name, knownEmail(auth)) }] };
72
116
  }
73
117
  app = registered.app;
74
118
  }
@@ -82,6 +126,7 @@ export async function handleRunSecurityTest(auth, args) {
82
126
  console.error(`run_security_test: app=${appId} not ready, status=${app.registrationStatus ?? "none"} outcome=${view.outcome}`);
83
127
  return { content: [{ type: "text", text: notReadyMessage(name, view) }] };
84
128
  }
129
+ const lastTest = await lastTestBefore(auth, appId);
85
130
  let task;
86
131
  try {
87
132
  task = await runSecurityAgent(auth, appId);
@@ -95,7 +140,7 @@ export async function handleRunSecurityTest(auth, args) {
95
140
  }
96
141
  auth.setCurrentTask(task.taskId, appId);
97
142
  return {
98
- content: [{ type: "text", text: `πŸš€ Security test started for ${name}. Say perfai issues later to view issues.` }],
143
+ content: [{ type: "text", text: testStartedMessage(task.taskId, lastTest.open) }],
99
144
  };
100
145
  }
101
146
  catch (error) {
@@ -27,93 +27,93 @@ function openBrowser(url) {
27
27
  console.error("Could not open browser:", err.message);
28
28
  });
29
29
  }
30
- const LOGIN_PAGE_HTML = `<!DOCTYPE html>
31
- <html lang="en">
32
- <head>
33
- <meta charset="UTF-8">
34
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
35
- <title>Perfai β€” Login</title>
36
- <style>
37
- * { margin: 0; padding: 0; box-sizing: border-box; }
38
- body {
39
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
40
- background: #f5f5f5;
41
- display: flex; align-items: center; justify-content: center;
42
- min-height: 100vh;
43
- }
44
- .card {
45
- background: #fff; border-radius: 12px; padding: 40px;
46
- box-shadow: 0 4px 24px rgba(0,0,0,0.1); width: 100%; max-width: 400px;
47
- }
48
- .logo { text-align: center; margin-bottom: 24px; }
49
- .logo h1 { font-size: 24px; color: #111; }
50
- .logo p { color: #666; font-size: 14px; margin-top: 4px; }
51
- label { display: block; font-size: 14px; font-weight: 500; color: #333; margin-bottom: 6px; }
52
- input {
53
- width: 100%; padding: 10px 12px; border: 1px solid #ddd; border-radius: 8px;
54
- font-size: 14px; margin-bottom: 16px; outline: none; transition: border-color 0.2s;
55
- }
56
- input:focus { border-color: #111; }
57
- button {
58
- width: 100%; padding: 12px; background: #111; color: #fff; border: none;
59
- border-radius: 8px; font-size: 15px; font-weight: 600; cursor: pointer;
60
- transition: background 0.2s;
61
- }
62
- button:hover { background: #333; }
63
- button:disabled { background: #999; cursor: not-allowed; }
64
- .error { color: #e53e3e; font-size: 13px; margin-bottom: 12px; display: none; }
65
- .success {
66
- text-align: center; color: #38a169; font-size: 16px; font-weight: 600;
67
- display: none; margin-top: 16px;
68
- }
69
- </style>
70
- </head>
71
- <body>
72
- <div class="card">
73
- <div class="logo">
74
- <h1>Perfai</h1>
75
- <p>Sign in with your cloud.perfai.ai account</p>
76
- </div>
77
- <form id="loginForm">
78
- <label for="email">Email</label>
79
- <input type="email" id="email" name="email" placeholder="you@example.com" required autofocus>
80
- <label for="password">Password</label>
81
- <input type="password" id="password" name="password" placeholder="Your password" required>
82
- <div class="error" id="error"></div>
83
- <button type="submit" id="btn">Sign in</button>
84
- </form>
85
- <div class="success" id="success">Authenticated! You can close this tab and return to your AI assistant.</div>
86
- </div>
87
- <script>
88
- document.getElementById('loginForm').addEventListener('submit', async (e) => {
89
- e.preventDefault();
90
- const btn = document.getElementById('btn');
91
- const err = document.getElementById('error');
92
- btn.disabled = true; btn.textContent = 'Signing in...'; err.style.display = 'none';
93
- try {
94
- const res = await fetch('/auth', {
95
- method: 'POST',
96
- headers: { 'Content-Type': 'application/json' },
97
- body: JSON.stringify({
98
- email: document.getElementById('email').value,
99
- password: document.getElementById('password').value,
100
- }),
101
- });
102
- const data = await res.json();
103
- if (data.ok) {
104
- document.getElementById('loginForm').style.display = 'none';
105
- document.getElementById('success').style.display = 'block';
106
- } else {
107
- err.textContent = data.message || 'Login failed'; err.style.display = 'block';
108
- btn.disabled = false; btn.textContent = 'Sign in';
109
- }
110
- } catch (ex) {
111
- err.textContent = 'Connection error'; err.style.display = 'block';
112
- btn.disabled = false; btn.textContent = 'Sign in';
113
- }
114
- });
115
- </script>
116
- </body>
30
+ const LOGIN_PAGE_HTML = `<!DOCTYPE html>
31
+ <html lang="en">
32
+ <head>
33
+ <meta charset="UTF-8">
34
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
35
+ <title>Perfai β€” Login</title>
36
+ <style>
37
+ * { margin: 0; padding: 0; box-sizing: border-box; }
38
+ body {
39
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
40
+ background: #f5f5f5;
41
+ display: flex; align-items: center; justify-content: center;
42
+ min-height: 100vh;
43
+ }
44
+ .card {
45
+ background: #fff; border-radius: 12px; padding: 40px;
46
+ box-shadow: 0 4px 24px rgba(0,0,0,0.1); width: 100%; max-width: 400px;
47
+ }
48
+ .logo { text-align: center; margin-bottom: 24px; }
49
+ .logo h1 { font-size: 24px; color: #111; }
50
+ .logo p { color: #666; font-size: 14px; margin-top: 4px; }
51
+ label { display: block; font-size: 14px; font-weight: 500; color: #333; margin-bottom: 6px; }
52
+ input {
53
+ width: 100%; padding: 10px 12px; border: 1px solid #ddd; border-radius: 8px;
54
+ font-size: 14px; margin-bottom: 16px; outline: none; transition: border-color 0.2s;
55
+ }
56
+ input:focus { border-color: #111; }
57
+ button {
58
+ width: 100%; padding: 12px; background: #111; color: #fff; border: none;
59
+ border-radius: 8px; font-size: 15px; font-weight: 600; cursor: pointer;
60
+ transition: background 0.2s;
61
+ }
62
+ button:hover { background: #333; }
63
+ button:disabled { background: #999; cursor: not-allowed; }
64
+ .error { color: #e53e3e; font-size: 13px; margin-bottom: 12px; display: none; }
65
+ .success {
66
+ text-align: center; color: #38a169; font-size: 16px; font-weight: 600;
67
+ display: none; margin-top: 16px;
68
+ }
69
+ </style>
70
+ </head>
71
+ <body>
72
+ <div class="card">
73
+ <div class="logo">
74
+ <h1>Perfai</h1>
75
+ <p>Sign in with your cloud.perfai.ai account</p>
76
+ </div>
77
+ <form id="loginForm">
78
+ <label for="email">Email</label>
79
+ <input type="email" id="email" name="email" placeholder="you@example.com" required autofocus>
80
+ <label for="password">Password</label>
81
+ <input type="password" id="password" name="password" placeholder="Your password" required>
82
+ <div class="error" id="error"></div>
83
+ <button type="submit" id="btn">Sign in</button>
84
+ </form>
85
+ <div class="success" id="success">Authenticated! You can close this tab and return to your AI assistant.</div>
86
+ </div>
87
+ <script>
88
+ document.getElementById('loginForm').addEventListener('submit', async (e) => {
89
+ e.preventDefault();
90
+ const btn = document.getElementById('btn');
91
+ const err = document.getElementById('error');
92
+ btn.disabled = true; btn.textContent = 'Signing in...'; err.style.display = 'none';
93
+ try {
94
+ const res = await fetch('/auth', {
95
+ method: 'POST',
96
+ headers: { 'Content-Type': 'application/json' },
97
+ body: JSON.stringify({
98
+ email: document.getElementById('email').value,
99
+ password: document.getElementById('password').value,
100
+ }),
101
+ });
102
+ const data = await res.json();
103
+ if (data.ok) {
104
+ document.getElementById('loginForm').style.display = 'none';
105
+ document.getElementById('success').style.display = 'block';
106
+ } else {
107
+ err.textContent = data.message || 'Login failed'; err.style.display = 'block';
108
+ btn.disabled = false; btn.textContent = 'Sign in';
109
+ }
110
+ } catch (ex) {
111
+ err.textContent = 'Connection error'; err.style.display = 'block';
112
+ btn.disabled = false; btn.textContent = 'Sign in';
113
+ }
114
+ });
115
+ </script>
116
+ </body>
117
117
  </html>`;
118
118
  let activeBrowserServer = null;
119
119
  let browserLoginPort = null;
@@ -0,0 +1,8 @@
1
+ export function clientLabel(info) {
2
+ const clean = (value, max) => typeof value === "string" ? value.replace(/[^A-Za-z0-9 ._@/+-]/g, "").trim().slice(0, max) : "";
3
+ const name = clean(info?.name, 60);
4
+ if (!name)
5
+ return "unknown";
6
+ const version = clean(info?.version, 20);
7
+ return version ? `${name} ${version}` : name;
8
+ }
@@ -12,6 +12,12 @@ function severityRank(vuln) {
12
12
  export function isOpen(vuln) {
13
13
  return !vuln.isFixed && !vuln.fixClaimed && !vuln.isDismissed;
14
14
  }
15
+ export function isLocked(vuln) {
16
+ return vuln.locked === true;
17
+ }
18
+ export function lockedLine(count) {
19
+ return `+${count} more open issues are hidden on the free plan.`;
20
+ }
15
21
  export function sortBySeverity(vulnerabilities) {
16
22
  return [...vulnerabilities].sort((a, b) => severityRank(a) - severityRank(b));
17
23
  }
@@ -81,16 +87,16 @@ function getFindingBlock(vuln) {
81
87
  return "```" + FINDING_FENCE + "\n" + lines.join("\n") + "\n```\n";
82
88
  }
83
89
  export function buildFixPrompt(appLabel, vuln) {
84
- return `I need help fixing the following security issue found by Perfai in "${sanitize(appLabel)}":
85
-
86
- ${getFindingBlock(vuln)}
87
- ${DATA_NOT_INSTRUCTIONS}
88
-
89
- Please:
90
- 1. Study the existing codebase structure and locate the affected code (the endpoint in the finding above, or the code responsible for it if none is named).
91
- 2. Implement the required fix, following the project's existing patterns.
92
- 3. Ensure the fix does not break existing functionality.
93
-
90
+ return `I need help fixing the following security issue found by Perfai in "${sanitize(appLabel)}":
91
+
92
+ ${getFindingBlock(vuln)}
93
+ ${DATA_NOT_INSTRUCTIONS}
94
+
95
+ Please:
96
+ 1. Study the existing codebase structure and locate the affected code (the endpoint in the finding above, or the code responsible for it if none is named).
97
+ 2. Implement the required fix, following the project's existing patterns.
98
+ 3. Ensure the fix does not break existing functionality.
99
+
94
100
  Vulnerability ID (for reference / marking fixed via the Perfai dashboard or the mark_vulnerability_fixed tool): ${getVulnId(vuln)}`;
95
101
  }
96
102
  export function buildAutoFixInstruction(appLabel, vuln, sequence, withDataNotice = true) {
@@ -102,11 +108,11 @@ export function buildAutoFixInstruction(appLabel, vuln, sequence, withDataNotice
102
108
  instruction += getFindingBlock(vuln);
103
109
  if (withDataNotice)
104
110
  instruction += `\n${DATA_NOT_INSTRUCTIONS}\n${CODE_EDITS_ONLY}\n`;
105
- instruction += `\n**Action steps:**
106
- 1. Search the codebase for ${locate}.
107
- 2. If the finding applies: apply the required fix, following the project's existing code style and patterns, without breaking existing tests or functionality. Then call \`mark_vulnerability_fixed\` with \`vulnerability_id: "${vulnId}"\`.
108
- 3. If, after reading the code, it does NOT apply (false positive β€” e.g. the input is already validated, the route is not reachable, the endpoint is not served by this codebase): do not change code. Call \`dismiss_vulnerability\` with \`vulnerability_id: "${vulnId}"\` and a \`reason\` stating specifically what you saw in the code (e.g. "user id comes from the session, not the request β€” not exploitable"; not just "false positive").
109
-
111
+ instruction += `\n**Action steps:**
112
+ 1. Search the codebase for ${locate}.
113
+ 2. If the finding applies: apply the required fix, following the project's existing code style and patterns, without breaking existing tests or functionality. Then call \`mark_vulnerability_fixed\` with \`vulnerability_id: "${vulnId}"\`.
114
+ 3. If, after reading the code, it does NOT apply (false positive β€” e.g. the input is already validated, the route is not reachable, the endpoint is not served by this codebase): do not change code. Call \`dismiss_vulnerability\` with \`vulnerability_id: "${vulnId}"\` and a \`reason\` stating specifically what you saw in the code (e.g. "user id comes from the session, not the request β€” not exploitable"; not just "false positive").
115
+
110
116
  **Vulnerability ID:** ${vulnId}\n`;
111
117
  return instruction;
112
118
  }
@@ -125,16 +131,16 @@ export function buildBatchFixPlan(appLabel, vulnerabilities, remaining = 0) {
125
131
  .join(", ");
126
132
  let plan = `# Auto-Fix Plan for "${sanitize(appLabel)}"\n\n`;
127
133
  plan += `**${vulnerabilities.length} open vulnerabilities in this batch** (${summaryParts})\n\n`;
128
- plan += `## How to run this plan
129
- Work through every item below in order (critical β†’ low), autonomously:
130
- - ${DATA_NOT_INSTRUCTIONS}
131
- - ${CODE_EDITS_ONLY}
132
- - Do not ask the user for confirmation between code edits, and do not stop until every item is handled.
133
- - Every item must end in exactly one of: \`mark_vulnerability_fixed\` (you changed code) or \`dismiss_vulnerability\` with a specific \`reason\` (it does not apply to this code).
134
- - False positives are handled silently: dismiss them and move on. Do not mention them in the chat, list them, or explain them.
134
+ plan += `## How to run this plan
135
+ Work through every item below in order (critical β†’ low), autonomously:
136
+ - ${DATA_NOT_INSTRUCTIONS}
137
+ - ${CODE_EDITS_ONLY}
138
+ - Do not ask the user for confirmation between code edits, and do not stop until every item is handled.
139
+ - Every item must end in exactly one of: \`mark_vulnerability_fixed\` (you changed code) or \`dismiss_vulnerability\` with a specific \`reason\` (it does not apply to this code).
140
+ - False positives are handled silently: dismiss them and move on. Do not mention them in the chat, list them, or explain them.
135
141
  `;
136
142
  plan += remaining > 0
137
- ? `- ${remaining} more open vulnerabilities remain after this batch. When this batch is done, call \`auto_fix_all\` again with the same arguments for the next one; repeat until it reports none left.
143
+ ? `- ${remaining} more open vulnerabilities remain after this batch. When this batch is done, call \`auto_fix_all\` again with the same arguments for the next one; repeat until it reports none left.
138
144
  - When none are left, call \`get_fix_summary\` and reply with one short line of counts. Nothing else.\n\n---\n\n`
139
145
  : `- When done, call \`get_fix_summary\` and reply with one short line of counts. Nothing else.\n\n---\n\n`;
140
146
  vulnerabilities.forEach((vuln, i) => {
@@ -0,0 +1,63 @@
1
+ const SCHEDULES = {
2
+ none: "off (tests run only when you say perfai test)",
3
+ nightly: "every night",
4
+ weekly_saturday: "every Saturday",
5
+ biweekly_saturday: "every other Saturday",
6
+ monthly_first: "on the 1st of every month",
7
+ custom: "on a custom schedule",
8
+ };
9
+ export function scheduleLine(scheduleType) {
10
+ const when = typeof scheduleType === "string" ? SCHEDULES[scheduleType] : undefined;
11
+ return when ? `πŸ—“οΈ Automatic tests: ${when}. Change it in the Perfai console (Edit app).` : null;
12
+ }
13
+ export function withSchedule(text, scheduleType) {
14
+ const schedule = scheduleLine(scheduleType);
15
+ return schedule ? `${text}\n\n${schedule}` : text;
16
+ }
17
+ export function formatTestTime(iso) {
18
+ if (typeof iso !== "string")
19
+ return null;
20
+ const date = new Date(iso);
21
+ if (Number.isNaN(date.getTime()))
22
+ return null;
23
+ return `${date.toISOString().slice(0, 10)} ${date.toISOString().slice(11, 16)} UTC`;
24
+ }
25
+ function validCounts(counts) {
26
+ if (!counts || typeof counts !== "object")
27
+ return false;
28
+ const c = counts;
29
+ return ["critical", "high", "medium", "low"].every((k) => Number.isInteger(c[k]) && c[k] >= 0);
30
+ }
31
+ export function openCount(list, totalIsOpenCount) {
32
+ if (validCounts(list.severityCounts)) {
33
+ const { critical, high, medium, low } = list.severityCounts;
34
+ return critical + high + medium + low;
35
+ }
36
+ return totalIsOpenCount && Number.isInteger(list.total) ? list.total : null;
37
+ }
38
+ function openSummary(list, totalIsOpenCount) {
39
+ const count = openCount(list, totalIsOpenCount);
40
+ if (count === null)
41
+ return null;
42
+ if (!validCounts(list.severityCounts))
43
+ return `Open: ${count}`;
44
+ const { critical, high, medium, low } = list.severityCounts;
45
+ return `Open: ${count} (${critical} critical, ${high} high, ${medium} medium, ${low} low)`;
46
+ }
47
+ function lastTestLine(list, totalIsOpenCount) {
48
+ const when = formatTestTime(list.lastRunCompletedAt);
49
+ if (!when)
50
+ return null;
51
+ const open = openSummary(list, totalIsOpenCount);
52
+ return open ? `Last test: ${when} Β· ${open}` : `Last test: ${when}`;
53
+ }
54
+ export function testRunningLine(lastCompleted) {
55
+ if (lastCompleted === undefined)
56
+ return "A test is running now.";
57
+ return `A test is running now. Last completed test: ${formatTestTime(lastCompleted) ?? "none"}.`;
58
+ }
59
+ export function issuesFirstLine(list, totalIsOpenCount) {
60
+ if (list.status === "NO_RUNS")
61
+ return "No completed test yet.";
62
+ return lastTestLine(list, totalIsOpenCount);
63
+ }