issue-flow 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/dist/agent-TB6W7PT7.js +30 -0
  2. package/dist/{analyze-556KCJKZ.js → analyze-6M3KEOX7.js} +22 -22
  3. package/dist/{apply-WVV7G7WN.js → apply-ADB3ZK7W.js} +14 -14
  4. package/dist/{bench-UBFGKUHR.js → bench-FM7I7EIV.js} +23 -23
  5. package/dist/{chunk-YA6FWFYW.js → chunk-2SUFAE6X.js} +53 -11
  6. package/dist/chunk-2SUFAE6X.js.map +1 -0
  7. package/dist/{chunk-DBEMD34J.js → chunk-32JSYXEK.js} +8 -8
  8. package/dist/chunk-3R27MJ5R.js +25 -0
  9. package/dist/chunk-3R27MJ5R.js.map +1 -0
  10. package/dist/{chunk-QZOBR6YF.js → chunk-6YQT3SSM.js} +4 -4
  11. package/dist/chunk-6YQT3SSM.js.map +1 -0
  12. package/dist/{chunk-OGVWJO4S.js → chunk-7F7LGMVO.js} +3 -3
  13. package/dist/{chunk-X6GY3CM2.js → chunk-A4H7P7T7.js} +102 -102
  14. package/dist/chunk-A4H7P7T7.js.map +1 -0
  15. package/dist/{chunk-OGN2NX57.js → chunk-ANI2NTR4.js} +9 -9
  16. package/dist/{chunk-VK65RNFA.js → chunk-B3TSS7BT.js} +3 -3
  17. package/dist/chunk-D6ZBGJ3L.js +321 -0
  18. package/dist/chunk-D6ZBGJ3L.js.map +1 -0
  19. package/dist/{chunk-MXCOSPLJ.js → chunk-DGRTJD5R.js} +3 -3
  20. package/dist/{chunk-ROIIEVZH.js → chunk-DUS5ZNKL.js} +474 -361
  21. package/dist/chunk-DUS5ZNKL.js.map +1 -0
  22. package/dist/{chunk-VTF4RWS5.js → chunk-DV7HUC4Z.js} +7 -7
  23. package/dist/{chunk-OOX3RMD3.js → chunk-E6KXCV3T.js} +4 -4
  24. package/dist/{chunk-OLUOZLU5.js → chunk-HJBF4WD2.js} +1653 -1071
  25. package/dist/chunk-HJBF4WD2.js.map +1 -0
  26. package/dist/{chunk-4FUWWBTP.js → chunk-HLAPOUEM.js} +8 -8
  27. package/dist/{chunk-J2LJB2OH.js → chunk-HY5HLFDU.js} +630 -571
  28. package/dist/chunk-HY5HLFDU.js.map +1 -0
  29. package/dist/{chunk-QVLIIGBU.js → chunk-ICM463EO.js} +60 -13
  30. package/dist/chunk-ICM463EO.js.map +1 -0
  31. package/dist/{chunk-KV2K7MK2.js → chunk-ISZ54SVE.js} +9 -9
  32. package/dist/{chunk-GV2DABNZ.js → chunk-KZ5EY5XX.js} +12 -12
  33. package/dist/{chunk-SW2MF47D.js → chunk-KZXQWC7U.js} +19 -19
  34. package/dist/{chunk-2H43OVTU.js → chunk-LPWPFIIB.js} +11 -11
  35. package/dist/{chunk-EPFC4LHT.js → chunk-MI5TREN3.js} +9 -9
  36. package/dist/{chunk-R42YHLDV.js → chunk-PPZ3K4YM.js} +2 -2
  37. package/dist/{chunk-H3EYBJZU.js → chunk-QMIQR7EE.js} +10 -10
  38. package/dist/{chunk-FKWYD44M.js → chunk-QPGEFLMY.js} +2 -2
  39. package/dist/chunk-RCZJQUTC.js +196 -0
  40. package/dist/chunk-RCZJQUTC.js.map +1 -0
  41. package/dist/{chunk-NQCR3HSU.js → chunk-RNFUVKC3.js} +3 -3
  42. package/dist/{chunk-G5LACAXO.js → chunk-RYOUZ6EK.js} +2 -2
  43. package/dist/{chunk-BSBJXPLC.js → chunk-SGTTR4XW.js} +10 -10
  44. package/dist/{chunk-GVOZ6NDO.js → chunk-SOM4QA6C.js} +3 -3
  45. package/dist/{chunk-73TS2H42.js → chunk-UK4E2FUA.js} +132 -34
  46. package/dist/chunk-UK4E2FUA.js.map +1 -0
  47. package/dist/{chunk-PGN2VX4Y.js → chunk-UWDCIFTP.js} +7 -7
  48. package/dist/{chunk-MCLPSL6B.js → chunk-VE3IYNDN.js} +3 -3
  49. package/dist/{chunk-IAMIBZRF.js → chunk-WCCZJL7W.js} +2 -2
  50. package/dist/{chunk-SVDEWOUD.js → chunk-XZUEFTUP.js} +6 -6
  51. package/dist/{chunk-GPLP7EPL.js → chunk-YII4U7ZD.js} +10 -10
  52. package/dist/{chunk-GPLP7EPL.js.map → chunk-YII4U7ZD.js.map} +1 -1
  53. package/dist/{chunk-WLJVL25O.js → chunk-YUNBOUQH.js} +6 -6
  54. package/dist/{chunk-WNROH2YE.js → chunk-YVPZUN6X.js} +2 -2
  55. package/dist/{chunk-Q2TZA6AC.js → chunk-Z5O2XBWA.js} +14 -14
  56. package/dist/cli.js +57 -49
  57. package/dist/cli.js.map +1 -1
  58. package/dist/{config-UE7IP36J.js → config-KGZUPAUP.js} +13 -13
  59. package/dist/{conventions-Z3QC2NSG.js → conventions-RYN7OXJN.js} +15 -15
  60. package/dist/{diagnostics-2Z5HFQOO.js → diagnostics-HTCWF7F4.js} +7 -7
  61. package/dist/execute-QL3ZQIAP.js +37 -0
  62. package/dist/{generate-PB4L7V5N.js → generate-CX6KNHZS.js} +22 -22
  63. package/dist/{git-7MUOGVRG.js → git-A2IP32PQ.js} +2 -2
  64. package/dist/init-PDVQDRS6.js +24 -0
  65. package/dist/{operations-QDJAFZUN.js → operations-CAKIT2BO.js} +15 -15
  66. package/dist/{permissions-XVXXENVP.js → permissions-G4XCAESF.js} +4 -4
  67. package/dist/plan-PRORGS3L.js +34 -0
  68. package/dist/{policy-6WQZB6B2.js → policy-WX6O2JID.js} +14 -14
  69. package/dist/pr-27RMQI5F.js +39 -0
  70. package/dist/pr-review-VNESMAMT.js +32 -0
  71. package/dist/prd-ZNC4T5BS.js +33 -0
  72. package/dist/{ps-CX7756QG.js → ps-76L6ZAZL.js} +12 -12
  73. package/dist/{recorder-RK6XZYF3.js → recorder-N7U66HCO.js} +7 -7
  74. package/dist/{registry-POSB35Q4.js → registry-XLHHYLTR.js} +5 -5
  75. package/dist/{resume-OQJZV3JH.js → resume-VLWIE264.js} +39 -38
  76. package/dist/{resume-OQJZV3JH.js.map → resume-VLWIE264.js.map} +1 -1
  77. package/dist/review-7CREJDKB.js +35 -0
  78. package/dist/routing-VCDYHSXA.js +33 -0
  79. package/dist/run-3MPORLF5.js +56 -0
  80. package/dist/{session-publisher-VVXOCJ2S.js → session-publisher-KAJQRHNZ.js} +3 -2
  81. package/dist/{state-manager-TIC73GQY.js → state-manager-UPHO2EA2.js} +4 -4
  82. package/dist/state-manager-UPHO2EA2.js.map +1 -0
  83. package/dist/{usage-WDDNSIHP.js → usage-U7QNGCPK.js} +12 -12
  84. package/dist/{web-IPGY52AK.js → web-HUNDHCJ4.js} +20 -18
  85. package/dist/{web-IPGY52AK.js.map → web-HUNDHCJ4.js.map} +1 -1
  86. package/package.json +6 -5
  87. package/web/AGENTS.md +10 -11
  88. package/web/public/app.css +38 -0
  89. package/web/public/app.js +277 -56
  90. package/dist/agent-PMWCDWOW.js +0 -30
  91. package/dist/chunk-73TS2H42.js.map +0 -1
  92. package/dist/chunk-7Z4Y3VKM.js +0 -26
  93. package/dist/chunk-7Z4Y3VKM.js.map +0 -1
  94. package/dist/chunk-AOAQU7PD.js +0 -180
  95. package/dist/chunk-AOAQU7PD.js.map +0 -1
  96. package/dist/chunk-J2LJB2OH.js.map +0 -1
  97. package/dist/chunk-OLUOZLU5.js.map +0 -1
  98. package/dist/chunk-QVLIIGBU.js.map +0 -1
  99. package/dist/chunk-QZOBR6YF.js.map +0 -1
  100. package/dist/chunk-ROIIEVZH.js.map +0 -1
  101. package/dist/chunk-X6GY3CM2.js.map +0 -1
  102. package/dist/chunk-YA6FWFYW.js.map +0 -1
  103. package/dist/execute-QYLJ5L4T.js +0 -36
  104. package/dist/init-XBERAZ4O.js +0 -24
  105. package/dist/plan-RXOW32KY.js +0 -34
  106. package/dist/pr-3WFYAVA7.js +0 -39
  107. package/dist/pr-review-RK63ZEMM.js +0 -32
  108. package/dist/prd-LRV6IW3E.js +0 -33
  109. package/dist/review-AEFISJZD.js +0 -35
  110. package/dist/routing-EA5NJGNU.js +0 -94
  111. package/dist/routing-EA5NJGNU.js.map +0 -1
  112. package/dist/run-HSC7R33Y.js +0 -55
  113. /package/dist/{agent-PMWCDWOW.js.map → agent-TB6W7PT7.js.map} +0 -0
  114. /package/dist/{analyze-556KCJKZ.js.map → analyze-6M3KEOX7.js.map} +0 -0
  115. /package/dist/{apply-WVV7G7WN.js.map → apply-ADB3ZK7W.js.map} +0 -0
  116. /package/dist/{bench-UBFGKUHR.js.map → bench-FM7I7EIV.js.map} +0 -0
  117. /package/dist/{chunk-DBEMD34J.js.map → chunk-32JSYXEK.js.map} +0 -0
  118. /package/dist/{chunk-OGVWJO4S.js.map → chunk-7F7LGMVO.js.map} +0 -0
  119. /package/dist/{chunk-OGN2NX57.js.map → chunk-ANI2NTR4.js.map} +0 -0
  120. /package/dist/{chunk-VK65RNFA.js.map → chunk-B3TSS7BT.js.map} +0 -0
  121. /package/dist/{chunk-MXCOSPLJ.js.map → chunk-DGRTJD5R.js.map} +0 -0
  122. /package/dist/{chunk-VTF4RWS5.js.map → chunk-DV7HUC4Z.js.map} +0 -0
  123. /package/dist/{chunk-OOX3RMD3.js.map → chunk-E6KXCV3T.js.map} +0 -0
  124. /package/dist/{chunk-4FUWWBTP.js.map → chunk-HLAPOUEM.js.map} +0 -0
  125. /package/dist/{chunk-KV2K7MK2.js.map → chunk-ISZ54SVE.js.map} +0 -0
  126. /package/dist/{chunk-GV2DABNZ.js.map → chunk-KZ5EY5XX.js.map} +0 -0
  127. /package/dist/{chunk-SW2MF47D.js.map → chunk-KZXQWC7U.js.map} +0 -0
  128. /package/dist/{chunk-2H43OVTU.js.map → chunk-LPWPFIIB.js.map} +0 -0
  129. /package/dist/{chunk-EPFC4LHT.js.map → chunk-MI5TREN3.js.map} +0 -0
  130. /package/dist/{chunk-R42YHLDV.js.map → chunk-PPZ3K4YM.js.map} +0 -0
  131. /package/dist/{chunk-H3EYBJZU.js.map → chunk-QMIQR7EE.js.map} +0 -0
  132. /package/dist/{chunk-FKWYD44M.js.map → chunk-QPGEFLMY.js.map} +0 -0
  133. /package/dist/{chunk-NQCR3HSU.js.map → chunk-RNFUVKC3.js.map} +0 -0
  134. /package/dist/{chunk-G5LACAXO.js.map → chunk-RYOUZ6EK.js.map} +0 -0
  135. /package/dist/{chunk-BSBJXPLC.js.map → chunk-SGTTR4XW.js.map} +0 -0
  136. /package/dist/{chunk-GVOZ6NDO.js.map → chunk-SOM4QA6C.js.map} +0 -0
  137. /package/dist/{chunk-PGN2VX4Y.js.map → chunk-UWDCIFTP.js.map} +0 -0
  138. /package/dist/{chunk-MCLPSL6B.js.map → chunk-VE3IYNDN.js.map} +0 -0
  139. /package/dist/{chunk-IAMIBZRF.js.map → chunk-WCCZJL7W.js.map} +0 -0
  140. /package/dist/{chunk-SVDEWOUD.js.map → chunk-XZUEFTUP.js.map} +0 -0
  141. /package/dist/{chunk-WLJVL25O.js.map → chunk-YUNBOUQH.js.map} +0 -0
  142. /package/dist/{chunk-WNROH2YE.js.map → chunk-YVPZUN6X.js.map} +0 -0
  143. /package/dist/{chunk-Q2TZA6AC.js.map → chunk-Z5O2XBWA.js.map} +0 -0
  144. /package/dist/{config-UE7IP36J.js.map → config-KGZUPAUP.js.map} +0 -0
  145. /package/dist/{conventions-Z3QC2NSG.js.map → conventions-RYN7OXJN.js.map} +0 -0
  146. /package/dist/{diagnostics-2Z5HFQOO.js.map → diagnostics-HTCWF7F4.js.map} +0 -0
  147. /package/dist/{execute-QYLJ5L4T.js.map → execute-QL3ZQIAP.js.map} +0 -0
  148. /package/dist/{generate-PB4L7V5N.js.map → generate-CX6KNHZS.js.map} +0 -0
  149. /package/dist/{git-7MUOGVRG.js.map → git-A2IP32PQ.js.map} +0 -0
  150. /package/dist/{init-XBERAZ4O.js.map → init-PDVQDRS6.js.map} +0 -0
  151. /package/dist/{operations-QDJAFZUN.js.map → operations-CAKIT2BO.js.map} +0 -0
  152. /package/dist/{permissions-XVXXENVP.js.map → permissions-G4XCAESF.js.map} +0 -0
  153. /package/dist/{plan-RXOW32KY.js.map → plan-PRORGS3L.js.map} +0 -0
  154. /package/dist/{policy-6WQZB6B2.js.map → policy-WX6O2JID.js.map} +0 -0
  155. /package/dist/{pr-3WFYAVA7.js.map → pr-27RMQI5F.js.map} +0 -0
  156. /package/dist/{pr-review-RK63ZEMM.js.map → pr-review-VNESMAMT.js.map} +0 -0
  157. /package/dist/{prd-LRV6IW3E.js.map → prd-ZNC4T5BS.js.map} +0 -0
  158. /package/dist/{ps-CX7756QG.js.map → ps-76L6ZAZL.js.map} +0 -0
  159. /package/dist/{recorder-RK6XZYF3.js.map → recorder-N7U66HCO.js.map} +0 -0
  160. /package/dist/{registry-POSB35Q4.js.map → registry-XLHHYLTR.js.map} +0 -0
  161. /package/dist/{review-AEFISJZD.js.map → review-7CREJDKB.js.map} +0 -0
  162. /package/dist/{run-HSC7R33Y.js.map → routing-VCDYHSXA.js.map} +0 -0
  163. /package/dist/{session-publisher-VVXOCJ2S.js.map → run-3MPORLF5.js.map} +0 -0
  164. /package/dist/{state-manager-TIC73GQY.js.map → session-publisher-KAJQRHNZ.js.map} +0 -0
  165. /package/dist/{usage-WDDNSIHP.js.map → usage-U7QNGCPK.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/pipeline.ts","../src/execution/plan.ts","../src/execution/containers.ts","../src/issues/graph.ts","../src/execution/order.ts"],"sourcesContent":["import type { PipelineState, TaskPlan } from '../types.js';\nimport { loadTaskPlan, saveTaskPlan } from './state-manager.js';\n\n/**\n * Ordered pipeline phases. Each phase must complete before the next can start.\n *\n * `pr-review` is deliberately NOT here: it is opt-in via `--pr-review`. Adding\n * it to the default set would make every existing `tasks.json` (which has no\n * `prReviewCompleted`) look unfinished, so `getNextPhase()` would resume into a\n * phase the user never asked for.\n */\nexport const PIPELINE_PHASES = ['init', 'prd', 'plan', 'execute', 'review', 'pr'] as const;\n\n/**\n * The default set plus the opt-in `pr-review` phase, used when the user passes\n * `--pr-review` (or the flag was persisted in `plan.prReview.enabled`).\n */\nexport const PIPELINE_PHASES_WITH_PR_REVIEW = [...PIPELINE_PHASES, 'pr-review'] as const;\n\nexport type PipelinePhase = (typeof PIPELINE_PHASES_WITH_PR_REVIEW)[number];\n\n/**\n * Pipeline phases excluding the 'pr' phase, for --no-branch mode.\n * `pr-review` is excluded too: without a branch there is no PR to review.\n */\nexport const PIPELINE_PHASES_NO_BRANCH = PIPELINE_PHASES.filter(\n (p): p is Exclude<PipelinePhase, 'pr' | 'pr-review'> => p !== 'pr',\n);\n\n/**\n * Map pipeline phases to their corresponding PipelineState field.\n * 'init' has no persisted state — it's a runtime-only check.\n */\nconst PHASE_TO_FIELD: Record<PipelinePhase, keyof PipelineState | null> = {\n init: null,\n prd: 'prdCompleted',\n plan: 'jsonCompleted',\n execute: 'executionCompleted',\n review: 'reviewCompleted',\n pr: 'prCreated',\n 'pr-review': 'prReviewCompleted',\n};\n\nexport class PipelineManager {\n private tasksJsonPath: string;\n private plan: TaskPlan;\n private activePhases: readonly PipelinePhase[];\n\n constructor(plan: TaskPlan, tasksJsonPath: string, activePhases?: readonly PipelinePhase[]) {\n this.plan = plan;\n this.tasksJsonPath = tasksJsonPath;\n this.activePhases = activePhases ?? PIPELINE_PHASES;\n }\n\n /**\n * Reload state from disk.\n */\n async reload(): Promise<void> {\n this.plan = await loadTaskPlan(this.tasksJsonPath);\n }\n\n /**\n * Check if a phase is complete.\n */\n isPhaseComplete(phase: PipelinePhase): boolean {\n const field = PHASE_TO_FIELD[phase];\n if (field === null) return true; // init is always \"complete\" after running\n return this.plan.pipeline?.[field] ?? false;\n }\n\n /**\n * Get the first incomplete phase in the pipeline.\n * Returns null if all phases are complete.\n */\n getNextPhase(): PipelinePhase | null {\n for (const phase of this.activePhases) {\n if (!this.isPhaseComplete(phase)) {\n return phase;\n }\n }\n return null;\n }\n\n /**\n * Get the current phase (alias for getNextPhase).\n */\n getCurrentPhase(): PipelinePhase | null {\n return this.getNextPhase();\n }\n\n /**\n * Check whether we can resume from a specific phase.\n * All prerequisite phases must be complete.\n */\n canResume(fromPhase: PipelinePhase): boolean {\n const idx = this.activePhases.indexOf(fromPhase);\n if (idx < 0) return false;\n\n // All active phases before fromPhase must be complete\n for (let i = 0; i < idx; i++) {\n if (!this.isPhaseComplete(this.activePhases[i])) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Mark a phase as complete and persist to disk.\n */\n async markPhaseComplete(phase: PipelinePhase): Promise<void> {\n const field = PHASE_TO_FIELD[phase];\n if (field === null) return; // init has no persisted state\n\n this.plan = {\n ...this.plan,\n pipeline: {\n ...(this.plan.pipeline ?? {\n prdCompleted: false,\n jsonCompleted: false,\n executionCompleted: false,\n reviewCompleted: false,\n prCreated: false,\n }),\n [field]: true,\n },\n };\n\n await saveTaskPlan(this.tasksJsonPath, this.plan);\n }\n}\n","import { mkdir, readFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { ZodError } from 'zod';\nimport { isoNow } from '../core/state-manager.js';\nimport type { DependencyGraph } from '../issues/graph.js';\nimport type { Issue } from '../issues/types.js';\nimport { executionPlanSchema } from '../storage/schemas.js';\nimport type { LastError, PullRequestRef } from '../types.js';\nimport { writeFileAtomic } from '../utils/fs.js';\nimport { isContainer } from './containers.js';\nimport { priorityOf } from './order.js';\nimport type {\n ExecutionPlan,\n ExecutionPlanExcluded,\n ExecutionPlanIssue,\n QueueIssueRole,\n QueueIssueStatus,\n QueueStatus,\n} from './types.js';\n\n/**\n * Building, reading, writing and advancing the execution plan of a queue.\n *\n * The plan is the only state a multi-issue run adds to the storage tree, and it\n * is written **only** for a queue with more than one Issue — a single-issue run\n * leaves the layout exactly as it was.\n */\n\nexport interface BuildExecutionPlanInput {\n /** Project id of the global storage tree. */\n projectId: string;\n /** Identifiers the user asked for, in order; the first one names the queue. */\n requested: readonly string[];\n graph: DependencyGraph;\n /** Ids to run, already ordered by `computeExecutionOrder`. */\n order: readonly string[];\n noBranch?: boolean;\n prReview?: boolean;\n /** Injectable clock, so tests can assert `createdAt` vs `updatedAt`. */\n now?: () => string;\n}\n\nfunction parentOf(graph: DependencyGraph, id: string): string | null {\n for (const node of graph.nodes.values()) {\n if (node.relations.children.includes(id)) return node.id;\n }\n return null;\n}\n\n/** Title/url/number of a node, falling back to what the id alone tells us. */\nfunction describeIssue(\n issue: Issue | null,\n id: string,\n): {\n number: number | null;\n title: string;\n url: string | null;\n source: string;\n} {\n const parsed = Number.parseInt(id, 10);\n return {\n number: issue?.number ?? (Number.isNaN(parsed) ? null : parsed),\n title: issue?.title ?? '',\n url: issue?.remoteRef ?? null,\n source: issue?.source ?? 'github',\n };\n}\n\n/**\n * Turn a graph plus an order into the persisted plan.\n *\n * Every Issue of the graph that is *not* in the order becomes an `excluded`\n * entry: the consolidated Pull Request reports them as known pending work, so a\n * hierarchy the user chose to trim never disappears silently.\n */\nexport function buildExecutionPlan(input: BuildExecutionPlanInput): ExecutionPlan {\n const now = input.now ?? isoNow;\n const at = now();\n const scheduled = new Set(input.order);\n const requested = new Set(input.requested);\n\n const issues: ExecutionPlanIssue[] = input.order.map((id, index) => {\n const node = input.graph.nodes.get(id);\n const relations = node?.relations;\n const described = describeIssue(node?.issue ?? null, id);\n const children = relations?.children ?? [];\n const role: QueueIssueRole = isContainer({\n issue: node?.issue ?? null,\n children,\n })\n ? 'container'\n : 'executable';\n\n return {\n id,\n number: described.number,\n title: described.title,\n url: described.url,\n source: described.source,\n position: index + 1,\n status: 'pending',\n origin: requested.has(id) ? 'requested' : 'discovered',\n role,\n externalDependencies: (relations?.blockedBy ?? []).filter(\n (blocker) => !scheduled.has(blocker),\n ),\n // Only the constraints that survive inside the queue: a blocker left out\n // of it is reported in `excluded`, not enforced as a dependency.\n dependsOn: (relations?.blockedBy ?? []).filter((blocker) => scheduled.has(blocker)),\n parent: relations?.parent ?? parentOf(input.graph, id),\n priority: priorityOf(node?.issue?.labels ?? []),\n heuristic: (relations?.heuristic.length ?? 0) > 0,\n failedPhase: null,\n lastError: null,\n attempts: 0,\n blockedReason: null,\n startedAt: null,\n completedAt: null,\n };\n });\n\n const excluded: ExecutionPlanExcluded[] = [];\n for (const node of input.graph.nodes.values()) {\n if (scheduled.has(node.id)) continue;\n const described = describeIssue(node.issue, node.id);\n excluded.push({\n id: node.id,\n number: described.number,\n title: described.title,\n url: described.url,\n reason: 'Discovered in the hierarchy but not selected for this run',\n });\n }\n\n return {\n schemaVersion: 1,\n id: input.requested[0] ?? (input.order[0] as string),\n project: input.projectId,\n requested: [...input.requested],\n branchName: null,\n noBranch: input.noBranch ?? false,\n prReview: input.prReview ?? false,\n status: 'pending',\n createdAt: at,\n updatedAt: at,\n truncated: input.graph.truncated,\n issues,\n excluded,\n };\n}\n\n/** Read a persisted plan. Throws with the offending fields on invalid content. */\nexport async function loadExecutionPlan(path: string): Promise<ExecutionPlan> {\n const raw: unknown = JSON.parse(await readFile(path, 'utf-8'));\n\n try {\n return executionPlanSchema.parse(raw) as ExecutionPlan;\n } catch (err) {\n if (err instanceof ZodError) {\n const issues = err.issues.map((i) => ` - ${i.path.join('.')}: ${i.message}`).join('\\n');\n throw new Error(`Invalid execution-plan.json at ${path}:\\n${issues}`);\n }\n throw err;\n }\n}\n\n/**\n * Persist a plan atomically, creating the queue directory on first write.\n *\n * `updatedAt` is stamped here so no call site can forget it — the file is the\n * only record of how far a queue got, and a stale timestamp on it is worse than\n * none.\n */\nexport async function saveExecutionPlan(\n path: string,\n plan: ExecutionPlan,\n now: () => string = isoNow,\n): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const stamped: ExecutionPlan = { ...plan, updatedAt: now() };\n await writeFileAtomic(path, `${JSON.stringify(stamped, null, 2)}\\n`);\n}\n\n/**\n * The Issue the queue should work on next, or `null` when every one of them is\n * completed.\n *\n * The order of the lookups *is* the resume policy: an interrupted issue\n * (`in_progress`) and a failed one are retried before the queue moves on, and\n * each of them picks up from its own `tasks.json` (phase-level resume) rather\n * than from the start. A `completed` issue is never revisited — that is the\n * whole point of persisting the queue.\n */\nexport interface NextQueueIssueOptions {\n /**\n * Ids this invocation is done with, however they ended. A queue that skips a\n * failing Issue and comes back to it needs a way to say \"not this one again\",\n * or \"come back later\" becomes \"come back forever\".\n */\n exclude?: ReadonlySet<string>;\n}\n\n/**\n * Whether every dependency this Issue declares *inside the queue* is finished.\n *\n * The execution order already places dependencies first, so this only bites\n * once an entry stops being `completed` — skipped, blocked or failed. Handing\n * out an Issue whose blocker was skipped is how a queue produces work that\n * cannot compile.\n */\nfunction dependenciesSatisfied(plan: ExecutionPlan, entry: ExecutionPlanIssue): boolean {\n return entry.dependsOn.every((id) => {\n const dependency = plan.issues.find((candidate) => candidate.id === id);\n if (dependency === undefined) return true;\n // A container is not work: waiting on it would deadlock the children\n // that complete it.\n if (dependency.role === 'container') return true;\n return dependency.status === 'completed';\n });\n}\n\n/**\n * The Issue to work on next.\n *\n * The order of the four lookups is the resumption policy:\n * an interrupted Issue first (it was mid-flight), then one that failed on a\n * previous invocation, then the untouched ones, and only at the end the ones\n * this queue deliberately set aside — which is what \"go on with the\n * independent work and come back to it\" means in one line.\n *\n * `blocked` is absent on purpose: it needs a human, and no ordering of the\n * queue changes that.\n */\nexport function nextQueueIssue(\n plan: ExecutionPlan,\n options: NextQueueIssueOptions = {},\n): ExecutionPlanIssue | null {\n const exclude = options.exclude ?? new Set<string>();\n const eligible = (status: QueueIssueStatus) => (entry: ExecutionPlanIssue) =>\n entry.role !== 'container' &&\n entry.status === status &&\n !exclude.has(entry.id) &&\n dependenciesSatisfied(plan, entry);\n\n return (\n plan.issues.find(eligible('in_progress')) ??\n plan.issues.find(eligible('failed')) ??\n plan.issues.find(eligible('pending')) ??\n plan.issues.find(eligible('skipped')) ??\n null\n );\n}\n\n/**\n * Status of the queue derived from its entries.\n *\n * `skipped` is *not* terminal — the queue means to come back to it — so a queue\n * holding one is still `in_progress`. `blocked` is: nothing the queue can do\n * moves it, so a queue that ends with one ends `failed`, which is what a person\n * needs to see.\n */\nexport function queueStatus(plan: ExecutionPlan): QueueStatus {\n if (plan.issues.some((entry) => entry.status === 'failed' || entry.status === 'blocked')) {\n return 'failed';\n }\n if (plan.issues.every((entry) => entry.status === 'completed')) return 'completed';\n if (plan.issues.some((entry) => entry.status !== 'pending')) return 'in_progress';\n return 'pending';\n}\n\n/** Whether every Issue of the queue has been resolved. */\nexport function isQueueComplete(plan: ExecutionPlan): boolean {\n return plan.issues.every((entry) => entry.status === 'completed');\n}\n\n/** Apply `patch` to one entry and recompute the queue status. Pure. */\nfunction updateIssue(\n plan: ExecutionPlan,\n id: string,\n patch: Partial<ExecutionPlanIssue>,\n): ExecutionPlan {\n const issues = plan.issues.map((entry) => (entry.id === id ? { ...entry, ...patch } : entry));\n const next: ExecutionPlan = { ...plan, issues };\n return { ...next, status: queueStatus(next) };\n}\n\nexport function markQueueIssueInProgress(\n plan: ExecutionPlan,\n id: string,\n now: () => string = isoNow,\n): ExecutionPlan {\n const current = plan.issues.find((entry) => entry.id === id);\n return updateIssue(plan, id, {\n status: 'in_progress',\n // Preserved across a resume: the queue reports when the work on this Issue\n // really began, not when it was last picked up.\n startedAt: current?.startedAt ?? now(),\n failedPhase: null,\n lastError: null,\n });\n}\n\nfunction completeResolvedContainers(plan: ExecutionPlan, now: () => string): ExecutionPlan {\n let next = plan;\n let changed = true;\n while (changed) {\n changed = false;\n for (const entry of next.issues) {\n if (entry.role !== 'container' || entry.status === 'completed') continue;\n const children = next.issues.filter((candidate) => candidate.parent === entry.id);\n if (children.length === 0) continue;\n if (children.every((child) => child.status === 'completed')) {\n next = updateIssue(next, entry.id, {\n status: 'completed',\n completedAt: now(),\n failedPhase: null,\n lastError: null,\n });\n changed = true;\n }\n }\n }\n return next;\n}\n\nexport function markQueueIssueCompleted(\n plan: ExecutionPlan,\n id: string,\n now: () => string = isoNow,\n): ExecutionPlan {\n return completeResolvedContainers(\n updateIssue(plan, id, {\n status: 'completed',\n completedAt: now(),\n failedPhase: null,\n lastError: null,\n }),\n now,\n );\n}\n\nexport function markQueueIssueFailed(\n plan: ExecutionPlan,\n id: string,\n failure: { phase: string | null; error: LastError | null },\n): ExecutionPlan {\n const current = plan.issues.find((entry) => entry.id === id);\n return updateIssue(plan, id, {\n status: 'failed',\n failedPhase: failure.phase,\n lastError: failure.error,\n attempts: (current?.attempts ?? 0) + 1,\n });\n}\n\n/**\n * Set an Issue aside and come back to it later.\n *\n * The difference from `failed` is the whole point of `--on-issue-failure skip`:\n * a failure that stopped this attempt is not a verdict on the eleven other\n * Issues in the queue, and `skipped` is the status that says \"not now\" rather\n * than \"not at all\". `attempts` is incremented here because the counter is what\n * keeps \"come back later\" from becoming \"come back forever\".\n */\nexport function markQueueIssueSkipped(\n plan: ExecutionPlan,\n id: string,\n failure: { phase: string | null; error: LastError | null },\n): ExecutionPlan {\n const current = plan.issues.find((entry) => entry.id === id);\n return updateIssue(plan, id, {\n status: 'skipped',\n failedPhase: failure.phase,\n lastError: failure.error,\n attempts: (current?.attempts ?? 0) + 1,\n });\n}\n\n/**\n * Stop working on an Issue until a person looks at it.\n *\n * `blocked` is never handed back out by `nextQueueIssue`: waiting cannot fix\n * a missing credential or a repository mid-rebase, and a queue that could\n * unblock itself would spin on the same cause forever.\n */\nexport function markQueueIssueBlocked(\n plan: ExecutionPlan,\n id: string,\n reason: string,\n failure: { phase: string | null; error: LastError | null },\n): ExecutionPlan {\n const current = plan.issues.find((entry) => entry.id === id);\n return updateIssue(plan, id, {\n status: 'blocked',\n blockedReason: reason,\n failedPhase: failure.phase,\n lastError: failure.error,\n attempts: (current?.attempts ?? 0) + 1,\n });\n}\n\n/** Record the branch every Issue of the queue shares. */\nexport function setQueueBranch(plan: ExecutionPlan, branchName: string): ExecutionPlan {\n return { ...plan, branchName };\n}\n\n/** Record the single Pull Request that consolidated the queue. */\nexport function setQueuePullRequest(\n plan: ExecutionPlan,\n pullRequest: PullRequestRef,\n): ExecutionPlan {\n return { ...plan, pullRequest };\n}\n","import type { DependencyGraph } from '../issues/graph.js';\nimport type { Issue } from '../issues/types.js';\n\nexport const CONTAINER_SIGNALS = ['children', 'issue-type', 'label', 'title-prefix'] as const;\n\nexport type ContainerSignal = (typeof CONTAINER_SIGNALS)[number];\n\nexport interface ContainerConfig {\n detect: readonly ContainerSignal[];\n issueTypes: readonly string[];\n labels: readonly string[];\n titlePrefixes: readonly string[];\n}\n\n/** Unconfigured repos: only the universal signal. */\nexport const DEFAULT_CONTAINER_CONFIG: ContainerConfig = {\n detect: ['children'],\n issueTypes: ['Epic'],\n labels: ['epic'],\n titlePrefixes: ['[Epic]'],\n};\n\nexport interface ContainerProbe {\n issue: Pick<Issue, 'title' | 'labels' | 'type'> | null;\n children: readonly string[];\n}\n\nfunction enabled(config: ContainerConfig, signal: ContainerSignal): boolean {\n return config.detect.includes(signal);\n}\n\nfunction hasTitlePrefix(title: string, prefixes: readonly string[]): boolean {\n const trimmed = title.trim();\n return prefixes.some((prefix) => trimmed.toLowerCase().startsWith(prefix.toLowerCase()));\n}\n\n/**\n * Precedence: children > issue type > label > title prefix.\n * Having children always wins when that signal is enabled.\n */\nexport function isContainer(\n probe: ContainerProbe,\n config: ContainerConfig = DEFAULT_CONTAINER_CONFIG,\n): boolean {\n if (enabled(config, 'children') && probe.children.length > 0) return true;\n\n const issue = probe.issue;\n if (issue === null) return false;\n\n if (enabled(config, 'issue-type')) {\n const type = issue.type?.trim();\n if (\n type !== undefined &&\n type !== '' &&\n config.issueTypes.some((name) => name.toLowerCase() === type.toLowerCase())\n ) {\n return true;\n }\n }\n\n if (enabled(config, 'label')) {\n const labels = new Set(issue.labels.map((label) => label.toLowerCase()));\n if (config.labels.some((label) => labels.has(label.toLowerCase()))) return true;\n }\n\n if (enabled(config, 'title-prefix') && hasTitlePrefix(issue.title, config.titlePrefixes)) {\n return true;\n }\n\n return false;\n}\n\n/** Root plus every descendant reached through `children`. */\nexport function collectCascadeIds(graph: DependencyGraph, roots: readonly string[]): string[] {\n const ids = new Set<string>();\n const walk = (id: string): void => {\n if (ids.has(id)) return;\n ids.add(id);\n for (const child of graph.nodes.get(id)?.relations.children ?? []) {\n walk(child);\n }\n };\n for (const root of roots) walk(root);\n return [...ids];\n}\n","import { emptyRelations, uniqueIds } from './relations.js';\nimport type { Issue, IssueRelations } from './types.js';\n\n/**\n * Dependency graph of a set of Issues, built by walking the relations every\n * provider exposes through `fetchRelations`.\n *\n * The traversal is deliberately *structural*: it follows hierarchy\n * (parent/children) and dependencies (blockedBy/blocking) and stops there. Plain\n * mentions are recorded on each node but never expanded — a body citing \"see\n * also #12\" would otherwise drag an unrelated Issue into an execution plan the\n * user is about to confirm.\n */\n\nexport interface DependencyGraphNode {\n id: string;\n relations: IssueRelations;\n /** Distance from the closest root, in traversal hops. */\n depth: number;\n /** The Issue itself, when the caller supplied a way to read it. */\n issue: Issue | null;\n /** True when the node was requested by the user rather than discovered. */\n root: boolean;\n}\n\nexport interface DependencyGraph {\n /** Ids the traversal started from, in the order they were requested. */\n roots: string[];\n /** Every discovered node, keyed by id, in discovery order. */\n nodes: Map<string, DependencyGraphNode>;\n /**\n * Dependency cycles found among the discovered nodes, each listed once,\n * starting at its smallest member. Reported rather than thrown: discovery\n * must still answer, and it is the ordering layer that refuses to run.\n */\n cycles: string[][];\n /** True when a limit stopped the traversal before it was exhausted. */\n truncated: boolean;\n limits: { maxNodes: number; maxDepth: number };\n}\n\n/**\n * Conservative defaults: a real hierarchy is a handful of Issues, and each node\n * costs several API calls. A malformed (or simply huge) graph must not turn a\n * `run` into a rate-limit incident.\n */\nexport const DEFAULT_MAX_NODES = 25;\nexport const DEFAULT_MAX_DEPTH = 3;\n\nexport interface BuildDependencyGraphOptions {\n maxNodes?: number;\n maxDepth?: number;\n /** Issues the caller already resolved, so the traversal does not re-read them. */\n known?: Iterable<Issue>;\n /** Reader for the Issues the traversal discovers. Optional. */\n fetchIssue?: (id: string) => Promise<Issue | null>;\n /** Warning sink for a source that failed. Silent by default. */\n warn?: (message: string) => void;\n}\n\n/** Edge `from` → `to`, meaning \"`from` must be resolved before `to`\". */\nexport interface DependencyEdge {\n from: string;\n to: string;\n}\n\n/**\n * Ordering constraints of a graph: only hierarchy-free, explicit dependencies.\n *\n * `blockedBy`/`blocking` are the two spellings of the same fact, so both are\n * normalized into a single direction here. Parent/child is **not** a constraint\n * — it is a presentation and tie-breaking concern (see `computeExecutionOrder`),\n * because a parent is usually an umbrella that neither blocks nor is blocked by\n * its children.\n *\n * Edges pointing outside the graph are dropped: an Issue the traversal never\n * reached cannot be scheduled, so a constraint against it is unenforceable.\n */\nexport function dependencyEdges(graph: DependencyGraph): DependencyEdge[] {\n const edges: DependencyEdge[] = [];\n const seen = new Set<string>();\n\n const add = (from: string, to: string): void => {\n if (from === to || !graph.nodes.has(from) || !graph.nodes.has(to)) return;\n const key = `${from}->${to}`;\n if (seen.has(key)) return;\n seen.add(key);\n edges.push({ from, to });\n };\n\n for (const node of graph.nodes.values()) {\n for (const blocker of node.relations.blockedBy) {\n add(blocker, node.id);\n }\n for (const blocked of node.relations.blocking) {\n add(node.id, blocked);\n }\n }\n\n return edges;\n}\n\n/** Every cycle of the dependency edges, each reported once. */\nexport function findCycles(graph: DependencyGraph): string[][] {\n const adjacency = new Map<string, string[]>();\n for (const { from, to } of dependencyEdges(graph)) {\n const list = adjacency.get(from);\n if (list === undefined) {\n adjacency.set(from, [to]);\n } else {\n list.push(to);\n }\n }\n\n const cycles: string[][] = [];\n const reported = new Set<string>();\n const state = new Map<string, 'visiting' | 'done'>();\n const stack: string[] = [];\n\n const record = (cycle: string[]): void => {\n // Rotate to the smallest member so the same cycle found from two entry\n // points is reported once.\n let pivot = 0;\n for (let i = 1; i < cycle.length; i++) {\n if (compareIds(cycle[i] as string, cycle[pivot] as string) < 0) pivot = i;\n }\n const normalized = [...cycle.slice(pivot), ...cycle.slice(0, pivot)];\n const key = normalized.join('->');\n if (reported.has(key)) return;\n reported.add(key);\n cycles.push(normalized);\n };\n\n const visit = (id: string): void => {\n state.set(id, 'visiting');\n stack.push(id);\n\n for (const next of adjacency.get(id) ?? []) {\n const status = state.get(next);\n if (status === 'visiting') {\n record(stack.slice(stack.indexOf(next)));\n continue;\n }\n if (status === undefined) {\n visit(next);\n }\n }\n\n stack.pop();\n state.set(id, 'done');\n };\n\n for (const id of graph.nodes.keys()) {\n if (!state.has(id)) visit(id);\n }\n\n return cycles;\n}\n\n/** Numeric when both ids are numbers, lexicographic otherwise. */\nexport function compareIds(a: string, b: string): number {\n const na = Number(a);\n const nb = Number(b);\n if (Number.isInteger(na) && Number.isInteger(nb)) {\n return na - nb;\n }\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** Ids a node links to structurally, in traversal order. */\nfunction neighbours(relations: IssueRelations): string[] {\n return uniqueIds(\n [\n ...(relations.parent === null ? [] : [relations.parent]),\n ...relations.children,\n ...relations.blockedBy,\n ...relations.blocking,\n ],\n relations.id,\n );\n}\n\n/**\n * Walk the relations of `roots` breadth-first and return the whole structure.\n *\n * Failures never abort the walk: a node whose relations cannot be read enters\n * the graph with empty relations (and a warning), exactly like an Issue that\n * genuinely relates to nothing. That keeps a partially unavailable API from\n * costing the user the Issues that *were* discovered.\n *\n * Breadth-first is what makes `depth` meaningful under a limit: when the walk is\n * truncated, what is missing is the far edge of the graph, not a random subset.\n */\nexport async function buildDependencyGraph(\n roots: readonly string[],\n fetchRelations: (id: string) => Promise<IssueRelations | null>,\n options: BuildDependencyGraphOptions = {},\n): Promise<DependencyGraph> {\n const maxNodes = options.maxNodes ?? DEFAULT_MAX_NODES;\n const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;\n const warn = options.warn ?? ((): void => {});\n\n const known = new Map<string, Issue>();\n for (const issue of options.known ?? []) {\n known.set(issue.id, issue);\n }\n\n const rootIds = uniqueIds(roots);\n const nodes = new Map<string, DependencyGraphNode>();\n const queued = new Set<string>(rootIds);\n let truncated = false;\n\n let frontier: { id: string; depth: number }[] = rootIds.map((id) => ({ id, depth: 0 }));\n\n while (frontier.length > 0) {\n const next: { id: string; depth: number }[] = [];\n\n for (const { id, depth } of frontier) {\n if (nodes.size >= maxNodes) {\n truncated = true;\n break;\n }\n\n let relations: IssueRelations | null = null;\n try {\n relations = await fetchRelations(id);\n } catch (err) {\n warn(\n `Could not read the relations of issue '${id}': ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n\n let issue = known.get(id) ?? null;\n if (issue === null && options.fetchIssue !== undefined) {\n try {\n issue = await options.fetchIssue(id);\n } catch (err) {\n warn(`Could not read issue '${id}': ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n const resolved = relations ?? emptyRelations(id);\n nodes.set(id, { id, relations: resolved, depth, issue, root: rootIds.includes(id) });\n\n if (depth >= maxDepth) {\n // Only a node that actually has unexplored neighbours truncates the\n // graph; a leaf at max depth explored everything there was.\n if (neighbours(resolved).some((neighbour) => !queued.has(neighbour))) {\n truncated = true;\n }\n continue;\n }\n\n for (const neighbour of neighbours(resolved)) {\n if (queued.has(neighbour)) continue;\n queued.add(neighbour);\n next.push({ id: neighbour, depth: depth + 1 });\n }\n }\n\n if (nodes.size >= maxNodes && next.length > 0) {\n truncated = true;\n break;\n }\n frontier = next;\n }\n\n const graph: DependencyGraph = {\n roots: rootIds,\n nodes,\n cycles: [],\n truncated,\n limits: { maxNodes, maxDepth },\n };\n\n linkReferencedBy(graph);\n graph.cycles = findCycles(graph);\n\n return graph;\n}\n\n/**\n * Complete `referencedBy` with the inverse of `references` among the discovered\n * nodes.\n *\n * The origin only reports the citations it can see (GitHub's timeline covers\n * cross-references but not, for instance, a mention added by the textual\n * heuristic); inverting what the graph already holds costs no API call and\n * keeps the two directions consistent inside it.\n */\nfunction linkReferencedBy(graph: DependencyGraph): void {\n for (const node of graph.nodes.values()) {\n for (const cited of node.relations.references) {\n const target = graph.nodes.get(cited);\n if (target === undefined || target.id === node.id) continue;\n target.relations.referencedBy = uniqueIds(\n [...target.relations.referencedBy, node.id],\n target.id,\n );\n }\n }\n}\n","import { compareIds, type DependencyGraph, dependencyEdges, findCycles } from '../issues/graph.js';\nimport type { IssuePriority } from './types.js';\n\n/**\n * Turning a dependency graph into the order the queue runs in.\n *\n * The criteria are applied in the exact precedence the initiative specifies:\n *\n * 1. **dependencies and blocks** — hard constraints; an Issue never starts\n * before something it depends on has finished. This is the topological part\n * and the only one that can make the computation fail (a cycle);\n * 2. **hierarchy** — with two Issues both ready to run, the ancestor goes\n * first, so an umbrella Issue frames the work of its sub-issues;\n * 3. **priority** — the GitHub labels `high`, `medium` and `low`;\n * 4. **logical order** — the identifier, numerically when it is a number.\n *\n * Everything below the first item is a *tie-break among Issues that are already\n * free to run*, never a constraint: a `high` Issue that depends on a `low` one\n * still runs second, which is the whole point of the feature.\n */\n\nconst PRIORITY_LABELS: Record<string, IssuePriority> = {\n high: 'high',\n medium: 'medium',\n low: 'low',\n};\n\n/** Ranking of a priority; an Issue with no label sorts after every labelled one. */\nconst PRIORITY_RANK: Record<IssuePriority, number> = { high: 0, medium: 1, low: 2 };\nconst NO_PRIORITY_RANK = 3;\n\n/**\n * Priority carried by a label set, or `null` when there is none.\n *\n * Both the bare labels used by this repository (`high`) and the qualified\n * spellings other projects use (`priority: high`, `priority/high`, `P-high`)\n * are accepted; anything else is simply not a priority. The absence of a label\n * is never an error — most Issues have none.\n */\nexport function priorityOf(labels: readonly string[]): IssuePriority | null {\n for (const label of labels) {\n const normalized = label.trim().toLowerCase();\n const direct = PRIORITY_LABELS[normalized];\n if (direct !== undefined) return direct;\n\n const qualified = /^(?:priority|prio|p)\\s*[:/-]\\s*(high|medium|low)$/.exec(normalized);\n const matched = qualified?.[1];\n if (matched !== undefined) return PRIORITY_LABELS[matched] as IssuePriority;\n }\n return null;\n}\n\nexport interface ExecutionOrderOptions {\n /**\n * Subset of the graph to schedule. Defaults to every node — the \"run the\n * whole hierarchy\" answer; the \"only the ones I asked for\" answer passes the\n * requested ids.\n */\n include?: readonly string[];\n}\n\nexport type ExecutionOrderResult =\n | { ok: true; order: string[] }\n | { ok: false; cycles: string[][] };\n\n/** Number of ancestors of `id` inside the selection: 0 for a top-level Issue. */\nfunction hierarchyDepth(\n id: string,\n parentOf: Map<string, string | null>,\n selected: Set<string>,\n): number {\n let depth = 0;\n let current = parentOf.get(id) ?? null;\n const seen = new Set<string>([id]);\n\n while (current !== null && selected.has(current) && !seen.has(current)) {\n depth++;\n seen.add(current);\n current = parentOf.get(current) ?? null;\n }\n\n return depth;\n}\n\n/**\n * Order the selected Issues of a graph.\n *\n * Kahn's algorithm with a deterministic tie-break, so the same graph always\n * produces the same order — a plan the user confirmed must not reshuffle itself\n * on the next run.\n *\n * A cycle is reported, never worked around: an arbitrary order would silently\n * implement an Issue before its dependency, which is exactly the failure this\n * whole feature exists to prevent. Constraints pointing outside the selection\n * are dropped — an Issue that is not going to run cannot block anything.\n */\nexport function computeExecutionOrder(\n graph: DependencyGraph,\n options: ExecutionOrderOptions = {},\n): ExecutionOrderResult {\n const selected = new Set(\n (options.include ?? [...graph.nodes.keys()]).filter((id) => graph.nodes.has(id)),\n );\n\n const parentOf = new Map<string, string | null>();\n const priority = new Map<string, IssuePriority | null>();\n for (const id of selected) {\n const node = graph.nodes.get(id);\n parentOf.set(id, node?.relations.parent ?? null);\n priority.set(id, priorityOf(node?.issue?.labels ?? []));\n }\n\n const incoming = new Map<string, Set<string>>();\n const outgoing = new Map<string, string[]>();\n for (const id of selected) {\n incoming.set(id, new Set());\n outgoing.set(id, []);\n }\n for (const { from, to } of dependencyEdges(graph)) {\n if (!selected.has(from) || !selected.has(to) || from === to) continue;\n incoming.get(to)?.add(from);\n outgoing.get(from)?.push(to);\n }\n\n const depth = new Map<string, number>();\n for (const id of selected) {\n depth.set(id, hierarchyDepth(id, parentOf, selected));\n }\n\n const rank = (id: string): number => {\n const value = priority.get(id) ?? null;\n return value === null ? NO_PRIORITY_RANK : PRIORITY_RANK[value];\n };\n\n const better = (a: string, b: string): number => {\n const byHierarchy = (depth.get(a) ?? 0) - (depth.get(b) ?? 0);\n if (byHierarchy !== 0) return byHierarchy;\n const byPriority = rank(a) - rank(b);\n if (byPriority !== 0) return byPriority;\n return compareIds(a, b);\n };\n\n const ready = [...selected].filter((id) => (incoming.get(id)?.size ?? 0) === 0);\n const order: string[] = [];\n\n while (ready.length > 0) {\n ready.sort(better);\n const next = ready.shift() as string;\n order.push(next);\n\n for (const dependent of outgoing.get(next) ?? []) {\n const pending = incoming.get(dependent);\n if (pending === undefined) continue;\n pending.delete(next);\n if (pending.size === 0) {\n ready.push(dependent);\n }\n }\n }\n\n if (order.length !== selected.size) {\n // Prefer the cycles the graph already recorded; recompute only if the\n // selection is what closed the loop.\n const cycles = graph.cycles.length > 0 ? graph.cycles : findCycles(graph);\n const relevant = cycles.filter((cycle) => cycle.every((id) => selected.has(id)));\n return { ok: false, cycles: relevant.length > 0 ? relevant : cycles };\n }\n\n return { ok: true, order };\n}\n\n/** One-line description of the cycles, for an error message. */\nexport function describeCycles(cycles: readonly string[][]): string {\n return cycles.map((cycle) => [...cycle, cycle[0]].map((id) => `#${id}`).join(' → ')).join('; ');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAWO,IAAM,kBAAkB,CAAC,QAAQ,OAAO,QAAQ,WAAW,UAAU,IAAI;AAMzE,IAAM,iCAAiC,CAAC,GAAG,iBAAiB,WAAW;AAQvE,IAAM,4BAA4B,gBAAgB;AAAA,EACvD,CAAC,MAAuD,MAAM;AAChE;AAMA,IAAM,iBAAoE;AAAA,EACxE,MAAM;AAAA,EACN,KAAK;AAAA,EACL,MAAM;AAAA,EACN,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,IAAI;AAAA,EACJ,aAAa;AACf;AAEO,IAAM,kBAAN,MAAsB;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EAER,YAAY,MAAgB,eAAuB,cAAyC;AAC1F,SAAK,OAAO;AACZ,SAAK,gBAAgB;AACrB,SAAK,eAAe,gBAAgB;AAAA,EACtC;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,SAAwB;AAC5B,SAAK,OAAO,MAAM,aAAa,KAAK,aAAa;AAAA,EACnD;AAAA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AAM,UAAU,KAAK,OAAO,KAAK,CAAC,UAAU,MAAM,OAAO,EAAE;AAC3D,SAAO,YAAY,MAAM,IAAI;AAAA,IAC3B,QAAQ;AAAA,IACR,aAAa,QAAQ;AAAA,IACrB,WAAW,QAAQ;AAAA,IACnB,WAAW,SAAS,YAAY,KAAK;AAAA,EACvC,CAAC;AACH;AASO,SAAS,sBACd,MACA,IACA,QACA,SACe;AACf,QAAM,UAAU,KAAK,OAAO,KAAK,CAAC,UAAU,MAAM,OAAO,EAAE;AAC3D,SAAO,YAAY,MAAM,IAAI;AAAA,IAC3B,QAAQ;AAAA,IACR,eAAe;AAAA,IACf,aAAa,QAAQ;AAAA,IACrB,WAAW,QAAQ;AAAA,IACnB,WAAW,SAAS,YAAY,KAAK;AAAA,EACvC,CAAC;AACH;AAGO,SAAS,eAAe,MAAqB,YAAmC;AACrF,SAAO,EAAE,GAAG,MAAM,WAAW;AAC/B;AAGO,SAAS,oBACd,MACA,aACe;AACf,SAAO,EAAE,GAAG,MAAM,YAAY;AAChC;","names":["parentOf"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/web/lock.ts","../src/web/server.ts"],"sourcesContent":["import { type ChildProcess, spawn as nodeSpawn } from 'node:child_process';\nimport { randomUUID } from 'node:crypto';\nimport { mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport chalk from 'chalk';\nimport { execa } from 'execa';\nimport { isoNow } from '../core/state-manager.js';\n// The liveness probe is shared with `storage/lock.ts`, which generalised this\n// module's guard into run ownership: one definition of \"is that pid alive\",\n// with one place to get the EPERM case right.\nimport { isProcessAlive } from '../storage/lock.js';\nimport { type GetGlobalRootOptions, getGlobalRoot } from '../storage/paths.js';\nimport { type WebLock, webLockSchema } from '../storage/schemas.js';\nimport { printInfo, printWarning } from '../ui/logger.js';\nimport { getPackageVersion } from '../version.js';\nimport { startWebServer, type WebServerHandle, type WebServerOptions } from './server.js';\n\n/**\n * Single-instance guard for the web monitoring server (`~/.issue-flow/web.lock`).\n *\n * A machine runs at most one monitoring server. Two entry points build on top\n * of the same lock:\n *\n * - `ensureSingleWebServer` binds (or reuses) a server **in the calling\n * process**. It is the low-level primitive, used by the `web serve` command\n * (the standalone process that ends up owning the lock) and by this\n * module's own tests. Nothing else should call it directly.\n * - `ensureWebMonitor` (US-002) is what `run`/`execute` call: it reuses an\n * active instance exactly like `ensureSingleWebServer`, but when none\n * exists it spawns `web serve` as a **detached** child instead of binding\n * locally, so the server outlives the pipeline process. Falls back to the\n * legacy in-process `startWebServer` (US-006) when the global storage tree\n * itself is unreachable.\n */\n\n/** Lock file name, sibling of `config.json` at the global storage root. */\nexport const WEB_LOCK_FILENAME = 'web.lock';\nexport const WEB_RESTART_LOCK_FILENAME = 'web.restart.lock';\n\n/** How long a health probe against a candidate instance waits before giving up. */\nconst HEALTH_PROBE_TIMEOUT_MS = 1000;\n\ninterface WebHealth {\n ok: true;\n pid?: number;\n instanceId?: string;\n startedAt?: string;\n uptime?: number;\n version?: string;\n}\n\ninterface ManagedWebInstance {\n lock: WebLock;\n health: WebHealth;\n source: 'lock' | 'port';\n}\n\nexport interface PortOwner {\n pid: number;\n command: string;\n}\n\n/**\n * A process that loses the atomic lock creation retries this many times,\n * waiting for the winner to finish starting up, before giving up.\n */\nconst LOCK_CLAIM_RETRIES = 5;\nconst LOCK_CLAIM_RETRY_DELAY_MS = 100;\n\nexport function getWebLockFile(options: GetGlobalRootOptions = {}): string {\n return join(getGlobalRoot(options), WEB_LOCK_FILENAME);\n}\n\nfunction getWebRestartLockFile(options: GetGlobalRootOptions = {}): string {\n return join(getGlobalRoot(options), WEB_RESTART_LOCK_FILENAME);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/** 0.0.0.0 is not a connectable address; probe loopback instead, same mapping\n * `startWebServer` uses to build its own display URL. */\nfunction probeUrl(host: string, port: number): string {\n const probeHost = host === '0.0.0.0' ? '127.0.0.1' : host;\n return `http://${probeHost}:${port}/api/health`;\n}\n\nasync function probeHealth(host: string, port: number): Promise<WebHealth | null> {\n try {\n const res = await fetch(probeUrl(host, port), {\n signal: AbortSignal.timeout(HEALTH_PROBE_TIMEOUT_MS),\n });\n if (!res.ok) return null;\n const body = (await res.json()) as Record<string, unknown>;\n if (body.ok !== true) return null;\n return {\n ok: true,\n ...(typeof body.pid === 'number' && Number.isInteger(body.pid) && body.pid > 0\n ? { pid: body.pid }\n : {}),\n ...(typeof body.instanceId === 'string' && body.instanceId !== ''\n ? { instanceId: body.instanceId }\n : {}),\n ...(typeof body.startedAt === 'string' && body.startedAt !== ''\n ? { startedAt: body.startedAt }\n : {}),\n ...(typeof body.uptime === 'number' && Number.isFinite(body.uptime)\n ? { uptime: body.uptime }\n : {}),\n ...(typeof body.version === 'string' && body.version !== '' ? { version: body.version } : {}),\n };\n } catch {\n return null;\n }\n}\n\nfunction sameLock(a: WebLock | null, b: WebLock): boolean {\n return (\n a !== null &&\n a.pid === b.pid &&\n a.port === b.port &&\n a.host === b.host &&\n a.startedAt === b.startedAt &&\n a.instanceId === b.instanceId\n );\n}\n\nasync function removeWebLockIfOwned(lockFile: string, expected: WebLock): Promise<void> {\n if (sameLock(await readWebLock(lockFile), expected)) {\n await removeWebLock(lockFile);\n }\n}\n\nasync function inspectProcessCommand(pid: number): Promise<string | null> {\n const invocation =\n process.platform === 'win32'\n ? {\n command: 'powershell.exe',\n args: [\n '-NoProfile',\n '-NonInteractive',\n '-Command',\n `(Get-CimInstance Win32_Process -Filter \"ProcessId = ${pid}\").CommandLine`,\n ],\n }\n : { command: 'ps', args: ['-p', String(pid), '-o', 'command='] };\n try {\n const result = await execa(invocation.command, invocation.args, { reject: false });\n const command = result.stdout.trim();\n return result.exitCode === 0 && command !== '' ? command : null;\n } catch {\n return null;\n }\n}\n\nasync function findListeningProcess(port: number): Promise<PortOwner | null> {\n try {\n let pids: number[];\n if (process.platform === 'win32') {\n const result = await execa(\n 'powershell.exe',\n [\n '-NoProfile',\n '-NonInteractive',\n '-Command',\n `(Get-NetTCPConnection -State Listen -LocalPort ${port} -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess -Unique) -join [Environment]::NewLine`,\n ],\n { reject: false },\n );\n pids = result.stdout\n .split(/\\s+/)\n .map(Number)\n .filter((pid) => Number.isInteger(pid) && pid > 0);\n } else {\n const result = await execa('lsof', ['-nP', '-t', `-iTCP:${port}`, '-sTCP:LISTEN'], {\n reject: false,\n });\n pids = result.stdout\n .split(/\\s+/)\n .map(Number)\n .filter((pid) => Number.isInteger(pid) && pid > 0);\n }\n const unique = [...new Set(pids)];\n if (unique.length !== 1) return null;\n const pid = unique[0] as number;\n const command = await inspectProcessCommand(pid);\n return command === null ? null : { pid, command };\n } catch {\n return null;\n }\n}\n\nfunction isIssueFlowWebServe(owner: PortOwner, port: number): boolean {\n const escapedPort = String(port).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return (\n /(?:^|\\s)web\\s+serve(?:\\s|$)/.test(owner.command) &&\n new RegExp(`(?:^|\\\\s)--port(?:=|\\\\s+)${escapedPort}(?:\\\\s|$)`).test(owner.command) &&\n /issue-flow|(?:^|[/\\\\])dist[/\\\\]cli\\.js/.test(owner.command)\n );\n}\n\n/** Malformed content (partial write, older/newer incompatible shape) reads as\n * \"no lock\" — the same degrade-to-absent behavior as `loadGlobalConfig()`. */\nexport async function readWebLock(lockFile: string): Promise<WebLock | null> {\n let raw: string;\n try {\n raw = await readFile(lockFile, 'utf-8');\n } catch {\n return null;\n }\n try {\n const result = webLockSchema.safeParse(JSON.parse(raw));\n return result.success ? result.data : null;\n } catch {\n return null;\n }\n}\n\nexport async function removeWebLock(lockFile: string): Promise<void> {\n try {\n await rm(lockFile, { force: true });\n } catch {\n /* best-effort cleanup */\n }\n}\n\n/**\n * A lock is only trustworthy when both signals agree: the owning process is\n * alive AND it answers `/api/health`. A dead pid is the obvious stale case;\n * a live pid that does not answer covers a process that still exists but\n * crashed before binding, was killed -9 leaving a zombie-adjacent state, or\n * whose port was reclaimed by something else entirely. Either way the lock is\n * removed so the next attempt starts clean instead of looping on it forever.\n */\nexport async function detectActiveInstance(lockFile: string): Promise<WebLock | null> {\n const lock = await readWebLock(lockFile);\n if (lock === null) return null;\n\n const health = isProcessAlive(lock.pid) ? await probeHealth(lock.host, lock.port) : null;\n if (health !== null && (lock.instanceId === undefined || health.instanceId === lock.instanceId)) {\n return lock;\n }\n\n await removeWebLockIfOwned(lockFile, lock);\n return null;\n}\n\n/**\n * Atomic exclusive create: `wx` fails with EEXIST when another process won\n * the race, which is what lets two concurrent invocations agree on a single\n * winner without a separate lock-of-the-lock.\n */\nasync function claimWebLock(lockFile: string, lock: WebLock): Promise<boolean> {\n try {\n await writeFile(lockFile, JSON.stringify(lock, null, 2), { encoding: 'utf-8', flag: 'wx' });\n return true;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'EEXIST') return false;\n throw err;\n }\n}\n\ninterface RestartLock {\n pid: number;\n operationId: string;\n startedAt: string;\n}\n\nasync function readRestartLock(file: string): Promise<RestartLock | null> {\n try {\n const value = JSON.parse(await readFile(file, 'utf-8')) as Record<string, unknown>;\n return typeof value.pid === 'number' &&\n Number.isInteger(value.pid) &&\n value.pid > 0 &&\n typeof value.operationId === 'string' &&\n value.operationId !== '' &&\n typeof value.startedAt === 'string' &&\n value.startedAt !== ''\n ? { pid: value.pid, operationId: value.operationId, startedAt: value.startedAt }\n : null;\n } catch {\n return null;\n }\n}\n\nasync function removeRestartLockIfOwned(file: string, expected: RestartLock): Promise<void> {\n const current = await readRestartLock(file);\n if (current?.operationId === expected.operationId) {\n await rm(file, { force: true }).catch(() => {});\n }\n}\n\nasync function waitForRestart(file: string, timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const lock = await readRestartLock(file);\n if (lock === null) {\n // Missing or malformed means there is no owner we can safely wait for.\n // Do not unlink here: a restart may have claimed the path between the\n // read and this branch. The explicit acquirer cleans malformed files.\n return true;\n }\n if (!isProcessAlive(lock.pid)) {\n await removeRestartLockIfOwned(file, lock);\n return true;\n }\n await sleep(LOCK_CLAIM_RETRY_DELAY_MS);\n }\n return false;\n}\n\nasync function acquireRestartLock(\n file: string,\n timeoutMs: number,\n): Promise<{ lock: RestartLock; waited: boolean; release: () => Promise<void> } | null> {\n const deadline = Date.now() + timeoutMs;\n let waited = false;\n while (Date.now() < deadline) {\n const lock: RestartLock = {\n pid: process.pid,\n operationId: randomUUID(),\n startedAt: isoNow(),\n };\n try {\n await writeFile(file, JSON.stringify(lock, null, 2), { encoding: 'utf-8', flag: 'wx' });\n return {\n lock,\n waited,\n release: () => removeRestartLockIfOwned(file, lock),\n };\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'EEXIST') return null;\n }\n waited = true;\n const existing = await readRestartLock(file);\n if (existing === null || !isProcessAlive(existing.pid)) {\n if (existing === null) await rm(file, { force: true }).catch(() => {});\n else await removeRestartLockIfOwned(file, existing);\n continue;\n }\n await sleep(LOCK_CLAIM_RETRY_DELAY_MS);\n }\n return null;\n}\n\n/** Handle returned when reusing an already-running instance instead of\n * binding a new one — there is no local `Server` to hold, and closing it\n * must not tear down a server another process owns. */\nfunction reusedHandle(lock: WebLock): WebServerHandle {\n const displayHost = lock.host === '0.0.0.0' ? 'localhost' : lock.host;\n return {\n host: lock.host,\n port: lock.port,\n url: `http://${displayHost}:${lock.port}`,\n instanceId: lock.instanceId ?? `legacy-${lock.pid}-${lock.startedAt}`,\n close: async () => {},\n };\n}\n\n/**\n * Start the web monitoring server, first checking whether a live instance\n * already owns `web.lock` and reusing it instead of binding a second one.\n *\n * The lock is claimed only *after* a successful bind, never before: claiming\n * it with the port the server is about to (but hasn't yet) listen on would\n * make that lock briefly answer no health probe at all, and a concurrent\n * invocation would misread that gap as \"stale\" and delete a perfectly good\n * lock out from under its owner. Binding first also means two invocations\n * racing for the same fixed port never both reach the claim step — the OS\n * itself lets only one `listen()` succeed. The `wx` claim then exists for the\n * remaining race: two invocations that *both* manage to bind (only possible\n * with an ephemeral port) still agree on exactly one winner. The loser closes\n * the server it just opened and defers to whichever lock exists.\n *\n * Returns null exactly when `startWebServer` would: nothing here may affect\n * the pipeline, so a lock we cannot resolve after every retry degrades to \"no\n * server\" rather than throwing.\n */\nexport async function ensureSingleWebServer(\n options: WebServerOptions,\n lockOptions: GetGlobalRootOptions = {},\n): Promise<WebServerHandle | null> {\n const warn = options.warn ?? printWarning;\n const info = options.info ?? printInfo;\n const lockFile = getWebLockFile(lockOptions);\n\n for (let attempt = 0; attempt <= LOCK_CLAIM_RETRIES; attempt++) {\n const active = await detectActiveInstance(lockFile);\n if (active !== null) {\n info(`Reusing existing web monitor at ${reusedHandle(active).url}`);\n return reusedHandle(active);\n }\n\n const handle = await startWebServer(options);\n if (handle === null) {\n // Could not bind. Most likely another instance's listen() won a race\n // on the same fixed port between our detection above and this call —\n // its lock should be visible shortly. Anything else (port taken by an\n // unrelated process, invalid host, ...) fails the same way on the next\n // retry too, and the loop's own limit stops it from spinning forever.\n await sleep(LOCK_CLAIM_RETRY_DELAY_MS);\n continue;\n }\n\n let claimed: boolean;\n try {\n claimed = await claimWebLock(lockFile, {\n pid: process.pid,\n port: handle.port,\n host: handle.host,\n startedAt: isoNow(),\n instanceId: handle.instanceId,\n });\n } catch (err) {\n await handle.close();\n throw err;\n }\n\n if (!claimed) {\n // We bound successfully (an ephemeral port let both of us through),\n // but another invocation's lock got written first. We are not the\n // canonical instance: close what we just opened and defer to it.\n await handle.close();\n await sleep(LOCK_CLAIM_RETRY_DELAY_MS);\n continue;\n }\n\n const originalClose = handle.close;\n handle.close = async () => {\n await originalClose();\n await removeWebLock(lockFile);\n };\n return handle;\n }\n\n warn('Could not determine the web monitor lock ownership. Continuing without the web server.');\n return null;\n}\n\n/** Bounded wait for a freshly spawned `web serve` child to claim the lock. */\nconst DETACHED_CLAIM_TIMEOUT_MS = 5000;\nconst DETACHED_CLAIM_POLL_MS = 150;\n\nexport interface EnsureWebMonitorOptions extends GetGlobalRootOptions {\n /** Injectable for tests. Defaults to `node:child_process`'s `spawn`. */\n spawn?: (\n command: string,\n args: string[],\n options: { detached: true; stdio: 'ignore' },\n ) => ChildProcess;\n /** Node executable to spawn. Defaults to `process.execPath`. */\n execPath?: string;\n /** CLI entry script re-invoked as `<entry> web serve ...`. Defaults to `process.argv[1]`. */\n entryScript?: string;\n /** How long to wait for the spawned instance's lock to become healthy. */\n claimTimeoutMs?: number;\n claimPollIntervalMs?: number;\n /** Explicitly replace any managed monitor before spawning this entry point. */\n restart?: boolean;\n /** Injectable process operations used by restart and orphan recovery tests. */\n kill?: typeof process.kill;\n isAlive?: (pid: number) => boolean;\n findPortOwner?: (port: number) => Promise<PortOwner | null>;\n inspectProcess?: (pid: number) => Promise<string | null>;\n shutdownTimeoutMs?: number;\n restartLockTimeoutMs?: number;\n}\n\ninterface DiscoveryResult {\n instance: ManagedWebInstance | null;\n /** A monitor-like health endpoint answered, but ownership could not be proven. */\n unownedMonitor: boolean;\n}\n\nfunction inferredStartedAt(health: WebHealth): string {\n if (health.startedAt !== undefined) return health.startedAt;\n if (health.uptime !== undefined) {\n return new Date(Date.now() - Math.max(0, health.uptime) * 1000).toISOString();\n }\n return isoNow();\n}\n\nasync function discoverManagedInstance(\n lockFile: string,\n options: WebServerOptions,\n monitorOptions: EnsureWebMonitorOptions,\n): Promise<DiscoveryResult> {\n const existingLock = await readWebLock(lockFile);\n if (existingLock !== null) {\n const health = isProcessAlive(existingLock.pid)\n ? await probeHealth(existingLock.host, existingLock.port)\n : null;\n if (\n health !== null &&\n (existingLock.instanceId === undefined || health.instanceId === existingLock.instanceId)\n ) {\n return { instance: { lock: existingLock, health, source: 'lock' }, unownedMonitor: false };\n }\n await removeWebLockIfOwned(lockFile, existingLock);\n }\n\n // The global storage may have been deleted while the detached process kept\n // running. In that state there is no PID file to consult, so prove both\n // halves independently: an Issue Flow health endpoint and the command line\n // of the sole process listening on the configured port.\n const health = await probeHealth(options.host, options.port);\n if (health === null) return { instance: null, unownedMonitor: false };\n\n const inspect = monitorOptions.inspectProcess ?? inspectProcessCommand;\n let owner: PortOwner | null = null;\n if (health.pid !== undefined) {\n const command = await inspect(health.pid);\n if (command !== null) owner = { pid: health.pid, command };\n }\n owner ??= await (monitorOptions.findPortOwner ?? findListeningProcess)(options.port);\n if (owner === null || !isIssueFlowWebServe(owner, options.port)) {\n return { instance: null, unownedMonitor: true };\n }\n\n const recovered: WebLock = {\n pid: owner.pid,\n port: options.port,\n host: options.host,\n startedAt: inferredStartedAt(health),\n ...(health.instanceId === undefined ? {} : { instanceId: health.instanceId }),\n };\n const claimed = await claimWebLock(lockFile, recovered).catch(() => false);\n if (!claimed) {\n const winner = await readWebLock(lockFile);\n if (winner !== null) {\n const winnerHealth = await probeHealth(winner.host, winner.port);\n if (winnerHealth !== null) {\n return {\n instance: { lock: winner, health: winnerHealth, source: 'lock' },\n unownedMonitor: false,\n };\n }\n }\n }\n return { instance: { lock: recovered, health, source: 'port' }, unownedMonitor: false };\n}\n\nasync function stopManagedInstance(\n instance: ManagedWebInstance,\n lockFile: string,\n options: WebServerOptions,\n monitorOptions: EnsureWebMonitorOptions,\n): Promise<boolean> {\n const info = options.info ?? printInfo;\n const warn = options.warn ?? printWarning;\n const version =\n instance.health.version === undefined ? '' : `, version ${instance.health.version}`;\n info(`Web monitor: stopping previous instance (pid ${instance.lock.pid}${version}).`);\n\n try {\n (monitorOptions.kill ?? process.kill)(instance.lock.pid, 'SIGTERM');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ESRCH') {\n await removeWebLockIfOwned(lockFile, instance.lock);\n info(`Web monitor: previous pid ${instance.lock.pid} was already gone; stale lock removed.`);\n return true;\n }\n warn(\n `Web monitor: failed to stop pid ${instance.lock.pid} (${err instanceof Error ? err.message : String(err)}). Continuing the pipeline without restarting it.`,\n );\n return false;\n }\n\n const isAlive = monitorOptions.isAlive ?? isProcessAlive;\n const deadline = Date.now() + (monitorOptions.shutdownTimeoutMs ?? 5000);\n const pollMs = monitorOptions.claimPollIntervalMs ?? DETACHED_CLAIM_POLL_MS;\n while (Date.now() < deadline) {\n const alive = isAlive(instance.lock.pid);\n const health = alive ? await probeHealth(instance.lock.host, instance.lock.port) : null;\n if (!alive || health === null) {\n await removeWebLockIfOwned(lockFile, instance.lock);\n info(`Web monitor: previous instance stopped (pid ${instance.lock.pid}).`);\n info(\n 'Web monitor: process-local static asset and ETag caches invalidated; no on-disk web build cache exists.',\n );\n return true;\n }\n await sleep(pollMs);\n }\n\n warn(\n `Web monitor: pid ${instance.lock.pid} did not confirm shutdown in time. Continuing the pipeline without starting a competing instance.`,\n );\n return false;\n}\n\nexport type StopWebMonitorResult = 'stopped' | 'not-running' | 'unowned' | 'failed';\n\n/** Stop the managed monitor without starting a replacement. Shared by\n * `web stop` and the restart path so both use identical ownership checks. */\nexport async function stopWebMonitor(\n options: Pick<WebServerOptions, 'port' | 'host' | 'info' | 'warn'>,\n monitorOptions: EnsureWebMonitorOptions = {},\n): Promise<StopWebMonitorResult> {\n const info = options.info ?? printInfo;\n const warn = options.warn ?? printWarning;\n let lockFile: string;\n let restartLockFile: string;\n try {\n await mkdir(getGlobalRoot(monitorOptions), { recursive: true });\n lockFile = getWebLockFile(monitorOptions);\n restartLockFile = getWebRestartLockFile(monitorOptions);\n } catch (err) {\n warn(\n `Web monitor: global storage unavailable (${err instanceof Error ? err.message : String(err)}).`,\n );\n return 'failed';\n }\n\n const lease = await acquireRestartLock(\n restartLockFile,\n monitorOptions.restartLockTimeoutMs ?? 5000,\n );\n if (lease === null) {\n warn('Web monitor: could not acquire the maintenance lock; no process was stopped.');\n return 'failed';\n }\n try {\n const stale = await readWebLock(lockFile);\n const discovered = await discoverManagedInstance(lockFile, options, monitorOptions);\n if (discovered.instance === null) {\n if (stale !== null && !isProcessAlive(stale.pid)) {\n info(`Web monitor: stale lock for dead pid ${stale.pid} removed.`);\n }\n if (discovered.unownedMonitor) {\n warn(\n `Web monitor: port ${options.port} looks like an Issue Flow monitor, but its process ownership could not be verified; it was left untouched.`,\n );\n return 'unowned';\n }\n info('No web monitor is currently running.');\n return 'not-running';\n }\n return (await stopManagedInstance(discovered.instance, lockFile, options, monitorOptions))\n ? 'stopped'\n : 'failed';\n } finally {\n await lease.release();\n }\n}\n\n/**\n * Entry point for `run`/`execute`: get a web monitor without binding one in\n * this process (US-002).\n *\n * 1. Reuse a live, healthy instance exactly like `ensureSingleWebServer`.\n * 2. Otherwise, spawn `<node> <cli> web serve --port … --host … [--refresh …]`\n * detached (`{ detached: true, stdio: 'ignore' }`) and `unref()`ed, so it\n * survives this process exiting and never pipes its own stdio back here.\n * 3. Poll the lock file (bounded) until the spawned instance claims it, then\n * return a *reused* handle for it — this process never owns that `Server`,\n * the same shape `ensureSingleWebServer`'s reuse path already returns.\n *\n * Two failure modes degrade gracefully rather than affecting the pipeline:\n * the global storage tree being unreachable (no resolvable home directory)\n * falls back to `startWebServer` bound right here, exactly the pre-US-001\n * behavior (US-006); a spawn or claim failure with the storage tree otherwise\n * healthy just returns null, same contract `startWebServer` itself has.\n */\nexport async function ensureWebMonitor(\n options: WebServerOptions,\n monitorOptions: EnsureWebMonitorOptions = {},\n): Promise<WebServerHandle | null> {\n const warn = options.warn ?? printWarning;\n const info = options.info ?? printInfo;\n\n let lockFile: string;\n let restartLockFile: string;\n try {\n await mkdir(getGlobalRoot(monitorOptions), { recursive: true });\n lockFile = getWebLockFile(monitorOptions);\n restartLockFile = getWebRestartLockFile(monitorOptions);\n } catch (err) {\n warn(\n `Web monitor: global storage unavailable (${err instanceof Error ? err.message : String(err)}). Falling back to legacy in-process mode.`,\n );\n return startWebServer(options);\n }\n\n const coordinationTimeout = monitorOptions.restartLockTimeoutMs ?? 5000;\n const restartRequestedAt = Date.now();\n const restartLease = monitorOptions.restart\n ? await acquireRestartLock(restartLockFile, coordinationTimeout)\n : null;\n if (monitorOptions.restart && restartLease === null) {\n warn(\n 'Web monitor: could not acquire the restart lock. Continuing the pipeline without changing the server.',\n );\n return null;\n }\n if (!monitorOptions.restart && !(await waitForRestart(restartLockFile, coordinationTimeout))) {\n warn(\n 'Web monitor: another restart is still in progress. Continuing the pipeline without starting a competing instance.',\n );\n return null;\n }\n\n try {\n const discovered = await discoverManagedInstance(lockFile, options, monitorOptions);\n const active = discovered.instance;\n if (\n monitorOptions.restart &&\n restartLease?.waited === true &&\n active !== null &&\n Date.parse(active.lock.startedAt) >= restartRequestedAt\n ) {\n info(\n `Web monitor: a concurrent restart already started pid ${active.lock.pid}; reusing ${reusedHandle(active.lock).url}`,\n );\n return reusedHandle(active.lock);\n }\n\n if (active !== null && !monitorOptions.restart) {\n if (active.source === 'port') {\n info(\n `Recovered orphaned web monitor pid ${active.lock.pid} on port ${active.lock.port} and restored web.lock.`,\n );\n }\n const running = active.health.version;\n info(\n `Reusing existing web monitor${running === undefined ? '' : ` v${running}`} at ${chalk.bold.cyan(reusedHandle(active.lock).url)}`,\n );\n // The dashboard is served from the monitor's own memory, so an older\n // process keeps showing an older UI no matter which CLI starts the run.\n // Saying so here is the only moment the user can act on it.\n const current = getPackageVersion();\n if (running !== undefined && running !== current) {\n warn(\n `Web monitor: it runs v${running} and this CLI is v${current}, so the dashboard is the older one. Replace it with --restart-web.`,\n );\n }\n return reusedHandle(active.lock);\n }\n\n if (active !== null && monitorOptions.restart) {\n if (!(await stopManagedInstance(active, lockFile, options, monitorOptions))) return null;\n } else if (discovered.unownedMonitor) {\n warn(\n `Web monitor: port ${options.port} answers an Issue Flow health check, but its owning process could not be verified. It was left untouched and no competing server was started.`,\n );\n return null;\n } else if (monitorOptions.restart) {\n info('Web monitor: no previous managed instance was found; starting a fresh one.');\n info('Web monitor: no on-disk web build cache exists; no files were removed.');\n }\n\n const execPath = monitorOptions.execPath ?? process.execPath;\n const entryScript = monitorOptions.entryScript ?? process.argv[1];\n if (entryScript === undefined) {\n warn('Web monitor: could not determine the CLI entry point to spawn a detached server.');\n return null;\n }\n\n const args = [\n entryScript,\n 'web',\n 'serve',\n '--port',\n String(options.port),\n '--host',\n options.host,\n ];\n if (options.refreshSeconds !== undefined) {\n args.push('--refresh', String(options.refreshSeconds));\n }\n\n const spawnFn = monitorOptions.spawn ?? nodeSpawn;\n try {\n const child = spawnFn(execPath, args, { detached: true, stdio: 'ignore' });\n child.unref();\n } catch (err) {\n warn(\n `Web monitor: failed to start the detached server (${err instanceof Error ? err.message : String(err)}). Continuing without the web server.`,\n );\n return null;\n }\n\n const timeoutMs = monitorOptions.claimTimeoutMs ?? DETACHED_CLAIM_TIMEOUT_MS;\n const pollMs = monitorOptions.claimPollIntervalMs ?? DETACHED_CLAIM_POLL_MS;\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const claimed = await detectActiveInstance(lockFile);\n if (claimed !== null) {\n const handle = reusedHandle(claimed);\n const health = await probeHealth(claimed.host, claimed.port);\n if (monitorOptions.restart) {\n const version = health?.version === undefined ? '' : `, version ${health.version}`;\n info(\n `Web monitor: new instance started (pid ${claimed.pid}${version}) at ${chalk.bold.cyan(handle.url)}`,\n );\n } else {\n info(`Web monitor running at ${chalk.bold.cyan(handle.url)}`);\n }\n return handle;\n }\n await sleep(pollMs);\n }\n\n warn(\n 'Web monitor: the detached server did not start in time. Continuing without the web server.',\n );\n return null;\n } finally {\n await restartLease?.release();\n }\n}\n","import { createHash, randomUUID } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport { join } from 'node:path';\nimport chalk from 'chalk';\nimport { isAgentPhase, isAgentProviderId } from '../agents/types.js';\nimport { writeAgentPreference } from '../commands/agent.js';\nimport type { JournalEntry } from '../core/journal.js';\nimport { resolvePackageDir } from '../core/prompt-resolver.js';\nimport {\n NullPublisher,\n type SessionPublisher,\n type SessionSnapshot,\n} from '../core/session-state.js';\nimport { readDiagnostics } from '../storage/diagnostics.js';\nimport { printInfo, printWarning } from '../ui/logger.js';\nimport { getPackageVersion } from '../version.js';\nimport type { SessionDirectoryHandle } from './session-directory.js';\n\n/**\n * HTTP server for the web monitoring mode. Plain node:http — no new runtime\n * dependencies. Serves the publisher's in-memory snapshot (it never re-reads\n * issues/N/session.json) and the static UI assets.\n *\n * Resilience contract: nothing here may ever affect the pipeline. Listen\n * failures (EADDRINUSE included) log a warning and the execution continues\n * without a server; the server is unref()'d so it cannot keep the process\n * alive; request handling is wrapped so a handler error answers 500 instead\n * of crashing the process.\n */\n\n/** Max length of `issueDescription` on GET /api/sessions (dashboard preview). */\nexport const SESSION_LIST_DESCRIPTION_MAX = 280;\n\n/** Collapse whitespace and truncate for the sessions list payload. */\nexport function truncateSessionDescription(\n text: string | null | undefined,\n max = SESSION_LIST_DESCRIPTION_MAX,\n): string | null {\n if (text === null || text === undefined) return null;\n const normalized = text.replace(/\\s+/g, ' ').trim();\n if (normalized.length === 0) return normalized;\n if (normalized.length <= max) return normalized;\n return `${normalized.slice(0, max - 1).trimEnd()}…`;\n}\n\nexport interface WebServerOptions {\n /**\n * Legacy single-session mode (pre-US-003, still used by the US-006\n * fallback): serves this publisher's in-memory snapshot directly, with no\n * directory scan and no lock file involved. Mutually exclusive with\n * `sessions` — when both are given, `sessions` wins.\n */\n publisher?: SessionPublisher;\n /**\n * Multi-session mode: sessions discovered by polling the global storage\n * tree (`web/session-directory.ts`). This is what every current entry\n * point (`web serve`) passes; `publisher` only exists for the legacy path.\n */\n sessions?: SessionDirectoryHandle;\n port: number;\n host: string;\n /** Suggested UI polling interval, exposed via /api/health. */\n refreshSeconds?: number;\n /** Package version reported by /api/health. Default: read from package.json. */\n version?: string;\n /** Stable identity for this server process. Default: a fresh UUID at startup. */\n instanceId?: string;\n /** Directory holding index.html/app.css/app.js. Default: auto-resolved. */\n publicDir?: string;\n /** Info logger. Default: printInfo. */\n info?: (message: string) => void;\n /** Warning logger. Default: printWarning. */\n warn?: (message: string) => void;\n /**\n * Whether to `unref()` the underlying socket so it never keeps the process\n * alive on its own. Default `true`, matching the historical contract for a\n * server bound inline in the pipeline process. The standalone `web serve`\n * process (the detached server itself) passes `false`: it has nothing else\n * to do, so staying alive for as long as the server is bound *is* the job.\n */\n unref?: boolean;\n}\n\nexport interface WebServerHandle {\n /**\n * Absent when this handle represents an existing instance reused through\n * `ensureSingleWebServer` (`web/lock.ts`) instead of one bound locally.\n */\n server?: Server;\n /** Host the server is bound to. */\n host: string;\n /** Actual bound port (relevant when options.port is 0). */\n port: number;\n /** Human-facing access URL. */\n url: string;\n /** Identity exposed by health checks and written into web.lock. */\n instanceId: string;\n /** Close the server and release signal handlers. Idempotent, never rejects. */\n close(): Promise<void>;\n}\n\ninterface StaticAsset {\n body: string;\n contentType: string;\n}\n\nconst JSON_TYPE = 'application/json; charset=utf-8';\n\n/**\n * Uniform view over \"whatever sessions this server knows about\", so the route\n * handlers below never care whether they are backed by a single in-memory\n * publisher (legacy mode) or by the global directory scan (US-003/US-004).\n */\ninterface SessionSource {\n /** Every session currently considered active, in no particular order. */\n list(): SessionSnapshot[];\n /** A specific session by id, or undefined when it is not currently active. */\n get(sessionId: string): SessionSnapshot | undefined;\n events(sessionId: string): Promise<JournalEntry[] | undefined>;\n}\n\nfunction publisherSessionSource(publisher: SessionPublisher): SessionSource {\n return {\n list: () => {\n const snapshot = publisher.snapshot();\n return snapshot.sessionId === null ? [] : [snapshot];\n },\n get: (sessionId) => {\n const snapshot = publisher.snapshot();\n return snapshot.sessionId === sessionId ? snapshot : undefined;\n },\n events: async (sessionId) => (publisher.snapshot().sessionId === sessionId ? [] : undefined),\n };\n}\n\nfunction directorySessionSource(handle: SessionDirectoryHandle): SessionSource {\n return {\n list: () => handle.sessions().map((entry) => entry.snapshot),\n get: (sessionId) => handle.getSession(sessionId)?.snapshot,\n events: (sessionId) => handle.events(sessionId),\n };\n}\n\nfunction resolveSessionSource(options: WebServerOptions): SessionSource {\n if (options.sessions) return directorySessionSource(options.sessions);\n return publisherSessionSource(options.publisher ?? new NullPublisher());\n}\n\nconst STATIC_ROUTES: Record<string, { file: string; contentType: string }> = {\n '/': { file: 'index.html', contentType: 'text/html; charset=utf-8' },\n '/app.css': { file: 'app.css', contentType: 'text/css; charset=utf-8' },\n '/app.js': { file: 'app.js', contentType: 'text/javascript; charset=utf-8' },\n};\n\n/** Assets are read once at startup; missing files simply 404. */\nasync function loadStaticAssets(publicDir: string | null): Promise<Map<string, StaticAsset>> {\n const assets = new Map<string, StaticAsset>();\n if (publicDir === null) return assets;\n for (const [route, { file, contentType }] of Object.entries(STATIC_ROUTES)) {\n try {\n const body = await readFile(join(publicDir, file), 'utf-8');\n assets.set(route, { body, contentType });\n } catch {\n // Asset not present (e.g. UI not built yet) — route answers 404.\n }\n }\n return assets;\n}\n\n/** Headers applied to every response, including 304s and errors. */\nfunction baseHeaders(res: ServerResponse, instanceId: string): void {\n res.setHeader('Cache-Control', 'no-store');\n res.setHeader('X-Issue-Flow-Instance', instanceId);\n res.setHeader('X-Content-Type-Options', 'nosniff');\n res.setHeader('Referrer-Policy', 'no-referrer');\n res.setHeader('X-Robots-Tag', 'noindex, nofollow');\n}\n\nfunction respond(res: ServerResponse, status: number, contentType: string, body: string): void {\n res.statusCode = status;\n res.setHeader('Content-Type', contentType);\n res.end(body);\n}\n\nfunction respondJson(res: ServerResponse, status: number, payload: unknown): void {\n respond(res, status, JSON_TYPE, JSON.stringify(payload));\n}\n\nfunction isLoopbackHost(host: string): boolean {\n return host === '127.0.0.1' || host === '::1' || host === 'localhost';\n}\n\nasync function readJsonBody(req: IncomingMessage): Promise<unknown> {\n const chunks: Buffer[] = [];\n let size = 0;\n for await (const chunk of req) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n size += buffer.length;\n if (size > 64 * 1024) throw new Error('Request body too large.');\n chunks.push(buffer);\n }\n return JSON.parse(Buffer.concat(chunks).toString('utf-8') || '{}');\n}\n\n/**\n * Start the monitoring HTTP server. Returns null when the server could not\n * listen (port in use, invalid host, ...) — the pipeline continues without\n * monitoring, it is never brought down by the server.\n */\nexport async function startWebServer(options: WebServerOptions): Promise<WebServerHandle | null> {\n const info = options.info ?? printInfo;\n const warn = options.warn ?? printWarning;\n const version = options.version ?? getPackageVersion();\n const instanceId = options.instanceId ?? randomUUID();\n const startedAtMs = Date.now();\n\n // The UI ships at the package root as web/public/ (sibling of prompts/),\n // resolved the same way from src/ and from the published dist/ layout.\n const assets = await loadStaticAssets(\n options.publicDir ?? resolvePackageDir(join('web', 'public')),\n );\n\n const source = resolveSessionSource(options);\n\n // JSON serialization memoized per session id: an unchanged poll answers 304\n // with an empty body. Content-hashed rather than counter-based, unlike the\n // pre-multi-session version — a directory-backed session has no in-process\n // publisher to hand out a monotonic version(), and a hash works uniformly\n // for both sources.\n const statusCache = new Map<string, { body: string; etag: string }>();\n const statusPayload = (snapshot: SessionSnapshot): { body: string; etag: string } => {\n const key = snapshot.sessionId ?? '';\n const body = JSON.stringify(snapshot);\n const cached = statusCache.get(key);\n if (cached !== undefined && cached.body === body) return cached;\n const etag = `\"${createHash('sha1').update(body).digest('hex')}\"`;\n const entry = { body, etag };\n statusCache.set(key, entry);\n return entry;\n };\n\n const handleRequest = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n baseHeaders(res, instanceId);\n\n const requestUrl = new URL(req.url ?? '/', 'http://localhost');\n const path = requestUrl.pathname;\n\n if (req.method === 'POST' && path === '/api/config/agent') {\n if (!isLoopbackHost(options.host)) {\n respondJson(res, 403, {\n error: 'Configuration writes are disabled when the monitor is not bound to loopback.',\n });\n return;\n }\n const body = await readJsonBody(req);\n if (body === null || typeof body !== 'object' || Array.isArray(body)) {\n respondJson(res, 400, { error: 'Expected a JSON object.' });\n return;\n }\n const input = body as { provider?: unknown; model?: unknown; phase?: unknown };\n if (typeof input.provider !== 'string' || !isAgentProviderId(input.provider)) {\n respondJson(res, 400, { error: 'Invalid provider.' });\n return;\n }\n if (\n input.phase !== undefined &&\n (typeof input.phase !== 'string' || !isAgentPhase(input.phase))\n ) {\n respondJson(res, 400, { error: 'Invalid phase.' });\n return;\n }\n if (input.model !== undefined && typeof input.model !== 'string') {\n respondJson(res, 400, { error: 'Invalid model.' });\n return;\n }\n const file = await writeAgentPreference({\n target: 'global',\n provider: input.provider,\n ...(input.model ? { model: input.model } : {}),\n ...(input.phase ? { phase: input.phase } : {}),\n });\n respondJson(res, 200, { ok: true, file, appliesTo: 'future executions' });\n return;\n }\n\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n respondJson(res, 404, { error: 'Not found' });\n return;\n }\n\n if (path === '/api/status' || path === '/status.json') {\n const sessionId = requestUrl.searchParams.get('session');\n let snapshot: SessionSnapshot | undefined;\n if (sessionId !== null) {\n snapshot = source.get(sessionId);\n if (snapshot === undefined) {\n respondJson(res, 404, { error: `No active session with id '${sessionId}'.` });\n return;\n }\n } else {\n // Back-compat shorthand (US-005): with exactly one active session,\n // GET /api/status with no query string still answers it directly, the\n // same behavior a single-session run always had. Zero or several\n // active sessions is genuinely ambiguous without an id and answers an\n // explicit error instead of guessing.\n const active = source.list();\n if (active.length === 0) {\n respondJson(res, 404, {\n error: 'No active session. Pass ?session=<id> — see GET /api/sessions.',\n });\n return;\n }\n if (active.length > 1) {\n respondJson(res, 409, {\n error: 'Multiple active sessions; specify ?session=<id>.',\n sessions: active.map((entry) => entry.sessionId),\n });\n return;\n }\n snapshot = active[0];\n }\n\n const { body, etag } = statusPayload(snapshot);\n res.setHeader('ETag', etag);\n if (req.headers['if-none-match'] === etag) {\n res.statusCode = 304;\n res.end();\n return;\n }\n respond(res, 200, JSON_TYPE, body);\n return;\n }\n\n if (path === '/api/sessions') {\n // Summary fields for the multi-session dashboard (issue #35): the full\n // SessionSnapshot is already in memory, so the client can render cards\n // from this single list without N× /api/status fetches per poll.\n // issueDescription is truncated — cards only need a short preview.\n respondJson(\n res,\n 200,\n source.list().map((snapshot) => ({\n sessionId: snapshot.sessionId,\n issueNumber: snapshot.issue.number,\n issueTitle: snapshot.issue.title,\n issueDescription: truncateSessionDescription(snapshot.issue.description),\n repositoryName: snapshot.repository.name,\n currentPhase: snapshot.currentPhase,\n progressPercent: snapshot.progress.percent,\n elapsedSeconds: snapshot.elapsedSeconds,\n status: snapshot.status,\n startedAt: snapshot.startedAt,\n updatedAt: snapshot.updatedAt,\n // Resilience fields, for a card that has to answer \"is this still\n // moving\" during a six-hour run. `updatedAt` is already the last\n // activity; these two say how hard the run has had to work for it.\n retries: snapshot.execution.retries,\n correctionCycle: snapshot.execution.correctionCycle,\n attempt: snapshot.resilience.attempt,\n provider: snapshot.resilience.provider,\n lastFailureKind: snapshot.resilience.lastFailureKind,\n cooldownUntil: snapshot.resilience.cooldownUntil,\n lastActivityAt: snapshot.resilience.lastActivityAt,\n statusUrl: `/api/status?session=${encodeURIComponent(snapshot.sessionId ?? '')}`,\n eventsUrl: `/api/events?session=${encodeURIComponent(snapshot.sessionId ?? '')}`,\n })),\n );\n return;\n }\n\n if (path === '/api/events') {\n const sessionId = requestUrl.searchParams.get('session');\n if (sessionId === null) {\n respondJson(res, 400, { error: 'Pass ?session=<id>.' });\n return;\n }\n const entries = await source.events(sessionId);\n if (entries === undefined) {\n respondJson(res, 404, { error: `No active session with id '${sessionId}'.` });\n return;\n }\n respondJson(res, 200, entries);\n return;\n }\n\n if (path === '/api/diagnostics') {\n const sessionId = requestUrl.searchParams.get('session') ?? undefined;\n respondJson(res, 200, await readDiagnostics({ sessionId, limit: 500 }));\n return;\n }\n\n if (path === '/api/config') {\n const sessionId = requestUrl.searchParams.get('session');\n const snapshot = sessionId === null ? undefined : source.get(sessionId);\n respondJson(res, 200, {\n effective: snapshot?.configuration ?? null,\n capturedForSession: snapshot?.sessionId ?? null,\n writable: isLoopbackHost(options.host),\n writeScope: 'global preferences for future executions',\n });\n return;\n }\n\n if (path === '/api/health') {\n respondJson(res, 200, {\n ok: true,\n pid: process.pid,\n instanceId,\n startedAt: new Date(startedAtMs).toISOString(),\n uptime: Math.round((Date.now() - startedAtMs) / 1000),\n version,\n refreshSeconds: options.refreshSeconds ?? 5,\n capabilities: isLoopbackHost(options.host) ? ['config:agent:write'] : [],\n });\n return;\n }\n\n const asset = assets.get(path);\n if (asset) {\n respond(res, 200, asset.contentType, asset.body);\n return;\n }\n\n respondJson(res, 404, { error: 'Not found' });\n };\n\n const server = createServer((req, res) => {\n void handleRequest(req, res).catch((err) => {\n try {\n respondJson(res, 500, { error: err instanceof Error ? err.message : String(err) });\n } catch {\n // Response already destroyed — nothing to do, never crash the process.\n }\n });\n });\n\n const listening = await new Promise<boolean>((resolve) => {\n const onError = (err: NodeJS.ErrnoException): void => {\n if (err.code === 'EADDRINUSE') {\n warn(\n `Web monitor port ${options.port} is already in use. Continuing without the web server.`,\n );\n } else {\n warn(`Web monitor failed to start (${err.message}). Continuing without the web server.`);\n }\n resolve(false);\n };\n server.once('error', onError);\n server.listen(options.port, options.host, () => {\n server.removeListener('error', onError);\n resolve(true);\n });\n });\n\n if (!listening) return null;\n\n // Never keep the process alive on its own, unless explicitly told not to\n // unref: the pipeline ending must end the process. The one exception is the\n // detached `web serve` process (options.unref === false) — it has no other\n // work, so staying alive for as long as the server is bound is the point.\n if (options.unref !== false) {\n server.unref();\n }\n // Post-listen errors must never become uncaught exceptions.\n server.on('error', (err) => {\n warn(`Web monitor server error: ${err.message}`);\n });\n\n const address = server.address() as AddressInfo;\n const port = address.port;\n const displayHost = options.host === '0.0.0.0' ? 'localhost' : options.host;\n const url = `http://${displayHost}:${port}`;\n\n if (options.host === '0.0.0.0') {\n warn('Web monitor bound to 0.0.0.0: anyone on your local network can view the session state.');\n }\n info(`Web monitor running at ${chalk.bold.cyan(url)}`);\n\n let closed = false;\n let closePromise: Promise<void> | null = null;\n\n const doClose = (): Promise<void> =>\n new Promise<void>((resolve) => {\n process.removeListener('SIGINT', onSignal);\n process.removeListener('SIGTERM', onSignal);\n server.close(() => resolve());\n // Drop idle keep-alive connections so close() never hangs.\n server.closeAllConnections();\n });\n\n const close = (): Promise<void> => {\n if (closed) return closePromise ?? Promise.resolve();\n closed = true;\n closePromise = doClose();\n return closePromise;\n };\n\n // `handle.close` is built here, but ensureSingleWebServer/ensureWebMonitor\n // and the `web serve` command each wrap it afterwards (to also remove the\n // lock file, stop the session-directory poller, ...). onSignal below calls\n // `handle.close()` — the *current* value of the property — rather than the\n // `close` closed over here, so a `kill -TERM <pid>` (including `issue-flow\n // web stop`) always runs the fully wrapped shutdown, not just this raw\n // socket close. Capturing `close` directly here was a real bug: the wrapped\n // behavior only ever ran for an *explicit* `handle.close()` call, leaving\n // the lock file (and the poller) behind on every signal-driven shutdown.\n const handle: WebServerHandle = { server, host: options.host, port, url, instanceId, close };\n\n // Explicit close on SIGINT/SIGTERM, then re-raise so the default\n // termination behavior still applies.\n const onSignal = (signal: NodeJS.Signals): void => {\n void handle.close().finally(() => {\n process.kill(process.pid, signal);\n });\n };\n process.once('SIGINT', onSignal);\n process.once('SIGTERM', onSignal);\n\n return handle;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAA4B,SAAS,iBAAiB;AACtD,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,OAAO,YAAAC,WAAU,IAAI,iBAAiB;AAC/C,SAAS,QAAAC,aAAY;AACrB,OAAOC,YAAW;AAClB,SAAS,aAAa;;;ACLtB,SAAS,YAAY,kBAAkB;AACvC,SAAS,gBAAgB;AACzB,SAAS,oBAA4E;AAErF,SAAS,YAAY;AACrB,OAAO,WAAW;AA4BX,IAAM,+BAA+B;AAGrC,SAAS,2BACd,MACA,MAAM,8BACS;AACf,MAAI,SAAS,QAAQ,SAAS,OAAW,QAAO;AAChD,QAAM,aAAa,KAAK,QAAQ,QAAQ,GAAG,EAAE,KAAK;AAClD,MAAI,WAAW,WAAW,EAAG,QAAO;AACpC,MAAI,WAAW,UAAU,IAAK,QAAO;AACrC,SAAO,GAAG,WAAW,MAAM,GAAG,MAAM,CAAC,EAAE,QAAQ,CAAC;AAClD;AA+DA,IAAM,YAAY;AAelB,SAAS,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,MACT;AACA,YAAM,MAAM,MAAM;AAAA,IACpB;AAEA;AAAA,MACE;AAAA,IACF;AACA,WAAO;AAAA,EACT,UAAE;AACA,UAAM,cAAc,QAAQ;AAAA,EAC9B;AACF;","names":["randomUUID","readFile","join","chalk","join","pid","readFile","randomUUID","health","chalk"]}
@@ -1,36 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- runExecute
4
- } from "./chunk-SW2MF47D.js";
5
- import "./chunk-YA6FWFYW.js";
6
- import "./chunk-QZOBR6YF.js";
7
- import "./chunk-BSBJXPLC.js";
8
- import "./chunk-CRGIQFUQ.js";
9
- import "./chunk-L6HSKTQE.js";
10
- import "./chunk-PGN2VX4Y.js";
11
- import "./chunk-4FUWWBTP.js";
12
- import "./chunk-OGVWJO4S.js";
13
- import "./chunk-73TS2H42.js";
14
- import "./chunk-AOAQU7PD.js";
15
- import "./chunk-IAMIBZRF.js";
16
- import "./chunk-MXCOSPLJ.js";
17
- import "./chunk-C5TL7T4V.js";
18
- import "./chunk-OOX3RMD3.js";
19
- import "./chunk-J2LJB2OH.js";
20
- import "./chunk-VTF4RWS5.js";
21
- import "./chunk-SVDEWOUD.js";
22
- import "./chunk-ROIIEVZH.js";
23
- import "./chunk-FKWYD44M.js";
24
- import "./chunk-HAKDLR6N.js";
25
- import "./chunk-WNROH2YE.js";
26
- import "./chunk-GPLP7EPL.js";
27
- import "./chunk-P3LRUNC6.js";
28
- import "./chunk-R42YHLDV.js";
29
- import "./chunk-GVOZ6NDO.js";
30
- import "./chunk-QVLIIGBU.js";
31
- import "./chunk-7Z4Y3VKM.js";
32
- import "./chunk-XEYH6ZZI.js";
33
- export {
34
- runExecute
35
- };
36
- //# sourceMappingURL=execute-QYLJ5L4T.js.map
@@ -1,24 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- runInit,
4
- summarizePreflight
5
- } from "./chunk-KV2K7MK2.js";
6
- import "./chunk-J2LJB2OH.js";
7
- import "./chunk-VTF4RWS5.js";
8
- import "./chunk-SVDEWOUD.js";
9
- import "./chunk-ROIIEVZH.js";
10
- import "./chunk-FKWYD44M.js";
11
- import "./chunk-HAKDLR6N.js";
12
- import "./chunk-WNROH2YE.js";
13
- import "./chunk-GPLP7EPL.js";
14
- import "./chunk-P3LRUNC6.js";
15
- import "./chunk-R42YHLDV.js";
16
- import "./chunk-GVOZ6NDO.js";
17
- import "./chunk-QVLIIGBU.js";
18
- import "./chunk-7Z4Y3VKM.js";
19
- import "./chunk-XEYH6ZZI.js";
20
- export {
21
- runInit,
22
- summarizePreflight
23
- };
24
- //# sourceMappingURL=init-XBERAZ4O.js.map
@@ -1,34 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- runPlan
4
- } from "./chunk-GV2DABNZ.js";
5
- import "./chunk-DBEMD34J.js";
6
- import "./chunk-MCLPSL6B.js";
7
- import "./chunk-H3EYBJZU.js";
8
- import "./chunk-KMMASOA6.js";
9
- import "./chunk-4FUWWBTP.js";
10
- import "./chunk-OGVWJO4S.js";
11
- import "./chunk-73TS2H42.js";
12
- import "./chunk-AOAQU7PD.js";
13
- import "./chunk-IAMIBZRF.js";
14
- import "./chunk-MXCOSPLJ.js";
15
- import "./chunk-3D4A4B46.js";
16
- import "./chunk-OOX3RMD3.js";
17
- import "./chunk-J2LJB2OH.js";
18
- import "./chunk-VTF4RWS5.js";
19
- import "./chunk-SVDEWOUD.js";
20
- import "./chunk-ROIIEVZH.js";
21
- import "./chunk-FKWYD44M.js";
22
- import "./chunk-HAKDLR6N.js";
23
- import "./chunk-WNROH2YE.js";
24
- import "./chunk-GPLP7EPL.js";
25
- import "./chunk-P3LRUNC6.js";
26
- import "./chunk-R42YHLDV.js";
27
- import "./chunk-GVOZ6NDO.js";
28
- import "./chunk-QVLIIGBU.js";
29
- import "./chunk-7Z4Y3VKM.js";
30
- import "./chunk-XEYH6ZZI.js";
31
- export {
32
- runPlan
33
- };
34
- //# sourceMappingURL=plan-RXOW32KY.js.map
@@ -1,39 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- issueClosesLines,
4
- multiIssueContext,
5
- runPr
6
- } from "./chunk-2H43OVTU.js";
7
- import "./chunk-WLJVL25O.js";
8
- import "./chunk-DBEMD34J.js";
9
- import "./chunk-MCLPSL6B.js";
10
- import "./chunk-H3EYBJZU.js";
11
- import "./chunk-KMMASOA6.js";
12
- import "./chunk-4FUWWBTP.js";
13
- import "./chunk-OGVWJO4S.js";
14
- import "./chunk-73TS2H42.js";
15
- import "./chunk-AOAQU7PD.js";
16
- import "./chunk-IAMIBZRF.js";
17
- import "./chunk-MXCOSPLJ.js";
18
- import "./chunk-3D4A4B46.js";
19
- import "./chunk-OOX3RMD3.js";
20
- import "./chunk-J2LJB2OH.js";
21
- import "./chunk-VTF4RWS5.js";
22
- import "./chunk-SVDEWOUD.js";
23
- import "./chunk-ROIIEVZH.js";
24
- import "./chunk-FKWYD44M.js";
25
- import "./chunk-HAKDLR6N.js";
26
- import "./chunk-WNROH2YE.js";
27
- import "./chunk-GPLP7EPL.js";
28
- import "./chunk-P3LRUNC6.js";
29
- import "./chunk-R42YHLDV.js";
30
- import "./chunk-GVOZ6NDO.js";
31
- import "./chunk-QVLIIGBU.js";
32
- import "./chunk-7Z4Y3VKM.js";
33
- import "./chunk-XEYH6ZZI.js";
34
- export {
35
- issueClosesLines,
36
- multiIssueContext,
37
- runPr
38
- };
39
- //# sourceMappingURL=pr-3WFYAVA7.js.map
@@ -1,32 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- exitCodeFor,
4
- runPrReview
5
- } from "./chunk-Q2TZA6AC.js";
6
- import "./chunk-WLJVL25O.js";
7
- import "./chunk-4FUWWBTP.js";
8
- import "./chunk-OGVWJO4S.js";
9
- import "./chunk-73TS2H42.js";
10
- import "./chunk-AOAQU7PD.js";
11
- import "./chunk-IAMIBZRF.js";
12
- import "./chunk-MXCOSPLJ.js";
13
- import "./chunk-OOX3RMD3.js";
14
- import "./chunk-J2LJB2OH.js";
15
- import "./chunk-VTF4RWS5.js";
16
- import "./chunk-SVDEWOUD.js";
17
- import "./chunk-ROIIEVZH.js";
18
- import "./chunk-FKWYD44M.js";
19
- import "./chunk-HAKDLR6N.js";
20
- import "./chunk-WNROH2YE.js";
21
- import "./chunk-GPLP7EPL.js";
22
- import "./chunk-P3LRUNC6.js";
23
- import "./chunk-R42YHLDV.js";
24
- import "./chunk-GVOZ6NDO.js";
25
- import "./chunk-QVLIIGBU.js";
26
- import "./chunk-7Z4Y3VKM.js";
27
- import "./chunk-XEYH6ZZI.js";
28
- export {
29
- exitCodeFor,
30
- runPrReview
31
- };
32
- //# sourceMappingURL=pr-review-RK63ZEMM.js.map
@@ -1,33 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- runPrd
4
- } from "./chunk-OGN2NX57.js";
5
- import "./chunk-DBEMD34J.js";
6
- import "./chunk-MCLPSL6B.js";
7
- import "./chunk-H3EYBJZU.js";
8
- import "./chunk-KMMASOA6.js";
9
- import "./chunk-4FUWWBTP.js";
10
- import "./chunk-OGVWJO4S.js";
11
- import "./chunk-73TS2H42.js";
12
- import "./chunk-AOAQU7PD.js";
13
- import "./chunk-IAMIBZRF.js";
14
- import "./chunk-MXCOSPLJ.js";
15
- import "./chunk-OOX3RMD3.js";
16
- import "./chunk-J2LJB2OH.js";
17
- import "./chunk-VTF4RWS5.js";
18
- import "./chunk-SVDEWOUD.js";
19
- import "./chunk-ROIIEVZH.js";
20
- import "./chunk-FKWYD44M.js";
21
- import "./chunk-HAKDLR6N.js";
22
- import "./chunk-WNROH2YE.js";
23
- import "./chunk-GPLP7EPL.js";
24
- import "./chunk-P3LRUNC6.js";
25
- import "./chunk-R42YHLDV.js";
26
- import "./chunk-GVOZ6NDO.js";
27
- import "./chunk-QVLIIGBU.js";
28
- import "./chunk-7Z4Y3VKM.js";
29
- import "./chunk-XEYH6ZZI.js";
30
- export {
31
- runPrd
32
- };
33
- //# sourceMappingURL=prd-LRV6IW3E.js.map
@@ -1,35 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- runReview
4
- } from "./chunk-EPFC4LHT.js";
5
- import "./chunk-QZOBR6YF.js";
6
- import "./chunk-BSBJXPLC.js";
7
- import "./chunk-L6HSKTQE.js";
8
- import "./chunk-MCLPSL6B.js";
9
- import "./chunk-H3EYBJZU.js";
10
- import "./chunk-KMMASOA6.js";
11
- import "./chunk-4FUWWBTP.js";
12
- import "./chunk-OGVWJO4S.js";
13
- import "./chunk-73TS2H42.js";
14
- import "./chunk-AOAQU7PD.js";
15
- import "./chunk-IAMIBZRF.js";
16
- import "./chunk-MXCOSPLJ.js";
17
- import "./chunk-OOX3RMD3.js";
18
- import "./chunk-J2LJB2OH.js";
19
- import "./chunk-VTF4RWS5.js";
20
- import "./chunk-SVDEWOUD.js";
21
- import "./chunk-ROIIEVZH.js";
22
- import "./chunk-FKWYD44M.js";
23
- import "./chunk-HAKDLR6N.js";
24
- import "./chunk-WNROH2YE.js";
25
- import "./chunk-GPLP7EPL.js";
26
- import "./chunk-P3LRUNC6.js";
27
- import "./chunk-R42YHLDV.js";
28
- import "./chunk-GVOZ6NDO.js";
29
- import "./chunk-QVLIIGBU.js";
30
- import "./chunk-7Z4Y3VKM.js";
31
- import "./chunk-XEYH6ZZI.js";
32
- export {
33
- runReview
34
- };
35
- //# sourceMappingURL=review-AEFISJZD.js.map