@mastra/factory 0.28.0-alpha.6 → 0.28.0-alpha.7
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/dist/boards/board-writes.d.ts +1 -1
- package/dist/boards/board-writes.d.ts.map +1 -1
- package/dist/boards/board-writes.js +1 -1
- package/dist/boards/board-writes.js.map +1 -1
- package/dist/environment/build-runner.d.ts.map +1 -1
- package/dist/environment/build-runner.js +2 -2
- package/dist/environment/build-runner.js.map +1 -1
- package/dist/environment/build-workflow.d.ts.map +1 -1
- package/dist/environment/build-workflow.js +6 -5
- package/dist/environment/build-workflow.js.map +1 -1
- package/dist/environment/build.d.ts +15 -2
- package/dist/environment/build.d.ts.map +1 -1
- package/dist/environment/build.js +32 -9
- package/dist/environment/build.js.map +1 -1
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +29 -3
- package/dist/factory.js.map +1 -1
- package/dist/integrations/github/integration.d.ts.map +1 -1
- package/dist/integrations/github/integration.js +7 -3
- package/dist/integrations/github/integration.js.map +1 -1
- package/dist/integrations/github/issue-reconciler.js +2 -2
- package/dist/integrations/github/issue-reconciler.js.map +1 -1
- package/dist/integrations/github/provenance.js +1 -1
- package/dist/integrations/github/provenance.js.map +1 -1
- package/dist/integrations/github/reconcile-worker.d.ts +5 -1
- package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
- package/dist/integrations/github/reconcile-worker.js +39 -6
- package/dist/integrations/github/reconcile-worker.js.map +1 -1
- package/dist/integrations/github/routes.d.ts +4 -3
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +9 -86
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/rules.d.ts +67 -0
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +215 -12
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/github/sandbox.d.ts +10 -2
- package/dist/integrations/github/sandbox.d.ts.map +1 -1
- package/dist/integrations/github/sandbox.js +20 -4
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/gitlab/merge-request-reconciler.js +1 -1
- package/dist/integrations/gitlab/merge-request-reconciler.js.map +1 -1
- package/dist/integrations/gitlab/rules.d.ts.map +1 -1
- package/dist/integrations/gitlab/rules.js +6 -5
- package/dist/integrations/gitlab/rules.js.map +1 -1
- package/dist/integrations/incidentio/rules.d.ts.map +1 -1
- package/dist/integrations/incidentio/rules.js +5 -2
- package/dist/integrations/incidentio/rules.js.map +1 -1
- package/dist/integrations/issue-reconciler.js +1 -1
- package/dist/integrations/issue-reconciler.js.map +1 -1
- package/dist/integrations/jira/rules.d.ts.map +1 -1
- package/dist/integrations/jira/rules.js +5 -2
- package/dist/integrations/jira/rules.js.map +1 -1
- package/dist/integrations/linear/rules.d.ts.map +1 -1
- package/dist/integrations/linear/rules.js +2 -2
- package/dist/integrations/linear/rules.js.map +1 -1
- package/dist/integrations/platform/github/event-worker.d.ts +4 -1
- package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +39 -3
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts +8 -0
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +21 -3
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/linear/event-worker.d.ts +1 -1
- package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/linear/event-worker.js +1 -1
- package/dist/integrations/platform/linear/event-worker.js.map +1 -1
- package/dist/mcp/routes.js +1 -1
- package/dist/mcp/routes.js.map +1 -1
- package/dist/routes/attention-parked.js +1 -1
- package/dist/routes/attention-parked.js.map +1 -1
- package/dist/routes/boards.d.ts +1 -1
- package/dist/routes/boards.d.ts.map +1 -1
- package/dist/routes/boards.js.map +1 -1
- package/dist/routes/contracts.d.ts +115 -0
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +69 -1
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/projects.js +12 -6
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/sandbox-envs.d.ts +26 -0
- package/dist/routes/sandbox-envs.d.ts.map +1 -0
- package/dist/routes/sandbox-envs.js +180 -0
- package/dist/routes/sandbox-envs.js.map +1 -0
- package/dist/routes/work-items.js +1 -1
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +3 -2
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/sandbox/sandbox-env-cache.d.ts +33 -0
- package/dist/sandbox/sandbox-env-cache.d.ts.map +1 -0
- package/dist/sandbox/sandbox-env-cache.js +140 -0
- package/dist/sandbox/sandbox-env-cache.js.map +1 -0
- package/dist/sandbox/sandbox-env.d.ts +77 -0
- package/dist/sandbox/sandbox-env.d.ts.map +1 -0
- package/dist/sandbox/sandbox-env.js +130 -0
- package/dist/sandbox/sandbox-env.js.map +1 -0
- package/dist/storage/domains/audit/actions.d.ts +1 -0
- package/dist/storage/domains/audit/actions.d.ts.map +1 -1
- package/dist/storage/domains/audit/actions.js +5 -0
- package/dist/storage/domains/audit/actions.js.map +1 -1
- package/dist/storage/domains/sandbox-envs/base.d.ts +70 -0
- package/dist/storage/domains/sandbox-envs/base.d.ts.map +1 -0
- package/dist/storage/domains/sandbox-envs/base.js +227 -0
- package/dist/storage/domains/sandbox-envs/base.js.map +1 -0
- package/dist/storage/domains/work-items/base.d.ts +2 -1
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +11 -2
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/storage/domains/work-items/metrics.d.ts +1 -1
- package/dist/storage/domains/work-items/metrics.d.ts.map +1 -1
- package/dist/storage/domains/work-items/metrics.js.map +1 -1
- package/dist/workspace.d.ts +3 -0
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +21 -4
- package/dist/workspace.js.map +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/github/rules.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\n\nimport { closeReason } from '../../boards/board-events.js';\nimport type { BoardEventFacts } from '../../boards/board-events.js';\nimport {\n boardEventHandlers,\n boardForWorkItem,\n cardBoardFlow,\n eventBoardId,\n isTerminalWorkItem,\n cardOwnsBranch,\n newestOwnedOpenPullRequestNumber,\n pullRequestSources,\n intakeTarget,\n rulePhaseField,\n withBoardClosure,\n withBoardFlow,\n workItemPhaseSemantics,\n} from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { cardLabels } from '../../boards/relocate.js';\nimport { requestsChangesVerdict } from '../../review-verdict.js';\nimport { deploymentOwnsEvent, routeEventDecision, selectEventRule, withoutRouteEvent } from '../../rules/event-rules.js';\nimport type {\n FactoryGithubEventName,\n FactoryGithubRuleContext,\n FactoryPullRequestHome,\n FactoryRuleActor,\n FactoryRuleDecision,\n FactorySignalActivityDecision,\n} from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.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 { Card, ExternalWorkItemSource, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport {\n FACTORY_PULL_REQUEST_RECONCILIATION_KEY,\n WorkItemUpdateConflictError,\n} from '../../storage/domains/work-items/base.js';\nimport { primarySource } from '../../storage/domains/work-items/work-item-schema.js';\nimport type { WorkItemSourceRow } from '../../storage/domains/work-items/work-item-schema.js';\nimport { workItemBranch, workItemBranchSource } from '../../work-item-branch.js';\nimport type { IntegrationContext, IntegrationHooks } from '../base.js';\nimport { closingIssueNumbers } from '../closing-references.js';\nimport { recordPullRequestHead } from '../pull-request-head.js';\nimport type { GithubAppIdentity } from './app-identity.js';\nimport type { GithubEventRules } from './default-rules.js';\nimport type { GithubRepositoryPermission } from './integration.js';\nimport { isRepositoryPullRequest } from './pull-request-source.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 timestamp(value: unknown): number | undefined {\n const parsed = typeof value === 'string' ? Date.parse(value) : NaN;\n return Number.isNaN(parsed) ? undefined : parsed;\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 sameLabels(a: readonly string[], b: readonly string[]): boolean {\n return a.length === b.length && a.every((label, index) => label === b[index]);\n}\n\nfunction labelNames(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap(label => {\n if (typeof label === 'string') return label ? [label] : [];\n const name = string(object(label)?.name);\n return name ? [name] : [];\n });\n}\n\nfunction parseFactoryReviewCommand(\n body: string | undefined,\n target: string | undefined,\n): { command: 'review' | 're-review'; target: string } | undefined {\n if (!body || !target) return undefined;\n const firstLine = body\n .split('\\n')\n .map(line => line.trim())\n .find(line => line.length > 0)\n ?.toLowerCase();\n if (!firstLine) return undefined;\n const mention = `@${target.toLowerCase().replace(/\\[bot\\]$/, '')}`;\n if (firstLine === `${mention} review`) return { command: 'review', target };\n if (firstLine === `${mention} re-review`) return { command: 're-review', target };\n return undefined;\n}\n\n/**\n * Points the card's session at a new comment or an edit on its issue. Only\n * pointers travel (who, where, a link); Factory's own comments are skipped so\n * a session is not woken by what it wrote.\n */\nexport function activitySignalFor(\n context: Pick<FactoryGithubRuleContext, 'event' | 'item' | 'actor' | 'ingress' | 'repository' | 'issue' | 'issueComment'>,\n): FactorySignalActivityDecision | undefined {\n const event =\n context.event === 'issueCommentCreated'\n ? ('work_item.commented' as const)\n : context.event === 'issueEdited'\n ? ('work_item.edited' as const)\n : undefined;\n if (!event || !context.item || !context.issue) return undefined;\n if (context.actor.type !== 'github' || context.actor.factoryAuthored) return undefined;\n return {\n type: 'signalActivity',\n idempotencyKey: `${context.ingress.id}:activity`,\n event,\n reference: `${context.repository.fullName}#${context.issue.number}`,\n url: (event === 'work_item.commented' ? context.issueComment?.url : undefined) ?? context.issue.url,\n ...(context.actor.login ? { author: context.actor.login } : {}),\n authorTrusted: context.actor.trusted,\n };\n}\n\n/** The status change a GitHub delivery reports. `not_planned` and `duplicate` closes are canceled work. */\nexport function boardEventFor(context: Pick<FactoryGithubRuleContext, 'event' | 'issue'>): BoardEventFacts | undefined {\n switch (context.event) {\n case 'issueOpened':\n return { type: 'work_item.created' };\n case 'issueReopened':\n return { type: 'work_item.reopened' };\n case 'issueClosed': {\n const stateReason = context.issue?.stateReason;\n return { type: 'work_item.closed', reason: closeReason(stateReason === 'not_planned' || stateReason === 'duplicate') };\n }\n default:\n return undefined;\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 === 'issues' && action === 'closed') return 'issueClosed';\n if (parsed.event === 'issues' && action === 'reopened') return 'issueReopened';\n if (parsed.event === 'issue_comment') {\n const issue = object(parsed.payload.issue);\n // A comment on a PR arrives as `issue_comment` with `issue.pull_request` set.\n // It routes to the PR's own event so it binds to the authoring Work item via\n // provenance instead of being mistaken for a comment on an issue of the same\n // number. Edits and deletions are not new feedback, with one exception: the\n // review skill updates its earlier request-changes verdict in place instead\n // of posting a new one, and that edit is the only handoff the author gets.\n if (object(issue?.pull_request)) {\n if (action === 'created') return 'pullRequestCommentCreated';\n return action === 'edited' && editedRequestChangesVerdict(parsed.payload, parsed.payload.comment)\n ? 'pullRequestCommentCreated'\n : undefined;\n }\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 if (parsed.event === 'pull_request_review' && action === 'submitted') return 'pullRequestReviewSubmitted';\n if (parsed.event === 'pull_request_review' && action === 'edited') {\n const review = object(parsed.payload.review);\n return string(review?.state)?.toLowerCase() === 'changes_requested' &&\n editedRequestChangesVerdict(parsed.payload, review)\n ? 'pullRequestReviewSubmitted'\n : undefined;\n }\n return undefined;\n}\n\n/** A body edit that leaves a Factory request-changes verdict on the post. */\nfunction editedRequestChangesVerdict(payload: Record<string, unknown>, post: unknown): boolean {\n return object(object(payload.changes)?.body) !== undefined && requestsChangesVerdict(string(object(post)?.body));\n}\n\n/**\n * Canonical source keys (`github-issue:N`, `github-pr:N`) do not identify a\n * repository, so a project linked to several repositories could bind repo A's\n * event to repo B's same-numbered card. The card's intake-stamped URL is\n * authoritative; the intake-stamped `githubRepositoryId` covers URL-less\n * cards. A card with neither signal cannot be attributed by number alone.\n */\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\nexport function cardBelongsToRepository(item: Card, repositoryId: number, repositoryFullName: string): boolean {\n const url = item.externalSource?.url;\n if (url) {\n const match = /^https?:\\/\\/[^/]+\\/(.+)\\/(?:issues|pull)\\/\\d+(?:[/?#]|$)/.exec(url);\n if (match && match[1] === repositoryFullName) return true;\n }\n // A renamed repository leaves the old owner/name in the card URL, so a URL\n // mismatch still defers to the stable intake-stamped repository id.\n return item.workItem.metadata?.githubRepositoryId === repositoryId;\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\n/**\n * The head branch of a pull request pushed to the repository itself. A fork's branch lives in\n * another repository, so its name says nothing about which card wrote it — anyone could name a\n * fork branch after a card. A payload without `head.repo` (rebuilt from polled state) is the\n * base repository's own record and keeps its branch.\n */\nfunction sameRepositoryHeadBranch(pullRequest: Record<string, unknown> | undefined, repositoryId: number) {\n const head = object(pullRequest?.head);\n if (head && 'repo' in head && number(object(head.repo)?.id) !== repositoryId) return undefined;\n return string(head?.ref);\n}\n\n/** A card attributed to a different repository than the pull request's. */\nfunction cardInOtherRepository(item: Card, repositoryId: number, repositoryFullName: string): boolean {\n const attributed =\n /^https?:\\/\\/[^/]+\\/.+\\/(?:issues|pull)\\/\\d+(?:[/?#]|$)/.test(item.externalSource?.url ?? '') ||\n typeof item.workItem.metadata?.githubRepositoryId === 'number';\n return attributed && !cardBelongsToRepository(item, repositoryId, repositoryFullName);\n}\n\n/**\n * The work item a pull request's head branch belongs to: a session of the item checked it out,\n * or it is the item's own branch name, which covers pull requests opened from a session that\n * only follows the card (no session on the card holds the branch, and no provenance was\n * recorded). Only a single match counts; two cards claiming one branch name neither.\n */\nfunction branchAuthoringItem(\n items: Card[],\n headBranch: string | undefined,\n repositoryId: number,\n repositoryFullName: string,\n): Card | undefined {\n if (!headBranch) return undefined;\n const matches = items.filter(\n item =>\n item.externalSource?.type !== 'pull-request' &&\n !cardInOtherRepository(item, repositoryId, repositoryFullName) &&\n (Object.values(item.sessions).some(session => session.branch === headBranch) ||\n workItemBranch({\n id: item.id,\n source: workItemBranchSource(item.externalSource),\n metadata: item.workItem.metadata,\n }) === headBranch),\n );\n return matches.length === 1 ? matches[0] : undefined;\n}\n\n/** Every source a card for this issue or pull request may be filed under. */\nexport function githubItemSources(\n repositoryId: number,\n kind: 'issue' | 'pull-request',\n itemNumber: number,\n): ExternalWorkItemSource[] {\n return [canonicalSourceKey(kind, itemNumber), legacySourceKey(repositoryId, kind, itemNumber)].map(externalId => ({\n integrationId: 'github',\n type: kind,\n externalId,\n }));\n}\n\n/**\n * The pull request source an issue card carries for this repository's pull request, when it was\n * attached to the card rather than filed on a card of its own.\n */\nexport function attachedPullRequestSource(\n item: Card,\n repositoryId: number,\n repositoryFullName: string,\n pullRequestNumber: number,\n): WorkItemSourceRow | undefined {\n if (item.externalSource?.type === 'pull-request') return undefined;\n return pullRequestSources(item).find(source =>\n isRepositoryPullRequest(source, repositoryId, repositoryFullName, pullRequestNumber),\n );\n}\n\nfunction provenanceTarget(repositoryId: number, pullRequestNumber: number): string {\n return `factory-pr-provenance:${repositoryId}:${pullRequestNumber}`;\n}\n\nfunction workItemSource(item: Card) {\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: Card): string | null {\n return item.externalSource?.externalId ?? null;\n}\n\n// Throws on a failed lookup: callers writing permanent state must retry, not\n// record the failure as distrust.\nexport async function trustedCollaborator(\n github: GithubRulesIntegration,\n input: { installationId: number; repository: string; login: string },\n): Promise<boolean> {\n const permission = await github.getRepositoryCollaboratorPermission(\n input.installationId,\n input.repository,\n input.login,\n );\n return permission !== undefined && TRUSTED_PERMISSIONS.has(permission);\n}\n\n// Terminal cards leave the reconcile loop below, so the ones that got there before author\n// trust was recorded have no other path to an answer.\nfunction authorAwaitingTrust(item: Card, repository: ReconcileRepository): string | undefined {\n const metadata = { ...item.workItem.metadata, ...item.metadata };\n if (typeof metadata.author !== 'string' || metadata.authorTrusted !== undefined) return undefined;\n const tracked = reconcilablePullRequestNumber(item, repository) ?? reconcilableIssueNumber(item, repository);\n if (tracked === undefined) return undefined;\n // A canonical key with no URL names no repository, and the pull request matcher takes it anyway.\n // Asking GitHub about the wrong repository of a multi-repository project would record a wrong answer.\n const unattributed =\n !item.externalSource?.url && /^github-(?:pr|issue):\\d+$/.test(item.externalSource?.externalId ?? '');\n if (unattributed && metadata.githubRepositoryId !== repository.id) return undefined;\n return metadata.author;\n}\n\nexport function sweepTrustLookup(\n github: GithubRulesIntegration,\n repository: ReconcileRepository,\n): (login: string) => Promise<boolean> {\n const cache = new Map<string, boolean>();\n return async login => {\n const cached = cache.get(login);\n if (cached !== undefined) return cached;\n const trusted = await trustedCollaborator(github, {\n installationId: repository.installationId,\n repository: repository.fullName,\n login,\n });\n cache.set(login, trusted);\n return trusted;\n };\n}\n\nasync function githubActor(\n github: GithubRulesIntegration,\n input: { installationId: number; repository: string; login: string; factoryAuthored: boolean },\n): Promise<FactoryRuleActor> {\n // The actor bit is recomputed on every event, so a failed lookup can read\n // untrusted for this one delivery instead of failing the ingest.\n const trusted = await trustedCollaborator(github, input).catch(() => false);\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(\n data: Record<string, unknown> | undefined,\n factoryProjectId: string,\n): FactoryPullRequestProvenanceData | null {\n if (!data || data.kind !== 'factory-pr-provenance' || typeof data.workItemId !== 'string') return null;\n // Provenance proves which Factory *project's* run authored the PR. A row\n // written by a sibling project in the same org — or a legacy row without the\n // project stamp — fails closed here: honoring it would brand the PR\n // Factory-authored in a project that never touched it, and auto-start a\n // review that checks out and executes the PR there.\n if (data.factoryProjectId !== factoryProjectId) return null;\n return { kind: 'factory-pr-provenance', workItemId: data.workItemId };\n}\n\nexport interface GithubRulesIntegration {\n readonly rules: GithubEventRules;\n readonly slug?: string;\n /**\n * Factory's own GitHub login, used to ignore its own writes. Optional because\n * not every integration can name itself; when absent, self-recognition falls\n * back to the configured slug and, failing that, to content Factory stamps\n * itself (see `FACTORY_TRIAGE_COMMENT_MARKER`).\n */\n readonly identity?: GithubAppIdentity;\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 configVersion: string;\n /** The code boards, or the per-project source so a project's stored boards run its cards. */\n boards: BoardRegistry | ProjectBoardSource;\n /** Hands a push to a linked repository off for an environment build. */\n onRepositoryPush?: IntegrationHooks['onRepositoryPush'];\n}\n\n/** Identity under which label and assignee syncs are recorded. */\nconst CARD_SYNC_USER_ID = 'factory-rule-dispatcher';\n\ntype IssueActionHandler = (\n parsed: ParsedGithubWebhook,\n repositoryId: number,\n repositoryName: string,\n project: ExternalRepositoryProjectTarget,\n) => Promise<{ status: 'ignored' | 'committed' }>;\n\n/**\n * Whether a login is Factory itself. Prefers the resolved identity, which is\n * observed from Factory's own writes, and falls back to the configured slug.\n */\nexport function isFactoryGithubLogin(\n github: Pick<GithubRulesIntegration, 'identity' | 'slug'>,\n login: string | null | undefined,\n): boolean {\n if (github.identity?.known) return github.identity.matches(login);\n const slug = github.slug?.trim();\n if (!slug || !login) return false;\n return login.toLowerCase() === `${slug.toLowerCase()}[bot]`;\n}\n\nexport class GithubRules {\n constructor(private readonly options: GithubRulesOptions) {}\n\n /** Brings the project's boards up to date, so the sync reads below see its stored boards. */\n async loadBoards(scope: StoredBoardScope): Promise<void> {\n await toBoardSource(this.options.boards).load(scope);\n }\n\n /** The project's loaded boards; {@link loadBoards} runs before an event is handled. */\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n /**\n * Whether a login is Factory itself. Prefers the resolved identity, which is\n * observed from Factory's own writes, and falls back to the configured slug.\n * An unset slug must not silently answer \"not Factory\" — that is what\n * disabled every self-loop guard.\n */\n #isFactoryLogin(login: string | undefined): boolean {\n return isFactoryGithubLogin(this.options.github, login);\n }\n\n #factoryMentionTarget(): string | undefined {\n const identity = this.options.github.identity;\n if (identity?.known) return identity.login;\n const slug = this.options.github.slug?.trim();\n return slug ? `${slug.toLowerCase()}[bot]` : undefined;\n }\n\n /**\n * `labeled` / `unlabeled` are not rule events: the card's label metadata is refreshed and the card\n * stays where it is. Intake routes placed it when it arrived; a label change doesn't move it.\n */\n async #syncIssueLabels(\n parsed: ParsedGithubWebhook,\n repositoryId: number,\n repositoryName: string,\n project: ExternalRepositoryProjectTarget,\n ): Promise<{ status: 'ignored' | 'committed' }> {\n const issue = object(parsed.payload.issue);\n const issueNumber = issue?.pull_request === undefined ? number(issue?.number) : undefined;\n if (!issueNumber) return { status: 'ignored' };\n const found = await this.#relatedItem(\n project.orgId,\n project.factoryProjectId,\n repositoryId,\n repositoryName,\n issueNumber,\n undefined,\n undefined,\n null,\n );\n if (!found || found.externalSource?.type !== 'issue') return { status: 'ignored' };\n const labels = labelNames(issue?.labels);\n if (sameLabels(cardLabels(found), labels)) return { status: 'ignored' };\n let updated;\n try {\n updated = await this.options.storage.syncCard({\n orgId: found.orgId,\n id: found.id,\n userId: CARD_SYNC_USER_ID,\n patch: { metadata: { labels } },\n expectedSourceRevision: primarySource(found)?.revision,\n });\n } catch (error) {\n // The card changed under us (a run wrote it, or a concurrent delivery won). The next\n // delivery or reconcile pass carries the same labels, so drop this one instead of 5xx-ing.\n if (!(error instanceof WorkItemUpdateConflictError)) throw error;\n return { status: 'ignored' };\n }\n return { status: updated ? 'committed' : 'ignored' };\n }\n\n /**\n * `assigned` / `unassigned` are not rule events either: an existing issue card only mirrors the\n * issue's full assignee list. No card is created, moved, or handed to a run.\n */\n async #syncIssueAssignees(\n parsed: ParsedGithubWebhook,\n repositoryId: number,\n repositoryName: string,\n project: ExternalRepositoryProjectTarget,\n ): Promise<{ status: 'ignored' | 'committed' }> {\n const issue = object(parsed.payload.issue);\n const issueNumber = issue?.pull_request === undefined ? number(issue?.number) : undefined;\n if (!issueNumber) return { status: 'ignored' };\n const item = await this.#relatedItem(\n project.orgId,\n project.factoryProjectId,\n repositoryId,\n repositoryName,\n issueNumber,\n undefined,\n undefined,\n null,\n );\n if (!item || item.externalSource?.type !== 'issue') return { status: 'ignored' };\n const assignees = actorLogins(issue?.assignees);\n // GitHub can deliver webhooks out of order; drop payloads older than the last applied one.\n // Timestamps have one-second resolution, so equal timestamps still apply.\n const updatedAt = string(issue?.updated_at);\n const payloadTime = timestamp(updatedAt);\n const storedTime = timestamp(item.workItem.metadata?.githubAssigneesUpdatedAt);\n if (payloadTime !== undefined && storedTime !== undefined && payloadTime < storedTime) {\n return { status: 'ignored' };\n }\n // A newer payload with unchanged assignees still advances the stored time, so a delayed older\n // payload cannot slip in behind it.\n const advancesTime = payloadTime !== undefined && (storedTime === undefined || payloadTime > storedTime);\n if (sameStrings(item.workItem.metadata?.assignees, assignees) && !advancesTime) return { status: 'ignored' };\n try {\n const updated = await this.options.storage.syncCard({\n orgId: item.orgId,\n id: item.id,\n userId: CARD_SYNC_USER_ID,\n patch: {\n metadata: {\n assignees,\n ...(payloadTime !== undefined ? { githubAssigneesUpdatedAt: updatedAt } : {}),\n },\n },\n expectedSourceRevision: primarySource(item)?.revision,\n });\n return { status: updated ? 'committed' : 'ignored' };\n } catch (error) {\n // A concurrent write won; nothing reconciles issue-card assignees, so they stay as the\n // winner left them until the next assigned/unassigned delivery for this issue.\n if (!(error instanceof WorkItemUpdateConflictError)) throw error;\n return { status: 'ignored' };\n }\n }\n\n /** `issues` actions that are not rule events but still update an existing card. */\n #issueActionHandler(parsed: ParsedGithubWebhook): IssueActionHandler | undefined {\n if (parsed.event !== 'issues') return undefined;\n switch (string(parsed.payload.action)) {\n case 'labeled':\n case 'unlabeled':\n return (...args) => this.#syncIssueLabels(...args);\n case 'assigned':\n case 'unassigned':\n return (...args) => this.#syncIssueAssignees(...args);\n default:\n return undefined;\n }\n }\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 (parsed.event === 'push' && installationId && repositoryId) {\n await this.#handOffPush(parsed, installationId, repositoryId);\n return { status: 'ignored' };\n }\n if (!installationId || !repositoryId || !repositoryName || !login) return { status: 'ignored' };\n const issueAction = this.#issueActionHandler(parsed);\n const handle = event\n ? (project: ExternalRepositoryProjectTarget) =>\n this.#ingestProject(parsed, event, installationId, repositoryId, repositoryName, login, project)\n : issueAction\n ? (project: ExternalRepositoryProjectTarget) => issueAction(parsed, repositoryId, repositoryName, project)\n : undefined;\n if (!handle) 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 await this.loadBoards(project);\n results.push(await handle(project));\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 /**\n * A push is not a work-item event; it only reaches the environment build\n * hand-off, once per project the repository is linked to. The hook decides\n * whether the project builds on push.\n */\n async #handOffPush(parsed: ParsedGithubWebhook, installationId: number, repositoryId: number): Promise<void> {\n const onRepositoryPush = this.options.onRepositoryPush;\n const ref = string(parsed.payload.ref);\n const defaultBranch = string(object(parsed.payload.repository)?.default_branch);\n if (!onRepositoryPush || !ref || !defaultBranch) return;\n const projects = await this.options.sourceControl.projectRepositories.listByExternalRepository({\n installationExternalId: String(installationId),\n repositoryExternalId: String(repositoryId),\n });\n for (const project of projects) {\n onRepositoryPush({\n orgId: project.orgId,\n factoryProjectId: project.factoryProjectId,\n projectRepository: {\n id: project.projectRepository.id,\n inEnvironment: project.projectRepository.inEnvironment,\n },\n ref,\n defaultBranch,\n });\n }\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 // A comment on a PR carries the PR under `issue` (with `pull_request` set)\n // and has no `pull_request` payload of its own. Read the PR from `issue` in\n // that case so provenance and `context.pullRequest` behave as they do for\n // every other PR event, and so the number is never treated as an issue's.\n const commentOnPullRequest = object(parsed.payload.issue)?.pull_request !== undefined;\n const pullRequest = object(parsed.payload.pull_request) ?? (commentOnPullRequest ? issue : undefined);\n const issueNumber = commentOnPullRequest ? undefined : 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(\n subscription =>\n subscription.orgId === project.orgId && subscription.data?.factoryProjectId === project.factoryProjectId,\n )?.data,\n project.factoryProjectId,\n )\n : null;\n // Re-review events target the PR's own Review card, not the Work item that\n // provenance would otherwise bind the event to. For review_requested the\n // sender is whoever clicked re-request, so a Factory-authored PR must not\n // brand a human requester as factory-authored.\n const reviewRequested = event === 'pullRequestReviewRequested';\n const reviewCommand =\n event === 'pullRequestCommentCreated'\n ? parseFactoryReviewCommand(string(issueComment?.body), this.#factoryMentionTarget())\n : undefined;\n const reviewEntryRequested = reviewRequested || reviewCommand !== undefined;\n // Provenance proves the *pull request* came from Factory, which is not the\n // same as the sender of this event. For events where the sender is whoever\n // reacted to the PR — re-requesting review, commenting, submitting a review\n // — branding them from provenance would mark every human and every review\n // bot as Factory. Only the app login identifies Factory for those.\n const senderIsResponder =\n reviewRequested || event === 'pullRequestCommentCreated' || event === 'pullRequestReviewSubmitted';\n const reReviewEvent = reviewEntryRequested || event === 'pullRequestUpdated';\n const requestedReviewer = string(object(parsed.payload.requested_reviewer)?.login);\n const pullRequestAuthor = string(object(pullRequest?.user)?.login);\n const pullRequestFactoryAuthored = provenance !== null || this.#isFactoryLogin(pullRequestAuthor);\n const resolvedItem = await this.#relatedItem(\n project.orgId,\n project.factoryProjectId,\n repositoryId,\n repositoryName,\n issueNumber,\n pullRequestNumber,\n sameRepositoryHeadBranch(pullRequest, repositoryId),\n reReviewEvent ? null : provenance,\n senderIsResponder && !reviewEntryRequested,\n );\n // A review-entry request must never treat a branch-matched authoring Work\n // card as the PR's Review card. A missing Review card is materialized below.\n const matchedItem =\n reviewEntryRequested &&\n resolvedItem?.externalSource?.type !== 'pull-request' &&\n !(\n resolvedItem &&\n pullRequestNumber &&\n attachedPullRequestSource(resolvedItem, repositoryId, repositoryName, pullRequestNumber)\n )\n ? undefined\n : resolvedItem;\n const intake = intakeTarget(this.#boards(project));\n const actor = await githubActor(this.options.github, {\n installationId,\n repository: repositoryName,\n login,\n factoryAuthored: (!senderIsResponder && provenance !== null) || this.#isFactoryLogin(login),\n });\n // A marked handoff comment is ignored only when Factory authored it: a\n // human may quote the marker to add an investigation lead, and a custom\n // comment rule must still see it. Recognising the author is therefore the\n // whole guard — when identity cannot be resolved this fails open, and a\n // rule that starts triage on comments would cancel the run that wrote it.\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 // A pull request seen for the first time is filed on the card it belongs to, when one is\n // on the board: the card that authored it, or the card of the issue it closes.\n const home =\n event === 'pullRequestOpened' && pullRequestNumber\n ? await this.#pullRequestHome({\n orgId: project.orgId,\n factoryProjectId: project.factoryProjectId,\n repositoryId,\n repositoryName,\n pullRequestNumber,\n matchedItem,\n factoryAuthored: pullRequestFactoryAuthored,\n // Only the author's own trust lets a pull request join another card.\n authorTrusted: actor.type === 'github' && actor.trusted && login === pullRequestAuthor,\n body: string(pullRequest?.body),\n })\n : undefined;\n // The card of an issue the pull request closes isn't the pull request's card yet: the\n // project's intake routes decide, when it is filed, whether it joins that card.\n const relatedItem = (home?.reason === 'authored' ? home.card : undefined) ?? matchedItem;\n const pullRequestHome: FactoryPullRequestHome | undefined = home\n ? { workItemId: home.card.id, reason: home.reason }\n : undefined;\n // One delivery can concern two cards — a merged pull request settles both\n // its own Review card and the Work item that authored it — and every\n // decision a rule returns is committed against a single item, at that\n // item's revision. So the evaluation, not the decision, is what fans out:\n // the rule runs once per bound item, each with its own ingress identity.\n const evaluate = async (\n item: Card | undefined,\n ingressIdentity: string,\n /** Set on the evaluation that files the pull request's own Review card. */\n pullRequestIntake = false,\n attempt = 1,\n ): Promise<{ status: 'ignored' | 'committed' | 'replayed' | 'missing' }> => {\n const context: FactoryGithubRuleContext = {\n tenant: { orgId: project.orgId, projectId: project.factoryProjectId },\n actor,\n ingress: { type: 'github', id: ingressIdentity },\n cause: `github.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(item\n ? {\n item: {\n id: item.id,\n source: workItemSource(item),\n sourceKey: workItemSourceKey(item),\n parentWorkItemId: item.parentWorkItemId,\n title: item.title,\n url: item.externalSource?.url ?? null,\n stages: item.stages,\n workItem: item.workItem,\n acceptedAt: item.acceptedAt,\n metadata: item.metadata,\n },\n board: boardForWorkItem(item),\n itemRevision: item.revision,\n ...withBoardClosure(this.#boards(project), item),\n ...rulePhaseField(this.#boards(project), item),\n ...withBoardFlow(this.#boards(project), item),\n }\n : {}),\n ...(intake ? { intake } : {}),\n ...(pullRequestIntake ? { pullRequestIntake: true } : {}),\n ...(pullRequestHome ? { pullRequestHome } : {}),\n event,\n deliveryId: parsed.deliveryId,\n factory: { createdAt: factoryProject.createdAt.toISOString() },\n repository: { id: repositoryId, fullName: repositoryName, installationId },\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 labels: labelNames(issue?.labels),\n ...(string(object(issue?.user)?.login) ? { author: string(object(issue?.user)?.login) } : {}),\n ...(string(issue?.state) === 'closed' || string(issue?.state) === 'open'\n ? { state: string(issue?.state) as 'open' | 'closed' }\n : {}),\n ...(string(issue?.state_reason) ? { stateReason: string(issue?.state_reason) } : {}),\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)\n ? { author: string(object(issueComment?.user)?.login) }\n : {}),\n ...(string(object(issueComment?.user)?.type)\n ? { authorType: string(object(issueComment?.user)?.type) }\n : {}),\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 labels: labelNames(pullRequest?.labels),\n ...(pullRequestAuthor ? { author: pullRequestAuthor } : {}),\n factoryAuthored: pullRequestFactoryAuthored,\n headBranch: string(object(pullRequest?.head)?.ref) ?? '',\n ...(string(object(pullRequest?.head)?.sha)\n ? { headSha: string(object(pullRequest?.head)?.sha)!.toLowerCase() }\n : {}),\n baseBranch: string(object(pullRequest?.base)?.ref) ?? '',\n },\n }\n : {}),\n ...(reviewRequested && requestedReviewer\n ? {\n reviewRequest: {\n reviewer: requestedReviewer,\n factoryReviewer: this.#isFactoryLogin(requestedReviewer),\n },\n }\n : {}),\n ...(reviewCommand ? { reviewCommand } : {}),\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 ...(string(object(object(parsed.payload.review)?.user)?.login)\n ? { author: string(object(object(parsed.payload.review)?.user)?.login) }\n : {}),\n ...(string(object(parsed.payload.review)?.body)\n ? { body: string(object(parsed.payload.review)?.body) }\n : {}),\n },\n }\n : {}),\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n\n const ownedByDeployment = deploymentOwnsEvent(\n this.options.github.rules,\n boardEventHandlers(this.#boards(project), eventBoardId(context), 'github'),\n event,\n );\n const rule = selectEventRule(\n this.options.github.rules,\n boardEventHandlers(this.#boards(project), eventBoardId(context), 'github'),\n event,\n );\n let decision: FactoryRuleDecision | void = undefined;\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 => {\n assertFactoryDecisionTarget(entry, this.#boards(project), item ? boardForWorkItem(item) : undefined);\n return { ...entry };\n });\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 if (ownedByDeployment) decisions = decisions.map(withoutRouteEvent);\n if (!decision && !ownedByDeployment && outcome.status === 'accepted') {\n const routed =\n (await routeEventDecision(context, this.options.storage, {\n orgId: project.orgId,\n factoryProjectId: project.factoryProjectId,\n })) ?? activitySignalFor(context);\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: project.orgId,\n factoryProjectId: project.factoryProjectId,\n workItemId: item?.id ?? null,\n ingress: { identity: ingressIdentity, triggerType: `github.${event}` },\n configVersion: this.options.configVersion,\n expectedRevision: item?.revision ?? null,\n actor: { ...actor },\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n // The item was written concurrently. Re-read it and run the rule again\n // against the fresh revision; nothing was persisted for this attempt.\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory GitHub rule evaluation for ${ingressIdentity} kept losing revision races.`);\n }\n const fresh = item ? await this.options.storage.get({ orgId: project.orgId, id: item.id }) : null;\n if (item && !fresh) return { status: 'missing' };\n return evaluate(fresh ?? undefined, ingressIdentity, pullRequestIntake, attempt + 1);\n }\n return { status: committed.status };\n };\n\n // A push moves the head a recorded review verdict was given on. Recording\n // the new head lets the verdict badge show that it is outdated, while the\n // verdict itself stays so the next pass still runs as a re-review. It is\n // recorded before the push is evaluated: the dispatcher can apply the\n // re-review transition as soon as it commits, and the pass it starts names\n // the head it covers, which must be the pushed one.\n const stampHead = async () => {\n const headSha = string(object(pullRequest?.head)?.sha)?.toLowerCase();\n if (event !== 'pullRequestUpdated' || !headSha || !pullRequestNumber) return;\n const headAt = timestamp(pullRequest?.updated_at);\n // A pull request attached to its issue's card records its head there, while it is the one out.\n if (relatedItem && attachedPullRequestSource(relatedItem, repositoryId, repositoryName, pullRequestNumber)) {\n await recordPullRequestHead(this.options.storage, {\n orgId: relatedItem.orgId,\n id: relatedItem.id,\n headSha,\n headAt,\n ownedPullRequestNumber: pullRequestNumber,\n });\n return;\n }\n if (relatedItem?.externalSource?.type !== 'pull-request') return;\n const parent = await this.#linkedClosureItem(\n project.orgId,\n project.factoryProjectId,\n repositoryId,\n repositoryName,\n pullRequestNumber,\n relatedItem,\n );\n // The authoring Work item mirrors the verdict of the pull request it has\n // out; a push to an older one must not mark its successor's verdict.\n await recordPullRequestHead(this.options.storage, {\n orgId: relatedItem.orgId,\n id: relatedItem.id,\n headSha,\n headAt,\n });\n if (parent) {\n await recordPullRequestHead(this.options.storage, {\n orgId: parent.orgId,\n id: parent.id,\n headSha,\n headAt,\n ownedPullRequestNumber: pullRequestNumber,\n });\n }\n };\n await stampHead();\n const evaluated =\n event === 'pullRequestUpdated' && relatedItem\n ? ((await this.options.storage.get({ orgId: relatedItem.orgId, id: relatedItem.id })) ?? relatedItem)\n : relatedItem;\n const deliveryIdentity = `${installationId}:${parsed.deliveryId}`;\n // A pull request opening concerns two cards: its own Review card, which the\n // arrival rule files — committed against the Work item that authored the\n // pull request when one exists, because that binding is what links the two\n // — and that authoring item, which is now out for review. The arrival is\n // the delivery's own evaluation; the item's is a second one, under an\n // identity suffixed with its id, because ingress identities are the replay\n // key and reusing the delivery's own would drop it as a duplicate.\n const pullRequestOpened = event === 'pullRequestOpened';\n const primary = await evaluate(evaluated, deliveryIdentity, pullRequestOpened);\n // A closed pull request is the one *other* event both linked cards need:\n // the Review card has to close, and the Work item that wrote the code has\n // to finish (on merge) or at least stop recording it as open. Resolution binds the delivery to\n // whichever card it matched first, so evaluate the other one too.\n const linked =\n (event === 'pullRequestMerged' || event === 'pullRequestClosed') && relatedItem && pullRequestNumber\n ? await this.#linkedClosureItem(\n project.orgId,\n project.factoryProjectId,\n repositoryId,\n repositoryName,\n pullRequestNumber,\n relatedItem,\n // Only a trusted author's (or Factory's) pull request may finish a card by its branch name.\n // The lookup is needed only when an unlinked Review card leaves the branch to decide.\n relatedItem.externalSource?.type === 'pull-request' &&\n !relatedItem.parentWorkItemId &&\n (pullRequestFactoryAuthored ||\n (pullRequestAuthor !== undefined &&\n (await trustedCollaborator(this.options.github, {\n installationId,\n repository: repositoryName,\n login: pullRequestAuthor,\n }))))\n ? sameRepositoryHeadBranch(pullRequest, repositoryId)\n : undefined,\n )\n : undefined;\n // Moving the card to Done does not touch its pull request fields, so without\n // this the card reads \"open\" until the next sweep and still offers Re-review.\n // Stamped after the evaluations, which commit at the revision they read.\n const stampClosed = async (companionStatus?: string) => {\n if (!pullRequestNumber) return;\n // The authoring Work item records which pull request it has out, so an\n // agent cannot close the work while that pull request is still open.\n if (pullRequestOpened) {\n // Mirrors the out-for-review rule's trust gate. A replayed opened\n // delivery only restores the mark (after a failed write) while the\n // pull request's Review card still records it open, so a redelivery\n // after the close cannot block the Work item again.\n const trusted = (actor.type === 'github' && actor.trusted) || pullRequestFactoryAuthored;\n if (!authoringItem || !trusted || authoringItem.metadata?.openPullRequestNumber === pullRequestNumber) return;\n const reviewCard = await this.#linkedClosureItem(\n project.orgId,\n project.factoryProjectId,\n repositoryId,\n repositoryName,\n pullRequestNumber,\n authoringItem,\n );\n // Filed on the authoring card itself, the pull request's own source says whether it is open.\n const attached = attachedPullRequestSource(authoringItem, repositoryId, repositoryName, pullRequestNumber);\n const recordedState = reviewCard ? reviewCard.workItem.state : attached?.state;\n const stillOpen =\n companionStatus === 'replayed'\n ? (reviewCard !== undefined || attached !== undefined) && !['closed', 'merged'].includes(recordedState ?? '')\n : !['closed', 'merged'].includes(recordedState ?? '');\n if (!stillOpen) return;\n // Only a pull request the card wrote is the one it has out. One filed there because it\n // closes the issue is someone else's work: recording it would stop the builder's own\n // self-review and pull request.\n const headBranch = string(object(pullRequest?.head)?.ref);\n const ownedByCard =\n home?.reason === 'authored' ||\n (home === undefined &&\n (attached === undefined ||\n pullRequestFactoryAuthored ||\n cardOwnsBranch(authoringItem, headBranch)));\n if (!ownedByCard) return;\n // The head comes along so a head recorded for an earlier pull\n // request cannot mark this one's verdict outdated.\n await this.options.storage.update({\n orgId: authoringItem.orgId,\n id: authoringItem.id,\n userId: 'factory-rule-dispatcher',\n patch: {\n metadata: {\n openPullRequestNumber: pullRequestNumber,\n pullRequestHeadSha: string(object(pullRequest?.head)?.sha)?.toLowerCase() ?? null,\n pullRequestHeadAt: timestamp(pullRequest?.updated_at) ?? null,\n },\n },\n });\n return;\n }\n if (event !== 'pullRequestMerged' && event !== 'pullRequestClosed') return;\n for (const card of [relatedItem, linked]) {\n if (!card) continue;\n if (card.externalSource?.type !== 'pull-request') {\n // A pull request attached to this card settles on its own source, never the issue's.\n const attached = attachedPullRequestSource(card, repositoryId, repositoryName, pullRequestNumber);\n if (attached) {\n await this.options.storage.syncWorkItemSource({\n orgId: card.orgId,\n factoryProjectId: card.factoryProjectId,\n provider: attached.provider,\n externalId: attached.externalId,\n patch: {\n state: event === 'pullRequestMerged' ? 'merged' : 'closed',\n metadata: { state: 'closed', merged: event === 'pullRequestMerged' },\n },\n });\n }\n // Numbers repeat across repositories: a card carrying pull requests settles only for one of its own.\n if (!attached && pullRequestSources(card).length > 0) continue;\n // A merge settles the review, so the authoring Work item's mirrored\n // \"request changes\" no longer stops it from being closed.\n // Only the pull request the card has out settles it; an older one\n // merging must not clear a verdict that belongs to its successor.\n const recorded = card.metadata?.openPullRequestNumber;\n const ownsCard = typeof recorded !== 'number' || recorded === pullRequestNumber;\n const settled = {\n ...(ownsCard && event === 'pullRequestMerged' && typeof card.metadata?.reviewVerdict === 'string'\n ? { reviewVerdict: null }\n : {}),\n // With several pull requests on the card, the newest one its sessions opened is out next;\n // someone else's pull request never becomes the card's own.\n ...(recorded === pullRequestNumber\n ? { openPullRequestNumber: newestOwnedOpenPullRequestNumber(card, pullRequestNumber) }\n : {}),\n };\n if (Object.keys(settled).length > 0) {\n await this.options.storage.update({\n orgId: card.orgId,\n id: card.id,\n userId: 'factory-rule-dispatcher',\n patch: { metadata: settled },\n });\n }\n continue;\n }\n await this.options.storage.syncCard({\n orgId: card.orgId,\n id: card.id,\n userId: 'factory-rule-dispatcher',\n patch: { metadata: { state: 'closed', merged: event === 'pullRequestMerged' } },\n });\n }\n };\n const authoringItem =\n linked === undefined &&\n pullRequestOpened &&\n relatedItem !== undefined &&\n relatedItem.externalSource?.type !== 'pull-request'\n ? relatedItem\n : undefined;\n if (linked === undefined && authoringItem === undefined) {\n await stampClosed();\n return primary;\n }\n const companion = linked ?? authoringItem;\n const secondary = await evaluate(companion, `${deliveryIdentity}:${companion?.id ?? 'pull-request'}`);\n await stampClosed(secondary.status);\n for (const status of ['committed', 'replayed'] as const) {\n if (primary.status === status || secondary.status === status) return { status };\n }\n return primary;\n }\n\n /**\n * The other card a closed pull request concerns, joined through the Review\n * card's `parentWorkItemId` — the link `upsertLinkedWorkItem` records when the\n * pull request is opened, and therefore an exact join that needs no branch\n * heuristics. Returns nothing when the pull request has only one card, which\n * is every pull request Factory did not open from a work item's session.\n */\n async #linkedClosureItem(\n orgId: string,\n projectId: string,\n repositoryId: number,\n repositoryFullName: string,\n pullRequestNumber: number,\n resolved: Card,\n headBranch?: string,\n ): Promise<Card | undefined> {\n await this.options.storage.copyLegacyCards({\n orgId,\n factoryProjectId: projectId,\n sources: githubItemSources(repositoryId, 'pull-request', pullRequestNumber),\n });\n const items = await this.options.storage.list({ orgId, factoryProjectId: projectId });\n const linked =\n resolved.externalSource?.type === 'pull-request'\n ? // Bound to the pull request's own Review card: follow the recorded\n // link back to the work item that authored it. A card filed without\n // that link (no provenance when the pull request opened) is joined by\n // its head branch, so the merge still finishes the authoring item.\n resolved.parentWorkItemId\n ? await this.#parentItem(orgId, projectId, items, resolved)\n : branchAuthoringItem(items, headBranch, repositoryId, repositoryFullName)\n : // Bound to the work item (provenance): find the Review card this pull\n // request opened, and only when it names this item as its parent — a\n // card for the same number in another repository is not this one's.\n items.find(\n item =>\n item.parentWorkItemId === resolved.id &&\n (item.externalSource?.externalId === canonicalSourceKey('pull-request', pullRequestNumber) ||\n item.externalSource?.externalId === legacySourceKey(repositoryId, 'pull-request', pullRequestNumber)) &&\n cardBelongsToRepository(item, repositoryId, repositoryFullName),\n );\n return linked?.id === resolved.id ? undefined : linked;\n }\n\n /**\n * The existing card a pull request opened for the first time belongs with, or undefined when it\n * gets a card of its own. The card must be open, in this repository, and not a pull request's\n * own card. In order: the card that authored it (on a board that reviews pull requests), by provenance or session branch,\n * when the pull request is Factory-authored or its author is trusted; it is filed there. Then,\n * for a trusted author only, the card of the first issue its description says it closes; an\n * intake route decides whether it joins that one. An untrusted author's pull request never\n * lands on another card, whatever it says.\n */\n async #pullRequestHome(input: {\n orgId: string;\n factoryProjectId: string;\n repositoryId: number;\n repositoryName: string;\n pullRequestNumber: number;\n matchedItem: Card | undefined;\n factoryAuthored: boolean;\n authorTrusted: boolean;\n body: string | undefined;\n }): Promise<{ card: Card; reason: FactoryPullRequestHome['reason'] } | undefined> {\n if (!input.factoryAuthored && !input.authorTrusted) return undefined;\n const items = await this.options.storage.list({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const filed = items.some(\n item =>\n attachedPullRequestSource(item, input.repositoryId, input.repositoryName, input.pullRequestNumber) ||\n (item.externalSource?.type === 'pull-request' &&\n (item.externalSource.externalId === canonicalSourceKey('pull-request', input.pullRequestNumber) ||\n item.externalSource.externalId ===\n legacySourceKey(input.repositoryId, 'pull-request', input.pullRequestNumber)) &&\n cardBelongsToRepository(item, input.repositoryId, input.repositoryName)),\n );\n if (filed) return undefined;\n const eligible = (card: Card) =>\n card.externalSource?.type !== 'pull-request' &&\n !isTerminalWorkItem(this.#boards(input), card) &&\n cardBelongsToRepository(card, input.repositoryId, input.repositoryName);\n if (\n input.matchedItem &&\n eligible(input.matchedItem) &&\n cardBoardFlow(this.#boards(input), input.matchedItem).pullRequestReview !== undefined\n ) {\n return { card: input.matchedItem, reason: 'authored' };\n }\n if (!input.authorTrusted) return undefined;\n for (const issueNumber of closingIssueNumbers(input.body, { provider: 'github', repository: input.repositoryName })) {\n const card = items.find(\n item =>\n (item.externalSource?.externalId === canonicalSourceKey('issue', issueNumber) ||\n item.externalSource?.externalId === legacySourceKey(input.repositoryId, 'issue', issueNumber)) &&\n eligible(item),\n );\n if (card) return { card, reason: 'closes' };\n }\n return undefined;\n }\n\n async #relatedItem(\n orgId: string,\n projectId: string,\n repositoryId: number,\n repositoryFullName: string,\n issueNumber: number | undefined,\n pullRequestNumber: number | undefined,\n pullRequestHeadBranch: string | undefined,\n provenance: FactoryPullRequestProvenanceData | null,\n preferAuthoringItem = false,\n ): Promise<Card | undefined> {\n // A finished card may still be only in the legacy table; copy it so the event finds it.\n await this.options.storage.copyLegacyCards({\n orgId,\n factoryProjectId: projectId,\n sources: [\n ...(issueNumber ? githubItemSources(repositoryId, 'issue', issueNumber) : []),\n ...(pullRequestNumber ? githubItemSources(repositoryId, 'pull-request', pullRequestNumber) : []),\n ],\n });\n if (provenance) await this.options.storage.getForProject(orgId, projectId, provenance.workItemId);\n const items = await this.options.storage.list({ orgId, factoryProjectId: projectId });\n const resolved = this.#resolveItem(\n items,\n repositoryId,\n repositoryFullName,\n issueNumber,\n pullRequestNumber,\n pullRequestHeadBranch,\n provenance,\n );\n // Feedback on a pull request has to reach the item that *wrote* the code.\n // Provenance normally lands it there directly, but when provenance is\n // missing the PR-number lookup wins and returns the PR's own Review card\n // instead — a board the feedback rules deliberately refuse to act on, so\n // the wake is silently dropped. The linked card records its author in\n // `parentWorkItemId`, so follow that link back rather than relaxing the\n // guard, which would let a Review card react to its own posted review.\n if (preferAuthoringItem && resolved?.externalSource?.type === 'pull-request' && resolved.parentWorkItemId) {\n return (await this.#parentItem(orgId, projectId, items, resolved)) ?? resolved;\n }\n return resolved;\n }\n\n /** The card `child` was filed from; read on its own when the board list lacks it (not copied yet). */\n async #parentItem(orgId: string, projectId: string, items: Card[], child: Card): Promise<Card | undefined> {\n if (!child.parentWorkItemId) return undefined;\n return (\n items.find(item => item.id === child.parentWorkItemId) ??\n (await this.options.storage.getForProject(orgId, projectId, child.parentWorkItemId)) ??\n undefined\n );\n }\n\n #resolveItem(\n items: Card[],\n repositoryId: number,\n repositoryFullName: string,\n issueNumber: number | undefined,\n pullRequestNumber: number | undefined,\n pullRequestHeadBranch: string | undefined,\n provenance: FactoryPullRequestProvenanceData | null,\n ): Card | undefined {\n if (provenance) return items.find(item => item.id === provenance.workItemId);\n if (issueNumber) {\n return (\n items.find(\n item =>\n item.externalSource?.externalId === canonicalSourceKey('issue', issueNumber) &&\n cardBelongsToRepository(item, repositoryId, repositoryFullName),\n ) ?? items.find(item => item.externalSource?.externalId === legacySourceKey(repositoryId, 'issue', issueNumber))\n );\n }\n if (pullRequestNumber) {\n return (\n items.find(\n item =>\n item.externalSource?.externalId === canonicalSourceKey('pull-request', pullRequestNumber) &&\n cardBelongsToRepository(item, repositoryId, repositoryFullName),\n ) ??\n items.find(\n item => item.externalSource?.externalId === legacySourceKey(repositoryId, 'pull-request', pullRequestNumber),\n ) ??\n // A pull request attached to its issue's card.\n items.find(item => attachedPullRequestSource(item, repositoryId, repositoryFullName, pullRequestNumber)) ??\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 branchAuthoringItem(items, pullRequestHeadBranch, repositoryId, repositoryFullName)\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 labels?: string[];\n headBranch: string;\n baseBranch: string;\n author?: string;\n createdAt?: string;\n mergedBy?: string;\n}\n\nexport interface PolledPullRequestState extends ReconcilePullRequestState {\n createdAt: string;\n}\n\nexport type GithubPullRequestFetcher = (input: {\n installationId: number;\n repository: string;\n number: number;\n}) => Promise<ReconcilePullRequestState | undefined>;\n\nexport interface ReconcileIssueState {\n title: string;\n url: string;\n state: 'open' | 'closed';\n /** GitHub close reason: `completed`, `not_planned`, or `duplicate`. */\n stateReason?: string;\n assignees?: string[];\n labels?: string[];\n author?: string;\n createdAt?: string;\n updatedAt?: string;\n}\n\nexport type GithubIssueFetcher = (input: {\n installationId: number;\n repository: string;\n number: number;\n}) => Promise<ReconcileIssueState | undefined>;\n\n/** Lists a repository's open issues (pull requests excluded) for missed-open discovery. */\nexport type GithubOpenIssueLister = (input: {\n installationId: number;\n repository: string;\n}) => Promise<Array<ReconcileIssueState & { number: number }>>;\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/issues (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; issueNumber?: number; error: string }>;\n}\n\nexport type GithubPullRequestReconciler = (repositories: ReconcileRepository[]) => Promise<ReconcileSweepSummary>;\n\nexport const RECONCILE_ERROR_SAMPLE_LIMIT = 5;\n\nexport function 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: Card, 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\n/** The number of an attached pull request source, when it belongs to the given repository. */\nfunction attachedPullRequestNumber(source: WorkItemSourceRow, repository: ReconcileRepository): number | undefined {\n if (source.integrationId !== 'github') return undefined;\n if (source.url) {\n const match = /^https?:\\/\\/[^/]+\\/(.+)\\/pull\\/(\\d+)(?:[/?#]|$)/.exec(source.url);\n return match && match[1] === repository.fullName ? Number(match[2]) : undefined;\n }\n const legacy = /^pull-request:github:(\\d+):pull-request:(\\d+)$/.exec(source.externalId);\n return legacy && Number(legacy[1]) === repository.id ? Number(legacy[2]) : undefined;\n}\n\n/**\n * Extracts the issue number a work item tracks, but only when the item\n * belongs to the given repository. Stricter than\n * {@link reconcilablePullRequestNumber}: a canonical key with no URL is only\n * trusted when the intake-stamped `githubRepositoryId` confirms the\n * repository, because the sweep initiates closes on its own.\n */\nexport function reconcilableIssueNumber(item: Card, repository: ReconcileRepository): number | undefined {\n if (item.externalSource?.type !== 'issue') return undefined;\n const url = item.externalSource.url;\n if (url) {\n const match = /^https?:\\/\\/[^/]+\\/(.+)\\/issues\\/(\\d+)(?:[/?#]|$)/.exec(url);\n if (!match) return undefined;\n // A renamed repository leaves the old owner/name in the card URL, so a\n // URL mismatch still defers to the stable intake-stamped repository id.\n const belongs = match[1] === repository.fullName || item.workItem.metadata?.githubRepositoryId === repository.id;\n return belongs ? Number(match[2]) : undefined;\n }\n const externalId = item.externalSource.externalId;\n const legacy = /^github:(\\d+):issue:(\\d+)$/.exec(externalId);\n if (legacy) return Number(legacy[1]) === repository.id ? Number(legacy[2]) : undefined;\n const canonical = /^github-issue:(\\d+)$/.exec(externalId);\n if (!canonical) return undefined;\n // Canonical keys carry no repository; only the intake-stamped repository id\n // can attribute a URL-less card, and guessing would let a multi-repo\n // project close repo B's card because repo A's same-numbered issue closed.\n return item.workItem.metadata?.githubRepositoryId === repository.id ? Number(canonical[1]) : undefined;\n}\n\nexport function reconciledIssueClosedEvent(\n repository: ReconcileRepository,\n issueNumber: number,\n state: ReconcileIssueState,\n): ParsedGithubWebhook {\n return {\n event: 'issues',\n // Stable per (repository, issue): the ingress dedupe makes repeat\n // reconcile cycles replay instead of re-committing decisions.\n deliveryId: `reconcile:${repository.id}:issue:${issueNumber}:closed`,\n payload: {\n action: 'closed',\n installation: { id: repository.installationId },\n repository: { id: repository.id, full_name: repository.fullName },\n sender: { login: state.author ?? 'github' },\n issue: {\n number: issueNumber,\n title: state.title,\n html_url: state.url,\n state: 'closed',\n ...(state.stateReason ? { state_reason: state.stateReason } : {}),\n ...(state.createdAt ? { created_at: state.createdAt } : {}),\n ...(state.updatedAt ? { updated_at: state.updatedAt } : {}),\n assignees: githubUsers(state.assignees),\n },\n },\n };\n}\n\n/**\n * The label-drift replay: an open issue whose labels changed without a\n * `labeled`/`unlabeled` webhook ever arriving (Factory was down, the delivery\n * was lost, or the label was applied by something other than a delivery the\n * webhook saw). Synthesized as an `opened` delivery so the deployment's\n * `issueOpened` rule decides placement, exactly as it does at arrival — one\n * source of placement policy for both.\n */\nexport function reconciledIssueRelabeledEvent(\n repository: ReconcileRepository,\n issueNumber: number,\n state: ReconcileIssueState,\n): ParsedGithubWebhook {\n const labels = state.labels ?? [];\n // GitHub updates `updated_at` for a label change. Including it makes retries\n // of one observed issue version idempotent while allowing A → B → A to replay\n // its final A placement as a new version. Synthetic callers without it retain\n // the legacy label-only identity.\n const digest = createHash('sha256')\n .update([...labels].sort().join('\\n'))\n .digest('hex')\n .slice(0, 16);\n const version = state.updatedAt ? `:${createHash('sha256').update(state.updatedAt).digest('hex').slice(0, 16)}` : '';\n return {\n event: 'issues',\n deliveryId: `reconcile:${repository.id}:issue:${issueNumber}:relabeled:${digest}${version}`,\n payload: {\n // `opened` is the event that carries an issue's labels through the rules;\n // an already-filed card is re-placed by the decision, not re-materialized.\n action: 'opened',\n installation: { id: repository.installationId },\n repository: { id: repository.id, full_name: repository.fullName },\n sender: { login: state.author ?? 'github' },\n issue: {\n number: issueNumber,\n title: state.title,\n html_url: state.url,\n state: 'open',\n ...(state.createdAt ? { created_at: state.createdAt } : {}),\n ...(state.updatedAt ? { updated_at: state.updatedAt } : {}),\n assignees: githubUsers(state.assignees),\n labels: githubLabels(labels),\n },\n },\n };\n}\n\n/**\n * The missed-open replay: an open issue with no Work card, because its\n * `opened` delivery never reached the rules ingress. Synthesized as the same\n * `opened` delivery so the deployment's `issueOpened` rule decides whether and\n * where it lands, exactly as it would have at arrival. The delivery id is\n * stable per issue so repeat sweeps dedupe at the ingress.\n */\nexport function reconciledIssueOpenedEvent(\n repository: ReconcileRepository,\n issueNumber: number,\n state: ReconcileIssueState,\n): ParsedGithubWebhook {\n const event = reconciledIssueRelabeledEvent(repository, issueNumber, state);\n return { ...event, deliveryId: `reconcile:${repository.id}:issue:${issueNumber}:opened` };\n}\n\nexport function polledPullRequestEvent(\n repository: ReconcileRepository,\n pullRequestNumber: number,\n state: PolledPullRequestState,\n): ParsedGithubWebhook {\n return {\n event: 'pull_request',\n deliveryId: `poll:${repository.id}:pull-request:${pullRequestNumber}:${state.createdAt}`,\n payload: {\n action: 'opened',\n installation: { id: repository.installationId },\n repository: { id: repository.id, full_name: repository.fullName },\n sender: { login: state.author ?? '__unknown__' },\n pull_request: pullRequestPayload(pullRequestNumber, state),\n },\n };\n}\n\nexport function reconciledClosedEvent(\n repository: ReconcileRepository,\n pullRequestNumber: number,\n state: ReconcilePullRequestState,\n): ParsedGithubWebhook {\n const outcome = state.merged ? 'merged' : 'closed';\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}:${outcome}`,\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: pullRequestPayload(pullRequestNumber, { ...state, state: 'closed' }),\n },\n };\n}\n\nfunction pullRequestPayload(pullRequestNumber: number, state: ReconcilePullRequestState): Record<string, unknown> {\n const payload: Record<string, unknown> = {\n number: pullRequestNumber,\n title: state.title,\n html_url: state.url,\n state: state.state,\n draft: state.draft,\n merged: state.merged,\n assignees: githubUsers(state.assignees),\n requested_reviewers: githubUsers(state.requestedReviewers),\n labels: githubLabels(state.labels),\n head: { ref: state.headBranch },\n base: { ref: state.baseBranch },\n };\n if (state.createdAt) payload.created_at = state.createdAt;\n if (state.author) payload.user = { login: state.author };\n return payload;\n}\n\nfunction githubUsers(logins: readonly string[] = []): Array<{ login: string }> {\n return logins.map(login => ({ login }));\n}\n\nfunction githubLabels(names: readonly string[] = []): Array<{ name: string }> {\n return names.map(name => ({ name }));\n}\n\nfunction reconciledPullRequestMetadata(\n state: ReconcilePullRequestState,\n reconciliation: 'clear' | 'settled' | undefined,\n authorTrusted?: boolean,\n): Record<string, unknown> {\n return {\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 ...(state.labels ? { labels: state.labels } : {}),\n ...(authorTrusted === undefined ? {} : { authorTrusted }),\n ...(reconciliation === undefined\n ? {}\n : {\n [FACTORY_PULL_REQUEST_RECONCILIATION_KEY]:\n reconciliation === 'settled' ? (state.merged ? 'merged' : 'closed') : null,\n }),\n };\n}\n\nfunction reconciledPullRequestOutcome(metadata: Record<string, unknown>): 'merged' | 'closed' | undefined {\n if (metadata.state !== 'closed' || typeof metadata.merged !== 'boolean') return undefined;\n return metadata.merged ? 'merged' : 'closed';\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 = {\n repositories: 0,\n checked: 0,\n merged: 0,\n closed: 0,\n failed: 0,\n errors: [],\n };\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, Card[]>;\n // Open pull requests attached to an issue's card. Their facts live on their own source, so\n // the sweep only replays a missed close; the rules settle the source and the card.\n let attachedOpen: Set<number>;\n let unanswered: Array<{ item: Card; author: string }>;\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, Card[]>();\n attachedOpen = new Set<number>();\n unanswered = [];\n for (const project of projects) {\n await rules.loadBoards(project);\n const items = await options.storage.list({\n orgId: project.orgId,\n factoryProjectId: project.factoryProjectId,\n });\n for (const item of items) {\n const unansweredAuthor = authorAwaitingTrust(item, repository);\n if (unansweredAuthor) unanswered.push({ item, author: unansweredAuthor });\n if (item.externalSource?.type !== 'pull-request' && !isTerminalWorkItem(toBoardSource(options.boards).forProject(item), item)) {\n for (const source of pullRequestSources(item)) {\n const number = attachedPullRequestNumber(source, repository);\n if (number !== undefined && !['closed', 'merged'].includes(source.state ?? '')) attachedOpen.add(number);\n }\n }\n const pullRequestNumber = reconcilablePullRequestNumber(item, repository);\n if (!pullRequestNumber) continue;\n const metadata = { ...item.workItem.metadata, ...item.metadata };\n const reconciliation = metadata[FACTORY_PULL_REQUEST_RECONCILIATION_KEY];\n const reconciledOutcome = reconciledPullRequestOutcome(metadata);\n if (\n workItemPhaseSemantics(toBoardSource(options.boards).forProject(item), item)?.kind === 'terminal' &&\n reconciledOutcome !== undefined &&\n reconciliation === reconciledOutcome\n ) {\n continue;\n }\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 const authorTrust = sweepTrustLookup(options.github, repository);\n for (const { item, author } of unanswered) {\n try {\n await options.storage.syncCard({\n orgId: item.orgId,\n id: item.id,\n userId: 'factory-rule-dispatcher',\n patch: { metadata: { authorTrusted: await authorTrust(author) } },\n });\n } catch (error) {\n recordFailure(repository, error);\n }\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 // Re-stamped on every sweep so revoked write access reads untrusted\n // within one cycle; a failed lookup keeps the last stamp and retries.\n let authorTrusted: boolean | undefined;\n if (state.author !== undefined) {\n try {\n authorTrusted = await authorTrust(state.author);\n } catch (error) {\n recordFailure(repository, error, pullRequestNumber);\n }\n }\n for (const card of cards) {\n if (state.state === 'closed') continue;\n const metadata = { ...card.workItem.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 const labelsChanged = !sameStrings(metadata.labels, state.labels);\n const trustStale = authorTrusted !== undefined && metadata.authorTrusted !== authorTrusted;\n const metadataChanged =\n statusChanged || authorChanged || assigneesChanged || reviewersChanged || labelsChanged || trustStale;\n const reconciliation = metadata[FACTORY_PULL_REQUEST_RECONCILIATION_KEY];\n if (!metadataChanged && reconciliation !== 'merged' && reconciliation !== 'closed') continue;\n try {\n await options.storage.syncCard({\n orgId: card.orgId,\n id: card.id,\n userId: 'factory-rule-dispatcher',\n patch: {\n metadata: reconciledPullRequestMetadata(\n state,\n reconciliation === 'merged' || reconciliation === 'closed' ? 'clear' : undefined,\n trustStale ? authorTrusted : undefined,\n ),\n },\n });\n } catch (error) {\n recordFailure(repository, error, pullRequestNumber);\n }\n }\n if (state.state !== 'closed') continue;\n const cleanupFailures = new Set<string>();\n for (const card of cards) {\n if (workItemPhaseSemantics(toBoardSource(options.boards).forProject(card), card)?.kind !== 'terminal') continue;\n try {\n await options.storage.supersedeDecisionsForWorkItem({\n orgId: card.orgId,\n factoryProjectId: card.factoryProjectId,\n workItemId: card.id,\n supersededAt: new Date(),\n });\n } catch (error) {\n recordFailure(repository, error, pullRequestNumber);\n cleanupFailures.add(card.id);\n }\n }\n await rules.ingest(reconciledClosedEvent(repository, pullRequestNumber, state));\n await retireReconciledSubscriptions(options.integrationStorage, repository, pullRequestNumber, state.merged);\n for (const card of cards) {\n if (cleanupFailures.has(card.id)) continue;\n const trustStale = authorTrusted !== undefined && (card.metadata ?? {}).authorTrusted !== authorTrusted;\n try {\n await options.storage.syncCard({\n orgId: card.orgId,\n id: card.id,\n userId: 'factory-rule-dispatcher',\n patch: {\n metadata: reconciledPullRequestMetadata(state, 'settled', trustStale ? authorTrusted : undefined),\n },\n });\n } catch (error) {\n recordFailure(repository, error, pullRequestNumber);\n }\n }\n if (state.merged) summary.merged += 1;\n else summary.closed += 1;\n } catch (error) {\n recordFailure(repository, error, pullRequestNumber);\n }\n }\n for (const pullRequestNumber of attachedOpen) {\n if (cardsByNumber.has(pullRequestNumber)) continue;\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 !== '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\nexport function githubRulesOptions(\n github: GithubRulesIntegration,\n context: IntegrationContext,\n): GithubRulesOptions | undefined {\n if (!context.runtime) return undefined;\n return {\n github,\n sourceControl: context.storage.sourceControl,\n integrationStorage: context.storage.generic,\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards: context.runtime.boards,\n ...(context.hooks?.onRepositoryPush ? { onRepositoryPush: context.hooks.onRepositoryPush } : {}),\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":";;;;;;;;;;;;;;;;;AA2DA,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,UAAU,OAAoC;CACrD,MAAM,SAAS,OAAO,UAAU,WAAW,KAAK,MAAM,KAAK,IAAI;CAC/D,OAAO,OAAO,MAAM,MAAM,IAAI,KAAA,IAAY;AAC5C;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;AAE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WAAW;KACnB,IAAI,OAAO,UAAU,UAAU;KAC/B,MAAM,MAAM,OAAO,sBAAsB,YAAY,mBAAmB,KAAK,CAAC;KAC9E,MAAM,8BAA8B,QAAQ,oBAAoB,YAAY,mBAAmB,MAAM,MAAM;KAC3G,IAAI,MAAM,QAAQ,QAAQ,UAAU;UAC/B,QAAQ,UAAU;IACzB,SAAS,OAAO;KACd,cAAc,YAAY,OAAO,iBAAiB;IACpD;GACF;EACF;EACA,OAAO;CACT;AACF;AAEA,SAAgB,mBACd,QACA,SACgC;CAChC,IAAI,CAAC,QAAQ,SAAS,OAAO,KAAA;CAC7B,OAAO;EACL;EACA,eAAe,QAAQ,QAAQ;EAC/B,oBAAoB,QAAQ,QAAQ;EACpC,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ,QAAQ;EACzB,eAAe,QAAQ,QAAQ;EAC/B,QAAQ,QAAQ,QAAQ;EACxB,GAAI,QAAQ,OAAO,mBAAmB,EAAE,kBAAkB,QAAQ,MAAM,iBAAiB,IAAI,CAAC;CAChG;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":[],"sources":["../../../src/integrations/github/rules.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\n\nimport { closeReason } from '../../boards/board-events.js';\nimport type { BoardEventFacts } from '../../boards/board-events.js';\nimport {\n boardEventHandlers,\n boardForWorkItem,\n cardBoardFlow,\n eventBoardId,\n isTerminalWorkItem,\n cardOwnsBranch,\n newestOwnedOpenPullRequestNumber,\n pullRequestSources,\n intakeTarget,\n rulePhaseField,\n withBoardClosure,\n withBoardFlow,\n workItemPhaseSemantics,\n} from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { cardLabels } from '../../boards/relocate.js';\nimport type { PullRequest, PullRequestPage, VersionControl } from '../../capabilities/version-control.js';\nimport { requestsChangesVerdict } from '../../review-verdict.js';\nimport { deploymentOwnsEvent, routeEventDecision, selectEventRule, withoutRouteEvent } from '../../rules/event-rules.js';\nimport type {\n FactoryGithubEventName,\n FactoryGithubRuleContext,\n FactoryPullRequestHome,\n FactoryRuleActor,\n FactoryRuleDecision,\n FactorySignalActivityDecision,\n} from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.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 { Card, ExternalWorkItemSource, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport {\n FACTORY_PULL_REQUEST_RECONCILIATION_KEY,\n WorkItemUpdateConflictError,\n} from '../../storage/domains/work-items/base.js';\nimport { primarySource } from '../../storage/domains/work-items/work-item-schema.js';\nimport type { WorkItemSourceRow } from '../../storage/domains/work-items/work-item-schema.js';\nimport { workItemBranch, workItemBranchSource } from '../../work-item-branch.js';\nimport type { IntegrationContext, IntegrationHooks } from '../base.js';\nimport { closingIssueNumbers } from '../closing-references.js';\nimport { recordPullRequestHead } from '../pull-request-head.js';\nimport type { GithubAppIdentity } from './app-identity.js';\nimport type { GithubEventRules } from './default-rules.js';\nimport type { GithubRepositoryPermission } from './integration.js';\nimport { isRepositoryPullRequest } from './pull-request-source.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 timestamp(value: unknown): number | undefined {\n const parsed = typeof value === 'string' ? Date.parse(value) : NaN;\n return Number.isNaN(parsed) ? undefined : parsed;\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 sameLabels(a: readonly string[], b: readonly string[]): boolean {\n return a.length === b.length && a.every((label, index) => label === b[index]);\n}\n\nfunction labelNames(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap(label => {\n if (typeof label === 'string') return label ? [label] : [];\n const name = string(object(label)?.name);\n return name ? [name] : [];\n });\n}\n\nfunction parseFactoryReviewCommand(\n body: string | undefined,\n target: string | undefined,\n): { command: 'review' | 're-review'; target: string } | undefined {\n if (!body || !target) return undefined;\n const firstLine = body\n .split('\\n')\n .map(line => line.trim())\n .find(line => line.length > 0)\n ?.toLowerCase();\n if (!firstLine) return undefined;\n const mention = `@${target.toLowerCase().replace(/\\[bot\\]$/, '')}`;\n if (firstLine === `${mention} review`) return { command: 'review', target };\n if (firstLine === `${mention} re-review`) return { command: 're-review', target };\n return undefined;\n}\n\n/**\n * Points the card's session at a new comment or an edit on its issue. Only\n * pointers travel (who, where, a link); Factory's own comments are skipped so\n * a session is not woken by what it wrote.\n */\nexport function activitySignalFor(\n context: Pick<FactoryGithubRuleContext, 'event' | 'item' | 'actor' | 'ingress' | 'repository' | 'issue' | 'issueComment'>,\n): FactorySignalActivityDecision | undefined {\n const event =\n context.event === 'issueCommentCreated'\n ? ('work_item.commented' as const)\n : context.event === 'issueEdited'\n ? ('work_item.edited' as const)\n : undefined;\n if (!event || !context.item || !context.issue) return undefined;\n if (context.actor.type !== 'github' || context.actor.factoryAuthored) return undefined;\n return {\n type: 'signalActivity',\n idempotencyKey: `${context.ingress.id}:activity`,\n event,\n reference: `${context.repository.fullName}#${context.issue.number}`,\n url: (event === 'work_item.commented' ? context.issueComment?.url : undefined) ?? context.issue.url,\n ...(context.actor.login ? { author: context.actor.login } : {}),\n authorTrusted: context.actor.trusted,\n };\n}\n\n/** The status change a GitHub delivery reports. `not_planned` and `duplicate` closes are canceled work. */\nexport function boardEventFor(context: Pick<FactoryGithubRuleContext, 'event' | 'issue'>): BoardEventFacts | undefined {\n switch (context.event) {\n case 'issueOpened':\n return { type: 'work_item.created' };\n case 'issueReopened':\n return { type: 'work_item.reopened' };\n case 'issueClosed': {\n const stateReason = context.issue?.stateReason;\n return { type: 'work_item.closed', reason: closeReason(stateReason === 'not_planned' || stateReason === 'duplicate') };\n }\n default:\n return undefined;\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 === 'issues' && action === 'closed') return 'issueClosed';\n if (parsed.event === 'issues' && action === 'reopened') return 'issueReopened';\n if (parsed.event === 'issue_comment') {\n const issue = object(parsed.payload.issue);\n // A comment on a PR arrives as `issue_comment` with `issue.pull_request` set.\n // It routes to the PR's own event so it binds to the authoring Work item via\n // provenance instead of being mistaken for a comment on an issue of the same\n // number. Edits and deletions are not new feedback, with one exception: the\n // review skill updates its earlier request-changes verdict in place instead\n // of posting a new one, and that edit is the only handoff the author gets.\n if (object(issue?.pull_request)) {\n if (action === 'created') return 'pullRequestCommentCreated';\n return action === 'edited' && editedRequestChangesVerdict(parsed.payload, parsed.payload.comment)\n ? 'pullRequestCommentCreated'\n : undefined;\n }\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 if (parsed.event === 'pull_request_review' && action === 'submitted') return 'pullRequestReviewSubmitted';\n if (parsed.event === 'pull_request_review' && action === 'edited') {\n const review = object(parsed.payload.review);\n return string(review?.state)?.toLowerCase() === 'changes_requested' &&\n editedRequestChangesVerdict(parsed.payload, review)\n ? 'pullRequestReviewSubmitted'\n : undefined;\n }\n return undefined;\n}\n\n/** A body edit that leaves a Factory request-changes verdict on the post. */\nfunction editedRequestChangesVerdict(payload: Record<string, unknown>, post: unknown): boolean {\n return object(object(payload.changes)?.body) !== undefined && requestsChangesVerdict(string(object(post)?.body));\n}\n\n/**\n * Canonical source keys (`github-issue:N`, `github-pr:N`) do not identify a\n * repository, so a project linked to several repositories could bind repo A's\n * event to repo B's same-numbered card. The card's intake-stamped URL is\n * authoritative; the intake-stamped `githubRepositoryId` covers URL-less\n * cards. A card with neither signal cannot be attributed by number alone.\n */\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\nexport function cardBelongsToRepository(item: Card, repositoryId: number, repositoryFullName: string): boolean {\n const url = item.externalSource?.url;\n if (url) {\n const match = /^https?:\\/\\/[^/]+\\/(.+)\\/(?:issues|pull)\\/\\d+(?:[/?#]|$)/.exec(url);\n if (match && match[1] === repositoryFullName) return true;\n }\n // A renamed repository leaves the old owner/name in the card URL, so a URL\n // mismatch still defers to the stable intake-stamped repository id.\n return item.workItem.metadata?.githubRepositoryId === repositoryId;\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\n/**\n * The head branch of a pull request pushed to the repository itself. A fork's branch lives in\n * another repository, so its name says nothing about which card wrote it — anyone could name a\n * fork branch after a card. A payload without `head.repo` (rebuilt from polled state) is the\n * base repository's own record and keeps its branch.\n */\nfunction sameRepositoryHeadBranch(pullRequest: Record<string, unknown> | undefined, repositoryId: number) {\n const head = object(pullRequest?.head);\n if (head && 'repo' in head && number(object(head.repo)?.id) !== repositoryId) return undefined;\n return string(head?.ref);\n}\n\n/** A card attributed to a different repository than the pull request's. */\nfunction cardInOtherRepository(item: Card, repositoryId: number, repositoryFullName: string): boolean {\n const attributed =\n /^https?:\\/\\/[^/]+\\/.+\\/(?:issues|pull)\\/\\d+(?:[/?#]|$)/.test(item.externalSource?.url ?? '') ||\n typeof item.workItem.metadata?.githubRepositoryId === 'number';\n return attributed && !cardBelongsToRepository(item, repositoryId, repositoryFullName);\n}\n\n/**\n * The work item a pull request's head branch belongs to: a session of the item checked it out,\n * or it is the item's own branch name, which covers pull requests opened from a session that\n * only follows the card (no session on the card holds the branch, and no provenance was\n * recorded). Only a single match counts; two cards claiming one branch name neither.\n */\nfunction branchAuthoringItem(\n items: readonly Card[],\n headBranch: string | undefined,\n repositoryId: number,\n repositoryFullName: string,\n): Card | undefined {\n if (!headBranch) return undefined;\n const matches = items.filter(\n item =>\n item.externalSource?.type !== 'pull-request' &&\n !cardInOtherRepository(item, repositoryId, repositoryFullName) &&\n (Object.values(item.sessions).some(session => session.branch === headBranch) ||\n workItemBranch({\n id: item.id,\n source: workItemBranchSource(item.externalSource),\n metadata: item.workItem.metadata,\n }) === headBranch),\n );\n return matches.length === 1 ? matches[0] : undefined;\n}\n\n/** Every source a card for this issue or pull request may be filed under. */\nexport function githubItemSources(\n repositoryId: number,\n kind: 'issue' | 'pull-request',\n itemNumber: number,\n): ExternalWorkItemSource[] {\n return [canonicalSourceKey(kind, itemNumber), legacySourceKey(repositoryId, kind, itemNumber)].map(externalId => ({\n integrationId: 'github',\n type: kind,\n externalId,\n }));\n}\n\n/**\n * The pull request source an issue card carries for this repository's pull request, when it was\n * attached to the card rather than filed on a card of its own.\n */\nexport function attachedPullRequestSource(\n item: Card,\n repositoryId: number,\n repositoryFullName: string,\n pullRequestNumber: number,\n): WorkItemSourceRow | undefined {\n if (item.externalSource?.type === 'pull-request') return undefined;\n return pullRequestSources(item).find(source =>\n isRepositoryPullRequest(source, repositoryId, repositoryFullName, pullRequestNumber),\n );\n}\n\nfunction provenanceTarget(repositoryId: number, pullRequestNumber: number): string {\n return `factory-pr-provenance:${repositoryId}:${pullRequestNumber}`;\n}\n\nfunction workItemSource(item: Card) {\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: Card): string | null {\n return item.externalSource?.externalId ?? null;\n}\n\n// Throws on a failed lookup: callers writing permanent state must retry, not\n// record the failure as distrust.\nexport async function trustedCollaborator(\n github: GithubRulesIntegration,\n input: { installationId: number; repository: string; login: string },\n): Promise<boolean> {\n const permission = await github.getRepositoryCollaboratorPermission(\n input.installationId,\n input.repository,\n input.login,\n );\n return permission !== undefined && TRUSTED_PERMISSIONS.has(permission);\n}\n\n// Terminal cards leave the reconcile loop below, so the ones that got there before author\n// trust was recorded have no other path to an answer.\nfunction authorAwaitingTrust(item: Card, repository: ReconcileRepository): string | undefined {\n const metadata = { ...item.workItem.metadata, ...item.metadata };\n if (typeof metadata.author !== 'string' || metadata.authorTrusted !== undefined) return undefined;\n const tracked = reconcilablePullRequestNumber(item, repository) ?? reconcilableIssueNumber(item, repository);\n if (tracked === undefined) return undefined;\n // A canonical key with no URL names no repository, and the pull request matcher takes it anyway.\n // Asking GitHub about the wrong repository of a multi-repository project would record a wrong answer.\n const unattributed =\n !item.externalSource?.url && /^github-(?:pr|issue):\\d+$/.test(item.externalSource?.externalId ?? '');\n if (unattributed && metadata.githubRepositoryId !== repository.id) return undefined;\n return metadata.author;\n}\n\nexport function sweepTrustLookup(\n github: GithubRulesIntegration,\n repository: ReconcileRepository,\n): (login: string) => Promise<boolean> {\n const cache = new Map<string, boolean>();\n return async login => {\n const cached = cache.get(login);\n if (cached !== undefined) return cached;\n const trusted = await trustedCollaborator(github, {\n installationId: repository.installationId,\n repository: repository.fullName,\n login,\n });\n cache.set(login, trusted);\n return trusted;\n };\n}\n\nasync function githubActor(\n github: GithubRulesIntegration,\n input: { installationId: number; repository: string; login: string; factoryAuthored: boolean },\n): Promise<FactoryRuleActor> {\n // The actor bit is recomputed on every event, so a failed lookup can read\n // untrusted for this one delivery instead of failing the ingest.\n const trusted = await trustedCollaborator(github, input).catch(() => false);\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(\n data: Record<string, unknown> | undefined,\n factoryProjectId: string,\n): FactoryPullRequestProvenanceData | null {\n if (!data || data.kind !== 'factory-pr-provenance' || typeof data.workItemId !== 'string') return null;\n // Provenance proves which Factory *project's* run authored the PR. A row\n // written by a sibling project in the same org — or a legacy row without the\n // project stamp — fails closed here: honoring it would brand the PR\n // Factory-authored in a project that never touched it, and auto-start a\n // review that checks out and executes the PR there.\n if (data.factoryProjectId !== factoryProjectId) return null;\n return { kind: 'factory-pr-provenance', workItemId: data.workItemId };\n}\n\nexport interface GithubRulesIntegration {\n readonly rules: GithubEventRules;\n readonly slug?: string;\n /**\n * Factory's own GitHub login, used to ignore its own writes. Optional because\n * not every integration can name itself; when absent, self-recognition falls\n * back to the configured slug and, failing that, to content Factory stamps\n * itself (see `FACTORY_TRIAGE_COMMENT_MARKER`).\n */\n readonly identity?: GithubAppIdentity;\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 configVersion: string;\n /** The code boards, or the per-project source so a project's stored boards run its cards. */\n boards: BoardRegistry | ProjectBoardSource;\n /** Hands a push to a linked repository off for an environment build. */\n onRepositoryPush?: IntegrationHooks['onRepositoryPush'];\n}\n\n/** Identity under which label and assignee syncs are recorded. */\nconst CARD_SYNC_USER_ID = 'factory-rule-dispatcher';\n\ntype IssueActionHandler = (\n parsed: ParsedGithubWebhook,\n repositoryId: number,\n repositoryName: string,\n project: ExternalRepositoryProjectTarget,\n) => Promise<{ status: 'ignored' | 'committed' }>;\n\n/**\n * Whether a login is Factory itself. Prefers the resolved identity, which is\n * observed from Factory's own writes, and falls back to the configured slug.\n */\nexport function isFactoryGithubLogin(\n github: Pick<GithubRulesIntegration, 'identity' | 'slug'>,\n login: string | null | undefined,\n): boolean {\n if (github.identity?.known) return github.identity.matches(login);\n const slug = github.slug?.trim();\n if (!slug || !login) return false;\n return login.toLowerCase() === `${slug.toLowerCase()}[bot]`;\n}\n\nexport class GithubRules {\n constructor(private readonly options: GithubRulesOptions) {}\n\n /** Brings the project's boards up to date, so the sync reads below see its stored boards. */\n async loadBoards(scope: StoredBoardScope): Promise<void> {\n await toBoardSource(this.options.boards).load(scope);\n }\n\n /** The project's loaded boards; {@link loadBoards} runs before an event is handled. */\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n /**\n * Whether a login is Factory itself. Prefers the resolved identity, which is\n * observed from Factory's own writes, and falls back to the configured slug.\n * An unset slug must not silently answer \"not Factory\" — that is what\n * disabled every self-loop guard.\n */\n #isFactoryLogin(login: string | undefined): boolean {\n return isFactoryGithubLogin(this.options.github, login);\n }\n\n #factoryMentionTarget(): string | undefined {\n const identity = this.options.github.identity;\n if (identity?.known) return identity.login;\n const slug = this.options.github.slug?.trim();\n return slug ? `${slug.toLowerCase()}[bot]` : undefined;\n }\n\n /**\n * `labeled` / `unlabeled` are not rule events: the card's label metadata is refreshed and the card\n * stays where it is. Intake routes placed it when it arrived; a label change doesn't move it.\n */\n async #syncIssueLabels(\n parsed: ParsedGithubWebhook,\n repositoryId: number,\n repositoryName: string,\n project: ExternalRepositoryProjectTarget,\n ): Promise<{ status: 'ignored' | 'committed' }> {\n const issue = object(parsed.payload.issue);\n const issueNumber = issue?.pull_request === undefined ? number(issue?.number) : undefined;\n if (!issueNumber) return { status: 'ignored' };\n const found = await this.#relatedItem(\n project.orgId,\n project.factoryProjectId,\n repositoryId,\n repositoryName,\n issueNumber,\n undefined,\n undefined,\n null,\n );\n if (!found || found.externalSource?.type !== 'issue') return { status: 'ignored' };\n const labels = labelNames(issue?.labels);\n if (sameLabels(cardLabels(found), labels)) return { status: 'ignored' };\n let updated;\n try {\n updated = await this.options.storage.syncCard({\n orgId: found.orgId,\n id: found.id,\n userId: CARD_SYNC_USER_ID,\n patch: { metadata: { labels } },\n expectedSourceRevision: primarySource(found)?.revision,\n });\n } catch (error) {\n // The card changed under us (a run wrote it, or a concurrent delivery won). The next\n // delivery or reconcile pass carries the same labels, so drop this one instead of 5xx-ing.\n if (!(error instanceof WorkItemUpdateConflictError)) throw error;\n return { status: 'ignored' };\n }\n return { status: updated ? 'committed' : 'ignored' };\n }\n\n /**\n * `assigned` / `unassigned` are not rule events either: an existing issue card only mirrors the\n * issue's full assignee list. No card is created, moved, or handed to a run.\n */\n async #syncIssueAssignees(\n parsed: ParsedGithubWebhook,\n repositoryId: number,\n repositoryName: string,\n project: ExternalRepositoryProjectTarget,\n ): Promise<{ status: 'ignored' | 'committed' }> {\n const issue = object(parsed.payload.issue);\n const issueNumber = issue?.pull_request === undefined ? number(issue?.number) : undefined;\n if (!issueNumber) return { status: 'ignored' };\n const item = await this.#relatedItem(\n project.orgId,\n project.factoryProjectId,\n repositoryId,\n repositoryName,\n issueNumber,\n undefined,\n undefined,\n null,\n );\n if (!item || item.externalSource?.type !== 'issue') return { status: 'ignored' };\n const assignees = actorLogins(issue?.assignees);\n // GitHub can deliver webhooks out of order; drop payloads older than the last applied one.\n // Timestamps have one-second resolution, so equal timestamps still apply.\n const updatedAt = string(issue?.updated_at);\n const payloadTime = timestamp(updatedAt);\n const storedTime = timestamp(item.workItem.metadata?.githubAssigneesUpdatedAt);\n if (payloadTime !== undefined && storedTime !== undefined && payloadTime < storedTime) {\n return { status: 'ignored' };\n }\n // A newer payload with unchanged assignees still advances the stored time, so a delayed older\n // payload cannot slip in behind it.\n const advancesTime = payloadTime !== undefined && (storedTime === undefined || payloadTime > storedTime);\n if (sameStrings(item.workItem.metadata?.assignees, assignees) && !advancesTime) return { status: 'ignored' };\n try {\n const updated = await this.options.storage.syncCard({\n orgId: item.orgId,\n id: item.id,\n userId: CARD_SYNC_USER_ID,\n patch: {\n metadata: {\n assignees,\n ...(payloadTime !== undefined ? { githubAssigneesUpdatedAt: updatedAt } : {}),\n },\n },\n expectedSourceRevision: primarySource(item)?.revision,\n });\n return { status: updated ? 'committed' : 'ignored' };\n } catch (error) {\n // A concurrent write won; nothing reconciles issue-card assignees, so they stay as the\n // winner left them until the next assigned/unassigned delivery for this issue.\n if (!(error instanceof WorkItemUpdateConflictError)) throw error;\n return { status: 'ignored' };\n }\n }\n\n /** `issues` actions that are not rule events but still update an existing card. */\n #issueActionHandler(parsed: ParsedGithubWebhook): IssueActionHandler | undefined {\n if (parsed.event !== 'issues') return undefined;\n switch (string(parsed.payload.action)) {\n case 'labeled':\n case 'unlabeled':\n return (...args) => this.#syncIssueLabels(...args);\n case 'assigned':\n case 'unassigned':\n return (...args) => this.#syncIssueAssignees(...args);\n default:\n return undefined;\n }\n }\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 (parsed.event === 'push' && installationId && repositoryId) {\n await this.#handOffPush(parsed, installationId, repositoryId);\n return { status: 'ignored' };\n }\n if (!installationId || !repositoryId || !repositoryName || !login) return { status: 'ignored' };\n const issueAction = this.#issueActionHandler(parsed);\n const handle = event\n ? (project: ExternalRepositoryProjectTarget) =>\n this.#ingestProject(parsed, event, installationId, repositoryId, repositoryName, login, project)\n : issueAction\n ? (project: ExternalRepositoryProjectTarget) => issueAction(parsed, repositoryId, repositoryName, project)\n : undefined;\n if (!handle) 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 await this.loadBoards(project);\n results.push(await handle(project));\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 /**\n * A push is not a work-item event; it only reaches the environment build\n * hand-off, once per project the repository is linked to. The hook decides\n * whether the project builds on push.\n */\n async #handOffPush(parsed: ParsedGithubWebhook, installationId: number, repositoryId: number): Promise<void> {\n const onRepositoryPush = this.options.onRepositoryPush;\n const ref = string(parsed.payload.ref);\n const defaultBranch = string(object(parsed.payload.repository)?.default_branch);\n if (!onRepositoryPush || !ref || !defaultBranch) return;\n const projects = await this.options.sourceControl.projectRepositories.listByExternalRepository({\n installationExternalId: String(installationId),\n repositoryExternalId: String(repositoryId),\n });\n for (const project of projects) {\n onRepositoryPush({\n orgId: project.orgId,\n factoryProjectId: project.factoryProjectId,\n projectRepository: {\n id: project.projectRepository.id,\n inEnvironment: project.projectRepository.inEnvironment,\n },\n ref,\n defaultBranch,\n });\n }\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 // A comment on a PR carries the PR under `issue` (with `pull_request` set)\n // and has no `pull_request` payload of its own. Read the PR from `issue` in\n // that case so provenance and `context.pullRequest` behave as they do for\n // every other PR event, and so the number is never treated as an issue's.\n const commentOnPullRequest = object(parsed.payload.issue)?.pull_request !== undefined;\n const pullRequest = object(parsed.payload.pull_request) ?? (commentOnPullRequest ? issue : undefined);\n const issueNumber = commentOnPullRequest ? undefined : 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(\n subscription =>\n subscription.orgId === project.orgId && subscription.data?.factoryProjectId === project.factoryProjectId,\n )?.data,\n project.factoryProjectId,\n )\n : null;\n // Re-review events target the PR's own Review card, not the Work item that\n // provenance would otherwise bind the event to. For review_requested the\n // sender is whoever clicked re-request, so a Factory-authored PR must not\n // brand a human requester as factory-authored.\n const reviewRequested = event === 'pullRequestReviewRequested';\n const reviewCommand =\n event === 'pullRequestCommentCreated'\n ? parseFactoryReviewCommand(string(issueComment?.body), this.#factoryMentionTarget())\n : undefined;\n const reviewEntryRequested = reviewRequested || reviewCommand !== undefined;\n // Provenance proves the *pull request* came from Factory, which is not the\n // same as the sender of this event. For events where the sender is whoever\n // reacted to the PR — re-requesting review, commenting, submitting a review\n // — branding them from provenance would mark every human and every review\n // bot as Factory. Only the app login identifies Factory for those.\n const senderIsResponder =\n reviewRequested || event === 'pullRequestCommentCreated' || event === 'pullRequestReviewSubmitted';\n const reReviewEvent = reviewEntryRequested || event === 'pullRequestUpdated';\n const requestedReviewer = string(object(parsed.payload.requested_reviewer)?.login);\n const pullRequestAuthor = string(object(pullRequest?.user)?.login);\n const pullRequestFactoryAuthored = provenance !== null || this.#isFactoryLogin(pullRequestAuthor);\n const resolvedItem = await this.#relatedItem(\n project.orgId,\n project.factoryProjectId,\n repositoryId,\n repositoryName,\n issueNumber,\n pullRequestNumber,\n sameRepositoryHeadBranch(pullRequest, repositoryId),\n reReviewEvent ? null : provenance,\n senderIsResponder && !reviewEntryRequested,\n );\n // A review-entry request must never treat a branch-matched authoring Work\n // card as the PR's Review card. A missing Review card is materialized below.\n const matchedItem =\n reviewEntryRequested &&\n resolvedItem?.externalSource?.type !== 'pull-request' &&\n !(\n resolvedItem &&\n pullRequestNumber &&\n attachedPullRequestSource(resolvedItem, repositoryId, repositoryName, pullRequestNumber)\n )\n ? undefined\n : resolvedItem;\n const intake = intakeTarget(this.#boards(project));\n const actor = await githubActor(this.options.github, {\n installationId,\n repository: repositoryName,\n login,\n factoryAuthored: (!senderIsResponder && provenance !== null) || this.#isFactoryLogin(login),\n });\n // A marked handoff comment is ignored only when Factory authored it: a\n // human may quote the marker to add an investigation lead, and a custom\n // comment rule must still see it. Recognising the author is therefore the\n // whole guard — when identity cannot be resolved this fails open, and a\n // rule that starts triage on comments would cancel the run that wrote it.\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 // A pull request seen for the first time is filed on the card it belongs to, when one is\n // on the board: the card that authored it, or the card of the issue it closes.\n const home =\n event === 'pullRequestOpened' && pullRequestNumber\n ? await this.#pullRequestHome({\n orgId: project.orgId,\n factoryProjectId: project.factoryProjectId,\n repositoryId,\n repositoryName,\n pullRequestNumber,\n matchedItem,\n factoryAuthored: pullRequestFactoryAuthored,\n // Only the author's own trust lets a pull request join another card.\n authorTrusted: actor.type === 'github' && actor.trusted && login === pullRequestAuthor,\n body: string(pullRequest?.body),\n })\n : undefined;\n // The card of an issue the pull request closes isn't the pull request's card yet: the\n // project's intake routes decide, when it is filed, whether it joins that card.\n const relatedItem = (home?.reason === 'authored' ? home.card : undefined) ?? matchedItem;\n const pullRequestHome: FactoryPullRequestHome | undefined = home\n ? { workItemId: home.card.id, reason: home.reason }\n : undefined;\n // One delivery can concern two cards — a merged pull request settles both\n // its own Review card and the Work item that authored it — and every\n // decision a rule returns is committed against a single item, at that\n // item's revision. So the evaluation, not the decision, is what fans out:\n // the rule runs once per bound item, each with its own ingress identity.\n const evaluate = async (\n item: Card | undefined,\n ingressIdentity: string,\n /** Set on the evaluation that files the pull request's own Review card. */\n pullRequestIntake = false,\n attempt = 1,\n ): Promise<{ status: 'ignored' | 'committed' | 'replayed' | 'missing' }> => {\n const context: FactoryGithubRuleContext = {\n tenant: { orgId: project.orgId, projectId: project.factoryProjectId },\n actor,\n ingress: { type: 'github', id: ingressIdentity },\n cause: `github.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(item\n ? {\n item: {\n id: item.id,\n source: workItemSource(item),\n sourceKey: workItemSourceKey(item),\n parentWorkItemId: item.parentWorkItemId,\n title: item.title,\n url: item.externalSource?.url ?? null,\n stages: item.stages,\n workItem: item.workItem,\n acceptedAt: item.acceptedAt,\n metadata: item.metadata,\n },\n board: boardForWorkItem(item),\n itemRevision: item.revision,\n ...withBoardClosure(this.#boards(project), item),\n ...rulePhaseField(this.#boards(project), item),\n ...withBoardFlow(this.#boards(project), item),\n }\n : {}),\n ...(intake ? { intake } : {}),\n ...(pullRequestIntake ? { pullRequestIntake: true } : {}),\n ...(pullRequestHome ? { pullRequestHome } : {}),\n event,\n deliveryId: parsed.deliveryId,\n factory: { createdAt: factoryProject.createdAt.toISOString() },\n repository: { id: repositoryId, fullName: repositoryName, installationId },\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 labels: labelNames(issue?.labels),\n ...(string(object(issue?.user)?.login) ? { author: string(object(issue?.user)?.login) } : {}),\n ...(string(issue?.state) === 'closed' || string(issue?.state) === 'open'\n ? { state: string(issue?.state) as 'open' | 'closed' }\n : {}),\n ...(string(issue?.state_reason) ? { stateReason: string(issue?.state_reason) } : {}),\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)\n ? { author: string(object(issueComment?.user)?.login) }\n : {}),\n ...(string(object(issueComment?.user)?.type)\n ? { authorType: string(object(issueComment?.user)?.type) }\n : {}),\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 labels: labelNames(pullRequest?.labels),\n ...(pullRequestAuthor ? { author: pullRequestAuthor } : {}),\n factoryAuthored: pullRequestFactoryAuthored,\n headBranch: string(object(pullRequest?.head)?.ref) ?? '',\n ...(string(object(pullRequest?.head)?.sha)\n ? { headSha: string(object(pullRequest?.head)?.sha)!.toLowerCase() }\n : {}),\n baseBranch: string(object(pullRequest?.base)?.ref) ?? '',\n },\n }\n : {}),\n ...(reviewRequested && requestedReviewer\n ? {\n reviewRequest: {\n reviewer: requestedReviewer,\n factoryReviewer: this.#isFactoryLogin(requestedReviewer),\n },\n }\n : {}),\n ...(reviewCommand ? { reviewCommand } : {}),\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 ...(string(object(object(parsed.payload.review)?.user)?.login)\n ? { author: string(object(object(parsed.payload.review)?.user)?.login) }\n : {}),\n ...(string(object(parsed.payload.review)?.body)\n ? { body: string(object(parsed.payload.review)?.body) }\n : {}),\n },\n }\n : {}),\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n\n const ownedByDeployment = deploymentOwnsEvent(\n this.options.github.rules,\n boardEventHandlers(this.#boards(project), eventBoardId(context), 'github'),\n event,\n );\n const rule = selectEventRule(\n this.options.github.rules,\n boardEventHandlers(this.#boards(project), eventBoardId(context), 'github'),\n event,\n );\n let decision: FactoryRuleDecision | void = undefined;\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 => {\n assertFactoryDecisionTarget(entry, this.#boards(project), item ? boardForWorkItem(item) : undefined);\n return { ...entry };\n });\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 if (ownedByDeployment) decisions = decisions.map(withoutRouteEvent);\n if (!decision && !ownedByDeployment && outcome.status === 'accepted') {\n const routed =\n (await routeEventDecision(context, this.options.storage, {\n orgId: project.orgId,\n factoryProjectId: project.factoryProjectId,\n })) ?? activitySignalFor(context);\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: project.orgId,\n factoryProjectId: project.factoryProjectId,\n workItemId: item?.id ?? null,\n ingress: { identity: ingressIdentity, triggerType: `github.${event}` },\n configVersion: this.options.configVersion,\n expectedRevision: item?.revision ?? null,\n actor: { ...actor },\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n // The item was written concurrently. Re-read it and run the rule again\n // against the fresh revision; nothing was persisted for this attempt.\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory GitHub rule evaluation for ${ingressIdentity} kept losing revision races.`);\n }\n const fresh = item ? await this.options.storage.get({ orgId: project.orgId, id: item.id }) : null;\n if (item && !fresh) return { status: 'missing' };\n return evaluate(fresh ?? undefined, ingressIdentity, pullRequestIntake, attempt + 1);\n }\n return { status: committed.status };\n };\n\n // A push moves the head a recorded review verdict was given on. Recording\n // the new head lets the verdict badge show that it is outdated, while the\n // verdict itself stays so the next pass still runs as a re-review. It is\n // recorded before the push is evaluated: the dispatcher can apply the\n // re-review transition as soon as it commits, and the pass it starts names\n // the head it covers, which must be the pushed one.\n const stampHead = async () => {\n const headSha = string(object(pullRequest?.head)?.sha)?.toLowerCase();\n if (event !== 'pullRequestUpdated' || !headSha || !pullRequestNumber) return;\n const headAt = timestamp(pullRequest?.updated_at);\n // A pull request attached to its issue's card records its head there, while it is the one out.\n if (relatedItem && attachedPullRequestSource(relatedItem, repositoryId, repositoryName, pullRequestNumber)) {\n await recordPullRequestHead(this.options.storage, {\n orgId: relatedItem.orgId,\n id: relatedItem.id,\n headSha,\n headAt,\n ownedPullRequestNumber: pullRequestNumber,\n });\n return;\n }\n if (relatedItem?.externalSource?.type !== 'pull-request') return;\n const parent = await this.#linkedClosureItem(\n project.orgId,\n project.factoryProjectId,\n repositoryId,\n repositoryName,\n pullRequestNumber,\n relatedItem,\n );\n // The authoring Work item mirrors the verdict of the pull request it has\n // out; a push to an older one must not mark its successor's verdict.\n await recordPullRequestHead(this.options.storage, {\n orgId: relatedItem.orgId,\n id: relatedItem.id,\n headSha,\n headAt,\n });\n if (parent) {\n await recordPullRequestHead(this.options.storage, {\n orgId: parent.orgId,\n id: parent.id,\n headSha,\n headAt,\n ownedPullRequestNumber: pullRequestNumber,\n });\n }\n };\n await stampHead();\n const evaluated =\n event === 'pullRequestUpdated' && relatedItem\n ? ((await this.options.storage.get({ orgId: relatedItem.orgId, id: relatedItem.id })) ?? relatedItem)\n : relatedItem;\n const deliveryIdentity = `${installationId}:${parsed.deliveryId}`;\n // A pull request opening concerns two cards: its own Review card, which the\n // arrival rule files — committed against the Work item that authored the\n // pull request when one exists, because that binding is what links the two\n // — and that authoring item, which is now out for review. The arrival is\n // the delivery's own evaluation; the item's is a second one, under an\n // identity suffixed with its id, because ingress identities are the replay\n // key and reusing the delivery's own would drop it as a duplicate.\n const pullRequestOpened = event === 'pullRequestOpened';\n const primary = await evaluate(evaluated, deliveryIdentity, pullRequestOpened);\n // A closed pull request is the one *other* event both linked cards need:\n // the Review card has to close, and the Work item that wrote the code has\n // to finish (on merge) or at least stop recording it as open. Resolution binds the delivery to\n // whichever card it matched first, so evaluate the other one too.\n const linked =\n (event === 'pullRequestMerged' || event === 'pullRequestClosed') && relatedItem && pullRequestNumber\n ? await this.#linkedClosureItem(\n project.orgId,\n project.factoryProjectId,\n repositoryId,\n repositoryName,\n pullRequestNumber,\n relatedItem,\n // Only a trusted author's (or Factory's) pull request may finish a card by its branch name.\n // The lookup is needed only when an unlinked Review card leaves the branch to decide.\n relatedItem.externalSource?.type === 'pull-request' &&\n !relatedItem.parentWorkItemId &&\n (pullRequestFactoryAuthored ||\n (pullRequestAuthor !== undefined &&\n (await trustedCollaborator(this.options.github, {\n installationId,\n repository: repositoryName,\n login: pullRequestAuthor,\n }))))\n ? sameRepositoryHeadBranch(pullRequest, repositoryId)\n : undefined,\n )\n : undefined;\n // Moving the card to Done does not touch its pull request fields, so without\n // this the card reads \"open\" until the next sweep and still offers Re-review.\n // Stamped after the evaluations, which commit at the revision they read.\n const stampClosed = async (companionStatus?: string) => {\n if (!pullRequestNumber) return;\n // The authoring Work item records which pull request it has out, so an\n // agent cannot close the work while that pull request is still open.\n if (pullRequestOpened) {\n // Mirrors the out-for-review rule's trust gate. A replayed opened\n // delivery only restores the mark (after a failed write) while the\n // pull request's Review card still records it open, so a redelivery\n // after the close cannot block the Work item again.\n const trusted = (actor.type === 'github' && actor.trusted) || pullRequestFactoryAuthored;\n if (!authoringItem || !trusted || authoringItem.metadata?.openPullRequestNumber === pullRequestNumber) return;\n const reviewCard = await this.#linkedClosureItem(\n project.orgId,\n project.factoryProjectId,\n repositoryId,\n repositoryName,\n pullRequestNumber,\n authoringItem,\n );\n // Filed on the authoring card itself, the pull request's own source says whether it is open.\n const attached = attachedPullRequestSource(authoringItem, repositoryId, repositoryName, pullRequestNumber);\n const recordedState = reviewCard ? reviewCard.workItem.state : attached?.state;\n const stillOpen =\n companionStatus === 'replayed'\n ? (reviewCard !== undefined || attached !== undefined) && !['closed', 'merged'].includes(recordedState ?? '')\n : !['closed', 'merged'].includes(recordedState ?? '');\n if (!stillOpen) return;\n // Only a pull request the card wrote is the one it has out. One filed there because it\n // closes the issue is someone else's work: recording it would stop the builder's own\n // self-review and pull request.\n const headBranch = string(object(pullRequest?.head)?.ref);\n const ownedByCard =\n home?.reason === 'authored' ||\n (home === undefined &&\n (attached === undefined ||\n pullRequestFactoryAuthored ||\n cardOwnsBranch(authoringItem, headBranch)));\n if (!ownedByCard) return;\n // The head comes along so a head recorded for an earlier pull\n // request cannot mark this one's verdict outdated.\n await this.options.storage.update({\n orgId: authoringItem.orgId,\n id: authoringItem.id,\n userId: 'factory-rule-dispatcher',\n patch: {\n metadata: {\n openPullRequestNumber: pullRequestNumber,\n pullRequestHeadSha: string(object(pullRequest?.head)?.sha)?.toLowerCase() ?? null,\n pullRequestHeadAt: timestamp(pullRequest?.updated_at) ?? null,\n },\n },\n });\n return;\n }\n if (event !== 'pullRequestMerged' && event !== 'pullRequestClosed') return;\n for (const card of [relatedItem, linked]) {\n if (!card) continue;\n if (card.externalSource?.type !== 'pull-request') {\n // A pull request attached to this card settles on its own source, never the issue's.\n const attached = attachedPullRequestSource(card, repositoryId, repositoryName, pullRequestNumber);\n if (attached) {\n await this.options.storage.syncWorkItemSource({\n orgId: card.orgId,\n factoryProjectId: card.factoryProjectId,\n provider: attached.provider,\n externalId: attached.externalId,\n patch: {\n state: event === 'pullRequestMerged' ? 'merged' : 'closed',\n metadata: { state: 'closed', merged: event === 'pullRequestMerged' },\n },\n });\n }\n // Numbers repeat across repositories: a card carrying pull requests settles only for one of its own.\n if (!attached && pullRequestSources(card).length > 0) continue;\n // A merge settles the review, so the authoring Work item's mirrored\n // \"request changes\" no longer stops it from being closed.\n // Only the pull request the card has out settles it; an older one\n // merging must not clear a verdict that belongs to its successor.\n const recorded = card.metadata?.openPullRequestNumber;\n const ownsCard = typeof recorded !== 'number' || recorded === pullRequestNumber;\n const settled = {\n ...(ownsCard && event === 'pullRequestMerged' && typeof card.metadata?.reviewVerdict === 'string'\n ? { reviewVerdict: null }\n : {}),\n // With several pull requests on the card, the newest one its sessions opened is out next;\n // someone else's pull request never becomes the card's own.\n ...(recorded === pullRequestNumber\n ? { openPullRequestNumber: newestOwnedOpenPullRequestNumber(card, pullRequestNumber) }\n : {}),\n };\n if (Object.keys(settled).length > 0) {\n await this.options.storage.update({\n orgId: card.orgId,\n id: card.id,\n userId: 'factory-rule-dispatcher',\n patch: { metadata: settled },\n });\n }\n continue;\n }\n await this.options.storage.syncCard({\n orgId: card.orgId,\n id: card.id,\n userId: 'factory-rule-dispatcher',\n patch: { metadata: { state: 'closed', merged: event === 'pullRequestMerged' } },\n });\n }\n };\n const authoringItem =\n linked === undefined &&\n pullRequestOpened &&\n relatedItem !== undefined &&\n relatedItem.externalSource?.type !== 'pull-request'\n ? relatedItem\n : undefined;\n if (linked === undefined && authoringItem === undefined) {\n await stampClosed();\n return primary;\n }\n const companion = linked ?? authoringItem;\n const secondary = await evaluate(companion, `${deliveryIdentity}:${companion?.id ?? 'pull-request'}`);\n await stampClosed(secondary.status);\n for (const status of ['committed', 'replayed'] as const) {\n if (primary.status === status || secondary.status === status) return { status };\n }\n return primary;\n }\n\n /**\n * The other card a closed pull request concerns, joined through the Review\n * card's `parentWorkItemId` — the link `upsertLinkedWorkItem` records when the\n * pull request is opened, and therefore an exact join that needs no branch\n * heuristics. Returns nothing when the pull request has only one card, which\n * is every pull request Factory did not open from a work item's session.\n */\n async #linkedClosureItem(\n orgId: string,\n projectId: string,\n repositoryId: number,\n repositoryFullName: string,\n pullRequestNumber: number,\n resolved: Card,\n headBranch?: string,\n ): Promise<Card | undefined> {\n await this.options.storage.copyLegacyCards({\n orgId,\n factoryProjectId: projectId,\n sources: githubItemSources(repositoryId, 'pull-request', pullRequestNumber),\n });\n const items = await this.options.storage.listShared({ orgId, factoryProjectId: projectId });\n const linked =\n resolved.externalSource?.type === 'pull-request'\n ? // Bound to the pull request's own Review card: follow the recorded\n // link back to the work item that authored it. A card filed without\n // that link (no provenance when the pull request opened) is joined by\n // its head branch, so the merge still finishes the authoring item.\n resolved.parentWorkItemId\n ? await this.#parentItem(orgId, projectId, items, resolved)\n : branchAuthoringItem(items, headBranch, repositoryId, repositoryFullName)\n : // Bound to the work item (provenance): find the Review card this pull\n // request opened, and only when it names this item as its parent — a\n // card for the same number in another repository is not this one's.\n items.find(\n item =>\n item.parentWorkItemId === resolved.id &&\n (item.externalSource?.externalId === canonicalSourceKey('pull-request', pullRequestNumber) ||\n item.externalSource?.externalId === legacySourceKey(repositoryId, 'pull-request', pullRequestNumber)) &&\n cardBelongsToRepository(item, repositoryId, repositoryFullName),\n );\n return linked && linked.id !== resolved.id ? structuredClone(linked) : undefined;\n }\n\n /**\n * The existing card a pull request opened for the first time belongs with, or undefined when it\n * gets a card of its own. The card must be open, in this repository, and not a pull request's\n * own card. In order: the card that authored it (on a board that reviews pull requests), by provenance or session branch,\n * when the pull request is Factory-authored or its author is trusted; it is filed there. Then,\n * for a trusted author only, the card of the first issue its description says it closes; an\n * intake route decides whether it joins that one. An untrusted author's pull request never\n * lands on another card, whatever it says.\n */\n async #pullRequestHome(input: {\n orgId: string;\n factoryProjectId: string;\n repositoryId: number;\n repositoryName: string;\n pullRequestNumber: number;\n matchedItem: Card | undefined;\n factoryAuthored: boolean;\n authorTrusted: boolean;\n body: string | undefined;\n }): Promise<{ card: Card; reason: FactoryPullRequestHome['reason'] } | undefined> {\n if (!input.factoryAuthored && !input.authorTrusted) return undefined;\n const items = await this.options.storage.listShared({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n const filed = items.some(\n item =>\n attachedPullRequestSource(item, input.repositoryId, input.repositoryName, input.pullRequestNumber) ||\n (item.externalSource?.type === 'pull-request' &&\n (item.externalSource.externalId === canonicalSourceKey('pull-request', input.pullRequestNumber) ||\n item.externalSource.externalId ===\n legacySourceKey(input.repositoryId, 'pull-request', input.pullRequestNumber)) &&\n cardBelongsToRepository(item, input.repositoryId, input.repositoryName)),\n );\n if (filed) return undefined;\n const eligible = (card: Card) =>\n card.externalSource?.type !== 'pull-request' &&\n !isTerminalWorkItem(this.#boards(input), card) &&\n cardBelongsToRepository(card, input.repositoryId, input.repositoryName);\n if (\n input.matchedItem &&\n eligible(input.matchedItem) &&\n cardBoardFlow(this.#boards(input), input.matchedItem).pullRequestReview !== undefined\n ) {\n return { card: input.matchedItem, reason: 'authored' };\n }\n if (!input.authorTrusted) return undefined;\n for (const issueNumber of closingIssueNumbers(input.body, { provider: 'github', repository: input.repositoryName })) {\n const card = items.find(\n item =>\n (item.externalSource?.externalId === canonicalSourceKey('issue', issueNumber) ||\n item.externalSource?.externalId === legacySourceKey(input.repositoryId, 'issue', issueNumber)) &&\n eligible(item),\n );\n if (card) return { card: structuredClone(card), reason: 'closes' };\n }\n return undefined;\n }\n\n async #relatedItem(\n orgId: string,\n projectId: string,\n repositoryId: number,\n repositoryFullName: string,\n issueNumber: number | undefined,\n pullRequestNumber: number | undefined,\n pullRequestHeadBranch: string | undefined,\n provenance: FactoryPullRequestProvenanceData | null,\n preferAuthoringItem = false,\n ): Promise<Card | undefined> {\n // A finished card may still be only in the legacy table; copy it so the event finds it.\n await this.options.storage.copyLegacyCards({\n orgId,\n factoryProjectId: projectId,\n sources: [\n ...(issueNumber ? githubItemSources(repositoryId, 'issue', issueNumber) : []),\n ...(pullRequestNumber ? githubItemSources(repositoryId, 'pull-request', pullRequestNumber) : []),\n ],\n });\n if (provenance) await this.options.storage.getForProject(orgId, projectId, provenance.workItemId);\n const items = await this.options.storage.listShared({ orgId, factoryProjectId: projectId });\n const resolved = this.#resolveItem(\n items,\n repositoryId,\n repositoryFullName,\n issueNumber,\n pullRequestNumber,\n pullRequestHeadBranch,\n provenance,\n );\n // Feedback on a pull request has to reach the item that *wrote* the code.\n // Provenance normally lands it there directly, but when provenance is\n // missing the PR-number lookup wins and returns the PR's own Review card\n // instead — a board the feedback rules deliberately refuse to act on, so\n // the wake is silently dropped. The linked card records its author in\n // `parentWorkItemId`, so follow that link back rather than relaxing the\n // guard, which would let a Review card react to its own posted review.\n if (preferAuthoringItem && resolved?.externalSource?.type === 'pull-request' && resolved.parentWorkItemId) {\n return structuredClone((await this.#parentItem(orgId, projectId, items, resolved)) ?? resolved);\n }\n return resolved && structuredClone(resolved);\n }\n\n /** The card `child` was filed from; read on its own when the board list lacks it (not copied yet). */\n async #parentItem(orgId: string, projectId: string, items: readonly Card[], child: Card): Promise<Card | undefined> {\n if (!child.parentWorkItemId) return undefined;\n return (\n items.find(item => item.id === child.parentWorkItemId) ??\n (await this.options.storage.getForProject(orgId, projectId, child.parentWorkItemId)) ??\n undefined\n );\n }\n\n #resolveItem(\n items: readonly Card[],\n repositoryId: number,\n repositoryFullName: string,\n issueNumber: number | undefined,\n pullRequestNumber: number | undefined,\n pullRequestHeadBranch: string | undefined,\n provenance: FactoryPullRequestProvenanceData | null,\n ): Card | undefined {\n if (provenance) return items.find(item => item.id === provenance.workItemId);\n if (issueNumber) {\n return (\n items.find(\n item =>\n item.externalSource?.externalId === canonicalSourceKey('issue', issueNumber) &&\n cardBelongsToRepository(item, repositoryId, repositoryFullName),\n ) ?? items.find(item => item.externalSource?.externalId === legacySourceKey(repositoryId, 'issue', issueNumber))\n );\n }\n if (pullRequestNumber) {\n return (\n items.find(\n item =>\n item.externalSource?.externalId === canonicalSourceKey('pull-request', pullRequestNumber) &&\n cardBelongsToRepository(item, repositoryId, repositoryFullName),\n ) ??\n items.find(\n item => item.externalSource?.externalId === legacySourceKey(repositoryId, 'pull-request', pullRequestNumber),\n ) ??\n // A pull request attached to its issue's card.\n items.find(item => attachedPullRequestSource(item, repositoryId, repositoryFullName, pullRequestNumber)) ??\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 branchAuthoringItem(items, pullRequestHeadBranch, repositoryId, repositoryFullName)\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 labels?: string[];\n headBranch: string;\n baseBranch: string;\n author?: string;\n createdAt?: string;\n mergedBy?: string;\n}\n\nexport interface PolledPullRequestState extends ReconcilePullRequestState {\n createdAt: string;\n /** Carried so a replayed opening records the head it opens with, as the webhook does. */\n headSha?: string;\n updatedAt?: string;\n}\n\nexport type GithubPullRequestFetcher = (input: {\n installationId: number;\n repository: string;\n number: number;\n}) => Promise<ReconcilePullRequestState | undefined>;\n\nexport interface ReconcileIssueState {\n title: string;\n url: string;\n state: 'open' | 'closed';\n /** GitHub close reason: `completed`, `not_planned`, or `duplicate`. */\n stateReason?: string;\n assignees?: string[];\n labels?: string[];\n author?: string;\n createdAt?: string;\n updatedAt?: string;\n}\n\nexport type GithubIssueFetcher = (input: {\n installationId: number;\n repository: string;\n number: number;\n}) => Promise<ReconcileIssueState | undefined>;\n\n/** Lists a repository's open issues (pull requests excluded) for missed-open discovery. */\nexport type GithubOpenIssueLister = (input: {\n installationId: number;\n repository: string;\n}) => Promise<Array<ReconcileIssueState & { number: number }>>;\n\n/**\n * Lists a repository's open, non-draft pull requests opened at or after\n * `createdSince` (epoch ms) for missed-open discovery.\n */\nexport type GithubOpenPullRequestLister = (input: {\n installationId: number;\n repository: string;\n createdSince: number;\n}) => Promise<Array<PolledPullRequestState & { number: number }>>;\n\n/** The facts of an open, non-draft pull request as a version-control listing reports them. */\nexport function listedPullRequestState(pullRequest: PullRequest): PolledPullRequestState & { number: number } {\n return {\n number: Number(pullRequest.id),\n title: pullRequest.title,\n url: pullRequest.url,\n state: 'open',\n draft: false,\n merged: false,\n assignees: pullRequest.assignees ?? [],\n requestedReviewers: pullRequest.requestedReviewers ?? [],\n labels: pullRequest.labels ?? [],\n headBranch: pullRequest.headBranch,\n baseBranch: pullRequest.baseBranch,\n ...(pullRequest.author ? { author: pullRequest.author } : {}),\n createdAt: pullRequest.createdAt,\n headSha: pullRequest.headSha,\n updatedAt: pullRequest.updatedAt,\n };\n}\n\n/**\n * Missed-open discovery reads at most this many pages per repository per sweep,\n * so a repository flooded with pull requests (or a listing whose cursor never\n * ends) cannot grow a sweep's API cost without limit. A missed open is among\n * the newest, and thirty per page keeps the 600 newest in reach.\n */\nconst OPEN_PULL_REQUEST_DISCOVERY_MAX_PAGES = 20;\n\n/**\n * Missed-open discovery over an integration's version-control capability.\n * GitHub lists open pull requests newest first, so paging stops at the first\n * page opened entirely before `createdSince`, or at the page cap.\n */\nexport function openPullRequestLister(\n versionControl: Pick<VersionControl, 'listPullRequests'>,\n): GithubOpenPullRequestLister {\n return async ({ installationId, repository, createdSince }) => {\n const states: Array<PolledPullRequestState & { number: number }> = [];\n let cursor: string | null = '1';\n for (let page = 0; cursor !== null && page < OPEN_PULL_REQUEST_DISCOVERY_MAX_PAGES; page += 1) {\n // Drafts are listed too: a page of drafts still tells how far back the listing has reached.\n const listed: PullRequestPage = await versionControl.listPullRequests({\n connection: { type: 'app-installation', installationId },\n sourceId: repository,\n state: 'open',\n includeDrafts: true,\n cursor,\n });\n // A pull request without a parseable creation time counts as recent rather than ending the scan.\n const recent = listed.pullRequests.filter(pullRequest => !(Date.parse(pullRequest.createdAt) < createdSince));\n states.push(...recent.filter(pullRequest => !pullRequest.draft).map(listedPullRequestState));\n if (recent.length === 0) break;\n cursor = listed.nextCursor;\n }\n return states;\n };\n}\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/issues (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; issueNumber?: number; error: string }>;\n}\n\nexport type GithubPullRequestReconciler = (repositories: ReconcileRepository[]) => Promise<ReconcileSweepSummary>;\n\nexport interface GithubPullRequestDiscoverySummary {\n /** Factory-configured repositories included in the sweep. */\n repositories: number;\n /** Open pull requests listed, opened since their repository was linked. */\n listed: number;\n /** Open pull requests with no card, replayed as missed opens. */\n created: number;\n /** Open pull requests whose authoring card had lost its open mark, restored by replaying the opening. */\n repaired: number;\n /** Repositories or pull requests 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 GithubPullRequestDiscovery = (\n repositories: ReconcileRepository[],\n) => Promise<GithubPullRequestDiscoverySummary>;\n\nexport const RECONCILE_ERROR_SAMPLE_LIMIT = 5;\n\nexport function 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: Card, 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\n/** The number of an attached pull request source, when it belongs to the given repository. */\nfunction attachedPullRequestNumber(source: WorkItemSourceRow, repository: ReconcileRepository): number | undefined {\n if (source.integrationId !== 'github') return undefined;\n if (source.url) {\n const match = /^https?:\\/\\/[^/]+\\/(.+)\\/pull\\/(\\d+)(?:[/?#]|$)/.exec(source.url);\n return match && match[1] === repository.fullName ? Number(match[2]) : undefined;\n }\n const legacy = /^pull-request:github:(\\d+):pull-request:(\\d+)$/.exec(source.externalId);\n return legacy && Number(legacy[1]) === repository.id ? Number(legacy[2]) : undefined;\n}\n\n/**\n * Extracts the issue number a work item tracks, but only when the item\n * belongs to the given repository. Stricter than\n * {@link reconcilablePullRequestNumber}: a canonical key with no URL is only\n * trusted when the intake-stamped `githubRepositoryId` confirms the\n * repository, because the sweep initiates closes on its own.\n */\nexport function reconcilableIssueNumber(item: Card, repository: ReconcileRepository): number | undefined {\n if (item.externalSource?.type !== 'issue') return undefined;\n const url = item.externalSource.url;\n if (url) {\n const match = /^https?:\\/\\/[^/]+\\/(.+)\\/issues\\/(\\d+)(?:[/?#]|$)/.exec(url);\n if (!match) return undefined;\n // A renamed repository leaves the old owner/name in the card URL, so a\n // URL mismatch still defers to the stable intake-stamped repository id.\n const belongs = match[1] === repository.fullName || item.workItem.metadata?.githubRepositoryId === repository.id;\n return belongs ? Number(match[2]) : undefined;\n }\n const externalId = item.externalSource.externalId;\n const legacy = /^github:(\\d+):issue:(\\d+)$/.exec(externalId);\n if (legacy) return Number(legacy[1]) === repository.id ? Number(legacy[2]) : undefined;\n const canonical = /^github-issue:(\\d+)$/.exec(externalId);\n if (!canonical) return undefined;\n // Canonical keys carry no repository; only the intake-stamped repository id\n // can attribute a URL-less card, and guessing would let a multi-repo\n // project close repo B's card because repo A's same-numbered issue closed.\n return item.workItem.metadata?.githubRepositoryId === repository.id ? Number(canonical[1]) : undefined;\n}\n\nexport function reconciledIssueClosedEvent(\n repository: ReconcileRepository,\n issueNumber: number,\n state: ReconcileIssueState,\n): ParsedGithubWebhook {\n return {\n event: 'issues',\n // Stable per (repository, issue): the ingress dedupe makes repeat\n // reconcile cycles replay instead of re-committing decisions.\n deliveryId: `reconcile:${repository.id}:issue:${issueNumber}:closed`,\n payload: {\n action: 'closed',\n installation: { id: repository.installationId },\n repository: { id: repository.id, full_name: repository.fullName },\n sender: { login: state.author ?? 'github' },\n issue: {\n number: issueNumber,\n title: state.title,\n html_url: state.url,\n state: 'closed',\n ...(state.stateReason ? { state_reason: state.stateReason } : {}),\n ...(state.createdAt ? { created_at: state.createdAt } : {}),\n ...(state.updatedAt ? { updated_at: state.updatedAt } : {}),\n assignees: githubUsers(state.assignees),\n },\n },\n };\n}\n\n/**\n * The label-drift replay: an open issue whose labels changed without a\n * `labeled`/`unlabeled` webhook ever arriving (Factory was down, the delivery\n * was lost, or the label was applied by something other than a delivery the\n * webhook saw). Synthesized as an `opened` delivery so the deployment's\n * `issueOpened` rule decides placement, exactly as it does at arrival — one\n * source of placement policy for both.\n */\nexport function reconciledIssueRelabeledEvent(\n repository: ReconcileRepository,\n issueNumber: number,\n state: ReconcileIssueState,\n): ParsedGithubWebhook {\n const labels = state.labels ?? [];\n // GitHub updates `updated_at` for a label change. Including it makes retries\n // of one observed issue version idempotent while allowing A → B → A to replay\n // its final A placement as a new version. Synthetic callers without it retain\n // the legacy label-only identity.\n const digest = createHash('sha256')\n .update([...labels].sort().join('\\n'))\n .digest('hex')\n .slice(0, 16);\n const version = state.updatedAt ? `:${createHash('sha256').update(state.updatedAt).digest('hex').slice(0, 16)}` : '';\n return {\n event: 'issues',\n deliveryId: `reconcile:${repository.id}:issue:${issueNumber}:relabeled:${digest}${version}`,\n payload: {\n // `opened` is the event that carries an issue's labels through the rules;\n // an already-filed card is re-placed by the decision, not re-materialized.\n action: 'opened',\n installation: { id: repository.installationId },\n repository: { id: repository.id, full_name: repository.fullName },\n sender: { login: state.author ?? 'github' },\n issue: {\n number: issueNumber,\n title: state.title,\n html_url: state.url,\n state: 'open',\n ...(state.createdAt ? { created_at: state.createdAt } : {}),\n ...(state.updatedAt ? { updated_at: state.updatedAt } : {}),\n assignees: githubUsers(state.assignees),\n labels: githubLabels(labels),\n },\n },\n };\n}\n\n/**\n * The missed-open replay: an open issue with no Work card, because its\n * `opened` delivery never reached the rules ingress. Synthesized as the same\n * `opened` delivery so the deployment's `issueOpened` rule decides whether and\n * where it lands, exactly as it would have at arrival. The delivery id is\n * stable per issue so repeat sweeps dedupe at the ingress.\n */\nexport function reconciledIssueOpenedEvent(\n repository: ReconcileRepository,\n issueNumber: number,\n state: ReconcileIssueState,\n): ParsedGithubWebhook {\n const event = reconciledIssueRelabeledEvent(repository, issueNumber, state);\n return { ...event, deliveryId: `reconcile:${repository.id}:issue:${issueNumber}:opened` };\n}\n\nexport function polledPullRequestEvent(\n repository: ReconcileRepository,\n pullRequestNumber: number,\n state: PolledPullRequestState,\n): ParsedGithubWebhook {\n return {\n event: 'pull_request',\n deliveryId: `poll:${repository.id}:pull-request:${pullRequestNumber}:${state.createdAt}`,\n payload: {\n action: 'opened',\n installation: { id: repository.installationId },\n repository: { id: repository.id, full_name: repository.fullName },\n sender: { login: state.author ?? '__unknown__' },\n pull_request: pullRequestPayload(pullRequestNumber, state),\n },\n };\n}\n\n/**\n * Replays an open pull request that has no card as the `opened` delivery\n * GitHub never sent. The delivery id is stable per pull request so repeat\n * sweeps dedupe at the ingress.\n */\nexport function reconciledPullRequestOpenedEvent(\n repository: ReconcileRepository,\n pullRequestNumber: number,\n state: PolledPullRequestState,\n): ParsedGithubWebhook {\n return {\n ...polledPullRequestEvent(repository, pullRequestNumber, state),\n deliveryId: `reconcile:${repository.id}:pull-request:${pullRequestNumber}:opened`,\n };\n}\n\nexport function reconciledClosedEvent(\n repository: ReconcileRepository,\n pullRequestNumber: number,\n state: ReconcilePullRequestState,\n): ParsedGithubWebhook {\n const outcome = state.merged ? 'merged' : 'closed';\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}:${outcome}`,\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: pullRequestPayload(pullRequestNumber, { ...state, state: 'closed' }),\n },\n };\n}\n\nfunction pullRequestPayload(\n pullRequestNumber: number,\n state: ReconcilePullRequestState & Pick<Partial<PolledPullRequestState>, 'headSha' | 'updatedAt'>,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {\n number: pullRequestNumber,\n title: state.title,\n html_url: state.url,\n state: state.state,\n draft: state.draft,\n merged: state.merged,\n assignees: githubUsers(state.assignees),\n requested_reviewers: githubUsers(state.requestedReviewers),\n labels: githubLabels(state.labels),\n head: { ref: state.headBranch, ...(state.headSha ? { sha: state.headSha } : {}) },\n base: { ref: state.baseBranch },\n };\n if (state.createdAt) payload.created_at = state.createdAt;\n if (state.updatedAt) payload.updated_at = state.updatedAt;\n if (state.author) payload.user = { login: state.author };\n return payload;\n}\n\nfunction githubUsers(logins: readonly string[] = []): Array<{ login: string }> {\n return logins.map(login => ({ login }));\n}\n\nfunction githubLabels(names: readonly string[] = []): Array<{ name: string }> {\n return names.map(name => ({ name }));\n}\n\nfunction reconciledPullRequestMetadata(\n state: ReconcilePullRequestState,\n reconciliation: 'clear' | 'settled' | undefined,\n authorTrusted?: boolean,\n): Record<string, unknown> {\n return {\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 ...(state.labels ? { labels: state.labels } : {}),\n ...(authorTrusted === undefined ? {} : { authorTrusted }),\n ...(reconciliation === undefined\n ? {}\n : {\n [FACTORY_PULL_REQUEST_RECONCILIATION_KEY]:\n reconciliation === 'settled' ? (state.merged ? 'merged' : 'closed') : null,\n }),\n };\n}\n\nfunction reconciledPullRequestOutcome(metadata: Record<string, unknown>): 'merged' | 'closed' | undefined {\n if (metadata.state !== 'closed' || typeof metadata.merged !== 'boolean') return undefined;\n return metadata.merged ? 'merged' : 'closed';\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 * Missed opens are {@link createGithubPullRequestDiscovery}'s, on its own cadence.\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 = {\n repositories: 0,\n checked: 0,\n merged: 0,\n closed: 0,\n failed: 0,\n errors: [],\n };\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 const scoped = await linkedRepositories(options, repositories);\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, Card[]>;\n // Open pull requests attached to an issue's card. Their facts live on their own source, so\n // the sweep only replays a missed close; the rules settle the source and the card.\n let attachedOpen: Set<number>;\n let unanswered: Array<{ item: Card; author: string }>;\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, Card[]>();\n attachedOpen = new Set<number>();\n unanswered = [];\n for (const project of projects) {\n await rules.loadBoards(project);\n const items = await options.storage.listShared({\n orgId: project.orgId,\n factoryProjectId: project.factoryProjectId,\n });\n for (const item of items) {\n const unansweredAuthor = authorAwaitingTrust(item, repository);\n if (unansweredAuthor) unanswered.push({ item, author: unansweredAuthor });\n if (item.externalSource?.type !== 'pull-request' && !isTerminalWorkItem(toBoardSource(options.boards).forProject(item), item)) {\n for (const source of pullRequestSources(item)) {\n const number = attachedPullRequestNumber(source, repository);\n if (number !== undefined && !['closed', 'merged'].includes(source.state ?? '')) attachedOpen.add(number);\n }\n }\n const pullRequestNumber = reconcilablePullRequestNumber(item, repository);\n if (!pullRequestNumber) continue;\n const metadata = { ...item.workItem.metadata, ...item.metadata };\n const reconciliation = metadata[FACTORY_PULL_REQUEST_RECONCILIATION_KEY];\n const reconciledOutcome = reconciledPullRequestOutcome(metadata);\n if (\n workItemPhaseSemantics(toBoardSource(options.boards).forProject(item), item)?.kind === 'terminal' &&\n reconciledOutcome !== undefined &&\n reconciliation === reconciledOutcome\n ) {\n continue;\n }\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 const authorTrust = sweepTrustLookup(options.github, repository);\n for (const { item, author } of unanswered) {\n try {\n await options.storage.syncCard({\n orgId: item.orgId,\n id: item.id,\n userId: 'factory-rule-dispatcher',\n patch: { metadata: { authorTrusted: await authorTrust(author) } },\n });\n } catch (error) {\n recordFailure(repository, error);\n }\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 // Re-stamped on every sweep so revoked write access reads untrusted\n // within one cycle; a failed lookup keeps the last stamp and retries.\n let authorTrusted: boolean | undefined;\n if (state.author !== undefined) {\n try {\n authorTrusted = await authorTrust(state.author);\n } catch (error) {\n recordFailure(repository, error, pullRequestNumber);\n }\n }\n for (const card of cards) {\n if (state.state === 'closed') continue;\n const metadata = { ...card.workItem.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 const labelsChanged = !sameStrings(metadata.labels, state.labels);\n const trustStale = authorTrusted !== undefined && metadata.authorTrusted !== authorTrusted;\n const metadataChanged =\n statusChanged || authorChanged || assigneesChanged || reviewersChanged || labelsChanged || trustStale;\n const reconciliation = metadata[FACTORY_PULL_REQUEST_RECONCILIATION_KEY];\n if (!metadataChanged && reconciliation !== 'merged' && reconciliation !== 'closed') continue;\n try {\n await options.storage.syncCard({\n orgId: card.orgId,\n id: card.id,\n userId: 'factory-rule-dispatcher',\n patch: {\n metadata: reconciledPullRequestMetadata(\n state,\n reconciliation === 'merged' || reconciliation === 'closed' ? 'clear' : undefined,\n trustStale ? authorTrusted : undefined,\n ),\n },\n });\n } catch (error) {\n recordFailure(repository, error, pullRequestNumber);\n }\n }\n if (state.state !== 'closed') continue;\n const cleanupFailures = new Set<string>();\n for (const card of cards) {\n if (workItemPhaseSemantics(toBoardSource(options.boards).forProject(card), card)?.kind !== 'terminal') continue;\n try {\n await options.storage.supersedeDecisionsForWorkItem({\n orgId: card.orgId,\n factoryProjectId: card.factoryProjectId,\n workItemId: card.id,\n supersededAt: new Date(),\n });\n } catch (error) {\n recordFailure(repository, error, pullRequestNumber);\n cleanupFailures.add(card.id);\n }\n }\n await rules.ingest(reconciledClosedEvent(repository, pullRequestNumber, state));\n await retireReconciledSubscriptions(options.integrationStorage, repository, pullRequestNumber, state.merged);\n for (const card of cards) {\n if (cleanupFailures.has(card.id)) continue;\n const trustStale = authorTrusted !== undefined && (card.metadata ?? {}).authorTrusted !== authorTrusted;\n try {\n await options.storage.syncCard({\n orgId: card.orgId,\n id: card.id,\n userId: 'factory-rule-dispatcher',\n patch: {\n metadata: reconciledPullRequestMetadata(state, 'settled', trustStale ? authorTrusted : undefined),\n },\n });\n } catch (error) {\n recordFailure(repository, error, pullRequestNumber);\n }\n }\n if (state.merged) summary.merged += 1;\n else summary.closed += 1;\n } catch (error) {\n recordFailure(repository, error, pullRequestNumber);\n }\n }\n for (const pullRequestNumber of attachedOpen) {\n if (cardsByNumber.has(pullRequestNumber)) continue;\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 !== '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\n/**\n * An installation can expose hundreds of repositories; only the ones actually\n * linked to a factory project can have cards, so sweeps scope to those up\n * front instead of probing each repository.\n */\nasync function linkedRepositories(\n options: GithubRulesOptions,\n repositories: ReconcileRepository[],\n): Promise<ReconcileRepository[]> {\n const configured = new Set(\n (await options.sourceControl.projectRepositories.listConfiguredExternalKeys()).map(\n key => `${key.installationExternalId}\\u0000${key.repositoryExternalId}`,\n ),\n );\n return repositories.filter(repository => configured.has(`${repository.installationId}\\u0000${repository.id}`));\n}\n\n/** A non-terminal card that holds an open pull request but no longer records it as the one it has out. */\n\n/**\n * Catches what the opened webhook (or its follow-up writes) missed, from the\n * open pull request list alone, so its GitHub cost is the listing's and does\n * not grow with the cards on the board:\n *\n * - an open pull request filed since the repository was linked that no card\n * holds is replayed as its `opened` delivery, which files it;\n * - an open pull request whose authoring card lost its open mark (the write\n * after the opening failed) is replayed the same way, which restores it.\n *\n * Both replays use one stable delivery id per pull request, so repeats in\n * later sweeps are absorbed by the ingress instead of filing a second card.\n */\nexport function createGithubPullRequestDiscovery(\n options: GithubRulesOptions,\n listOpenPullRequests: GithubOpenPullRequestLister,\n): GithubPullRequestDiscovery {\n const rules = new GithubRules(options);\n const boards = toBoardSource(options.boards);\n return async repositories => {\n const summary: GithubPullRequestDiscoverySummary = {\n repositories: 0,\n listed: 0,\n created: 0,\n repaired: 0,\n failed: 0,\n errors: [],\n };\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 const scoped = await linkedRepositories(options, repositories);\n summary.repositories = scoped.length;\n for (const repository of scoped) {\n // Every pull request some card holds, terminal cards included, so discovery never re-mints one.\n const carded = new Set<number>();\n const unmarked = new Map<number, Card[]>();\n let linkedAt: 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 linkedAt = Math.min(...projects.map(project => project.projectRepository.createdAt.getTime()));\n const items: Readonly<Card>[] = [];\n for (const project of projects) {\n await rules.loadBoards(project);\n items.push(...(await options.storage.listShared({ orgId: project.orgId, factoryProjectId: project.factoryProjectId })));\n }\n const authoring = (item: Card | undefined) =>\n item !== undefined &&\n item.externalSource?.type !== 'pull-request' &&\n typeof item.metadata?.openPullRequestNumber !== 'number' &&\n !isTerminalWorkItem(boards.forProject(item), item);\n const byId = new Map(items.map(item => [item.id, item]));\n for (const item of items) {\n for (const source of pullRequestSources(item)) {\n const number = attachedPullRequestNumber(source, repository);\n if (number === undefined) continue;\n carded.add(number);\n if (authoring(item) && !['closed', 'merged'].includes(source.state ?? '')) {\n unmarked.set(number, [...(unmarked.get(number) ?? []), item]);\n }\n }\n const number = reconcilablePullRequestNumber(item, repository);\n if (number === undefined) continue;\n carded.add(number);\n const parent = item.parentWorkItemId ? byId.get(item.parentWorkItemId) : undefined;\n if (parent && authoring(parent) && !['closed', 'merged'].includes(item.workItem.state ?? '')) {\n unmarked.set(number, [...(unmarked.get(number) ?? []), parent]);\n }\n }\n } catch (error) {\n recordFailure(repository, error);\n continue;\n }\n let open: Array<PolledPullRequestState & { number: number }>;\n try {\n open = await listOpenPullRequests({\n installationId: repository.installationId,\n repository: repository.fullName,\n // Linking never backfills: the link-time import owns the backlog filed before it.\n createdSince: linkedAt,\n });\n } catch (error) {\n recordFailure(repository, error);\n continue;\n }\n summary.listed += open.length;\n // Listed newest first, so a card holding several open pull requests is\n // restored to its newest, the one it would have out next.\n const restored = new Set<string>();\n for (const pullRequest of open) {\n try {\n if (!carded.has(pullRequest.number)) {\n const result = await rules.ingest(\n reconciledPullRequestOpenedEvent(repository, pullRequest.number, pullRequest),\n );\n if (result.status === 'committed') summary.created += 1;\n continue;\n }\n const candidate = await ownedUnmarkedCard(\n options,\n repository,\n pullRequest,\n (unmarked.get(pullRequest.number) ?? []).filter(card => !restored.has(card.id)),\n );\n if (!candidate) continue;\n restored.add(candidate.id);\n await rules.ingest(reconciledPullRequestOpenedEvent(repository, pullRequest.number, pullRequest));\n const after = await options.storage.get({ orgId: candidate.orgId, id: candidate.id });\n if (after?.metadata?.openPullRequestNumber === pullRequest.number) summary.repaired += 1;\n } catch (error) {\n recordFailure(repository, error, pullRequest.number);\n }\n }\n }\n return summary;\n };\n}\n\n/**\n * The unmarked card an open pull request's replayed opening would mark: the\n * one Factory's provenance names, which is the only link a replay resolves\n * back to the authoring card once the pull request has its own Review card.\n * Decided from storage, so a card holding someone else's pull request (or one\n * a replay cannot restore) costs no replay, and no permission lookup, per sweep.\n */\nasync function ownedUnmarkedCard(\n options: GithubRulesOptions,\n repository: ReconcileRepository,\n pullRequest: PolledPullRequestState & { number: number },\n candidates: Card[],\n): Promise<Card | undefined> {\n if (candidates.length === 0) return undefined;\n const provenance = await options.integrationStorage.subscriptions.listByTarget(\n provenanceTarget(repository.id, pullRequest.number),\n { status: 'active' },\n );\n return candidates.find(card =>\n provenance.some(\n subscription =>\n subscription.orgId === card.orgId &&\n pullRequestProvenance(subscription.data, card.factoryProjectId)?.workItemId === card.id,\n ),\n );\n}\n\nexport function attachGithubPullRequestDiscovery(\n github: GithubRulesIntegration,\n context: IntegrationContext,\n listOpenPullRequests: GithubOpenPullRequestLister,\n): GithubPullRequestDiscovery | undefined {\n const options = githubRulesOptions(github, context);\n if (!options) return undefined;\n return createGithubPullRequestDiscovery(options, listOpenPullRequests);\n}\n\nexport function githubRulesOptions(\n github: GithubRulesIntegration,\n context: IntegrationContext,\n): GithubRulesOptions | undefined {\n if (!context.runtime) return undefined;\n return {\n github,\n sourceControl: context.storage.sourceControl,\n integrationStorage: context.storage.generic,\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards: context.runtime.boards,\n ...(context.hooks?.onRepositoryPush ? { onRepositoryPush: context.hooks.onRepositoryPush } : {}),\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":";;;;;;;;;;;;;;;;;AA4DA,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,UAAU,OAAoC;CACrD,MAA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