issue-flow 0.10.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +1 -1
  2. package/dist/{analyze-UZYJAWAP.js → analyze-XV3K25K3.js} +15 -9
  3. package/dist/analyze-XV3K25K3.js.map +1 -0
  4. package/dist/apply-WUJHDD7A.js +788 -0
  5. package/dist/apply-WUJHDD7A.js.map +1 -0
  6. package/dist/{chunk-2Z7OEZZT.js → chunk-34WNTK3K.js} +14 -9
  7. package/dist/chunk-34WNTK3K.js.map +1 -0
  8. package/dist/{chunk-UUY4PCWW.js → chunk-3BOHTH4V.js} +2 -2
  9. package/dist/chunk-3D4A4B46.js +2 -0
  10. package/dist/{policy-NP4ZAVF6.js → chunk-47VIN33V.js} +82 -112
  11. package/dist/chunk-47VIN33V.js.map +1 -0
  12. package/dist/{chunk-67ZO5ROQ.js → chunk-6N7LZZ5U.js} +19 -13
  13. package/dist/chunk-6N7LZZ5U.js.map +1 -0
  14. package/dist/{chunk-S67Q4I2O.js → chunk-AAY6KM7N.js} +6 -3
  15. package/dist/chunk-AAY6KM7N.js.map +1 -0
  16. package/dist/{chunk-2LNQL4XH.js → chunk-BXCPXRBR.js} +17 -12
  17. package/dist/chunk-BXCPXRBR.js.map +1 -0
  18. package/dist/{chunk-MXTGCD5C.js → chunk-EWDJENFW.js} +30 -9
  19. package/dist/chunk-EWDJENFW.js.map +1 -0
  20. package/dist/{chunk-SP7DD4ID.js → chunk-EY6WMHV2.js} +17 -12
  21. package/dist/chunk-EY6WMHV2.js.map +1 -0
  22. package/dist/{chunk-652DJBCN.js → chunk-GANSDJV7.js} +4 -4
  23. package/dist/{chunk-V5OHFSW4.js → chunk-HC2MT7BX.js} +23 -3
  24. package/dist/chunk-HC2MT7BX.js.map +1 -0
  25. package/dist/chunk-HQYXVIH6.js +110 -0
  26. package/dist/chunk-HQYXVIH6.js.map +1 -0
  27. package/dist/{chunk-UH4KAJBJ.js → chunk-IVHZEYAX.js} +17 -12
  28. package/dist/chunk-IVHZEYAX.js.map +1 -0
  29. package/dist/{chunk-EWA3OGCM.js → chunk-KQ4JQN7T.js} +14 -9
  30. package/dist/chunk-KQ4JQN7T.js.map +1 -0
  31. package/dist/{chunk-VOKNTBOO.js → chunk-LVKQ2AKT.js} +3 -3
  32. package/dist/chunk-OBLVLIUS.js +285 -0
  33. package/dist/chunk-OBLVLIUS.js.map +1 -0
  34. package/dist/chunk-RKTEV6EG.js +246 -0
  35. package/dist/chunk-RKTEV6EG.js.map +1 -0
  36. package/dist/{chunk-VYFKOUUR.js → chunk-VQ5VN7DF.js} +9 -5
  37. package/dist/chunk-VQ5VN7DF.js.map +1 -0
  38. package/dist/cli.js +26 -22
  39. package/dist/cli.js.map +1 -1
  40. package/dist/{config-YCF3HIKR.js → config-4THHOXNN.js} +3 -3
  41. package/dist/execute-5OEKLM5X.js +15 -0
  42. package/dist/{generate-TW6QKSW5.js → generate-TBVTLMOP.js} +101 -13
  43. package/dist/generate-TBVTLMOP.js.map +1 -0
  44. package/dist/init-PRMOTQ7N.js +9 -0
  45. package/dist/plan-Y2BYZD24.js +17 -0
  46. package/dist/policy-XQW5NUIE.js +117 -0
  47. package/dist/policy-XQW5NUIE.js.map +1 -0
  48. package/dist/pr-H6GLOSXF.js +21 -0
  49. package/dist/pr-review-CK5FR6WX.js +17 -0
  50. package/dist/prd-4PWLCGH5.js +17 -0
  51. package/dist/review-QGVAHEZF.js +15 -0
  52. package/dist/review-QGVAHEZF.js.map +1 -0
  53. package/dist/{run-DIBC3YKX.js → run-DBF2VWUN.js} +26 -25
  54. package/dist/{run-DIBC3YKX.js.map → run-DBF2VWUN.js.map} +1 -1
  55. package/dist/{web-O2FVOYZW.js → web-ANQQTTRD.js} +5 -5
  56. package/package.json +1 -1
  57. package/prompts/analyze.md +24 -0
  58. package/prompts/execute.md +29 -1
  59. package/prompts/generate.md +61 -7
  60. package/prompts/plan.md +24 -1
  61. package/prompts/pr-review.md +65 -4
  62. package/prompts/pr.md +37 -3
  63. package/prompts/prd.md +17 -0
  64. package/prompts/review.md +40 -0
  65. package/dist/analyze-UZYJAWAP.js.map +0 -1
  66. package/dist/chunk-2LNQL4XH.js.map +0 -1
  67. package/dist/chunk-2Z7OEZZT.js.map +0 -1
  68. package/dist/chunk-67ZO5ROQ.js.map +0 -1
  69. package/dist/chunk-EWA3OGCM.js.map +0 -1
  70. package/dist/chunk-EZMOEBLU.js +0 -135
  71. package/dist/chunk-EZMOEBLU.js.map +0 -1
  72. package/dist/chunk-MXTGCD5C.js.map +0 -1
  73. package/dist/chunk-PPLIXZI5.js +0 -101
  74. package/dist/chunk-PPLIXZI5.js.map +0 -1
  75. package/dist/chunk-S67Q4I2O.js.map +0 -1
  76. package/dist/chunk-SLHZPB3C.js +0 -50
  77. package/dist/chunk-SLHZPB3C.js.map +0 -1
  78. package/dist/chunk-SP7DD4ID.js.map +0 -1
  79. package/dist/chunk-UH4KAJBJ.js.map +0 -1
  80. package/dist/chunk-V5OHFSW4.js.map +0 -1
  81. package/dist/chunk-VYFKOUUR.js.map +0 -1
  82. package/dist/execute-QYXA225W.js +0 -14
  83. package/dist/generate-TW6QKSW5.js.map +0 -1
  84. package/dist/init-G57UXKDG.js +0 -9
  85. package/dist/plan-YJLGBYBQ.js +0 -16
  86. package/dist/policy-NP4ZAVF6.js.map +0 -1
  87. package/dist/pr-V5H65MRW.js +0 -20
  88. package/dist/pr-review-RCMXKXVP.js +0 -16
  89. package/dist/prd-3XR5KYJS.js +0 -16
  90. package/dist/review-ZZG3CSUO.js +0 -14
  91. /package/dist/{chunk-UUY4PCWW.js.map → chunk-3BOHTH4V.js.map} +0 -0
  92. /package/dist/{config-YCF3HIKR.js.map → chunk-3D4A4B46.js.map} +0 -0
  93. /package/dist/{chunk-652DJBCN.js.map → chunk-GANSDJV7.js.map} +0 -0
  94. /package/dist/{chunk-VOKNTBOO.js.map → chunk-LVKQ2AKT.js.map} +0 -0
  95. /package/dist/{execute-QYXA225W.js.map → config-4THHOXNN.js.map} +0 -0
  96. /package/dist/{init-G57UXKDG.js.map → execute-5OEKLM5X.js.map} +0 -0
  97. /package/dist/{plan-YJLGBYBQ.js.map → init-PRMOTQ7N.js.map} +0 -0
  98. /package/dist/{pr-V5H65MRW.js.map → plan-Y2BYZD24.js.map} +0 -0
  99. /package/dist/{pr-review-RCMXKXVP.js.map → pr-H6GLOSXF.js.map} +0 -0
  100. /package/dist/{prd-3XR5KYJS.js.map → pr-review-CK5FR6WX.js.map} +0 -0
  101. /package/dist/{review-ZZG3CSUO.js.map → prd-4PWLCGH5.js.map} +0 -0
  102. /package/dist/{web-O2FVOYZW.js.map → web-ANQQTTRD.js.map} +0 -0
  103. /package/web/{CLAUDE.md → AGENTS.md} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/issues/registry.ts","../src/issues/hash.ts","../src/issues/relations.ts","../src/issues/providers/github.ts","../src/issues/providers/local.ts","../src/issues/bootstrap.ts","../src/issues/resolver.ts","../src/issues/context.ts"],"sourcesContent":["import type { IssueProvider } from './provider.js';\nimport type { IssueSource } from './types.js';\n\n/**\n * Registry of Issue providers.\n *\n * Adding an origin is creating a provider file and registering one line here\n * (or from the caller's side), so nothing in src/commands/ needs to know the\n * list of sources.\n */\nconst providers = new Map<IssueSource, IssueProvider>();\n\n/**\n * Register a provider under its own `name`.\n *\n * Registering the same source twice replaces the previous entry, which is what\n * lets tests substitute a real provider with a fake one.\n */\nexport function registerProvider(provider: IssueProvider): void {\n providers.set(provider.name, provider);\n}\n\n/** Sources currently registered, in registration order. */\nexport function getRegisteredSources(): IssueSource[] {\n return [...providers.keys()];\n}\n\n/**\n * Look up a provider by origin.\n *\n * @throws when the origin is not registered, listing what is available so the\n * caller knows which sources they can pick instead.\n */\nexport function getProvider(source: IssueSource): IssueProvider {\n const provider = providers.get(source);\n if (provider === undefined) {\n const available = getRegisteredSources();\n const hint =\n available.length > 0\n ? `Available sources: ${available.join(', ')}.`\n : 'No Issue providers are registered.';\n throw new Error(`Unknown Issue source: '${source}'. ${hint}`);\n }\n return provider;\n}\n\n/** Drop every registration. Intended for test isolation. */\nexport function clearProviders(): void {\n providers.clear();\n}\n","import { createHash } from 'node:crypto';\n\n/**\n * Content hashing shared by every Issue provider.\n *\n * The hash is what lets the resolver tell \"the local and the remote Issue are\n * the same demand\" from \"they diverged\", so it has to be stable across\n * platforms: Windows checkouts store CRLF, editors add or drop trailing\n * newlines, and neither should count as a content change.\n */\n\n/** Normalizes line endings (CRLF/CR to LF) and trims the edges. */\nfunction normalizeText(value: string): string {\n return value.replace(/\\r\\n?/g, '\\n').trim();\n}\n\n/**\n * Returns `sha256:<hex>` for the given title and body.\n *\n * The payload is a canonical JSON object rather than a concatenation, so text\n * moved from the title into the body always changes the hash.\n */\nexport function hashIssueContent(title: string, body: string): string {\n const payload = JSON.stringify({\n title: normalizeText(title),\n body: normalizeText(body),\n });\n const digest = createHash('sha256').update(payload, 'utf8').digest('hex');\n return `sha256:${digest}`;\n}\n","import type { IssueRelations } from './types.js';\n\n/**\n * Pure helpers around {@link IssueRelations}.\n *\n * Everything here is origin-agnostic: a provider maps its own payload into\n * these shapes, and the textual heuristic below is the shared fallback for\n * repositories that express hierarchy and dependencies in Markdown instead of\n * through a structured API.\n */\n\n/** Relations of an Issue nothing is known about — every field empty. */\nexport function emptyRelations(id: string): IssueRelations {\n return {\n id,\n parent: null,\n children: [],\n blockedBy: [],\n blocking: [],\n references: [],\n referencedBy: [],\n heuristic: [],\n };\n}\n\n/** Whether an Issue relates to nothing at all (mentions included). */\nexport function hasNoRelations(relations: IssueRelations): boolean {\n return (\n relations.parent === null &&\n relations.children.length === 0 &&\n relations.blockedBy.length === 0 &&\n relations.blocking.length === 0\n );\n}\n\n/** Deduplicate preserving order, dropping empty entries and `self`. */\nexport function uniqueIds(ids: readonly string[], self?: string): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const raw of ids) {\n const id = raw.trim();\n if (id === '' || id === self || seen.has(id)) continue;\n seen.add(id);\n out.push(id);\n }\n return out;\n}\n\n/** What {@link parseTextualRelations} can recover from a Markdown body. */\nexport interface TextualRelations {\n children: string[];\n blockedBy: string[];\n blocking: string[];\n /** Every other `#N` cited, with no relation attached to it. */\n references: string[];\n}\n\n/**\n * Code spans and fenced blocks, blanked out before scanning.\n *\n * A snippet that happens to contain `#42` (a shell comment, a CSS colour, a\n * diff hunk header) is documentation, not a dependency — and it is exactly the\n * kind of false positive that would put an unrelated Issue in front of the user\n * as \"part of this hierarchy\".\n */\nfunction stripCode(body: string): string {\n return body.replace(/```[\\s\\S]*?```/g, ' ').replace(/`[^`\\n]*`/g, ' ');\n}\n\n/**\n * Keyword forms accepted before a list of ids, per relation kind.\n *\n * Portuguese spellings sit next to the English ones because issues are written\n * in the language of the team, not of the tool: a repository whose issues say\n * \"Depende de #50\" would otherwise get an empty graph while an identical\n * English-language repository gets a full one.\n */\nconst BLOCKED_BY =\n /\\b(?:depends[- ]on|depends upon|blocked[- ]by|requires|depende[ -]de|dependente[ -]de|bloquead[ao] por|requer)\\b\\s*:?\\s*/gi;\nconst BLOCKING = /\\b(?:blocks|blocking|bloqueia|bloqueando)\\b\\s*:?\\s*/gi;\n\n/** A task list item (`- [ ] #12 …`), the Markdown spelling of a sub-issue. */\nconst TASK_ITEM = /^[ \\t]*[-*]\\s*\\[[ xX]\\]\\s*(.*)$/gm;\n\n/** Every `#N` that is not glued to a word character (`abc#12` is not a citation). */\nconst ANY_ID = /(?:^|[^\\w#])#(\\d+)\\b/g;\n\n/**\n * Ids of the `#a, #b and #c` run that starts exactly at `text`.\n *\n * Anchored on purpose: the keyword must be immediately followed by the list, so\n * \"blocked by the API redesign discussed in #12\" contributes nothing — the\n * sentence names a cause, not a dependency.\n */\nfunction idsFrom(text: string): string[] {\n const ids: string[] = [];\n const id = /#(\\d+)/y;\n let cursor = 0;\n\n while (cursor < text.length) {\n id.lastIndex = cursor;\n const match = id.exec(text);\n if (match === null) break;\n ids.push(match[1] as string);\n cursor = id.lastIndex;\n\n // A parenthetical after an id is a gloss, not the end of the list:\n // \"Depends on #50 (discovery) and #51 (ordering)\" names two dependencies.\n const gloss = /^\\s*\\([^)]*\\)/.exec(text.slice(cursor));\n if (gloss !== null) {\n cursor += gloss[0].length;\n }\n\n // Consume the separator between two ids of the same list.\n const separator = /^\\s*(?:,|and\\b|e\\b|&)\\s*/i.exec(text.slice(cursor));\n if (separator === null) break;\n cursor += separator[0].length;\n }\n\n return ids;\n}\n\nfunction collect(body: string, keyword: RegExp): string[] {\n const ids: string[] = [];\n keyword.lastIndex = 0;\n let match = keyword.exec(body);\n while (match !== null) {\n ids.push(...idsFrom(body.slice(keyword.lastIndex)));\n match = keyword.exec(body);\n }\n return ids;\n}\n\n/**\n * Best-effort hierarchy and dependencies from a Markdown body.\n *\n * Heuristic by construction, and documented as such everywhere it surfaces: a\n * repository that never adopted GitHub's Sub-issues or Issue Dependencies still\n * expresses the same information in prose, and refusing to read it would leave\n * most repositories with an empty graph. The trade-off is accepted with three\n * guards — code is stripped first, only explicit keywords create a relation,\n * and everything else is demoted to a plain reference, which no consumer orders\n * execution by.\n *\n * `self` (the Issue's own id) is filtered out of every list: a body that says\n * \"part 2 of #51\" while being #51 must not depend on itself.\n */\nexport function parseTextualRelations(body: string, self?: string): TextualRelations {\n const text = stripCode(body ?? '');\n\n const blockedBy = collect(text, BLOCKED_BY);\n const blocking = collect(text, BLOCKING);\n\n const children: string[] = [];\n TASK_ITEM.lastIndex = 0;\n let item = TASK_ITEM.exec(text);\n while (item !== null) {\n const content = item[1] ?? '';\n // The citation must **open** the item, which is how GitHub's own task lists\n // reference an issue (`- [ ] #21 Title`). A checklist entry that merely\n // mentions an issue in its prose (\"- [ ] Reuse the graph of issue #50\") is\n // a note, not a sub-issue — and treating it as one was the most common\n // false positive this heuristic produced on real bodies.\n const first = /^\\s*\\[?#(\\d+)\\b/.exec(content);\n if (first?.[1] !== undefined) {\n children.push(first[1]);\n }\n item = TASK_ITEM.exec(text);\n }\n\n const classified = new Set([...blockedBy, ...blocking, ...children]);\n const references: string[] = [];\n ANY_ID.lastIndex = 0;\n let cited = ANY_ID.exec(text);\n while (cited !== null) {\n const id = cited[1] as string;\n if (!classified.has(id)) {\n references.push(id);\n }\n // Overlapping matches: `#1 #2` shares the separator, so rewind by one.\n ANY_ID.lastIndex = Math.max(ANY_ID.lastIndex - 1, cited.index + 1);\n cited = ANY_ID.exec(text);\n }\n\n return {\n children: uniqueIds(children, self),\n blockedBy: uniqueIds(blockedBy, self),\n blocking: uniqueIds(blocking, self),\n references: uniqueIds(references, self),\n };\n}\n\n/**\n * Merge structured relations with the textual fallback, recording which\n * identifiers exist only because of the heuristic.\n *\n * Structured data always wins the ordering of a list (it is listed first), and\n * an id present in both is *not* marked heuristic — it was confirmed by an API.\n */\nexport function mergeRelations(\n structured: Omit<IssueRelations, 'heuristic'>,\n textual: TextualRelations,\n): IssueRelations {\n const self = structured.id;\n\n const children = uniqueIds([...structured.children, ...textual.children], self);\n const blockedBy = uniqueIds([...structured.blockedBy, ...textual.blockedBy], self);\n const blocking = uniqueIds([...structured.blocking, ...textual.blocking], self);\n const references = uniqueIds([...structured.references, ...textual.references], self);\n\n const fromApi = new Set([\n ...structured.children,\n ...structured.blockedBy,\n ...structured.blocking,\n ...(structured.parent === null ? [] : [structured.parent]),\n ]);\n const heuristic = uniqueIds(\n [...textual.children, ...textual.blockedBy, ...textual.blocking].filter(\n (id) => !fromApi.has(id),\n ),\n self,\n );\n\n return {\n id: self,\n parent: structured.parent,\n children,\n blockedBy,\n blocking,\n references,\n referencedBy: uniqueIds(structured.referencedBy, self),\n heuristic,\n };\n}\n","import { run } from '../../utils/shell.js';\nimport { hashIssueContent } from '../hash.js';\nimport type { IssueProvider } from '../provider.js';\nimport { emptyRelations, mergeRelations, parseTextualRelations, uniqueIds } from '../relations.js';\nimport type { Issue, IssueDraft, IssueRelations, IssueState } from '../types.js';\n\n/** Fields requested from `gh issue view`, in the order the PRD specifies. */\nconst VIEW_FIELDS = 'number,title,body,labels,state,url,createdAt,updatedAt';\n\n/** Timeout for the availability probes, matching the `init` prerequisite checks. */\nconst PROBE_TIMEOUT_MS = 10_000;\n\n/**\n * gh reports a missing Issue on stderr with one of these phrasings. The match\n * must stay issue-specific: a bare /not found/ would also swallow\n * `gh: command not found`, turning a broken environment into \"issue absent\".\n * Anything else on a non-zero exit is a real failure (network, auth, gh not\n * installed) and must surface as a thrown error.\n */\nconst NOT_FOUND_PATTERN =\n /could not resolve to an issue|no issues? found|issue not found|could not find any issue/i;\n\ninterface GhLabel {\n name?: unknown;\n}\n\ninterface GhIssuePayload {\n number?: unknown;\n title?: unknown;\n body?: unknown;\n labels?: unknown;\n state?: unknown;\n url?: unknown;\n createdAt?: unknown;\n updatedAt?: unknown;\n}\n\nfunction normalizeState(state: unknown): IssueState {\n return String(state ?? '').toUpperCase() === 'CLOSED' ? 'closed' : 'open';\n}\n\nfunction normalizeLabels(labels: unknown): string[] {\n if (!Array.isArray(labels)) return [];\n return labels\n .map((label: GhLabel | string) => (typeof label === 'string' ? label : label?.name))\n .filter((name): name is string => typeof name === 'string' && name.length > 0);\n}\n\nfunction toIssue(payload: GhIssuePayload): Issue {\n const title = typeof payload.title === 'string' ? payload.title : '';\n const body = typeof payload.body === 'string' ? payload.body : '';\n const number = typeof payload.number === 'number' ? payload.number : null;\n const url = typeof payload.url === 'string' && payload.url.length > 0 ? payload.url : null;\n\n return {\n id: number === null ? '' : String(number),\n number,\n title,\n body,\n labels: normalizeLabels(payload.labels),\n state: normalizeState(payload.state),\n source: 'github',\n remoteRef: url,\n createdAt: typeof payload.createdAt === 'string' ? payload.createdAt : '',\n updatedAt: typeof payload.updatedAt === 'string' ? payload.updatedAt : '',\n contentHash: hashIssueContent(title, body),\n raw: payload,\n };\n}\n\n/** Strip a leading `#` so both `23` and `#23` are accepted. */\nfunction normalizeId(id: string): string {\n return id.trim().replace(/^#/, '');\n}\n\n/** Page size for the relation endpoints — one page is enough in practice. */\nconst API_PAGE_SIZE = 100;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * `gh api <path>`, parsed as JSON.\n *\n * Answers `null` for every failure — a disabled feature (404), a plan without\n * Issue Dependencies (403), a network hiccup or unparseable output. That is the\n * whole graceful-degradation contract of `fetchRelations`: a source that cannot\n * answer contributes nothing instead of failing the discovery.\n */\nasync function ghApiJson(path: string): Promise<unknown> {\n try {\n const result = await run('gh', ['api', path]);\n if (result.exitCode !== 0) return null;\n return JSON.parse(result.stdout) as unknown;\n } catch {\n return null;\n }\n}\n\n/** `number` of an Issue-shaped payload, as a string id. */\nfunction issueNumberOf(value: unknown): string | null {\n if (!isRecord(value)) return null;\n const number = value.number;\n return typeof number === 'number' && Number.isInteger(number) ? String(number) : null;\n}\n\n/** Ids of an array of Issue-shaped payloads, skipping anything unusable. */\nfunction issueNumbersOf(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return uniqueIds(\n value.map((entry) => issueNumberOf(entry) ?? '').filter((entry) => entry !== ''),\n );\n}\n\n/**\n * Issues that cited this one, from the timeline's `cross-referenced` events.\n *\n * Pull Requests are filtered out: they reference the Issue as *work on it*, not\n * as another demand to schedule.\n */\nfunction crossReferences(timeline: unknown, self: string): string[] {\n if (!Array.isArray(timeline)) return [];\n\n const ids: string[] = [];\n for (const event of timeline) {\n if (!isRecord(event) || event.event !== 'cross-referenced') continue;\n const source = isRecord(event.source) ? event.source : null;\n const issue = isRecord(source?.issue) ? source.issue : null;\n if (issue === null || issue.pull_request !== undefined) continue;\n const number = issueNumberOf(issue);\n if (number !== null) ids.push(number);\n }\n\n return uniqueIds(ids, self);\n}\n\nfunction extractIssueNumber(output: string): string | null {\n return output.match(/\\/issues\\/(\\d+)/)?.[1] ?? null;\n}\n\n/**\n * Issue provider backed by the GitHub CLI.\n *\n * Every call goes through `run` (execa, no shell) so tests can mock the shell\n * layer instead of the network, and so the Issue content is identical across\n * every pipeline phase.\n */\nexport class GitHubIssueProvider implements IssueProvider {\n readonly name = 'github' as const;\n\n /** True when gh is installed and authenticated. Never throws. */\n async isAvailable(): Promise<boolean> {\n try {\n const version = await run('gh', ['--version'], { timeout: PROBE_TIMEOUT_MS });\n if (version.exitCode !== 0) return false;\n\n const auth = await run('gh', ['auth', 'status'], { timeout: PROBE_TIMEOUT_MS });\n return auth.exitCode === 0;\n } catch {\n return false;\n }\n }\n\n async get(id: string): Promise<Issue | null> {\n const issueId = normalizeId(id);\n const result = await run('gh', ['issue', 'view', issueId, '--json', VIEW_FIELDS]);\n\n if (result.exitCode !== 0) {\n const detail = (result.stderr || result.stdout).trim();\n if (NOT_FOUND_PATTERN.test(detail)) return null;\n throw new Error(\n `Failed to fetch GitHub issue #${issueId}: ${detail || 'gh issue view failed'}`,\n );\n }\n\n let payload: GhIssuePayload;\n try {\n payload = JSON.parse(result.stdout);\n } catch {\n throw new Error(\n `Failed to parse gh output for issue #${issueId}: ${result.stdout.slice(0, 200)}`,\n );\n }\n\n return toIssue(payload);\n }\n\n async create(draft: IssueDraft): Promise<Issue> {\n const args = ['issue', 'create', '--title', draft.title, '--body', draft.body];\n for (const label of draft.labels) {\n args.push('--label', label);\n }\n // Only when the draft actually chose one. An organization without Issue\n // Types rejects the flag outright, so it must never be sent speculatively.\n if (draft.type !== undefined && draft.type !== '') {\n args.push('--type', draft.type);\n }\n\n const result = await run('gh', args);\n if (result.exitCode !== 0) {\n const detail = (result.stderr || result.stdout).trim();\n throw new Error(`Failed to create GitHub issue: ${detail || 'gh issue create failed'}`);\n }\n\n const number = extractIssueNumber(result.stdout);\n if (!number) {\n throw new Error(\n `GitHub issue creation did not report an issue URL: ${result.stdout.trim() || '(no output)'}`,\n );\n }\n\n const created = await this.get(number);\n if (!created) {\n throw new Error(`GitHub issue #${number} was created but could not be read back`);\n }\n return created;\n }\n\n /**\n * Hierarchy and dependencies of an Issue, reconciled from three GitHub\n * mechanisms that only partially overlap:\n *\n * 1. **Sub-issues** (`/sub_issues` plus the `parent` field of the Issue\n * payload) — the native hierarchy;\n * 2. **Issue Dependencies** (`/dependencies/blocked_by` and `/blocking`);\n * 3. the **textual heuristic** over the body, for repositories that adopted\n * neither and write `Depends on #12` or `- [ ] #13` instead.\n *\n * Cross-references (`referencedBy`) come from the issue timeline, which is\n * the only place GitHub reports \"who cited me\" without a search query.\n *\n * Every source is queried independently and is allowed to fail on its own: an\n * organization without Issue Dependencies enabled answers 404 for two of the\n * five calls, and that has to cost the caller those two fields, never the\n * whole discovery. Only what could be read is reported — nothing here throws.\n */\n async fetchRelations(id: string): Promise<IssueRelations> {\n const issueId = normalizeId(id);\n if (!/^\\d+$/.test(issueId)) {\n // A non-numeric identifier cannot address a GitHub REST endpoint; the\n // Issue simply has no relations we can discover.\n return emptyRelations(issueId);\n }\n\n const base = `repos/{owner}/{repo}/issues/${issueId}`;\n const [payload, subIssues, blockedBy, blocking, timeline] = await Promise.all([\n ghApiJson(base),\n ghApiJson(`${base}/sub_issues?per_page=${API_PAGE_SIZE}`),\n ghApiJson(`${base}/dependencies/blocked_by?per_page=${API_PAGE_SIZE}`),\n ghApiJson(`${base}/dependencies/blocking?per_page=${API_PAGE_SIZE}`),\n ghApiJson(`${base}/timeline?per_page=${API_PAGE_SIZE}`),\n ]);\n\n const issue = isRecord(payload) ? payload : null;\n // Without the REST payload the body still comes from `gh issue view`, so a\n // repository where only the REST API is blocked keeps the textual fallback.\n const body = typeof issue?.body === 'string' ? issue.body : await this.bodyFallback(issueId);\n\n const structured = {\n id: issueId,\n parent: issueNumberOf(issue?.parent),\n children: issueNumbersOf(subIssues),\n blockedBy: issueNumbersOf(blockedBy),\n blocking: issueNumbersOf(blocking),\n references: [],\n referencedBy: crossReferences(timeline, issueId),\n };\n\n return mergeRelations(structured, parseTextualRelations(body, issueId));\n }\n\n /** Body of an Issue when the REST payload could not be read. Never throws. */\n private async bodyFallback(issueId: string): Promise<string> {\n try {\n return (await this.get(issueId))?.body ?? '';\n } catch {\n return '';\n }\n }\n\n async close(id: string): Promise<void> {\n const issueId = normalizeId(id);\n const result = await run('gh', ['issue', 'close', issueId]);\n\n if (result.exitCode !== 0) {\n const detail = (result.stderr || result.stdout).trim();\n throw new Error(\n `Failed to close GitHub issue #${issueId}: ${detail || 'gh issue close failed'}`,\n );\n }\n }\n}\n\n/** Shared instance; providers are stateless, so a singleton is enough. */\nexport const githubIssueProvider = new GitHubIssueProvider();\n","import { constants } from 'node:fs';\nimport { access, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { ZodError } from 'zod';\nimport { isoNow } from '../../core/state-manager.js';\nimport { issueMetadataSchema } from '../../schemas.js';\nimport type { IssuePaths } from '../../storage/paths.js';\nimport { resolveIssuePaths, resolveProjectPaths } from '../../storage/resolve.js';\nimport { writeFileAtomic } from '../../utils/fs.js';\nimport { getProjectRoot } from '../../utils/git.js';\nimport { run } from '../../utils/shell.js';\nimport { hashIssueContent } from '../hash.js';\nimport type { IssueProvider } from '../provider.js';\nimport type { Issue, IssueDraft, IssueMetadata } from '../types.js';\n\n/** Timeout for the optional remote probes done while allocating an identifier. */\nconst REMOTE_PROBE_TIMEOUT_MS = 10_000;\n\nfunction isNotFound(err: unknown): boolean {\n const code = (err as NodeJS.ErrnoException).code;\n return code === 'ENOENT' || code === 'ENOTDIR';\n}\n\n/**\n * True when `dir` already is a writable directory, or does not exist yet but\n * would be created successfully by `mkdir(dir, { recursive: true })` — i.e.\n * its nearest existing ancestor is a writable directory.\n *\n * Never mutates the filesystem: `isAvailable()` only needs to answer \"could\n * this work\", which must not leave a `~/.issue-flow/projects/<id>/` directory\n * behind for a project that ends up never using local issues (every other\n * source is queried on every resolution, so this runs far more often than the\n * provider is actually chosen).\n */\nasync function isWritableDirectory(dir: string): Promise<boolean> {\n let current = dir;\n for (;;) {\n let stats: Awaited<ReturnType<typeof stat>>;\n try {\n stats = await stat(current);\n } catch (err: unknown) {\n if (!isNotFound(err)) return false;\n const parent = dirname(current);\n if (parent === current) return false; // reached the filesystem root\n current = parent;\n continue;\n }\n if (!stats.isDirectory()) return false;\n try {\n await access(current, constants.W_OK);\n return true;\n } catch {\n return false;\n }\n }\n}\n\n/**\n * Identifiers become path segments, so anything that could escape the issues\n * directory is rejected before it reaches `join`.\n */\nfunction normalizeId(id: string): string {\n const normalized = id.trim().replace(/^#/, '');\n if (normalized.length === 0) {\n throw new Error('Local issue identifier cannot be empty');\n }\n if (/[/\\\\]/.test(normalized) || normalized === '.' || normalized === '..') {\n throw new Error(`Invalid local issue identifier: '${id}'`);\n }\n return normalized;\n}\n\nfunction toNumber(id: string): number | null {\n return /^\\d+$/.test(id) ? Number.parseInt(id, 10) : null;\n}\n\n/**\n * Title lives in the leading H1, body is everything after it.\n *\n * Only the first non-empty line is considered: an H1 further down belongs to\n * the body (issue descriptions routinely use headings), so promoting it would\n * silently retitle the Issue.\n */\nexport function parseIssueMarkdown(content: string): { title: string; body: string } {\n const lines = content.replace(/\\r\\n?/g, '\\n').split('\\n');\n const headingIndex = lines.findIndex((line) => line.trim().length > 0);\n const heading = headingIndex === -1 ? undefined : lines[headingIndex].match(/^#[ \\t]+(.*)$/);\n\n if (!heading) {\n return { title: '', body: lines.join('\\n').trim() };\n }\n\n return {\n title: heading[1].trim(),\n body: lines\n .slice(headingIndex + 1)\n .join('\\n')\n .trim(),\n };\n}\n\nfunction renderIssueMarkdown(title: string, body: string): string {\n return `# ${title}\\n\\n${body.trim()}\\n`;\n}\n\n/**\n * Issue provider backed by plain files in the project's global storage\n * directory (`~/.issue-flow/projects/<project-id>/issues/<id>/`).\n *\n * Enables the whole pipeline without any network access: no gh, no remote, no\n * authentication. `issue.md` is the source of truth for the content and\n * `metadata.json` for everything else; the content hash is always recomputed\n * from the file so a hand-edited issue.md is never reported as unchanged.\n *\n * Every path goes through `resolveIssuePaths()`, exactly like the pipeline\n * commands, so an issue that still only exists under the legacy\n * `<projectRoot>/issues/` tree is migrated on first read instead of coming back\n * as \"not found\".\n */\nexport class LocalFileIssueProvider implements IssueProvider {\n readonly name = 'local' as const;\n\n private readonly configuredRoot?: string;\n private cachedRoot?: string;\n\n /**\n * @param projectRoot Repository the issues belong to. It is no longer the\n * literal parent of an `issues/` directory: it is the root the project id —\n * and therefore the global storage directory — is derived from.\n */\n constructor(projectRoot?: string) {\n this.configuredRoot = projectRoot;\n }\n\n /**\n * True whenever the project's global storage directory already is — or\n * could be — a writable directory. Never mutates the filesystem, never\n * throws.\n *\n * A brand new project has no directory of its own until something writes, so\n * \"does it already exist\" would report the provider as unavailable exactly\n * when it is about to create the very first issue — `isWritableDirectory`\n * walks up to the nearest existing ancestor instead of requiring the leaf to\n * be there already.\n */\n async isAvailable(): Promise<boolean> {\n try {\n const { projectDir } = await resolveProjectPaths({ projectRoot: await this.root() });\n return await isWritableDirectory(projectDir);\n } catch {\n return false;\n }\n }\n\n async get(id: string): Promise<Issue | null> {\n const issueId = normalizeId(id);\n const markdownPath = await this.issueFile(issueId);\n\n let raw: string;\n try {\n raw = await readFile(markdownPath, 'utf-8');\n } catch (err: unknown) {\n if (isNotFound(err)) return null;\n throw err;\n }\n\n const { title: headingTitle, body } = parseIssueMarkdown(raw);\n const metadata = await this.readMetadata(issueId);\n const title = headingTitle || metadata?.title || '';\n\n if (metadata) {\n return {\n id: metadata.id,\n number: metadata.number,\n title,\n body,\n labels: metadata.labels,\n state: metadata.state,\n source: 'local',\n remoteRef: metadata.remote?.ref ?? null,\n createdAt: metadata.createdAt,\n updatedAt: metadata.updatedAt,\n contentHash: hashIssueContent(title, body),\n raw: metadata,\n };\n }\n\n // metadata.json is optional: an issue.md dropped in by hand still works,\n // with timestamps taken from the file itself.\n const stats = await stat(markdownPath);\n return {\n id: issueId,\n number: toNumber(issueId),\n title,\n body,\n labels: [],\n state: 'open',\n source: 'local',\n remoteRef: null,\n createdAt: stats.birthtime.toISOString(),\n updatedAt: stats.mtime.toISOString(),\n contentHash: hashIssueContent(title, body),\n };\n }\n\n async create(draft: IssueDraft): Promise<Issue> {\n // An explicit id is how a mirror keeps the identifier of the Issue it\n // mirrors: allocating a fresh one would make `issue-flow run <n>` see two\n // unrelated Issues instead of one demand in two places.\n const id = draft.id === undefined ? String(await this.allocateNumber()) : normalizeId(draft.id);\n const paths = await this.paths(id);\n\n await mkdir(paths.issueDir, { recursive: true });\n\n // Exclusive create (the 'wx' flag, O_EXCL under the hood) instead of a\n // check-then-write: two concurrent `create()` calls racing the same id\n // would both pass a plain existence check before either writes, and the\n // second would then silently overwrite the first through the atomic\n // temp+rename writer. The OS now rejects the loser instead.\n try {\n await writeFile(paths.issueFile, renderIssueMarkdown(draft.title, draft.body), {\n encoding: 'utf-8',\n flag: 'wx',\n });\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'EEXIST') {\n throw new Error(\n `Local issue '${id}' already exists at ${paths.issueFile}. ` +\n 'Remove it or pick another identifier before creating a new Issue.',\n );\n }\n throw err;\n }\n\n const timestamp = isoNow();\n const metadata: IssueMetadata = {\n schemaVersion: 1,\n id,\n number: toNumber(id),\n source: 'local',\n title: draft.title,\n labels: draft.labels,\n state: 'open',\n createdAt: timestamp,\n updatedAt: timestamp,\n contentHash: hashIssueContent(draft.title, draft.body),\n ...(draft.remote ? { remote: draft.remote } : {}),\n };\n\n await this.writeMetadata(id, metadata);\n\n return {\n id,\n number: metadata.number,\n title: draft.title,\n body: draft.body.trim(),\n labels: draft.labels,\n state: 'open',\n source: 'local',\n remoteRef: draft.remote?.ref ?? null,\n createdAt: timestamp,\n updatedAt: timestamp,\n contentHash: metadata.contentHash,\n raw: metadata,\n };\n }\n\n async close(id: string): Promise<void> {\n const issue = await this.get(id);\n if (!issue) {\n const issueDir = (await this.paths(normalizeId(id))).issueDir;\n throw new Error(`Local issue '${normalizeId(id)}' not found at ${issueDir}`);\n }\n\n const issueId = normalizeId(id);\n const existing = await this.readMetadata(issueId);\n\n await this.writeMetadata(issueId, {\n schemaVersion: 1,\n id: issue.id,\n number: issue.number,\n source: existing?.source ?? 'local',\n title: issue.title,\n labels: issue.labels,\n state: 'closed',\n createdAt: issue.createdAt,\n updatedAt: isoNow(),\n contentHash: issue.contentHash,\n ...(existing?.remote ? { remote: existing.remote } : {}),\n });\n }\n\n /**\n * Next free identifier: above every local number and, when GitHub answers,\n * above every remote one too. Sharing a numbering space with the remote is\n * what makes a naive `localMax + 1` collide the moment someone opens an Issue\n * on GitHub.\n */\n async allocateNumber(): Promise<number> {\n const [local, remote] = await Promise.all([this.highestLocalNumber(), highestRemoteNumber()]);\n return Math.max(local, remote) + 1;\n }\n\n private async root(): Promise<string> {\n if (this.configuredRoot !== undefined) return this.configuredRoot;\n this.cachedRoot ??= await getProjectRoot();\n return this.cachedRoot;\n }\n\n /**\n * Every artifact of one issue, from the same resolver the pipeline commands\n * use — which is also what triggers the migration of a legacy-only issue.\n */\n private async paths(id: string): Promise<IssuePaths> {\n return resolveIssuePaths(id, { projectRoot: await this.root() });\n }\n\n private async issueFile(id: string): Promise<string> {\n return (await this.paths(id)).issueFile;\n }\n\n private async metadataFile(id: string): Promise<string> {\n return (await this.paths(id)).metadataFile;\n }\n\n /** Parsed metadata.json, or `null` when the file is absent. */\n private async readMetadata(id: string): Promise<IssueMetadata | null> {\n const path = await this.metadataFile(id);\n\n let raw: string;\n try {\n raw = await readFile(path, 'utf-8');\n } catch (err: unknown) {\n if (isNotFound(err)) return null;\n throw err;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err: unknown) {\n throw new Error(`Invalid JSON in ${path}: ${(err as Error).message}`);\n }\n\n try {\n return issueMetadataSchema.parse(parsed);\n } catch (err: unknown) {\n if (err instanceof ZodError) {\n const details = err.issues\n .map((issue) => ` - ${issue.path.join('.') || '(root)'}: ${issue.message}`)\n .join('\\n');\n throw new Error(`Invalid issue metadata at ${path}:\\n${details}`);\n }\n throw err;\n }\n }\n\n private async writeMetadata(id: string, metadata: IssueMetadata): Promise<void> {\n await writeFileAtomic(await this.metadataFile(id), `${JSON.stringify(metadata, null, 2)}\\n`);\n }\n\n /**\n * Highest number across every `<issuesDir>/<id>/metadata.json` and numeric\n * directory name.\n *\n * Resolving `issuesDir` also migrates the legacy tree when it is the only one\n * that exists, which is what keeps an already-taken number from being handed\n * out a second time after adopting the global storage.\n */\n private async highestLocalNumber(): Promise<number> {\n const { issuesDir: dir } = await resolveProjectPaths({ projectRoot: await this.root() });\n\n let entries: string[];\n try {\n entries = (await readdir(dir, { withFileTypes: true }))\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name);\n } catch (err: unknown) {\n if (isNotFound(err)) return 0;\n throw err;\n }\n\n const numbers = await Promise.all(\n entries.map(async (name) => {\n const fromName = toNumber(name) ?? 0;\n // A directory whose metadata is unreadable still occupies its number.\n const fromMetadata = await this.readMetadata(name)\n .then((metadata) => metadata?.number ?? 0)\n .catch(() => 0);\n return Math.max(fromName, fromMetadata);\n }),\n );\n\n return numbers.reduce((max, value) => Math.max(max, value), 0);\n }\n}\n\n/** How many of the most-recently-created issues/PRs to inspect per probe. */\nconst REMOTE_PROBE_SAMPLE_SIZE = 20;\n\n/**\n * Highest number already taken on GitHub, or 0 when the remote is unreachable.\n *\n * Issues and pull requests share one counter, so both are probed: allocating\n * above the newest Issue alone would still collide with an open PR. Every\n * failure degrades to 0 — being offline must not block local creation.\n *\n * `gh ... list` defaults to sorting by creation date descending, which lines\n * up with number order in the overwhelming majority of repos — but that sort\n * is an implementation detail, not a contract. Rather than trust that the\n * single most-recent entry is also the highest-numbered one, a small sample\n * is fetched and the max is taken across it, which also tolerates the rare\n * case of a transferred issue whose creation date and number disagree.\n */\nasync function highestRemoteNumber(): Promise<number> {\n const probes = [\n ['issue', 'list'],\n ['pr', 'list'],\n ];\n\n const results = await Promise.all(\n probes.map(async (args) => {\n try {\n const result = await run(\n 'gh',\n [\n ...args,\n '--state',\n 'all',\n '--limit',\n String(REMOTE_PROBE_SAMPLE_SIZE),\n '--json',\n 'number',\n ],\n { timeout: REMOTE_PROBE_TIMEOUT_MS },\n );\n if (result.exitCode !== 0) return 0;\n\n const parsed = JSON.parse(result.stdout);\n if (!Array.isArray(parsed)) return 0;\n return parsed.reduce((max: number, entry: unknown) => {\n const n = (entry as { number?: unknown } | null)?.number;\n return typeof n === 'number' ? Math.max(max, n) : max;\n }, 0);\n } catch {\n return 0;\n }\n }),\n );\n\n return results.reduce((max, value) => Math.max(max, value), 0);\n}\n\n/** Shared instance resolving the project root lazily via git. */\nexport const localFileIssueProvider = new LocalFileIssueProvider();\n","import { githubIssueProvider } from './providers/github.js';\nimport { localFileIssueProvider } from './providers/local.js';\nimport { getRegisteredSources, registerProvider } from './registry.js';\n\n/**\n * Register the providers that ship with issue-flow.\n *\n * Idempotent and non-destructive: an origin that is already registered is left\n * untouched, so a test (or a future plugin) can install its own provider before\n * the first `resolveIssue` call without having it replaced by the built-in one.\n */\nexport function ensureProvidersRegistered(): void {\n const registered = new Set(getRegisteredSources());\n\n if (!registered.has('github')) {\n registerProvider(githubIssueProvider);\n }\n if (!registered.has('local')) {\n registerProvider(localFileIssueProvider);\n }\n}\n","import { createInterface, type Interface as ReadlineInterface } from 'node:readline';\nimport { loadIssuesConfig } from '../config.js';\nimport { printInfo, printWarning } from '../ui/logger.js';\nimport { ensureProvidersRegistered } from './bootstrap.js';\nimport { getProvider, getRegisteredSources } from './registry.js';\nimport type { Issue, IssueSource, IssuesConfig, ResolvedIssue } from './types.js';\n\n/**\n * Failure to settle on an Issue. Carries the exit code the CLI should return,\n * so callers propagate it instead of inventing their own.\n */\nexport class IssueResolutionError extends Error {\n readonly exitCode: number;\n\n constructor(message: string, exitCode = 1) {\n super(message);\n this.name = 'IssueResolutionError';\n this.exitCode = exitCode;\n }\n}\n\nexport interface ResolveIssueOptions {\n /** Already-resolved provider configuration. Defaults to loadIssuesConfig(). */\n config?: IssuesConfig;\n /** Origins to query. Defaults to every registered source. */\n sources?: IssueSource[];\n /**\n * Whether a prompt may be shown. Defaults to a real TTY outside CI, which is\n * what keeps `ask` from ever blocking a headless run.\n */\n interactive?: boolean;\n /** Input stream for the conflict prompt. Defaults to process.stdin. */\n stdin?: NodeJS.ReadableStream;\n /** Output stream for the conflict prompt. Defaults to process.stdout. */\n stdout?: NodeJS.WritableStream;\n /** Informational sink. Defaults to printInfo. */\n info?: (message: string) => void;\n /** Warning sink. Defaults to printWarning. */\n warn?: (message: string) => void;\n}\n\n/** How many invalid answers are tolerated before the prompt gives up. */\nconst MAX_PROMPT_ATTEMPTS = 3;\n\n/**\n * Labels shown to users for the built-in origins. An origin registered from\n * outside this package is displayed under its own name, so a new provider needs\n * no entry here.\n */\nconst SOURCE_LABELS: Record<string, string> = {\n github: 'GitHub',\n local: 'local',\n};\n\nfunction sourceLabel(source: IssueSource): string {\n return SOURCE_LABELS[source] ?? source;\n}\n\n/** Same label, capitalized for the numbered prompt ('local' -> 'Local'). */\nfunction promptLabel(source: IssueSource): string {\n const label = sourceLabel(source);\n return label.charAt(0).toUpperCase() + label.slice(1);\n}\n\ninterface Candidate {\n source: IssueSource;\n issue: Issue | null;\n /** Why the origin produced nothing, used only to explain a total miss. */\n reason: string | null;\n}\n\n/** A candidate that actually produced an Issue. */\ninterface FoundCandidate extends Candidate {\n issue: Issue;\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Read one origin without letting it break the others.\n *\n * An unavailable provider or a failed read degrades to \"no candidate\" plus a\n * reason: as long as another origin has the Issue the pipeline keeps going, and\n * when nothing is found the reasons are surfaced in the final error so a broken\n * environment is never reported as a missing Issue.\n */\nasync function fetchCandidate(\n source: IssueSource,\n id: string,\n warn: (message: string) => void,\n): Promise<Candidate> {\n let provider: ReturnType<typeof getProvider>;\n try {\n provider = getProvider(source);\n } catch (err) {\n return { source, issue: null, reason: errorMessage(err) };\n }\n\n let available: boolean;\n try {\n available = await provider.isAvailable();\n } catch (err) {\n return { source, issue: null, reason: `provider unavailable (${errorMessage(err)})` };\n }\n if (!available) {\n return { source, issue: null, reason: 'provider unavailable' };\n }\n\n try {\n const issue = await provider.get(id);\n return { source, issue, reason: issue === null ? 'not found' : null };\n } catch (err) {\n const reason = errorMessage(err);\n // A real failure (network, auth, corrupted metadata) must be visible even\n // when the other origin answers.\n warn(`Could not read issue '${id}' from ${sourceLabel(source)}: ${reason}`);\n return { source, issue: null, reason };\n }\n}\n\nfunction shortHash(hash: string): string {\n const hex = hash.startsWith('sha256:') ? hash.slice('sha256:'.length) : hash;\n return hex.slice(0, 12);\n}\n\n/** One line per origin describing what differs, without dumping every body. */\nfunction describeCandidate(source: IssueSource, issue: Issue): string {\n const lines = issue.body.length === 0 ? 0 : issue.body.split('\\n').length;\n return (\n ` ${sourceLabel(source).padEnd(6)} title: \"${issue.title}\" | body: ${lines} line(s), ` +\n `${issue.body.length} char(s) | updated: ${issue.updatedAt} | hash: ${shortHash(issue.contentHash)}`\n );\n}\n\n/** 'local and GitHub', 'local, GitHub and memory' — origins in query order. */\nfunction listSources(candidates: FoundCandidate[]): string {\n const labels = candidates.map((candidate) => sourceLabel(candidate.source));\n if (labels.length <= 1) {\n return labels.join('');\n }\n return `${labels.slice(0, -1).join(', ')} and ${labels[labels.length - 1]}`;\n}\n\n/**\n * Turn a readline interface into an awaitable line reader.\n *\n * Lines are queued instead of read on demand: `rl.question` drops whatever\n * arrives between two questions, which silently loses a piped answer typed\n * ahead of the prompt. Resolves `null` once the input is exhausted, so EOF ends\n * the prompt instead of hanging the process.\n */\nfunction createLineReader(\n rl: ReadlineInterface,\n output: NodeJS.WritableStream,\n): (query: string) => Promise<string | null> {\n const queued: string[] = [];\n let pending: ((line: string | null) => void) | null = null;\n let closed = false;\n\n rl.on('line', (line: string) => {\n if (pending !== null) {\n const resolve = pending;\n pending = null;\n resolve(line);\n return;\n }\n queued.push(line);\n });\n rl.on('close', () => {\n closed = true;\n if (pending !== null) {\n const resolve = pending;\n pending = null;\n resolve(null);\n }\n });\n\n return (query: string) =>\n new Promise<string | null>((resolve) => {\n const buffered = queued.shift();\n if (buffered !== undefined) {\n resolve(buffered);\n return;\n }\n if (closed) {\n resolve(null);\n return;\n }\n output.write(query);\n pending = resolve;\n });\n}\n\n/**\n * Interactive choice between the divergent versions.\n *\n * The options are numbered from the origins that actually answered, so a third\n * provider simply shows up as `[3] Memory` without this function knowing which\n * origins exist. Cancel is always the last option.\n */\nasync function promptChoice(\n sources: IssueSource[],\n stdin: NodeJS.ReadableStream,\n stdout: NodeJS.WritableStream,\n warn: (message: string) => void,\n): Promise<IssueSource | 'cancel'> {\n const options = sources.map((source, index) => `[${index + 1}] ${promptLabel(source)}`);\n const cancelOption = sources.length + 1;\n const query = `Which version should be used? ${options.join(' ')} [${cancelOption}] Cancel: `;\n const numbers = Array.from({ length: cancelOption }, (_, index) => String(index + 1));\n const accepted = `${numbers.slice(0, -1).join(', ')} or ${numbers[numbers.length - 1]}`;\n\n const rl = createInterface({ input: stdin, output: stdout });\n const ask = createLineReader(rl, stdout);\n try {\n for (let attempt = 0; attempt < MAX_PROMPT_ATTEMPTS; attempt++) {\n const answer = await ask(query);\n if (answer === null) {\n return 'cancel';\n }\n const choice = answer.trim();\n const picked = sources[Number(choice) - 1];\n if (choice.length > 0 && picked !== undefined) {\n return picked;\n }\n if (choice === String(cancelOption)) {\n return 'cancel';\n }\n warn(`Invalid choice: '${choice}'. Enter ${accepted}.`);\n }\n return 'cancel';\n } finally {\n rl.close();\n }\n}\n\nfunction isInteractiveByDefault(): boolean {\n const ci = process.env.CI;\n const inCi = ci !== undefined && ci !== '' && ci !== '0' && ci.toLowerCase() !== 'false';\n return Boolean(process.stdin.isTTY) && !inCi;\n}\n\nfunction buildResolved(\n issue: Issue,\n source: IssueSource,\n local: Issue | null,\n github: Issue | null,\n divergent: boolean,\n): ResolvedIssue {\n return { issue, source, local, github, divergent };\n}\n\n/** Origin `conflictPolicy` points at, or `null` for 'ask'. */\nfunction policyTarget(policy: IssuesConfig['conflictPolicy']): IssueSource | null {\n if (policy === 'prefer-local') {\n return 'local';\n }\n if (policy === 'prefer-github') {\n return 'github';\n }\n return null;\n}\n\n/**\n * Single entry point every command uses to decide which Issue the pipeline\n * works on.\n *\n * The logic is written against the origins that answered, never against a fixed\n * list of sources: registering a new provider is enough for it to take part in\n * the resolution, be reported in a divergence and appear in the prompt.\n *\n * Scenarios:\n * - only one origin has it -> that one, no questions asked;\n * - several, same contentHash -> equivalence is reported and the preferred\n * origin wins, without a prompt;\n * - several, different content -> the divergence is reported and\n * `conflictPolicy` decides (`ask` prompts on a TTY, falls back to\n * `preferredProvider` with a warning anywhere else);\n * - none -> IssueResolutionError, which carries the CLI exit code.\n */\nexport async function resolveIssue(\n id: string,\n opts: ResolveIssueOptions = {},\n): Promise<ResolvedIssue> {\n const info = opts.info ?? printInfo;\n const warn = opts.warn ?? printWarning;\n const config = opts.config ?? (await loadIssuesConfig({ warn }));\n\n ensureProvidersRegistered();\n const sources = opts.sources ?? getRegisteredSources();\n\n // Each origin is an independent I/O call (network for GitHub, disk for\n // local); querying them concurrently instead of one-by-one keeps the total\n // latency at the slowest origin instead of the sum of all of them, without\n // changing which candidate wins (order is preserved by Promise.all).\n const candidates: Candidate[] = await Promise.all(\n sources.map((source) => fetchCandidate(source, id, warn)),\n );\n\n const issueOf = (source: IssueSource): Issue | null =>\n candidates.find((candidate) => candidate.source === source)?.issue ?? null;\n const local = issueOf('local');\n const github = issueOf('github');\n\n const found = candidates.filter(\n (candidate): candidate is FoundCandidate => candidate.issue !== null,\n );\n\n if (found.length === 0) {\n const details = candidates\n .map((candidate) => `${sourceLabel(candidate.source)}: ${candidate.reason ?? 'not found'}`)\n .join('; ');\n const where = details.length > 0 ? ` (${details})` : '';\n throw new IssueResolutionError(`Issue '${id}' not found in any registered origin${where}`);\n }\n\n const build = (candidate: FoundCandidate, divergent: boolean): ResolvedIssue =>\n buildResolved(candidate.issue, candidate.source, local, github, divergent);\n\n const firstFound = found[0] as FoundCandidate;\n if (found.length === 1) {\n return build(firstFound, false);\n }\n\n // Several origins have it. The preferred one wins whenever it is among them;\n // otherwise the first origin queried does, so an unrelated preference never\n // leaves the pipeline without an Issue.\n const preferred =\n found.find((candidate) => candidate.source === config.preferredProvider) ?? firstFound;\n\n const distinct = new Set(found.map((candidate) => candidate.issue.contentHash));\n if (distinct.size === 1) {\n info(\n `Issue '${id}' has identical content in ${listSources(found)}; using ${sourceLabel(preferred.source)}.`,\n );\n return build(preferred, false);\n }\n\n info(`Issue '${id}' differs between origins:`);\n for (const candidate of found) {\n info(describeCandidate(candidate.source, candidate.issue));\n }\n\n const target = policyTarget(config.conflictPolicy);\n if (target !== null) {\n const chosen = found.find((candidate) => candidate.source === target);\n if (chosen !== undefined) {\n info(`Conflict policy '${config.conflictPolicy}': using the ${sourceLabel(target)} version.`);\n return build(chosen, true);\n }\n // The policy names an origin that has no version of this Issue: say so\n // instead of silently picking for the user under its name.\n warn(\n `Conflict policy '${config.conflictPolicy}' does not apply to Issue '${id}' ` +\n `(${sourceLabel(target)} has no version of it); using ${sourceLabel(preferred.source)}.`,\n );\n return build(preferred, true);\n }\n\n const interactive = opts.interactive ?? isInteractiveByDefault();\n if (!interactive) {\n warn(\n `Divergent Issue '${id}' and conflict policy 'ask' in a non-interactive environment; ` +\n `using the preferred provider (${sourceLabel(preferred.source)}).`,\n );\n return build(preferred, true);\n }\n\n const choice = await promptChoice(\n found.map((candidate) => candidate.source),\n opts.stdin ?? process.stdin,\n opts.stdout ?? process.stdout,\n warn,\n );\n if (choice === 'cancel') {\n throw new IssueResolutionError(\n `Cancelled: Issue '${id}' diverges between ${listSources(found)}.`,\n );\n }\n const picked = found.find((candidate) => candidate.source === choice) as FoundCandidate;\n return build(picked, true);\n}\n","import { printError } from '../ui/logger.js';\nimport { IssueResolutionError, type ResolveIssueOptions, resolveIssue } from './resolver.js';\nimport type { Issue, ResolvedIssue } from './types.js';\n\n/**\n * Bridge between the resolved Issue and the phase prompts.\n *\n * Commands never fetch the Issue themselves: they resolve it once through\n * `resolveIssue` and hand the content to the template, so every phase sees the\n * exact same title/body regardless of where the demand came from.\n */\n\n/** Path of the markdown file a local Issue lives in. */\nexport function localIssueRef(id: string): string {\n return `issues/${id}/issue.md`;\n}\n\n/**\n * Reference a human (or an agent) can follow to read the Issue: the remote URL\n * when there is one, the local file otherwise.\n */\nexport function issueReference(issue: Issue): string {\n return issue.remoteRef ?? localIssueRef(issue.id);\n}\n\n/** Shown instead of an empty list so the prompt never renders a dangling label. */\nconst NO_LABELS = '(none)';\n\n/**\n * Placeholder values every phase template consumes, replacing the former\n * `gh issue view` instruction.\n */\nexport function issuePlaceholders(resolved: ResolvedIssue): Record<string, string> {\n const { issue } = resolved;\n return {\n __ISSUE_TITLE__: issue.title,\n __ISSUE_BODY__: issue.body,\n __ISSUE_LABELS__: issue.labels.length > 0 ? issue.labels.join(', ') : NO_LABELS,\n __ISSUE_SOURCE__: resolved.source,\n __ISSUE_URL__: issueReference(issue),\n };\n}\n\nexport type CommandIssue = { ok: true; resolved: ResolvedIssue } | { ok: false; code: number };\n\n/**\n * Resolve the Issue a command works on, turning a resolution failure into the\n * exit code the command returns.\n *\n * `preResolved` short-circuits the lookup: the pipeline decides the origin once\n * and passes the decision down, so a phase never re-queries the providers (and\n * never asks the user twice about the same divergence).\n *\n * `options` forwards resolver options — `run.ts` passes the configuration it\n * already loaded so `.issue-flow.json` is read (and warned about) only once.\n */\nexport async function resolveCommandIssue(\n id: string,\n preResolved?: ResolvedIssue,\n options?: ResolveIssueOptions,\n): Promise<CommandIssue> {\n if (preResolved !== undefined) {\n return { ok: true, resolved: preResolved };\n }\n\n try {\n return { ok: true, resolved: await resolveIssue(id, options) };\n } catch (err) {\n if (err instanceof IssueResolutionError) {\n printError(err.message);\n return { ok: false, code: err.exitCode };\n }\n const message = err instanceof Error ? err.message : String(err);\n printError(`Could not resolve issue '${id}': ${message}`);\n return { ok: false, code: 1 };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAUA,IAAM,YAAY,oBAAI,IAAgC;AAQ/C,SAAS,iBAAiB,UAA+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C;AAAA,IACjE;AAAA,EACF;AACA,QAAM,SAAS,MAAM,KAAK,CAAC,cAAc,UAAU,WAAW,MAAM;AACpE,SAAO,MAAM,QAAQ,IAAI;AAC3B;;;AClXO,SAAS,cAAc,IAAoB;AAChD,SAAO,UAAU,EAAE;AACrB;AAMO,SAAS,eAAe,OAAsB;AACnD,SAAO,MAAM,aAAa,cAAc,MAAM,EAAE;AAClD;AAGA,IAAM,YAAY;AAMX,SAAS,kBAAkB,UAAiD;AACjF,QAAM,EAAE,MAAM,IAAI;AAClB,SAAO;AAAA,IACL,iBAAiB,MAAM;AAAA,IACvB,gBAAgB,MAAM;AAAA,IACtB,kBAAkB,MAAM,OAAO,SAAS,IAAI,MAAM,OAAO,KAAK,IAAI,IAAI;AAAA,IACtE,kBAAkB,SAAS;AAAA,IAC3B,eAAe,eAAe,KAAK;AAAA,EACrC;AACF;AAeA,eAAsB,oBACpB,IACA,aACA,SACuB;AACvB,MAAI,gBAAgB,QAAW;AAC7B,WAAO,EAAE,IAAI,MAAM,UAAU,YAAY;AAAA,EAC3C;AAEA,MAAI;AACF,WAAO,EAAE,IAAI,MAAM,UAAU,MAAM,aAAa,IAAI,OAAO,EAAE;AAAA,EAC/D,SAAS,KAAK;AACZ,QAAI,eAAe,sBAAsB;AACvC,iBAAW,IAAI,OAAO;AACtB,aAAO,EAAE,IAAI,OAAO,MAAM,IAAI,SAAS;AAAA,IACzC;AACA,UAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,eAAW,4BAA4B,EAAE,MAAM,OAAO,EAAE;AACxD,WAAO,EAAE,IAAI,OAAO,MAAM,EAAE;AAAA,EAC9B;AACF;","names":["normalizeId"]}
@@ -1,27 +1,29 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  runPhaseWithRetry
4
- } from "./chunk-UUY4PCWW.js";
4
+ } from "./chunk-3BOHTH4V.js";
5
5
  import {
6
6
  issuePlaceholders,
7
7
  resolveCommandIssue
8
- } from "./chunk-S67Q4I2O.js";
8
+ } from "./chunk-AAY6KM7N.js";
9
+ import {
10
+ DEFAULT_HEADLESS_TIMEOUT_MS,
11
+ runHeadless
12
+ } from "./chunk-EWDJENFW.js";
9
13
  import {
10
14
  isTransientFailure
11
15
  } from "./chunk-HDV3YDTG.js";
