export declare interface Branch { name: string; sha: string; protected: boolean; } export declare const BUZZ_FIXTURE_PUBKEYS: { readonly owner: "2ad53df8aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa4f05"; readonly attestor: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; readonly reactor: "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"; }; /** * Buzz/Nostr forge event kinds verified live against desktop-v0.5.3 (ADR-002). * Kind numbers are load-bearing and must match the deployed relay. */ export declare const BUZZ_FORGE_KINDS: { readonly repositoryAnnouncement: 30617; readonly refUpdate: 30618; readonly patch: 1617; readonly statusOpen: 1630; readonly statusApplied: 1631; readonly statusClosed: 1632; readonly statusDraft: 1633; readonly reaction: 7; readonly channelMembers: 39002; }; /** Channel role floor used when validating kind:7 approvals (ADR-002). */ export declare type BuzzChannelRole = 'owner' | 'admin' | 'member' | 'guest' | 'bot'; declare interface BuzzFixtureOptions { /** Override event id after computing the NIP-01 digest (duplicate/replay cases). */ id?: string; pubkey?: string; created_at?: number; tags?: readonly (readonly string[])[]; content?: string; sig?: string; } export declare type BuzzForgeKind = (typeof BUZZ_FORGE_KINDS)[keyof typeof BUZZ_FORGE_KINDS]; /** * Minimal buzz relay client: HTTP REQ polling plus an injectable event source * for tests and WebSocket adapters. * * The client never mutates process-global state. Each subscribe/poll call is * scoped to the constructed options. */ export declare class BuzzRelayClient { private readonly relays; private readonly kinds; private readonly channelIds; private readonly fetchImpl; private readonly pollIntervalMs; private readonly seenIds; constructor(options: BuzzRelayClientOptions); /** * Poll every configured relay once with a NIP-01-style HTTP REQ body and * return newly observed, verified envelopes (deduped by event id). */ pollOnce(options?: { since?: number; allowUnverifiedFixtures?: boolean; membersEvent?: NostrForgeEvent; referencedPatchEvent?: NostrForgeEvent; }): Promise; /** * Poll on an interval until `close()` is called. Useful for long-running * Aedile adapters. Returns a subscription handle. */ subscribe(onEvent: (envelope: ForgeEventEnvelope) => void | Promise, options?: { since?: number; allowUnverifiedFixtures?: boolean; membersEvent?: NostrForgeEvent; referencedPatchEvent?: NostrForgeEvent; onError?: (error: unknown) => void; }): BuzzRelaySubscription; /** * Normalize a pre-fetched event list (tests / custom transports) without * contacting a relay. Applies the same kind/channel filters and id dedupe. */ ingestEvents(events: readonly NostrForgeEvent[], options?: { allowUnverifiedFixtures?: boolean; membersEvent?: NostrForgeEvent; referencedPatchEvent?: NostrForgeEvent; verify?: boolean; }): ForgeEventEnvelope[]; /** Forget delivered ids (operator replay). */ resetSeen(): void; private fetchEvents; } export declare interface BuzzRelayClientOptions { /** WebSocket or HTTP relay endpoints. */ relays: readonly string[]; /** Optional filter limiting which kinds are accepted. */ kinds?: readonly number[]; /** Bound channel ids watched for forge activity. */ channelIds?: readonly string[]; /** Fetch implementation override for tests. */ fetch?: typeof fetch; /** Poll interval in ms when using HTTP REQ polling. Default 5000. */ pollIntervalMs?: number; } export declare interface BuzzRelaySubscription { close(): void; } export declare interface BuzzRoleResolution { pubkey: string; role: BuzzChannelRole; } /** Extract a channel id from common buzz tags when present. */ export declare function channelIdFromEvent(event: NostrForgeEvent): string | undefined; /** Normalized provider check run. */ export declare interface CheckRun { id: string; name: string; headSha: string; status: ForgeCheckStatus; conclusion?: ForgeCheckConclusion; detailsUrl?: string; externalId?: string; startedAt?: Date; completedAt?: Date; raw?: unknown; } /** Human-readable check-run output published by a forge. */ export declare interface CheckRunOutput { title: string; summary: string; text?: string; } declare interface Comment_2 { id: string; body: string; author: User; createdAt: Date; updatedAt: Date; url: string; } export { Comment_2 as Comment } /** Normalized provider commit status. */ export declare interface CommitStatus { id: string; sha: string; state: string; context: string; description?: string; targetUrl?: string; createdAt?: Date; raw?: unknown; } /** * Compute the NIP-01 event id for a Nostr event (sha256 of serialized fields). * Used by fixtures and verification when the caller supplies an unsigned skeleton. */ export declare function computeNostrEventId(event: Omit): string; export declare function createApprovalFixture(options?: BuzzFixtureOptions & { content?: string; headSha?: string; targetEventId?: string; }): NostrForgeEvent; /** * Deterministic sequences for convergence suites (duplicate / delayed / * out-of-order / replay). Each sequence is an ordered list of Nostr events; * consumers may reshuffle delivery while asserting identical projection state. */ export declare function createBuzzConvergenceSequences(): { canonical: NostrForgeEvent[]; duplicate: NostrForgeEvent[]; delayed: NostrForgeEvent[]; outOfOrder: NostrForgeEvent[]; replay: NostrForgeEvent[]; }; /** * Build a deterministic unsigned-then-id-bound Nostr event for tests. * Signature bytes are placeholders; pair with `allowUnverifiedFixtures: true`. */ export declare function createBuzzFixtureEvent(kind: number, options?: BuzzFixtureOptions): NostrForgeEvent; /** Input for publishing a provider check run. */ export declare interface CreateCheckRunInput { name: string; headSha: string; status?: ForgeCheckStatus; conclusion?: ForgeCheckConclusion; detailsUrl?: string; externalId?: string; startedAt?: Date | string; completedAt?: Date | string; output?: CheckRunOutput; } /** Input for publishing a provider commit status. */ export declare interface CreateCommitStatusInput { sha: string; state: 'error' | 'failure' | 'pending' | 'success'; context: string; description?: string; targetUrl?: string; } /** * Options for creating a repository from a template */ export declare interface CreateFromTemplateOptions { /** The organization or user who will own the new repository */ owner: string; /** The name for the new repository */ name: string; /** A short description of the new repository */ description?: string; /** Whether the new repository should be private (default: true) */ isPrivate?: boolean; /** Whether to include all branches from the template (default: false, only default branch) */ includeAllBranches?: boolean; } /** * Creates a short-lived GitHub App JWT without mutating process credentials. * @param credentials GitHub App ID and RSA private key. * @param now Clock value used for issued-at and expiry claims. * @returns Signed RS256 GitHub App JWT. * @throws {ForgeError} When credentials are missing or the key cannot sign. */ export declare function createGitHubAppJwt(credentials: GitHubAppCredentials, now?: Date): string; /** * Produces exact, repeatable webhook bytes and headers for integration suites. * Pass the same delivery id for duplicates, or a new id with the same payload * for a provider redelivery. * @param options Secret, delivery identity, event name, and payload. * @returns Exact bytes and matching GitHub delivery headers. */ export declare function createGitHubWebhookFixture(options: { secret: string; deliveryId: string; event: string; payload: unknown; }): GitHubWebhookFixture; export declare interface CreateIssueInput { title: string; body?: string; labels?: string[]; assignees?: string[]; } export declare function createMembersFixture(options?: BuzzFixtureOptions & { members?: readonly { pubkey: string; role: string; }[]; }): NostrForgeEvent; export declare function createPatchFixture(options?: BuzzFixtureOptions & { headSha?: string; number?: number; repoId?: string; }): NostrForgeEvent; export declare interface CreatePRInput { title: string; body?: string; headRef: string; baseRef: string; draft?: boolean; } export declare function createRefUpdateFixture(options?: BuzzFixtureOptions & { ref?: string; head?: string; previous?: string; repoId?: string; owner?: string; }): NostrForgeEvent; export declare function createRepositoryAnnouncementFixture(options?: BuzzFixtureOptions & { owner?: string; repoId?: string; channelId?: string; }): NostrForgeEvent; export declare function createStatusFixture(options?: BuzzFixtureOptions & { kind?: typeof BUZZ_FORGE_KINDS.statusOpen | typeof BUZZ_FORGE_KINDS.statusApplied | typeof BUZZ_FORGE_KINDS.statusClosed | typeof BUZZ_FORGE_KINDS.statusDraft; context?: string; headSha?: string; conclusion?: string; }): NostrForgeEvent; /** * Detect which template an issue was created from based on labels * * Matches issue labels against template labels to find the best match. * Returns the template with the most matching labels. * * @param labels - Issue labels * @param templates - Available templates * @returns Matching template or undefined if no match * * @example * ```typescript * const templates = await fetchIssueTemplates(repo); * const template = detectTemplateFromLabels(['bug', 'critical'], templates); * if (template) { * const fields = parseIssueBody(issue.body, template); * } * ``` */ export declare function detectTemplateFromLabels(labels: string[], templates: IssueTemplate[]): IssueTemplate | undefined; /** * Fetch issue templates from a repository via GitHub API * * @param repo - Repository client implementing IRepository * @returns Array of parsed issue templates * * @example * ```typescript * const repo = await getRepository({ type: 'github', owner: 'org', repo: 'name', token }); * const templates = await fetchIssueTemplates(repo); * // [{ name: 'Bug Report', labels: ['bug'], body: [...] }, ...] * ``` */ export declare function fetchIssueTemplates(repo: IRepository): Promise; /** Actor identity supplied by a forge event. */ export declare interface ForgeActor { id?: string; login: string; type?: string; } /** Provider health or webhook availability observation. */ export declare interface ForgeAvailabilityObservation extends ForgeObservationBase { kind: 'availability'; available: boolean; message?: string; } export declare type ForgeCheckConclusion = 'action_required' | 'cancelled' | 'failure' | 'neutral' | 'skipped' | 'stale' | 'startup_failure' | 'success' | 'timed_out'; /** Check-run or check-suite observation. */ export declare interface ForgeCheckObservation extends ForgeObservationBase { kind: 'check'; check: CheckRun; } export declare type ForgeCheckStatus = 'queued' | 'in_progress' | 'completed'; /** Deployment or deployment-status observation. */ export declare interface ForgeDeploymentObservation extends ForgeObservationBase { kind: 'deployment'; deployment: { id: string; sha?: string; ref?: string; environment?: string; state?: string; url?: string; }; } export declare class ForgeError extends Error { readonly provider?: ForgeProvider; readonly code: ForgeErrorCode; readonly status?: number; readonly requestId?: string; readonly rateLimit?: ForgeRateLimit; readonly details?: unknown; readonly retryable: boolean; constructor(message: string, code: ForgeErrorCode, options?: { cause?: unknown; provider?: ForgeProvider; status?: number; requestId?: string; rateLimit?: ForgeRateLimit; details?: unknown; retryable?: boolean; }); } export declare type ForgeErrorCode = 'AUTHENTICATION_FAILED' | 'AUTHORITY_MISMATCH' | 'CONFIGURATION_ERROR' | 'INVALID_INPUT' | 'NOT_FOUND' | 'PROVIDER_ERROR' | 'RATE_LIMITED' | 'SIGNATURE_INVALID' | 'TRANSPORT_ERROR'; /** Verified delivery envelope retaining the parsed provider payload. */ export declare interface ForgeEventEnvelope { provider: ForgeProvider; deliveryId: string; event: string; action?: string; occurredAt?: Date; receivedAt: Date; installation?: ForgeInstallationRef; repository?: ForgeRepositoryRef; actor?: ForgeActor; observation: TObservation; /** Original parsed provider payload. Raw request bytes remain caller-owned. */ raw: unknown; } /** Installation lifecycle or repository-scope observation. */ export declare interface ForgeInstallationObservation extends ForgeObservationBase { kind: 'installation'; installation: ForgeInstallationRef; repositories?: readonly ForgeRepositoryRef[]; } /** Installation identity associated with provider authority. */ export declare interface ForgeInstallationRef { id: string; account?: string; repositorySelection?: 'all' | 'selected'; } /** Merge-queue group observation tied to its synthetic head revision. */ export declare interface ForgeMergeGroupObservation extends ForgeObservationBase { kind: 'merge_group'; headSha: string; headRef?: string; baseSha?: string; baseRef?: string; } /** Completed pull-request merge observation. */ export declare interface ForgeMergeObservation extends ForgeObservationBase { kind: 'merge'; pullRequest: ForgePullRequestRef; mergeCommitSha?: string; } export declare type ForgeObservation = ForgeAvailabilityObservation | ForgeCheckObservation | ForgeDeploymentObservation | ForgeInstallationObservation | ForgeMergeGroupObservation | ForgeMergeObservation | ForgePullRequestObservation | ForgePushObservation | ForgeRepositoryObservation | ForgeReviewObservation | ForgeStatusObservation | ForgeUnknownObservation; /** Shared discriminator implemented by every normalized observation. */ declare interface ForgeObservationBase { kind: 'availability' | 'check' | 'deployment' | 'installation' | 'merge' | 'merge_group' | 'pull_request' | 'push' | 'repository' | 'review' | 'status' | 'unknown'; } /** Provider-neutral forge reconciliation and check-publishing operations. */ export declare interface ForgeOperations { /** Returns the configured repository. */ getRepository(): Promise>; /** Returns one pull request by repository-local number. */ getPullRequest(number: number): Promise>; /** Returns provider review payloads for one pull request. */ listPullRequestReviews(number: number): Promise>; /** Returns one commit payload by SHA. */ getCommit(sha: string): Promise>; /** Returns complete commit-status history across provider pages. */ listCommitStatuses(sha: string): Promise>; /** Publishes one commit status. */ createCommitStatus(input: CreateCommitStatusInput): Promise>; /** Returns complete check history, including reruns, across provider pages. */ listCheckRuns(sha: string): Promise>; /** Publishes one check run. */ createCheckRun(input: CreateCheckRunInput): Promise>; /** Changes one check run by provider ID. */ updateCheckRun(id: string, input: UpdateCheckRunInput): Promise>; /** Lists deployments using narrow optional filters. */ listDeployments(options?: { sha?: string; environment?: string; limit?: number; }): Promise>; /** Returns one deployment by provider ID. */ getDeployment(id: string): Promise>; } export declare type ForgeProvider = 'github' | (string & {}); /** Pull-request lifecycle or revision observation. */ export declare interface ForgePullRequestObservation extends ForgeObservationBase { kind: 'pull_request'; pullRequest: ForgePullRequestRef; } /** Pull-request identity and exact revision references. */ export declare interface ForgePullRequestRef { id?: string; number: number; state: 'open' | 'closed'; draft?: boolean; headSha: string; headRef?: string; baseSha?: string; baseRef?: string; merged?: boolean; mergeCommitSha?: string; url?: string; } /** Git reference update observation. */ export declare interface ForgePushObservation extends ForgeObservationBase { kind: 'push'; ref: string; beforeSha?: string; afterSha: string; forced?: boolean; created?: boolean; deleted?: boolean; } /** Provider quota information captured from one forge response. */ export declare interface ForgeRateLimit { limit?: number; remaining?: number; used?: number; resetAt?: Date; retryAfterMs?: number; } /** Repository lifecycle or metadata observation. */ export declare interface ForgeRepositoryObservation extends ForgeObservationBase { kind: 'repository'; repository: ForgeRepositoryRef; } /** Provider-neutral repository identity and reconciled attributes. */ export declare interface ForgeRepositoryRef { id?: string; owner: string; name: string; fullName: string; defaultBranch?: string; private?: boolean; url?: string; } /** Provider data paired with concurrency-safe request metadata. */ export declare interface ForgeResponse { data: T; metadata: ForgeResponseMetadata; } /** Metadata for the same provider request that produced a response. */ export declare interface ForgeResponseMetadata { provider: ForgeProvider; requestId?: string; status: number; rateLimit?: ForgeRateLimit; pagination?: { pages: number; totalCount?: number; }; } /** Pull-request review observation tied to an exact commit when available. */ export declare interface ForgeReviewObservation extends ForgeObservationBase { kind: 'review'; pullRequest: ForgePullRequestRef; review: { id: string; state: string; body?: string; commitSha?: string; submittedAt?: Date; author?: ForgeActor; }; } export declare class ForgeSignatureError extends ForgeError { constructor(message?: string); } /** Commit-status observation. */ export declare interface ForgeStatusObservation extends ForgeObservationBase { kind: 'status'; status: CommitStatus; } /** Executes authenticated provider requests and normalizes their metadata. */ export declare interface ForgeTransport { /** * Executes one provider request. * @throws {ForgeError} When transport or provider processing fails. */ request(request: ForgeTransportRequest): Promise>; } /** Provider-neutral HTTP request accepted by a forge transport. */ export declare interface ForgeTransportRequest { method: 'DELETE' | 'GET' | 'PATCH' | 'POST' | 'PUT'; path: string; body?: unknown; headers?: Readonly>; signal?: AbortSignal; } /** Forward-compatible observation for an unsupported provider event. */ export declare interface ForgeUnknownObservation extends ForgeObservationBase { kind: 'unknown'; } /** * Get a specific field value from an issue body * * @param body - The issue body markdown * @param fieldIdOrLabel - Field ID (with template) or label (without template) * @param template - Optional template for field ID lookup * @returns Field value or undefined if not found */ export declare function getIssueField(body: string, fieldIdOrLabel: string, template?: IssueTemplate): string | undefined; /** * Get a repository client instance * * This is the main entry point following the pattern from @happyvertical/files and @happyvertical/sql. * It can accept either a configuration object or an existing repository instance. * * @param options - Repository configuration or existing repository instance * @returns Promise resolving to repository interface * * @example * ```typescript * import { getRepository } from '@happyvertical/repos'; * * // Create a GitHub repository client * const repo = await getRepository({ * type: 'github', * owner: 'happyvertical', * repo: 'sdk', * token: process.env.GITHUB_TOKEN * }); * * // Use the client * const issue = await repo.getIssue(352); * await repo.addLabels(352, ['type: feature', 'priority: high']); * * // Pass existing instance (returns it unchanged) * const sameRepo = await getRepository(repo); * ``` */ export declare function getRepository(options: RepositoryConfig | IRepository): Promise; /** * Request/job-scoped GitHub App authority. * * Keep this object inside a single request or job. Its token cache and in-flight * acquisitions are instance fields, so installations cannot share credentials. */ export declare class GitHubAppAuth { private readonly credentials; private readonly baseUrl?; private readonly fetchImplementation?; private readonly now; private readonly expirySkewMs; private readonly tokens; private readonly issuedTokens; private readonly tokenRequests; private readonly authorizationRequests; private readonly revokedInstallations; private nextTokenGeneration; /** * Creates isolated GitHub App authority from credentials and dependencies. * @param options Credentials, clock, provider URL, and fetch override. */ constructor(options: GitHubAppAuthOptions); /** * Clears locally cached credentials without remote revocation. * @param installationId Optional installation to clear; omitted clears all. * @returns Nothing. */ clear(installationId?: string | number): void; /** * Acquires and verifies one installation/repository boundary. * @param scope Installation ID and exact repository coordinates. * @returns An isolated forge provider and revocation handle. * @throws {ForgeError} When authentication, provider access, or scope fails. */ createInstallationContext(scope: GitHubInstallationScope): Promise; private getAuthorizedToken; private getInstallationToken; private acquireInstallationToken; private verifyRepositoryScope; private revokeInstallationTokens; private revokeToken; private clearCachedInstallation; } /** Construction options for one request/job-scoped GitHub App authority. */ export declare interface GitHubAppAuthOptions extends GitHubAppCredentials { baseUrl?: string; fetch?: typeof globalThis.fetch; now?: () => Date; /** Refresh before provider expiry. Defaults to 60 seconds. */ expirySkewMs?: number; } /** Credentials required to sign GitHub App JSON Web Tokens. */ export declare interface GitHubAppCredentials { appId: string | number; privateKey: string; } /** Combined CI state of a repository's default-branch head commit. */ export declare type GitHubCiState = 'success' | 'failure' | 'pending' | 'none'; /** * Repository-scoped GitHub implementation of provider-neutral forge operations. * Every operation may throw `ForgeError` for transport or provider failures. */ export declare class GitHubForgeProvider implements ForgeOperations { private readonly transport; private readonly path; /** * Creates a repository-scoped GitHub forge provider. * @param options Repository coordinates and authenticated transport. */ constructor(options: GitHubForgeProviderOptions); /** @returns Normalized repository data and request metadata. */ getRepository(): Promise>; /** * Returns one normalized pull request. * @param number Repository-local pull-request number. * @returns Pull-request data and request metadata. * @throws {ForgeError} When GitHub rejects the request. */ getPullRequest(number: number): Promise>; /** * Lists every raw provider review for one pull request. * @param number Repository-local pull-request number. * @returns All reviews and final-page request metadata. */ listPullRequestReviews(number: number): Promise>; /** * Returns one raw provider commit payload. * @param sha Exact commit SHA. * @returns Commit payload and request metadata. */ getCommit(sha: string): Promise>; /** * Returns complete normalized commit-status history. * @param sha Exact commit SHA. * @returns All status pages and final-page request metadata. */ listCommitStatuses(sha: string): Promise>; /** * Publishes one commit status. * @param input Exact SHA and status attributes. * @returns Published status and request metadata. */ createCommitStatus(input: CreateCommitStatusInput): Promise>; /** * Returns all normalized check runs, including reruns. * @param sha Exact commit SHA. * @returns All check pages and final-page request metadata. */ listCheckRuns(sha: string): Promise>; /** * Publishes one check run. * @param input Check identity, exact head SHA, state, and output. * @returns Published check and request metadata. */ createCheckRun(input: CreateCheckRunInput): Promise>; /** * Changes one check run by provider ID. * @param id GitHub check-run ID. * @param input Attributes to change. * @returns Updated check and request metadata. */ updateCheckRun(id: string, input: UpdateCheckRunInput): Promise>; /** * Lists raw deployment payloads using narrow filters. * @param options Optional SHA, environment, and result limit. * @returns Matching deployments and request metadata. */ listDeployments(options?: { sha?: string; environment?: string; limit?: number; }): Promise>; /** * Returns one raw deployment payload. * @param id GitHub deployment ID. * @returns Deployment payload and request metadata. */ getDeployment(id: string): Promise>; private paginate; } /** Repository coordinates and transport for a GitHub forge provider. */ export declare interface GitHubForgeProviderOptions { owner: string; repo: string; transport: ForgeTransport; } /** Authorized repository client and explicit token-revocation handle. */ export declare interface GitHubInstallationContext { installation: ForgeInstallationRef; repository: ForgeRepositoryRef; forge: GitHubForgeProvider; /** Revokes issued tokens remotely and closes this local context. */ revoke(): Promise; } /** Installation and repository boundary requested by a caller. */ export declare interface GitHubInstallationScope { installationId: string | number; owner: string; repo: string; } /** Latest published (non-draft, non-prerelease) release of a repository. */ export declare interface GitHubLatestRelease { tag: string; /** ISO-8601 publication time, or null when GitHub reports none. */ publishedAt: string | null; url: string; } /** * GitHub repository implementation */ export declare class GitHubRepository implements IRepository { private rest; private graphql; private owner; private repo; constructor(config: RepositoryConfig); getRepository(): Promise; getIssue(number: number): Promise; createIssue(data: CreateIssueInput): Promise; updateIssue(number: number, data: UpdateIssueInput): Promise; closeIssue(number: number): Promise; addLabels(issueNumber: number, labels: string[]): Promise; removeLabel(issueNumber: number, label: string): Promise; createLabel(label: Label): Promise; updateLabel(name: string, label: Label): Promise; listLabels(): Promise; addComment(issueNumber: number, body: string): Promise; updateComment(commentId: string, body: string): Promise; deleteComment(commentId: string): Promise; listComments(issueNumber: number): Promise; assignIssue(issueNumber: number, assignees: string[]): Promise; unassignIssue(issueNumber: number, assignees: string[]): Promise; getPullRequest(number: number): Promise; createPullRequest(data: CreatePRInput): Promise; mergePullRequest(number: number, method?: MergeMethod): Promise; searchIssues(query: string, filters?: SearchFilters): Promise; getIssueNodeId(issueNumber: number): Promise; getPRNodeId(prNumber: number): Promise; createBranch(name: string, fromRef: string): Promise; deleteBranch(name: string): Promise; getBranch(name: string): Promise; markPRReady(prNumber: number): Promise; convertPRToDraft(prNumber: number): Promise; requestReview(prNumber: number, reviewers: string[]): Promise; triggerWorkflow(workflowId: string, ref: string, inputs?: Record): Promise; findPRsForIssue(issueNumber: number): Promise; findIssueForPR(prNumber: number): Promise; getFileContent(path: string, ref?: string): Promise; listDirectoryFiles(path: string, ref?: string): Promise; /** * Publishes one GitHub commit status. * @param input Exact commit SHA and status attributes. * @returns Normalized published status. */ createCommitStatus(input: CreateCommitStatusInput): Promise; /** * Returns complete commit-status history across GitHub pages. * @param sha Exact commit SHA. * @returns Every normalized status for the commit. */ listCommitStatuses(sha: string): Promise; /** * Publishes one GitHub check run. * @param input Check identity, exact head SHA, state, and output. * @returns Normalized published check run. */ createCheckRun(input: CreateCheckRunInput): Promise; /** * Changes one GitHub check run. * @param id GitHub check-run ID. * @param input Attributes to change. * @returns Normalized updated check run. */ updateCheckRun(id: string, input: UpdateCheckRunInput): Promise; /** * Returns complete GitHub check history, including reruns. * @param sha Exact commit SHA. * @returns Every normalized check run for the commit. */ listCheckRuns(sha: string): Promise; private mapCommitStatus; private mapCheckRunInput; private mapCheckRun; /** * Create a new repository from this repository as a template. * * Uses the GitHub "Generate" API: POST /repos/{template_owner}/{template_repo}/generate * The current repository (this.owner/this.repo) is used as the template. */ createRepositoryFromTemplate(options: CreateFromTemplateOptions): Promise; } /** Read-only activity summary of one repository in an organization. */ export declare interface GitHubRepositorySummary { owner: string; name: string; description: string | null; /** Null for empty repositories that have no default branch yet. */ defaultBranch: string | null; url: string; isPrivate: boolean; archived: boolean; /** ISO-8601 time of the last push, or null if never pushed. */ pushedAt: string | null; openPullRequestCount: number; latestRelease: GitHubLatestRelease | null; /** Rolled-up checks and statuses on the default-branch head commit. */ ciState: GitHubCiState; } export declare type GitHubTokenSource = string | (() => string | Promise); export declare class GitHubTransport implements ForgeTransport { private readonly token; private readonly baseUrl; private readonly fetchImplementation; /** * Creates a GitHub REST transport with fixed or lazy credentials. * @param options Token source, provider URL, and fetch override. */ constructor(options: GitHubTransportOptions); /** * Executes one GitHub REST request. * @param request Method, provider-relative path, body, headers, and signal. * @returns Parsed data and metadata for this exact request. * @throws {ForgeError} For transport, authentication, rate, or provider failures. */ request(request: ForgeTransportRequest): Promise>; } /** Construction options for an authenticated GitHub REST transport. */ export declare interface GitHubTransportOptions { token: GitHubTokenSource; baseUrl?: string; fetch?: typeof globalThis.fetch; } /** Exact webhook bytes and headers suitable for deterministic tests. */ export declare interface GitHubWebhookFixture { rawBody: Uint8Array; headers: GitHubWebhookHeaders; } export declare type GitHubWebhookHeaders = Headers | Readonly>; export declare class GitHubWebhookVerifier { private readonly secrets; private readonly now; /** * Creates a verifier with a current secret and optional rotation secrets. * @param options Current/rotation secrets and optional clock. * @throws {ForgeError} When no non-empty secret is configured. */ constructor(options: GitHubWebhookVerifierOptions); /** * Verifies unchanged provider bytes with constant-time comparisons. * @param rawBody Exact bytes received from the HTTP server. * @param signature GitHub SHA-256 signature header. * @returns Index of the configured secret that matched. * @throws {ForgeSignatureError} When the signature is missing or invalid. */ verify(rawBody: Uint8Array, signature: string | undefined): number; /** * Verifies raw bytes before decoding and normalizes the delivery. * @param rawBody Exact bytes received from the HTTP server. * @param headers Case-insensitive GitHub delivery headers. * @returns Verified normalized delivery. * @throws {ForgeError} For invalid signatures, headers, UTF-8, or JSON. */ verifyAndNormalize(rawBody: Uint8Array, headers: GitHubWebhookHeaders): ForgeEventEnvelope; } /** Construction options for raw GitHub webhook verification. */ export declare interface GitHubWebhookVerifierOptions { /** Current secret first, followed by still-valid rotation secrets. */ secrets: string | readonly string[]; now?: () => Date; } /** * Repository interface - all repository implementations must implement this */ export declare interface IRepository { getRepository(): Promise; getIssue(number: number): Promise; createIssue(data: CreateIssueInput): Promise; updateIssue(number: number, data: UpdateIssueInput): Promise; closeIssue(number: number): Promise; addLabels(issueNumber: number, labels: string[]): Promise; removeLabel(issueNumber: number, label: string): Promise; createLabel(label: Label): Promise; updateLabel(name: string, label: Label): Promise; listLabels(): Promise; addComment(issueNumber: number, body: string): Promise; updateComment(commentId: string, body: string): Promise; deleteComment(commentId: string): Promise; listComments(issueNumber: number): Promise; assignIssue(issueNumber: number, assignees: string[]): Promise; unassignIssue(issueNumber: number, assignees: string[]): Promise; getPullRequest(number: number): Promise; createPullRequest(data: CreatePRInput): Promise; mergePullRequest(number: number, method?: MergeMethod): Promise; searchIssues(query: string, filters?: SearchFilters): Promise; getIssueNodeId(issueNumber: number): Promise; getPRNodeId(prNumber: number): Promise; createBranch(name: string, fromRef: string): Promise; deleteBranch(name: string): Promise; getBranch(name: string): Promise; markPRReady(prNumber: number): Promise; convertPRToDraft(prNumber: number): Promise; requestReview(prNumber: number, reviewers: string[]): Promise; triggerWorkflow(workflowId: string, ref: string, inputs?: Record): Promise; findPRsForIssue(issueNumber: number): Promise; findIssueForPR(prNumber: number): Promise; getFileContent(path: string, ref?: string): Promise; listDirectoryFiles(path: string, ref?: string): Promise; /** Publishes one provider commit status. */ createCommitStatus?(input: CreateCommitStatusInput): Promise; /** Returns complete commit-status history across provider pages. */ listCommitStatuses?(sha: string): Promise; /** Publishes one provider check run. */ createCheckRun?(input: CreateCheckRunInput): Promise; /** Changes one provider check run. */ updateCheckRun?(id: string, input: UpdateCheckRunInput): Promise; /** Returns complete check history, including reruns, across provider pages. */ listCheckRuns?(sha: string): Promise; } export declare interface Issue { number: number; id: string; title: string; body: string; state: 'open' | 'closed'; labels: Label[]; assignees: User[]; author: User; createdAt: Date; updatedAt: Date; closedAt?: Date; url: string; commentsCount: number; } /** * Issue template definition */ export declare interface IssueTemplate { name: string; description?: string; title?: string; labels?: string[]; assignees?: string[]; body: TemplateField[]; } export declare interface Label { name: string; color: string; description: string; } /** * Lists every repository of an organization, archived included, with an * activity summary, using one GraphQL request per page of repositories. * Read-only: works with a token that has read access to repository metadata, * pull requests, and checks/statuses. * @param options Owner login, credentials, and paging controls. * @returns Repository summaries ordered by name, plus request accounting. * @throws {ForgeError} When the owner is missing, GraphQL reports errors, or * the transport fails (including rate limiting). */ export declare function listOrganizationRepositories(options: ListOrganizationRepositoriesOptions): Promise; /** Options for {@link listOrganizationRepositories}. */ export declare interface ListOrganizationRepositoriesOptions { /** Organization (or user) login whose repositories are listed. */ owner: string; /** Read-only token (or lazy token source). Ignored when `transport` is set. */ token?: GitHubTokenSource; /** * GitHub REST base URL. Defaults to https://api.github.com. GHES * `https://HOST/api/v3` resolves GraphQL to `https://HOST/api/graphql`. * Also set it when passing a `transport` for a non-github.com host. */ baseUrl?: string; /** Fetch override, mainly for tests. Ignored when `transport` is set. */ fetch?: typeof globalThis.fetch; /** Pre-built transport, for example from a GitHub App installation. */ transport?: ForgeTransport; /** Repositories per GraphQL page, 1-100. Defaults to 50. */ pageSize?: number; /** Safety cap on GraphQL pages fetched. Defaults to 100. */ maxPages?: number; signal?: AbortSignal; } /** * Load and parse an issue template from a YAML file * * @param yamlPath - Path to the YAML template file * @returns Parsed issue template * * @example * ```typescript * const template = await loadIssueTemplate('.github/ISSUE_TEMPLATE/bug_report.yml'); * ``` */ export declare function loadIssueTemplate(yamlPath: string): Promise; export declare type MergeMethod = 'merge' | 'squash' | 'rebase'; /** * Normalize one already-verified Nostr forge event into a provider-neutral * envelope. Signature verification is the caller's responsibility (or use * {@link verifyAndNormalizeBuzzEvent}). */ export declare function normalizeBuzzEvent(event: NostrForgeEvent, receivedAt?: Date, options?: { roleFloor?: BuzzChannelRole; membersEvent?: NostrForgeEvent; referencedPatchEvent?: NostrForgeEvent; }): ForgeEventEnvelope; /** * Normalizes one already-verified GitHub payload. * @param deliveryId Stable provider delivery identity. * @param event GitHub event header value. * @param raw Parsed provider payload. * @param receivedAt Local receipt timestamp. * @returns A provider-neutral event envelope preserving the parsed payload. */ export declare function normalizeGitHubWebhook(deliveryId: string, event: string, raw: unknown, receivedAt?: Date): ForgeEventEnvelope; /** Minimal Nostr event shape consumed by the buzz forge adapter. */ export declare interface NostrForgeEvent { id: string; pubkey: string; created_at: number; kind: number; tags: readonly (readonly string[])[]; content: string; sig: string; } /** Repositories plus how many GraphQL requests were spent fetching them. */ export declare interface OrganizationRepositoryListing { repositories: GitHubRepositorySummary[]; /** Number of GraphQL requests issued (one per page). */ requests: number; /** Rate-limit headers from the final response, when present. */ rateLimit?: ForgeRateLimit; } /** * Parse an issue body into field values * * GitHub renders form fields as markdown sections: * ``` * ### Label * * Content here * * ### Next Label * ``` * * Without a template, returns a Record keyed by label. * With a template, returns a Record keyed by field ID. * * @param body - The issue body markdown * @param template - Optional template for mapping labels to field IDs * @returns Parsed fields as key-value pairs * * @example * ```typescript * // Without template - keyed by label * const fields = parseIssueBody(issue.body); * // { 'Description': '...', 'Steps to Reproduce': '...' } * * // With template - keyed by field ID * const template = await loadIssueTemplate('.github/ISSUE_TEMPLATE/bug_report.yml'); * const fields = parseIssueBody(issue.body, template); * // { description: '...', reproduction: '...' } * ``` */ export declare function parseIssueBody(body: string, template?: IssueTemplate): Record; /** * Parse an issue template from YAML content * * @param yamlContent - YAML content string * @returns Parsed issue template * * @example * ```typescript * const template = parseIssueTemplate(` * name: Bug Report * body: * - type: textarea * id: description * attributes: * label: Description * `); * ``` */ export declare function parseIssueTemplate(yamlContent: string): IssueTemplate; export declare interface PullRequest extends Issue { headRef: string; baseRef: string; merged: boolean; mergedAt?: Date; mergeable: boolean; draft: boolean; } /** * Render fields into an issue body markdown string * * Without a template, uses field keys as labels. * With a template, uses field IDs to look up labels and renders in template order. * * @param fields - Field values as key-value pairs * @param template - Optional template for field ordering and labels * @returns Markdown string for issue body * * @example * ```typescript * // Without template * const body = renderIssueBody({ * 'Description': 'Bug description here', * 'Steps to Reproduce': '1. Do X\n2. See error' * }); * * // With template * const template = await loadIssueTemplate('.github/ISSUE_TEMPLATE/bug_report.yml'); * const body = renderIssueBody({ * description: 'Bug description here', * reproduction: '1. Do X\n2. See error' * }, template); * ``` */ export declare function renderIssueBody(fields: Record, template?: IssueTemplate): string; export declare interface Repository { owner: string; name: string; description: string; defaultBranch: string; url: string; isPrivate: boolean; } /** * Repository configuration */ export declare interface RepositoryConfig { type: 'github' | 'gitlab' | 'bitbucket' | 'azure'; owner: string; repo: string; token: string; baseUrl?: string; } export declare class RepositoryError extends Error { code: RepositoryErrorCode; statusCode?: number | undefined; response?: unknown | undefined; constructor(message: string, code: RepositoryErrorCode, statusCode?: number | undefined, response?: unknown | undefined); static fromHTTPStatus(statusCode: number, message: string, response?: unknown): RepositoryError; static networkError(message: string, cause?: Error): RepositoryError; isRetryable(): boolean; } /** * Repository error handling */ export declare enum RepositoryErrorCode { NOT_FOUND = "NOT_FOUND", UNAUTHORIZED = "UNAUTHORIZED", FORBIDDEN = "FORBIDDEN", RATE_LIMITED = "RATE_LIMITED", VALIDATION_ERROR = "VALIDATION_ERROR", NETWORK_ERROR = "NETWORK_ERROR", UNKNOWN = "UNKNOWN" } /** * Resolve a reactor's channel role from a kind:39002 members list. * Returns null when the pubkey is absent from the membership event. */ export declare function resolveBuzzChannelRole(membersEvent: NostrForgeEvent, pubkey: string): BuzzRoleResolution | null; /** True when the reactor's role rank is at or above the configured floor. */ export declare function roleMeetsFloor(role: BuzzChannelRole, floor: BuzzChannelRole): boolean; export declare interface SearchFilters { state?: 'open' | 'closed' | 'all'; labels?: string[]; author?: string; assignee?: string; limit?: number; sort?: 'created' | 'updated' | 'comments'; order?: 'asc' | 'desc'; } /** * Template field definition - mirrors GitHub ISSUE_TEMPLATE YAML structure */ export declare interface TemplateField { type: 'textarea' | 'input' | 'dropdown' | 'checkboxes' | 'markdown'; id?: string; attributes: { label: string; description?: string; placeholder?: string; value?: string; options?: string[]; }; validations?: { required?: boolean; }; } /** Input for changing an existing provider check run. */ export declare interface UpdateCheckRunInput extends Omit { name?: string; } /** * Update a specific field in an issue body * * @param body - The issue body markdown * @param fieldIdOrLabel - Field ID (with template) or label (without template) * @param value - New value for the field * @param template - Optional template for field ID lookup * @returns Updated issue body markdown */ export declare function updateIssueField(body: string, fieldIdOrLabel: string, value: string, template?: IssueTemplate): string; export declare interface UpdateIssueInput { title?: string; body?: string; state?: 'open' | 'closed'; } /** * Core types for repository operations */ export declare interface User { login: string; id: string; type: 'User' | 'Bot'; avatarUrl?: string; url?: string; } /** * Verify then normalize a buzz forge event. Rejects invalid signatures without * producing an observation. */ export declare function verifyAndNormalizeBuzzEvent(event: NostrForgeEvent, receivedAt?: Date, options?: { roleFloor?: BuzzChannelRole; membersEvent?: NostrForgeEvent; referencedPatchEvent?: NostrForgeEvent; allowUnverifiedFixtures?: boolean; }): ForgeEventEnvelope; /** * Structural signature verification for Nostr events. * * When `nostr-tools` is available it performs full Schnorr verification. * Otherwise it fails closed unless `allowUnverifiedFixtures` is set (tests * that inject pre-trusted fixture events with matching id digests). */ export declare function verifyNostrEventSignature(event: NostrForgeEvent, options?: { allowUnverifiedFixtures?: boolean; }): void; export { }