issue-flow 0.11.1 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{analyze-XV3K25K3.js → analyze-OEET7KGE.js} +15 -10
- package/dist/{analyze-XV3K25K3.js.map → analyze-OEET7KGE.js.map} +1 -1
- package/dist/{apply-WUJHDD7A.js → apply-ZIA3C52S.js} +6 -4
- package/dist/{apply-WUJHDD7A.js.map → apply-ZIA3C52S.js.map} +1 -1
- package/dist/{chunk-6N7LZZ5U.js → chunk-3QHK4YQA.js} +204 -107
- package/dist/chunk-3QHK4YQA.js.map +1 -0
- package/dist/chunk-42PJFMAR.js +605 -0
- package/dist/chunk-42PJFMAR.js.map +1 -0
- package/dist/{chunk-EWDJENFW.js → chunk-4JSOYE4G.js} +77 -12
- package/dist/chunk-4JSOYE4G.js.map +1 -0
- package/dist/chunk-56KS3TFQ.js +703 -0
- package/dist/chunk-56KS3TFQ.js.map +1 -0
- package/dist/{chunk-AAY6KM7N.js → chunk-73ATPIYX.js} +160 -154
- package/dist/chunk-73ATPIYX.js.map +1 -0
- package/dist/{chunk-KQ4JQN7T.js → chunk-A4SLHOW7.js} +68 -12
- package/dist/chunk-A4SLHOW7.js.map +1 -0
- package/dist/chunk-BAUPQXPE.js +173 -0
- package/dist/chunk-BAUPQXPE.js.map +1 -0
- package/dist/{chunk-HC2MT7BX.js → chunk-BYZDPR7N.js} +14 -581
- package/dist/chunk-BYZDPR7N.js.map +1 -0
- package/dist/chunk-CD5ULRVC.js +615 -0
- package/dist/chunk-CD5ULRVC.js.map +1 -0
- package/dist/chunk-DIDUVL6O.js +1365 -0
- package/dist/chunk-DIDUVL6O.js.map +1 -0
- package/dist/{chunk-47VIN33V.js → chunk-EZATO3DW.js} +7 -5
- package/dist/{chunk-47VIN33V.js.map → chunk-EZATO3DW.js.map} +1 -1
- package/dist/{chunk-BXCPXRBR.js → chunk-FADTCQGM.js} +46 -11
- package/dist/chunk-FADTCQGM.js.map +1 -0
- package/dist/{chunk-GANSDJV7.js → chunk-FJP3UQGD.js} +15 -13
- package/dist/chunk-FJP3UQGD.js.map +1 -0
- package/dist/chunk-KMMASOA6.js +134 -0
- package/dist/chunk-KMMASOA6.js.map +1 -0
- package/dist/{chunk-HQYXVIH6.js → chunk-LAFNLLQP.js} +3 -3
- package/dist/chunk-LWRSMTTZ.js +18 -0
- package/dist/chunk-LWRSMTTZ.js.map +1 -0
- package/dist/{chunk-IVHZEYAX.js → chunk-M5UCXTIT.js} +13 -11
- package/dist/{chunk-IVHZEYAX.js.map → chunk-M5UCXTIT.js.map} +1 -1
- package/dist/chunk-M66SJHQQ.js +206 -0
- package/dist/chunk-M66SJHQQ.js.map +1 -0
- package/dist/{chunk-OBLVLIUS.js → chunk-MJULIKQU.js} +42 -6
- package/dist/chunk-MJULIKQU.js.map +1 -0
- package/dist/{chunk-RKTEV6EG.js → chunk-NS6R37II.js} +4 -4
- package/dist/{run-DBF2VWUN.js → chunk-NTMMF5UD.js} +515 -544
- package/dist/chunk-NTMMF5UD.js.map +1 -0
- package/dist/{chunk-EY6WMHV2.js → chunk-QCPGHBSZ.js} +14 -12
- package/dist/{chunk-EY6WMHV2.js.map → chunk-QCPGHBSZ.js.map} +1 -1
- package/dist/{chunk-LVKQ2AKT.js → chunk-TSOLWK7Y.js} +8 -6
- package/dist/chunk-TSOLWK7Y.js.map +1 -0
- package/dist/{chunk-34WNTK3K.js → chunk-XQUSIEKA.js} +11 -9
- package/dist/{chunk-34WNTK3K.js.map → chunk-XQUSIEKA.js.map} +1 -1
- package/dist/chunk-Y5ZDJ4PJ.js +76 -0
- package/dist/chunk-Y5ZDJ4PJ.js.map +1 -0
- package/dist/cli.js +156 -26
- package/dist/cli.js.map +1 -1
- package/dist/{config-4THHOXNN.js → config-PRJGWW7J.js} +15 -3
- package/dist/execute-XBNVL753.js +18 -0
- package/dist/{generate-TBVTLMOP.js → generate-EGB4KV2B.js} +16 -10
- package/dist/{generate-TBVTLMOP.js.map → generate-EGB4KV2B.js.map} +1 -1
- package/dist/init-AJHCXJBP.js +10 -0
- package/dist/operations-BYT626KQ.js +365 -0
- package/dist/operations-BYT626KQ.js.map +1 -0
- package/dist/plan-QOZ3RIO6.js +21 -0
- package/dist/{policy-XQW5NUIE.js → policy-6S4GFC76.js} +6 -4
- package/dist/{policy-XQW5NUIE.js.map → policy-6S4GFC76.js.map} +1 -1
- package/dist/pr-EBBHD2ZX.js +26 -0
- package/dist/pr-review-VVMW5PO4.js +20 -0
- package/dist/prd-JQSZF7PR.js +21 -0
- package/dist/resume-PPCNQVVV.js +221 -0
- package/dist/resume-PPCNQVVV.js.map +1 -0
- package/dist/review-3F6MARWH.js +19 -0
- package/dist/run-RXE5GDQO.js +36 -0
- package/dist/run-RXE5GDQO.js.map +1 -0
- package/dist/state-manager-2EDVDBAR.js +34 -0
- package/dist/state-manager-2EDVDBAR.js.map +1 -0
- package/dist/{web-ANQQTTRD.js → web-EF5WIIGG.js} +13 -8
- package/dist/{web-ANQQTTRD.js.map → web-EF5WIIGG.js.map} +1 -1
- package/package.json +1 -1
- package/prompts/pr.md +11 -4
- package/web/public/app.js +12 -0
- package/dist/chunk-3BOHTH4V.js +0 -58
- package/dist/chunk-3BOHTH4V.js.map +0 -1
- package/dist/chunk-6N7LZZ5U.js.map +0 -1
- package/dist/chunk-AAY6KM7N.js.map +0 -1
- package/dist/chunk-BXCPXRBR.js.map +0 -1
- package/dist/chunk-EWDJENFW.js.map +0 -1
- package/dist/chunk-GANSDJV7.js.map +0 -1
- package/dist/chunk-HC2MT7BX.js.map +0 -1
- package/dist/chunk-HDV3YDTG.js +0 -52
- package/dist/chunk-HDV3YDTG.js.map +0 -1
- package/dist/chunk-KQ4JQN7T.js.map +0 -1
- package/dist/chunk-LVKQ2AKT.js.map +0 -1
- package/dist/chunk-OBLVLIUS.js.map +0 -1
- package/dist/chunk-VQ5VN7DF.js +0 -1018
- package/dist/chunk-VQ5VN7DF.js.map +0 -1
- package/dist/execute-5OEKLM5X.js +0 -15
- package/dist/init-PRMOTQ7N.js +0 -9
- package/dist/plan-Y2BYZD24.js +0 -17
- package/dist/pr-H6GLOSXF.js +0 -21
- package/dist/pr-review-CK5FR6WX.js +0 -17
- package/dist/prd-4PWLCGH5.js +0 -17
- package/dist/review-QGVAHEZF.js +0 -15
- package/dist/run-DBF2VWUN.js.map +0 -1
- /package/dist/{chunk-HQYXVIH6.js.map → chunk-LAFNLLQP.js.map} +0 -0
- /package/dist/{chunk-RKTEV6EG.js.map → chunk-NS6R37II.js.map} +0 -0
- /package/dist/{config-4THHOXNN.js.map → config-PRJGWW7J.js.map} +0 -0
- /package/dist/{execute-5OEKLM5X.js.map → execute-XBNVL753.js.map} +0 -0
- /package/dist/{init-PRMOTQ7N.js.map → init-AJHCXJBP.js.map} +0 -0
- /package/dist/{plan-Y2BYZD24.js.map → plan-QOZ3RIO6.js.map} +0 -0
- /package/dist/{pr-H6GLOSXF.js.map → pr-EBBHD2ZX.js.map} +0 -0
- /package/dist/{pr-review-CK5FR6WX.js.map → pr-review-VVMW5PO4.js.map} +0 -0
- /package/dist/{prd-4PWLCGH5.js.map → prd-JQSZF7PR.js.map} +0 -0
- /package/dist/{review-QGVAHEZF.js.map → review-3F6MARWH.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/journal.ts","../src/core/pipeline.ts","../src/execution/plan.ts","../src/issues/graph.ts","../src/execution/order.ts"],"sourcesContent":["import { appendFile, mkdir, rename, stat, unlink } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport {\n createInitialSnapshot,\n MemoryPublisher,\n type MemoryPublisherOptions,\n reduceSessionEvent,\n type SessionEvent,\n type SessionPublisher,\n type SessionReducerOptions,\n type SessionSnapshot,\n} from './session-state.js';\n\n/**\n * Append-only journal of `SessionEvent`s.\n *\n * `session.json` is a *projection*: the reducer folds every event into one\n * snapshot and the events themselves are discarded. That is the right shape for\n * a dashboard and the wrong one for an audit — after a six-hour run, \"what\n * happened at 3am\" has no answer, because the retries, the failures and their\n * order were consumed to produce a single final state.\n *\n * This publisher writes the events instead of the state: one JSON line each, in\n * order, with a monotonic `seq`. It sits **beside** `FilePublisher`, never in\n * its place. The snapshot stays the projection; the journal is the history, and\n * replaying it through `reduceSessionEvent` reproduces the snapshot — which is\n * the property `replayJournal()` and its test exist to keep true.\n *\n * The invariant of `session-state.ts` holds here unchanged: `publish()` is\n * synchronous, never throws, and every I/O failure is swallowed after a single\n * warning. Monitoring never affects the pipeline.\n */\n\n/** One line of `events.jsonl`. */\nexport interface JournalEntry {\n /** 1-based, monotonic within a file *and* across a rotation. */\n seq: number;\n event: SessionEvent;\n}\n\n/** Default ceiling before the journal rotates. */\nexport const DEFAULT_JOURNAL_MAX_BYTES = 10 * 1024 * 1024;\n\nexport interface JournalPublisherOptions extends MemoryPublisherOptions {\n /**\n * Rotate once the file would grow past this. Default 10 MB. `0` disables\n * rotation, which is what a caller that manages its own retention wants.\n */\n maxFileBytes?: number;\n}\n\n/**\n * Publisher that appends every event to `events.jsonl`.\n *\n * Writes are serialized on a promise chain — the same discipline as\n * `FilePublisher` — so lines never interleave and the order on disk is the\n * order of `publish()`. Nothing is throttled: dropping or coalescing events is\n * exactly what the snapshot already does, and the point of the journal is that\n * it does not.\n */\nexport class JournalPublisher extends MemoryPublisher {\n private readonly filePath: string;\n private readonly rotatedPath: string;\n private readonly maxFileBytes: number;\n private seq = 0;\n private writeChain: Promise<void> = Promise.resolve();\n private closed = false;\n /** Bytes in the current file. `null` until the first write measures it. */\n private bytes: number | null = null;\n\n constructor(filePath: string, rotatedPath: string, options: JournalPublisherOptions = {}) {\n super(options);\n this.filePath = filePath;\n this.rotatedPath = rotatedPath;\n this.maxFileBytes = options.maxFileBytes ?? DEFAULT_JOURNAL_MAX_BYTES;\n }\n\n protected override afterPublish(event: SessionEvent): void {\n if (this.closed) return;\n this.seq++;\n const line = `${JSON.stringify({ seq: this.seq, event } satisfies JournalEntry)}\\n`;\n this.enqueue(line);\n }\n\n private enqueue(line: string): void {\n this.writeChain = this.writeChain.then(async () => {\n try {\n await this.appendLine(line);\n } catch (err) {\n this.warnOnce(err);\n }\n });\n }\n\n private async appendLine(line: string): Promise<void> {\n const size = Buffer.byteLength(line);\n\n if (this.bytes === null) {\n await mkdir(dirname(this.filePath), { recursive: true });\n this.bytes = await currentSize(this.filePath);\n }\n\n // Rotate *before* the write that would cross the ceiling, so a line is\n // never split across two files: an entry that cannot be parsed whole is\n // worse than a file slightly under its limit.\n if (this.maxFileBytes > 0 && this.bytes > 0 && this.bytes + size > this.maxFileBytes) {\n await this.rotate();\n }\n\n await appendFile(this.filePath, line, 'utf-8');\n this.bytes += size;\n }\n\n /**\n * Keep exactly one previous generation.\n *\n * Deliberately not a numbered cascade: two files bound the disk cost at\n * `2 * maxFileBytes`, and a run long enough to fill 10 MB twice has already\n * put everything a human would look for in the current file. A caller that\n * needs full retention sets `maxFileBytes: 0` and rotates on its own terms.\n */\n private async rotate(): Promise<void> {\n try {\n await unlink(this.rotatedPath);\n } catch {\n // No previous generation. Nothing to remove.\n }\n await rename(this.filePath, this.rotatedPath);\n this.bytes = 0;\n }\n\n override async flush(): Promise<void> {\n await this.writeChain;\n }\n\n override async close(): Promise<void> {\n await this.flush();\n this.closed = true;\n }\n}\n\n/** Size of `path` in bytes, or `0` when it does not exist yet. */\nasync function currentSize(path: string): Promise<number> {\n try {\n return (await stat(path)).size;\n } catch {\n return 0;\n }\n}\n\n/**\n * Parse the lines of a journal, skipping what cannot be read.\n *\n * A journal is appended to by a live process and read by another, so the last\n * line may well be a partial write. Tolerating it — and any line a newer\n * release wrote in a shape this one does not know — is what makes the file\n * usable at all; the alternative is a reader that throws on a healthy run.\n */\nexport function parseJournal(content: string): JournalEntry[] {\n const entries: JournalEntry[] = [];\n\n for (const line of content.split('\\n')) {\n const trimmed = line.trim();\n if (trimmed === '') continue;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n continue;\n }\n\n if (!isEntry(parsed)) continue;\n entries.push(parsed);\n }\n\n return entries;\n}\n\nfunction isEntry(value: unknown): value is JournalEntry {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as { seq?: unknown; event?: unknown };\n if (typeof candidate.seq !== 'number') return false;\n const event = candidate.event;\n return (\n typeof event === 'object' && event !== null && typeof (event as SessionEvent).type === 'string'\n );\n}\n\n/**\n * Rebuild the snapshot from a journal.\n *\n * This is the reproducibility contract of the file: the same reducer that\n * produced `session.json` live, run over the events in the order they were\n * written, must land on the same state. A journal that cannot do that is a log,\n * not a journal.\n */\nexport function replayJournal(\n content: string,\n options: SessionReducerOptions = {},\n): SessionSnapshot {\n let snapshot = createInitialSnapshot();\n for (const entry of parseJournal(content)) {\n snapshot = reduceSessionEvent(snapshot, entry.event, options);\n }\n return snapshot;\n}\n\n/**\n * Fan one event stream out to several publishers.\n *\n * The journal sits **beside** the snapshot writer, so something has to hold\n * both. It is the composite rather than the journal that does it, because the\n * relationship is symmetric: neither surface owns the other, and dropping\n * either one has to leave the remaining one untouched.\n *\n * `snapshot()` and `version()` answer from the first member, which is the\n * primary surface. A member that fails has already swallowed its own error —\n * that is the contract of every publisher here — so the loop needs no guard of\n * its own beyond `publish()` never throwing.\n */\nexport class MultiPublisher implements SessionPublisher {\n private readonly members: readonly SessionPublisher[];\n private readonly primary: SessionPublisher;\n\n constructor(members: readonly SessionPublisher[]) {\n if (members.length === 0) {\n throw new Error('MultiPublisher needs at least one member');\n }\n this.members = members;\n this.primary = members[0] as SessionPublisher;\n }\n\n publish(event: SessionEvent): void {\n for (const member of this.members) {\n member.publish(event);\n }\n }\n\n snapshot(): SessionSnapshot {\n return this.primary.snapshot();\n }\n\n version(): number {\n return this.primary.version();\n }\n\n async flush(): Promise<void> {\n await Promise.all(this.members.map((member) => member.flush()));\n }\n\n async close(): Promise<void> {\n await Promise.all(this.members.map((member) => member.close()));\n }\n}\n","import type { PipelineState, TaskPlan } from '../types.js';\nimport { loadTaskPlan, saveTaskPlan } from './state-manager.js';\n\n/**\n * Ordered pipeline phases. Each phase must complete before the next can start.\n *\n * `pr-review` is deliberately NOT here: it is opt-in via `--pr-review`. Adding\n * it to the default set would make every existing `tasks.json` (which has no\n * `prReviewCompleted`) look unfinished, so `getNextPhase()` would resume into a\n * phase the user never asked for.\n */\nexport const PIPELINE_PHASES = ['init', 'prd', 'plan', 'execute', 'review', 'pr'] as const;\n\n/**\n * The default set plus the opt-in `pr-review` phase, used when the user passes\n * `--pr-review` (or the flag was persisted in `plan.prReview.enabled`).\n */\nexport const PIPELINE_PHASES_WITH_PR_REVIEW = [...PIPELINE_PHASES, 'pr-review'] as const;\n\nexport type PipelinePhase = (typeof PIPELINE_PHASES_WITH_PR_REVIEW)[number];\n\n/**\n * Pipeline phases excluding the 'pr' phase, for --no-branch mode.\n * `pr-review` is excluded too: without a branch there is no PR to review.\n */\nexport const PIPELINE_PHASES_NO_BRANCH = PIPELINE_PHASES.filter(\n (p): p is Exclude<PipelinePhase, 'pr' | 'pr-review'> => p !== 'pr',\n);\n\n/**\n * Map pipeline phases to their corresponding PipelineState field.\n * 'init' has no persisted state — it's a runtime-only check.\n */\nconst PHASE_TO_FIELD: Record<PipelinePhase, keyof PipelineState | null> = {\n init: null,\n prd: 'prdCompleted',\n plan: 'jsonCompleted',\n execute: 'executionCompleted',\n review: 'reviewCompleted',\n pr: 'prCreated',\n 'pr-review': 'prReviewCompleted',\n};\n\nexport class PipelineManager {\n private tasksJsonPath: string;\n private plan: TaskPlan;\n private activePhases: readonly PipelinePhase[];\n\n constructor(plan: TaskPlan, tasksJsonPath: string, activePhases?: readonly PipelinePhase[]) {\n this.plan = plan;\n this.tasksJsonPath = tasksJsonPath;\n this.activePhases = activePhases ?? PIPELINE_PHASES;\n }\n\n /**\n * Reload state from disk.\n */\n async reload(): Promise<void> {\n this.plan = await loadTaskPlan(this.tasksJsonPath);\n }\n\n /**\n * Check if a phase is complete.\n */\n isPhaseComplete(phase: PipelinePhase): boolean {\n const field = PHASE_TO_FIELD[phase];\n if (field === null) return true; // init is always \"complete\" after running\n return this.plan.pipeline?.[field] ?? false;\n }\n\n /**\n * Get the first incomplete phase in the pipeline.\n * Returns null if all phases are complete.\n */\n getNextPhase(): PipelinePhase | null {\n for (const phase of this.activePhases) {\n if (!this.isPhaseComplete(phase)) {\n return phase;\n }\n }\n return null;\n }\n\n /**\n * Get the current phase (alias for getNextPhase).\n */\n getCurrentPhase(): PipelinePhase | null {\n return this.getNextPhase();\n }\n\n /**\n * Check whether we can resume from a specific phase.\n * All prerequisite phases must be complete.\n */\n canResume(fromPhase: PipelinePhase): boolean {\n const idx = this.activePhases.indexOf(fromPhase);\n if (idx < 0) return false;\n\n // All active phases before fromPhase must be complete\n for (let i = 0; i < idx; i++) {\n if (!this.isPhaseComplete(this.activePhases[i])) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Mark a phase as complete and persist to disk.\n */\n async markPhaseComplete(phase: PipelinePhase): Promise<void> {\n const field = PHASE_TO_FIELD[phase];\n if (field === null) return; // init has no persisted state\n\n this.plan = {\n ...this.plan,\n pipeline: {\n ...(this.plan.pipeline ?? {\n prdCompleted: false,\n jsonCompleted: false,\n executionCompleted: false,\n reviewCompleted: false,\n prCreated: false,\n }),\n [field]: true,\n },\n };\n\n await saveTaskPlan(this.tasksJsonPath, this.plan);\n }\n}\n","import { mkdir, readFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { ZodError } from 'zod';\nimport { isoNow } from '../core/state-manager.js';\nimport type { DependencyGraph } from '../issues/graph.js';\nimport type { Issue } from '../issues/types.js';\nimport { executionPlanSchema } from '../storage/schemas.js';\nimport type { LastError, PullRequestRef } from '../types.js';\nimport { writeFileAtomic } from '../utils/fs.js';\nimport { priorityOf } from './order.js';\nimport type {\n ExecutionPlan,\n ExecutionPlanExcluded,\n ExecutionPlanIssue,\n QueueIssueStatus,\n QueueStatus,\n} from './types.js';\n\n/**\n * Building, reading, writing and advancing the execution plan of a queue.\n *\n * The plan is the only state a multi-issue run adds to the storage tree, and it\n * is written **only** for a queue with more than one Issue — a single-issue run\n * leaves the layout exactly as it was.\n */\n\nexport interface BuildExecutionPlanInput {\n /** Project id of the global storage tree. */\n projectId: string;\n /** Identifiers the user asked for, in order; the first one names the queue. */\n requested: readonly string[];\n graph: DependencyGraph;\n /** Ids to run, already ordered by `computeExecutionOrder`. */\n order: readonly string[];\n noBranch?: boolean;\n prReview?: boolean;\n /** Injectable clock, so tests can assert `createdAt` vs `updatedAt`. */\n now?: () => string;\n}\n\n/** Title/url/number of a node, falling back to what the id alone tells us. */\nfunction describeIssue(\n issue: Issue | null,\n id: string,\n): {\n number: number | null;\n title: string;\n url: string | null;\n source: string;\n} {\n const parsed = Number.parseInt(id, 10);\n return {\n number: issue?.number ?? (Number.isNaN(parsed) ? null : parsed),\n title: issue?.title ?? '',\n url: issue?.remoteRef ?? null,\n source: issue?.source ?? 'github',\n };\n}\n\n/**\n * Turn a graph plus an order into the persisted plan.\n *\n * Every Issue of the graph that is *not* in the order becomes an `excluded`\n * entry: the consolidated Pull Request reports them as known pending work, so a\n * hierarchy the user chose to trim never disappears silently.\n */\nexport function buildExecutionPlan(input: BuildExecutionPlanInput): ExecutionPlan {\n const now = input.now ?? isoNow;\n const at = now();\n const scheduled = new Set(input.order);\n const requested = new Set(input.requested);\n\n const issues: ExecutionPlanIssue[] = input.order.map((id, index) => {\n const node = input.graph.nodes.get(id);\n const relations = node?.relations;\n const described = describeIssue(node?.issue ?? null, id);\n\n return {\n id,\n number: described.number,\n title: described.title,\n url: described.url,\n source: described.source,\n position: index + 1,\n status: 'pending',\n origin: requested.has(id) ? 'requested' : 'discovered',\n // Only the constraints that survive inside the queue: a blocker left out\n // of it is reported in `excluded`, not enforced as a dependency.\n dependsOn: (relations?.blockedBy ?? []).filter((blocker) => scheduled.has(blocker)),\n parent: relations?.parent ?? null,\n priority: priorityOf(node?.issue?.labels ?? []),\n heuristic: (relations?.heuristic.length ?? 0) > 0,\n failedPhase: null,\n lastError: null,\n attempts: 0,\n blockedReason: null,\n startedAt: null,\n completedAt: null,\n };\n });\n\n const excluded: ExecutionPlanExcluded[] = [];\n for (const node of input.graph.nodes.values()) {\n if (scheduled.has(node.id)) continue;\n const described = describeIssue(node.issue, node.id);\n excluded.push({\n id: node.id,\n number: described.number,\n title: described.title,\n url: described.url,\n reason: 'Discovered in the hierarchy but not selected for this run',\n });\n }\n\n return {\n schemaVersion: 1,\n id: input.requested[0] ?? (input.order[0] as string),\n project: input.projectId,\n requested: [...input.requested],\n branchName: null,\n noBranch: input.noBranch ?? false,\n prReview: input.prReview ?? false,\n status: 'pending',\n createdAt: at,\n updatedAt: at,\n truncated: input.graph.truncated,\n issues,\n excluded,\n };\n}\n\n/** Read a persisted plan. Throws with the offending fields on invalid content. */\nexport async function loadExecutionPlan(path: string): Promise<ExecutionPlan> {\n const raw: unknown = JSON.parse(await readFile(path, 'utf-8'));\n\n try {\n return executionPlanSchema.parse(raw) as ExecutionPlan;\n } catch (err) {\n if (err instanceof ZodError) {\n const issues = err.issues.map((i) => ` - ${i.path.join('.')}: ${i.message}`).join('\\n');\n throw new Error(`Invalid execution-plan.json at ${path}:\\n${issues}`);\n }\n throw err;\n }\n}\n\n/**\n * Persist a plan atomically, creating the queue directory on first write.\n *\n * `updatedAt` is stamped here so no call site can forget it — the file is the\n * only record of how far a queue got, and a stale timestamp on it is worse than\n * none.\n */\nexport async function saveExecutionPlan(\n path: string,\n plan: ExecutionPlan,\n now: () => string = isoNow,\n): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const stamped: ExecutionPlan = { ...plan, updatedAt: now() };\n await writeFileAtomic(path, `${JSON.stringify(stamped, null, 2)}\\n`);\n}\n\n/**\n * The Issue the queue should work on next, or `null` when every one of them is\n * completed.\n *\n * The order of the lookups *is* the resume policy: an interrupted issue\n * (`in_progress`) and a failed one are retried before the queue moves on, and\n * each of them picks up from its own `tasks.json` (phase-level resume) rather\n * than from the start. A `completed` issue is never revisited — that is the\n * whole point of persisting the queue.\n */\nexport interface NextQueueIssueOptions {\n /**\n * Ids this invocation is done with, however they ended. A queue that skips a\n * failing Issue and comes back to it needs a way to say \"not this one again\",\n * or \"come back later\" becomes \"come back forever\".\n */\n exclude?: ReadonlySet<string>;\n}\n\n/**\n * Whether every dependency this Issue declares *inside the queue* is finished.\n *\n * The execution order already places dependencies first, so this only bites\n * once an entry stops being `completed` — skipped, blocked or failed. Handing\n * out an Issue whose blocker was skipped is how a queue produces work that\n * cannot compile.\n */\nfunction dependenciesSatisfied(plan: ExecutionPlan, entry: ExecutionPlanIssue): boolean {\n return entry.dependsOn.every((id) => {\n const dependency = plan.issues.find((candidate) => candidate.id === id);\n return dependency === undefined || dependency.status === 'completed';\n });\n}\n\n/**\n * The Issue to work on next.\n *\n * The order of the four lookups is the resumption policy:\n * an interrupted Issue first (it was mid-flight), then one that failed on a\n * previous invocation, then the untouched ones, and only at the end the ones\n * this queue deliberately set aside — which is what \"go on with the\n * independent work and come back to it\" means in one line.\n *\n * `blocked` is absent on purpose: it needs a human, and no ordering of the\n * queue changes that.\n */\nexport function nextQueueIssue(\n plan: ExecutionPlan,\n options: NextQueueIssueOptions = {},\n): ExecutionPlanIssue | null {\n const exclude = options.exclude ?? new Set<string>();\n const eligible = (status: QueueIssueStatus) => (entry: ExecutionPlanIssue) =>\n entry.status === status && !exclude.has(entry.id) && dependenciesSatisfied(plan, entry);\n\n return (\n plan.issues.find(eligible('in_progress')) ??\n plan.issues.find(eligible('failed')) ??\n plan.issues.find(eligible('pending')) ??\n plan.issues.find(eligible('skipped')) ??\n null\n );\n}\n\n/**\n * Status of the queue derived from its entries.\n *\n * `skipped` is *not* terminal — the queue means to come back to it — so a queue\n * holding one is still `in_progress`. `blocked` is: nothing the queue can do\n * moves it, so a queue that ends with one ends `failed`, which is what a person\n * needs to see.\n */\nexport function queueStatus(plan: ExecutionPlan): QueueStatus {\n if (plan.issues.some((entry) => entry.status === 'failed' || entry.status === 'blocked')) {\n return 'failed';\n }\n if (plan.issues.every((entry) => entry.status === 'completed')) return 'completed';\n if (plan.issues.some((entry) => entry.status !== 'pending')) return 'in_progress';\n return 'pending';\n}\n\n/** Whether every Issue of the queue has been resolved. */\nexport function isQueueComplete(plan: ExecutionPlan): boolean {\n return plan.issues.every((entry) => entry.status === 'completed');\n}\n\n/** Apply `patch` to one entry and recompute the queue status. Pure. */\nfunction updateIssue(\n plan: ExecutionPlan,\n id: string,\n patch: Partial<ExecutionPlanIssue>,\n): ExecutionPlan {\n const issues = plan.issues.map((entry) => (entry.id === id ? { ...entry, ...patch } : entry));\n const next: ExecutionPlan = { ...plan, issues };\n return { ...next, status: queueStatus(next) };\n}\n\nexport function markQueueIssueInProgress(\n plan: ExecutionPlan,\n id: string,\n now: () => string = isoNow,\n): ExecutionPlan {\n const current = plan.issues.find((entry) => entry.id === id);\n return updateIssue(plan, id, {\n status: 'in_progress',\n // Preserved across a resume: the queue reports when the work on this Issue\n // really began, not when it was last picked up.\n startedAt: current?.startedAt ?? now(),\n failedPhase: null,\n lastError: null,\n });\n}\n\nexport function markQueueIssueCompleted(\n plan: ExecutionPlan,\n id: string,\n now: () => string = isoNow,\n): ExecutionPlan {\n return updateIssue(plan, id, {\n status: 'completed',\n completedAt: now(),\n failedPhase: null,\n lastError: null,\n });\n}\n\nexport function markQueueIssueFailed(\n plan: ExecutionPlan,\n id: string,\n failure: { phase: string | null; error: LastError | null },\n): ExecutionPlan {\n const current = plan.issues.find((entry) => entry.id === id);\n return updateIssue(plan, id, {\n status: 'failed',\n failedPhase: failure.phase,\n lastError: failure.error,\n attempts: (current?.attempts ?? 0) + 1,\n });\n}\n\n/**\n * Set an Issue aside and come back to it later.\n *\n * The difference from `failed` is the whole point of `--on-issue-failure skip`:\n * a failure that stopped this attempt is not a verdict on the eleven other\n * Issues in the queue, and `skipped` is the status that says \"not now\" rather\n * than \"not at all\". `attempts` is incremented here because the counter is what\n * keeps \"come back later\" from becoming \"come back forever\".\n */\nexport function markQueueIssueSkipped(\n plan: ExecutionPlan,\n id: string,\n failure: { phase: string | null; error: LastError | null },\n): ExecutionPlan {\n const current = plan.issues.find((entry) => entry.id === id);\n return updateIssue(plan, id, {\n status: 'skipped',\n failedPhase: failure.phase,\n lastError: failure.error,\n attempts: (current?.attempts ?? 0) + 1,\n });\n}\n\n/**\n * Stop working on an Issue until a person looks at it.\n *\n * `blocked` is never handed back out by `nextQueueIssue`: waiting cannot fix\n * a missing credential or a repository mid-rebase, and a queue that could\n * unblock itself would spin on the same cause forever.\n */\nexport function markQueueIssueBlocked(\n plan: ExecutionPlan,\n id: string,\n reason: string,\n failure: { phase: string | null; error: LastError | null },\n): ExecutionPlan {\n const current = plan.issues.find((entry) => entry.id === id);\n return updateIssue(plan, id, {\n status: 'blocked',\n blockedReason: reason,\n failedPhase: failure.phase,\n lastError: failure.error,\n attempts: (current?.attempts ?? 0) + 1,\n });\n}\n\n/** Record the branch every Issue of the queue shares. */\nexport function setQueueBranch(plan: ExecutionPlan, branchName: string): ExecutionPlan {\n return { ...plan, branchName };\n}\n\n/** Record the single Pull Request that consolidated the queue. */\nexport function setQueuePullRequest(\n plan: ExecutionPlan,\n pullRequest: PullRequestRef,\n): ExecutionPlan {\n return { ...plan, pullRequest };\n}\n","import { emptyRelations, uniqueIds } from './relations.js';\nimport type { Issue, IssueRelations } from './types.js';\n\n/**\n * Dependency graph of a set of Issues, built by walking the relations every\n * provider exposes through `fetchRelations`.\n *\n * The traversal is deliberately *structural*: it follows hierarchy\n * (parent/children) and dependencies (blockedBy/blocking) and stops there. Plain\n * mentions are recorded on each node but never expanded — a body citing \"see\n * also #12\" would otherwise drag an unrelated Issue into an execution plan the\n * user is about to confirm.\n */\n\nexport interface DependencyGraphNode {\n id: string;\n relations: IssueRelations;\n /** Distance from the closest root, in traversal hops. */\n depth: number;\n /** The Issue itself, when the caller supplied a way to read it. */\n issue: Issue | null;\n /** True when the node was requested by the user rather than discovered. */\n root: boolean;\n}\n\nexport interface DependencyGraph {\n /** Ids the traversal started from, in the order they were requested. */\n roots: string[];\n /** Every discovered node, keyed by id, in discovery order. */\n nodes: Map<string, DependencyGraphNode>;\n /**\n * Dependency cycles found among the discovered nodes, each listed once,\n * starting at its smallest member. Reported rather than thrown: discovery\n * must still answer, and it is the ordering layer that refuses to run.\n */\n cycles: string[][];\n /** True when a limit stopped the traversal before it was exhausted. */\n truncated: boolean;\n limits: { maxNodes: number; maxDepth: number };\n}\n\n/**\n * Conservative defaults: a real hierarchy is a handful of Issues, and each node\n * costs several API calls. A malformed (or simply huge) graph must not turn a\n * `run` into a rate-limit incident.\n */\nexport const DEFAULT_MAX_NODES = 25;\nexport const DEFAULT_MAX_DEPTH = 3;\n\nexport interface BuildDependencyGraphOptions {\n maxNodes?: number;\n maxDepth?: number;\n /** Issues the caller already resolved, so the traversal does not re-read them. */\n known?: Iterable<Issue>;\n /** Reader for the Issues the traversal discovers. Optional. */\n fetchIssue?: (id: string) => Promise<Issue | null>;\n /** Warning sink for a source that failed. Silent by default. */\n warn?: (message: string) => void;\n}\n\n/** Edge `from` → `to`, meaning \"`from` must be resolved before `to`\". */\nexport interface DependencyEdge {\n from: string;\n to: string;\n}\n\n/**\n * Ordering constraints of a graph: only hierarchy-free, explicit dependencies.\n *\n * `blockedBy`/`blocking` are the two spellings of the same fact, so both are\n * normalized into a single direction here. Parent/child is **not** a constraint\n * — it is a presentation and tie-breaking concern (see `computeExecutionOrder`),\n * because a parent is usually an umbrella that neither blocks nor is blocked by\n * its children.\n *\n * Edges pointing outside the graph are dropped: an Issue the traversal never\n * reached cannot be scheduled, so a constraint against it is unenforceable.\n */\nexport function dependencyEdges(graph: DependencyGraph): DependencyEdge[] {\n const edges: DependencyEdge[] = [];\n const seen = new Set<string>();\n\n const add = (from: string, to: string): void => {\n if (from === to || !graph.nodes.has(from) || !graph.nodes.has(to)) return;\n const key = `${from}->${to}`;\n if (seen.has(key)) return;\n seen.add(key);\n edges.push({ from, to });\n };\n\n for (const node of graph.nodes.values()) {\n for (const blocker of node.relations.blockedBy) {\n add(blocker, node.id);\n }\n for (const blocked of node.relations.blocking) {\n add(node.id, blocked);\n }\n }\n\n return edges;\n}\n\n/** Every cycle of the dependency edges, each reported once. */\nexport function findCycles(graph: DependencyGraph): string[][] {\n const adjacency = new Map<string, string[]>();\n for (const { from, to } of dependencyEdges(graph)) {\n const list = adjacency.get(from);\n if (list === undefined) {\n adjacency.set(from, [to]);\n } else {\n list.push(to);\n }\n }\n\n const cycles: string[][] = [];\n const reported = new Set<string>();\n const state = new Map<string, 'visiting' | 'done'>();\n const stack: string[] = [];\n\n const record = (cycle: string[]): void => {\n // Rotate to the smallest member so the same cycle found from two entry\n // points is reported once.\n let pivot = 0;\n for (let i = 1; i < cycle.length; i++) {\n if (compareIds(cycle[i] as string, cycle[pivot] as string) < 0) pivot = i;\n }\n const normalized = [...cycle.slice(pivot), ...cycle.slice(0, pivot)];\n const key = normalized.join('->');\n if (reported.has(key)) return;\n reported.add(key);\n cycles.push(normalized);\n };\n\n const visit = (id: string): void => {\n state.set(id, 'visiting');\n stack.push(id);\n\n for (const next of adjacency.get(id) ?? []) {\n const status = state.get(next);\n if (status === 'visiting') {\n record(stack.slice(stack.indexOf(next)));\n continue;\n }\n if (status === undefined) {\n visit(next);\n }\n }\n\n stack.pop();\n state.set(id, 'done');\n };\n\n for (const id of graph.nodes.keys()) {\n if (!state.has(id)) visit(id);\n }\n\n return cycles;\n}\n\n/** Numeric when both ids are numbers, lexicographic otherwise. */\nexport function compareIds(a: string, b: string): number {\n const na = Number(a);\n const nb = Number(b);\n if (Number.isInteger(na) && Number.isInteger(nb)) {\n return na - nb;\n }\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** Ids a node links to structurally, in traversal order. */\nfunction neighbours(relations: IssueRelations): string[] {\n return uniqueIds(\n [\n ...(relations.parent === null ? [] : [relations.parent]),\n ...relations.children,\n ...relations.blockedBy,\n ...relations.blocking,\n ],\n relations.id,\n );\n}\n\n/**\n * Walk the relations of `roots` breadth-first and return the whole structure.\n *\n * Failures never abort the walk: a node whose relations cannot be read enters\n * the graph with empty relations (and a warning), exactly like an Issue that\n * genuinely relates to nothing. That keeps a partially unavailable API from\n * costing the user the Issues that *were* discovered.\n *\n * Breadth-first is what makes `depth` meaningful under a limit: when the walk is\n * truncated, what is missing is the far edge of the graph, not a random subset.\n */\nexport async function buildDependencyGraph(\n roots: readonly string[],\n fetchRelations: (id: string) => Promise<IssueRelations | null>,\n options: BuildDependencyGraphOptions = {},\n): Promise<DependencyGraph> {\n const maxNodes = options.maxNodes ?? DEFAULT_MAX_NODES;\n const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;\n const warn = options.warn ?? ((): void => {});\n\n const known = new Map<string, Issue>();\n for (const issue of options.known ?? []) {\n known.set(issue.id, issue);\n }\n\n const rootIds = uniqueIds(roots);\n const nodes = new Map<string, DependencyGraphNode>();\n const queued = new Set<string>(rootIds);\n let truncated = false;\n\n let frontier: { id: string; depth: number }[] = rootIds.map((id) => ({ id, depth: 0 }));\n\n while (frontier.length > 0) {\n const next: { id: string; depth: number }[] = [];\n\n for (const { id, depth } of frontier) {\n if (nodes.size >= maxNodes) {\n truncated = true;\n break;\n }\n\n let relations: IssueRelations | null = null;\n try {\n relations = await fetchRelations(id);\n } catch (err) {\n warn(\n `Could not read the relations of issue '${id}': ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n\n let issue = known.get(id) ?? null;\n if (issue === null && options.fetchIssue !== undefined) {\n try {\n issue = await options.fetchIssue(id);\n } catch (err) {\n warn(`Could not read issue '${id}': ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n const resolved = relations ?? emptyRelations(id);\n nodes.set(id, { id, relations: resolved, depth, issue, root: rootIds.includes(id) });\n\n if (depth >= maxDepth) {\n // Only a node that actually has unexplored neighbours truncates the\n // graph; a leaf at max depth explored everything there was.\n if (neighbours(resolved).some((neighbour) => !queued.has(neighbour))) {\n truncated = true;\n }\n continue;\n }\n\n for (const neighbour of neighbours(resolved)) {\n if (queued.has(neighbour)) continue;\n queued.add(neighbour);\n next.push({ id: neighbour, depth: depth + 1 });\n }\n }\n\n if (nodes.size >= maxNodes && next.length > 0) {\n truncated = true;\n break;\n }\n frontier = next;\n }\n\n const graph: DependencyGraph = {\n roots: rootIds,\n nodes,\n cycles: [],\n truncated,\n limits: { maxNodes, maxDepth },\n };\n\n linkReferencedBy(graph);\n graph.cycles = findCycles(graph);\n\n return graph;\n}\n\n/**\n * Complete `referencedBy` with the inverse of `references` among the discovered\n * nodes.\n *\n * The origin only reports the citations it can see (GitHub's timeline covers\n * cross-references but not, for instance, a mention added by the textual\n * heuristic); inverting what the graph already holds costs no API call and\n * keeps the two directions consistent inside it.\n */\nfunction linkReferencedBy(graph: DependencyGraph): void {\n for (const node of graph.nodes.values()) {\n for (const cited of node.relations.references) {\n const target = graph.nodes.get(cited);\n if (target === undefined || target.id === node.id) continue;\n target.relations.referencedBy = uniqueIds(\n [...target.relations.referencedBy, node.id],\n target.id,\n );\n }\n }\n}\n","import { compareIds, type DependencyGraph, dependencyEdges, findCycles } from '../issues/graph.js';\nimport type { IssuePriority } from './types.js';\n\n/**\n * Turning a dependency graph into the order the queue runs in.\n *\n * The criteria are applied in the exact precedence the initiative specifies:\n *\n * 1. **dependencies and blocks** — hard constraints; an Issue never starts\n * before something it depends on has finished. This is the topological part\n * and the only one that can make the computation fail (a cycle);\n * 2. **hierarchy** — with two Issues both ready to run, the ancestor goes\n * first, so an umbrella Issue frames the work of its sub-issues;\n * 3. **priority** — the GitHub labels `high`, `medium` and `low`;\n * 4. **logical order** — the identifier, numerically when it is a number.\n *\n * Everything below the first item is a *tie-break among Issues that are already\n * free to run*, never a constraint: a `high` Issue that depends on a `low` one\n * still runs second, which is the whole point of the feature.\n */\n\nconst PRIORITY_LABELS: Record<string, IssuePriority> = {\n high: 'high',\n medium: 'medium',\n low: 'low',\n};\n\n/** Ranking of a priority; an Issue with no label sorts after every labelled one. */\nconst PRIORITY_RANK: Record<IssuePriority, number> = { high: 0, medium: 1, low: 2 };\nconst NO_PRIORITY_RANK = 3;\n\n/**\n * Priority carried by a label set, or `null` when there is none.\n *\n * Both the bare labels used by this repository (`high`) and the qualified\n * spellings other projects use (`priority: high`, `priority/high`, `P-high`)\n * are accepted; anything else is simply not a priority. The absence of a label\n * is never an error — most Issues have none.\n */\nexport function priorityOf(labels: readonly string[]): IssuePriority | null {\n for (const label of labels) {\n const normalized = label.trim().toLowerCase();\n const direct = PRIORITY_LABELS[normalized];\n if (direct !== undefined) return direct;\n\n const qualified = /^(?:priority|prio|p)\\s*[:/-]\\s*(high|medium|low)$/.exec(normalized);\n const matched = qualified?.[1];\n if (matched !== undefined) return PRIORITY_LABELS[matched] as IssuePriority;\n }\n return null;\n}\n\nexport interface ExecutionOrderOptions {\n /**\n * Subset of the graph to schedule. Defaults to every node — the \"run the\n * whole hierarchy\" answer; the \"only the ones I asked for\" answer passes the\n * requested ids.\n */\n include?: readonly string[];\n}\n\nexport type ExecutionOrderResult =\n | { ok: true; order: string[] }\n | { ok: false; cycles: string[][] };\n\n/** Number of ancestors of `id` inside the selection: 0 for a top-level Issue. */\nfunction hierarchyDepth(\n id: string,\n parentOf: Map<string, string | null>,\n selected: Set<string>,\n): number {\n let depth = 0;\n let current = parentOf.get(id) ?? null;\n const seen = new Set<string>([id]);\n\n while (current !== null && selected.has(current) && !seen.has(current)) {\n depth++;\n seen.add(current);\n current = parentOf.get(current) ?? null;\n }\n\n return depth;\n}\n\n/**\n * Order the selected Issues of a graph.\n *\n * Kahn's algorithm with a deterministic tie-break, so the same graph always\n * produces the same order — a plan the user confirmed must not reshuffle itself\n * on the next run.\n *\n * A cycle is reported, never worked around: an arbitrary order would silently\n * implement an Issue before its dependency, which is exactly the failure this\n * whole feature exists to prevent. Constraints pointing outside the selection\n * are dropped — an Issue that is not going to run cannot block anything.\n */\nexport function computeExecutionOrder(\n graph: DependencyGraph,\n options: ExecutionOrderOptions = {},\n): ExecutionOrderResult {\n const selected = new Set(\n (options.include ?? [...graph.nodes.keys()]).filter((id) => graph.nodes.has(id)),\n );\n\n const parentOf = new Map<string, string | null>();\n const priority = new Map<string, IssuePriority | null>();\n for (const id of selected) {\n const node = graph.nodes.get(id);\n parentOf.set(id, node?.relations.parent ?? null);\n priority.set(id, priorityOf(node?.issue?.labels ?? []));\n }\n\n const incoming = new Map<string, Set<string>>();\n const outgoing = new Map<string, string[]>();\n for (const id of selected) {\n incoming.set(id, new Set());\n outgoing.set(id, []);\n }\n for (const { from, to } of dependencyEdges(graph)) {\n if (!selected.has(from) || !selected.has(to) || from === to) continue;\n incoming.get(to)?.add(from);\n outgoing.get(from)?.push(to);\n }\n\n const depth = new Map<string, number>();\n for (const id of selected) {\n depth.set(id, hierarchyDepth(id, parentOf, selected));\n }\n\n const rank = (id: string): number => {\n const value = priority.get(id) ?? null;\n return value === null ? NO_PRIORITY_RANK : PRIORITY_RANK[value];\n };\n\n const better = (a: string, b: string): number => {\n const byHierarchy = (depth.get(a) ?? 0) - (depth.get(b) ?? 0);\n if (byHierarchy !== 0) return byHierarchy;\n const byPriority = rank(a) - rank(b);\n if (byPriority !== 0) return byPriority;\n return compareIds(a, b);\n };\n\n const ready = [...selected].filter((id) => (incoming.get(id)?.size ?? 0) === 0);\n const order: string[] = [];\n\n while (ready.length > 0) {\n ready.sort(better);\n const next = ready.shift() as string;\n order.push(next);\n\n for (const dependent of outgoing.get(next) ?? []) {\n const pending = incoming.get(dependent);\n if (pending === undefined) continue;\n pending.delete(next);\n if (pending.size === 0) {\n ready.push(dependent);\n }\n }\n }\n\n if (order.length !== selected.size) {\n // Prefer the cycles the graph already recorded; recompute only if the\n // selection is what closed the loop.\n const cycles = graph.cycles.length > 0 ? graph.cycles : findCycles(graph);\n const relevant = cycles.filter((cycle) => cycle.every((id) => selected.has(id)));\n return { ok: false, cycles: relevant.length > 0 ? relevant : cycles };\n }\n\n return { ok: true, order };\n}\n\n/** One-line description of the cycles, for an error message. */\nexport function describeCycles(cycles: readonly string[][]): string {\n return cycles.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AAA,IAC3B,QAAQ;AAAA,IACR,aAAa,QAAQ;AAAA,IACrB,WAAW,QAAQ;AAAA,IACnB,WAAW,SAAS,YAAY,KAAK;AAAA,EACvC,CAAC;AACH;AASO,SAAS,sBACd,MACA,IACA,QACA,SACe;AACf,QAAM,UAAU,KAAK,OAAO,KAAK,CAAC,UAAU,MAAM,OAAO,EAAE;AAC3D,SAAO,YAAY,MAAM,IAAI;AAAA,IAC3B,QAAQ;AAAA,IACR,eAAe;AAAA,IACf,aAAa,QAAQ;AAAA,IACrB,WAAW,QAAQ;AAAA,IACnB,WAAW,SAAS,YAAY,KAAK;AAAA,EACvC,CAAC;AACH;AAGO,SAAS,eAAe,MAAqB,YAAmC;AACrF,SAAO,EAAE,GAAG,MAAM,WAAW;AAC/B;AAGO,SAAS,oBACd,MACA,aACe;AACf,SAAO,EAAE,GAAG,MAAM,YAAY;AAChC;","names":["mkdir","dirname","mkdir","dirname"]}
|
|
@@ -1,19 +1,36 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
|
+
emptyRelations,
|
|
4
|
+
mergeRelations,
|
|
5
|
+
parseTextualRelations,
|
|
6
|
+
uniqueIds
|
|
7
|
+
} from "./chunk-KMMASOA6.js";
|
|
8
|
+
import {
|
|
9
|
+
getActiveResilienceConfig,
|
|
10
|
+
loadIssuesConfig
|
|
11
|
+
} from "./chunk-42PJFMAR.js";
|
|
12
|
+
import {
|
|
13
|
+
ClassifiedError,
|
|
14
|
+
actionOf,
|
|
15
|
+
classify,
|
|
16
|
+
failureOf,
|
|
3
17
|
getProjectRoot,
|
|
4
|
-
|
|
18
|
+
requiresHumanAction,
|
|
5
19
|
resolveIssuePaths,
|
|
20
|
+
resolvePolicy,
|
|
6
21
|
resolveProjectPaths,
|
|
7
22
|
run
|
|
8
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-DIDUVL6O.js";
|
|
9
24
|
import {
|
|
10
|
-
isoNow,
|
|
11
|
-
issueMetadataSchema,
|
|
12
25
|
printError,
|
|
13
26
|
printInfo,
|
|
14
|
-
printWarning
|
|
27
|
+
printWarning
|
|
28
|
+
} from "./chunk-BYZDPR7N.js";
|
|
29
|
+
import {
|
|
30
|
+
isoNow,
|
|
31
|
+
issueMetadataSchema,
|
|
15
32
|
writeFileAtomic
|
|
16
|
-
} from "./chunk-
|
|
33
|
+
} from "./chunk-CD5ULRVC.js";
|
|
17
34
|
|
|
18
35
|
// src/issues/registry.ts
|
|
19
36
|
var providers = /* @__PURE__ */ new Map();
|
|
@@ -47,134 +64,32 @@ function hashIssueContent(title, body) {
|
|
|
47
64
|
return `sha256:${digest}`;
|
|
48
65
|
}
|
|
49
66
|
|
|
50
|
-
// src/issues/relations.ts
|
|
51
|
-
function emptyRelations(id) {
|
|
52
|
-
return {
|
|
53
|
-
id,
|
|
54
|
-
parent: null,
|
|
55
|
-
children: [],
|
|
56
|
-
blockedBy: [],
|
|
57
|
-
blocking: [],
|
|
58
|
-
references: [],
|
|
59
|
-
referencedBy: [],
|
|
60
|
-
heuristic: []
|
|
61
|
-
};
|
|
62
|
-
}
|
|
63
|
-
function uniqueIds(ids, self) {
|
|
64
|
-
const seen = /* @__PURE__ */ new Set();
|
|
65
|
-
const out = [];
|
|
66
|
-
for (const raw of ids) {
|
|
67
|
-
const id = raw.trim();
|
|
68
|
-
if (id === "" || id === self || seen.has(id)) continue;
|
|
69
|
-
seen.add(id);
|
|
70
|
-
out.push(id);
|
|
71
|
-
}
|
|
72
|
-
return out;
|
|
73
|
-
}
|
|
74
|
-
function stripCode(body) {
|
|
75
|
-
return body.replace(/```[\s\S]*?```/g, " ").replace(/`[^`\n]*`/g, " ");
|
|
76
|
-
}
|
|
77
|
-
var BLOCKED_BY = /\b(?:depends[- ]on|depends upon|blocked[- ]by|requires|depende[ -]de|dependente[ -]de|bloquead[ao] por|requer)\b\s*:?\s*/gi;
|
|
78
|
-
var BLOCKING = /\b(?:blocks|blocking|bloqueia|bloqueando)\b\s*:?\s*/gi;
|
|
79
|
-
var TASK_ITEM = /^[ \t]*[-*]\s*\[[ xX]\]\s*(.*)$/gm;
|
|
80
|
-
var ANY_ID = /(?:^|[^\w#])#(\d+)\b/g;
|
|
81
|
-
function idsFrom(text) {
|
|
82
|
-
const ids = [];
|
|
83
|
-
const id = /#(\d+)/y;
|
|
84
|
-
let cursor = 0;
|
|
85
|
-
while (cursor < text.length) {
|
|
86
|
-
id.lastIndex = cursor;
|
|
87
|
-
const match = id.exec(text);
|
|
88
|
-
if (match === null) break;
|
|
89
|
-
ids.push(match[1]);
|
|
90
|
-
cursor = id.lastIndex;
|
|
91
|
-
const gloss = /^\s*\([^)]*\)/.exec(text.slice(cursor));
|
|
92
|
-
if (gloss !== null) {
|
|
93
|
-
cursor += gloss[0].length;
|
|
94
|
-
}
|
|
95
|
-
const separator = /^\s*(?:,|and\b|e\b|&)\s*/i.exec(text.slice(cursor));
|
|
96
|
-
if (separator === null) break;
|
|
97
|
-
cursor += separator[0].length;
|
|
98
|
-
}
|
|
99
|
-
return ids;
|
|
100
|
-
}
|
|
101
|
-
function collect(body, keyword) {
|
|
102
|
-
const ids = [];
|
|
103
|
-
keyword.lastIndex = 0;
|
|
104
|
-
let match = keyword.exec(body);
|
|
105
|
-
while (match !== null) {
|
|
106
|
-
ids.push(...idsFrom(body.slice(keyword.lastIndex)));
|
|
107
|
-
match = keyword.exec(body);
|
|
108
|
-
}
|
|
109
|
-
return ids;
|
|
110
|
-
}
|
|
111
|
-
function parseTextualRelations(body, self) {
|
|
112
|
-
const text = stripCode(body ?? "");
|
|
113
|
-
const blockedBy = collect(text, BLOCKED_BY);
|
|
114
|
-
const blocking = collect(text, BLOCKING);
|
|
115
|
-
const children = [];
|
|
116
|
-
TASK_ITEM.lastIndex = 0;
|
|
117
|
-
let item = TASK_ITEM.exec(text);
|
|
118
|
-
while (item !== null) {
|
|
119
|
-
const content = item[1] ?? "";
|
|
120
|
-
const first = /^\s*\[?#(\d+)\b/.exec(content);
|
|
121
|
-
if (first?.[1] !== void 0) {
|
|
122
|
-
children.push(first[1]);
|
|
123
|
-
}
|
|
124
|
-
item = TASK_ITEM.exec(text);
|
|
125
|
-
}
|
|
126
|
-
const classified = /* @__PURE__ */ new Set([...blockedBy, ...blocking, ...children]);
|
|
127
|
-
const references = [];
|
|
128
|
-
ANY_ID.lastIndex = 0;
|
|
129
|
-
let cited = ANY_ID.exec(text);
|
|
130
|
-
while (cited !== null) {
|
|
131
|
-
const id = cited[1];
|
|
132
|
-
if (!classified.has(id)) {
|
|
133
|
-
references.push(id);
|
|
134
|
-
}
|
|
135
|
-
ANY_ID.lastIndex = Math.max(ANY_ID.lastIndex - 1, cited.index + 1);
|
|
136
|
-
cited = ANY_ID.exec(text);
|
|
137
|
-
}
|
|
138
|
-
return {
|
|
139
|
-
children: uniqueIds(children, self),
|
|
140
|
-
blockedBy: uniqueIds(blockedBy, self),
|
|
141
|
-
blocking: uniqueIds(blocking, self),
|
|
142
|
-
references: uniqueIds(references, self)
|
|
143
|
-
};
|
|
144
|
-
}
|
|
145
|
-
function mergeRelations(structured, textual) {
|
|
146
|
-
const self = structured.id;
|
|
147
|
-
const children = uniqueIds([...structured.children, ...textual.children], self);
|
|
148
|
-
const blockedBy = uniqueIds([...structured.blockedBy, ...textual.blockedBy], self);
|
|
149
|
-
const blocking = uniqueIds([...structured.blocking, ...textual.blocking], self);
|
|
150
|
-
const references = uniqueIds([...structured.references, ...textual.references], self);
|
|
151
|
-
const fromApi = /* @__PURE__ */ new Set([
|
|
152
|
-
...structured.children,
|
|
153
|
-
...structured.blockedBy,
|
|
154
|
-
...structured.blocking,
|
|
155
|
-
...structured.parent === null ? [] : [structured.parent]
|
|
156
|
-
]);
|
|
157
|
-
const heuristic = uniqueIds(
|
|
158
|
-
[...textual.children, ...textual.blockedBy, ...textual.blocking].filter(
|
|
159
|
-
(id) => !fromApi.has(id)
|
|
160
|
-
),
|
|
161
|
-
self
|
|
162
|
-
);
|
|
163
|
-
return {
|
|
164
|
-
id: self,
|
|
165
|
-
parent: structured.parent,
|
|
166
|
-
children,
|
|
167
|
-
blockedBy,
|
|
168
|
-
blocking,
|
|
169
|
-
references,
|
|
170
|
-
referencedBy: uniqueIds(structured.referencedBy, self),
|
|
171
|
-
heuristic
|
|
172
|
-
};
|
|
173
|
-
}
|
|
174
|
-
|
|
175
67
|
// src/issues/providers/github.ts
|
|
176
68
|
var VIEW_FIELDS = "number,title,body,labels,state,url,createdAt,updatedAt";
|
|
177
69
|
var PROBE_TIMEOUT_MS = 1e4;
|
|
70
|
+
function ghPolicy() {
|
|
71
|
+
return (failure) => resolvePolicy(failure.kind, getActiveResilienceConfig());
|
|
72
|
+
}
|
|
73
|
+
var PROBE_MAX_ATTEMPTS = 3;
|
|
74
|
+
var PROBE_MAX_DELAY_MS = 5e3;
|
|
75
|
+
function ghProbePolicy() {
|
|
76
|
+
const policyFor = ghPolicy();
|
|
77
|
+
return (failure) => {
|
|
78
|
+
const policy = policyFor(failure);
|
|
79
|
+
return {
|
|
80
|
+
...policy,
|
|
81
|
+
maxAttempts: Math.min(policy.maxAttempts, PROBE_MAX_ATTEMPTS),
|
|
82
|
+
maxDelayMs: Math.min(policy.maxDelayMs, PROBE_MAX_DELAY_MS),
|
|
83
|
+
retryForever: false
|
|
84
|
+
};
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
function gh(args, options = {}) {
|
|
88
|
+
return run("gh", args, {
|
|
89
|
+
retry: ghPolicy(),
|
|
90
|
+
...options.timeout === void 0 ? {} : { timeout: options.timeout }
|
|
91
|
+
});
|
|
92
|
+
}
|
|
178
93
|
var NOT_FOUND_PATTERN = /could not resolve to an issue|no issues? found|issue not found|could not find any issue/i;
|
|
179
94
|
function normalizeState(state) {
|
|
180
95
|
return String(state ?? "").toUpperCase() === "CLOSED" ? "closed" : "open";
|
|
@@ -212,7 +127,7 @@ function isRecord(value) {
|
|
|
212
127
|
}
|
|
213
128
|
async function ghApiJson(path) {
|
|
214
129
|
try {
|
|
215
|
-
const result = await
|
|
130
|
+
const result = await gh(["api", path]);
|
|
216
131
|
if (result.exitCode !== 0) return null;
|
|
217
132
|
return JSON.parse(result.stdout);
|
|
218
133
|
} catch {
|
|
@@ -246,27 +161,66 @@ function crossReferences(timeline, self) {
|
|
|
246
161
|
function extractIssueNumber(output) {
|
|
247
162
|
return output.match(/\/issues\/(\d+)/)?.[1] ?? null;
|
|
248
163
|
}
|
|
164
|
+
function ghError(message, result) {
|
|
165
|
+
const failure = result.failure;
|
|
166
|
+
if (failure === void 0) return new Error(message);
|
|
167
|
+
return new ClassifiedError(message, failure, ghAction(failure));
|
|
168
|
+
}
|
|
169
|
+
function ghAction(failure) {
|
|
170
|
+
if (!requiresHumanAction(failure.kind)) return void 0;
|
|
171
|
+
if (failure.kind === "authentication") {
|
|
172
|
+
return "Run `gh auth login` to authenticate the GitHub CLI";
|
|
173
|
+
}
|
|
174
|
+
return void 0;
|
|
175
|
+
}
|
|
176
|
+
function unavailable(result, action) {
|
|
177
|
+
const failure = result.failure;
|
|
178
|
+
const needsHuman = failure === void 0 || requiresHumanAction(failure.kind);
|
|
179
|
+
return {
|
|
180
|
+
available: false,
|
|
181
|
+
...failure === void 0 ? {} : { failure },
|
|
182
|
+
...needsHuman ? { action } : {}
|
|
183
|
+
};
|
|
184
|
+
}
|
|
249
185
|
var GitHubIssueProvider = class {
|
|
250
186
|
name = "github";
|
|
251
187
|
/** True when gh is installed and authenticated. Never throws. */
|
|
252
188
|
async isAvailable() {
|
|
189
|
+
return (await this.checkAvailability()).available;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Whether gh is installed and authenticated, with the reason when it is not.
|
|
193
|
+
*
|
|
194
|
+
* Both probes retry on the capped probe budget, so a DNS blip during a long
|
|
195
|
+
* run no longer reports GitHub as unavailable and takes the whole run down
|
|
196
|
+
* with it — while an authentication failure is clamped to zero attempts by
|
|
197
|
+
* `resolvePolicy()` and comes back immediately, with the action to take.
|
|
198
|
+
*/
|
|
199
|
+
async checkAvailability() {
|
|
253
200
|
try {
|
|
254
|
-
const
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
201
|
+
const retry = ghProbePolicy();
|
|
202
|
+
const version = await run("gh", ["--version"], { retry, timeout: PROBE_TIMEOUT_MS });
|
|
203
|
+
if (version.exitCode !== 0) {
|
|
204
|
+
return unavailable(version, "Install the GitHub CLI: https://cli.github.com");
|
|
205
|
+
}
|
|
206
|
+
const auth = await run("gh", ["auth", "status"], { retry, timeout: PROBE_TIMEOUT_MS });
|
|
207
|
+
if (auth.exitCode !== 0) {
|
|
208
|
+
return unavailable(auth, "Run `gh auth login` to authenticate the GitHub CLI");
|
|
209
|
+
}
|
|
210
|
+
return { available: true };
|
|
258
211
|
} catch {
|
|
259
|
-
return false;
|
|
212
|
+
return { available: false };
|
|
260
213
|
}
|
|
261
214
|
}
|
|
262
215
|
async get(id) {
|
|
263
216
|
const issueId = normalizeId(id);
|
|
264
|
-
const result = await
|
|
217
|
+
const result = await gh(["issue", "view", issueId, "--json", VIEW_FIELDS]);
|
|
265
218
|
if (result.exitCode !== 0) {
|
|
266
219
|
const detail = (result.stderr || result.stdout).trim();
|
|
267
220
|
if (NOT_FOUND_PATTERN.test(detail)) return null;
|
|
268
|
-
throw
|
|
269
|
-
`Failed to fetch GitHub issue #${issueId}: ${detail || "gh issue view failed"}
|
|
221
|
+
throw ghError(
|
|
222
|
+
`Failed to fetch GitHub issue #${issueId}: ${detail || "gh issue view failed"}`,
|
|
223
|
+
result
|
|
270
224
|
);
|
|
271
225
|
}
|
|
272
226
|
let payload;
|
|
@@ -287,10 +241,10 @@ var GitHubIssueProvider = class {
|
|
|
287
241
|
if (draft.type !== void 0 && draft.type !== "") {
|
|
288
242
|
args.push("--type", draft.type);
|
|
289
243
|
}
|
|
290
|
-
const result = await
|
|
244
|
+
const result = await gh(args);
|
|
291
245
|
if (result.exitCode !== 0) {
|
|
292
246
|
const detail = (result.stderr || result.stdout).trim();
|
|
293
|
-
throw
|
|
247
|
+
throw ghError(`Failed to create GitHub issue: ${detail || "gh issue create failed"}`, result);
|
|
294
248
|
}
|
|
295
249
|
const number = extractIssueNumber(result.stdout);
|
|
296
250
|
if (!number) {
|
|
@@ -358,11 +312,12 @@ var GitHubIssueProvider = class {
|
|
|
358
312
|
}
|
|
359
313
|
async close(id) {
|
|
360
314
|
const issueId = normalizeId(id);
|
|
361
|
-
const result = await
|
|
315
|
+
const result = await gh(["issue", "close", issueId]);
|
|
362
316
|
if (result.exitCode !== 0) {
|
|
363
317
|
const detail = (result.stderr || result.stdout).trim();
|
|
364
|
-
throw
|
|
365
|
-
`Failed to close GitHub issue #${issueId}: ${detail || "gh issue close failed"}
|
|
318
|
+
throw ghError(
|
|
319
|
+
`Failed to close GitHub issue #${issueId}: ${detail || "gh issue close failed"}`,
|
|
320
|
+
result
|
|
366
321
|
);
|
|
367
322
|
}
|
|
368
323
|
}
|
|
@@ -715,10 +670,20 @@ function ensureProvidersRegistered() {
|
|
|
715
670
|
import { createInterface } from "readline";
|
|
716
671
|
var IssueResolutionError = class extends Error {
|
|
717
672
|
exitCode;
|
|
718
|
-
|
|
673
|
+
/**
|
|
674
|
+
* The verdict of the origin that failed, when one origin failed for a reason
|
|
675
|
+
* worth naming. It is what tells "this Issue does not exist" apart from
|
|
676
|
+
* "GitHub could not be reached", which are the same message today.
|
|
677
|
+
*/
|
|
678
|
+
failure;
|
|
679
|
+
/** What a human has to do, for a failure that waiting cannot fix. */
|
|
680
|
+
action;
|
|
681
|
+
constructor(message, exitCode = 1, details = {}) {
|
|
719
682
|
super(message);
|
|
720
683
|
this.name = "IssueResolutionError";
|
|
721
684
|
this.exitCode = exitCode;
|
|
685
|
+
this.failure = details.failure;
|
|
686
|
+
this.action = details.action;
|
|
722
687
|
}
|
|
723
688
|
};
|
|
724
689
|
var MAX_PROMPT_ATTEMPTS = 3;
|
|
@@ -743,14 +708,23 @@ async function fetchCandidate(source, id, warn) {
|
|
|
743
708
|
} catch (err) {
|
|
744
709
|
return { source, issue: null, reason: errorMessage(err) };
|
|
745
710
|
}
|
|
746
|
-
let
|
|
711
|
+
let availability;
|
|
747
712
|
try {
|
|
748
|
-
|
|
713
|
+
availability = await provider.checkAvailability?.() ?? {
|
|
714
|
+
available: await provider.isAvailable()
|
|
715
|
+
};
|
|
749
716
|
} catch (err) {
|
|
750
717
|
return { source, issue: null, reason: `provider unavailable (${errorMessage(err)})` };
|
|
751
718
|
}
|
|
752
|
-
if (!available) {
|
|
753
|
-
|
|
719
|
+
if (!availability.available) {
|
|
720
|
+
const reason = availability.failure?.message ?? "provider unavailable";
|
|
721
|
+
return {
|
|
722
|
+
source,
|
|
723
|
+
issue: null,
|
|
724
|
+
reason,
|
|
725
|
+
...availability.failure === void 0 ? {} : { failure: availability.failure },
|
|
726
|
+
...availability.action === void 0 ? {} : { action: availability.action }
|
|
727
|
+
};
|
|
754
728
|
}
|
|
755
729
|
try {
|
|
756
730
|
const issue = await provider.get(id);
|
|
@@ -758,7 +732,15 @@ async function fetchCandidate(source, id, warn) {
|
|
|
758
732
|
} catch (err) {
|
|
759
733
|
const reason = errorMessage(err);
|
|
760
734
|
warn(`Could not read issue '${id}' from ${sourceLabel(source)}: ${reason}`);
|
|
761
|
-
|
|
735
|
+
const failure = failureOf(err);
|
|
736
|
+
const action = actionOf(err);
|
|
737
|
+
return {
|
|
738
|
+
source,
|
|
739
|
+
issue: null,
|
|
740
|
+
reason,
|
|
741
|
+
...failure === null ? {} : { failure },
|
|
742
|
+
...action === null ? {} : { action }
|
|
743
|
+
};
|
|
762
744
|
}
|
|
763
745
|
}
|
|
764
746
|
function shortHash(hash) {
|
|
@@ -875,6 +857,17 @@ async function resolveIssue(id, opts = {}) {
|
|
|
875
857
|
if (found.length === 0) {
|
|
876
858
|
const details = candidates.map((candidate) => `${sourceLabel(candidate.source)}: ${candidate.reason ?? "not found"}`).join("; ");
|
|
877
859
|
const where = details.length > 0 ? ` (${details})` : "";
|
|
860
|
+
const blocking = candidates.find((candidate) => candidate.action !== void 0);
|
|
861
|
+
if (blocking !== void 0) {
|
|
862
|
+
throw new IssueResolutionError(
|
|
863
|
+
`Cannot read issue '${id}' from ${sourceLabel(blocking.source)}: ${blocking.reason}`,
|
|
864
|
+
1,
|
|
865
|
+
{
|
|
866
|
+
...blocking.failure === void 0 ? {} : { failure: blocking.failure },
|
|
867
|
+
...blocking.action === void 0 ? {} : { action: blocking.action }
|
|
868
|
+
}
|
|
869
|
+
);
|
|
870
|
+
}
|
|
878
871
|
throw new IssueResolutionError(`Issue '${id}' not found in any registered origin${where}`);
|
|
879
872
|
}
|
|
880
873
|
const build = (candidate, divergent) => buildResolved(candidate.issue, candidate.source, local, github, divergent);
|
|
@@ -955,21 +948,34 @@ async function resolveCommandIssue(id, preResolved, options) {
|
|
|
955
948
|
} catch (err) {
|
|
956
949
|
if (err instanceof IssueResolutionError) {
|
|
957
950
|
printError(err.message);
|
|
951
|
+
printAction(err.action);
|
|
958
952
|
return { ok: false, code: err.exitCode };
|
|
959
953
|
}
|
|
960
954
|
const message = err instanceof Error ? err.message : String(err);
|
|
961
955
|
printError(`Could not resolve issue '${id}': ${message}`);
|
|
956
|
+
printAction(actionOf(err) ?? requiredAction(message));
|
|
962
957
|
return { ok: false, code: 1 };
|
|
963
958
|
}
|
|
964
959
|
}
|
|
960
|
+
function requiredAction(message) {
|
|
961
|
+
const failure = classify({ source: "github", stderr: message });
|
|
962
|
+
if (!requiresHumanAction(failure.kind)) return null;
|
|
963
|
+
if (failure.kind === "authentication") {
|
|
964
|
+
return "Run `gh auth login` to authenticate the GitHub CLI";
|
|
965
|
+
}
|
|
966
|
+
return null;
|
|
967
|
+
}
|
|
968
|
+
function printAction(action) {
|
|
969
|
+
if (action !== null && action !== void 0 && action !== "") {
|
|
970
|
+
printWarning(`Action required: ${action}`);
|
|
971
|
+
}
|
|
972
|
+
}
|
|
965
973
|
|
|
966
974
|
export {
|
|
967
|
-
emptyRelations,
|
|
968
|
-
uniqueIds,
|
|
969
975
|
getProvider,
|
|
970
976
|
ensureProvidersRegistered,
|
|
971
977
|
localIssueRef,
|
|
972
978
|
issuePlaceholders,
|
|
973
979
|
resolveCommandIssue
|
|
974
980
|
};
|
|
975
|
-
//# sourceMappingURL=chunk-
|
|
981
|
+
//# sourceMappingURL=chunk-73ATPIYX.js.map
|