12
16
  import {
13
- runHeadless
14
- } from "./chunk-MXTGCD5C.js";
15
- import {
16
- publishPhaseMetrics
17
- } from "./chunk-PPLIXZI5.js";
17
+ publishPhaseMetrics,
18
+ resolvePolicyPlaceholders
19
+ } from "./chunk-OBLVLIUS.js";
18
20
  import {
19
21
  applyPlaceholders,
20
22
  loadPrompt
21
- } from "./chunk-SLHZPB3C.js";
23
+ } from "./chunk-HQYXVIH6.js";
22
24
  import {
23
25
  resolveIssuePaths
24
- } from "./chunk-VYFKOUUR.js";
26
+ } from "./chunk-VQ5VN7DF.js";
25
27
  import {
26
28
  getGlobalTimeout,
27
29
  isoNow,
@@ -29,7 +31,7 @@ import {
29
31
  printError,
30
32
  printSuccess,
31
33
  saveTaskPlan
32
- } from "./chunk-V5OHFSW4.js";
34
+ } from "./chunk-HC2MT7BX.js";
33
35
 
34
36
  // src/commands/pr.ts
35
37
  import { execa } from "execa";
@@ -110,6 +112,9 @@ async function runPr(issue, resolvedIssue, options = {}) {
110
112
  const consolidating = queue !== void 0 && queue.issues.length > 1;
111
113
  const template = await loadPrompt("pr");
112
114
  const prompt = applyPlaceholders(template, {
115
+ // The repository's own conventions. Empty when it declares none, which is
116
+ // what keeps the rendered prompt identical to the pre-policy one.
117
+ ...await resolvePolicyPlaceholders(),
113
118
  __ISSUE_NUMBER__: issueNumber,
114
119
  __BRANCH_NAME__: branchName,
115
120
  __TASKS_PATH__: tasksPath,
@@ -125,7 +130,7 @@ async function runPr(issue, resolvedIssue, options = {}) {
125
130
  const result = await runHeadless({
126
131
  prompt,
127
132
  maxTurns: 15,
128
- timeout: getGlobalTimeout() ?? 3e5,
133
+ timeout: getGlobalTimeout() ?? DEFAULT_HEADLESS_TIMEOUT_MS,
129
134
  // json (not text) so the CLI reports usage: the envelope's `result`
130
135
  // field carries the same assistant text parsePrUrl() already consumed.
131
136
  outputFormat: "json",
@@ -178,4 +183,4 @@ export {
178
183
  multiIssueContext,
179
184
  runPr
180
185
  };
181
- //# sourceMappingURL=chunk-2LNQL4XH.js.map
186
+ //# sourceMappingURL=chunk-BXCPXRBR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/pr.ts"],"sourcesContent":["import { execa } from 'execa';\nimport { DEFAULT_HEADLESS_TIMEOUT_MS, runHeadless } from '../core/headless.js';\nimport { runPhaseWithRetry } from '../core/phase-runner.js';\nimport { applyPlaceholders, loadPrompt } from '../core/prompt-resolver.js';\nimport { publishPhaseMetrics } from '../core/session-metrics.js';\nimport { isoNow, loadTaskPlan, saveTaskPlan } from '../core/state-manager.js';\nimport { getGlobalTimeout } from '../core/verbose.js';\nimport { issuePlaceholders, resolveCommandIssue } from '../issues/context.js';\nimport type { Issue, IssueSource, ResolvedIssue } from '../issues/types.js';\nimport { resolvePolicyPlaceholders } from '../policy/placeholders.js';\nimport { resolveIssuePaths } from '../storage/resolve.js';\nimport { printError, printSuccess } from '../ui/logger.js';\nimport { isTransientFailure } from '../utils/retry.js';\n\n/**\n * Extract a PR URL from headless output.\n */\nfunction parsePrUrl(output: string): string | null {\n const match = output.match(/(https:\\/\\/github\\.com\\/[^\\s]+\\/pull\\/\\d+)/);\n return match?.[1] ?? null;\n}\n\n/**\n * The numeric id inside a PR URL, so later phases (`pr-review`) address the\n * Pull Request without querying GitHub again.\n */\nfunction parsePrNumber(url: string): number | null {\n const match = url.match(/\\/pull\\/(\\d+)/);\n return match?.[1] === undefined ? null : Number(match[1]);\n}\n\n/**\n * The `Closes #N` line for the PR body, empty when the Issue has no remote\n * counterpart: GitHub only understands the reference for Issues it hosts, and\n * an invented `#N` would silently point at an unrelated Issue.\n */\nfunction issueClosesLine(issue: Issue, fallbackId: string): string {\n if (issue.remoteRef === null) {\n return '';\n }\n return `Closes #${issue.number ?? fallbackId}`;\n}\n\n/** One Issue of a queue, as the consolidated Pull Request has to describe it. */\nexport interface PrQueueIssue {\n id: string;\n number: number | null;\n title: string;\n /** `null` when the Issue was never read — see {@link issueClosesLines}. */\n url: string | null;\n /** Origin the Issue came from; `github` is what GitHub can close. */\n source: IssueSource;\n}\n\n/**\n * What a multi-issue queue hands to the `pr` phase.\n *\n * Absent for every standalone run, and that absence is what guarantees the\n * single-issue Pull Request is byte-for-byte the one this command has always\n * produced: the extra placeholders resolve to empty strings.\n */\nexport interface PrQueueContext {\n /** Issues of the queue, in the order they were executed. */\n issues: PrQueueIssue[];\n /** Issues discovered but not executed, with the reason. */\n excluded: { id: string; number: number | null; title: string; reason: string }[];\n /** Anything else worth reporting as pending (unresolved review findings). */\n pending: string[];\n}\n\nexport interface RunPrOptions {\n /** Set only when the Pull Request consolidates a queue. */\n queue?: PrQueueContext;\n}\n\n/** `#51` when the Issue has a number, its raw identifier otherwise. */\nfunction issueRef(entry: { id: string; number: number | null }): string {\n return entry.number === null ? entry.id : `#${entry.number}`;\n}\n\n/**\n * Every `Closes #N` line of a consolidated Pull Request, one per line.\n *\n * Issues that GitHub does not host are skipped for the same reason a\n * single-issue Pull Request skips them — it cannot close what it does not\n * host — and a queue that mixes both origins still gets a valid body.\n *\n * The test is the origin and the number, not the URL: an Issue whose read\n * failed during discovery reaches the queue with `url: null`, and it is still\n * executed and still closed by the queue. Filtering on the URL would leave it\n * out of the very body that is supposed to reference it.\n */\nexport function issueClosesLines(issues: readonly PrQueueIssue[]): string {\n return issues\n .filter((entry) => entry.source === 'github' && entry.number !== null)\n .map((entry) => `Closes #${entry.number}`)\n .join('\\n');\n}\n\n/**\n * The extra instructions the prompt receives when the Pull Request covers a\n * whole queue.\n *\n * Returns `''` for a standalone run, which is what keeps `pr.md` rendering\n * exactly as before for the single-issue path — no empty \"Issues implemented\"\n * section, no redundant ordering of a list of one.\n */\nexport function multiIssueContext(queue: PrQueueContext | undefined): string {\n if (queue === undefined || queue.issues.length <= 1) {\n return '';\n }\n\n const order = queue.issues\n .map(\n (entry, index) => `${index + 1}. ${issueRef(entry)}${entry.title ? ` — ${entry.title}` : ''}`,\n )\n .join('\\n');\n\n const pending = [\n ...queue.excluded.map(\n (entry) => `- ${issueRef(entry)}${entry.title ? ` — ${entry.title}` : ''}: ${entry.reason}`,\n ),\n ...queue.pending.map((note) => `- ${note}`),\n ].join('\\n');\n\n return [\n '',\n 'This Pull Request consolidates several issues implemented on this same branch,',\n 'in this execution order:',\n '',\n order,\n '',\n 'The PR body MUST additionally contain:',\n '- an \"Issues implemented\" section listing every issue above, in that order,',\n ' with one line per issue describing what it delivered;',\n '- a \"Pending\" section with the items below, verbatim, plus anything you find',\n ' unfinished while reviewing the diff. Write \"None\" when the list below is',\n ' empty and you find nothing else;',\n '',\n pending === '' ? '(no known pending items)' : pending,\n '',\n 'The commits of this branch are scoped per issue (`feat(issue-N): …`), which is',\n 'how you tell which change belongs to which issue in `git log`.',\n ].join('\\n');\n}\n\nexport async function runPr(\n issue: string,\n resolvedIssue?: ResolvedIssue,\n options: RunPrOptions = {},\n): Promise<number> {\n const issueNumber = issue.replace(/^#/, '');\n const paths = await resolveIssuePaths(issueNumber);\n const tasksPath = paths.tasksFile;\n\n const resolution = await resolveCommandIssue(issueNumber, resolvedIssue);\n if (!resolution.ok) {\n return resolution.code;\n }\n\n // Get current branch\n let branchName: string;\n try {\n const proc = await execa('git', ['branch', '--show-current'], { reject: false });\n branchName = proc.stdout?.toString().trim() ?? '';\n if (!branchName) {\n printError('Could not determine current branch');\n return 1;\n }\n } catch {\n printError('Failed to get current branch');\n return 1;\n }\n\n const queue = options.queue;\n const consolidating = queue !== undefined && queue.issues.length > 1;\n\n const template = await loadPrompt('pr');\n const prompt = applyPlaceholders(template, {\n // The repository's own conventions. Empty when it declares none, which is\n // what keeps the rendered prompt identical to the pre-policy one.\n ...(await resolvePolicyPlaceholders()),\n __ISSUE_NUMBER__: issueNumber,\n __BRANCH_NAME__: branchName,\n __TASKS_PATH__: tasksPath,\n __ISSUE_CLOSES__: consolidating\n ? issueClosesLines(queue.issues)\n : issueClosesLine(resolution.resolved.issue, issueNumber),\n __MULTI_ISSUE_CONTEXT__: multiIssueContext(queue),\n ...issuePlaceholders(resolution.resolved),\n });\n\n let headlessOutput = '';\n\n const outcome = await runPhaseWithRetry({\n phase: 'pr',\n attempt: async () => {\n const startedAtMs = Date.now();\n const result = await runHeadless({\n prompt,\n maxTurns: 15,\n timeout: getGlobalTimeout() ?? DEFAULT_HEADLESS_TIMEOUT_MS,\n // json (not text) so the CLI reports usage: the envelope's `result`\n // field carries the same assistant text parsePrUrl() already consumed.\n outputFormat: 'json',\n allowedTools: ['Bash', 'Read', 'Glob', 'Grep'],\n addDirs: [paths.issueDir],\n statusMessage: `Creating PR for issue #${issueNumber}...`,\n });\n // One event per attempt; the reducer sums them into the phase total.\n publishPhaseMetrics('pr', result.cost, startedAtMs);\n\n if (!result.success) {\n return {\n ok: false,\n transient: isTransientFailure(1, result.error ?? ''),\n error: `PR creation failed: ${result.error}`,\n };\n }\n\n headlessOutput = result.result;\n return { ok: true };\n },\n });\n\n if (!outcome.ok) {\n printError(outcome.error ?? `PR creation failed for issue #${issueNumber}`);\n return 1;\n }\n\n const prUrl = parsePrUrl(headlessOutput);\n\n // Update pipeline state\n try {\n const plan = await loadTaskPlan(tasksPath);\n plan.pipeline.prCreated = true;\n const prNumber = prUrl === null ? null : parsePrNumber(prUrl);\n // Without a URL the PR is still assumed created (the phase succeeded), but\n // there is nothing trustworthy to record: an invented number would send\n // `pr-review` at an unrelated Pull Request.\n if (prUrl !== null && prNumber !== null) {\n plan.pullRequest = {\n number: prNumber,\n url: prUrl,\n headBranch: branchName,\n createdAt: isoNow(),\n };\n }\n await saveTaskPlan(tasksPath, plan);\n } catch {\n // tasks.json may not exist\n }\n\n if (prUrl) {\n printSuccess(`PR created: ${prUrl}`);\n } else {\n printSuccess('PR creation completed');\n }\n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K,EAAE;AAAA,EACrC,OAAO;AACL,iBAAa,uBAAuB;AAAA,EACtC;AACA,SAAO;AACT;","names":[]}
@@ -10,12 +10,28 @@ import {
10
10
  isoNow,
11
11
  parseUsage,
12
12
  useColor
13
- } from "./chunk-V5OHFSW4.js";
13
+ } from "./chunk-HC2MT7BX.js";
14
14
 
15
15
  // src/core/headless.ts
16
16
  import { createInterface } from "readline";
17
17
  import chalk from "chalk";
18
18
  import { execa } from "execa";
19
+ var DEFAULT_HEADLESS_TIMEOUT_MS = 9e5;
20
+ var TIMEOUT_ATTRIBUTION_RATIO = 0.9;
21
+ function reachedTimeout(timeoutMs, elapsedMs) {
22
+ return timeoutMs > 0 && elapsedMs >= timeoutMs * TIMEOUT_ATTRIBUTION_RATIO;
23
+ }
24
+ function wasTimedOut(proc, timeoutMs, elapsedMs) {
25
+ if (proc.timedOut === true) return true;
26
+ if (!reachedTimeout(timeoutMs, elapsedMs)) return false;
27
+ return proc.signal === "SIGTERM" || proc.signal === "SIGKILL" || proc.exitCode === 143 || proc.exitCode === 137;
28
+ }
29
+ function describeFailure(proc, diagnostics, timeoutMs, elapsedMs) {
30
+ if (wasTimedOut(proc, timeoutMs, elapsedMs)) {
31
+ return `Headless invocation timed out after ${formatDuration(Math.round(timeoutMs / 1e3))}. Raise the limit with --timeout <seconds> (0 = no limit).`;
32
+ }
33
+ return diagnostics.trim() || `claude exited with code ${proc.exitCode ?? "unknown"}`;
34
+ }
19
35
  function pushRepeatedFlag(args, flag, values) {
20
36
  if (!values || values.length === 0) return;
21
37
  for (const value of values) {
@@ -150,14 +166,11 @@ async function runHeadlessVerbose(options) {
150
166
  emit(doneLine);
151
167
  emit(connectorLine);
152
168
  if (proc.exitCode !== 0 && !resultText) {
153
- const stderr = proc.stderr?.toString() ?? "";
154
- const isTimeout = proc.exitCode === 143 || "signalName" in proc && proc.signalName === "SIGTERM";
155
- const errorMsg = isTimeout ? `Headless invocation timed out after ${timeout}ms` : stderr || `claude exited with code ${proc.exitCode}`;
156
169
  return {
157
170
  success: false,
158
171
  result: "",
159
172
  cost: null,
160
- error: errorMsg
173
+ error: describeFailure(proc, proc.stderr?.toString() ?? "", timeout, Date.now() - startTime)
161
174
  };
162
175
  }
163
176
  return {
@@ -171,7 +184,7 @@ async function runHeadless(options) {
171
184
  const {
172
185
  prompt,
173
186
  maxTurns = 10,
174
- timeout = 3e5,
187
+ timeout = DEFAULT_HEADLESS_TIMEOUT_MS,
175
188
  outputFormat = "json",
176
189
  allowedTools,
177
190
  addDirs,
@@ -190,6 +203,7 @@ async function runHeadless(options) {
190
203
  onOutput: effectiveOnOutput
191
204
  });
192
205
  }
206
+ const startTime = Date.now();
193
207
  const spinner = statusMessage ? createSpinner(statusMessage).start() : null;
194
208
  let timer = null;
195
209
  if (spinner) {
@@ -224,7 +238,7 @@ async function runHeadless(options) {
224
238
  success: false,
225
239
  result: "",
226
240
  cost: null,
227
- error: stderr || stdout || `claude exited with code ${proc.exitCode}`
241
+ error: describeFailure(proc, stderr || stdout, timeout, Date.now() - startTime)
228
242
  };
229
243
  }
230
244
  const elapsed = timer?.stop() ?? 0;
@@ -260,11 +274,17 @@ async function runHeadless(options) {
260
274
  const catchDur = useColor() ? chalk.dim(` (${formatDuration(catchElapsed)})`) : ` (${formatDuration(catchElapsed)})`;
261
275
  spinner?.fail(`${statusMessage}${catchDur}`);
262
276
  if (message.includes("timed out") || message.includes("ETIMEDOUT")) {
277
+ const elapsedMs = Date.now() - startTime;
263
278
  return {
264
279
  success: false,
265
280
  result: "",
266
281
  cost: null,
267
- error: `Headless invocation timed out after ${timeout}ms`
282
+ error: describeFailure(
283
+ { timedOut: reachedTimeout(timeout, elapsedMs) },
284
+ message,
285
+ timeout,
286
+ elapsedMs
287
+ )
268
288
  };
269
289
  }
270
290
  return {
@@ -277,6 +297,7 @@ async function runHeadless(options) {
277
297
  }
278
298
 
279
299
  export {
300
+ DEFAULT_HEADLESS_TIMEOUT_MS,
280
301
  runHeadless
281
302
  };
282
- //# sourceMappingURL=chunk-MXTGCD5C.js.map
303
+ //# sourceMappingURL=chunk-EWDJENFW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/headless.ts"],"sourcesContent":["import { createInterface } from 'node:readline';\nimport chalk from 'chalk';\nimport { execa } from 'execa';\nimport { createSpinner, ElapsedTimer, formatDuration, getIcons, useColor } from '../ui/logger.js';\nimport { type ClaudeUsage, parseUsage } from './metrics.js';\nimport { getSessionPublisher } from './session-publisher.js';\nimport { isoNow } from './state-manager.js';\nimport { getOutputCallback, isVerbose } from './verbose.js';\n\nexport interface HeadlessOptions {\n prompt: string;\n maxTurns?: number;\n timeout?: number;\n outputFormat?: 'json' | 'text' | 'stream-json';\n allowedTools?: string[];\n /**\n * Extra directories the headless session may read from and write to, passed\n * through as `--add-dir`. Required whenever a prompt points at a path outside\n * the working tree (e.g. the global issue storage under `~/.issue-flow`),\n * since `claude -p` otherwise refuses the access.\n */\n addDirs?: string[];\n /** Status message displayed as spinner (non-verbose) or header (verbose). */\n statusMessage?: string;\n /** Optional callback for routing verbose output (e.g., through listr2 task.output). When provided, verbose stream events are sent here instead of directly to stderr. */\n onOutput?: (line: string) => void;\n}\n\n/**\n * Token/cost metrics of a headless invocation.\n *\n * Alias of {@link ClaudeUsage} — the name is kept for the existing call sites,\n * but the shape (and the parsing behind it) now lives in core/metrics.ts, so\n * cache tokens and USD cost come along for free.\n */\nexport type HeadlessCost = ClaudeUsage;\n\nexport interface HeadlessResult {\n success: boolean;\n result: string;\n cost: HeadlessCost | null;\n error: string | null;\n}\n\n/**\n * Default wall-clock limit for a single headless invocation.\n *\n * Every phase that invokes `claude` once (analyze, prd, plan, review, pr,\n * pr-review, generate) shares it, so the limit is raised in one place. It is\n * deliberately generous: the phases read the repository before writing their\n * artifact, and on a large issue that alone outlives a few minutes. The execute\n * loop is the exception and runs with no limit at all (`core/executor.ts`),\n * because its iteration budget is what bounds it.\n */\nexport const DEFAULT_HEADLESS_TIMEOUT_MS = 900_000;\n\n/**\n * The subset of an execa result this module inspects. Declared structurally so\n * both the awaited `execa()` result and the awaited subprocess of the verbose\n * path fit it without a cast to `any`.\n */\ninterface FinishedProcess {\n exitCode?: number | undefined;\n signal?: string | undefined;\n timedOut?: boolean | undefined;\n}\n\n/**\n * How much of the limit an invocation has to have burned through before an\n * unlabelled kill is attributed to the timeout rather than to something\n * external. A limit of 0 means no limit, and nothing can be attributed to it.\n */\nconst TIMEOUT_ATTRIBUTION_RATIO = 0.9;\n\nfunction reachedTimeout(timeoutMs: number, elapsedMs: number): boolean {\n return timeoutMs > 0 && elapsedMs >= timeoutMs * TIMEOUT_ATTRIBUTION_RATIO;\n}\n\n/**\n * Whether a finished invocation was killed by the `timeout` option.\n *\n * `reject: false` means execa never throws on a timeout — it resolves with a\n * result carrying `timedOut: true`, which is why the `catch` block below never\n * sees one. That flag is the authoritative signal; the rest is a fallback for\n * the case execa cannot label, a CLI that installs its own SIGTERM handler and\n * exits by itself. `claude` does exactly that and leaves 143 (128 + SIGTERM),\n * with no signal for execa to report. The elapsed-time guard keeps that\n * fallback from mislabelling an unrelated external kill as a timeout.\n */\nfunction wasTimedOut(proc: FinishedProcess, timeoutMs: number, elapsedMs: number): boolean {\n if (proc.timedOut === true) return true;\n if (!reachedTimeout(timeoutMs, elapsedMs)) return false;\n return (\n proc.signal === 'SIGTERM' ||\n proc.signal === 'SIGKILL' ||\n proc.exitCode === 143 ||\n proc.exitCode === 137\n );\n}\n\n/**\n * The error text of a failed invocation.\n *\n * A timeout gets a message of its own, and it has to keep saying \"timed out\":\n * `utils/retry.ts` classifies a failure as transient by matching that text, and\n * it is what earns the phase its retries in `core/phase-runner.ts`. Reporting a\n * timeout as a bare `claude exited with code 143` — which is what the CLI\n * leaves behind when it handles the SIGTERM itself — both hid the cause and\n * cost the phase every retry it had.\n */\nfunction describeFailure(\n proc: FinishedProcess,\n diagnostics: string,\n timeoutMs: number,\n elapsedMs: number,\n): string {\n if (wasTimedOut(proc, timeoutMs, elapsedMs)) {\n return `Headless invocation timed out after ${formatDuration(Math.round(timeoutMs / 1000))}. Raise the limit with --timeout <seconds> (0 = no limit).`;\n }\n return diagnostics.trim() || `claude exited with code ${proc.exitCode ?? 'unknown'}`;\n}\n\n/* ── argument helpers ───────────────────────────────────────────────────── */\n\n/**\n * Append one `<flag> <value>` pair per value. An empty or absent list leaves\n * `args` untouched, so callers that pass nothing keep the exact same argv.\n */\nfunction pushRepeatedFlag(args: string[], flag: string, values: string[] | undefined): void {\n if (!values || values.length === 0) return;\n for (const value of values) {\n args.push(flag, value);\n }\n}\n\n/* ── verbose stream formatting ──────────────────────────────────────────── */\n\n/**\n * Extract a short context string from a tool_use input object.\n */\nfunction getToolContext(name: string, input: Record<string, unknown>): string {\n switch (name) {\n case 'Read':\n return shortPath(input.file_path as string);\n case 'Write':\n case 'Edit':\n return shortPath(input.file_path as string);\n case 'Glob':\n return (input.pattern as string) ?? '';\n case 'Grep':\n return (input.pattern as string) ?? '';\n case 'Bash': {\n const cmd = (input.command as string) ?? '';\n return cmd.length > 60 ? `${cmd.substring(0, 57)}...` : cmd;\n }\n default:\n return '';\n }\n}\n\n/**\n * Shorten a file path to be relative-friendly.\n */\nfunction shortPath(filePath: string | undefined): string {\n if (!filePath) return '';\n const cwd = process.cwd();\n if (filePath.startsWith(cwd)) {\n return filePath.substring(cwd.length + 1);\n }\n // Show last 2 segments for absolute paths\n const parts = filePath.split('/');\n if (parts.length > 2) {\n return `.../${parts.slice(-2).join('/')}`;\n }\n return filePath;\n}\n\n/**\n * Print a formatted stream event line to stderr.\n */\nfunction printStreamEvent(\n line: string,\n state: { turnCount: number },\n onOutput?: (line: string) => void,\n): void {\n let event: {\n type?: string;\n subtype?: string;\n message?: {\n content?: { type: string; text?: string; name?: string; input?: Record<string, unknown> }[];\n };\n };\n\n try {\n event = JSON.parse(line);\n } catch {\n return;\n }\n\n const icons = getIcons();\n const colored = useColor();\n const emit = onOutput ?? ((msg: string) => process.stderr.write(`${msg}\\n`));\n\n if (event.type === 'assistant' && event.message?.content) {\n state.turnCount++;\n\n for (const block of event.message.content) {\n if (block.type === 'text' && block.text) {\n // Wrap text with connector prefix\n const lines = block.text.split('\\n');\n for (const textLine of lines) {\n if (!textLine.trim()) continue;\n const prefix = colored ? chalk.dim(` ${icons.connector} `) : ` ${icons.connector} `;\n const text = colored ? chalk.dim(textLine) : textLine;\n emit(`${prefix}${text}`);\n }\n }\n\n if (block.type === 'tool_use' && block.name) {\n const context = block.input ? getToolContext(block.name, block.input) : '';\n getSessionPublisher().publish({\n type: 'activity',\n at: isoNow(),\n tool: block.name,\n detail: context || undefined,\n });\n const toolName = block.name.padEnd(12);\n\n const prefix = colored ? chalk.dim(` ${icons.connector} `) : ` ${icons.connector} `;\n const toolIcon = colored ? chalk.cyan(icons.tool) : icons.tool;\n const toolLabel = colored ? chalk.cyan(toolName) : toolName;\n const contextText = context ? (colored ? chalk.dim(context) : context) : '';\n\n emit(`${prefix}${toolIcon} ${toolLabel} ${contextText}`);\n }\n }\n }\n}\n\n/* ── verbose execution ──────────────────────────────────────────────────── */\n\n/**\n * Run headless in verbose mode using stream-json to display real-time progress.\n */\nasync function runHeadlessVerbose(options: {\n prompt: string;\n maxTurns: number;\n timeout: number;\n allowedTools?: string[];\n addDirs?: string[];\n statusMessage?: string;\n onOutput?: (line: string) => void;\n}): Promise<HeadlessResult> {\n const { prompt, maxTurns, timeout, allowedTools, addDirs, statusMessage, onOutput } = options;\n const icons = getIcons();\n const colored = useColor();\n const emit = onOutput ?? ((msg: string) => process.stderr.write(`${msg}\\n`));\n\n // Print header\n if (statusMessage) {\n const msg = colored\n ? chalk.blue(`${icons.start} ${statusMessage}`)\n : `${icons.start} ${statusMessage}`;\n emit(msg);\n }\n\n // Print opening connector\n const connectorLine = colored ? chalk.dim(` ${icons.connector}`) : ` ${icons.connector}`;\n emit(connectorLine);\n\n const startTime = Date.now();\n\n const args: string[] = [\n '-p',\n prompt,\n '--output-format',\n 'stream-json',\n '--verbose',\n '--max-turns',\n String(maxTurns),\n ];\n\n pushRepeatedFlag(args, '--allowedTools', allowedTools);\n pushRepeatedFlag(args, '--add-dir', addDirs);\n\n const subprocess = execa('claude', args, {\n stdin: 'ignore',\n reject: false,\n timeout,\n stripFinalNewline: false,\n });\n\n let resultText = '';\n let isError = false;\n let costData: HeadlessCost | null = null;\n const state = { turnCount: 0 };\n\n if (subprocess.stdout) {\n const rl = createInterface({ input: subprocess.stdout });\n for await (const line of rl) {\n printStreamEvent(line, state, onOutput);\n\n try {\n const event = JSON.parse(line);\n if (event.type === 'result') {\n resultText = event.result ?? '';\n isError = event.is_error === true;\n // Keep the previous metrics when this event carries none, so a\n // malformed trailing result never erases what was already captured.\n costData = parseUsage(event) ?? costData;\n }\n } catch {\n // ignore malformed lines\n }\n }\n }\n\n // Wait for the process to finish\n const proc = await subprocess;\n\n // Close connector with elapsed time\n const elapsedSec = Math.floor((Date.now() - startTime) / 1000);\n const durationStr = formatDuration(elapsedSec);\n const doneLine = colored\n ? chalk.dim(` ${icons.connector} ${chalk.italic(`Done in ${durationStr}`)}`)\n : ` ${icons.connector} Done in ${durationStr}`;\n emit(doneLine);\n emit(connectorLine);\n\n if (proc.exitCode !== 0 && !resultText) {\n return {\n success: false,\n result: '',\n cost: null,\n error: describeFailure(proc, proc.stderr?.toString() ?? '', timeout, Date.now() - startTime),\n };\n }\n\n return {\n success: !isError,\n result: resultText,\n cost: costData,\n error: isError ? resultText : null,\n };\n}\n\n/* ── standard execution ─────────────────────────────────────────────────── */\n\n/**\n * Invoke Claude Code in headless mode via `claude -p`.\n *\n * Each invocation is an isolated session — no context is shared between calls.\n * Output is parsed as JSON when outputFormat is 'json' (default).\n *\n * When verbose mode is active, uses stream-json to display real-time progress.\n * Otherwise, shows a spinner while waiting.\n */\nexport async function runHeadless(options: HeadlessOptions): Promise<HeadlessResult> {\n const {\n prompt,\n maxTurns = 10,\n timeout = DEFAULT_HEADLESS_TIMEOUT_MS,\n outputFormat = 'json',\n allowedTools,\n addDirs,\n statusMessage,\n onOutput,\n } = options;\n\n if (isVerbose()) {\n // Use explicit onOutput, fall back to global output callback, or default to stderr\n const effectiveOnOutput = onOutput ?? getOutputCallback();\n return runHeadlessVerbose({\n prompt,\n maxTurns,\n timeout,\n allowedTools,\n addDirs,\n statusMessage,\n onOutput: effectiveOnOutput,\n });\n }\n\n // Non-verbose: use spinner with elapsed timer\n const startTime = Date.now();\n const spinner = statusMessage ? createSpinner(statusMessage).start() : null;\n\n let timer: ElapsedTimer | null = null;\n if (spinner) {\n timer = new ElapsedTimer((elapsed) => {\n spinner.suffixText = useColor() ? chalk.dim(`(${elapsed})`) : `(${elapsed})`;\n }).start();\n }\n\n const args: string[] = [\n '-p',\n prompt,\n '--output-format',\n outputFormat,\n '--max-turns',\n String(maxTurns),\n ];\n\n pushRepeatedFlag(args, '--allowedTools', allowedTools);\n pushRepeatedFlag(args, '--add-dir', addDirs);\n\n try {\n const proc = await execa('claude', args, {\n stdin: 'ignore',\n reject: false,\n timeout,\n stripFinalNewline: false,\n });\n\n const stdout = proc.stdout?.toString() ?? '';\n const stderr = proc.stderr?.toString() ?? '';\n\n if (proc.exitCode !== 0) {\n const elapsed = timer?.stop() ?? 0;\n const dur = useColor()\n ? chalk.dim(` (${formatDuration(elapsed)})`)\n : ` (${formatDuration(elapsed)})`;\n spinner?.fail(`${statusMessage}${dur}`);\n return {\n success: false,\n result: '',\n cost: null,\n error: describeFailure(proc, stderr || stdout, timeout, Date.now() - startTime),\n };\n }\n\n const elapsed = timer?.stop() ?? 0;\n const dur = useColor()\n ? chalk.dim(` (${formatDuration(elapsed)})`)\n : ` (${formatDuration(elapsed)})`;\n spinner?.succeed(`${statusMessage}${dur}`);\n\n if (outputFormat === 'json') {\n try {\n const parsed = JSON.parse(stdout);\n return {\n success: true,\n result: parsed.result ?? stdout,\n cost: parseUsage(parsed),\n error: null,\n };\n } catch {\n return {\n success: true,\n result: stdout,\n cost: null,\n error: null,\n };\n }\n }\n\n return {\n success: true,\n result: stdout,\n cost: null,\n error: null,\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n const catchElapsed = timer?.stop() ?? 0;\n const catchDur = useColor()\n ? chalk.dim(` (${formatDuration(catchElapsed)})`)\n : ` (${formatDuration(catchElapsed)})`;\n spinner?.fail(`${statusMessage}${catchDur}`);\n\n if (message.includes('timed out') || message.includes('ETIMEDOUT')) {\n // There is no finished process to inspect here, so the clock is the only\n // evidence. Claim our own limit only when the invocation actually ran up\n // against it: an ETIMEDOUT raised minutes earlier — or with no limit set\n // at all — keeps its own message, which is the honest diagnosis and\n // already carries the words isTransientFailure() matches on.\n const elapsedMs = Date.now() - startTime;\n return {\n success: false,\n result: '',\n cost: null,\n error: describeFailure(\n { timedOut: reachedTimeout(timeout, elapsedMs) },\n message,\n timeout,\n elapsedMs,\n ),\n };\n }\n\n return {\n success: false,\n result: '',\n cost: null,\n error: message,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,uBAAuB;AAChC,OAAO,WAAW;AAClB,SAAS,aAAa;AAoDf,IAAM,8BAA8B;AAkB3C,IAAM,4BAA4B;AAElC,SAAS,eAAe,WAAmB,WAA4B;AACrE,SAAO,YAAY,KAAK,aAAa,YAAY;AACnD;AAaA,SAAS,YAAY,MAAuB,WAAmB,WAA4B;AACzF,MAAI,KAAK,aAAa,KAAM,QAAO;AACnC,MAAI,CAAC,eAAe,WAAW,SAAS,EAAG,QAAO;AAClD,SACE,KAAK,WAAW,aAChB,KAAK,WAAW,aAChB,KAAK,aAAa,OAClB,KAAK,aAAa;AAEtB;AAYA,SAAS,gBACP,MACA,aACA,WACA,WACQ;AACR,MAAI,YAAY,MAAM,WAAW,SAAS,GAAG;AAC3C,WAAO,uCAAuC,eAAe,KAAK,MAAM,YAAY,GAAI,CAAC,CAAC;AAAA,EAC5F;AACA,SAAO,YAAY,KAAK,KAAK,2BAA2B,KAAK,YAAY,SAAS;AACpF;AAQA,SAAS,iBAAiB,MAAgB,MAAc,QAAoC;AAC1F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MACN,OAAO;AAAA,IACT;AAAA,EACF,SAAS,KAAK;AACZ,UAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,UAAM,eAAe,OAAO,KAAK,KAAK;AACtC,UAAM,WAAW,SAAS,IACtB,MAAM,IAAI,KAAK,eAAe,YAAY,CAAC,GAAG,IAC9C,KAAK,eAAe,YAAY,CAAC;AACrC,aAAS,KAAK,GAAG,aAAa,GAAG,QAAQ,EAAE;AAE3C,QAAI,QAAQ,SAAS,WAAW,KAAK,QAAQ,SAAS,WAAW,GAAG;AAMlE,YAAM,YAAY,KAAK,IAAI,IAAI;AAC/B,aAAO;AAAA,QACL,SAAS;AAAA,QACT,QAAQ;AAAA,QACR,MAAM;AAAA,QACN,OAAO;AAAA,UACL,EAAE,UAAU,eAAe,SAAS,SAAS,EAAE;AAAA,UAC/C;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,MACL,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,MAAM;AAAA,MACN,OAAO;AAAA,IACT;AAAA,EACF;AACF;","names":["elapsed","dur"]}
@@ -2,31 +2,33 @@
2
2
  import {
3
3
  readFileWithGrace,
4
4
  runPhaseWithRetry
5
- } from "./chunk-UUY4PCWW.js";
5
+ } from "./chunk-3BOHTH4V.js";
6
6
  import {
7
7
  issuePlaceholders,
8
8
  resolveCommandIssue
9
- } from "./chunk-S67Q4I2O.js";
9
+ } from "./chunk-AAY6KM7N.js";
10
+ import {
11
+ DEFAULT_HEADLESS_TIMEOUT_MS,
12
+ runHeadless
13
+ } from "./chunk-EWDJENFW.js";
10
14
  import {
11
15
  isTransientFailure
12
16
  } from "./chunk-HDV3YDTG.js";
13
17
  import {
14
- runHeadless
15
- } from "./chunk-MXTGCD5C.js";
16
- import {
17
- publishPhaseMetrics
18
- } from "./chunk-PPLIXZI5.js";
18
+ publishPhaseMetrics,
19
+ resolvePolicyPlaceholders
20
+ } from "./chunk-OBLVLIUS.js";
19
21
  import {
20
22
  applyPlaceholders,
21
23
  loadPrompt
22
- } from "./chunk-SLHZPB3C.js";
24
+ } from "./chunk-HQYXVIH6.js";
23
25
  import {
24
26
  getIssuePaths,
25
27
  getProjectRoot,
26
28
  recordUserStoryNumbering,
27
29
  resolveIssuePaths,
28
30
  resolveProjectPaths
29
- } from "./chunk-VYFKOUUR.js";
31
+ } from "./chunk-VQ5VN7DF.js";
30
32
  import {
31
33
  getGlobalTimeout,
32
34
  isoNow,
@@ -37,7 +39,7 @@ import {
37
39
  printWarning,
38
40
  saveTaskPlan,
39
41
  taskPlanSchema
40
- } from "./chunk-V5OHFSW4.js";
42
+ } from "./chunk-HC2MT7BX.js";
41
43
 
42
44
  // src/commands/plan.ts
43
45
  import { mkdir, readFile as readFile2 } from "fs/promises";
@@ -184,6 +186,9 @@ async function runPlan(issue, resolvedIssue, numbering) {
184
186
  printInfo(numberingMessage);
185
187
  const template = await loadPrompt("plan");
186
188
  const prompt = applyPlaceholders(template, {
189
+ // The repository's own conventions. Empty when it declares none, which is
190
+ // what keeps the rendered prompt identical to the pre-policy one.
191
+ ...await resolvePolicyPlaceholders(),
187
192
  __ISSUE_NUMBER__: issueNumber,
188
193
  __PRD_CONTENT__: prdContent,
189
194
  __TASKS_PATH__: tasksPath,
@@ -198,7 +203,7 @@ async function runPlan(issue, resolvedIssue, numbering) {
198
203
  const result = await runHeadless({
199
204
  prompt,
200
205
  maxTurns: 25,
201
- timeout: getGlobalTimeout() ?? 3e5,
206
+ timeout: getGlobalTimeout() ?? DEFAULT_HEADLESS_TIMEOUT_MS,
202
207
  // json (not text) so the CLI reports usage: the envelope's `result`
203
208
  // field carries the same assistant text this phase already consumed.
204
209
  outputFormat: "json",
@@ -262,4 +267,4 @@ ${issues}`
262
267
  export {
263
268
  runPlan
264
269
  };
265
- //# sourceMappingURL=chunk-SP7DD4ID.js.map
270
+ //# sourceMappingURL=chunk-EY6WMHV2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/plan.ts","../src/storage/user-story-numbering.ts"],"sourcesContent":["import { mkdir, readFile } from 'node:fs/promises';\nimport { DEFAULT_HEADLESS_TIMEOUT_MS, runHeadless } from '../core/headless.js';\nimport { readFileWithGrace, runPhaseWithRetry } from '../core/phase-runner.js';\nimport { applyPlaceholders, loadPrompt } from '../core/prompt-resolver.js';\nimport { publishPhaseMetrics } from '../core/session-metrics.js';\nimport { loadTaskPlan, saveTaskPlan } from '../core/state-manager.js';\nimport { getGlobalTimeout } from '../core/verbose.js';\nimport { issuePlaceholders, resolveCommandIssue } from '../issues/context.js';\nimport type { ResolvedIssue } from '../issues/types.js';\nimport { resolvePolicyPlaceholders } from '../policy/placeholders.js';\nimport { taskPlanSchema } from '../schemas.js';\nimport { resolveIssuePaths } from '../storage/resolve.js';\nimport {\n determineUserStoryNumbering,\n formatUserStoryId,\n parseUserStoryNumber,\n} from '../storage/user-story-numbering.js';\nimport { printError, printInfo, printSuccess, printWarning } from '../ui/logger.js';\nimport { isTransientFailure } from '../utils/retry.js';\n\n/** `--continue` / `--start-us <n>` override of the numbering cascade (issue #36). */\nexport interface PlanUserStoryNumberingOptions {\n continueFlag?: boolean;\n startUs?: number;\n}\n\nexport async function runPlan(\n issue: string,\n resolvedIssue?: ResolvedIssue,\n numbering?: PlanUserStoryNumberingOptions,\n): Promise<number> {\n const issueNumber = issue.replace(/^#/, '');\n const paths = await resolveIssuePaths(issueNumber);\n\n const resolution = await resolveCommandIssue(issueNumber, resolvedIssue);\n if (!resolution.ok) {\n return resolution.code;\n }\n\n // Read the PRD\n const prdPath = paths.prdFile;\n let prdContent: string;\n try {\n prdContent = await readFile(prdPath, 'utf-8');\n } catch {\n printError(`PRD not found at ${prdPath}. Run 'issue-flow prd ${issueNumber}' first.`);\n return 1;\n }\n\n const tasksPath = paths.tasksFile;\n\n // Resolve the User Story numbering continuity (issue #36), log where the\n // decision came from — never silently — and persist it into the project's\n // metadata.json for audit before the prompt is even built, so the record on\n // disk always matches what the prompt was told.\n const {\n message: numberingMessage,\n nextUserStoryId,\n decision: { nextNumber },\n } = await determineUserStoryNumbering({\n issueNumber,\n continueFlag: numbering?.continueFlag,\n startUs: numbering?.startUs,\n });\n printInfo(numberingMessage);\n\n const template = await loadPrompt('plan');\n const prompt = applyPlaceholders(template, {\n // The repository's own conventions. Empty when it declares none, which is\n // what keeps the rendered prompt identical to the pre-policy one.\n ...(await resolvePolicyPlaceholders()),\n __ISSUE_NUMBER__: issueNumber,\n __PRD_CONTENT__: prdContent,\n __TASKS_PATH__: tasksPath,\n __NEXT_US_NUMBER__: nextUserStoryId,\n ...issuePlaceholders(resolution.resolved),\n });\n\n await mkdir(paths.issueDir, { recursive: true });\n\n const outcome = await runPhaseWithRetry({\n phase: 'plan',\n attempt: async () => {\n const startedAtMs = Date.now();\n const result = await runHeadless({\n prompt,\n maxTurns: 25,\n timeout: getGlobalTimeout() ?? DEFAULT_HEADLESS_TIMEOUT_MS,\n // json (not text) so the CLI reports usage: the envelope's `result`\n // field carries the same assistant text this phase already consumed.\n outputFormat: 'json',\n allowedTools: ['Bash', 'Read', 'Glob', 'Grep', 'Write'],\n addDirs: [paths.issueDir],\n statusMessage: `Converting PRD to task plan for issue #${issueNumber}...`,\n });\n // One event per attempt; the reducer sums them into the phase total.\n publishPhaseMetrics('plan', result.cost, startedAtMs);\n\n if (!result.success) {\n return {\n ok: false,\n transient: isTransientFailure(1, result.error ?? ''),\n error: `Task plan generation failed: ${result.error}`,\n };\n }\n\n // Verify the file was created, tolerating a brief FS-visibility lag.\n let rawContent: string;\n try {\n rawContent = await readFileWithGrace(tasksPath);\n } catch {\n return { ok: false, transient: true, error: `tasks.json was not created at ${tasksPath}` };\n }\n\n // Validate JSON structure — a content defect, not a timing issue, but\n // still worth a bounded retry since it's a fresh Claude invocation.\n let parsed: unknown;\n try {\n parsed = JSON.parse(rawContent);\n } catch {\n return { ok: false, transient: true, error: 'tasks.json contains invalid JSON' };\n }\n\n // Validate with zod schema\n const validation = taskPlanSchema.safeParse(parsed);\n if (!validation.success) {\n const issues = validation.error.issues\n .map((i) => ` - ${i.path.join('.')}: ${i.message}`)\n .join('\\n');\n return {\n ok: false,\n transient: true,\n error: `tasks.json does not match expected schema:\\n${issues}`,\n };\n }\n\n return { ok: true };\n },\n });\n\n if (!outcome.ok) {\n printError(outcome.error ?? `Task plan generation failed for issue #${issueNumber}`);\n return 1;\n }\n\n // Ensure pipeline state reflects completion of this phase\n const plan = await loadTaskPlan(tasksPath);\n plan.pipeline.jsonCompleted = true;\n await saveTaskPlan(tasksPath, plan);\n\n // The numbering is a prompt instruction, not a programmatic rewrite, so the\n // generated plan can still ignore it. Say so out loud instead of leaving the\n // log and metadata.json claiming a numbering the file on disk contradicts.\n const generatedLowest = plan.userStories\n .map((story) => parseUserStoryNumber(story.id))\n .filter((value): value is number => value !== null)\n .reduce<number | null>(\n (lowest, value) => (lowest === null ? value : Math.min(lowest, value)),\n null,\n );\n if (generatedLowest !== null && generatedLowest < nextNumber) {\n printWarning(\n `The generated plan starts at ${formatUserStoryId(generatedLowest)}, not the requested ` +\n `${nextUserStoryId}. User Story ids may collide with earlier issues of this project — ` +\n `re-run 'issue-flow plan ${issueNumber} --start-us ${nextNumber}' if that matters.`,\n );\n }\n\n printSuccess(`Task plan saved to ${tasksPath} (${plan.userStories.length} stories)`);\n return 0;\n}\n","import { readdir, readFile } from 'node:fs/promises';\nimport { isoNow } from '../core/state-manager.js';\nimport { getProjectRoot } from '../utils/git.js';\nimport { recordUserStoryNumbering } from './compat.js';\nimport { getIssuePaths } from './paths.js';\nimport { type ResolveIssuePathsOptions, resolveProjectPaths } from './resolve.js';\nimport type { UserStoryNumberingDecision } from './schemas.js';\n\n/**\n * Continuity of `US-NNN` numbering across `plan` executions of the same\n * project (issue #36).\n *\n * The User Story `id` field is free-form — `userStorySchema` in\n * `src/schemas.ts` only requires a non-empty string, no `US-NNN` regex is\n * enforced — so every reader here tolerates an id that does not carry a\n * trailing number instead of throwing on it.\n */\n\nconst USER_STORY_ID_PAD = 3;\n\n/** `16` -> `'US-016'`. Numbers past 999 are not padded further. */\nexport function formatUserStoryId(n: number): string {\n return `US-${String(n).padStart(USER_STORY_ID_PAD, '0')}`;\n}\n\n/**\n * Extract the last run of digits from a User Story id, or `null` when none is\n * found. Tolerant by design: an id like `US-001` yields `1`, but so does a\n * free-form one such as `story-1` or `v2-US-007` (the last digit run, `007`,\n * wins over the `2` version prefix) — only an id with no digits at all (e.g.\n * `add-auth`) is ignored.\n */\nexport function parseUserStoryNumber(id: string): number | null {\n const matches = id.match(/\\d+/g);\n if (!matches || matches.length === 0) return null;\n\n const value = Number.parseInt(matches[matches.length - 1], 10);\n return Number.isNaN(value) ? null : value;\n}\n\nexport interface HighestUserStoryNumberResult {\n number: number;\n /** Issue directory name the winning story came from. */\n issueId: string;\n /** Verbatim id of the winning story. */\n storyId: string;\n}\n\n/**\n * Loose read of one `tasks.json`: only cares about `userStories[].id` and\n * tolerates every failure (missing file, invalid JSON, unexpected shape) by\n * returning `null` — a sibling issue mid-migration, or with a corrupt plan,\n * must not abort the whole project scan.\n */\nasync function readUserStoryIds(tasksPath: string): Promise<string[] | null> {\n let raw: string;\n try {\n raw = await readFile(tasksPath, 'utf-8');\n } catch {\n return null;\n }\n\n try {\n const parsed: unknown = JSON.parse(raw);\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n !Array.isArray((parsed as { userStories?: unknown }).userStories)\n ) {\n return null;\n }\n\n return (parsed as { userStories: unknown[] }).userStories\n .map((story) =>\n typeof story === 'object' &&\n story !== null &&\n typeof (story as { id?: unknown }).id === 'string'\n ? (story as { id: string }).id\n : null,\n )\n .filter((id): id is string => id !== null);\n } catch {\n return null;\n }\n}\n\nexport interface FindHighestUserStoryNumberOptions extends ResolveIssuePathsOptions {\n /**\n * Issue directory to leave out of the scan — the issue the numbering is\n * being resolved for. Re-planning an issue overwrites its own `tasks.json`,\n * so counting the plan about to be replaced would push the numbering forward\n * on every `plan` re-run of the same issue.\n */\n excludeIssueId?: string;\n}\n\n/**\n * Highest User Story number already used anywhere in the project, scanning\n * every `<issuesDir>/<id>/tasks.json` regardless of which issue produced it —\n * that project-wide scope is what makes `US-NNN` unambiguous across issues.\n * The issue named by `excludeIssueId` is skipped, so re-planning is idempotent.\n *\n * `null` means no readable `tasks.json` was found (the project's first `plan`\n * run ever, or a brand-new project directory). A storage directory that exists\n * but cannot be read throws instead: silently restarting at `US-001` because\n * `~/.issue-flow` was momentarily unreadable is the worst outcome this feature\n * can produce.\n */\nexport async function findHighestUserStoryNumber(\n options: FindHighestUserStoryNumberOptions = {},\n): Promise<HighestUserStoryNumberResult | null> {\n const { excludeIssueId, ...rootOptions } = options;\n const { projectId, issuesDir } = await resolveProjectPaths(rootOptions);\n\n let entries: string[];\n try {\n entries = (await readdir(issuesDir, { withFileTypes: true }))\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name);\n } catch (error) {\n // ENOENT is the legitimate \"no history yet\" case. Any other failure\n // (EACCES, EIO, an unavailable mount) must not be reported as an empty\n // history, or the numbering would restart silently.\n if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') return null;\n throw new Error(\n `Could not scan the project's User Story history at ${issuesDir}: ` +\n `${(error as Error).message}. Fix the storage directory, or pass --start-us <n> ` +\n 'to set the numbering explicitly.',\n { cause: error },\n );\n }\n\n let best: HighestUserStoryNumberResult | null = null;\n\n for (const issueId of entries) {\n if (excludeIssueId !== undefined && issueId === excludeIssueId) continue;\n // Never hand-build an artifact path (see src/storage/AGENTS.md): asking\n // getIssuePaths() keeps a rename of `tasks.json` a one-file change instead\n // of silently making this scan find nothing.\n const { tasksFile } = getIssuePaths(projectId, issueId, { env: options.env });\n const ids = await readUserStoryIds(tasksFile);\n if (!ids) continue;\n\n for (const id of ids) {\n const value = parseUserStoryNumber(id);\n if (value === null) continue;\n if (best === null || value > best.number) {\n best = { number: value, issueId, storyId: id };\n }\n }\n }\n\n return best;\n}\n\nexport interface ResolveUserStoryNumberingOptions extends ResolveIssuePathsOptions {\n /** Issue the decision is being made for — carried into the audit record. */\n issueNumber: string;\n /** `--continue` was passed explicitly. Purely cosmetic on the log message:\n * the resolved number is identical to the automatic default. */\n continueFlag?: boolean;\n /** `--start-us <n>` was passed. Wins outright over any history. */\n startUs?: number;\n /** Timestamp source, injectable for tests. */\n now?: () => string;\n}\n\nexport interface UserStoryNumberingOutcome {\n decision: UserStoryNumberingDecision;\n /** Ready-to-print explanation of where the decision came from — the CLI\n * must never resolve this silently (issue #36). */\n message: string;\n}\n\n/**\n * Resolve the numbering cascade of #36:\n *\n * 1. `--start-us <n>` wins outright — history is not even scanned, since the\n * whole point is to ignore it.\n * 2. Otherwise the project's history is scanned for the highest number used\n * so far. This is what running with no flag at all does automatically,\n * and what `--continue` names explicitly (the two produce the same\n * number; the flag only changes the log message).\n * 3. No history found (the project's first `plan` ever) starts at `US-001`.\n *\n * Pure with respect to `metadata.json` — this only reads `tasks.json` files,\n * never writes. Persisting the decision is {@link determineUserStoryNumbering}\n * below, via `recordUserStoryNumbering()` in `compat.ts`.\n */\nexport async function resolveUserStoryNumbering(\n options: ResolveUserStoryNumberingOptions,\n): Promise<UserStoryNumberingOutcome> {\n const { issueNumber, continueFlag, startUs, now, ...rootOptions } = options;\n const decidedAt = (now ?? isoNow)();\n\n if (startUs !== undefined) {\n const decision: UserStoryNumberingDecision = {\n nextNumber: startUs,\n source: 'start-us',\n issueNumber,\n decidedAt,\n };\n return {\n decision,\n message: `User Story numbering forced to ${formatUserStoryId(startUs)} via --start-us.`,\n };\n }\n\n // The issue being planned is excluded from the scan: `plan` overwrites its\n // own `tasks.json`, so counting the plan it is about to replace would push\n // the numbering forward on every re-run of `plan` for the same issue.\n const highest = await findHighestUserStoryNumber({ ...rootOptions, excludeIssueId: issueNumber });\n\n if (highest === null) {\n const decision: UserStoryNumberingDecision = {\n nextNumber: 1,\n source: 'none',\n issueNumber,\n decidedAt,\n };\n return {\n decision,\n message: `Starting User Story numbering at ${formatUserStoryId(1)} (no previous history found for this project).`,\n };\n }\n\n const nextNumber = highest.number + 1;\n const decision: UserStoryNumberingDecision = {\n nextNumber,\n source: 'history',\n issueNumber,\n decidedAt,\n detail: `${highest.storyId} (issue #${highest.issueId})`,\n };\n const via = continueFlag ? ' via --continue' : '';\n return {\n decision,\n message:\n `Continuing User Story numbering from ${formatUserStoryId(nextNumber)}${via} ` +\n `— last used was ${highest.storyId} (issue #${highest.issueId}).`,\n };\n}\n\nexport interface DetermineUserStoryNumberingOptions extends ResolveUserStoryNumberingOptions {\n /** Repository root. Defaults to the git toplevel of the current directory. */\n projectRoot?: string;\n}\n\nexport interface UserStoryNumberingResult extends UserStoryNumberingOutcome {\n /** `decision.nextNumber` formatted as `US-NNN`, ready for the prompt. */\n nextUserStoryId: string;\n}\n\n/**\n * The entry point commands use: resolve the cascade and persist the decision\n * into `metadata.json` in one call, so no call site can log/prompt with one\n * decision and audit a different one.\n */\nexport async function determineUserStoryNumbering(\n options: DetermineUserStoryNumberingOptions,\n): Promise<UserStoryNumberingResult> {\n const { projectRoot: projectRootOption, ...rest } = options;\n const projectRoot = projectRootOption ?? (await getProjectRoot());\n\n const outcome = await resolveUserStoryNumbering({ ...rest, projectRoot });\n await recordUserStoryNumbering(projectRoot, outcome.decision, {\n env: options.env,\n now: options.now,\n });\n\n return { ...outcome, nextUserStoryId: formatUserStoryId(outcome.decision.nextNumber) };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,YAAAA,iBAAgB;;;ACAhC,SAAS,SAAS,gBAAgB;AAkBlC,IAAM,oBAAoB;AAGnB,SAAS,kBAAkB,GAAmB;AACnD,SAAO,MAAM,OAAO,CAAC,EAAE,SAAS,mBAAmB,GAAG,CAAC;AACzD;AASO,SAAS,qBAAqB,IAA2B;AAC9D,QAAM,UAAU,GAAG,MAAM,MAAM;AAC/B,MAAI,CAAC,WAAW,QAAQ,WAAW,EAAG,QAAO;AAE7C,Q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;AAAA,UACX,OAAO;AAAA,EAA+C,MAAM;AAAA,QAC9D;AAAA,MACF;AAEA,aAAO,EAAE,IAAI,KAAK;AAAA,IACpB;AAAA,EACF,CAAC;AAED,MAAI,CAAC,QAAQ,IAAI;AACf,eAAW,QAAQ,SAAS,0CAA0C,WAAW,EAAE;AACnF,WAAO;AAAA,EACT;AAGA,QAAM,OAAO,MAAM,aAAa,SAAS;AACzC,OAAK,SAAS,gBAAgB;AAC9B,QAAM,aAAa,WAAW,IAAI;AAKlC,QAAM,kBAAkB,KAAK,YAC1B,IAAI,CAAC,UAAU,qBAAqB,MAAM,EAAE,CAAC,EAC7C,OAAO,CAAC,UAA2B,UAAU,IAAI,EACjD;AAAA,IACC,CAAC,QAAQ,UAAW,WAAW,OAAO,QAAQ,KAAK,IAAI,QAAQ,KAAK;AAAA,IACpE;AAAA,EACF;AACF,MAAI,oBAAoB,QAAQ,kBAAkB,YAAY;AAC5D;AAAA,MACE,gCAAgC,kBAAkB,eAAe,CAAC,uBAC7D,eAAe,mGACS,WAAW,eAAe,UAAU;AAAA,IACnE;AAAA,EACF;AAEA,eAAa,sBAAsB,SAAS,KAAK,KAAK,YAAY,MAAM,WAAW;AACnF,SAAO;AACT;","names":["readFile","decision","readFile"]}
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  resolvePackageDir
4
- } from "./chunk-SLHZPB3C.js";
4
+ } from "./chunk-HQYXVIH6.js";
5
5
  import {
6
6
  getGlobalRoot,
7
7
  webLockSchema
8
- } from "./chunk-VYFKOUUR.js";
8
+ } from "./chunk-VQ5VN7DF.js";
9
9
  import {
10
10
  NullPublisher,
11
11
  isoNow,
12
12
  printInfo,
13
13
  printWarning
14
- } from "./chunk-V5OHFSW4.js";
14
+ } from "./chunk-HC2MT7BX.js";
15
15
 
16
16
  // src/web/lock.ts
17
17
  import { spawn as nodeSpawn } from "child_process";
@@ -458,4 +458,4 @@ export {
458
458
  ensureSingleWebServer,
459
459
  ensureWebMonitor
460
460
  };
461
- //# sourceMappingURL=chunk-652DJBCN.js.map
461
+ //# sourceMappingURL=chunk-GANSDJV7.js.map