Repository navigation
Expand file tree
/
Copy pathgithub_action.ts
More file actions
267 lines (258 loc) · 14.1 KB
/
Copy pathgithub_action.ts
File metadata and controls
267 lines (258 loc) · 14.1 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
import { runIssueEventAdmissionAction } from './issue_event_admission_action';
import { runNativeVerificationEntry } from '../infrastructure/native_verification_controller';
import { createNativeStatusReadPort } from '../infrastructure/composition/issue_completion_composition_root';
import * as core from '@actions/core';
import * as github from '@actions/github';
import { ConfigurationHandler } from '../manager/description/configuration_handler';
import { GitCliRepository } from '../data/repository/git_cli_repository';
import { createIssueContentCompositionRoot } from '../infrastructure/composition/issue_content_composition_root';
import { createProjectBoardCompositionRoot } from '../infrastructure/composition/project_board_composition_root';
import { finishGithubAction } from './github_action_completion';
import { getGithubActionInput } from './github_action_input';
import { isEnabledInput, parseIssueWorkflowBoolean } from './input_boolean_policy';
import { buildGithubActionExecution, hydrateGithubActionExecutionProjects, readGithubActionSingleAction } from './github_action_execution';
import { buildGithubActionEventInputs } from './github_event_inputs';
import { mainRun } from './common_action';
import { INPUT_KEYS } from '../application/contracts/input_keys';
import { logDebugInfo, logError, logInfo } from '../utils/logger';
import { createGithubExecutionAdmissionUseCase } from '../infrastructure/composition/github_execution_admission_composition_root';
import { createSynchronizeLifecycleStateUseCase } from '../infrastructure/composition/lifecycle_state_composition_root';
import { createCopilotEvidenceCompositionRoot } from '../infrastructure/composition/copilot_evidence_composition_root';
import { createGithubActionSummaryCompositionRoot } from '../infrastructure/composition/github_action_summary_composition_root';
import { createSynchronizeAgentActivityUseCase } from '../infrastructure/composition/agent_activity_composition_root';
import { readGithubActionAiInputs } from './github_action_ai_inputs';
import { activeAgentTasks, isUnaddressedCommentEvent } from '../application/policies/agent_task_activation_policy';
import { createActorAuthorizationRepository } from '../infrastructure/composition/actor_authorization_composition_root';
import { runAtApplicationErrorBoundary } from '../application/errors/application_error_context';
import { toApplicationError } from '../application/errors/application_error';
import { renderApplicationErrorMarkdown, renderApplicationErrorText } from '../application/policies/application_error_presentation_policy';
import { bindIssueCommentPublication } from '../infrastructure/composition/push_single_action_capability_port_binding';
import { bindPublicationSourceQuery } from '../infrastructure/composition/shared_capability_port_binding';
import { GithubPublicationSourceRepository } from '../data/repository/github_publication_source_repository';
import { createBranchClient } from '../infrastructure/composition/github_branch_client_factory';
import { createLanguageQueryPort } from '../infrastructure/composition/agent_capability_composition_root';
import { ResolveMessageCatalogUseCase } from '../application/usecases/localization/resolve_message_catalog_use_case';
import { readGithubActionLocaleInputs } from './github_action_locale_inputs';
import { publicationLocaleNeedsDynamicCatalog } from '../application/policies/publication_message_catalog';
import {
resolveStaticApplicationErrorCatalog,
type ApplicationErrorMessageReader,
} from '../application/policies/application_error_message_catalog';
import { prepareGithubAgentRuntime } from './github_action_runtime';
import { runPullRequestApprovalAction } from './pull_request_approval_action';
import { isBotPullRequestAnalysisEvent } from '../application/policies/bot_pull_request_analysis_policy';
import { createPullRequestUseCaseCompositionRoot } from '../infrastructure/composition/pull_request_use_case_composition_root';
export async function runGitHubAction(): Promise<void> {
if (process.env.COPILOT_ISSUE_ADMISSION_BOOTSTRAP === '1') {
// Only the isolated bootstrap owns this input; ordinary JSON input maps
// must not redirect the mutation entry into a successful read-only no-op.
await runIssueEventAdmissionAction(core.getInput('issue-event-admission-mode', { required: true }));
return;
}
if (isEnabledInput(getGithubActionInput('pr-approval-observer'))) {
await runPullRequestApprovalAction(getGithubActionInput(INPUT_KEYS.TOKEN, { required: true }));
return;
}
const eventInputs = buildGithubActionEventInputs({
payload: github.context.payload as Record<string, unknown>,
eventName: github.context.eventName,
actor: github.context.actor,
repo: github.context.repo,
});
logInfo('GitHub Action: runGitHubAction started.');
const debug = isEnabledInput(getGithubActionInput(INPUT_KEYS.DEBUG));
if (debug) {
logInfo('Debug mode is enabled. Full logs will be included in the report.');
}
const token = getGithubActionInput(INPUT_KEYS.TOKEN, { required: true });
const singleAction = readGithubActionSingleAction(getGithubActionInput);
const admission = await createGithubExecutionAdmissionUseCase().invoke({
actor: eventInputs.actor,
token,
isSingleAction: singleAction.enabledSingleAction,
validSingleAction: singleAction.validSingleAction,
});
const botAnalysisOnly = admission.decision === 'discard' && isBotPullRequestAnalysisEvent({
eventName: eventInputs.eventName,
action: eventInputs.action,
actor: eventInputs.actor,
tokenUser: admission.tokenUser,
repositoryId: github.context.payload.repository?.id,
pullRequest: eventInputs.pull_request,
});
const botClosedIssueOnly = !singleAction.enabledSingleAction && eventInputs.eventName === 'issues'
&& eventInputs.action === 'closed' && eventInputs.issue?.state === 'closed'
&& typeof eventInputs.issue.number === 'number' && Number.isSafeInteger(eventInputs.issue.number) && eventInputs.issue.number > 0;
if (admission.decision === 'discard' && !botAnalysisOnly && !botClosedIssueOnly) {
logInfo('GitHub Action: event actor matches the PAT user. Skipping normal pipeline before queue and mutation work.');
return;
}
const preBranchSddEnabled = parseIssueWorkflowBoolean(
getGithubActionInput(INPUT_KEYS.PRE_BRANCH_SDD), INPUT_KEYS.PRE_BRANCH_SDD, false,
);
if (isUnaddressedCommentEvent(eventInputs, admission.tokenUser, preBranchSddEnabled)) {
logInfo('GitHub Action: comment does not address Copilot. Skipping before project, AI, and agent runtime work.');
return;
}
const localeInputs = readGithubActionLocaleInputs(getGithubActionInput);
const aiInputs = readGithubActionAiInputs(getGithubActionInput);
const activeRuntimeAgentTasks = activeAgentTasks(
eventInputs,
singleAction,
admission.tokenUser,
aiInputs.pullRequestDescriptionMode !== 'disabled',
preBranchSddEnabled,
);
const requestedActiveAgentTasks = [...new Set([
...activeRuntimeAgentTasks,
...([localeInputs.repository, localeInputs.issue, localeInputs.pullRequest]
.some(publicationLocaleNeedsDynamicCatalog) ? ['planner' as const] : []),
])];
const memberOnlyAgentTaskAuthorizationRequired = !botAnalysisOnly
&& aiInputs.membersOnly
&& requestedActiveAgentTasks.length > 0;
let memberOnlyAgentTasksAuthorized = !memberOnlyAgentTaskAuthorizationRequired;
let languageRuntimeAvailable = false;
const projectBoard = createProjectBoardCompositionRoot();
const execution = await buildGithubActionExecution({
debug,
eventInputs,
getInput: getGithubActionInput,
projectQuery: projectBoard.query,
token,
tokenUser: admission.tokenUser,
singleAction,
aiInputs,
activeAgentTasks: requestedActiveAgentTasks,
agentRuntimeAuthorized: memberOnlyAgentTasksAuthorized,
localeInputs,
});
if (botAnalysisOnly) {
// Bypass the normal lifecycle/issue route entirely. The only permitted
// side effect is Bugbot's PR analysis and its own bounded presentation.
execution.issueNumber = execution.pullRequest.number;
prepareGithubAgentRuntime(aiInputs.requestedAgentTasks, ['reviewer']);
const results = await createPullRequestUseCaseCompositionRoot({
owner: execution.owner,
repository: execution.repo,
token,
}).reviewOnly(execution);
if (results.some(result => !result.success)) {
throw new Error('Bot-authored pull-request analysis did not complete.');
}
await core.summary.addRaw('Copilot analyzed this bot-authored pull request. Native bot approval is never permitted.').write();
return;
}
logDebugInfo(
`Execution built. Event will be resolved in mainRun. Single action: ${execution.singleAction.currentSingleAction ?? 'none'}, ` +
`AI PR description mode: ${execution.ai.getPullRequestDescriptionMode()}, bugbot min severity: ${execution.ai.getBugbotMinSeverity()}.`,
);
const repositoryBinding = {
owner: execution.owner,
repository: execution.repo,
token: execution.tokens.token,
};
const results = await mainRun(
execution,
projectBoard.command,
new GitCliRepository(token),
'github-workflow',
createSynchronizeLifecycleStateUseCase(repositoryBinding),
createSynchronizeAgentActivityUseCase(repositoryBinding),
async (admittedExecution) => {
await hydrateGithubActionExecutionProjects(admittedExecution, {
getInput: getGithubActionInput,
projectQuery: projectBoard.query,
token,
});
if (admittedExecution.isIssue && admittedExecution.issueWorkflowRuntimeMode !== 'execute') return;
if (memberOnlyAgentTaskAuthorizationRequired) {
// Agent-task admission is intentionally membership-based. File-changing
// commands enforce their separate repository-write authorization later.
memberOnlyAgentTasksAuthorized = await createActorAuthorizationRepository()
.isActorAllowedToUseMemberOnlyAutomation(
eventInputs.repo.owner,
eventInputs.repo.repo,
eventInputs.actor,
token,
);
if (memberOnlyAgentTasksAuthorized) {
admittedExecution.ai.enableAuthorizedAgentTasks(aiInputs.requestedAgentTasks);
}
}
if (!memberOnlyAgentTasksAuthorized) {
logInfo('Skipping agent runtime preparation because ai-members-only is enabled and the actor is not authorized.');
return;
}
if (!singleAction.isCloseInactiveIssuesAction && requestedActiveAgentTasks.length > 0) {
prepareGithubAgentRuntime(aiInputs.requestedAgentTasks, requestedActiveAgentTasks);
languageRuntimeAvailable = requestedActiveAgentTasks.includes('planner');
}
},
);
const issueContentPort = createIssueContentCompositionRoot();
const configurationHandler = new ConfigurationHandler(issueContentPort);
await finishGithubAction(
execution,
results,
bindIssueCommentPublication(issueContentPort, repositoryBinding),
{
update: (context) => configurationHandler.update({
...repositoryBinding,
issueNumber: context.issueNumber,
}, context),
},
createCopilotEvidenceCompositionRoot(),
createGithubActionSummaryCompositionRoot(),
new ResolveMessageCatalogUseCase(
languageRuntimeAvailable ? createLanguageQueryPort() : undefined,
),
bindPublicationSourceQuery(
new GithubPublicationSourceRepository(createBranchClient()),
repositoryBinding,
createNativeStatusReadPort(repositoryBinding),
),
);
}
/**
* Runs the action entrypoint without forcing a successful process exit.
*
* `@actions/core.setFailed` deliberately communicates failure through
* `process.exitCode`. Calling `process.exit(0)` after a resolved workflow would
* overwrite that signal (for example when Bugbot is configured to fail on
* unresolved findings), so this boundary must let Node exit naturally.
*/
export async function runGitHubActionEntry(
run: () => Promise<void> = runGitHubAction,
): Promise<void> {
return runAtApplicationErrorBoundary(async () => {
try {
await run();
} catch (cause: unknown) {
const semanticError = toApplicationError(cause, 'workflow.failed', 'GitHub Action execution failed.');
logError(semanticError);
const message = earlyGithubActionErrorMessage();
core.setFailed(renderApplicationErrorText(semanticError, message));
if (semanticError.recovery?.id.startsWith('stored-configuration-')) {
try {
await createGithubActionSummaryCompositionRoot().publish(renderApplicationErrorMarkdown(semanticError, message));
} catch (summaryCause) {
logError(toApplicationError(summaryCause, 'provider.unavailable', 'Unable to publish the configuration failure summary.'));
}
}
}
});
}
function earlyGithubActionErrorMessage(): ApplicationErrorMessageReader {
try {
const locale = readGithubActionLocaleInputs(getGithubActionInput).repository;
return resolveStaticApplicationErrorCatalog(locale).message;
} catch {
return resolveStaticApplicationErrorCatalog('en-US').message;
}
}
// Only auto-run when executed as the action entry (not when imported by tests)
/* istanbul ignore next -- the bundled production entry is covered by the Action smoke path. */
if (typeof process.env.JEST_WORKER_ID === 'undefined' && process.env.COPILOT_ISSUE_ADMISSION_BOOTSTRAP !== '1') {
void runGitHubActionEntry(() => runNativeVerificationEntry(runGitHubActionEntry));
}