import { type GithubStateWriteOptions } from "./durable-state.ts"; import { type GithubOwnershipIndex, type GithubOwnedTarget } from "./import-ownership.ts"; import { type GithubStatusRegistry } from "./workspace.ts"; export { githubLabelsToTags } from "./import-tags.ts"; import type { ExtensionApi } from "@unbrained/pm-cli/sdk/authoring"; export { compileIssueForm, completeIssueForm, readRepositoryIssueForm } from "./issue-forms.ts"; export type { IssueFormInput, IssueFormSelection, IssueFormContract, IssueFormReport, IssueFormCompletion, IssueFormRefusalCode, FormField, FormRepair, IssueFormReader } from "./issue-forms.ts"; import { type LegacyGithubIdentityConflict, fetchImportTimeline, readImportReleases, type AmbiguousCitationPlan, type CitationCandidate, type ImportFidelity } from "./import-fidelity.ts"; export { captureGithubDiscussion, readGithubDiscussionComment, validateDiscussionCaptureReport } from "./discussions.ts"; export type { DiscussionCaptureOptions, DiscussionCommentReader, DiscussionRefusalCode } from "./discussions.ts"; export type { DiscussionCaptureInput, DiscussionCaptureReport, DiscussionDecisionEvidence } from "./discussion-schema.ts"; export { planGithubLabelMigration, readGithubLabelCatalog, validateGithubLabelMigrationReport } from "./labels.ts"; export type { GithubLabelMigrationInput, GithubLabelCatalog, GithubLabelCatalogReader, GithubLabelMigrationReport, LabelMigrationRefusalCode } from "./labels.ts"; export { exploreGithubIdentities, planGithubIdentityRepair, applyGithubIdentityRepair } from "./identity.ts"; export type { IdentityRefusalCode, IdentityEdge, IdentityNode, IdentityReport, IdentityRepairPlan } from "./identity.ts"; export { acceptGithubWebhook, reconcileGithubWebhooks, WebhookRefusal } from "./webhooks.ts"; export type { GithubWebhookDelivery, WebhookProposal, WebhookReconciliation, WebhookRefusalCode } from "./webhooks.ts"; import { type BulkItemMutation, type CommitItemMutationsOptions, type CommitItemMutationsResult, type ItemDocument } from "@unbrained/pm-cli/sdk"; import { type GateReport, type GateVerdict } from "./gate.ts"; export { resolvePmDataDir } from "./gate.ts"; import { type ProjectItem, type ProjectMeta, type ProjectRef, buildProjectPushPlan } from "./projects.ts"; /** * One GitHub issue or pull request as returned by the REST issues endpoint. * * The REST issues endpoint lists PRs alongside issues (a PR is an issue that * also carries a `pull_request` object); {@link isDraftPr} and the * `includePrs` / `skipDrafts` filters decide which of those survive into an * import. */ export interface GhIssue { /** Issue/PR number within its repo (the `N` in `gh:owner/repo#N` provenance). */ number: number; /** One-line issue title, imported as the pm item title. */ title: string; /** Markdown body, imported as the pm item body (`null` when GitHub stored none). */ body: string | null; /** GitHub lifecycle state; mapped to a pm status by {@link mapState}. */ state: "open" | "closed"; /** Why a closed issue was closed; `not_planned` maps to `canceled`, not `closed`. */ state_reason?: "completed" | "not_planned" | "duplicate" | "reopened" | null; /** Labels on the issue, converted through the importer's CSV/SDK native tag rules. */ labels: Array<{ name: string; }>; /** Author login, surfaced as a `github_author:` tag when present. */ user?: { login: string; } | null; /** Assigned user, or `null` (imported as the item assignee when set). */ assignee: { login: string; } | null; /** Milestone title, or `null` (filtered client-side by `--milestone`). */ milestone: { title: string; } | null; /** ISO 8601 creation timestamp. */ created_at: string; /** ISO 8601 last-update timestamp, used by the `--since` incremental filter. */ updated_at: string; /** GitHub completion timestamp (`null` while the issue is open); carried as `--completed-at` on close. */ closed_at?: string | null; /** Browser URL of the issue, embedded in the imported description. */ html_url: string; /** Comment count GitHub reports; drives whether comments are fetched at all. */ comments?: number; /** REST URL of the issue's comments collection (paginated when present). */ comments_url?: string; /** Present (opaque) when the issue is actually a pull request; its presence is the PR signal. */ pull_request?: unknown; /** `true` when the issue is a draft pull request (GitHub sets this only on draft PRs). */ draft?: boolean; } export interface GhComment { id: number; user: { login: string; } | null; created_at: string; body: string | null; } type CommentsMode = "body" | "annotations" | "both"; /** * Normalized options governing one GitHub issue import. * * Produced by {@link parseImportOptions} from the raw CLI flag bag so the rest * of the import path consumes a typed shape rather than re-parsing strings. */ export interface ImportOptions { /** Explicitly enable conservative citation adoption; default imports only report candidates. */ adoptCited?: boolean; /** Explicit comma-separated issue numbers or same-repository references. */ issue?: string; /** Positive cap on list-mode issues, ordered by latest update. */ limit?: number; /** GitHub issue state to fetch: `open`, `closed`, or `all`. */ state: "open" | "closed" | "all"; /** Comma-separated label filter applied server-side. */ labels?: string; /** ISO timestamp; only issues updated after it are fetched (server-side). */ since?: string; /** Assignee login filter applied server-side. */ assignee?: string; /** Milestone title filter applied client-side (the API keys milestones by number, not title). */ milestone?: string; /** Whether pull requests are included (filtered out by default). */ includePrs: boolean; /** Whether draft pull requests are excluded (only meaningful with {@link includePrs}). */ skipDrafts: boolean; /** Whether fetched comments are also embedded in the item body (legacy behavior). */ withComments: boolean; /** How fetched comments are persisted: body, native annotations, or both. */ commentsMode: CommentsMode; /** pm item type assigned to every created item (default `Issue`). */ itemType: string; /** When true, preview the plan without writing to the tracker or GitHub. */ dryRun: boolean; /** When true, commit the batch as one crash-resumable SDK transaction. */ atomic: boolean; /** When true, run the `--link-deps` dependency-edge second pass after import. */ linkDeps: boolean; /** When true, verify plan completeness + provenance idempotency before the * write, and run the fail-closed tracker privacy gate after it, failing the * import (non-zero) on any credential, personal-data, or host-path finding. */ gate: boolean; } type CommitItemMutations = (options: CommitItemMutationsOptions) => Promise; type NormalizeItemId = (input: string, prefix: string) => string; type ReadSettings = (pmRoot: string) => Promise<{ id_prefix?: string; }>; /** * Injectable collaborators for the atomic import path. * * Lets the crash-resumable transaction be exercised hermetically against fake * SDK functions. Every member is optional because production wires the real SDK * defaults; a test overrides only the ones it needs. */ export interface AtomicImportOptions { /** Observe a fully flushed recovery plan before its atomic exclusive publication. */ onPlanStaged?: GithubStateWriteOptions["onStaged"]; /** Refuse unmatched entries and emit updates only, including deterministic imported ids. */ updateOnly?: boolean; /** Require complete side data for gated callers; every atomic import requires passing privacy preflight. */ gate?: boolean; /** Recover issue dependency side effects from the recorded source bodies. */ linkDeps?: boolean; /** Complete original source batch, including unchanged entries needing dependency repair. */ dependencyIssues?: readonly GhIssue[]; /** Author identity stamped onto the transaction's mutations (default `pm-github`). */ atomicAuthor?: string; /** SDK transaction observer; explicit failure injection still exercises real rollback. */ onTransition?: CommitItemMutationsOptions["onTransition"]; /** SDK bulk-mutation primitive that applies and journals the transaction. */ commitItemMutations?: CommitItemMutations; /** SDK id normalizer that derives each item's stable external-key id. */ normalizeItemId?: NormalizeItemId; /** SDK settings reader used to resolve the workspace's id prefix. */ readSettings?: ReadSettings; } export interface ImportRunDependencies { resolveToken?: () => string | undefined; fetchIssues?: (repo: string, opts: ImportOptions, token?: string) => Promise; fetchIssueTimeline?: typeof fetchImportTimeline; fetchIssueComments?: (issue: GhIssue, repo: string, token?: string) => Promise; readItems?: (pmRoot: string) => PmItem[]; commitAtomic?: typeof importGithubAtomic; /** Snapshot workspace item metadata for the ordering-cycle advisory. Defaults to the SDK `listAllItemMetadata`. */ listItemMetadata?: (pmRoot: string) => Promise; /** Warnings for ordering cycles a mutation newly introduced. Defaults to the SDK `collectNewOrderingCycleWarnings`. */ collectOrderingCycleWarnings?: (before: readonly DepLinkSnapshotItem[], after: readonly DepLinkSnapshotItem[], changedItemId: string) => string[]; /** Apply one resolved dependency edge. Defaults to spawning `pm update --dep`. */ applyDependencyLink?: (edge: ResolvedDepEdge, pmRoot: string) => { ok: boolean; stderr: string; }; } export declare function resolveGitHubToken(): string | undefined; /** * Decide whether the Authorization token may be forwarded across a redirect. * * Only same-origin (scheme + host + port) redirects keep the credential; any * origin change drops it so the bearer token can never leak to a third party. * * @param fromUrl - The URL the redirect originated from. * @param toUrl - The redirect target URL. * @returns True when both URLs share an origin. */ export declare function sameOrigin(fromUrl: string, toUrl: string): boolean; /** * Compute how long (ms) to wait before retrying a rate-limited or transient * response. * * Honors `Retry-After` (seconds) and the primary rate-limit reset window * (`X-RateLimit-Remaining: 0` + `X-RateLimit-Reset` epoch), then falls back to * exponential backoff. The result is capped so a CLI run is never hung * indefinitely. * * @param headers - Response headers to read the retry hints from. * @param attempt - Zero-based retry index feeding the exponential backoff floor. * @param nowMs - Current epoch ms, used to measure the reset window's remaining time. * @returns The capped wait in milliseconds. */ export declare function computeBackoffMs(headers: Record, attempt: number, nowMs?: number): number; /** * Structured view of GitHub's rate-limit headers off one response. * * Fields are `undefined` when the corresponding header is absent or non-numeric * so callers can degrade gracefully; `reset` is the epoch-second timestamp at * which the current window reopens. */ export interface RateLimitInfo { /** Remaining requests in the current window. */ remaining?: number; /** Total requests permitted per window. */ limit?: number; /** Epoch seconds at which the window resets. */ reset?: number; /** True when the remaining quota is at/under the low-water mark. */ low: boolean; } export declare function parseRateLimit(headers: Record, lowThreshold?: number): RateLimitInfo; export declare function formatRateLimit(info: RateLimitInfo): string | undefined; export declare function parseNextLink(linkHeader?: string): string | undefined; export declare function mapState(state: string, stateReason?: string | null): string; export declare function optionEnabled(options: Record, ...keys: string[]): boolean; export declare function optionString(options: Record, ...keys: string[]): string | undefined; export declare function optionProvided(options: Record, ...keys: string[]): boolean; export declare function parseSince(value: string | undefined, nowMs?: number): string | undefined; export declare function parseLabelMap(options: Record, ...keys: string[]): Map | undefined; export declare function applyLabelMap(labels: string[], labelMap: Map | undefined): string[]; export declare function optionCsv(options: Record, ...keys: string[]): string[]; export declare const EXIT_CODE: { readonly GENERIC_FAILURE: 1; readonly USAGE: 2; readonly NOT_FOUND: 3; readonly BLOCKERS_CLEARED: 4; }; /** * Error that carries a semantic process exit code. * * pm's command runtime treats a thrown error as a cleanly handled non-zero exit * only when it exposes a numeric `exitCode`; a plain `Error` instead falls * through to the "unhandled" path, which re-invokes the handler (doubling side * effects such as a second GitHub fetch) and exits with a generic code. Throwing * this routes a failure to a clean, single exit at the chosen code. */ export declare class CommandError extends Error { /** Numeric exit code the runtime propagates to the shell (one of {@link EXIT_CODE}). */ exitCode: number; constructor(message: string, exitCode?: number); } /** * Build the `gh:owner/repo#N` provenance tag linking a pm item to a GitHub issue. * * Tags are portable references for search and review. Import identity comes * from importer-owned provenance; shared references never select an owner. * * @param repo - `owner/repo`, lowercased into the tag. * @param issueNumber - The issue/PR number. * @returns The provenance tag string. */ export declare function provenanceTag(repo: string, issueNumber: number): string; /** * Parse a `gh:owner/repo#N` provenance tag back into its repo and issue number. * * Returns `undefined` for anything that is not a provenance tag, so a caller * scanning a tag list can skip foreign tags without a try/catch. * * @param tag - The candidate tag string. * @returns The parsed repo (lowercased) and number, or `undefined`. */ export declare function parseProvenanceTag(tag: string): { repo: string; number: number; } | undefined; /** * Build the `github_author:login` tag recording who opened a GitHub issue. * * Mirrors how provenance rides on tags so the author survives a round-trip. * Returns `undefined` when the API supplied no usable login, so an empty tag is * never emitted. * * @param issue - The issue whose author to tag. * @returns The author tag, or `undefined`. */ export declare function authorTag(issue: GhIssue): string | undefined; /** * The slice of a pm item this package reads and writes. * * A deliberately loose projection of the full tracker item: only the fields the * import / export / sync paths touch, so JSON from `pm list --all` parses without * depending on every SDK field. */ export interface PmItem { /** Full proven-complete metadata, including provider links and source lifecycle. */ [key: string]: unknown; /** Stable item id (absent for items not yet created). */ id?: string; /** One-line title. */ title?: string; /** Lifecycle status (`open`, `in_progress`, `closed`, `canceled`, …). */ status?: string; /** Long-form markdown body. */ body?: string; /** Short summary shown in listings. */ description?: string; /** Tag set, carrying provenance and labels. */ tags?: string[]; } export interface ItemScopeResult { selected: TItem[]; missing: string[]; } export declare function scopeItemsByIds(items: TItem[], ids: string[] | undefined): ItemScopeResult; /** * Narrow one runtime search document to a {@link PmItem}. * * The SDK declares `SearchProviderQueryContext.documents` as `ItemDocument[]` * with a REQUIRED `metadata`, but the runtime also hands raw pm items straight * through on some paths — `SearchProviderQueryContext` carries an * `[key: string]: unknown` index signature, so its shape is looser than the * declared type. Trusting `d.metadata` unconditionally therefore yields * `undefined` entries and crashes `indexByProvenance` with a TypeError; the * pre-typing code guarded this with `d?.metadata ? d.metadata : d`, and that * guard is preserved here rather than dropped in the name of the declared type. * Anything matching neither shape is skipped instead of poisoning the index. */ export declare function searchDocumentToItem(document: ItemDocument | PmItem | null | undefined): PmItem | undefined; /** * Resolve the corpus the search provider matches remote hits against. * * Prefers the runtime-provided documents (already the current corpus) and falls * back to a fresh workspace read when absent. This is the provider's REAL mapping, * extracted so it is directly testable: the surrounding `query` handler performs * network I/O first, so an end-to-end test cannot reach the mapping without * stubbing internals, and an inline expression would be untestable in practice. */ export declare function resolveSearchCorpus(documents: unknown, pmRootValue: unknown): PmItem[]; /** * Index complete pm items by their normalized GitHub issue provenance. * * References alone never identify a local owner. Contradictory or competing * ownership is refused before associating a search result with a tracker item. * * @param items - Complete runtime-validated pm item corpus. * @returns Map keyed by lowercase `owner/repo#N` provenance. */ export declare function indexByProvenance(items: PmItem[], targets?: ReadonlySet): Map; /** Fully rendered desired state for one GitHub issue import. */ export interface PreparedGithubImport { issueNumber: number; title: string; itemType: string; status: string; description: string; body: string; /** Original remote body for dependency replay, independent of body comment rendering. */ sourceBody?: string; tags: string[]; assignee?: string; milestone?: string; comments: GhComment[]; syncAnnotations: boolean; /** Source completion timestamp; full issue plans finalize it together with source creation. */ closedAt?: string; /** Source dates, closure evidence and tag-date attribution in the verified plan. */ fidelity?: ImportFidelity; /** Existing external owner receives a link without replacing its provider context. */ linkOnly?: boolean; /** Existing local content is curated; only source lifecycle and provenance may merge. */ preserveContent?: boolean; /** Auditable identity and lifecycle conflict decision. */ identity?: { via: string; title_conflict?: boolean; conflict?: { local: string; github: string; rule: string; }; }; /** Rejected prose references remain visible for explicit manual provenance tagging. */ citation_candidates?: CitationCandidate[]; match?: PmItem; } /** Minimal shape of the SDK module the atomic import path reads. */ interface AtomicSdkModule { commitItemMutations?: CommitItemMutations; } /** Resolve the atomic bulk-mutation helper. Accepts an optional SDK override for * tests that simulate a missing export; the default path uses the top-level * imported `commitItemMutations` so normal imports never touch the dynamic * loader. */ export declare function resolveCommitItemMutations(importSdk?: () => Promise): Promise; /** * Derive an order-independent transaction id from the desired import state and * exact ordered mutation plan. Content or target changes produce a fresh * transaction; a reordered retry of the same plan resumes the durable journal. * External history revisions distinguish a local edit from a retry of import-owned writes. */ export declare function deriveAtomicTransactionId(repo: string, entries: readonly PreparedGithubImport[], mutations: readonly BulkItemMutation[], contextVersions?: readonly string[]): string; /** Stable create id keyed by the external GitHub issue, never by fetch order. */ export declare function deriveAtomicItemId(repo: string, issueNumber: number, idPrefix: string, normalizeItemId: (input: string, prefix: string) => string): string; /** Map one rendered import entry to its reversible SDK mutation sequence. */ export declare function buildAtomicImportMutations(repo: string, entry: PreparedGithubImport, idPrefix: string, normalizeItemId: (input: string, prefix: string) => string, updateOnly?: boolean, statuses?: GithubStatusRegistry): { itemId: string; mutations: BulkItemMutation[]; }; /** Durable outcome of one committed (or recovered) github-import transaction. */ export interface GithubImportCommitResult { /** Stable transaction identifier that owns the journal. */ transactionId: string; /** True when a durable journal was resumed instead of newly committed. */ recovered: boolean; /** New items created by a fresh (non-recovered) transaction. */ imported: number; /** Existing items updated by a fresh (non-recovered) transaction. */ updated: number; /** Entries covered by a recovered journal; present only when recovered. */ recoveredItems?: number; /** Dependency receipts from the original persisted plan. */ depLink?: DepLinkResult; /** Native annotation failures are best-effort after the item transaction commits. */ commentWriteFailures?: number; /** Entries whose annotations this transaction already attempted, including failed attempts. */ annotationIssueNumbers?: number[]; /** Post-commit routing map from GitHub issue number to pm item id. */ itemIds: Map; } /** One durable github-import journal that still owes a commit or a finished compensation. */ export interface UnfinishedGithubImport { /** Stable transaction id; also the journal file name inside the tracker. */ transactionId: string; /** Durable journal state the SDK reported when the tracker was scanned. */ status: "applying" | "compensating"; /** Mutation target item ids extracted from the journal's planned step ids. */ itemIds: string[]; } /** The exact pre-commit transaction plan persisted beside the SDK journal. */ export interface GithubImportPlanRecord { /** Original privacy preflight receipt; missing or failed receipts cannot authorize replay. */ preflight?: ImportGateReceipt; /** Complete source batch used by the original dependency pass. */ dependencyIssues?: readonly GhIssue[]; /** Whether the original caller requested dependency side effects. */ linkDeps?: boolean; /** Absent on released refresh plans; those plans are update-only. */ updateOnly?: boolean; /** Original target mapping, including deterministic targets not yet created. */ itemIds?: readonly (readonly [number, string])[]; /** Stable transaction id the plan belongs to. */ transactionId: string; /** Lowercased repository the transaction planned to refresh. */ repo: string; /** Original complete prepared entries, reused for finalization and reporting. */ entries: readonly PreparedGithubImport[]; /** Original ordered mutation steps; a resumed journal validates them verbatim. */ mutations: readonly BulkItemMutation[]; } /** List pending github-import journals without changing plans or tracker bytes. */ export declare function listUnfinishedGithubImports(pmRoot: string): Promise; /** Discover retained producer plans even when their SDK journals already committed. */ export declare function listRetainedGithubImportPlans(pmRoot: string): Promise; /** Read one persisted plan; only absence returns null, while corrupt bytes require explicit recovery. */ export declare function readGithubImportPlan(pmRoot: string, transactionId: string): Promise; /** Carry a verified first-link decision without letting it override an existing GitHub owner. */ export declare function githubImportTarget(repo: string, entry: PreparedGithubImport, id: string, allowCreate?: boolean): GithubOwnedTarget; /** Commit a complete issue-import batch under one crash-resumable transaction. */ export declare function importGithubAtomic(pmRoot: string, repo: string, entries: readonly PreparedGithubImport[], opts?: AtomicImportOptions): Promise; /** Validate every source-finalization input against its effective native lifecycle before writes. */ export declare function validateGithubImportFidelity(entry: PreparedGithubImport, repo: string, context: string, items?: readonly PmItem[]): void; /** Validate a persisted refresh plan without writing or opening an SDK transaction. */ export declare function validateGithubImportPlan(record: GithubImportPlanRecord, items?: readonly PmItem[]): Map; /** * Resume one interrupted github-import journal by replaying its persisted * original plan. The plan — never a re-derivation from current item state — * supplies the exact ordered mutations and the transaction id, because a * partial apply changes both the derived step set and the history context the * id is fingerprinted from. When the recorded plan cannot be trusted, the * caller fails closed instead of leaving the journal silently unfinished. */ export declare function resumeGithubImport(pmRoot: string, record: GithubImportPlanRecord, opts?: AtomicImportOptions): Promise; /** Typed recovery refusal when the original durable plan cannot be safely replayed. */ export declare class GithubImportRecoveryError extends CommandError { /** Machine-readable conflict category for recovery and upstream ownership guards. */ readonly code: string; /** Retain the recovery category and its concrete correction instruction. */ constructor(code: string, message: string); } export declare function buildIssuesUrl(repo: string, opts: ImportOptions): string; /** Parse, deduplicate, and validate selected issue references before any fetch. */ export declare function parseIssueNumbers(repo: string, input: string): number[]; export declare function composeBody(issue: GhIssue, comments: GhComment[]): string; export declare const IMPORT_LOCK_TTL_MS_DEFAULT: number; /** Default total budget a caller waits to acquire a contended comment-sync lock before giving up and skipping that item's sync. */ export declare const IMPORT_LOCK_WAIT_MS_DEFAULT = 30000; /** * Payload JSON written into a comment-sync lock file. * * Mirrors the pm CLI's own lock payload so the CLI's `pm gc` lock sweep (which * reads `ttl_seconds`) treats these locks exactly like its own. */ export interface ImportLockPayload { /** Lock identity (the lock file's basename without `.lock`). */ id: string; /** OS process id of the holder, used to detect a dead owner. */ pid: number; /** Human-readable holder label (always `pm-github`). */ owner: string; /** Unique per acquisition; release() only unlinks a file carrying it. */ token: string; /** ISO timestamp recorded at acquisition, the staleness age base. */ created_at: string; /** Lock lifetime in seconds, read by `pm gc` to sweep abandoned locks. */ ttl_seconds: number; } export interface ImportLock { /** Absolute path of the held lock file (diagnostics/tests). */ path: string; /** Release the lock. Best-effort, idempotent, never throws. */ release(): void; } export type ImportLockAcquisition = { status: "acquired"; lock: ImportLock; } | { status: "contended"; } | { status: "degraded"; }; /** * Absolute lock file path for one item's comment-sync critical section. * * The item id is sanitized defensively: pm ids are already filename-safe, but * the lock path must never become a directory-traversal vector if that ever * changes. * * @param pmRoot - Workspace root or pm data dir. * @param itemId - The pm item id to serialize. * @returns Absolute path under the data dir's `locks/` directory. */ export declare function importCommentSyncLockPath(pmRoot: string, itemId: string): string; /** * Staleness TTL for a breaker election sidecar, in ms. * * A breaker's critical section is a handful of syscalls (re-stat, re-read, * unlink), so a crashed breaker's sidecar goes stale in seconds, not minutes; * this short window lets a contender clear and re-run a dead election. */ export declare const IMPORT_LOCK_BREAKER_TTL_MS = 10000; /** * Acquire the cross-process comment-sync lock for one item. * * Never throws: every failure mode maps to one of the three acquisition * statuses (`acquired`, `contended`, `degraded`) so the caller decides how to * degrade. `ttlMs`/`waitMs` are injectable so the wait and staleness windows * can be exercised without real timing in tests. * * @param pmRoot - Workspace root or pm data dir passed to {@link resolvePmDataDir}. * @param itemId - The pm item whose comment critical section is serialized. * @param opts - Optional TTL/wait overrides and observation of the candidate before publication. * @returns The acquisition outcome. */ export declare function acquireImportLock(pmRoot: string, itemId: string, opts?: { ttlMs?: number; waitMs?: number; onStaged?: GithubStateWriteOptions["onStaged"]; }): Promise; /** * Matches the hidden HTML-comment marker carrying a synced GitHub comment id. * * HTML comments are invisible in rendered markdown but survive `pm comments` * storage verbatim, so the id embedded in the marker is the stable dedupe key. */ export declare const COMMENT_MARKER_REGEX: RegExp; /** * Build the text for one native pm comment from a GitHub comment. * * Appends the marker so a later re-sync can de-duplicate on the GitHub comment * id (see {@link COMMENT_MARKER_REGEX}). * * @param comment - The GitHub comment to render. * @returns The comment text with the trailing id marker. */ export declare function buildCommentText(comment: GhComment): string; /** * Collect the GitHub comment ids already synced into an item's native comments. * * Scans each stored comment's text for the stable marker. Returns the set of * synced ids (empty when none match, e.g. for hand-written pm comments). * * @param stored - The item's existing native comments (each may carry marker text). * @returns The set of already-synced GitHub comment ids. */ export declare function extractSyncedCommentIds(stored: { text?: string; }[]): Set; /** * Extract the newly-created item id from `pm create --json` stdout. * * The CLI emits a FLAT envelope (`{ "id": "pm-xxxx", … }`) with no `item` * wrapper, so this reads `parsed.id` directly. Returns `undefined` when the * output genuinely cannot be parsed, so callers skip-with-warning instead of * crashing the whole import. * * @param stdout - Raw `pm create --json` output. * @returns The created item id, or `undefined`. */ export declare function parseCreatedItemId(stdout: string): string | undefined; /** * Sync GitHub issue comments into a pm item's native comments collection. * * Idempotent: comments already present (matched by their marker id) are skipped, * so re-running import never duplicates. Each GitHub comment becomes one pm * comment authored by the GitHub login. Failures are reported in the returned * `failed` count and logged, never thrown: a contended or unavailable lock, an * unreadable existing-comment collection, and each refused add all count every * comment that did not land (see {@link acquireImportLock}). Gated callers turn * a non-zero `failed` count into a fail-closed refusal; ungated ones continue. * * @param itemId - The pm item to append comments to. * @param comments - The GitHub comments to sync. * @param pmRoot - Workspace root or pm data dir. * @param issueNumber - The source issue number (for log prefixes). * @returns How many comments were added, skipped as duplicates, and not written. */ export declare function syncGithubCommentsToAnnotations(itemId: string, comments: GhComment[], pmRoot: string, issueNumber: number, ownership?: GithubOwnedTarget): Promise<{ added: number; skipped: number; failed: number; }>; /** * Whether a GitHub issue node is a draft pull request. * * A draft PR is an issue that is BOTH a pull request and flagged `draft: true`; * plain issues are never drafts. * * @param issue - The issue node to test. * @returns True only for draft pull requests. */ export declare function isDraftPr(issue: GhIssue): boolean; /** * Apply the client-side import filters the REST API cannot express. * * Drops pull requests (unless `includePrs`), draft PRs (when `skipDrafts`), and * items whose milestone title does not match (the API keys milestones by number, * not title). Returns the surviving issues in input order. * * @param issues - Fetched issues to narrow. * @param opts - Import options carrying the filter flags. * @returns The filtered issue list. */ export declare function applyClientFilters(issues: GhIssue[], opts: ImportOptions): GhIssue[]; /** * Normalize the raw CLI flag bag into a typed {@link ImportOptions}. * * Resolves the state filter, labels, assignee, milestone, the `--since` window, * PR inclusion, draft skipping, and the comment-fetching mode, throwing a * {@link CommandError} with a usage code on a malformed `--since` or * `--comments-mode`. * * @param options - The raw option object from the command handler. * @returns The normalized import options. */ export declare function parseImportOptions(options: Record): ImportOptions; /** pm dependency kinds a GitHub body reference can map to. */ export type DepRefKind = "blocked_by" | "blocks"; /** One dependency reference parsed out of an issue body. `repo` is lowercased. */ export interface ParsedDepRef { repo: string; number: number; kind: DepRefKind; /** Normalized human phrase that produced this ref ("blocked by" | "depends on" | "blocks"). */ phrase: string; } /** A resolved, workspace-concrete edge ready to apply to the source pm item. */ export interface ResolvedDepEdge { sourceId: string; targetId: string; kind: DepRefKind; /** GitHub issue number of the source item (for the audit message). */ sourceIssue: number; phrase: string; } /** Minimal item-metadata shape the link pass reads (subset of the SDK `ItemMetadata`). */ export interface DepLinkSnapshotItem extends PmItem { id: string; tags: string[]; dependencies?: Array<{ id: string; kind: string; }>; } /** Structured outcome of the `--link-deps` pass, merged into the import result. */ export interface DepLinkResult { linked: number; unresolved: number; orderingCycleWarnings: string[]; failures: string[]; } /** * Parse dependency references from one issue body. Pure. Bare `#N` refs resolve * against `sourceRepo` (lowercased); `owner/repo#N` refs keep their explicit * repo (lowercased). References are de-duplicated within the body by * repo+number+kind so a body repeating a link yields one ref. * * Scanning is linear: each dependency phrase is found once, then references are * consumed one at a time with sticky (`y`) regexes anchored at the exact scan * position. There is no nested quantifier or look-ahead over unbounded input, * so the parser cannot backtrack catastrophically on adversarial bodies. */ export declare function parseDependencyReferences(body: string, sourceRepo: string): ParsedDepRef[]; /** Index only unique ownership; expose ambiguous keys without selecting an arbitrary claimant. */ export declare function buildProvenanceIndexFromMetadata(items: readonly DepLinkSnapshotItem[], ambiguities?: Map, repositories?: readonly string[]): Map; /** * Resolve parsed references into concrete workspace edges. Skips references * whose source or target issue is not present in the workspace (counted as * `unresolved`), self-references, and duplicates. Pure. */ export declare function planDependencyLinks(repo: string, issues: readonly GhIssue[], provenance: ReadonlyMap): { edges: ResolvedDepEdge[]; unresolved: number; }; /** Count candidate references across issues without resolving them (dry-run preview). */ export declare function countDependencyRefCandidates(repo: string, issues: readonly GhIssue[]): number; /** * The `--link-deps` second pass. Snapshots the workspace, resolves body * references to edges, applies them idempotently, then re-snapshots and asks the * SDK which ordering cycles the batch newly introduced. Never throws for an * individual edge; a resolution/SDK failure surfaces through the returned * `failures`/warnings so the import result stays truthful. */ export declare function linkImportedDependencies(repo: string, issues: readonly GhIssue[], pmRoot: string, deps?: ImportRunDependencies): Promise; /** * Render one GitHub issue into the import-ready desired state. * * Computes the title, status, provenance/author tags, description, body (with * optional embedded comments), and the comment list for native sync. Returns * `undefined` for an issue with no usable title so the caller counts it skipped. * * @param issue - The fetched issue to render. * @param repo - `owner/repo`, baked into the provenance tag. * @param opts - Import options governing body/comments. * @param token - GitHub token for the comment fetch. * @param match - The existing pm item linked to this issue, if any (drives update vs create). * @param fetchIssueComments - Injectable comment fetcher (defaults to {@link fetchComments}). * @returns The prepared import entry, or `undefined` when the issue has no title. */ export declare function prepareGithubImport(issue: GhIssue, repo: string, opts: ImportOptions, token: string | undefined, match: PmItem | undefined, fetchIssueComments: ImportRunDependencies["fetchIssueComments"], fidelityContext: { items: PmItem[]; ownership?: GithubOwnershipIndex; releases: ReturnType; timeline: typeof fetchImportTimeline; statuses?: GithubStatusRegistry; }): Promise; /** Recognize a complete source projection without treating the SDK mutation clock as content. */ export declare function importEntryUnchanged(entry: PreparedGithubImport, types?: ReadonlyMap, statuses?: GithubStatusRegistry): boolean; /** Receipts from the gated import's completeness check. */ export interface ImportPlanCompletenessReceipts { /** Number of issues the fetch delivered after filtering. */ readonly fetched: number; /** Number of issues the plan prepares to import or update. */ readonly planned: number; /** Number of issues the plan explicitly skips (e.g. empty titles). */ readonly skipped: number; } /** Receipts from the gated import's idempotency check. */ export interface ImportIdempotencyReceipts { /** Existing untagged items selected by exact prose citation, each with one landing target. */ readonly adopted: number; /** Distinct durable import identity keys in the existing corpus. */ readonly provenance_indexed: number; /** Number of plan entries matched to an existing importer identity. */ readonly matched_by_provenance: number; /** Number of plan entries that will be born new; each must carry its tag. */ readonly new_entries: number; } /** * Verify that a gated import's plan accounts for every fetched issue exactly once. * * An import that silently drops an issue (or plans one twice) would leave the * tracker out of sync with GitHub while reporting success, and the sync PR * would then publish an incomplete state. The check is fail-closed: every * filtered issue number must appear in the prepared entries or the explicit * skip list exactly once, nothing outside the fetched set may appear, and the * counts must reconcile. A violation throws {@link CommandError} before any * mutation happens. * * @param issues - The filtered issues the fetch delivered. * @param prepared - The plan entries built from them. * @param skippedNumbers - Issue numbers the plan explicitly skips. * @returns The reconciled counts on success. */ export declare function verifyImportPlanCompleteness(issues: readonly GhIssue[], prepared: readonly PreparedGithubImport[], skippedNumbers: readonly number[]): ImportPlanCompletenessReceipts; /** * Verify that explicit import identities and planned targets are unique. * * Shared gh: references are unrestricted. Persisted importer claims must still * identify one item, and every new entry must carry its reference for review. * Two planned issues cannot write the same existing local item. * * @param existing - The complete existing pm item corpus. * @param prepared - The plan entries about to be written. * @param repo - The `owner/repo` being imported from. * @returns The provenance idempotency receipts on success. */ export declare function verifyImportIdempotency(existing: readonly PmItem[], prepared: readonly PreparedGithubImport[], repo: string, ownership?: GithubOwnershipIndex): ImportIdempotencyReceipts; /** * Verify the persisted corpus actually contains every issue in the written plan. * * A recovered SDK journal alone is insufficient evidence after local files are * reset or removed. Require unique durable provenance before a caller may push. * * @param existing - Complete post-write item corpus. * @param prepared - Every entry the verified plan required. * @param repo - Source repository whose provenance must be present. * @returns Number of durable issue identities verified. */ export declare function verifyImportedProvenance(existing: PmItem[], prepared: readonly PreparedGithubImport[], repo: string): number; /** Receipt of the fail-closed tracker privacy gate embedded in an import result. */ export interface ImportGateReceipt { /** The gate verdict for the proposed tracker change. */ verdict: GateVerdict; /** Shared redacted evidence, retained only on a failed preflight and never staged. */ diagnostic?: GateReport; /** Number of files whose added lines were scanned. */ scanned_files: number; /** Number of findings that survived the allowlist (0 on pass). */ findings: number; /** Number of reviewed findings suppressed by the content-hash allowlist. */ allowlisted: number; } /** Scan both the content projection and exact SDK write payload with the shared privacy gate. */ export declare function scanGithubImportPreflight(pmRoot: string, entries: readonly PreparedGithubImport[], mutations?: readonly BulkItemMutation[], persisted?: unknown): ImportGateReceipt; /** A saved passing verdict and a fresh passing scan are both required before any replay mutation. */ export declare function assertGithubImportReplayPreflight(pmRoot: string, record: GithubImportPlanRecord): void; /** * Run the full GitHub issue import flow. * * Idempotent: items already linked by explicit provenance to a fetched issue are * UPDATEd; new issues are created. Honors `--atomic` (one crash-resumable * transaction) versus the per-item `pm` mutation path, optional `--link-deps`, * and `--dry-run`. With `--gate` the plan is verified (completeness + provenance * idempotency) BEFORE any mutation, and the proposed tracker change is scanned * by the fail-closed privacy gate AFTER it — a gated failure exits non-zero so * a caller never commits or pushes the change. Returns a structured result and * throws {@link CommandError} (with a semantic exit code) on failure. * * @param repoArg - The `owner/repo` to import from. * @param pmPath - Workspace root or pm data dir. * @param opts - Normalized import options. * @param deps - Injectable collaborators (token resolver, fetchers, etc.) for tests. */ export declare function runImport(repoArg: string | undefined, pmPath: string, opts: ImportOptions, dependencies?: ImportRunDependencies): Promise<{ transactionId: string; recovered: boolean; recoveredItems: number | undefined; imported: number; updated: number; adopted: number; skipped: number; atomic: boolean; replayedOriginalPlan: boolean; commentWriteFailures?: number | undefined; } | { limit?: number | undefined; truncated?: boolean | undefined; missingIssues?: number[] | undefined; dryRun: boolean; wouldImport: number; wouldUpdate: number; wouldAdopt: number; wouldSkip: number; atomic?: boolean | undefined; } | { limit?: number | undefined; truncated?: boolean | undefined; missingIssues?: number[] | undefined; citation_candidates?: (CitationCandidate & { issue: number; })[]; code: string; blocked: boolean; plan: AmbiguousCitationPlan[]; dryRun: boolean; wouldImport: number; wouldUpdate: number; wouldAdopt: number; wouldSkip: number; atomic?: boolean | undefined; } | { limit?: number | undefined; truncated?: boolean | undefined; missingIssues?: number[] | undefined; identity_conflicts?: LegacyGithubIdentityConflict[]; citation_candidates?: (CitationCandidate & { issue: number; })[]; plan?: { issue: number; item: string | undefined; action: string; status: string; github_close_reason: string; created_at: unknown; updated_at_policy: string; closed_at: unknown; close_reason: string; release: string; identity: { via: string; title_conflict?: boolean; conflict?: { local: string; github: string; rule: string; }; } | undefined; citation_candidates?: CitationCandidate[] | undefined; github_url: string; github_number: number; github_state: string; github_state_reason: string; github_created_at: string; github_updated_at: string; github_closed_at: string; github_release: string; }[] | undefined; gate?: { completeness: ImportPlanCompletenessReceipts | undefined; idempotency: ImportIdempotencyReceipts | undefined; scan: string; } | undefined; dryRun: boolean; wouldImport: number; wouldUpdate: number; wouldAdopt: number; wouldSkip: number; atomic: boolean; wouldLinkDependencyCandidates?: number | undefined; } | { limit?: number | undefined; truncated?: boolean | undefined; missingIssues?: number[] | undefined; identity_conflicts?: LegacyGithubIdentityConflict[]; citation_candidates?: (CitationCandidate & { issue: number; })[]; plan?: { issue: number; item: string | undefined; action: string; status: string; github_close_reason: string; created_at: unknown; updated_at_policy: string; closed_at: unknown; close_reason: string; release: string; identity: { via: string; title_conflict?: boolean; conflict?: { local: string; github: string; rule: string; }; } | undefined; citation_candidates?: CitationCandidate[] | undefined; github_url: string; github_number: number; github_state: string; github_state_reason: string; github_created_at: string; github_updated_at: string; github_closed_at: string; github_release: string; }[] | undefined; transactionId: string | undefined; unchanged?: boolean | undefined; recovered: boolean; imported: number; updated: number; adopted: number; recoveredItems?: number | undefined; skipped: number; atomic: boolean; commentWriteFailures?: number | undefined; gate?: ImportGateReceipt | undefined; } | { limit?: number | undefined; truncated?: boolean | undefined; missingIssues?: number[] | undefined; identity_conflicts?: LegacyGithubIdentityConflict[]; citation_candidates?: (CitationCandidate & { issue: number; })[]; plan?: { issue: number; item: string | undefined; action: string; status: string; github_close_reason: string; created_at: unknown; updated_at_policy: string; closed_at: unknown; close_reason: string; release: string; identity: { via: string; title_conflict?: boolean; conflict?: { local: string; github: string; rule: string; }; } | undefined; citation_candidates?: CitationCandidate[] | undefined; github_url: string; github_number: number; github_state: string; github_state_reason: string; github_created_at: string; github_updated_at: string; github_closed_at: string; github_release: string; }[] | undefined; gate?: { completeness: ImportPlanCompletenessReceipts | undefined; idempotency: ImportIdempotencyReceipts | undefined; scan: string; } | undefined; dryRun: boolean; wouldImport: number; wouldUpdate: number; wouldAdopt: number; wouldSkip: number; wouldLinkDependencyCandidates?: number | undefined; } | { limit?: number | undefined; truncated?: boolean | undefined; missingIssues?: number[] | undefined; identity_conflicts?: LegacyGithubIdentityConflict[]; citation_candidates?: (CitationCandidate & { issue: number; })[]; plan?: { issue: number; item: string | undefined; action: string; status: string; github_close_reason: string; created_at: unknown; updated_at_policy: string; closed_at: unknown; close_reason: string; release: string; identity: { via: string; title_conflict?: boolean; conflict?: { local: string; github: string; rule: string; }; } | undefined; citation_candidates?: CitationCandidate[] | undefined; github_url: string; github_number: number; github_state: string; github_state_reason: string; github_created_at: string; github_updated_at: string; github_closed_at: string; github_release: string; }[] | undefined; imported: number; updated: number; adopted: number; skipped: number; commentWriteFailures?: number | undefined; gate?: ImportGateReceipt | undefined; }>; /** * One pm → GitHub issue state-change proposed by {@link planSync}. * * `from`/`to` are GitHub issue states; the executor only PATCHes when GitHub's * live state disagrees with `to`. */ export interface SyncPlanEntry { /** pm item id driving the proposed change. */ id: string; /** GitHub issue number to PATCH. */ number: number; /** Item title, surfaced in progress output. */ title: string; /** GitHub state assumed before the write (the inverse of `to`; re-checked live). */ from: "open" | "closed"; /** Desired GitHub state derived from the pm status. */ to: "open" | "closed"; } /** Legacy option retained for compatibility; tags always remain references. */ export interface UpstreamIdentityOptions { allowReferenceTags?: boolean; corpus?: readonly PmItem[]; } /** Re-resolve current ownership immediately before sending an upstream write. */ export declare function assertCurrentUpstreamTarget(pmRoot: string, repo: string, entry: { id?: string; number?: number; }, options: UpstreamIdentityOptions): void; export declare function planSync(items: PmItem[], repo: string, statuses?: GithubStatusRegistry, options?: UpstreamIdentityOptions): SyncPlanEntry[]; export interface GithubExportPayload { title: string; body: string; labels: string[]; state: "open" | "closed"; } export interface ExportPlanEntry { id?: string; action: "create" | "update"; number?: number; payload: GithubExportPayload; } export declare function buildExportPlan(items: PmItem[], repo: string | undefined, labelMap?: Map, statuses?: GithubStatusRegistry, options?: UpstreamIdentityOptions): ExportPlanEntry[]; export declare function exportWillApply(options: Record): boolean; export interface ExportApplyFailure { id?: string; action: "create" | "update"; number?: number; title: string; error: string; } export interface ExportApplyResult { created: number; updated: number; failed: number; failures: ExportApplyFailure[]; } export type ExportRequestFn = (method: string, url: string, token: string | undefined, payload?: string) => Promise; /** * Apply an already-built export plan to GitHub, one issue at a time. * * Each create/update is isolated: a single failed write (e.g. a 422 for a label * that does not exist on the repo) is recorded and the loop CONTINUES with the * remaining items — it never abandons the rest of the batch. Pure aside from the * injected `requestFn`, so the per-item isolation is directly unit-testable * without real network I/O. */ export declare function applyExportPlan(plan: ExportPlanEntry[], repo: string, token: string | undefined, requestFn: ExportRequestFn, beforeWrite?: (entry: ExportPlanEntry) => void | Promise): Promise; /** * Decide the exit status of a completed `export --apply` batch. * * Per-item continuation is intentional (one bad item never aborts the batch), * but the batch as a whole must still report honestly: a non-empty plan that * wrote NOTHING while recording at least one failure is a total failure, so it * returns a {@link CommandError} to throw; otherwise `undefined` (exit 0). * * @param plan - The plan that was applied. * @param result - What the apply loop actually wrote. * @param repo - Target repo, included in the failure message. * @returns A `CommandError` to throw on total failure, else `undefined`. */ export declare function applyOutcomeError(plan: ExportPlanEntry[], result: ExportApplyResult, repo: string): CommandError | undefined; /** Terminal pm lifecycle statuses: an item in one of these can no longer be blocked. */ export declare const BLOCKER_TERMINAL_STATUSES: ReadonlySet; /** How many blocker references are resolved per GraphQL request. */ export declare const BLOCKER_STATES_BATCH_SIZE = 25; /** The syntactic form a parsed GitHub reference was recognized in. */ export type BlockerReferenceForm = "repo_hash" | "url" | "gh_dash" | "short_repo_hash" | "bare_hash" | "unparsed_url"; /** One GitHub reference found in blocker text, before its repo hint is applied. */ export interface ParsedBlockerReference { /** `owner/repo` (lowercase) when the reference carries it; `undefined` for hint-resolved forms. */ repo?: string; /** Issue or PR number; absent for an unparsed URL. */ number?: number; /** The syntactic form the reference was recognized in. */ form: BlockerReferenceForm; /** The literal matched text (for report provenance). */ raw: string; } /** A deduplicated, hint-resolved GitHub reference. `key` is its stable identity. */ export interface BlockerReference { /** Stable dedupe/lookup key: `owner/repo#N` when resolved, a normalized unresolved reference otherwise. */ key: string; /** `owner/repo` (lowercase); `undefined` when no hint could resolve the reference. */ repo?: string; /** Issue or PR number; absent for an unparsed URL. */ number?: number; /** The syntactic form the reference was recognized in. */ form: BlockerReferenceForm; /** The literal matched text (for report provenance). */ raw: string; } /** Live state of one blocker reference as queried from GitHub (or why it could not be). */ export interface BlockerReferenceState { /** `owner/repo` (lowercase); `undefined` when the reference never resolved to a repo. */ repo?: string; /** Issue or PR number; absent for an unparsed URL. */ number?: number; /** The syntactic form the reference was recognized in. */ form: BlockerReferenceForm; /** The literal matched text (for report provenance). */ raw: string; /** Live state, or the reason it is unknown. */ state: "open" | "closed" | "merged" | "not_found" | "error" | "unresolved" | "unparsed"; /** GitHub close reason for issues (`COMPLETED`, `NOT_PLANNED`, `REOPENED`), when known. */ state_reason?: string; /** ISO timestamp the issue closed, when known. */ closed_at?: string; /** ISO timestamp the pull request merged, when known. */ merged_at?: string; /** Canonical GitHub URL, when known. */ url?: string; /** Failure detail, only for `state === "error"`. */ error?: string; } /** Per-item revalidation outcome. */ export type BlockerVerdict = "cleared" | "partially_cleared" | "still_blocked" | "unresolvable"; /** One revalidated candidate item, as reported. */ export interface BlockerItemReport { /** The pm item id. */ id: string; /** Item status at read time (the status that made it a candidate). */ status: string; /** Revalidation verdict over the item's references. */ verdict: BlockerVerdict; /** Every parsed reference and its live state, sorted deterministically. */ references: BlockerReferenceState[]; } /** The full `pm github blockers` report, returned to the host renderer. */ export interface BlockersReport { /** Fixed marker naming the producing command. */ command: "github blockers"; /** ISO timestamp of the run. */ generated_at: string; /** Items read from the complete corpus (after any `--ids` scoping). */ items_read: number; /** Items revalidated (blocked status, or external GitHub blocked_by dependency). */ candidates: number; /** Per-item reports. */ items: BlockerItemReport[]; /** Items per verdict. */ counts: { cleared: number; partially_cleared: number; still_blocked: number; unresolvable: number; }; /** Non-zero host exit status: 4 alerts, 1 query or annotation failures. */ exit_code?: number; /** Receipt for `--comment`, present only when comments were requested. */ comment?: { requested: true; dry_run: boolean; added: number; skipped: number; failed: number; }; } /** * Parse every GitHub reference in one text source. * * Recognized forms: full issue/PR URLs, `owner/repo#N`, `GH-N`, bare `#N`, and * `name#N` (a repo short name). URL and `owner/repo#N` references carry their * repo; `GH-N`, bare `#N`, and `name#N` do not and are resolved later against * the item's provenance repo or `--repo` (see {@link resolveBlockerReferences}). * Duplicate mentions within one text are not deduplicated here — the resolver * owns the stable identity — but each form's scan is independent, so one text * never yields the same (form, raw, number) twice. * * @param text - One blocker text source (blocked_reason, description, comment, …). * @returns Every URL (including unparsed candidates), then owner/repo, GH-N, short and bare forms. */ export declare function parseBlockerReferences(text: string): ParsedBlockerReference[]; /** * Resolve hint-dependent references and deduplicate the result. * * `GH-N`, bare `#N`, and `name#N` references resolve against the first * applicable hint — the item's own `gh:owner/repo#N` provenance repo, then * `--repo`. A `name#N` short form resolves only when the name matches the * hint's repo segment (so `pm-cli#854` resolves against `unbraind/pm-cli`, but * `other#854` stays unresolved instead of guessing an owner). References that * resolve to the same `owner/repo#N` collapse to the first-seen form. * * @param parsed - References from {@link parseBlockerReferences}. * @param itemRepo - The item's provenance repo hint (`owner/repo`), when it has one. * @param fallbackRepo - The `--repo` hint, when given. * @returns Deduplicated references, sorted by repo then number for a deterministic report. */ export declare function resolveBlockerReferences(parsed: readonly ParsedBlockerReference[], itemRepo: string | undefined, fallbackRepo: string | undefined): BlockerReference[]; /** * Collect and resolve every GitHub reference named by one item's blocker text. * * Sources scanned, in order: external `blocked_by` dependency targets, the * item-level `blocked_by` field, `blocked_reason`, `description`, and every * stored comment. A `blocked_reason` is a static string that nothing re-reads — * that is exactly the staleness this command exists to surface — so comments * (including the latest ones) are scanned too. Only authoritative import identity * is excluded as self; shareable reference tags never hide a blocker. * * @param item - One complete item from {@link decodeBlockerPmItems}. * @param fallbackRepo - The `--repo` hint, when given. * @returns Deduplicated resolved references for the item. */ export declare function collectBlockerReferences(item: BlockerPmItem, fallbackRepo: string | undefined, peers?: readonly PmItem[]): BlockerReference[]; /** * Select the items `pm github blockers` revalidates. * * Every item whose status is `blocked`, plus every non-terminal item carrying a * `blocked_by` dependency (or `blocked_by` field) whose target is an explicit * external reference — the tracker's own cross-system locator classification * plus an explicit GitHub locator or URL decides what counts as * a GitHub target, so a foreign tracker or local `blocked_by` edge to another pm item never selects the * item here. Terminal items are excluded: a closed item cannot be blocked. * * @param items - The complete runtime-validated item corpus. * @returns The candidate items, in corpus order. */ export declare function selectBlockerCandidates(items: readonly BlockerPmItem[], statuses?: GithubStatusRegistry): BlockerPmItem[]; /** One `pm list --all` dependency row, as consumed by blocker revalidation. */ export interface BlockerPmDependency { /** Dependency target: a local item id or an external locator string. */ id: string; /** Dependency kind, e.g. `blocked_by`, `blocks`, `parent`. */ kind: string; } /** One `pm list --all` comment row, as consumed by blocker revalidation. */ export interface BlockerPmComment { /** The comment text. */ text: string; } /** A complete pm item plus the blocker fields the complete list output carries. */ export interface BlockerPmItem extends PmItem { /** Stable item id (required: the complete reader refuses id-less rows). */ id: string; /** Item title at read time (validated by the complete reader). */ title: string; /** Lifecycle status at read time (validated by the complete reader). */ status: string; /** Short summary shown in listings (validated by the complete reader). */ description: string; /** The static blocked-reason text, when the item carries one. */ blockedReason?: string; /** The item-level `blocked_by` field (an item id, external locator, or reason text). */ blockedBy?: string; /** Dependency rows (id + kind only; dates and authors are not consumed). */ dependencies: BlockerPmDependency[]; /** Stored comment texts, oldest first. */ comments: BlockerPmComment[]; } /** * Decode the complete `pm list --all` envelope into blocker-revalidation items. * * The envelope and every base field are validated by {@link decodeCompletePmItems} * first (the same complete-read contract import uses), then the extra rows this * command consumes — `blocked_reason`, `blocked_by`, dependency rows, and * comment texts — are validated on top. A wrong-type extra fails closed with * the same refusal wording, because blocker revalidation reading a partial or * untrustworthy corpus would silently miss items. * * @param parsed - JSON decoded from the installed pm CLI. * @returns Fresh runtime-validated blocker items. * @throws {@link CommandError} When a receipt, count, identity, or consumed row * field is absent, incomplete, or contradictory. */ export declare function decodeBlockerPmItems(parsed: unknown): BlockerPmItem[]; /** * Read every item through the complete SDK path and check its completeness certificate. * * The SDK disables extensions for the observational read. The shared item * decoder also validates every blocker field consumed by this command. * * @param pmRoot - Workspace or tracker root accepted by the SDK. * @returns The complete runtime-validated blocker item corpus. * @throws On unreadable, incomplete, omitted, or invalid tracker data. */ export declare function readBlockerPmItems(pmRoot: string): Promise; /** Issue node fields selected by the blocker states query. */ interface GraphqlBlockerIssue { state?: string; stateReason?: string | null; closedAt?: string | null; url?: string; } /** Pull-request node fields selected by the blocker states query. */ interface GraphqlBlockerPullRequest { state?: string; mergedAt?: string | null; closedAt?: string | null; url?: string; } /** Response of one blocker states query: alias `rN` → aliased issue/PR nodes (or null for an inaccessible repo). */ type GraphqlBlockerStatesData = Record | null>; /** One reference's aliases inside a blocker states query, for reading its response back. */ export interface BlockerStatesQueryPlanEntry { /** The reference the aliases answer. */ ref: ResolvedBlockerReference; /** Alias of the reference's `repository(…)` block. */ repoAlias: string; /** Alias of the reference's `issue(number:…)` field. */ issueAlias: string; /** Alias of the reference's `pullRequest(number:…)` field. */ pullAlias: string; } /** The query plus the alias map needed to read its response back. */ export interface BlockerStatesQueryPlan { /** The literal GraphQL document to send. */ query: string; /** Repos in alias order: `repos[i]` answers under alias `r${i}`. */ repos: string[]; /** Per-reference aliases, aligned with the document's fields. */ entries: BlockerStatesQueryPlanEntry[]; } /** A reference whose repo hint resolved — the only kind GraphQL can query. */ export interface ResolvedBlockerReference { /** Stable dedupe/lookup key: `owner/repo#N`. */ key: string; /** `owner/repo` (lowercase). */ repo: string; /** Issue or pull-request number. */ number: number; /** The syntactic form the reference was recognized in. */ form: BlockerReferenceForm; /** The literal matched text (for report provenance). */ raw: string; } /** * Build the batched GraphQL document resolving many references' live state. * * One query aliases each distinct repo (`r0: repository(owner:…, name:…)`), and * within it each reference twice (`iN: issue(number:…)` plus `pN: * pullRequest(number:…)`) — a number is either an issue or a PR and GraphQL * resolves the wrong one to null, so one round-trip classifies every reference * without guessing its kind. Repos are deduplicated and sorted, and each repo's * references are sorted by number, so the document is a pure function of the * reference SET, keeping recorded fixtures stable. The returned entries carry * every reference's aliases so the response can be read back without * re-deriving that ordering. * * @param refs - One batch's resolved references. * @returns The query, its repo alias order, and the per-reference alias entries. */ export declare function buildBlockerStatesQueryPlan(refs: readonly ResolvedBlockerReference[]): BlockerStatesQueryPlan; /** * Split references into fixed-size batches. * * @param refs - References to batch. * @param size - Maximum references per batch (at least 1). * @returns Consecutive slices of the input, in order. */ export declare function chunkBlockerReferences(refs: readonly ResolvedBlockerReference[], size: number): ResolvedBlockerReference[][]; /** Injectable GraphQL transport for the blocker states query (token closed over). */ export type BlockerGraphQLTransport = (query: string) => Promise>; /** * Query the live state of every resolved reference, batched. * * References are batched ({@link BLOCKER_STATES_BATCH_SIZE} per request) through * the shared client, auth, and rate-limit handling. A batch whose transport * fails (no usable data — e.g. an invalid token or a total GraphQL error) marks * every reference in it `error` and the run continues, so one inaccessible repo * cannot blind the report on the others. * * @param refs - Every resolved reference across all items. * @param transport - GraphQL transport (the production one closes over the token). * @returns Live state by {@link BlockerReference.key}. */ export declare function fetchBlockerReferenceStates(refs: readonly ResolvedBlockerReference[], transport: BlockerGraphQLTransport): Promise>; /** * The revalidation verdict over one item's reference states. * * `cleared` requires every reference closed or merged; a partially cleared item * (some blocker closed, some still open or unreadable) is reported as such * rather than cleared, because an unreadable reference can always be open. An * item with no references at all — a blocked_reason naming no GitHub reference — * is `unresolvable`: its static text can never be revalidated automatically. * * @param states - The item's reference states. * @returns The item's verdict. */ export declare function blockerItemVerdict(states: readonly BlockerReferenceState[]): BlockerVerdict; /** Marker a blockers comment carries so re-runs can skip it (`pm-github:blockers:…`). */ export declare const BLOCKERS_COMMENT_MARKER_REGEX: RegExp; /** * Build the idempotency marker for one cleared blocker reference. * * Identity is the reference PLUS its observed state (repo, number, closed or * merged, and the exact timestamp): if the blocker later reopens and closes * again, the changed timestamp makes the marker a new one and a fresh comment * is appended, while an unchanged state never repeats. * * @param repo - The blocker's `owner/repo`. * @param number - The blocker's number. * @param disposition - `closed` or `merged`. * @param at - The close/merge ISO timestamp. * @returns The marker string embedded in the comment. */ export declare function blockerCommentMarker(repo: string, number: number, disposition: "closed" | "merged", at: string): string; /** * Build the comment appended for one cleared blocker reference. * * Human text first (what the blocker was and when it closed, then the ask — * revalidate), marker last, mirroring the GitHub comment sync's layout so stored * comments stay scannable and machine-skippable. * * @param state - The cleared reference's live state. * @returns The comment text. */ export declare function buildBlockerClearedComment(state: BlockerReferenceState): string; /** * Collect the blocker markers already present in an item's comments. * * Mirrors {@link extractSyncedCommentIds}: each stored comment's text is scanned * for the marker; hand-written comments simply contribute nothing. * * @param stored - The item's existing native comments. * @returns The set of marker strings already present. */ export declare function extractBlockerCommentMarkers(stored: { text?: string; }[]): Set; /** * Build the GitHub Search-API URL for issues in one repo matching a free-text query. * * Restricted to `type:issue repo:` so a search never leaks across repos. * * @param repo - The `owner/repo` to search within. * @param query - Free-text query string. * @returns The encoded search URL. */ export declare function buildSearchUrl(repo: string, query: string): string; /** * Map GitHub search result numbers to local pm-item hits. * * For every returned issue number, looks up the pm item carrying the matching * `gh:repo#N` provenance tag; only locally-present items become hits (the * runtime would drop the rest anyway). Score preserves GitHub's ranking, * normalized into `(0, 1]` so hits clear pm's default threshold. * * @param matchedNumbers - Issue numbers GitHub returned, best-first. * @param repo - The repo the search ran against. * @param itemsByProvenance - Local items keyed `owner/repo#N`. * @returns One hit per locally-present matching item. */ export declare function mapSearchHits(matchedNumbers: number[], repo: string, itemsByProvenance: Map): Array<{ id: string; score: number; matched_fields: string[]; }>; /** * Resolve the search target repo for the GitHub search provider. * * An explicit option wins, then the `PM_GITHUB_REPO` env var so a workspace can * pin its upstream. Returns `undefined` when neither yields an `owner/repo`. * * @param options - The raw option object from the search context. * @returns The resolved `owner/repo`, or `undefined`. */ export declare function resolveSearchRepo(options: Record): string | undefined; /** * Structured result of `pm github validate`. * * Reports the resolved token source, whether the `gh` CLI is installed, the * current rate-limit snapshot, and (when a repo is given) its reachability. * `ok` is the overall pass/fail; `messages` carries the human-readable detail. */ export interface ValidateReport { /** Overall pass/fail for the validation. */ ok: boolean; /** Whether the `gh` CLI was found on PATH. */ gh_cli: boolean; /** Whether any GitHub token was resolvable. */ token: boolean; /** Where the token came from: `env`, `gh`, or `none`. */ token_source: "env" | "gh" | "none"; /** The repo examined, when one was supplied. */ repo?: string; /** Whether the repo responded 2xx. */ repo_accessible?: boolean; /** Raw HTTP status the repo check returned. */ repo_status?: number; /** Remaining requests in the current rate-limit window. */ rate_limit_remaining?: number; /** Total requests permitted per window. */ rate_limit_limit?: number; /** Epoch seconds at which the window resets. */ rate_limit_reset?: number; /** Whether the remaining quota is at/under the low-water mark. */ rate_limit_low?: boolean; /** Human-readable diagnostic lines. */ messages: string[]; } interface GraphQLResponse { data?: T | null; errors?: Array<{ message: string; type?: string; path?: Array; }>; } /** One project-summary node in a `projectsV2` connection. */ interface GraphqlProjectsV2Node { number: number; title?: string; url?: string; closed?: boolean; shortDescription?: string | null; } /** A `projectsV2` connection (user or organization), as returned by the listing * query. */ interface GraphqlProjectsV2Connection { pageInfo?: { hasNextPage?: boolean; endCursor?: string; }; nodes?: Array; } /** Response shape of the `listOwnerProjectsV2Nodes` query — one of * user/organization resolves, the other is null. */ interface GraphqlListOwnerProjectsData { user?: { projectsV2?: GraphqlProjectsV2Connection | null; } | null; organization?: { projectsV2?: GraphqlProjectsV2Connection | null; } | null; } /** Shared GraphQL client retaining partial errors for reference-level classification. */ export declare function githubGraphQLResponse(token: string | undefined, query: string, variables: Record): Promise>; /** * Resolve the GraphQL node id of a repo's issue or PR by number. * * @param repo - `owner/repo` to look up in. * @param number - The issue/PR number. * @param token - GitHub token. * @returns The node id, or `undefined` when not found or the repo ref is malformed. */ export declare function gqlResolveIssueNodeId(repo: string, number: number, token: string | undefined): Promise; /** * One page of a `projectsV2` connection as returned by GitHub GraphQL. * * Carries the page's nodes and the cursor threading needed to fetch the rest. */ export interface ProjectsV2Page { /** Project-summary nodes on this page (null entries are redacted/inaccessible). */ nodes?: Array; /** Relay pagination info for the next page. */ pageInfo?: { hasNextPage?: boolean; endCursor?: string; }; } export declare function collectProjectsV2Pages(fetchPage: (cursor: string | undefined) => Promise): Promise; export type GraphQLTransport = (query: string, variables: Record) => Promise; /** * Resolve and paginate the `projectsV2` connection for a user-or-org owner. * * A login is either a user or an organization, never both; querying both in one * request resolves the owner type without an extra round-trip, then this keeps * paginating the connection that actually exists so owners with more than 100 * projects are fully listed instead of silently truncated. * * @param owner - The user or org login. * @param graphQL - Injectable transport (query + variables → data), for tests. * @returns Every project-summary node for the owner. */ export declare function listOwnerProjectsV2Nodes(owner: string, graphQL: GraphQLTransport): Promise; /** * Push one pm item's status onto its board item. * * Tolerates a missing target option (writes the item but skips the Status set). * Returns whether a real change was made and an optional error string so the * caller can continue the batch per-item. * * @param entry - The push-plan entry to execute. * @param meta - The board metadata (id, Status field). * @param ref - The board reference (for the provenance tag). * @param pmById - Local pm items keyed by id (for body lookup and tagging). * @param pmRoot - Workspace root for the `pm` tag write. * @param token - GitHub token for the GraphQL calls. * @returns Whether the item changed, plus an optional error message. */ export declare function applyPushEntry(entry: ReturnType["entries"][number], meta: ProjectMeta, ref: ProjectRef, pmById: Map, pmRoot: string, token: string | undefined, projectItems: ProjectItem[]): Promise<{ changed: boolean; error?: string; }>; /** * Build the `pm` CLI argv that applies one pull (project → pm) status transition. * * Pure so the pm lifecycle contract is unit-testable without spawning `pm`: * `closed` goes through `pm close`; `canceled` keeps its distinct terminal state * via `pm update --status canceled` with `--close-reason`; everything else is a * plain `pm update --status`. See the long note above for the pm CLI contracts. * * @param entry - The pull-plan entry to render argv for. * @param pmRoot - Workspace root for the `pm` invocation. * @returns The argv array. */ export declare function buildPullEntryArgs(entry: PullPlanEntryLike, pmRoot: string, statuses?: GithubStatusRegistry): string[]; interface PullPlanEntryLike { itemId: string; pmId: string; title: string; fromStatus: string; toStatus: string; } /** * Report whether a github subcommand will mutate GitHub. * * Feeds the host CLI's "mutating command" guard, accounting for the `--dry-run` * and `--apply` overrides that turn an otherwise-mutating command into a preview. * * @param command - The subcommand string (e.g. `github sync`). * @param options - The raw option object from the command handler. * @returns True when the command will perform real GitHub writes. */ export declare function isMutatingGithubCommand(command: string, options: Record): boolean; declare const _default: { name: string; version: string; activate(api: ExtensionApi): void; }; export default _default; //# sourceMappingURL=index.d.ts.map