Skip to content

Commit 0ed2f51

Browse files
authored
allowedWritePatterns for agent (#103)
1 parent 9e6ffd0 commit 0ed2f51

30 files changed

Lines changed: 1835 additions & 105 deletions

‎helm/environments/local/lifecycle.yaml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,12 +79,14 @@ components:
7979
initialDelaySeconds: 60
8080
periodSeconds: 10
8181
failureThreshold: 6
82+
timeoutSeconds: 10
8283
readinessProbe:
8384
httpGet:
8485
path: /api/health
8586
port: 80
86-
periodSeconds: 5
87+
periodSeconds: 15
8788
failureThreshold: 3
89+
timeoutSeconds: 10
8890

8991
worker:
9092
enabled: true

‎src/app/api/v2/ai/chat/[buildUuid]/route.ts‎

Lines changed: 65 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ import AIAgentConfigService from 'server/services/aiAgentConfig';
2424
import { getLogger, withLogContext } from 'server/lib/logger';
2525
import { extractJsonFromResponse } from 'server/services/ai/utils/jsonExtraction';
2626
import { sanitizeForJson } from 'server/services/ai/utils/sanitize';
27+
import { normalizeInvestigationPayload } from 'server/services/ai/utils/normalizePayload';
28+
import { authorizeToolForFixTarget, FixTargetScope } from 'server/services/ai/utils/fixTargetAuthorization';
2729
import {
2830
createClassifiedError,
2931
ErrorCategory,
@@ -150,6 +152,25 @@ export const dynamic = 'force-dynamic';
150152
* Operation mode. "investigate" (default) is read-only analysis.
151153
* "fix" enables the agent to take corrective actions via tools.
152154
* default: investigate
155+
* fixTarget:
156+
* type: object
157+
* description: >
158+
* Optional service-scoped fix target. When provided in fix mode,
159+
* mutating tool calls are constrained to this selected issue.
160+
* properties:
161+
* serviceName:
162+
* type: string
163+
* suggestedFix:
164+
* type: string
165+
* filePath:
166+
* type: string
167+
* files:
168+
* type: array
169+
* items:
170+
* type: object
171+
* properties:
172+
* path:
173+
* type: string
153174
* responses:
154175
* '200':
155176
* description: >
@@ -278,7 +299,7 @@ const postHandler = async (req: NextRequest, { params }: { params: { buildUuid:
278299
return;
279300
}
280301

281-
const { message, clearHistory, provider, modelId, isSystemAction, mode: requestedMode } = body;
302+
const { message, clearHistory, provider, modelId, isSystemAction, mode: requestedMode, fixTarget } = body;
282303

283304
getLogger().info(
284305
`AI: v2 chat request received provider=${provider} modelId=${modelId} hasProvider=${!!provider} hasModelId=${!!modelId}`
@@ -364,6 +385,13 @@ const postHandler = async (req: NextRequest, { params }: { params: { buildUuid:
364385
getLogger().info(`AI: using mode=${mode} (requestedMode=${requestedMode})`);
365386

366387
const onToolConfirmation = mode === 'fix' ? async () => true : undefined;
388+
const onToolAuthorization =
389+
mode === 'fix' && fixTarget
390+
? async (
391+
tool: { name: string; description: string; category: string; safetyLevel: string },
392+
args: Record<string, unknown>
393+
) => authorizeToolForFixTarget(fixTarget as FixTargetScope, { ...tool, args })
394+
: undefined;
367395

368396
const result = await llmService.processQueryStream(
369397
message,
@@ -414,6 +442,7 @@ const postHandler = async (req: NextRequest, { params }: { params: { buildUuid:
414442
collectedEvidence.push(evidenceEvent as unknown as Record<string, unknown>);
415443
},
416444
onToolConfirmation,
445+
onToolAuthorization,
417446
mode,
418447
(event: AIChatSSEEvent) => {
419448
try {
@@ -470,35 +499,46 @@ const postHandler = async (req: NextRequest, { params }: { params: { buildUuid:
470499
aiResponse = result.response;
471500
isJsonResponse = result.isJson;
472501
totalInvestigationTimeMs = result.totalInvestigationTimeMs;
502+
let preambleText: string | undefined = result.preamble;
503+
let completeJsonEmitted = false;
473504

474-
if (!isJsonResponse && aiResponse.includes('"investigation_complete"')) {
505+
if (aiResponse.includes('"investigation_complete"')) {
475506
const extracted = extractJsonFromResponse(aiResponse, buildUuid);
476-
aiResponse = extracted.response;
477-
isJsonResponse = extracted.isJson;
507+
if (extracted.isJson) {
508+
aiResponse = extracted.response;
509+
isJsonResponse = true;
510+
if (extracted.preamble && !preambleText) {
511+
preambleText = extracted.preamble;
512+
}
513+
}
478514
}
479515

480516
if (isJsonResponse) {
481517
try {
482-
const parsed = JSON.parse(aiResponse);
518+
let parsed = JSON.parse(aiResponse);
483519
getLogger().info(
484520
`AI: JSON response type=${parsed.type} hasPullRequest=${!!context.lifecycleContext
485521
?.pullRequest} fullName=${context.lifecycleContext?.pullRequest?.fullName} branch=${
486522
context.lifecycleContext?.pullRequest?.branch
487523
}`
488524
);
489-
if (parsed.type === 'investigation_complete' && context.lifecycleContext?.pullRequest) {
490-
const fullName = context.lifecycleContext.pullRequest.fullName;
491-
const branch = context.lifecycleContext.pullRequest.branch;
492-
if (fullName && branch) {
493-
const [owner, name] = fullName.split('/');
494-
parsed.repository = { owner, name, branch };
495-
getLogger().info(`AI: added repository to response owner=${owner} name=${name} branch=${branch}`);
496-
497-
const sanitized = sanitizeForJson(parsed);
498-
aiResponse = JSON.stringify(sanitized, null, 2);
499-
500-
JSON.parse(aiResponse);
525+
if (parsed.type === 'investigation_complete') {
526+
parsed = normalizeInvestigationPayload(parsed, { availableTools: result.availableTools });
527+
528+
if (context.lifecycleContext?.pullRequest) {
529+
const fullName = context.lifecycleContext.pullRequest.fullName;
530+
const branch = context.lifecycleContext.pullRequest.branch;
531+
if (fullName && branch) {
532+
const [owner, name] = fullName.split('/');
533+
parsed.repository = { owner, name, branch };
534+
getLogger().info(`AI: added repository to response owner=${owner} name=${name} branch=${branch}`);
535+
}
501536
}
537+
538+
const sanitized = sanitizeForJson(parsed);
539+
aiResponse = JSON.stringify(sanitized, null, 2);
540+
541+
JSON.parse(aiResponse);
502542
}
503543
} catch (e) {
504544
getLogger().error(
@@ -510,8 +550,14 @@ const postHandler = async (req: NextRequest, { params }: { params: { buildUuid:
510550
isJsonResponse = false;
511551
}
512552

513-
if (isJsonResponse) {
514-
sendEvent({ type: 'complete_json', content: aiResponse, totalInvestigationTimeMs });
553+
if (isJsonResponse && !completeJsonEmitted) {
554+
completeJsonEmitted = true;
555+
sendEvent({
556+
type: 'complete_json',
557+
content: aiResponse,
558+
totalInvestigationTimeMs,
559+
...(preambleText ? { preamble: preambleText } : {}),
560+
});
515561
}
516562
}
517563
} catch (error: any) {

‎src/components/ai-agent/hooks/useChat.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -272,12 +272,24 @@ export function useChat({ buildUuid, selectedModel }: UseChatOptions) {
272272
receivedCompleteJson = true;
273273
const debugToolData =
274274
debugToolDataMapRef.current.size > 0 ? Array.from(debugToolDataMapRef.current.values()) : undefined;
275+
const preamble =
276+
typeof data.preamble === 'string' && data.preamble.trim().length > 0 ? data.preamble.trim() : null;
277+
const timestamp = Date.now();
275278
setMessages((prev) => [
276279
...prev,
280+
...(preamble
281+
? [
282+
{
283+
role: 'assistant' as const,
284+
content: preamble,
285+
timestamp,
286+
},
287+
]
288+
: []),
277289
{
278290
role: 'assistant',
279291
content: data.content,
280-
timestamp: Date.now(),
292+
timestamp: timestamp + (preamble ? 1 : 0),
281293
activityHistory: collectedActivities.length > 0 ? collectedActivities : undefined,
282294
evidenceItems: collectedEvidence.length > 0 ? collectedEvidence : undefined,
283295
totalInvestigationTimeMs: data.totalInvestigationTimeMs,
@@ -420,6 +432,10 @@ export function useChat({ buildUuid, selectedModel }: UseChatOptions) {
420432
};
421433

422434
const handleAutoFix = (service: ServiceInvestigationResult) => {
435+
if (!service.canAutoFix) {
436+
return;
437+
}
438+
423439
let fixMessage = `User consents to fix ${service.serviceName}. `;
424440

425441
if (service.suggestedFix) {

‎src/server/lib/validation/aiAgentConfigSchemas.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ export const aiAgentConfigSchema = {
5252
systemPromptOverride: { type: 'string', maxLength: 50000 },
5353
excludedTools: { type: 'array', items: { type: 'string' } },
5454
excludedFilePatterns: { type: 'array', items: { type: 'string' } },
55+
allowedWritePatterns: { type: 'array', items: { type: 'string' } },
5556
maxIterations: { type: 'integer', minimum: 1 },
5657
maxToolCalls: { type: 'integer', minimum: 1 },
5758
maxRepeatedCalls: { type: 'integer', minimum: 1 },
@@ -76,6 +77,7 @@ export const aiAgentRepoOverrideSchema = {
7677
systemPromptOverride: { type: 'string', maxLength: 50000 },
7778
excludedTools: { type: 'array', items: { type: 'string' } },
7879
excludedFilePatterns: { type: 'array', items: { type: 'string' } },
80+
allowedWritePatterns: { type: 'array', items: { type: 'string' } },
7981
},
8082
additionalProperties: false,
8183
};

‎src/server/services/ai/orchestration/safety.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,28 @@ export class ToolSafetyManager {
5757
};
5858
}
5959

60+
if (callbacks.onToolAuthorization) {
61+
const decision = await callbacks.onToolAuthorization(
62+
{
63+
name: tool.name,
64+
description: tool.description,
65+
category: tool.category,
66+
safetyLevel: tool.safetyLevel,
67+
},
68+
args
69+
);
70+
if (!decision.allowed) {
71+
return {
72+
success: false,
73+
error: {
74+
message: decision.reason || `Tool ${tool.name} is not authorized for this operation`,
75+
code: 'TOOL_NOT_AUTHORIZED',
76+
recoverable: false,
77+
},
78+
};
79+
}
80+
}
81+
6082
if (this.needsConfirmation(tool)) {
6183
const confirmDetails = await tool.shouldConfirmExecution?.(args);
6284

‎src/server/services/ai/prompts/sections/investigation.ts‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,10 @@ Vague messages ("something seems wrong", "help") — ask for clarification befor
4343
1. Call get_file — fetch current content. This is your ground truth.
4444
2. Copy the file content EXACTLY. Change ONLY the lines needed for the fix. Do not remove comments, delete unused sections, reformat, or make any other modifications.
4545
3. Before calling update_file, verify: does your new_content differ from the original in ONLY the intended lines? If you changed anything else, redo step 2.
46-
4. Call update_file or commit_lifecycle_fix with the verified content.
46+
4. Execute ONLY the mutating tool needed for the selected issue:
47+
- File content fixes: update_file
48+
- PR label fixes: update_pr_labels
49+
- Runtime K8s patch fixes: patch_k8s_resource
4750
5. Verify success response, extract commit_url.
4851
6. Output JSON with fixesApplied: true + commitUrl.
4952
@@ -65,7 +68,7 @@ Decide your output format using this decision tree:
6568
- Any issue found OR config problem even if pods running → JSON schema below
6669
- Fix applied successfully → JSON with fixesApplied: true and commitUrl
6770
68-
JSON — output ONLY valid JSON (no markdown, no conversational text):
71+
JSON — output ONLY the raw JSON object. Do not include any markdown preamble, conversational text, or code fences before or after it. If you want to provide a conversational summary, put it in the "summary" field of the JSON. The response must start with \`{\` and end with \`}\`:
6972
7073
<output_schema>
7174
{
@@ -111,9 +114,9 @@ JSON — output ONLY valid JSON (no markdown, no conversational text):
111114
112115
**status:** Use lowercase values: \`build_failed\`, \`deploy_failed\`, \`error\`, \`ready\`. These must match the TypeScript union type exactly.
113116
114-
**canAutoFix=true** ONLY when: (1) a specific error message from logs/K8s/build output points to the problem, (2) file read + verified the fix, (3) 100% certain. False when: no error messages found, config-only analysis, user decision needed, uncertainty, missing files.
117+
**canAutoFix=true** ONLY when: (1) a specific error message from logs/K8s/build output points to the problem, (2) a concrete fix is prepared and verified, (3) 100% certain, (4) the required mutating tool is actually available in this run (e.g., update_file for file edits, update_pr_labels for PR labels, patch_k8s_resource for K8s patches). False when: no error messages found, config-only analysis, user decision needed, uncertainty, missing files, or required tool unavailable.
115118
116-
**fixesApplied=true** ONLY when: called update_file, received success, have commit_url. Otherwise false.
119+
**fixesApplied=true** ONLY when: you actually executed the intended fix tool for the selected issue and it succeeded. Otherwise false.
117120
118121
**keyError:** Extract the exact error message from logs. Helps the UI display the root cause prominently.
119122
@@ -125,7 +128,7 @@ JSON — output ONLY valid JSON (no markdown, no conversational text):
125128
126129
**suggestedFix patterns:** For single-line changes, use the pattern: \`Change <field> from '<old>' to '<new>' in <file>\`. The UI parses this pattern to render inline diffs. For multi-line changes, use the files array with oldContent/newContent instead.
127130
128-
**commitUrl:** Only include after successfully calling update_file or commit_lifecycle_fix and receiving a commit URL in the response.
131+
**commitUrl:** Include only when the successful fix action produced a commit URL (typically update_file).
129132
130133
**repository:** Include when available from the injected context. Used by the UI to build GitHub links for file paths.
131134
</output_format>
@@ -221,7 +224,7 @@ Root cause confirmed: memory limit too low. Stop — don't also check configs or
221224
<reasoning>
222225
Action: [get_file: lifecycle.yaml] → read current content (147 lines), identified wrong path on line 42
223226
Action: Copied original content, changed ONLY line 42. Verified: 146 of 147 lines unchanged. No comments removed, no reformatting.
224-
Action: [commit_lifecycle_fix: path="lifecycle.yaml", content="..."] → success, commit URL returned
227+
Action: [update_file: path="lifecycle.yaml", new_content="..."] → success, commit URL returned
225228
Fix applied successfully.
226229
</reasoning>
227230
<example_output>

‎src/server/services/ai/prompts/sections/safety.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,11 @@ export const SAFETY_SECTION = `<safety_rules>
1818
# Security & Safety
1919
2020
- **User Consent:** Present findings as JSON first. The user clicks "Fix it for me" before any changes are applied. After applying, show the commit URL.
21+
- **Selected-Issue Scope:** "Fix it for me" approval applies only to the selected issue/target. Do not fix additional services or unrelated findings unless the user explicitly requests each one.
2122
- **Surgical Changes:** Change ONLY what was suggested. No formatting, no cleanup, no unrelated fixes.
2223
- **Content Integrity:** When modifying a file via update_file, use the EXACT content returned by get_file as your starting point. Apply only the specific fix — do not remove comments, reformat whitespace, delete unused sections, or make any other modifications. Your new_content must be identical to the original except for the targeted fix lines.
2324
- **Scope Boundaries:** You can modify files in the PR repo only. For issues in other service repos, describe the fix but do not attempt to commit.
25+
- **Tool-Capability Gate:** Only mark an issue auto-fixable or execute a fix when the matching mutating tool is available (file edits → update_file, PR labels → update_pr_labels, runtime K8s patches → patch_k8s_resource).
2426
- **Path Verification:** Before including a filePath in your JSON response, you must have either (a) read it via get_file, (b) seen it in the injected context, or (c) confirmed it exists via list_directory.
2527
- **No Fabrication:** Never diagnose a root cause you cannot support with a specific error message cited from your tool results. If no tool output contains an error pointing to the problem, say "I don't have enough information to determine the root cause." General knowledge about config structure is not evidence.
2628
- **Ambiguity:** When multiple valid options exist, ask the user to choose.

0 commit comments

Comments
 (0)