-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathplan.ts
More file actions
275 lines (251 loc) · 8.55 KB
/
plan.ts
File metadata and controls
275 lines (251 loc) · 8.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/**
* sentry issue plan
*
* Generate a solution plan for a Sentry issue using Seer AI.
* Automatically runs root cause analysis if not already done.
*/
import type { SentryContext } from "../../context.js";
import { triggerSolutionPlanning } from "../../lib/api-client.js";
import { buildCommand, numberParser } from "../../lib/command.js";
import { ApiError, ValidationError } from "../../lib/errors.js";
import { CommandOutput } from "../../lib/formatters/output.js";
import {
formatSolution,
handleSeerApiError,
} from "../../lib/formatters/seer.js";
import {
applyFreshFlag,
FRESH_ALIASES,
FRESH_FLAG,
} from "../../lib/list-command.js";
import { logger } from "../../lib/logger.js";
import {
type AutofixState,
extractRootCauses,
extractSolution,
type RootCause,
type SolutionArtifact,
} from "../../types/seer.js";
import {
ensureRootCauseAnalysis,
issueIdPositional,
pollAutofixState,
resolveOrgAndIssueId,
} from "./utils.js";
type PlanFlags = {
readonly cause?: number;
readonly json: boolean;
readonly force: boolean;
readonly fresh: boolean;
readonly fields?: string[];
};
/**
* Validate that the autofix state has root causes identified.
*
* @param state - Current autofix state (already ensured to exist)
* @returns Array of root causes
* @throws {ValidationError} If no root causes found
*/
function validateRootCauses(state: AutofixState): RootCause[] {
const causes = extractRootCauses(state);
if (causes.length === 0) {
throw new ValidationError(
"No root causes identified. Cannot create a plan without a root cause."
);
}
return causes;
}
/**
* Validate and resolve the cause selection for solution planning.
*
* @param causes - Array of available root causes
* @param selectedCause - User-specified cause index, or undefined for auto-select
* @param issueId - Issue ID for error message hints
* @returns Validated cause index (0-based)
* @throws {ValidationError} If multiple causes exist without selection, or if selection is out of range
*/
function validateCauseSelection(
causes: RootCause[],
selectedCause: number | undefined,
issueId: string
): number {
// If only one cause and none specified, use it
if (causes.length === 1 && selectedCause === undefined) {
return 0;
}
// If multiple causes and none specified, error with list
if (causes.length > 1 && selectedCause === undefined) {
const lines = [
"Multiple root causes found. Please specify one with --cause <id>:",
"",
];
for (let i = 0; i < causes.length; i++) {
const cause = causes[i];
if (cause) {
lines.push(` ${i}: ${cause.description.slice(0, 60)}...`);
}
}
lines.push("");
lines.push(`Example: sentry issue plan ${issueId} --cause 0`);
throw new ValidationError(lines.join("\n"));
}
const causeId = selectedCause ?? 0;
// Validate the cause ID is in range
if (causeId < 0 || causeId >= causes.length) {
throw new ValidationError(
`Invalid cause ID: ${causeId}. Valid range is 0-${causes.length - 1}.`
);
}
return causeId;
}
/** Return type for issue plan — includes state metadata and solution data */
type PlanData = {
run_id: number;
status: string;
/** The solution data (without the artifact wrapper). Null when no solution is available. */
solution: SolutionArtifact["data"] | null;
};
/**
* Format solution plan data for human-readable terminal output.
*
* Returns the formatted solution or a "no solution" message.
*/
function formatPlanOutput(data: PlanData): string {
if (data.solution) {
return formatSolution({ key: "solution", data: data.solution });
}
return "No solution found. Check the Sentry web UI for details.";
}
/**
* Build the plan data object from autofix state.
*
* Stores `solution.data` (not the full artifact) to keep the JSON shape flat —
* consumers get `{ run_id, status, solution: { one_line_summary, steps, ... } }`.
*/
function buildPlanData(state: AutofixState): PlanData {
const solution = extractSolution(state);
return {
run_id: state.run_id,
status: state.status,
solution: solution?.data ?? null,
};
}
export const planCommand = buildCommand({
docs: {
brief: "Generate a solution plan using Seer AI",
fullDescription:
"Generate a solution plan for a Sentry issue using Seer AI.\n\n" +
"This command automatically runs root cause analysis if needed, then " +
"generates a solution plan with specific implementation steps to fix the issue.\n\n" +
"If multiple root causes are identified, use --cause to specify which one.\n" +
"Use --force to regenerate a plan even if one already exists.\n\n" +
"Issue formats:\n" +
" @latest - Most recent unresolved issue\n" +
" @most_frequent - Issue with highest event frequency\n" +
" <org>/ID - Explicit org: sentry/EXTENSION-7, sentry/cli-G\n" +
" <org>/@selector - Selector with org: my-org/@latest\n" +
" <project>-suffix - Project + suffix: cli-G, spotlight-electron-4Y\n" +
" ID - Short ID: CLI-G (searches across orgs)\n" +
" suffix - Suffix only: G (requires DSN context)\n" +
" numeric - Numeric ID: 123456789\n\n" +
"Prerequisites:\n" +
" - GitHub integration configured for your organization\n" +
" - Code mappings set up for your project\n\n" +
"Examples:\n" +
" sentry issue plan @latest --cause 0\n" +
" sentry issue plan 123456789 --cause 0\n" +
" sentry issue plan sentry/EXTENSION-7 --cause 1\n" +
" sentry issue plan cli-G --cause 0\n" +
" sentry issue plan 123456789 --force",
},
output: {
human: formatPlanOutput,
},
parameters: {
positional: issueIdPositional,
flags: {
cause: {
kind: "parsed",
parse: numberParser,
brief: "Root cause ID to plan (required if multiple causes exist)",
optional: true,
},
force: {
kind: "boolean",
brief: "Force new plan even if one exists",
default: false,
},
fresh: FRESH_FLAG,
},
aliases: FRESH_ALIASES,
},
async *func(this: SentryContext, flags: PlanFlags, issueArg: string) {
applyFreshFlag(flags);
const { cwd } = this;
// Declare org outside try block so it's accessible in catch for error messages
let resolvedOrg: string | undefined;
try {
// Resolve org and issue ID
const { org, issueId: numericId } = await resolveOrgAndIssueId({
issueArg,
cwd,
command: "plan",
});
resolvedOrg = org;
// Ensure root cause analysis exists (runs explain if needed)
const state = await ensureRootCauseAnalysis({
org,
issueId: numericId,
json: flags.json,
});
// Validate we have root causes
const causes = validateRootCauses(state);
// Validate cause selection
const causeId = validateCauseSelection(causes, flags.cause, issueArg);
const selectedCause = causes[causeId];
// Check if solution already exists (skip if --force)
if (!flags.force) {
const existingSolution = extractSolution(state);
if (existingSolution) {
return yield new CommandOutput(buildPlanData(state));
}
}
// No solution exists, trigger planning
if (!flags.json) {
const log = logger.withTag("issue.plan");
log.info(`Creating plan for cause #${causeId}...`);
if (selectedCause) {
log.info(`"${selectedCause.description}"`);
}
}
await triggerSolutionPlanning(org, numericId, state.run_id);
// Poll until PR is created
const finalState = await pollAutofixState({
orgSlug: org,
issueId: numericId,
json: flags.json,
timeoutMessage:
"Plan creation timed out after 6 minutes. Try again or check the issue in Sentry web UI.",
timeoutHint:
"The plan may still be generated in the background.\n" +
` Or retry: sentry issue plan ${issueArg}`,
});
// Handle errors
if (finalState.status === "ERROR") {
throw new Error(
"Plan creation failed. Check the Sentry web UI for details."
);
}
if (finalState.status === "CANCELLED") {
throw new Error("Plan creation was cancelled.");
}
return yield new CommandOutput(buildPlanData(finalState));
} catch (error) {
// Handle API errors with friendly messages
if (error instanceof ApiError) {
throw handleSeerApiError(error.status, error.detail, resolvedOrg);
}
throw error;
}
},
});