@mastra/factory 0.5.0 → 0.6.0-alpha.1
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/CHANGELOG.md +42 -0
- package/dist/auth.d.ts +2 -0
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +2 -0
- package/dist/auth.js.map +1 -1
- package/dist/capabilities/intake.d.ts +1 -0
- package/dist/capabilities/intake.d.ts.map +1 -1
- package/dist/capabilities/version-control.d.ts +2 -0
- package/dist/capabilities/version-control.d.ts.map +1 -1
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +2 -1
- package/dist/factory.js.map +1 -1
- package/dist/integrations/base.d.ts +6 -0
- package/dist/integrations/base.d.ts.map +1 -1
- package/dist/integrations/github/integration.d.ts +1 -0
- package/dist/integrations/github/integration.d.ts.map +1 -1
- package/dist/integrations/github/integration.js +11 -1
- package/dist/integrations/github/integration.js.map +1 -1
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +20 -46
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/rules.d.ts +4 -0
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +68 -10
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/github/sandbox-release.d.ts +16 -1
- package/dist/integrations/github/sandbox-release.d.ts.map +1 -1
- package/dist/integrations/github/sandbox-release.js +42 -1
- package/dist/integrations/github/sandbox-release.js.map +1 -1
- package/dist/integrations/linear/integration.d.ts +2 -0
- package/dist/integrations/linear/integration.d.ts.map +1 -1
- package/dist/integrations/linear/integration.js +5 -1
- package/dist/integrations/linear/integration.js.map +1 -1
- package/dist/integrations/linear/routes.d.ts.map +1 -1
- package/dist/integrations/linear/routes.js +1 -0
- package/dist/integrations/linear/routes.js.map +1 -1
- package/dist/integrations/linear/rules.d.ts +2 -0
- package/dist/integrations/linear/rules.d.ts.map +1 -1
- package/dist/integrations/linear/rules.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +7 -0
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/slack/integration.d.ts.map +1 -1
- package/dist/integrations/slack/integration.js +3 -2
- package/dist/integrations/slack/integration.js.map +1 -1
- package/dist/integrations/slack/slack.d.ts +37 -110
- package/dist/integrations/slack/slack.d.ts.map +1 -1
- package/dist/integrations/slack/slack.js +49 -44
- package/dist/integrations/slack/slack.js.map +1 -1
- package/dist/routes/surface.d.ts +11 -1
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +18 -8
- package/dist/routes/surface.js.map +1 -1
- package/dist/rules/defaults.d.ts.map +1 -1
- package/dist/rules/defaults.js +35 -4
- package/dist/rules/defaults.js.map +1 -1
- package/dist/rules/start-coordinator.d.ts.map +1 -1
- package/dist/rules/start-coordinator.js +7 -26
- package/dist/rules/start-coordinator.js.map +1 -1
- package/dist/rules/types.d.ts +10 -0
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js.map +1 -1
- package/dist/session/factory-session.d.ts +116 -0
- package/dist/session/factory-session.d.ts.map +1 -0
- package/dist/session/factory-session.js +162 -0
- package/dist/session/factory-session.js.map +1 -0
- package/dist/storage/domains/audit/domain.d.ts +9 -2
- package/dist/storage/domains/audit/domain.d.ts.map +1 -1
- package/dist/storage/domains/audit/domain.js +106 -4
- package/dist/storage/domains/audit/domain.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +11 -0
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/package.json +7 -7
- package/dist/integrations/github/factory-session.d.ts +0 -12
- package/dist/integrations/github/factory-session.d.ts.map +0 -1
- package/dist/integrations/github/factory-session.js +0 -37
- package/dist/integrations/github/factory-session.js.map +0 -1
|
@@ -27,6 +27,13 @@ function number(value) {
|
|
|
27
27
|
function boolean(value) {
|
|
28
28
|
return typeof value === "boolean" ? value : void 0;
|
|
29
29
|
}
|
|
30
|
+
function actorLogins(value) {
|
|
31
|
+
if (!Array.isArray(value)) return [];
|
|
32
|
+
return value.flatMap((actor) => {
|
|
33
|
+
const login = string(object(actor)?.login);
|
|
34
|
+
return login ? [login] : [];
|
|
35
|
+
});
|
|
36
|
+
}
|
|
30
37
|
function eventName(parsed) {
|
|
31
38
|
const action = string(parsed.payload.action);
|
|
32
39
|
if (parsed.event === "issues" && action === "opened") return "issueOpened";
|
|
@@ -120,12 +127,14 @@ var GithubRules = class {
|
|
|
120
127
|
const issueNumber = number(issue?.number);
|
|
121
128
|
const pullRequestNumber = number(pullRequest?.number);
|
|
122
129
|
const provenance = pullRequestNumber ? pullRequestProvenance((await this.options.integrationStorage.subscriptions.listByTarget(provenanceTarget(repositoryId, pullRequestNumber), { status: "active" })).find((subscription) => subscription.orgId === project.orgId)?.data) : null;
|
|
123
|
-
const
|
|
130
|
+
const reviewRequested = event === "pullRequestReviewRequested";
|
|
131
|
+
const requestedReviewer = string(object(parsed.payload.requested_reviewer)?.login);
|
|
132
|
+
const relatedItem = await this.#relatedItem(project.orgId, project.factoryProjectId, repositoryId, issueNumber, pullRequestNumber, string(object(pullRequest?.head)?.ref), reviewRequested ? null : provenance);
|
|
124
133
|
const actor = await githubActor(this.options.github, {
|
|
125
134
|
installationId,
|
|
126
135
|
repository: repositoryName,
|
|
127
136
|
login,
|
|
128
|
-
factoryAuthored: provenance !== null || login === `${this.options.github.slug}[bot]`
|
|
137
|
+
factoryAuthored: !reviewRequested && provenance !== null || login === `${this.options.github.slug}[bot]`
|
|
129
138
|
});
|
|
130
139
|
if (actor.type === "github" && actor.factoryAuthored && (event === "issueCommentCreated" || event === "issueCommentEdited") && string(issueComment?.body)?.includes(FACTORY_TRIAGE_COMMENT_MARKER)) return { status: "ignored" };
|
|
131
140
|
const context = {
|
|
@@ -166,7 +175,8 @@ var GithubRules = class {
|
|
|
166
175
|
title: string(issue?.title),
|
|
167
176
|
url: string(issue?.html_url),
|
|
168
177
|
...string(issue?.created_at) ? { createdAt: string(issue?.created_at) } : {},
|
|
169
|
-
...string(issue?.updated_at) ? { updatedAt: string(issue?.updated_at) } : {}
|
|
178
|
+
...string(issue?.updated_at) ? { updatedAt: string(issue?.updated_at) } : {},
|
|
179
|
+
assignees: actorLogins(issue?.assignees)
|
|
170
180
|
} } : {},
|
|
171
181
|
...event === "issueEdited" ? { issueChange: {
|
|
172
182
|
title: Boolean(object(changes?.title)),
|
|
@@ -187,10 +197,17 @@ var GithubRules = class {
|
|
|
187
197
|
url: string(pullRequest?.html_url),
|
|
188
198
|
...string(pullRequest?.created_at) ? { createdAt: string(pullRequest?.created_at) } : {},
|
|
189
199
|
state: string(pullRequest?.state) === "closed" ? "closed" : "open",
|
|
200
|
+
draft: boolean(pullRequest?.draft) ?? false,
|
|
190
201
|
merged: boolean(pullRequest?.merged) ?? false,
|
|
202
|
+
assignees: actorLogins(pullRequest?.assignees),
|
|
203
|
+
requestedReviewers: actorLogins(pullRequest?.requested_reviewers),
|
|
191
204
|
headBranch: string(object(pullRequest?.head)?.ref) ?? "",
|
|
192
205
|
baseBranch: string(object(pullRequest?.base)?.ref) ?? ""
|
|
193
206
|
} } : {},
|
|
207
|
+
...reviewRequested && requestedReviewer ? { reviewRequest: {
|
|
208
|
+
reviewer: requestedReviewer,
|
|
209
|
+
factoryReviewer: requestedReviewer === `${this.options.github.slug}[bot]`
|
|
210
|
+
} } : {},
|
|
194
211
|
...object(parsed.payload.review) ? { review: {
|
|
195
212
|
id: number(object(parsed.payload.review)?.id) ?? 0,
|
|
196
213
|
state: string(object(parsed.payload.review)?.state) ?? "unknown",
|
|
@@ -245,6 +262,13 @@ var GithubRules = class {
|
|
|
245
262
|
}
|
|
246
263
|
};
|
|
247
264
|
const RECONCILE_ERROR_SAMPLE_LIMIT = 5;
|
|
265
|
+
function sameStrings(left, right) {
|
|
266
|
+
if (right === void 0) return true;
|
|
267
|
+
if (!Array.isArray(left)) return false;
|
|
268
|
+
const leftValues = new Set(left.flatMap((value) => typeof value === "string" ? [value] : []));
|
|
269
|
+
const rightValues = new Set(right);
|
|
270
|
+
return leftValues.size === rightValues.size && [...leftValues].every((value) => rightValues.has(value));
|
|
271
|
+
}
|
|
248
272
|
/**
|
|
249
273
|
* Extracts the PR number a work item tracks, but only when the item belongs
|
|
250
274
|
* to the given repository. Card URLs pin the repository unambiguously; the
|
|
@@ -285,7 +309,10 @@ function reconciledClosedEvent(repository, pullRequestNumber, state) {
|
|
|
285
309
|
html_url: state.url,
|
|
286
310
|
...state.createdAt ? { created_at: state.createdAt } : {},
|
|
287
311
|
state: "closed",
|
|
312
|
+
draft: state.draft,
|
|
288
313
|
merged: state.merged,
|
|
314
|
+
assignees: (state.assignees ?? []).map((login) => ({ login })),
|
|
315
|
+
requested_reviewers: (state.requestedReviewers ?? []).map((login) => ({ login })),
|
|
289
316
|
head: { ref: state.headBranch },
|
|
290
317
|
base: { ref: state.baseBranch }
|
|
291
318
|
}
|
|
@@ -335,38 +362,69 @@ function createGithubPullRequestReconciler(options, fetchPullRequest) {
|
|
|
335
362
|
const scoped = repositories.filter((repository) => configured.has(`${repository.installationId}\u0000${repository.id}`));
|
|
336
363
|
summary.repositories = scoped.length;
|
|
337
364
|
for (const repository of scoped) {
|
|
338
|
-
let
|
|
365
|
+
let cardsByNumber;
|
|
339
366
|
try {
|
|
340
367
|
const projects = await options.sourceControl.projectRepositories.listByExternalRepository({
|
|
341
368
|
installationExternalId: String(repository.installationId),
|
|
342
369
|
repositoryExternalId: String(repository.id)
|
|
343
370
|
});
|
|
344
371
|
if (projects.length === 0) continue;
|
|
345
|
-
|
|
372
|
+
cardsByNumber = /* @__PURE__ */ new Map();
|
|
346
373
|
for (const project of projects) {
|
|
347
374
|
const items = await options.storage.list({
|
|
348
375
|
orgId: project.orgId,
|
|
349
376
|
factoryProjectId: project.factoryProjectId
|
|
350
377
|
});
|
|
351
378
|
for (const item of items) {
|
|
352
|
-
const stage = item.stages[0];
|
|
353
|
-
if (stage === "done" || stage === "canceled") continue;
|
|
354
379
|
const pullRequestNumber = reconcilablePullRequestNumber(item, repository);
|
|
355
|
-
if (pullRequestNumber)
|
|
380
|
+
if (!pullRequestNumber) continue;
|
|
381
|
+
const stage = item.stages[0];
|
|
382
|
+
const metadata = item.metadata ?? {};
|
|
383
|
+
const hasReconciledMetadata = (metadata.state === "open" || metadata.state === "closed") && typeof metadata.draft === "boolean" && typeof metadata.merged === "boolean" && typeof metadata.author === "string" && Array.isArray(metadata.assignees) && Array.isArray(metadata.requestedReviewers);
|
|
384
|
+
if ((stage === "done" || stage === "canceled") && hasReconciledMetadata) continue;
|
|
385
|
+
const cards = cardsByNumber.get(pullRequestNumber) ?? [];
|
|
386
|
+
cards.push(item);
|
|
387
|
+
cardsByNumber.set(pullRequestNumber, cards);
|
|
356
388
|
}
|
|
357
389
|
}
|
|
358
390
|
} catch (error) {
|
|
359
391
|
recordFailure(repository, error);
|
|
360
392
|
continue;
|
|
361
393
|
}
|
|
362
|
-
for (const pullRequestNumber of
|
|
394
|
+
for (const [pullRequestNumber, cards] of cardsByNumber) try {
|
|
363
395
|
const state = await fetchPullRequest({
|
|
364
396
|
installationId: repository.installationId,
|
|
365
397
|
repository: repository.fullName,
|
|
366
398
|
number: pullRequestNumber
|
|
367
399
|
});
|
|
368
400
|
summary.checked += 1;
|
|
369
|
-
if (!state
|
|
401
|
+
if (!state) continue;
|
|
402
|
+
for (const card of cards) {
|
|
403
|
+
const metadata = card.metadata ?? {};
|
|
404
|
+
const statusChanged = metadata.state !== state.state || metadata.draft !== state.draft || metadata.merged !== state.merged;
|
|
405
|
+
const authorChanged = state.author !== void 0 && metadata.author !== state.author;
|
|
406
|
+
const assigneesChanged = !sameStrings(metadata.assignees, state.assignees);
|
|
407
|
+
const reviewersChanged = !sameStrings(metadata.requestedReviewers, state.requestedReviewers);
|
|
408
|
+
if (!statusChanged && !authorChanged && !assigneesChanged && !reviewersChanged) continue;
|
|
409
|
+
try {
|
|
410
|
+
await options.storage.update({
|
|
411
|
+
orgId: card.orgId,
|
|
412
|
+
id: card.id,
|
|
413
|
+
userId: "factory-rule-dispatcher",
|
|
414
|
+
patch: { metadata: {
|
|
415
|
+
state: state.state,
|
|
416
|
+
draft: state.draft,
|
|
417
|
+
merged: state.merged,
|
|
418
|
+
...state.author ? { author: state.author } : {},
|
|
419
|
+
...state.assignees ? { assignees: state.assignees } : {},
|
|
420
|
+
...state.requestedReviewers ? { requestedReviewers: state.requestedReviewers } : {}
|
|
421
|
+
} }
|
|
422
|
+
});
|
|
423
|
+
} catch (error) {
|
|
424
|
+
recordFailure(repository, error, pullRequestNumber);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
if (state.state !== "closed") continue;
|
|
370
428
|
await rules.ingest(reconciledClosedEvent(repository, pullRequestNumber, state));
|
|
371
429
|
await retireReconciledSubscriptions(options.integrationStorage, repository, pullRequestNumber, state.merged);
|
|
372
430
|
if (state.merged) summary.merged += 1;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rules.js","names":["#ingestProject","#relatedItem"],"sources":["../../../src/integrations/github/rules.ts"],"sourcesContent":["import { resolveFactoryGithubRule } from '../../rules/resolve.js';\nimport type {\n FactoryGithubEventName,\n FactoryGithubRuleContext,\n FactoryRuleActor,\n FactoryRuleDecision,\n FactoryRules,\n} from '../../rules/types.js';\nimport { validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { IntegrationStorageHandle } from '../../storage/domains/integrations/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type {\n ExternalRepositoryProjectTarget,\n SourceControlStorageHandle,\n} from '../../storage/domains/source-control/base.js';\nimport type { WorkItemRow, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\nimport type { GithubRepositoryPermission } from './integration.js';\nimport { changeRequestTargetKey } from './subscriptions.js';\nimport type { ParsedGithubWebhook } from './webhook.js';\n\nconst TRUSTED_PERMISSIONS = new Set(['write', 'admin']);\nconst RULE_TIMEOUT_MS = 5_000;\nconst FACTORY_TRIAGE_COMMENT_MARKER = '<!-- mastra-factory-triage -->';\n\nasync function withRuleTimeout<T>(promise: Promise<T>): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nfunction object(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction string(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction number(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\nfunction boolean(value: unknown): boolean | undefined {\n return typeof value === 'boolean' ? value : undefined;\n}\n\nfunction eventName(parsed: ParsedGithubWebhook): FactoryGithubEventName | undefined {\n const action = string(parsed.payload.action);\n if (parsed.event === 'issues' && action === 'opened') return 'issueOpened';\n if (parsed.event === 'issues' && action === 'edited') {\n const changes = object(parsed.payload.changes);\n return object(changes?.title) || object(changes?.body) ? 'issueEdited' : undefined;\n }\n if (parsed.event === 'issue_comment') {\n const issue = object(parsed.payload.issue);\n if (object(issue?.pull_request)) return undefined;\n if (action === 'created') return 'issueCommentCreated';\n if (action === 'edited') return 'issueCommentEdited';\n if (action === 'deleted') return 'issueCommentDeleted';\n }\n if (parsed.event === 'pull_request' && action === 'opened') return 'pullRequestOpened';\n if (parsed.event === 'pull_request' && action === 'synchronize') return 'pullRequestUpdated';\n if (parsed.event === 'pull_request' && action === 'closed') {\n return boolean(object(parsed.payload.pull_request)?.merged) ? 'pullRequestMerged' : 'pullRequestClosed';\n }\n if (parsed.event === 'pull_request' && action === 'review_requested') return 'pullRequestReviewRequested';\n return undefined;\n}\n\nfunction canonicalSourceKey(kind: 'issue' | 'pull-request', itemNumber: number): string {\n return kind === 'issue' ? `github-issue:${itemNumber}` : `github-pr:${itemNumber}`;\n}\n\nfunction legacySourceKey(repositoryId: number, kind: 'issue' | 'pull-request', itemNumber: number): string {\n return `github:${repositoryId}:${kind}:${itemNumber}`;\n}\n\nfunction provenanceTarget(repositoryId: number, pullRequestNumber: number): string {\n return `factory-pr-provenance:${repositoryId}:${pullRequestNumber}`;\n}\n\nfunction workItemSource(item: WorkItemRow) {\n if (!item.externalSource) return 'manual' as const;\n return item.externalSource.type === 'pull-request' ? ('github-pr' as const) : ('github-issue' as const);\n}\n\nfunction workItemSourceKey(item: WorkItemRow): string | null {\n return item.externalSource?.externalId ?? null;\n}\n\nasync function githubActor(\n github: GithubRulesIntegration,\n input: { installationId: number; repository: string; login: string; factoryAuthored: boolean },\n): Promise<FactoryRuleActor> {\n let trusted = false;\n try {\n const permission = await github.getRepositoryCollaboratorPermission(\n input.installationId,\n input.repository,\n input.login,\n );\n trusted = permission !== undefined && TRUSTED_PERMISSIONS.has(permission);\n } catch {\n trusted = false;\n }\n return { type: 'github', login: input.login, trusted, factoryAuthored: input.factoryAuthored };\n}\n\ninterface FactoryPullRequestProvenanceData {\n kind: 'factory-pr-provenance';\n workItemId: string;\n}\n\nfunction pullRequestProvenance(data: Record<string, unknown> | undefined): FactoryPullRequestProvenanceData | null {\n if (!data || data.kind !== 'factory-pr-provenance' || typeof data.workItemId !== 'string') return null;\n return { kind: 'factory-pr-provenance', workItemId: data.workItemId };\n}\n\nexport interface GithubRulesIntegration {\n readonly slug?: string;\n getRepositoryCollaboratorPermission(\n installationId: number,\n repoFullName: string,\n username: string,\n ): Promise<GithubRepositoryPermission | undefined>;\n}\n\nexport interface GithubRulesOptions {\n github: GithubRulesIntegration;\n sourceControl: SourceControlStorageHandle;\n /** Integration-scoped storage; provenance rows are validated at read. */\n integrationStorage: IntegrationStorageHandle;\n projects: FactoryProjectsStorage;\n storage: WorkItemsStorage;\n rules: FactoryRules;\n}\n\nexport class GithubRules {\n constructor(private readonly options: GithubRulesOptions) {}\n\n async ingest(parsed: ParsedGithubWebhook): Promise<{ status: 'ignored' | 'committed' | 'replayed' | 'missing' }> {\n const event = eventName(parsed);\n const repository = object(parsed.payload.repository);\n const installationId = number(object(parsed.payload.installation)?.id);\n const repositoryId = number(repository?.id);\n const repositoryName = string(repository?.full_name);\n const login = string(object(parsed.payload.sender)?.login);\n if (!event || !installationId || !repositoryId || !repositoryName || !login) return { status: 'ignored' };\n\n const projects = await this.options.sourceControl.projectRepositories.listByExternalRepository({\n installationExternalId: String(installationId),\n repositoryExternalId: String(repositoryId),\n });\n if (projects.length === 0) return { status: 'ignored' };\n const results = [];\n for (const project of projects) {\n results.push(\n await this.#ingestProject(parsed, event, installationId, repositoryId, repositoryName, login, project),\n );\n }\n if (results.some(result => result.status === 'committed')) return { status: 'committed' };\n if (results.some(result => result.status === 'replayed')) return { status: 'replayed' };\n return results[0] ?? { status: 'ignored' };\n }\n\n async #ingestProject(\n parsed: ParsedGithubWebhook,\n event: FactoryGithubEventName,\n installationId: number,\n repositoryId: number,\n repositoryName: string,\n login: string,\n project: ExternalRepositoryProjectTarget,\n ): Promise<{ status: 'ignored' | 'committed' | 'replayed' | 'missing' }> {\n const factoryProject = await this.options.projects.get({\n orgId: project.orgId,\n id: project.factoryProjectId,\n });\n if (!factoryProject) return { status: 'missing' };\n const issue = object(parsed.payload.issue);\n const issueComment = object(parsed.payload.comment);\n const changes = object(parsed.payload.changes);\n const pullRequest = object(parsed.payload.pull_request);\n const issueNumber = number(issue?.number);\n const pullRequestNumber = number(pullRequest?.number);\n const provenance = pullRequestNumber\n ? pullRequestProvenance(\n (\n await this.options.integrationStorage.subscriptions.listByTarget(\n provenanceTarget(repositoryId, pullRequestNumber),\n { status: 'active' },\n )\n ).find(subscription => subscription.orgId === project.orgId)?.data,\n )\n : null;\n const relatedItem = await this.#relatedItem(\n project.orgId,\n project.factoryProjectId,\n repositoryId,\n issueNumber,\n pullRequestNumber,\n string(object(pullRequest?.head)?.ref),\n provenance,\n );\n const actor = await githubActor(this.options.github, {\n installationId,\n repository: repositoryName,\n login,\n factoryAuthored: provenance !== null || login === `${this.options.github.slug}[bot]`,\n });\n if (\n actor.type === 'github' &&\n actor.factoryAuthored &&\n (event === 'issueCommentCreated' || event === 'issueCommentEdited') &&\n string(issueComment?.body)?.includes(FACTORY_TRIAGE_COMMENT_MARKER)\n ) {\n return { status: 'ignored' };\n }\n const context: FactoryGithubRuleContext = {\n tenant: { orgId: project.orgId, projectId: project.factoryProjectId },\n actor,\n ingress: { type: 'github', id: `${installationId}:${parsed.deliveryId}` },\n cause: `github.${event}`,\n causalChain: [],\n ruleSetVersion: this.options.rules.version,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: workItemSource(relatedItem),\n sourceKey: workItemSourceKey(relatedItem),\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n },\n board: relatedItem.externalSource?.type === 'pull-request' ? ('review' as const) : ('work' as const),\n itemRevision: relatedItem.revision,\n }\n : {}),\n event,\n deliveryId: parsed.deliveryId,\n factory: { createdAt: factoryProject.createdAt.toISOString() },\n repository: { id: repositoryId, fullName: repositoryName },\n ...(issueNumber && string(issue?.title) && string(issue?.html_url)\n ? {\n issue: {\n number: issueNumber,\n title: string(issue?.title)!,\n url: string(issue?.html_url)!,\n ...(string(issue?.created_at) ? { createdAt: string(issue?.created_at) } : {}),\n ...(string(issue?.updated_at) ? { updatedAt: string(issue?.updated_at) } : {}),\n },\n }\n : {}),\n ...(event === 'issueEdited'\n ? { issueChange: { title: Boolean(object(changes?.title)), body: Boolean(object(changes?.body)) } }\n : {}),\n ...(number(issueComment?.id)\n ? {\n issueComment: {\n id: number(issueComment?.id)!,\n ...(string(issueComment?.body) ? { body: string(issueComment?.body) } : {}),\n ...(string(issueComment?.html_url) ? { url: string(issueComment?.html_url) } : {}),\n ...(string(object(issueComment?.user)?.login) ? { author: string(object(issueComment?.user)?.login) } : {}),\n ...(string(object(issueComment?.user)?.type) ? { authorType: string(object(issueComment?.user)?.type) } : {}),\n ...(string(issueComment?.created_at) ? { createdAt: string(issueComment?.created_at) } : {}),\n ...(string(issueComment?.updated_at) ? { updatedAt: string(issueComment?.updated_at) } : {}),\n },\n }\n : {}),\n ...(pullRequestNumber && string(pullRequest?.title) && string(pullRequest?.html_url)\n ? {\n pullRequest: {\n number: pullRequestNumber,\n title: string(pullRequest?.title)!,\n url: string(pullRequest?.html_url)!,\n ...(string(pullRequest?.created_at) ? { createdAt: string(pullRequest?.created_at) } : {}),\n state: string(pullRequest?.state) === 'closed' ? ('closed' as const) : ('open' as const),\n merged: boolean(pullRequest?.merged) ?? false,\n headBranch: string(object(pullRequest?.head)?.ref) ?? '',\n baseBranch: string(object(pullRequest?.base)?.ref) ?? '',\n },\n }\n : {}),\n ...(object(parsed.payload.review)\n ? {\n review: {\n id: number(object(parsed.payload.review)?.id) ?? 0,\n state: string(object(parsed.payload.review)?.state) ?? 'unknown',\n url: string(object(parsed.payload.review)?.html_url) ?? '',\n },\n }\n : {}),\n };\n\n const rule = resolveFactoryGithubRule(this.options.rules, event);\n let decision: FactoryRuleDecision | void;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => ({ ...entry }));\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory GitHub rule failed.',\n };\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: project.orgId,\n factoryProjectId: project.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: `${installationId}:${parsed.deliveryId}`, triggerType: `github.${event}` },\n ruleSetVersion: this.options.rules.version,\n expectedRevision: relatedItem?.revision ?? null,\n actor: { ...actor },\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n return { status: committed.status };\n }\n\n async #relatedItem(\n orgId: string,\n projectId: string,\n repositoryId: number,\n issueNumber: number | undefined,\n pullRequestNumber: number | undefined,\n pullRequestHeadBranch: string | undefined,\n provenance: FactoryPullRequestProvenanceData | null,\n ): Promise<WorkItemRow | undefined> {\n const items = await this.options.storage.list({ orgId, factoryProjectId: projectId });\n if (provenance) return items.find(item => item.id === provenance.workItemId);\n if (issueNumber) {\n return (\n items.find(item => item.externalSource?.externalId === canonicalSourceKey('issue', issueNumber)) ??\n items.find(item => item.externalSource?.externalId === legacySourceKey(repositoryId, 'issue', issueNumber))\n );\n }\n if (pullRequestNumber) {\n return (\n items.find(item => item.externalSource?.externalId === canonicalSourceKey('pull-request', pullRequestNumber)) ??\n items.find(\n item => item.externalSource?.externalId === legacySourceKey(repositoryId, 'pull-request', pullRequestNumber),\n ) ??\n // Provenance fallback: a PR pushed from a work item's session branch\n // belongs to that item even when no gh-pr-create provenance was\n // recorded (session predating state seeding, or the PR was opened\n // outside the tracked tool call). Session branches are per-item\n // (`factory/issue-N`), so a head-branch match is unambiguous.\n (pullRequestHeadBranch\n ? items.find(\n item =>\n item.externalSource?.type !== 'pull-request' &&\n Object.values(item.sessions).some(session => session.branch === pullRequestHeadBranch),\n )\n : undefined)\n );\n }\n return undefined;\n }\n}\n\nexport interface ReconcilePullRequestState {\n title: string;\n url: string;\n state: 'open' | 'closed';\n merged: boolean;\n headBranch: string;\n baseBranch: string;\n createdAt?: string;\n mergedBy?: string;\n}\n\nexport type GithubPullRequestFetcher = (input: {\n installationId: number;\n repository: string;\n number: number;\n}) => Promise<ReconcilePullRequestState | undefined>;\n\nexport interface ReconcileRepository {\n id: number;\n fullName: string;\n installationId: number;\n}\n\nexport interface ReconcileSweepSummary {\n /** Factory-configured repositories included in the sweep. */\n repositories: number;\n /** PRs whose live state was fetched from GitHub. */\n checked: number;\n /** Missed merges replayed through the rules ingress. */\n merged: number;\n /** Missed closes-without-merge replayed through the rules ingress. */\n closed: number;\n /** PRs (or whole repositories) skipped because of an error. */\n failed: number;\n /** Error samples with context, capped at {@link RECONCILE_ERROR_SAMPLE_LIMIT}. */\n errors: Array<{ repository: string; pullRequestNumber?: number; error: string }>;\n}\n\nexport type GithubPullRequestReconciler = (repositories: ReconcileRepository[]) => Promise<ReconcileSweepSummary>;\n\nconst RECONCILE_ERROR_SAMPLE_LIMIT = 5;\n\n/**\n * Extracts the PR number a work item tracks, but only when the item belongs\n * to the given repository. Card URLs pin the repository unambiguously; the\n * legacy source key embeds the repository id. Canonical keys (`github-pr:N`)\n * carry no repository, so they are only trusted when the item has no URL —\n * a project mapped to multiple repositories must not reconcile one repo's\n * card against another repo's PR number.\n */\nfunction reconcilablePullRequestNumber(item: WorkItemRow, repository: ReconcileRepository): number | undefined {\n if (item.externalSource?.type !== 'pull-request') return undefined;\n const url = item.externalSource.url;\n if (url) {\n const match = /^https?:\\/\\/[^/]+\\/(.+)\\/pull\\/(\\d+)(?:[/?#]|$)/.exec(url);\n if (!match) return undefined;\n return match[1] === repository.fullName ? Number(match[2]) : undefined;\n }\n const externalId = item.externalSource.externalId;\n const legacy = /^github:(\\d+):pull-request:(\\d+)$/.exec(externalId);\n if (legacy) return Number(legacy[1]) === repository.id ? Number(legacy[2]) : undefined;\n const canonical = /^github-pr:(\\d+)$/.exec(externalId);\n return canonical ? Number(canonical[1]) : undefined;\n}\n\nexport function reconciledClosedEvent(\n repository: ReconcileRepository,\n pullRequestNumber: number,\n state: ReconcilePullRequestState,\n): ParsedGithubWebhook {\n return {\n event: 'pull_request',\n // Stable per (repository, PR, outcome): the ingress dedupe makes repeat\n // reconcile cycles replay instead of re-committing decisions.\n deliveryId: `reconcile:${repository.id}:pull-request:${pullRequestNumber}:${state.merged ? 'merged' : 'closed'}`,\n payload: {\n action: 'closed',\n installation: { id: repository.installationId },\n repository: { id: repository.id, full_name: repository.fullName },\n sender: { login: state.mergedBy ?? 'github' },\n pull_request: {\n number: pullRequestNumber,\n title: state.title,\n html_url: state.url,\n ...(state.createdAt ? { created_at: state.createdAt } : {}),\n state: 'closed',\n merged: state.merged,\n head: { ref: state.headBranch },\n base: { ref: state.baseBranch },\n },\n },\n };\n}\n\n/**\n * The webhook handler retires subscriptions itself; the sweep replays only the\n * rules ingress, so without this the thread's PR chip and the workspace row\n * stay `open` forever on a deployment GitHub cannot reach.\n */\nasync function retireReconciledSubscriptions(\n storage: IntegrationStorageHandle,\n repository: ReconcileRepository,\n pullRequestNumber: number,\n merged: boolean,\n): Promise<void> {\n const target = changeRequestTargetKey({\n installationExternalId: String(repository.installationId),\n repositoryExternalId: String(repository.id),\n changeRequestId: String(pullRequestNumber),\n });\n const rows = await storage.subscriptions.listByTarget(target);\n await Promise.all(\n rows\n .filter(row => row.status === 'open')\n .map(row => storage.subscriptions.updateStatus(row.id, merged ? 'merged' : 'closed')),\n );\n}\n\n/**\n * State-based safety net for merge signals: webhooks and event-log tailing\n * can miss a merge (cursor gaps, downtime, terminally failed decisions), so\n * this sweep compares still-open PR cards against actual GitHub state and\n * replays the merge through the normal rules ingress when they disagree.\n */\nexport function createGithubPullRequestReconciler(\n options: GithubRulesOptions,\n fetchPullRequest: GithubPullRequestFetcher,\n): GithubPullRequestReconciler {\n const rules = new GithubRules(options);\n return async repositories => {\n const summary: ReconcileSweepSummary = { repositories: 0, checked: 0, merged: 0, closed: 0, failed: 0, errors: [] };\n const recordFailure = (repository: ReconcileRepository, error: unknown, pullRequestNumber?: number) => {\n summary.failed += 1;\n if (summary.errors.length < RECONCILE_ERROR_SAMPLE_LIMIT) {\n summary.errors.push({\n repository: repository.fullName,\n ...(pullRequestNumber === undefined ? {} : { pullRequestNumber }),\n error: error instanceof Error ? error.message : String(error),\n });\n }\n };\n // An installation can expose hundreds of repositories; only the ones\n // actually linked to a factory project can have cards to reconcile, so\n // scope the sweep to those up front instead of probing each repository.\n const configured = new Set(\n (await options.sourceControl.projectRepositories.listConfiguredExternalKeys()).map(\n key => `${key.installationExternalId}\\u0000${key.repositoryExternalId}`,\n ),\n );\n const scoped = repositories.filter(repository =>\n configured.has(`${repository.installationId}\\u0000${repository.id}`),\n );\n summary.repositories = scoped.length;\n for (const repository of scoped) {\n // One broken repository (or a failing token exchange for its\n // installation) must not abort the sweep for the others.\n let numbers: Set<number>;\n try {\n const projects = await options.sourceControl.projectRepositories.listByExternalRepository({\n installationExternalId: String(repository.installationId),\n repositoryExternalId: String(repository.id),\n });\n if (projects.length === 0) continue;\n numbers = new Set<number>();\n for (const project of projects) {\n const items = await options.storage.list({\n orgId: project.orgId,\n factoryProjectId: project.factoryProjectId,\n });\n for (const item of items) {\n const stage = item.stages[0];\n if (stage === 'done' || stage === 'canceled') continue;\n const pullRequestNumber = reconcilablePullRequestNumber(item, repository);\n if (pullRequestNumber) numbers.add(pullRequestNumber);\n }\n }\n } catch (error) {\n recordFailure(repository, error);\n continue;\n }\n for (const pullRequestNumber of numbers) {\n try {\n const state = await fetchPullRequest({\n installationId: repository.installationId,\n repository: repository.fullName,\n number: pullRequestNumber,\n });\n summary.checked += 1;\n if (!state || state.state !== 'closed') continue;\n await rules.ingest(reconciledClosedEvent(repository, pullRequestNumber, state));\n await retireReconciledSubscriptions(options.integrationStorage, repository, pullRequestNumber, state.merged);\n if (state.merged) summary.merged += 1;\n else summary.closed += 1;\n } catch (error) {\n recordFailure(repository, error, pullRequestNumber);\n }\n }\n }\n return summary;\n };\n}\n\nfunction githubRulesOptions(\n github: GithubRulesIntegration,\n context: IntegrationContext,\n): GithubRulesOptions | undefined {\n if (!context.rules) return undefined;\n return {\n github,\n sourceControl: context.storage.sourceControl,\n integrationStorage: context.storage.generic,\n projects: context.storage.projects,\n storage: context.rules.workItems,\n rules: context.rules.config,\n };\n}\n\nexport function attachGithubRules(\n github: GithubRulesIntegration,\n context: IntegrationContext,\n): ((event: ParsedGithubWebhook) => Promise<unknown>) | undefined {\n const options = githubRulesOptions(github, context);\n if (!options) return undefined;\n const rules = new GithubRules(options);\n return event => rules.ingest(event);\n}\n\nexport function attachGithubReconciler(\n github: GithubRulesIntegration,\n context: IntegrationContext,\n fetchPullRequest: GithubPullRequestFetcher,\n): GithubPullRequestReconciler | undefined {\n const options = githubRulesOptions(github, context);\n if (!options) return undefined;\n return createGithubPullRequestReconciler(options, fetchPullRequest);\n}\n"],"mappings":";;;;AAqBA,MAAM,sCAAsB,IAAI,IAAI,CAAC,SAAS,OAAO,CAAC;AACtD,MAAM,kBAAkB;AACxB,MAAM,gCAAgC;AAEtC,eAAe,gBAAmB,SAAiC;CACjE,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,QAAQ,KAAK,CACxB,SACA,IAAI,SAAgB,GAAG,WAAW;GAChC,UAAU,iBAAiB,uBAAO,IAAI,MAAM,sBAAsB,CAAC,GAAG,eAAe;EACvF,CAAC,CACH,CAAC;CACH,UAAU;EACR,IAAI,SAAS,aAAa,OAAO;CACnC;AACF;AAEA,SAAS,OAAO,OAAqD;CACnE,OAAO,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IAAK,QAAoC,KAAA;AAC5G;AAEA,SAAS,OAAO,OAAoC;CAClD,OAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ,KAAA;AACjE;AAEA,SAAS,OAAO,OAAoC;CAClD,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;AACvE;AAEA,SAAS,QAAQ,OAAqC;CACpD,OAAO,OAAO,UAAU,YAAY,QAAQ,KAAA;AAC9C;AAEA,SAAS,UAAU,QAAiE;CAClF,MAAM,SA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YAAY,mBAAmB,KAAK,CAAC;IAC9E,MAAM,8BAA8B,QAAQ,oBAAoB,YAAY,mBAAmB,MAAM,MAAM;IAC3G,IAAI,MAAM,QAAQ,QAAQ,UAAU;SAC/B,QAAQ,UAAU;GACzB,SAAS,OAAO;IACd,cAAc,YAAY,OAAO,iBAAiB;GACpD;EAEJ;EACA,OAAO;CACT;AACF;AAEA,SAAS,mBACP,QACA,SACgC;CAChC,IAAI,CAAC,QAAQ,OAAO,OAAO,KAAA;CAC3B,OAAO;EACL;EACA,eAAe,QAAQ,QAAQ;EAC/B,oBAAoB,QAAQ,QAAQ;EACpC,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ,MAAM;EACvB,OAAO,QAAQ,MAAM;CACvB;AACF;AAEA,SAAgB,kBACd,QACA,SACgE;CAChE,MAAM,UAAU,mBAAmB,QAAQ,OAAO;CAClD,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,MAAM,QAAQ,IAAI,YAAY,OAAO;CACrC,QAAO,UAAS,MAAM,OAAO,KAAK;AACpC;AAEA,SAAgB,uBACd,QACA,SACA,kBACyC;CACzC,MAAM,UAAU,mBAAmB,QAAQ,OAAO;CAClD,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,OAAO,kCAAkC,SAAS,gBAAgB;AACpE"}
|
|
1
|
+
{"version":3,"file":"rules.js","names":["#ingestProject","#relatedItem"],"sources":["../../../src/integrations/github/rules.ts"],"sourcesContent":["import { resolveFactoryGithubRule } from '../../rules/resolve.js';\nimport type {\n FactoryGithubEventName,\n FactoryGithubRuleContext,\n FactoryRuleActor,\n FactoryRuleDecision,\n FactoryRules,\n} from '../../rules/types.js';\nimport { validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { IntegrationStorageHandle } from '../../storage/domains/integrations/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type {\n ExternalRepositoryProjectTarget,\n SourceControlStorageHandle,\n} from '../../storage/domains/source-control/base.js';\nimport type { WorkItemRow, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\nimport type { GithubRepositoryPermission } from './integration.js';\nimport { changeRequestTargetKey } from './subscriptions.js';\nimport type { ParsedGithubWebhook } from './webhook.js';\n\nconst TRUSTED_PERMISSIONS = new Set(['write', 'admin']);\nconst RULE_TIMEOUT_MS = 5_000;\nconst FACTORY_TRIAGE_COMMENT_MARKER = '<!-- mastra-factory-triage -->';\n\nasync function withRuleTimeout<T>(promise: Promise<T>): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nfunction object(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction string(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction number(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\nfunction boolean(value: unknown): boolean | undefined {\n return typeof value === 'boolean' ? value : undefined;\n}\n\nfunction actorLogins(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap(actor => {\n const login = string(object(actor)?.login);\n return login ? [login] : [];\n });\n}\n\nfunction eventName(parsed: ParsedGithubWebhook): FactoryGithubEventName | undefined {\n const action = string(parsed.payload.action);\n if (parsed.event === 'issues' && action === 'opened') return 'issueOpened';\n if (parsed.event === 'issues' && action === 'edited') {\n const changes = object(parsed.payload.changes);\n return object(changes?.title) || object(changes?.body) ? 'issueEdited' : undefined;\n }\n if (parsed.event === 'issue_comment') {\n const issue = object(parsed.payload.issue);\n if (object(issue?.pull_request)) return undefined;\n if (action === 'created') return 'issueCommentCreated';\n if (action === 'edited') return 'issueCommentEdited';\n if (action === 'deleted') return 'issueCommentDeleted';\n }\n if (parsed.event === 'pull_request' && action === 'opened') return 'pullRequestOpened';\n if (parsed.event === 'pull_request' && action === 'synchronize') return 'pullRequestUpdated';\n if (parsed.event === 'pull_request' && action === 'closed') {\n return boolean(object(parsed.payload.pull_request)?.merged) ? 'pullRequestMerged' : 'pullRequestClosed';\n }\n if (parsed.event === 'pull_request' && action === 'review_requested') return 'pullRequestReviewRequested';\n return undefined;\n}\n\nfunction canonicalSourceKey(kind: 'issue' | 'pull-request', itemNumber: number): string {\n return kind === 'issue' ? `github-issue:${itemNumber}` : `github-pr:${itemNumber}`;\n}\n\nfunction legacySourceKey(repositoryId: number, kind: 'issue' | 'pull-request', itemNumber: number): string {\n return `github:${repositoryId}:${kind}:${itemNumber}`;\n}\n\nfunction provenanceTarget(repositoryId: number, pullRequestNumber: number): string {\n return `factory-pr-provenance:${repositoryId}:${pullRequestNumber}`;\n}\n\nfunction workItemSource(item: WorkItemRow) {\n if (!item.externalSource) return 'manual' as const;\n return item.externalSource.type === 'pull-request' ? ('github-pr' as const) : ('github-issue' as const);\n}\n\nfunction workItemSourceKey(item: WorkItemRow): string | null {\n return item.externalSource?.externalId ?? null;\n}\n\nasync function githubActor(\n github: GithubRulesIntegration,\n input: { installationId: number; repository: string; login: string; factoryAuthored: boolean },\n): Promise<FactoryRuleActor> {\n let trusted = false;\n try {\n const permission = await github.getRepositoryCollaboratorPermission(\n input.installationId,\n input.repository,\n input.login,\n );\n trusted = permission !== undefined && TRUSTED_PERMISSIONS.has(permission);\n } catch {\n trusted = false;\n }\n return { type: 'github', login: input.login, trusted, factoryAuthored: input.factoryAuthored };\n}\n\ninterface FactoryPullRequestProvenanceData {\n kind: 'factory-pr-provenance';\n workItemId: string;\n}\n\nfunction pullRequestProvenance(data: Record<string, unknown> | undefined): FactoryPullRequestProvenanceData | null {\n if (!data || data.kind !== 'factory-pr-provenance' || typeof data.workItemId !== 'string') return null;\n return { kind: 'factory-pr-provenance', workItemId: data.workItemId };\n}\n\nexport interface GithubRulesIntegration {\n readonly slug?: string;\n getRepositoryCollaboratorPermission(\n installationId: number,\n repoFullName: string,\n username: string,\n ): Promise<GithubRepositoryPermission | undefined>;\n}\n\nexport interface GithubRulesOptions {\n github: GithubRulesIntegration;\n sourceControl: SourceControlStorageHandle;\n /** Integration-scoped storage; provenance rows are validated at read. */\n integrationStorage: IntegrationStorageHandle;\n projects: FactoryProjectsStorage;\n storage: WorkItemsStorage;\n rules: FactoryRules;\n}\n\nexport class GithubRules {\n constructor(private readonly options: GithubRulesOptions) {}\n\n async ingest(parsed: ParsedGithubWebhook): Promise<{ status: 'ignored' | 'committed' | 'replayed' | 'missing' }> {\n const event = eventName(parsed);\n const repository = object(parsed.payload.repository);\n const installationId = number(object(parsed.payload.installation)?.id);\n const repositoryId = number(repository?.id);\n const repositoryName = string(repository?.full_name);\n const login = string(object(parsed.payload.sender)?.login);\n if (!event || !installationId || !repositoryId || !repositoryName || !login) return { status: 'ignored' };\n\n const projects = await this.options.sourceControl.projectRepositories.listByExternalRepository({\n installationExternalId: String(installationId),\n repositoryExternalId: String(repositoryId),\n });\n if (projects.length === 0) return { status: 'ignored' };\n const results = [];\n for (const project of projects) {\n results.push(\n await this.#ingestProject(parsed, event, installationId, repositoryId, repositoryName, login, project),\n );\n }\n if (results.some(result => result.status === 'committed')) return { status: 'committed' };\n if (results.some(result => result.status === 'replayed')) return { status: 'replayed' };\n return results[0] ?? { status: 'ignored' };\n }\n\n async #ingestProject(\n parsed: ParsedGithubWebhook,\n event: FactoryGithubEventName,\n installationId: number,\n repositoryId: number,\n repositoryName: string,\n login: string,\n project: ExternalRepositoryProjectTarget,\n ): Promise<{ status: 'ignored' | 'committed' | 'replayed' | 'missing' }> {\n const factoryProject = await this.options.projects.get({\n orgId: project.orgId,\n id: project.factoryProjectId,\n });\n if (!factoryProject) return { status: 'missing' };\n const issue = object(parsed.payload.issue);\n const issueComment = object(parsed.payload.comment);\n const changes = object(parsed.payload.changes);\n const pullRequest = object(parsed.payload.pull_request);\n const issueNumber = number(issue?.number);\n const pullRequestNumber = number(pullRequest?.number);\n const provenance = pullRequestNumber\n ? pullRequestProvenance(\n (\n await this.options.integrationStorage.subscriptions.listByTarget(\n provenanceTarget(repositoryId, pullRequestNumber),\n { status: 'active' },\n )\n ).find(subscription => subscription.orgId === project.orgId)?.data,\n )\n : null;\n // A review re-request targets the PR's own Review card, not the Work item\n // that provenance would bind the event to — and the sender is whoever\n // clicked re-request, so a Factory-authored PR must not brand a human\n // requester as factory-authored.\n const reviewRequested = event === 'pullRequestReviewRequested';\n const requestedReviewer = string(object(parsed.payload.requested_reviewer)?.login);\n const relatedItem = await this.#relatedItem(\n project.orgId,\n project.factoryProjectId,\n repositoryId,\n issueNumber,\n pullRequestNumber,\n string(object(pullRequest?.head)?.ref),\n reviewRequested ? null : provenance,\n );\n const actor = await githubActor(this.options.github, {\n installationId,\n repository: repositoryName,\n login,\n factoryAuthored: (!reviewRequested && provenance !== null) || login === `${this.options.github.slug}[bot]`,\n });\n if (\n actor.type === 'github' &&\n actor.factoryAuthored &&\n (event === 'issueCommentCreated' || event === 'issueCommentEdited') &&\n string(issueComment?.body)?.includes(FACTORY_TRIAGE_COMMENT_MARKER)\n ) {\n return { status: 'ignored' };\n }\n const context: FactoryGithubRuleContext = {\n tenant: { orgId: project.orgId, projectId: project.factoryProjectId },\n actor,\n ingress: { type: 'github', id: `${installationId}:${parsed.deliveryId}` },\n cause: `github.${event}`,\n causalChain: [],\n ruleSetVersion: this.options.rules.version,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: workItemSource(relatedItem),\n sourceKey: workItemSourceKey(relatedItem),\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n },\n board: relatedItem.externalSource?.type === 'pull-request' ? ('review' as const) : ('work' as const),\n itemRevision: relatedItem.revision,\n }\n : {}),\n event,\n deliveryId: parsed.deliveryId,\n factory: { createdAt: factoryProject.createdAt.toISOString() },\n repository: { id: repositoryId, fullName: repositoryName },\n ...(issueNumber && string(issue?.title) && string(issue?.html_url)\n ? {\n issue: {\n number: issueNumber,\n title: string(issue?.title)!,\n url: string(issue?.html_url)!,\n ...(string(issue?.created_at) ? { createdAt: string(issue?.created_at) } : {}),\n ...(string(issue?.updated_at) ? { updatedAt: string(issue?.updated_at) } : {}),\n assignees: actorLogins(issue?.assignees),\n },\n }\n : {}),\n ...(event === 'issueEdited'\n ? { issueChange: { title: Boolean(object(changes?.title)), body: Boolean(object(changes?.body)) } }\n : {}),\n ...(number(issueComment?.id)\n ? {\n issueComment: {\n id: number(issueComment?.id)!,\n ...(string(issueComment?.body) ? { body: string(issueComment?.body) } : {}),\n ...(string(issueComment?.html_url) ? { url: string(issueComment?.html_url) } : {}),\n ...(string(object(issueComment?.user)?.login) ? { author: string(object(issueComment?.user)?.login) } : {}),\n ...(string(object(issueComment?.user)?.type) ? { authorType: string(object(issueComment?.user)?.type) } : {}),\n ...(string(issueComment?.created_at) ? { createdAt: string(issueComment?.created_at) } : {}),\n ...(string(issueComment?.updated_at) ? { updatedAt: string(issueComment?.updated_at) } : {}),\n },\n }\n : {}),\n ...(pullRequestNumber && string(pullRequest?.title) && string(pullRequest?.html_url)\n ? {\n pullRequest: {\n number: pullRequestNumber,\n title: string(pullRequest?.title)!,\n url: string(pullRequest?.html_url)!,\n ...(string(pullRequest?.created_at) ? { createdAt: string(pullRequest?.created_at) } : {}),\n state: string(pullRequest?.state) === 'closed' ? ('closed' as const) : ('open' as const),\n draft: boolean(pullRequest?.draft) ?? false,\n merged: boolean(pullRequest?.merged) ?? false,\n assignees: actorLogins(pullRequest?.assignees),\n requestedReviewers: actorLogins(pullRequest?.requested_reviewers),\n headBranch: string(object(pullRequest?.head)?.ref) ?? '',\n baseBranch: string(object(pullRequest?.base)?.ref) ?? '',\n },\n }\n : {}),\n ...(reviewRequested && requestedReviewer\n ? {\n reviewRequest: {\n reviewer: requestedReviewer,\n factoryReviewer: requestedReviewer === `${this.options.github.slug}[bot]`,\n },\n }\n : {}),\n ...(object(parsed.payload.review)\n ? {\n review: {\n id: number(object(parsed.payload.review)?.id) ?? 0,\n state: string(object(parsed.payload.review)?.state) ?? 'unknown',\n url: string(object(parsed.payload.review)?.html_url) ?? '',\n },\n }\n : {}),\n };\n\n const rule = resolveFactoryGithubRule(this.options.rules, event);\n let decision: FactoryRuleDecision | void;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => ({ ...entry }));\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory GitHub rule failed.',\n };\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: project.orgId,\n factoryProjectId: project.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: `${installationId}:${parsed.deliveryId}`, triggerType: `github.${event}` },\n ruleSetVersion: this.options.rules.version,\n expectedRevision: relatedItem?.revision ?? null,\n actor: { ...actor },\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n return { status: committed.status };\n }\n\n async #relatedItem(\n orgId: string,\n projectId: string,\n repositoryId: number,\n issueNumber: number | undefined,\n pullRequestNumber: number | undefined,\n pullRequestHeadBranch: string | undefined,\n provenance: FactoryPullRequestProvenanceData | null,\n ): Promise<WorkItemRow | undefined> {\n const items = await this.options.storage.list({ orgId, factoryProjectId: projectId });\n if (provenance) return items.find(item => item.id === provenance.workItemId);\n if (issueNumber) {\n return (\n items.find(item => item.externalSource?.externalId === canonicalSourceKey('issue', issueNumber)) ??\n items.find(item => item.externalSource?.externalId === legacySourceKey(repositoryId, 'issue', issueNumber))\n );\n }\n if (pullRequestNumber) {\n return (\n items.find(item => item.externalSource?.externalId === canonicalSourceKey('pull-request', pullRequestNumber)) ??\n items.find(\n item => item.externalSource?.externalId === legacySourceKey(repositoryId, 'pull-request', pullRequestNumber),\n ) ??\n // Provenance fallback: a PR pushed from a work item's session branch\n // belongs to that item even when no gh-pr-create provenance was\n // recorded (session predating state seeding, or the PR was opened\n // outside the tracked tool call). Session branches are per-item\n // (`factory/issue-N`), so a head-branch match is unambiguous.\n (pullRequestHeadBranch\n ? items.find(\n item =>\n item.externalSource?.type !== 'pull-request' &&\n Object.values(item.sessions).some(session => session.branch === pullRequestHeadBranch),\n )\n : undefined)\n );\n }\n return undefined;\n }\n}\n\nexport interface ReconcilePullRequestState {\n title: string;\n url: string;\n state: 'open' | 'closed';\n draft: boolean;\n merged: boolean;\n assignees?: string[];\n requestedReviewers?: string[];\n headBranch: string;\n baseBranch: string;\n author?: string;\n createdAt?: string;\n mergedBy?: string;\n}\n\nexport type GithubPullRequestFetcher = (input: {\n installationId: number;\n repository: string;\n number: number;\n}) => Promise<ReconcilePullRequestState | undefined>;\n\nexport interface ReconcileRepository {\n id: number;\n fullName: string;\n installationId: number;\n}\n\nexport interface ReconcileSweepSummary {\n /** Factory-configured repositories included in the sweep. */\n repositories: number;\n /** PRs whose live state was fetched from GitHub. */\n checked: number;\n /** Missed merges replayed through the rules ingress. */\n merged: number;\n /** Missed closes-without-merge replayed through the rules ingress. */\n closed: number;\n /** PRs (or whole repositories) skipped because of an error. */\n failed: number;\n /** Error samples with context, capped at {@link RECONCILE_ERROR_SAMPLE_LIMIT}. */\n errors: Array<{ repository: string; pullRequestNumber?: number; error: string }>;\n}\n\nexport type GithubPullRequestReconciler = (repositories: ReconcileRepository[]) => Promise<ReconcileSweepSummary>;\n\nconst RECONCILE_ERROR_SAMPLE_LIMIT = 5;\n\nfunction sameStrings(left: unknown, right: string[] | undefined): boolean {\n if (right === undefined) return true;\n if (!Array.isArray(left)) return false;\n const leftValues = new Set(left.flatMap(value => (typeof value === 'string' ? [value] : [])));\n const rightValues = new Set(right);\n return leftValues.size === rightValues.size && [...leftValues].every(value => rightValues.has(value));\n}\n\n/**\n * Extracts the PR number a work item tracks, but only when the item belongs\n * to the given repository. Card URLs pin the repository unambiguously; the\n * legacy source key embeds the repository id. Canonical keys (`github-pr:N`)\n * carry no repository, so they are only trusted when the item has no URL —\n * a project mapped to multiple repositories must not reconcile one repo's\n * card against another repo's PR number.\n */\nfunction reconcilablePullRequestNumber(item: WorkItemRow, repository: ReconcileRepository): number | undefined {\n if (item.externalSource?.type !== 'pull-request') return undefined;\n const url = item.externalSource.url;\n if (url) {\n const match = /^https?:\\/\\/[^/]+\\/(.+)\\/pull\\/(\\d+)(?:[/?#]|$)/.exec(url);\n if (!match) return undefined;\n return match[1] === repository.fullName ? Number(match[2]) : undefined;\n }\n const externalId = item.externalSource.externalId;\n const legacy = /^github:(\\d+):pull-request:(\\d+)$/.exec(externalId);\n if (legacy) return Number(legacy[1]) === repository.id ? Number(legacy[2]) : undefined;\n const canonical = /^github-pr:(\\d+)$/.exec(externalId);\n return canonical ? Number(canonical[1]) : undefined;\n}\n\nexport function reconciledClosedEvent(\n repository: ReconcileRepository,\n pullRequestNumber: number,\n state: ReconcilePullRequestState,\n): ParsedGithubWebhook {\n return {\n event: 'pull_request',\n // Stable per (repository, PR, outcome): the ingress dedupe makes repeat\n // reconcile cycles replay instead of re-committing decisions.\n deliveryId: `reconcile:${repository.id}:pull-request:${pullRequestNumber}:${state.merged ? 'merged' : 'closed'}`,\n payload: {\n action: 'closed',\n installation: { id: repository.installationId },\n repository: { id: repository.id, full_name: repository.fullName },\n sender: { login: state.mergedBy ?? 'github' },\n pull_request: {\n number: pullRequestNumber,\n title: state.title,\n html_url: state.url,\n ...(state.createdAt ? { created_at: state.createdAt } : {}),\n state: 'closed',\n draft: state.draft,\n merged: state.merged,\n assignees: (state.assignees ?? []).map(login => ({ login })),\n requested_reviewers: (state.requestedReviewers ?? []).map(login => ({ login })),\n head: { ref: state.headBranch },\n base: { ref: state.baseBranch },\n },\n },\n };\n}\n\n/**\n * The webhook handler retires subscriptions itself; the sweep replays only the\n * rules ingress, so without this the thread's PR chip and the workspace row\n * stay `open` forever on a deployment GitHub cannot reach.\n */\nasync function retireReconciledSubscriptions(\n storage: IntegrationStorageHandle,\n repository: ReconcileRepository,\n pullRequestNumber: number,\n merged: boolean,\n): Promise<void> {\n const target = changeRequestTargetKey({\n installationExternalId: String(repository.installationId),\n repositoryExternalId: String(repository.id),\n changeRequestId: String(pullRequestNumber),\n });\n const rows = await storage.subscriptions.listByTarget(target);\n await Promise.all(\n rows\n .filter(row => row.status === 'open')\n .map(row => storage.subscriptions.updateStatus(row.id, merged ? 'merged' : 'closed')),\n );\n}\n\n/**\n * State-based safety net for merge signals: webhooks and event-log tailing\n * can miss a merge (cursor gaps, downtime, terminally failed decisions), so\n * this sweep compares still-open PR cards against actual GitHub state and\n * replays the merge through the normal rules ingress when they disagree.\n */\nexport function createGithubPullRequestReconciler(\n options: GithubRulesOptions,\n fetchPullRequest: GithubPullRequestFetcher,\n): GithubPullRequestReconciler {\n const rules = new GithubRules(options);\n return async repositories => {\n const summary: ReconcileSweepSummary = { repositories: 0, checked: 0, merged: 0, closed: 0, failed: 0, errors: [] };\n const recordFailure = (repository: ReconcileRepository, error: unknown, pullRequestNumber?: number) => {\n summary.failed += 1;\n if (summary.errors.length < RECONCILE_ERROR_SAMPLE_LIMIT) {\n summary.errors.push({\n repository: repository.fullName,\n ...(pullRequestNumber === undefined ? {} : { pullRequestNumber }),\n error: error instanceof Error ? error.message : String(error),\n });\n }\n };\n // An installation can expose hundreds of repositories; only the ones\n // actually linked to a factory project can have cards to reconcile, so\n // scope the sweep to those up front instead of probing each repository.\n const configured = new Set(\n (await options.sourceControl.projectRepositories.listConfiguredExternalKeys()).map(\n key => `${key.installationExternalId}\\u0000${key.repositoryExternalId}`,\n ),\n );\n const scoped = repositories.filter(repository =>\n configured.has(`${repository.installationId}\\u0000${repository.id}`),\n );\n summary.repositories = scoped.length;\n for (const repository of scoped) {\n // One broken repository (or a failing token exchange for its\n // installation) must not abort the sweep for the others.\n let cardsByNumber: Map<number, WorkItemRow[]>;\n try {\n const projects = await options.sourceControl.projectRepositories.listByExternalRepository({\n installationExternalId: String(repository.installationId),\n repositoryExternalId: String(repository.id),\n });\n if (projects.length === 0) continue;\n cardsByNumber = new Map<number, WorkItemRow[]>();\n for (const project of projects) {\n const items = await options.storage.list({\n orgId: project.orgId,\n factoryProjectId: project.factoryProjectId,\n });\n for (const item of items) {\n const pullRequestNumber = reconcilablePullRequestNumber(item, repository);\n if (!pullRequestNumber) continue;\n const stage = item.stages[0];\n const metadata = item.metadata ?? {};\n const hasReconciledMetadata =\n (metadata.state === 'open' || metadata.state === 'closed') &&\n typeof metadata.draft === 'boolean' &&\n typeof metadata.merged === 'boolean' &&\n typeof metadata.author === 'string' &&\n Array.isArray(metadata.assignees) &&\n Array.isArray(metadata.requestedReviewers);\n if ((stage === 'done' || stage === 'canceled') && hasReconciledMetadata) continue;\n const cards = cardsByNumber.get(pullRequestNumber) ?? [];\n cards.push(item);\n cardsByNumber.set(pullRequestNumber, cards);\n }\n }\n } catch (error) {\n recordFailure(repository, error);\n continue;\n }\n for (const [pullRequestNumber, cards] of cardsByNumber) {\n try {\n const state = await fetchPullRequest({\n installationId: repository.installationId,\n repository: repository.fullName,\n number: pullRequestNumber,\n });\n summary.checked += 1;\n if (!state) continue;\n for (const card of cards) {\n const metadata = card.metadata ?? {};\n const statusChanged =\n metadata.state !== state.state || metadata.draft !== state.draft || metadata.merged !== state.merged;\n const authorChanged = state.author !== undefined && metadata.author !== state.author;\n const assigneesChanged = !sameStrings(metadata.assignees, state.assignees);\n const reviewersChanged = !sameStrings(metadata.requestedReviewers, state.requestedReviewers);\n if (!statusChanged && !authorChanged && !assigneesChanged && !reviewersChanged) continue;\n try {\n await options.storage.update({\n orgId: card.orgId,\n id: card.id,\n userId: 'factory-rule-dispatcher',\n patch: {\n metadata: {\n state: state.state,\n draft: state.draft,\n merged: state.merged,\n ...(state.author ? { author: state.author } : {}),\n ...(state.assignees ? { assignees: state.assignees } : {}),\n ...(state.requestedReviewers ? { requestedReviewers: state.requestedReviewers } : {}),\n },\n },\n });\n } catch (error) {\n recordFailure(repository, error, pullRequestNumber);\n }\n }\n if (state.state !== 'closed') continue;\n await rules.ingest(reconciledClosedEvent(repository, pullRequestNumber, state));\n await retireReconciledSubscriptions(options.integrationStorage, repository, pullRequestNumber, state.merged);\n if (state.merged) summary.merged += 1;\n else summary.closed += 1;\n } catch (error) {\n recordFailure(repository, error, pullRequestNumber);\n }\n }\n }\n return summary;\n };\n}\n\nfunction githubRulesOptions(\n github: GithubRulesIntegration,\n context: IntegrationContext,\n): GithubRulesOptions | undefined {\n if (!context.rules) return undefined;\n return {\n github,\n sourceControl: context.storage.sourceControl,\n integrationStorage: context.storage.generic,\n projects: context.storage.projects,\n storage: context.rules.workItems,\n rules: context.rules.config,\n };\n}\n\nexport function attachGithubRules(\n github: GithubRulesIntegration,\n context: IntegrationContext,\n): ((event: ParsedGithubWebhook) => Promise<unknown>) | undefined {\n const options = githubRulesOptions(github, context);\n if (!options) return undefined;\n const rules = new GithubRules(options);\n return event => rules.ingest(event);\n}\n\nexport function attachGithubReconciler(\n github: GithubRulesIntegration,\n context: IntegrationContext,\n fetchPullRequest: GithubPullRequestFetcher,\n): GithubPullRequestReconciler | undefined {\n const options = githubRulesOptions(github, context);\n if (!options) return undefined;\n return createGithubPullRequestReconciler(options, fetchPullRequest);\n}\n"],"mappings":";;;;AAqBA,MAAM,sCAAsB,IAAI,IAAI,CAAC,SAAS,OAAO,CAAC;AACtD,MAAM,kBAAkB;AACxB,MAAM,gCAAgC;AAEtC,eAAe,gBA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CACzC,MAAM,UAAU,mBAAmB,QAAQ,OAAO;CAClD,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,OAAO,kCAAkC,SAAS,gBAAgB;AACpE"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { SandboxFleet } from '../../sandbox/fleet.js';
|
|
2
|
-
import type { SourceControlStorageHandle } from '../../storage/domains/source-control/base.js';
|
|
2
|
+
import type { SourceControlSession, SourceControlStorageHandle } from '../../storage/domains/source-control/base.js';
|
|
3
3
|
import type { WorkItemsStorage } from '../../storage/domains/work-items/base.js';
|
|
4
4
|
/**
|
|
5
5
|
* Scrub a sandbox that is about to enter the reuse pool: force-checkout the
|
|
@@ -18,6 +18,21 @@ export declare function cleanReleasedSandbox(options: {
|
|
|
18
18
|
sandboxId: string;
|
|
19
19
|
sandboxWorkdir: string;
|
|
20
20
|
}): Promise<void>;
|
|
21
|
+
/**
|
|
22
|
+
* Reclaim the sandbox a just-deleted user session was holding: return a remote
|
|
23
|
+
* VM to the reuse pool (scrubbed first), or tear a local/unpooled one down.
|
|
24
|
+
*
|
|
25
|
+
* Runs after the session row is already gone. Waking the VM and scrubbing a
|
|
26
|
+
* large checkout takes minutes, and none of it is something the caller can act
|
|
27
|
+
* on — the workspace has disappeared from their list either way. Nothing can
|
|
28
|
+
* claim the sandbox until `release` publishes it to the pool, so deferring the
|
|
29
|
+
* whole sequence preserves the scrub-before-reuse guarantee.
|
|
30
|
+
*/
|
|
31
|
+
export declare function reclaimDeletedSessionSandbox(options: {
|
|
32
|
+
fleet: Pick<SandboxFleet, 'provider' | 'reattachSandbox' | 'teardownSandbox'>;
|
|
33
|
+
sourceControl: Pick<SourceControlStorageHandle, 'sandboxPool' | 'projectRepositories' | 'repositories'>;
|
|
34
|
+
session: Pick<SourceControlSession, 'orgId' | 'userId' | 'projectRepositoryId' | 'sandboxId' | 'sandboxWorkdir'>;
|
|
35
|
+
}): Promise<void>;
|
|
21
36
|
/**
|
|
22
37
|
* Release the sandboxes held by a work item's sessions back to the reuse pool.
|
|
23
38
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sandbox-release.d.ts","sourceRoot":"","sources":["../../../src/integrations/github/sandbox-release.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"sandbox-release.d.ts","sourceRoot":"","sources":["../../../src/integrations/github/sandbox-release.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAA0B,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACnF,OAAO,KAAK,EAAE,oBAAoB,EAAE,0BAA0B,EAAE,MAAM,8CAA8C,CAAC;AACrH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AAGjF;;;;;;;;GAQG;AACH,wBAAsB,oBAAoB,CAAC,OAAO,EAAE;IAClD,KAAK,EAAE,IAAI,CAAC,YAAY,EAAE,iBAAiB,CAAC,CAAC;IAC7C,aAAa,EAAE,IAAI,CAAC,0BAA0B,EAAE,qBAAqB,GAAG,cAAc,CAAC,CAAC;IACxF,KAAK,EAAE,MAAM,CAAC;IACd,mBAAmB,EAAE,MAAM,CAAC;IAC5B,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,MAAM,CAAC;CACxB,GAAG,OAAO,CAAC,IAAI,CAAC,CAkBhB;AAED;;;;;;;;;GASG;AACH,wBAAsB,4BAA4B,CAAC,OAAO,EAAE;IAC1D,KAAK,EAAE,IAAI,CAAC,YAAY,EAAE,UAAU,GAAG,iBAAiB,GAAG,iBAAiB,CAAC,CAAC;IAC9E,aAAa,EAAE,IAAI,CAAC,0BAA0B,EAAE,aAAa,GAAG,qBAAqB,GAAG,cAAc,CAAC,CAAC;IACxG,OAAO,EAAE,IAAI,CAAC,oBAAoB,EAAE,OAAO,GAAG,QAAQ,GAAG,qBAAqB,GAAG,WAAW,GAAG,gBAAgB,CAAC,CAAC;CAClH,GAAG,OAAO,CAAC,IAAI,CAAC,CAqChB;AAED;;;;;;;;;GASG;AACH,wBAAsB,wBAAwB,CAAC,OAAO,EAAE;IACtD,SAAS,EAAE,IAAI,CAAC,gBAAgB,EAAE,KAAK,CAAC,CAAC;IACzC,aAAa,EAAE,IAAI,CAAC,0BAA0B,EAAE,UAAU,GAAG,aAAa,GAAG,qBAAqB,GAAG,cAAc,CAAC,CAAC;IACrH,KAAK,EAAE,IAAI,CAAC,YAAY,EAAE,iBAAiB,CAAC,CAAC;IAC7C,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;CACpB,GAAG,OAAO,CAAC,IAAI,CAAC,CA8BhB"}
|
|
@@ -25,6 +25,47 @@ async function cleanReleasedSandbox(options) {
|
|
|
25
25
|
} catch {}
|
|
26
26
|
}
|
|
27
27
|
/**
|
|
28
|
+
* Reclaim the sandbox a just-deleted user session was holding: return a remote
|
|
29
|
+
* VM to the reuse pool (scrubbed first), or tear a local/unpooled one down.
|
|
30
|
+
*
|
|
31
|
+
* Runs after the session row is already gone. Waking the VM and scrubbing a
|
|
32
|
+
* large checkout takes minutes, and none of it is something the caller can act
|
|
33
|
+
* on — the workspace has disappeared from their list either way. Nothing can
|
|
34
|
+
* claim the sandbox until `release` publishes it to the pool, so deferring the
|
|
35
|
+
* whole sequence preserves the scrub-before-reuse guarantee.
|
|
36
|
+
*/
|
|
37
|
+
async function reclaimDeletedSessionSandbox(options) {
|
|
38
|
+
const { fleet, sourceControl, session } = options;
|
|
39
|
+
if (!session.sandboxId) return;
|
|
40
|
+
if (fleet.provider !== "local" && session.sandboxWorkdir) {
|
|
41
|
+
await cleanReleasedSandbox({
|
|
42
|
+
fleet,
|
|
43
|
+
sourceControl,
|
|
44
|
+
orgId: session.orgId,
|
|
45
|
+
projectRepositoryId: session.projectRepositoryId,
|
|
46
|
+
sandboxId: session.sandboxId,
|
|
47
|
+
sandboxWorkdir: session.sandboxWorkdir
|
|
48
|
+
});
|
|
49
|
+
await sourceControl.sandboxPool.release({
|
|
50
|
+
orgId: session.orgId,
|
|
51
|
+
projectRepositoryId: session.projectRepositoryId,
|
|
52
|
+
userId: session.userId,
|
|
53
|
+
sandboxId: session.sandboxId,
|
|
54
|
+
sandboxWorkdir: session.sandboxWorkdir
|
|
55
|
+
});
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
let sandbox;
|
|
59
|
+
try {
|
|
60
|
+
sandbox = await fleet.reattachSandbox(session.sandboxId);
|
|
61
|
+
} catch {}
|
|
62
|
+
await fleet.teardownSandbox({
|
|
63
|
+
sandboxId: session.sandboxId,
|
|
64
|
+
setSandboxId: async () => {},
|
|
65
|
+
clear: async () => {}
|
|
66
|
+
}, sandbox);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
28
69
|
* Release the sandboxes held by a work item's sessions back to the reuse pool.
|
|
29
70
|
*
|
|
30
71
|
* Called when the item commits into a terminal stage (`done` / `canceled`):
|
|
@@ -69,6 +110,6 @@ async function releaseWorkItemSandboxes(options) {
|
|
|
69
110
|
}
|
|
70
111
|
}
|
|
71
112
|
//#endregion
|
|
72
|
-
export { cleanReleasedSandbox, releaseWorkItemSandboxes };
|
|
113
|
+
export { cleanReleasedSandbox, reclaimDeletedSessionSandbox, releaseWorkItemSandboxes };
|
|
73
114
|
|
|
74
115
|
//# sourceMappingURL=sandbox-release.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sandbox-release.js","names":[],"sources":["../../../src/integrations/github/sandbox-release.ts"],"sourcesContent":["import type { SandboxFleet } from '../../sandbox/fleet.js';\nimport type { SourceControlStorageHandle } from '../../storage/domains/source-control/base.js';\nimport type { WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport { recycleClaimedWorkdir } from './sandbox.js';\n\n/**\n * Scrub a sandbox that is about to enter the reuse pool: force-checkout the\n * default branch and drop the released session's local state, so idle pooled\n * VMs don't sit on stale branches, dirty worktrees, or abandoned work while\n * they wait for the next claim. Best-effort — the VM may already be reaped\n * (the pooled claim then falls back to fresh provisioning) and the claim\n * path recycles the workdir again before reuse, so a failed scrub never\n * blocks the release.\n */\nexport async function cleanReleasedSandbox(options: {\n fleet: Pick<SandboxFleet, 'reattachSandbox'>;\n sourceControl: Pick<SourceControlStorageHandle, 'projectRepositories' | 'repositories'>;\n orgId: string;\n projectRepositoryId: string;\n sandboxId: string;\n sandboxWorkdir: string;\n}): Promise<void> {\n try {\n const projectRepository = await options.sourceControl.projectRepositories.get({\n orgId: options.orgId,\n id: options.projectRepositoryId,\n });\n if (!projectRepository) return;\n const repository = await options.sourceControl.repositories.get({\n orgId: options.orgId,\n id: projectRepository.repositoryId,\n });\n if (!repository) return;\n const sandbox = await options.fleet.reattachSandbox(options.sandboxId);\n await recycleClaimedWorkdir(sandbox, options.sandboxWorkdir, repository.defaultBranch);\n } catch {\n // Reaped, unreachable, or wedged — the claim-side recycle is the\n // correctness guarantee; this scrub is hygiene for idle VMs.\n }\n}\n\n/**\n * Release the sandboxes held by a work item's sessions back to the reuse pool.\n *\n * Called when the item commits into a terminal stage (`done` / `canceled`):\n * its branch sessions stop receiving runs, so their VMs — which would\n * otherwise idle until the provider reaps them — can serve the next session\n * for the same repository instead of a fresh provision. Each session\n * keeps its row (a reopened branch simply claims a pooled VM or provisions\n * fresh on next use); it only loses its sandbox binding.\n */\nexport async function releaseWorkItemSandboxes(options: {\n workItems: Pick<WorkItemsStorage, 'get'>;\n sourceControl: Pick<SourceControlStorageHandle, 'sessions' | 'sandboxPool' | 'projectRepositories' | 'repositories'>;\n fleet: Pick<SandboxFleet, 'reattachSandbox'>;\n orgId: string;\n workItemId: string;\n}): Promise<void> {\n const { workItems, sourceControl } = options;\n const item = await workItems.get({ orgId: options.orgId, id: options.workItemId });\n if (!item) return;\n const sessionIds = [...new Set(Object.values(item.sessions).map(session => session.sessionId))];\n for (const sessionId of sessionIds) {\n const session = await sourceControl.sessions.getBySessionId(sessionId);\n if (!session || session.orgId !== options.orgId) continue;\n if (!session.sandboxId || !session.sandboxWorkdir) continue;\n await cleanReleasedSandbox({\n fleet: options.fleet,\n sourceControl,\n orgId: session.orgId,\n projectRepositoryId: session.projectRepositoryId,\n sandboxId: session.sandboxId,\n sandboxWorkdir: session.sandboxWorkdir,\n });\n await sourceControl.sandboxPool.release({\n orgId: session.orgId,\n projectRepositoryId: session.projectRepositoryId,\n userId: session.userId,\n sandboxId: session.sandboxId,\n sandboxWorkdir: session.sandboxWorkdir,\n });\n await sourceControl.sessions.setSandbox({\n id: session.id,\n sandboxId: null,\n sandboxWorkdir: session.sandboxWorkdir,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;AAcA,eAAsB,qBAAqB,SAOzB;CAChB,IAAI;EACF,MAAM,oBAAoB,MAAM,QAAQ,cAAc,oBAAoB,IAAI;GAC5E,OAAO,QAAQ;GACf,IAAI,QAAQ;EACd,CAAC;EACD,IAAI,CAAC,mBAAmB;EACxB,MAAM,aAAa,MAAM,QAAQ,cAAc,aAAa,IAAI;GAC9D,OAAO,QAAQ;GACf,IAAI,kBAAkB;EACxB,CAAC;EACD,IAAI,CAAC,YAAY;EAEjB,MAAM,sBAAsB,MADN,QAAQ,MAAM,gBAAgB,QAAQ,SAAS,GAChC,QAAQ,gBAAgB,WAAW,aAAa;CACvF,QAAQ,CAGR;AACF;;;;;;;;;;;AAYA,eAAsB,yBAAyB,SAM7B;CAChB,MAAM,EAAE,WAAW,kBAAkB;CACrC,MAAM,OAAO,MAAM,UAAU,IAAI;EAAE,OAAO,QAAQ;EAAO,IAAI,QAAQ;CAAW,CAAC;CACjF,IAAI,CAAC,MAAM;CACX,MAAM,aAAa,CAAC,GAAG,IAAI,IAAI,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,KAAI,YAAW,QAAQ,SAAS,CAAC,CAAC;CAC9F,KAAK,MAAM,aAAa,YAAY;EAClC,MAAM,UAAU,MAAM,cAAc,SAAS,eAAe,SAAS;EACrE,IAAI,CAAC,WAAW,QAAQ,UAAU,QAAQ,OAAO;EACjD,IAAI,CAAC,QAAQ,aAAa,CAAC,QAAQ,gBAAgB;EACnD,MAAM,qBAAqB;GACzB,OAAO,QAAQ;GACf;GACA,OAAO,QAAQ;GACf,qBAAqB,QAAQ;GAC7B,WAAW,QAAQ;GACnB,gBAAgB,QAAQ;EAC1B,CAAC;EACD,MAAM,cAAc,YAAY,QAAQ;GACtC,OAAO,QAAQ;GACf,qBAAqB,QAAQ;GAC7B,QAAQ,QAAQ;GAChB,WAAW,QAAQ;GACnB,gBAAgB,QAAQ;EAC1B,CAAC;EACD,MAAM,cAAc,SAAS,WAAW;GACtC,IAAI,QAAQ;GACZ,WAAW;GACX,gBAAgB,QAAQ;EAC1B,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"sandbox-release.js","names":[],"sources":["../../../src/integrations/github/sandbox-release.ts"],"sourcesContent":["import type { MaterializationSandbox, SandboxFleet } from '../../sandbox/fleet.js';\nimport type { SourceControlSession, SourceControlStorageHandle } from '../../storage/domains/source-control/base.js';\nimport type { WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport { recycleClaimedWorkdir } from './sandbox.js';\n\n/**\n * Scrub a sandbox that is about to enter the reuse pool: force-checkout the\n * default branch and drop the released session's local state, so idle pooled\n * VMs don't sit on stale branches, dirty worktrees, or abandoned work while\n * they wait for the next claim. Best-effort — the VM may already be reaped\n * (the pooled claim then falls back to fresh provisioning) and the claim\n * path recycles the workdir again before reuse, so a failed scrub never\n * blocks the release.\n */\nexport async function cleanReleasedSandbox(options: {\n fleet: Pick<SandboxFleet, 'reattachSandbox'>;\n sourceControl: Pick<SourceControlStorageHandle, 'projectRepositories' | 'repositories'>;\n orgId: string;\n projectRepositoryId: string;\n sandboxId: string;\n sandboxWorkdir: string;\n}): Promise<void> {\n try {\n const projectRepository = await options.sourceControl.projectRepositories.get({\n orgId: options.orgId,\n id: options.projectRepositoryId,\n });\n if (!projectRepository) return;\n const repository = await options.sourceControl.repositories.get({\n orgId: options.orgId,\n id: projectRepository.repositoryId,\n });\n if (!repository) return;\n const sandbox = await options.fleet.reattachSandbox(options.sandboxId);\n await recycleClaimedWorkdir(sandbox, options.sandboxWorkdir, repository.defaultBranch);\n } catch {\n // Reaped, unreachable, or wedged — the claim-side recycle is the\n // correctness guarantee; this scrub is hygiene for idle VMs.\n }\n}\n\n/**\n * Reclaim the sandbox a just-deleted user session was holding: return a remote\n * VM to the reuse pool (scrubbed first), or tear a local/unpooled one down.\n *\n * Runs after the session row is already gone. Waking the VM and scrubbing a\n * large checkout takes minutes, and none of it is something the caller can act\n * on — the workspace has disappeared from their list either way. Nothing can\n * claim the sandbox until `release` publishes it to the pool, so deferring the\n * whole sequence preserves the scrub-before-reuse guarantee.\n */\nexport async function reclaimDeletedSessionSandbox(options: {\n fleet: Pick<SandboxFleet, 'provider' | 'reattachSandbox' | 'teardownSandbox'>;\n sourceControl: Pick<SourceControlStorageHandle, 'sandboxPool' | 'projectRepositories' | 'repositories'>;\n session: Pick<SourceControlSession, 'orgId' | 'userId' | 'projectRepositoryId' | 'sandboxId' | 'sandboxWorkdir'>;\n}): Promise<void> {\n const { fleet, sourceControl, session } = options;\n if (!session.sandboxId) return;\n if (fleet.provider !== 'local' && session.sandboxWorkdir) {\n // Keep the remote VM alive: return it to the reuse pool so the next\n // session for this repository link and user claims it (repo already\n // cloned) instead of provisioning a fresh sandbox. Scrub the session's\n // work off the VM first so it doesn't idle with stale branches or dirty\n // state, and so nothing claims it mid-scrub.\n await cleanReleasedSandbox({\n fleet,\n sourceControl,\n orgId: session.orgId,\n projectRepositoryId: session.projectRepositoryId,\n sandboxId: session.sandboxId,\n sandboxWorkdir: session.sandboxWorkdir,\n });\n await sourceControl.sandboxPool.release({\n orgId: session.orgId,\n projectRepositoryId: session.projectRepositoryId,\n userId: session.userId,\n sandboxId: session.sandboxId,\n sandboxWorkdir: session.sandboxWorkdir,\n });\n return;\n }\n let sandbox: MaterializationSandbox | undefined;\n try {\n sandbox = await fleet.reattachSandbox(session.sandboxId);\n } catch {\n // The provider may already have reclaimed the sandbox.\n }\n // The session row is deleted, so there is no binding left to clear.\n await fleet.teardownSandbox(\n { sandboxId: session.sandboxId, setSandboxId: async () => {}, clear: async () => {} },\n sandbox,\n );\n}\n\n/**\n * Release the sandboxes held by a work item's sessions back to the reuse pool.\n *\n * Called when the item commits into a terminal stage (`done` / `canceled`):\n * its branch sessions stop receiving runs, so their VMs — which would\n * otherwise idle until the provider reaps them — can serve the next session\n * for the same repository instead of a fresh provision. Each session\n * keeps its row (a reopened branch simply claims a pooled VM or provisions\n * fresh on next use); it only loses its sandbox binding.\n */\nexport async function releaseWorkItemSandboxes(options: {\n workItems: Pick<WorkItemsStorage, 'get'>;\n sourceControl: Pick<SourceControlStorageHandle, 'sessions' | 'sandboxPool' | 'projectRepositories' | 'repositories'>;\n fleet: Pick<SandboxFleet, 'reattachSandbox'>;\n orgId: string;\n workItemId: string;\n}): Promise<void> {\n const { workItems, sourceControl } = options;\n const item = await workItems.get({ orgId: options.orgId, id: options.workItemId });\n if (!item) return;\n const sessionIds = [...new Set(Object.values(item.sessions).map(session => session.sessionId))];\n for (const sessionId of sessionIds) {\n const session = await sourceControl.sessions.getBySessionId(sessionId);\n if (!session || session.orgId !== options.orgId) continue;\n if (!session.sandboxId || !session.sandboxWorkdir) continue;\n await cleanReleasedSandbox({\n fleet: options.fleet,\n sourceControl,\n orgId: session.orgId,\n projectRepositoryId: session.projectRepositoryId,\n sandboxId: session.sandboxId,\n sandboxWorkdir: session.sandboxWorkdir,\n });\n await sourceControl.sandboxPool.release({\n orgId: session.orgId,\n projectRepositoryId: session.projectRepositoryId,\n userId: session.userId,\n sandboxId: session.sandboxId,\n sandboxWorkdir: session.sandboxWorkdir,\n });\n await sourceControl.sessions.setSandbox({\n id: session.id,\n sandboxId: null,\n sandboxWorkdir: session.sandboxWorkdir,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;AAcA,eAAsB,qBAAqB,SAOzB;CAChB,IAAI;EACF,MAAM,oBAAoB,MAAM,QAAQ,cAAc,oBAAoB,IAAI;GAC5E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S,CAAC,CAAC;CAC9F,KAAK,MAAM,aAAa,YAAY;EAClC,MAAM,UAAU,MAAM,cAAc,SAAS,eAAe,SAAS;EACrE,IAAI,CAAC,WAAW,QAAQ,UAAU,QAAQ,OAAO;EACjD,IAAI,CAAC,QAAQ,aAAa,CAAC,QAAQ,gBAAgB;EACnD,MAAM,qBAAqB;GACzB,OAAO,QAAQ;GACf;GACA,OAAO,QAAQ;GACf,qBAAqB,QAAQ;GAC7B,WAAW,QAAQ;GACnB,gBAAgB,QAAQ;EAC1B,CAAC;EACD,MAAM,cAAc,YAAY,QAAQ;GACtC,OAAO,QAAQ;GACf,qBAAqB,QAAQ;GAC7B,QAAQ,QAAQ;GAChB,WAAW,QAAQ;GACnB,gBAAgB,QAAQ;EAC1B,CAAC;EACD,MAAM,cAAc,SAAS,WAAW;GACtC,IAAI,QAAQ;GACZ,WAAW;GACX,gBAAgB,QAAQ;EAC1B,CAAC;CACH;AACF"}
|
|
@@ -64,6 +64,8 @@ export interface LinearIssue {
|
|
|
64
64
|
stateType: string;
|
|
65
65
|
priorityLabel: string;
|
|
66
66
|
assignee: string | null;
|
|
67
|
+
/** Display name of the Linear user who created the issue, when Linear returns one. */
|
|
68
|
+
creator: string | null;
|
|
67
69
|
team: string | null;
|
|
68
70
|
labels: string[];
|
|
69
71
|
createdAt: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration.d.ts","sourceRoot":"","sources":["../../../src/integrations/linear/integration.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,KAAK,EAGV,MAAM,EAKP,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,KAAK,EAAE,wBAAwB,EAAE,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,WAAW,eAAe;IAC9B,MAAM,EAAE,WAAW,EAAE,CAAC;IACtB,mEAAmE;IACnE,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B;AAED,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,kCAAkC;IAClC,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,aAAa;IAC5B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,0EAA0E;IAC1E,KAAK,EAAE,MAAM,CAAC;IACd,0EAA0E;IAC1E,KAAK,EAAE,iBAAiB,EAAE,CAAC;CAC5B;AAED,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,+GAA+G;AAC/G,MAAM,WAAW,iBAAkB,SAAQ,WAAW;IACpD,wDAAwD;IACxD,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,yCAAyC;IACzC,QAAQ,EAAE,kBAAkB,EAAE,CAAC;CAChC;AAED,2EAA2E;AAC3E,MAAM,WAAW,oBAAoB;IACnC,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,EAAE,MAAM,CAAC;CACb;AAeD,2EAA2E;AAC3E,qBAAa,yBAA0B,SAAQ,KAAK;;CAInD;AAED,kEAAkE;AAClE,MAAM,WAAW,qBAAqB;IACpC,SAAS,EAAE,OAAO,CAAC;IACnB,qEAAqE;IACrE,UAAU,EAAE,OAAO,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;CACnB;
|
|
1
|
+
{"version":3,"file":"integration.d.ts","sourceRoot":"","sources":["../../../src/integrations/linear/integration.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;A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var LinearIntegration = class {
|
|
|
474
474
|
state { name type }
|
|
475
475
|
project { id }
|
|
476
476
|
assignee { name }
|
|
477
|
+
creator { name }
|
|
477
478
|
team { key }
|
|
478
479
|
labels { nodes { name } }
|
|
479
480
|
}
|
|
@@ -496,6 +497,7 @@ var LinearIntegration = class {
|
|
|
496
497
|
stateType: node.state.type,
|
|
497
498
|
priorityLabel: node.priorityLabel,
|
|
498
499
|
assignee: node.assignee?.name ?? null,
|
|
500
|
+
creator: node.creator?.name ?? null,
|
|
499
501
|
team: node.team?.key ?? null,
|
|
500
502
|
labels: node.labels.nodes.map((label) => label.name),
|
|
501
503
|
createdAt: node.createdAt,
|
|
@@ -549,6 +551,7 @@ var LinearIntegration = class {
|
|
|
549
551
|
state { name type }
|
|
550
552
|
project { id }
|
|
551
553
|
assignee { name }
|
|
554
|
+
creator { name }
|
|
552
555
|
team { key }
|
|
553
556
|
labels { nodes { name } }
|
|
554
557
|
comments(first: $commentsFirst) {
|
|
@@ -578,6 +581,7 @@ var LinearIntegration = class {
|
|
|
578
581
|
stateType: issue.state.type,
|
|
579
582
|
priorityLabel: issue.priorityLabel,
|
|
580
583
|
assignee: issue.assignee?.name ?? null,
|
|
584
|
+
creator: issue.creator?.name ?? null,
|
|
581
585
|
team: issue.team?.key ?? null,
|
|
582
586
|
labels: issue.labels.nodes.map((label) => label.name),
|
|
583
587
|
createdAt: issue.createdAt,
|
|
@@ -654,7 +658,7 @@ function linearIssueToIntakeIssue(issue) {
|
|
|
654
658
|
identifier: issue.identifier,
|
|
655
659
|
title: issue.title,
|
|
656
660
|
url: issue.url,
|
|
657
|
-
author:
|
|
661
|
+
author: issue.creator,
|
|
658
662
|
state: issue.state,
|
|
659
663
|
stateType: issue.stateType,
|
|
660
664
|
priority: issue.priorityLabel,
|