issue-flow 0.11.1 → 0.13.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 (180) hide show
  1. package/README.md +79 -274
  2. package/dist/agent-BXRIEKVM.js +238 -0
  3. package/dist/agent-BXRIEKVM.js.map +1 -0
  4. package/dist/{analyze-XV3K25K3.js → analyze-WS47UYGN.js} +32 -15
  5. package/dist/analyze-WS47UYGN.js.map +1 -0
  6. package/dist/{apply-WUJHDD7A.js → apply-OS62UWRN.js} +15 -5
  7. package/dist/{apply-WUJHDD7A.js.map → apply-OS62UWRN.js.map} +1 -1
  8. package/dist/bench-SA3BOME5.js +906 -0
  9. package/dist/bench-SA3BOME5.js.map +1 -0
  10. package/dist/chunk-37N2RJW2.js +120 -0
  11. package/dist/chunk-37N2RJW2.js.map +1 -0
  12. package/dist/chunk-3XLCNVMD.js +180 -0
  13. package/dist/chunk-3XLCNVMD.js.map +1 -0
  14. package/dist/chunk-5TB6KLC2.js +72 -0
  15. package/dist/chunk-5TB6KLC2.js.map +1 -0
  16. package/dist/{chunk-OBLVLIUS.js → chunk-664Y3NDX.js} +25 -13
  17. package/dist/chunk-664Y3NDX.js.map +1 -0
  18. package/dist/chunk-6FDFRNXZ.js +357 -0
  19. package/dist/chunk-6FDFRNXZ.js.map +1 -0
  20. package/dist/chunk-7KD66LIM.js +658 -0
  21. package/dist/chunk-7KD66LIM.js.map +1 -0
  22. package/dist/chunk-7Z4Y3VKM.js +26 -0
  23. package/dist/chunk-7Z4Y3VKM.js.map +1 -0
  24. package/dist/chunk-ARFVHC2F.js +1111 -0
  25. package/dist/chunk-ARFVHC2F.js.map +1 -0
  26. package/dist/{chunk-RKTEV6EG.js → chunk-BHJCGWQX.js} +141 -12
  27. package/dist/chunk-BHJCGWQX.js.map +1 -0
  28. package/dist/chunk-BQDQTIM7.js +74 -0
  29. package/dist/chunk-BQDQTIM7.js.map +1 -0
  30. package/dist/chunk-CNBYCMSU.js +2709 -0
  31. package/dist/chunk-CNBYCMSU.js.map +1 -0
  32. package/dist/chunk-CRGIQFUQ.js +83 -0
  33. package/dist/chunk-CRGIQFUQ.js.map +1 -0
  34. package/dist/chunk-DIG5XKQQ.js +298 -0
  35. package/dist/chunk-DIG5XKQQ.js.map +1 -0
  36. package/dist/chunk-FZDR7CGH.js +71 -0
  37. package/dist/chunk-FZDR7CGH.js.map +1 -0
  38. package/dist/chunk-HEF2RMKN.js +413 -0
  39. package/dist/chunk-HEF2RMKN.js.map +1 -0
  40. package/dist/{chunk-IVHZEYAX.js → chunk-HJGGNLWI.js} +25 -19
  41. package/dist/chunk-HJGGNLWI.js.map +1 -0
  42. package/dist/chunk-HQAHNIAR.js +283 -0
  43. package/dist/chunk-HQAHNIAR.js.map +1 -0
  44. package/dist/{chunk-GANSDJV7.js → chunk-IHIEXUTC.js} +46 -24
  45. package/dist/chunk-IHIEXUTC.js.map +1 -0
  46. package/dist/chunk-IV5SS4JN.js +84 -0
  47. package/dist/chunk-IV5SS4JN.js.map +1 -0
  48. package/dist/{chunk-HC2MT7BX.js → chunk-IYV6KNVF.js} +158 -592
  49. package/dist/chunk-IYV6KNVF.js.map +1 -0
  50. package/dist/{chunk-LVKQ2AKT.js → chunk-J62QSVP6.js} +10 -8
  51. package/dist/chunk-J62QSVP6.js.map +1 -0
  52. package/dist/chunk-KMMASOA6.js +134 -0
  53. package/dist/chunk-KMMASOA6.js.map +1 -0
  54. package/dist/chunk-KQHB7ZT3.js +559 -0
  55. package/dist/chunk-KQHB7ZT3.js.map +1 -0
  56. package/dist/chunk-L6HSKTQE.js +77 -0
  57. package/dist/chunk-L6HSKTQE.js.map +1 -0
  58. package/dist/{chunk-6N7LZZ5U.js → chunk-LZ6GFQAG.js} +474 -160
  59. package/dist/chunk-LZ6GFQAG.js.map +1 -0
  60. package/dist/{chunk-HQYXVIH6.js → chunk-MIVHK5YI.js} +5 -5
  61. package/dist/chunk-NEZZ6KDR.js +1217 -0
  62. package/dist/chunk-NEZZ6KDR.js.map +1 -0
  63. package/dist/{run-DBF2VWUN.js → chunk-OPNGPUKJ.js} +747 -594
  64. package/dist/chunk-OPNGPUKJ.js.map +1 -0
  65. package/dist/chunk-P3LRUNC6.js +16 -0
  66. package/dist/chunk-P3LRUNC6.js.map +1 -0
  67. package/dist/{chunk-BXCPXRBR.js → chunk-PIVGJM6K.js} +129 -32
  68. package/dist/chunk-PIVGJM6K.js.map +1 -0
  69. package/dist/{chunk-AAY6KM7N.js → chunk-PV4OX5TC.js} +167 -196
  70. package/dist/chunk-PV4OX5TC.js.map +1 -0
  71. package/dist/chunk-QCXPNSEL.js +141 -0
  72. package/dist/chunk-QCXPNSEL.js.map +1 -0
  73. package/dist/{chunk-34WNTK3K.js → chunk-QXDNBYQF.js} +53 -13
  74. package/dist/chunk-QXDNBYQF.js.map +1 -0
  75. package/dist/chunk-SNTTOQAD.js +30 -0
  76. package/dist/chunk-SNTTOQAD.js.map +1 -0
  77. package/dist/{chunk-EY6WMHV2.js → chunk-TM67EHSV.js} +67 -23
  78. package/dist/chunk-TM67EHSV.js.map +1 -0
  79. package/dist/chunk-TVN2JVOF.js +77 -0
  80. package/dist/chunk-TVN2JVOF.js.map +1 -0
  81. package/dist/chunk-TX5WIVYP.js +129 -0
  82. package/dist/chunk-TX5WIVYP.js.map +1 -0
  83. package/dist/{chunk-KQ4JQN7T.js → chunk-UJ7XWK7J.js} +83 -21
  84. package/dist/chunk-UJ7XWK7J.js.map +1 -0
  85. package/dist/{chunk-47VIN33V.js → chunk-UOCPC2Y2.js} +596 -17
  86. package/dist/chunk-UOCPC2Y2.js.map +1 -0
  87. package/dist/chunk-XEYH6ZZI.js +289 -0
  88. package/dist/chunk-XEYH6ZZI.js.map +1 -0
  89. package/dist/cli.js +390 -40
  90. package/dist/cli.js.map +1 -1
  91. package/dist/config-MEM2IWWN.js +76 -0
  92. package/dist/contract-JH2WBIO6.js +8 -0
  93. package/dist/conventions-WV4NDXGH.js +143 -0
  94. package/dist/conventions-WV4NDXGH.js.map +1 -0
  95. package/dist/execute-NITIHHCK.js +31 -0
  96. package/dist/{generate-TBVTLMOP.js → generate-MVQI7A45.js} +39 -19
  97. package/dist/{generate-TBVTLMOP.js.map → generate-MVQI7A45.js.map} +1 -1
  98. package/dist/git-YRVRUN3C.js +31 -0
  99. package/dist/init-OKWEC3EV.js +21 -0
  100. package/dist/operations-LU6JA3BX.js +374 -0
  101. package/dist/operations-LU6JA3BX.js.map +1 -0
  102. package/dist/permissions-7NMDFU27.js +18 -0
  103. package/dist/plan-LEJJF3DE.js +31 -0
  104. package/dist/{policy-XQW5NUIE.js → policy-JSYEK5B2.js} +17 -4
  105. package/dist/policy-JSYEK5B2.js.map +1 -0
  106. package/dist/pr-HPVUZ7S3.js +36 -0
  107. package/dist/pr-review-R2QZBT3F.js +29 -0
  108. package/dist/pr-review-R2QZBT3F.js.map +1 -0
  109. package/dist/prd-5O6GYCC6.js +30 -0
  110. package/dist/prd-5O6GYCC6.js.map +1 -0
  111. package/dist/ps-TNE44R5V.js +90 -0
  112. package/dist/ps-TNE44R5V.js.map +1 -0
  113. package/dist/recorder-XGF55WXI.js +31 -0
  114. package/dist/recorder-XGF55WXI.js.map +1 -0
  115. package/dist/registry-LGPE53QD.js +15 -0
  116. package/dist/registry-LGPE53QD.js.map +1 -0
  117. package/dist/resume-QMEPMSZW.js +238 -0
  118. package/dist/resume-QMEPMSZW.js.map +1 -0
  119. package/dist/review-YKWD6SNN.js +32 -0
  120. package/dist/review-YKWD6SNN.js.map +1 -0
  121. package/dist/routing-2ZUMZPJB.js +91 -0
  122. package/dist/routing-2ZUMZPJB.js.map +1 -0
  123. package/dist/run-YU4TR62R.js +50 -0
  124. package/dist/run-YU4TR62R.js.map +1 -0
  125. package/dist/state-manager-X3PT3FGT.js +36 -0
  126. package/dist/state-manager-X3PT3FGT.js.map +1 -0
  127. package/dist/usage-VCFLDA5Y.js +174 -0
  128. package/dist/usage-VCFLDA5Y.js.map +1 -0
  129. package/dist/{web-ANQQTTRD.js → web-XVHLX62B.js} +43 -27
  130. package/dist/web-XVHLX62B.js.map +1 -0
  131. package/package.json +6 -2
  132. package/prompts/execute.md +7 -8
  133. package/prompts/plan.md +4 -5
  134. package/prompts/pr.md +13 -6
  135. package/web/AGENTS.md +3 -3
  136. package/web/public/app.css +38 -0
  137. package/web/public/app.js +132 -10
  138. package/web/public/index.html +24 -0
  139. package/dist/analyze-XV3K25K3.js.map +0 -1
  140. package/dist/chunk-34WNTK3K.js.map +0 -1
  141. package/dist/chunk-3BOHTH4V.js +0 -58
  142. package/dist/chunk-3BOHTH4V.js.map +0 -1
  143. package/dist/chunk-47VIN33V.js.map +0 -1
  144. package/dist/chunk-6N7LZZ5U.js.map +0 -1
  145. package/dist/chunk-AAY6KM7N.js.map +0 -1
  146. package/dist/chunk-BXCPXRBR.js.map +0 -1
  147. package/dist/chunk-EWDJENFW.js +0 -303
  148. package/dist/chunk-EWDJENFW.js.map +0 -1
  149. package/dist/chunk-EY6WMHV2.js.map +0 -1
  150. package/dist/chunk-GANSDJV7.js.map +0 -1
  151. package/dist/chunk-HC2MT7BX.js.map +0 -1
  152. package/dist/chunk-HDV3YDTG.js +0 -52
  153. package/dist/chunk-HDV3YDTG.js.map +0 -1
  154. package/dist/chunk-IVHZEYAX.js.map +0 -1
  155. package/dist/chunk-KQ4JQN7T.js.map +0 -1
  156. package/dist/chunk-LVKQ2AKT.js.map +0 -1
  157. package/dist/chunk-OBLVLIUS.js.map +0 -1
  158. package/dist/chunk-RKTEV6EG.js.map +0 -1
  159. package/dist/chunk-VQ5VN7DF.js +0 -1018
  160. package/dist/chunk-VQ5VN7DF.js.map +0 -1
  161. package/dist/config-4THHOXNN.js +0 -41
  162. package/dist/execute-5OEKLM5X.js +0 -15
  163. package/dist/init-PRMOTQ7N.js +0 -9
  164. package/dist/plan-Y2BYZD24.js +0 -17
  165. package/dist/policy-XQW5NUIE.js.map +0 -1
  166. package/dist/pr-H6GLOSXF.js +0 -21
  167. package/dist/pr-review-CK5FR6WX.js +0 -17
  168. package/dist/prd-4PWLCGH5.js +0 -17
  169. package/dist/review-QGVAHEZF.js +0 -15
  170. package/dist/run-DBF2VWUN.js.map +0 -1
  171. package/dist/web-ANQQTTRD.js.map +0 -1
  172. /package/dist/{chunk-HQYXVIH6.js.map → chunk-MIVHK5YI.js.map} +0 -0
  173. /package/dist/{config-4THHOXNN.js.map → config-MEM2IWWN.js.map} +0 -0
  174. /package/dist/{execute-5OEKLM5X.js.map → contract-JH2WBIO6.js.map} +0 -0
  175. /package/dist/{init-PRMOTQ7N.js.map → execute-NITIHHCK.js.map} +0 -0
  176. /package/dist/{plan-Y2BYZD24.js.map → git-YRVRUN3C.js.map} +0 -0
  177. /package/dist/{pr-H6GLOSXF.js.map → init-OKWEC3EV.js.map} +0 -0
  178. /package/dist/{pr-review-CK5FR6WX.js.map → permissions-7NMDFU27.js.map} +0 -0
  179. /package/dist/{prd-4PWLCGH5.js.map → plan-LEJJF3DE.js.map} +0 -0
  180. /package/dist/{review-QGVAHEZF.js.map → pr-HPVUZ7S3.js.map} +0 -0
@@ -1,19 +1,42 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- getProjectRoot,
4
- loadIssuesConfig,
3
+ emptyRelations,
4
+ mergeRelations,
5
+ parseTextualRelations,
6
+ uniqueIds
7
+ } from "./chunk-KMMASOA6.js";
8
+ import {
9
+ getActiveResilienceConfig,
10
+ loadIssuesConfig
11
+ } from "./chunk-CNBYCMSU.js";
12
+ import {
5
13
  resolveIssuePaths,
6
- resolveProjectPaths,
7
- run
8
- } from "./chunk-VQ5VN7DF.js";
14
+ resolveProjectPaths
15
+ } from "./chunk-HQAHNIAR.js";
9
16
  import {
10
- isoNow,
11
- issueMetadataSchema,
12
- printError,
13
17
  printInfo,
14
- printWarning,
18
+ printWarning
19
+ } from "./chunk-IYV6KNVF.js";
20
+ import {
21
+ isoNow
22
+ } from "./chunk-DIG5XKQQ.js";
23
+ import {
24
+ issueMetadataSchema
25
+ } from "./chunk-NEZZ6KDR.js";
26
+ import {
27
+ getProjectRoot,
28
+ resolvePolicy,
29
+ run
30
+ } from "./chunk-KQHB7ZT3.js";
31
+ import {
15
32
  writeFileAtomic
16
- } from "./chunk-HC2MT7BX.js";
33
+ } from "./chunk-7Z4Y3VKM.js";
34
+ import {
35
+ ClassifiedError,
36
+ actionOf,
37
+ failureOf,
38
+ requiresHumanAction
39
+ } from "./chunk-XEYH6ZZI.js";
17
40
 
18
41
  // src/issues/registry.ts
19
42
  var providers = /* @__PURE__ */ new Map();
@@ -47,134 +70,32 @@ function hashIssueContent(title, body) {
47
70
  return `sha256:${digest}`;
48
71
  }
49
72
 
50
- // src/issues/relations.ts
51
- function emptyRelations(id) {
52
- return {
53
- id,
54
- parent: null,
55
- children: [],
56
- blockedBy: [],
57
- blocking: [],
58
- references: [],
59
- referencedBy: [],
60
- heuristic: []
61
- };
62
- }
63
- function uniqueIds(ids, self) {
64
- const seen = /* @__PURE__ */ new Set();
65
- const out = [];
66
- for (const raw of ids) {
67
- const id = raw.trim();
68
- if (id === "" || id === self || seen.has(id)) continue;
69
- seen.add(id);
70
- out.push(id);
71
- }
72
- return out;
73
- }
74
- function stripCode(body) {
75
- return body.replace(/```[\s\S]*?```/g, " ").replace(/`[^`\n]*`/g, " ");
76
- }
77
- var BLOCKED_BY = /\b(?:depends[- ]on|depends upon|blocked[- ]by|requires|depende[ -]de|dependente[ -]de|bloquead[ao] por|requer)\b\s*:?\s*/gi;
78
- var BLOCKING = /\b(?:blocks|blocking|bloqueia|bloqueando)\b\s*:?\s*/gi;
79
- var TASK_ITEM = /^[ \t]*[-*]\s*\[[ xX]\]\s*(.*)$/gm;
80
- var ANY_ID = /(?:^|[^\w#])#(\d+)\b/g;
81
- function idsFrom(text) {
82
- const ids = [];
83
- const id = /#(\d+)/y;
84
- let cursor = 0;
85
- while (cursor < text.length) {
86
- id.lastIndex = cursor;
87
- const match = id.exec(text);
88
- if (match === null) break;
89
- ids.push(match[1]);
90
- cursor = id.lastIndex;
91
- const gloss = /^\s*\([^)]*\)/.exec(text.slice(cursor));
92
- if (gloss !== null) {
93
- cursor += gloss[0].length;
94
- }
95
- const separator = /^\s*(?:,|and\b|e\b|&)\s*/i.exec(text.slice(cursor));
96
- if (separator === null) break;
97
- cursor += separator[0].length;
98
- }
99
- return ids;
100
- }
101
- function collect(body, keyword) {
102
- const ids = [];
103
- keyword.lastIndex = 0;
104
- let match = keyword.exec(body);
105
- while (match !== null) {
106
- ids.push(...idsFrom(body.slice(keyword.lastIndex)));
107
- match = keyword.exec(body);
108
- }
109
- return ids;
110
- }
111
- function parseTextualRelations(body, self) {
112
- const text = stripCode(body ?? "");
113
- const blockedBy = collect(text, BLOCKED_BY);
114
- const blocking = collect(text, BLOCKING);
115
- const children = [];
116
- TASK_ITEM.lastIndex = 0;
117
- let item = TASK_ITEM.exec(text);
118
- while (item !== null) {
119
- const content = item[1] ?? "";
120
- const first = /^\s*\[?#(\d+)\b/.exec(content);
121
- if (first?.[1] !== void 0) {
122
- children.push(first[1]);
123
- }
124
- item = TASK_ITEM.exec(text);
125
- }
126
- const classified = /* @__PURE__ */ new Set([...blockedBy, ...blocking, ...children]);
127
- const references = [];
128
- ANY_ID.lastIndex = 0;
129
- let cited = ANY_ID.exec(text);
130
- while (cited !== null) {
131
- const id = cited[1];
132
- if (!classified.has(id)) {
133
- references.push(id);
134
- }
135
- ANY_ID.lastIndex = Math.max(ANY_ID.lastIndex - 1, cited.index + 1);
136
- cited = ANY_ID.exec(text);
137
- }
138
- return {
139
- children: uniqueIds(children, self),
140
- blockedBy: uniqueIds(blockedBy, self),
141
- blocking: uniqueIds(blocking, self),
142
- references: uniqueIds(references, self)
73
+ // src/issues/providers/github.ts
74
+ var VIEW_FIELDS = "number,title,body,labels,state,url,createdAt,updatedAt,issueType";
75
+ var PROBE_TIMEOUT_MS = 1e4;
76
+ function ghPolicy() {
77
+ return (failure) => resolvePolicy(failure.kind, getActiveResilienceConfig());
78
+ }
79
+ var PROBE_MAX_ATTEMPTS = 3;
80
+ var PROBE_MAX_DELAY_MS = 5e3;
81
+ function ghProbePolicy() {
82
+ const policyFor = ghPolicy();
83
+ return (failure) => {
84
+ const policy = policyFor(failure);
85
+ return {
86
+ ...policy,
87
+ maxAttempts: Math.min(policy.maxAttempts, PROBE_MAX_ATTEMPTS),
88
+ maxDelayMs: Math.min(policy.maxDelayMs, PROBE_MAX_DELAY_MS),
89
+ retryForever: false
90
+ };
143
91
  };
144
92
  }
145
- function mergeRelations(structured, textual) {
146
- const self = structured.id;
147
- const children = uniqueIds([...structured.children, ...textual.children], self);
148
- const blockedBy = uniqueIds([...structured.blockedBy, ...textual.blockedBy], self);
149
- const blocking = uniqueIds([...structured.blocking, ...textual.blocking], self);
150
- const references = uniqueIds([...structured.references, ...textual.references], self);
151
- const fromApi = /* @__PURE__ */ new Set([
152
- ...structured.children,
153
- ...structured.blockedBy,
154
- ...structured.blocking,
155
- ...structured.parent === null ? [] : [structured.parent]
156
- ]);
157
- const heuristic = uniqueIds(
158
- [...textual.children, ...textual.blockedBy, ...textual.blocking].filter(
159
- (id) => !fromApi.has(id)
160
- ),
161
- self
162
- );
163
- return {
164
- id: self,
165
- parent: structured.parent,
166
- children,
167
- blockedBy,
168
- blocking,
169
- references,
170
- referencedBy: uniqueIds(structured.referencedBy, self),
171
- heuristic
172
- };
93
+ function gh(args, options = {}) {
94
+ return run("gh", args, {
95
+ retry: ghPolicy(),
96
+ ...options.timeout === void 0 ? {} : { timeout: options.timeout }
97
+ });
173
98
  }
174
-
175
- // src/issues/providers/github.ts
176
- var VIEW_FIELDS = "number,title,body,labels,state,url,createdAt,updatedAt";
177
- var PROBE_TIMEOUT_MS = 1e4;
178
99
  var NOT_FOUND_PATTERN = /could not resolve to an issue|no issues? found|issue not found|could not find any issue/i;
179
100
  function normalizeState(state) {
180
101
  return String(state ?? "").toUpperCase() === "CLOSED" ? "closed" : "open";
@@ -183,17 +104,27 @@ function normalizeLabels(labels) {
183
104
  if (!Array.isArray(labels)) return [];
184
105
  return labels.map((label) => typeof label === "string" ? label : label?.name).filter((name) => typeof name === "string" && name.length > 0);
185
106
  }
107
+ function normalizeIssueType(value) {
108
+ if (typeof value === "string" && value.length > 0) return value;
109
+ if (value !== null && typeof value === "object" && "name" in value) {
110
+ const name = value.name;
111
+ return typeof name === "string" && name.length > 0 ? name : void 0;
112
+ }
113
+ return void 0;
114
+ }
186
115
  function toIssue(payload) {
187
116
  const title = typeof payload.title === "string" ? payload.title : "";
188
117
  const body = typeof payload.body === "string" ? payload.body : "";
189
118
  const number = typeof payload.number === "number" ? payload.number : null;
190
119
  const url = typeof payload.url === "string" && payload.url.length > 0 ? payload.url : null;
120
+ const type = normalizeIssueType(payload.issueType);
191
121
  return {
192
122
  id: number === null ? "" : String(number),
193
123
  number,
194
124
  title,
195
125
  body,
196
126
  labels: normalizeLabels(payload.labels),
127
+ ...type === void 0 ? {} : { type },
197
128
  state: normalizeState(payload.state),
198
129
  source: "github",
199
130
  remoteRef: url,
@@ -212,7 +143,7 @@ function isRecord(value) {
212
143
  }
213
144
  async function ghApiJson(path) {
214
145
  try {
215
- const result = await run("gh", ["api", path]);
146
+ const result = await gh(["api", path]);
216
147
  if (result.exitCode !== 0) return null;
217
148
  return JSON.parse(result.stdout);
218
149
  } catch {
@@ -246,27 +177,66 @@ function crossReferences(timeline, self) {
246
177
  function extractIssueNumber(output) {
247
178
  return output.match(/\/issues\/(\d+)/)?.[1] ?? null;
248
179
  }
180
+ function ghError(message, result) {
181
+ const failure = result.failure;
182
+ if (failure === void 0) return new Error(message);
183
+ return new ClassifiedError(message, failure, ghAction(failure));
184
+ }
185
+ function ghAction(failure) {
186
+ if (!requiresHumanAction(failure.kind)) return void 0;
187
+ if (failure.kind === "authentication") {
188
+ return "Run `gh auth login` to authenticate the GitHub CLI";
189
+ }
190
+ return void 0;
191
+ }
192
+ function unavailable(result, action) {
193
+ const failure = result.failure;
194
+ const needsHuman = failure === void 0 || requiresHumanAction(failure.kind);
195
+ return {
196
+ available: false,
197
+ ...failure === void 0 ? {} : { failure },
198
+ ...needsHuman ? { action } : {}
199
+ };
200
+ }
249
201
  var GitHubIssueProvider = class {
250
202
  name = "github";
251
203
  /** True when gh is installed and authenticated. Never throws. */
252
204
  async isAvailable() {
205
+ return (await this.checkAvailability()).available;
206
+ }
207
+ /**
208
+ * Whether gh is installed and authenticated, with the reason when it is not.
209
+ *
210
+ * Both probes retry on the capped probe budget, so a DNS blip during a long
211
+ * run no longer reports GitHub as unavailable and takes the whole run down
212
+ * with it — while an authentication failure is clamped to zero attempts by
213
+ * `resolvePolicy()` and comes back immediately, with the action to take.
214
+ */
215
+ async checkAvailability() {
253
216
  try {
254
- const version = await run("gh", ["--version"], { timeout: PROBE_TIMEOUT_MS });
255
- if (version.exitCode !== 0) return false;
256
- const auth = await run("gh", ["auth", "status"], { timeout: PROBE_TIMEOUT_MS });
257
- return auth.exitCode === 0;
217
+ const retry = ghProbePolicy();
218
+ const version = await run("gh", ["--version"], { retry, timeout: PROBE_TIMEOUT_MS });
219
+ if (version.exitCode !== 0) {
220
+ return unavailable(version, "Install the GitHub CLI: https://cli.github.com");
221
+ }
222
+ const auth = await run("gh", ["auth", "status"], { retry, timeout: PROBE_TIMEOUT_MS });
223
+ if (auth.exitCode !== 0) {
224
+ return unavailable(auth, "Run `gh auth login` to authenticate the GitHub CLI");
225
+ }
226
+ return { available: true };
258
227
  } catch {
259
- return false;
228
+ return { available: false };
260
229
  }
261
230
  }
262
231
  async get(id) {
263
232
  const issueId = normalizeId(id);
264
- const result = await run("gh", ["issue", "view", issueId, "--json", VIEW_FIELDS]);
233
+ const result = await gh(["issue", "view", issueId, "--json", VIEW_FIELDS]);
265
234
  if (result.exitCode !== 0) {
266
235
  const detail = (result.stderr || result.stdout).trim();
267
236
  if (NOT_FOUND_PATTERN.test(detail)) return null;
268
- throw new Error(
269
- `Failed to fetch GitHub issue #${issueId}: ${detail || "gh issue view failed"}`
237
+ throw ghError(
238
+ `Failed to fetch GitHub issue #${issueId}: ${detail || "gh issue view failed"}`,
239
+ result
270
240
  );
271
241
  }
272
242
  let payload;
@@ -287,10 +257,10 @@ var GitHubIssueProvider = class {
287
257
  if (draft.type !== void 0 && draft.type !== "") {
288
258
  args.push("--type", draft.type);
289
259
  }
290
- const result = await run("gh", args);
260
+ const result = await gh(args);
291
261
  if (result.exitCode !== 0) {
292
262
  const detail = (result.stderr || result.stdout).trim();
293
- throw new Error(`Failed to create GitHub issue: ${detail || "gh issue create failed"}`);
263
+ throw ghError(`Failed to create GitHub issue: ${detail || "gh issue create failed"}`, result);
294
264
  }
295
265
  const number = extractIssueNumber(result.stdout);
296
266
  if (!number) {
@@ -358,11 +328,12 @@ var GitHubIssueProvider = class {
358
328
  }
359
329
  async close(id) {
360
330
  const issueId = normalizeId(id);
361
- const result = await run("gh", ["issue", "close", issueId]);
331
+ const result = await gh(["issue", "close", issueId]);
362
332
  if (result.exitCode !== 0) {
363
333
  const detail = (result.stderr || result.stdout).trim();
364
- throw new Error(
365
- `Failed to close GitHub issue #${issueId}: ${detail || "gh issue close failed"}`
334
+ throw ghError(
335
+ `Failed to close GitHub issue #${issueId}: ${detail || "gh issue close failed"}`,
336
+ result
366
337
  );
367
338
  }
368
339
  }
@@ -715,10 +686,20 @@ function ensureProvidersRegistered() {
715
686
  import { createInterface } from "readline";
716
687
  var IssueResolutionError = class extends Error {
717
688
  exitCode;
718
- constructor(message, exitCode = 1) {
689
+ /**
690
+ * The verdict of the origin that failed, when one origin failed for a reason
691
+ * worth naming. It is what tells "this Issue does not exist" apart from
692
+ * "GitHub could not be reached", which are the same message today.
693
+ */
694
+ failure;
695
+ /** What a human has to do, for a failure that waiting cannot fix. */
696
+ action;
697
+ constructor(message, exitCode = 1, details = {}) {
719
698
  super(message);
720
699
  this.name = "IssueResolutionError";
721
700
  this.exitCode = exitCode;
701
+ this.failure = details.failure;
702
+ this.action = details.action;
722
703
  }
723
704
  };
724
705
  var MAX_PROMPT_ATTEMPTS = 3;
@@ -743,14 +724,23 @@ async function fetchCandidate(source, id, warn) {
743
724
  } catch (err) {
744
725
  return { source, issue: null, reason: errorMessage(err) };
745
726
  }
746
- let available;
727
+ let availability;
747
728
  try {
748
- available = await provider.isAvailable();
729
+ availability = await provider.checkAvailability?.() ?? {
730
+ available: await provider.isAvailable()
731
+ };
749
732
  } catch (err) {
750
733
  return { source, issue: null, reason: `provider unavailable (${errorMessage(err)})` };
751
734
  }
752
- if (!available) {
753
- return { source, issue: null, reason: "provider unavailable" };
735
+ if (!availability.available) {
736
+ const reason = availability.failure?.message ?? "provider unavailable";
737
+ return {
738
+ source,
739
+ issue: null,
740
+ reason,
741
+ ...availability.failure === void 0 ? {} : { failure: availability.failure },
742
+ ...availability.action === void 0 ? {} : { action: availability.action }
743
+ };
754
744
  }
755
745
  try {
756
746
  const issue = await provider.get(id);
@@ -758,7 +748,15 @@ async function fetchCandidate(source, id, warn) {
758
748
  } catch (err) {
759
749
  const reason = errorMessage(err);
760
750
  warn(`Could not read issue '${id}' from ${sourceLabel(source)}: ${reason}`);
761
- return { source, issue: null, reason };
751
+ const failure = failureOf(err);
752
+ const action = actionOf(err);
753
+ return {
754
+ source,
755
+ issue: null,
756
+ reason,
757
+ ...failure === null ? {} : { failure },
758
+ ...action === null ? {} : { action }
759
+ };
762
760
  }
763
761
  }
764
762
  function shortHash(hash) {
@@ -875,6 +873,17 @@ async function resolveIssue(id, opts = {}) {
875
873
  if (found.length === 0) {
876
874
  const details = candidates.map((candidate) => `${sourceLabel(candidate.source)}: ${candidate.reason ?? "not found"}`).join("; ");
877
875
  const where = details.length > 0 ? ` (${details})` : "";
876
+ const blocking = candidates.find((candidate) => candidate.action !== void 0);
877
+ if (blocking !== void 0) {
878
+ throw new IssueResolutionError(
879
+ `Cannot read issue '${id}' from ${sourceLabel(blocking.source)}: ${blocking.reason}`,
880
+ 1,
881
+ {
882
+ ...blocking.failure === void 0 ? {} : { failure: blocking.failure },
883
+ ...blocking.action === void 0 ? {} : { action: blocking.action }
884
+ }
885
+ );
886
+ }
878
887
  throw new IssueResolutionError(`Issue '${id}' not found in any registered origin${where}`);
879
888
  }
880
889
  const build = (candidate, divergent) => buildResolved(candidate.issue, candidate.source, local, github, divergent);
@@ -928,48 +937,10 @@ async function resolveIssue(id, opts = {}) {
928
937
  return build(picked, true);
929
938
  }
930
939
 
931
- // src/issues/context.ts
932
- function localIssueRef(id) {
933
- return `issues/${id}/issue.md`;
934
- }
935
- function issueReference(issue) {
936
- return issue.remoteRef ?? localIssueRef(issue.id);
937
- }
938
- var NO_LABELS = "(none)";
939
- function issuePlaceholders(resolved) {
940
- const { issue } = resolved;
941
- return {
942
- __ISSUE_TITLE__: issue.title,
943
- __ISSUE_BODY__: issue.body,
944
- __ISSUE_LABELS__: issue.labels.length > 0 ? issue.labels.join(", ") : NO_LABELS,
945
- __ISSUE_SOURCE__: resolved.source,
946
- __ISSUE_URL__: issueReference(issue)
947
- };
948
- }
949
- async function resolveCommandIssue(id, preResolved, options) {
950
- if (preResolved !== void 0) {
951
- return { ok: true, resolved: preResolved };
952
- }
953
- try {
954
- return { ok: true, resolved: await resolveIssue(id, options) };
955
- } catch (err) {
956
- if (err instanceof IssueResolutionError) {
957
- printError(err.message);
958
- return { ok: false, code: err.exitCode };
959
- }
960
- const message = err instanceof Error ? err.message : String(err);
961
- printError(`Could not resolve issue '${id}': ${message}`);
962
- return { ok: false, code: 1 };
963
- }
964
- }
965
-
966
940
  export {
967
- emptyRelations,
968
- uniqueIds,
969
941
  getProvider,
970
942
  ensureProvidersRegistered,
971
- localIssueRef,
972
- issuePlaceholders,
973
- resolveCommandIssue
943
+ IssueResolutionError,
944
+ resolveIssue
974
945
  };
975
- //# sourceMappingURL=chunk-AAY6KM7N.js.map
946
+ //# sourceMappingURL=chunk-PV4OX5TC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/issues/registry.ts","../src/issues/hash.ts","../src/issues/providers/github.ts","../src/issues/providers/local.ts","../src/issues/bootstrap.ts","../src/issues/resolver.ts"],"sourcesContent":["import type { IssueProvider } from './provider.js';\nimport type { IssueSource } from './types.js';\n\n/**\n * Registry of Issue providers.\n *\n * Adding an origin is creating a provider file and registering one line here\n * (or from the caller's side), so nothing in src/commands/ needs to know the\n * list of sources.\n */\nconst providers = new Map<IssueSource, IssueProvider>();\n\n/**\n * Register a provider under its own `name`.\n *\n * Registering the same source twice replaces the previous entry, which is what\n * lets tests substitute a real provider with a fake one.\n */\nexport function registerProvider(provider: IssueProvider): void {\n providers.set(provider.name, provider);\n}\n\n/** Sources currently registered, in registration order. */\nexport function getRegisteredSources(): IssueSource[] {\n return [...providers.keys()];\n}\n\n/**\n * Look up a provider by origin.\n *\n * @throws when the origin is not registered, listing what is available so the\n * caller knows which sources they can pick instead.\n */\nexport function getProvider(source: IssueSource): IssueProvider {\n const provider = providers.get(source);\n if (provider === undefined) {\n const available = getRegisteredSources();\n const hint =\n available.length > 0\n ? `Available sources: ${available.join(', ')}.`\n : 'No Issue providers are registered.';\n throw new Error(`Unknown Issue source: '${source}'. ${hint}`);\n }\n return provider;\n}\n\n/** Drop every registration. Intended for test isolation. */\nexport function clearProviders(): void {\n providers.clear();\n}\n","import { createHash } from 'node:crypto';\n\n/**\n * Content hashing shared by every Issue provider.\n *\n * The hash is what lets the resolver tell \"the local and the remote Issue are\n * the same demand\" from \"they diverged\", so it has to be stable across\n * platforms: Windows checkouts store CRLF, editors add or drop trailing\n * newlines, and neither should count as a content change.\n */\n\n/** Normalizes line endings (CRLF/CR to LF) and trims the edges. */\nfunction normalizeText(value: string): string {\n return value.replace(/\\r\\n?/g, '\\n').trim();\n}\n\n/**\n * Returns `sha256:<hex>` for the given title and body.\n *\n * The payload is a canonical JSON object rather than a concatenation, so text\n * moved from the title into the body always changes the hash.\n */\nexport function hashIssueContent(title: string, body: string): string {\n const payload = JSON.stringify({\n title: normalizeText(title),\n body: normalizeText(body),\n });\n const digest = createHash('sha256').update(payload, 'utf8').digest('hex');\n return `sha256:${digest}`;\n}\n","import { getActiveResilienceConfig } from '../../config.js';\nimport type { ClassifiedFailure } from '../../resilience/errors.js';\nimport { ClassifiedError, requiresHumanAction } from '../../resilience/errors.js';\nimport { type PolicyConfig, resolvePolicy } from '../../resilience/policy.js';\nimport type { RetryPolicyFor } from '../../resilience/retry.js';\nimport { type ExecResult, run } from '../../utils/shell.js';\nimport { hashIssueContent } from '../hash.js';\nimport type { IssueProvider, ProviderAvailability } from '../provider.js';\nimport { emptyRelations, mergeRelations, parseTextualRelations, uniqueIds } from '../relations.js';\nimport type { Issue, IssueDraft, IssueRelations, IssueState } from '../types.js';\n\n/** Fields requested from `gh issue view`, in the order the PRD specifies. */\nconst VIEW_FIELDS = 'number,title,body,labels,state,url,createdAt,updatedAt,issueType';\n\n/** Timeout for the availability probes, matching the `init` prerequisite checks. */\nconst PROBE_TIMEOUT_MS = 10_000;\n\n/**\n * Every `gh` invocation carries the resilience policy of the failure it hits:\n * the `network` budget for a DNS blip, the `rate_limit` budget (and the\n * server's `Retry-After`) for a rate limit, and — because `resolvePolicy()`\n * clamps them — **no** attempt at all for an authentication or configuration\n * failure. This is the one place `gh` failures stop being fatal on sight.\n */\nfunction ghPolicy(): RetryPolicyFor {\n return (failure: ClassifiedFailure) =>\n resolvePolicy(failure.kind, getActiveResilienceConfig() as PolicyConfig);\n}\n\n/**\n * The budget of the availability probes, capped well below the full one.\n *\n * A probe answers a question about liveness; the answer must not take minutes.\n * The real read (`get`, `create`, `close`) keeps the full policy, so a blip\n * during the work is still absorbed at its documented budget — what is capped\n * here is only how long an *unreachable* GitHub delays a `local` Issue that\n * would have resolved instantly.\n */\nconst PROBE_MAX_ATTEMPTS = 3;\nconst PROBE_MAX_DELAY_MS = 5_000;\n\nfunction ghProbePolicy(): RetryPolicyFor {\n const policyFor = ghPolicy();\n return (failure) => {\n const policy = policyFor(failure);\n return {\n ...policy,\n maxAttempts: Math.min(policy.maxAttempts, PROBE_MAX_ATTEMPTS),\n maxDelayMs: Math.min(policy.maxDelayMs, PROBE_MAX_DELAY_MS),\n retryForever: false,\n };\n };\n}\n\n/** `gh <args>` under the full resilience policy. */\nfunction gh(args: string[], options: { timeout?: number } = {}): Promise<ExecResult> {\n return run('gh', args, {\n retry: ghPolicy(),\n ...(options.timeout === undefined ? {} : { timeout: options.timeout }),\n });\n}\n\n/**\n * gh reports a missing Issue on stderr with one of these phrasings. The match\n * must stay issue-specific: a bare /not found/ would also swallow\n * `gh: command not found`, turning a broken environment into \"issue absent\".\n * Anything else on a non-zero exit is a real failure (network, auth, gh not\n * installed) and must surface as a thrown error.\n */\nconst NOT_FOUND_PATTERN =\n /could not resolve to an issue|no issues? found|issue not found|could not find any issue/i;\n\ninterface GhLabel {\n name?: unknown;\n}\n\ninterface GhIssuePayload {\n number?: unknown;\n title?: unknown;\n body?: unknown;\n labels?: unknown;\n state?: unknown;\n url?: unknown;\n createdAt?: unknown;\n updatedAt?: unknown;\n issueType?: unknown;\n}\n\nfunction normalizeState(state: unknown): IssueState {\n return String(state ?? '').toUpperCase() === 'CLOSED' ? 'closed' : 'open';\n}\n\nfunction normalizeLabels(labels: unknown): string[] {\n if (!Array.isArray(labels)) return [];\n return labels\n .map((label: GhLabel | string) => (typeof label === 'string' ? label : label?.name))\n .filter((name): name is string => typeof name === 'string' && name.length > 0);\n}\n\nfunction normalizeIssueType(value: unknown): string | undefined {\n if (typeof value === 'string' && value.length > 0) return value;\n if (value !== null && typeof value === 'object' && 'name' in value) {\n const name = (value as { name: unknown }).name;\n return typeof name === 'string' && name.length > 0 ? name : undefined;\n }\n return undefined;\n}\n\nfunction toIssue(payload: GhIssuePayload): Issue {\n const title = typeof payload.title === 'string' ? payload.title : '';\n const body = typeof payload.body === 'string' ? payload.body : '';\n const number = typeof payload.number === 'number' ? payload.number : null;\n const url = typeof payload.url === 'string' && payload.url.length > 0 ? payload.url : null;\n const type = normalizeIssueType(payload.issueType);\n\n return {\n id: number === null ? '' : String(number),\n number,\n title,\n body,\n labels: normalizeLabels(payload.labels),\n ...(type === undefined ? {} : { type }),\n state: normalizeState(payload.state),\n source: 'github',\n remoteRef: url,\n createdAt: typeof payload.createdAt === 'string' ? payload.createdAt : '',\n updatedAt: typeof payload.updatedAt === 'string' ? payload.updatedAt : '',\n contentHash: hashIssueContent(title, body),\n raw: payload,\n };\n}\n\n/** Strip a leading `#` so both `23` and `#23` are accepted. */\nfunction normalizeId(id: string): string {\n return id.trim().replace(/^#/, '');\n}\n\n/** Page size for the relation endpoints — one page is enough in practice. */\nconst API_PAGE_SIZE = 100;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * `gh api <path>`, parsed as JSON.\n *\n * Answers `null` for every failure — a disabled feature (404), a plan without\n * Issue Dependencies (403), a network hiccup or unparseable output. That is the\n * whole graceful-degradation contract of `fetchRelations`: a source that cannot\n * answer contributes nothing instead of failing the discovery.\n */\nasync function ghApiJson(path: string): Promise<unknown> {\n try {\n const result = await gh(['api', path]);\n if (result.exitCode !== 0) return null;\n return JSON.parse(result.stdout) as unknown;\n } catch {\n return null;\n }\n}\n\n/** `number` of an Issue-shaped payload, as a string id. */\nfunction issueNumberOf(value: unknown): string | null {\n if (!isRecord(value)) return null;\n const number = value.number;\n return typeof number === 'number' && Number.isInteger(number) ? String(number) : null;\n}\n\n/** Ids of an array of Issue-shaped payloads, skipping anything unusable. */\nfunction issueNumbersOf(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return uniqueIds(\n value.map((entry) => issueNumberOf(entry) ?? '').filter((entry) => entry !== ''),\n );\n}\n\n/**\n * Issues that cited this one, from the timeline's `cross-referenced` events.\n *\n * Pull Requests are filtered out: they reference the Issue as *work on it*, not\n * as another demand to schedule.\n */\nfunction crossReferences(timeline: unknown, self: string): string[] {\n if (!Array.isArray(timeline)) return [];\n\n const ids: string[] = [];\n for (const event of timeline) {\n if (!isRecord(event) || event.event !== 'cross-referenced') continue;\n const source = isRecord(event.source) ? event.source : null;\n const issue = isRecord(source?.issue) ? source.issue : null;\n if (issue === null || issue.pull_request !== undefined) continue;\n const number = issueNumberOf(issue);\n if (number !== null) ids.push(number);\n }\n\n return uniqueIds(ids, self);\n}\n\nfunction extractIssueNumber(output: string): string | null {\n return output.match(/\\/issues\\/(\\d+)/)?.[1] ?? null;\n}\n\n/**\n * A failed `gh` result turned into an error that still carries its verdict.\n *\n * `run()` already classified it — every `gh` call here goes through the retry\n * chokepoint — so the kind, and with it the \"retry or escalate\" decision, must\n * not be flattened back into a message by the throw.\n */\nfunction ghError(message: string, result: ExecResult): Error {\n const failure = result.failure;\n if (failure === undefined) return new Error(message);\n return new ClassifiedError(message, failure, ghAction(failure));\n}\n\n/** The action a human has to take, for the kinds that need one. */\nfunction ghAction(failure: ClassifiedFailure): string | undefined {\n if (!requiresHumanAction(failure.kind)) return undefined;\n if (failure.kind === 'authentication') {\n return 'Run `gh auth login` to authenticate the GitHub CLI';\n }\n return undefined;\n}\n\n/**\n * A failed probe as an availability answer, keeping the classification.\n *\n * `action` is only attached when the failure actually needs a human: telling\n * someone to run `gh auth login` because their Wi-Fi dropped is worse than\n * saying nothing, and the caller uses the presence of an action to decide that\n * waiting will not help.\n */\nfunction unavailable(result: ExecResult, action: string): ProviderAvailability {\n const failure = result.failure;\n const needsHuman = failure === undefined || requiresHumanAction(failure.kind);\n return {\n available: false,\n ...(failure === undefined ? {} : { failure }),\n ...(needsHuman ? { action } : {}),\n };\n}\n\n/**\n * Issue provider backed by the GitHub CLI.\n *\n * Every call goes through `run` (execa, no shell) so tests can mock the shell\n * layer instead of the network, and so the Issue content is identical across\n * every pipeline phase.\n */\nexport class GitHubIssueProvider implements IssueProvider {\n readonly name = 'github' as const;\n\n /** True when gh is installed and authenticated. Never throws. */\n async isAvailable(): Promise<boolean> {\n return (await this.checkAvailability()).available;\n }\n\n /**\n * Whether gh is installed and authenticated, with the reason when it is not.\n *\n * Both probes retry on the capped probe budget, so a DNS blip during a long\n * run no longer reports GitHub as unavailable and takes the whole run down\n * with it — while an authentication failure is clamped to zero attempts by\n * `resolvePolicy()` and comes back immediately, with the action to take.\n */\n async checkAvailability(): Promise<ProviderAvailability> {\n try {\n const retry = ghProbePolicy();\n\n const version = await run('gh', ['--version'], { retry, timeout: PROBE_TIMEOUT_MS });\n if (version.exitCode !== 0) {\n return unavailable(version, 'Install the GitHub CLI: https://cli.github.com');\n }\n\n const auth = await run('gh', ['auth', 'status'], { retry, timeout: PROBE_TIMEOUT_MS });\n if (auth.exitCode !== 0) {\n return unavailable(auth, 'Run `gh auth login` to authenticate the GitHub CLI');\n }\n\n return { available: true };\n } catch {\n return { available: false };\n }\n }\n\n async get(id: string): Promise<Issue | null> {\n const issueId = normalizeId(id);\n const result = await gh(['issue', 'view', issueId, '--json', VIEW_FIELDS]);\n\n if (result.exitCode !== 0) {\n const detail = (result.stderr || result.stdout).trim();\n if (NOT_FOUND_PATTERN.test(detail)) return null;\n throw ghError(\n `Failed to fetch GitHub issue #${issueId}: ${detail || 'gh issue view failed'}`,\n result,\n );\n }\n\n let payload: GhIssuePayload;\n try {\n payload = JSON.parse(result.stdout);\n } catch {\n throw new Error(\n `Failed to parse gh output for issue #${issueId}: ${result.stdout.slice(0, 200)}`,\n );\n }\n\n return toIssue(payload);\n }\n\n async create(draft: IssueDraft): Promise<Issue> {\n const args = ['issue', 'create', '--title', draft.title, '--body', draft.body];\n for (const label of draft.labels) {\n args.push('--label', label);\n }\n // Only when the draft actually chose one. An organization without Issue\n // Types rejects the flag outright, so it must never be sent speculatively.\n if (draft.type !== undefined && draft.type !== '') {\n args.push('--type', draft.type);\n }\n\n const result = await gh(args);\n if (result.exitCode !== 0) {\n const detail = (result.stderr || result.stdout).trim();\n throw ghError(`Failed to create GitHub issue: ${detail || 'gh issue create failed'}`, result);\n }\n\n const number = extractIssueNumber(result.stdout);\n if (!number) {\n throw new Error(\n `GitHub issue creation did not report an issue URL: ${result.stdout.trim() || '(no output)'}`,\n );\n }\n\n const created = await this.get(number);\n if (!created) {\n throw new Error(`GitHub issue #${number} was created but could not be read back`);\n }\n return created;\n }\n\n /**\n * Hierarchy and dependencies of an Issue, reconciled from three GitHub\n * mechanisms that only partially overlap:\n *\n * 1. **Sub-issues** (`/sub_issues` plus the `parent` field of the Issue\n * payload) — the native hierarchy;\n * 2. **Issue Dependencies** (`/dependencies/blocked_by` and `/blocking`);\n * 3. the **textual heuristic** over the body, for repositories that adopted\n * neither and write `Depends on #12` or `- [ ] #13` instead.\n *\n * Cross-references (`referencedBy`) come from the issue timeline, which is\n * the only place GitHub reports \"who cited me\" without a search query.\n *\n * Every source is queried independently and is allowed to fail on its own: an\n * organization without Issue Dependencies enabled answers 404 for two of the\n * five calls, and that has to cost the caller those two fields, never the\n * whole discovery. Only what could be read is reported — nothing here throws.\n */\n async fetchRelations(id: string): Promise<IssueRelations> {\n const issueId = normalizeId(id);\n if (!/^\\d+$/.test(issueId)) {\n // A non-numeric identifier cannot address a GitHub REST endpoint; the\n // Issue simply has no relations we can discover.\n return emptyRelations(issueId);\n }\n\n const base = `repos/{owner}/{repo}/issues/${issueId}`;\n const [payload, subIssues, blockedBy, blocking, timeline] = await Promise.all([\n ghApiJson(base),\n ghApiJson(`${base}/sub_issues?per_page=${API_PAGE_SIZE}`),\n ghApiJson(`${base}/dependencies/blocked_by?per_page=${API_PAGE_SIZE}`),\n ghApiJson(`${base}/dependencies/blocking?per_page=${API_PAGE_SIZE}`),\n ghApiJson(`${base}/timeline?per_page=${API_PAGE_SIZE}`),\n ]);\n\n const issue = isRecord(payload) ? payload : null;\n // Without the REST payload the body still comes from `gh issue view`, so a\n // repository where only the REST API is blocked keeps the textual fallback.\n const body = typeof issue?.body === 'string' ? issue.body : await this.bodyFallback(issueId);\n\n const structured = {\n id: issueId,\n parent: issueNumberOf(issue?.parent),\n children: issueNumbersOf(subIssues),\n blockedBy: issueNumbersOf(blockedBy),\n blocking: issueNumbersOf(blocking),\n references: [],\n referencedBy: crossReferences(timeline, issueId),\n };\n\n return mergeRelations(structured, parseTextualRelations(body, issueId));\n }\n\n /** Body of an Issue when the REST payload could not be read. Never throws. */\n private async bodyFallback(issueId: string): Promise<string> {\n try {\n return (await this.get(issueId))?.body ?? '';\n } catch {\n return '';\n }\n }\n\n async close(id: string): Promise<void> {\n const issueId = normalizeId(id);\n const result = await gh(['issue', 'close', issueId]);\n\n if (result.exitCode !== 0) {\n const detail = (result.stderr || result.stdout).trim();\n throw ghError(\n `Failed to close GitHub issue #${issueId}: ${detail || 'gh issue close failed'}`,\n result,\n );\n }\n }\n}\n\n/** Shared instance; providers are stateless, so a singleton is enough. */\nexport const githubIssueProvider = new GitHubIssueProvider();\n","import { constants } from 'node:fs';\nimport { access, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { ZodError } from 'zod';\nimport { isoNow } from '../../core/state-manager.js';\nimport { issueMetadataSchema } from '../../schemas.js';\nimport type { IssuePaths } from '../../storage/paths.js';\nimport { resolveIssuePaths, resolveProjectPaths } from '../../storage/resolve.js';\nimport { writeFileAtomic } from '../../utils/fs.js';\nimport { getProjectRoot } from '../../utils/git.js';\nimport { run } from '../../utils/shell.js';\nimport { hashIssueContent } from '../hash.js';\nimport type { IssueProvider } from '../provider.js';\nimport type { Issue, IssueDraft, IssueMetadata } from '../types.js';\n\n/** Timeout for the optional remote probes done while allocating an identifier. */\nconst REMOTE_PROBE_TIMEOUT_MS = 10_000;\n\nfunction isNotFound(err: unknown): boolean {\n const code = (err as NodeJS.ErrnoException).code;\n return code === 'ENOENT' || code === 'ENOTDIR';\n}\n\n/**\n * True when `dir` already is a writable directory, or does not exist yet but\n * would be created successfully by `mkdir(dir, { recursive: true })` — i.e.\n * its nearest existing ancestor is a writable directory.\n *\n * Never mutates the filesystem: `isAvailable()` only needs to answer \"could\n * this work\", which must not leave a `~/.issue-flow/projects/<id>/` directory\n * behind for a project that ends up never using local issues (every other\n * source is queried on every resolution, so this runs far more often than the\n * provider is actually chosen).\n */\nasync function isWritableDirectory(dir: string): Promise<boolean> {\n let current = dir;\n for (;;) {\n let stats: Awaited<ReturnType<typeof stat>>;\n try {\n stats = await stat(current);\n } catch (err: unknown) {\n if (!isNotFound(err)) return false;\n const parent = dirname(current);\n if (parent === current) return false; // reached the filesystem root\n current = parent;\n continue;\n }\n if (!stats.isDirectory()) return false;\n try {\n await access(current, constants.W_OK);\n return true;\n } catch {\n return false;\n }\n }\n}\n\n/**\n * Identifiers become path segments, so anything that could escape the issues\n * directory is rejected before it reaches `join`.\n */\nfunction normalizeId(id: string): string {\n const normalized = id.trim().replace(/^#/, '');\n if (normalized.length === 0) {\n throw new Error('Local issue identifier cannot be empty');\n }\n if (/[/\\\\]/.test(normalized) || normalized === '.' || normalized === '..') {\n throw new Error(`Invalid local issue identifier: '${id}'`);\n }\n return normalized;\n}\n\nfunction toNumber(id: string): number | null {\n return /^\\d+$/.test(id) ? Number.parseInt(id, 10) : null;\n}\n\n/**\n * Title lives in the leading H1, body is everything after it.\n *\n * Only the first non-empty line is considered: an H1 further down belongs to\n * the body (issue descriptions routinely use headings), so promoting it would\n * silently retitle the Issue.\n */\nexport function parseIssueMarkdown(content: string): { title: string; body: string } {\n const lines = content.replace(/\\r\\n?/g, '\\n').split('\\n');\n const headingIndex = lines.findIndex((line) => line.trim().length > 0);\n const heading = headingIndex === -1 ? undefined : lines[headingIndex].match(/^#[ \\t]+(.*)$/);\n\n if (!heading) {\n return { title: '', body: lines.join('\\n').trim() };\n }\n\n return {\n title: heading[1].trim(),\n body: lines\n .slice(headingIndex + 1)\n .join('\\n')\n .trim(),\n };\n}\n\nfunction renderIssueMarkdown(title: string, body: string): string {\n return `# ${title}\\n\\n${body.trim()}\\n`;\n}\n\n/**\n * Issue provider backed by plain files in the project's global storage\n * directory (`~/.issue-flow/projects/<project-id>/issues/<id>/`).\n *\n * Enables the whole pipeline without any network access: no gh, no remote, no\n * authentication. `issue.md` is the source of truth for the content and\n * `metadata.json` for everything else; the content hash is always recomputed\n * from the file so a hand-edited issue.md is never reported as unchanged.\n *\n * Every path goes through `resolveIssuePaths()`, exactly like the pipeline\n * commands, so an issue that still only exists under the legacy\n * `<projectRoot>/issues/` tree is migrated on first read instead of coming back\n * as \"not found\".\n */\nexport class LocalFileIssueProvider implements IssueProvider {\n readonly name = 'local' as const;\n\n private readonly configuredRoot?: string;\n private cachedRoot?: string;\n\n /**\n * @param projectRoot Repository the issues belong to. It is no longer the\n * literal parent of an `issues/` directory: it is the root the project id —\n * and therefore the global storage directory — is derived from.\n */\n constructor(projectRoot?: string) {\n this.configuredRoot = projectRoot;\n }\n\n /**\n * True whenever the project's global storage directory already is — or\n * could be — a writable directory. Never mutates the filesystem, never\n * throws.\n *\n * A brand new project has no directory of its own until something writes, so\n * \"does it already exist\" would report the provider as unavailable exactly\n * when it is about to create the very first issue — `isWritableDirectory`\n * walks up to the nearest existing ancestor instead of requiring the leaf to\n * be there already.\n */\n async isAvailable(): Promise<boolean> {\n try {\n const { projectDir } = await resolveProjectPaths({ projectRoot: await this.root() });\n return await isWritableDirectory(projectDir);\n } catch {\n return false;\n }\n }\n\n async get(id: string): Promise<Issue | null> {\n const issueId = normalizeId(id);\n const markdownPath = await this.issueFile(issueId);\n\n let raw: string;\n try {\n raw = await readFile(markdownPath, 'utf-8');\n } catch (err: unknown) {\n if (isNotFound(err)) return null;\n throw err;\n }\n\n const { title: headingTitle, body } = parseIssueMarkdown(raw);\n const metadata = await this.readMetadata(issueId);\n const title = headingTitle || metadata?.title || '';\n\n if (metadata) {\n return {\n id: metadata.id,\n number: metadata.number,\n title,\n body,\n labels: metadata.labels,\n state: metadata.state,\n source: 'local',\n remoteRef: metadata.remote?.ref ?? null,\n createdAt: metadata.createdAt,\n updatedAt: metadata.updatedAt,\n contentHash: hashIssueContent(title, body),\n raw: metadata,\n };\n }\n\n // metadata.json is optional: an issue.md dropped in by hand still works,\n // with timestamps taken from the file itself.\n const stats = await stat(markdownPath);\n return {\n id: issueId,\n number: toNumber(issueId),\n title,\n body,\n labels: [],\n state: 'open',\n source: 'local',\n remoteRef: null,\n createdAt: stats.birthtime.toISOString(),\n updatedAt: stats.mtime.toISOString(),\n contentHash: hashIssueContent(title, body),\n };\n }\n\n async create(draft: IssueDraft): Promise<Issue> {\n // An explicit id is how a mirror keeps the identifier of the Issue it\n // mirrors: allocating a fresh one would make `issue-flow run <n>` see two\n // unrelated Issues instead of one demand in two places.\n const id = draft.id === undefined ? String(await this.allocateNumber()) : normalizeId(draft.id);\n const paths = await this.paths(id);\n\n await mkdir(paths.issueDir, { recursive: true });\n\n // Exclusive create (the 'wx' flag, O_EXCL under the hood) instead of a\n // check-then-write: two concurrent `create()` calls racing the same id\n // would both pass a plain existence check before either writes, and the\n // second would then silently overwrite the first through the atomic\n // temp+rename writer. The OS now rejects the loser instead.\n try {\n await writeFile(paths.issueFile, renderIssueMarkdown(draft.title, draft.body), {\n encoding: 'utf-8',\n flag: 'wx',\n });\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'EEXIST') {\n throw new Error(\n `Local issue '${id}' already exists at ${paths.issueFile}. ` +\n 'Remove it or pick another identifier before creating a new Issue.',\n );\n }\n throw err;\n }\n\n const timestamp = isoNow();\n const metadata: IssueMetadata = {\n schemaVersion: 1,\n id,\n number: toNumber(id),\n source: 'local',\n title: draft.title,\n labels: draft.labels,\n state: 'open',\n createdAt: timestamp,\n updatedAt: timestamp,\n contentHash: hashIssueContent(draft.title, draft.body),\n ...(draft.remote ? { remote: draft.remote } : {}),\n };\n\n await this.writeMetadata(id, metadata);\n\n return {\n id,\n number: metadata.number,\n title: draft.title,\n body: draft.body.trim(),\n labels: draft.labels,\n state: 'open',\n source: 'local',\n remoteRef: draft.remote?.ref ?? null,\n createdAt: timestamp,\n updatedAt: timestamp,\n contentHash: metadata.contentHash,\n raw: metadata,\n };\n }\n\n async close(id: string): Promise<void> {\n const issue = await this.get(id);\n if (!issue) {\n const issueDir = (await this.paths(normalizeId(id))).issueDir;\n throw new Error(`Local issue '${normalizeId(id)}' not found at ${issueDir}`);\n }\n\n const issueId = normalizeId(id);\n const existing = await this.readMetadata(issueId);\n\n await this.writeMetadata(issueId, {\n schemaVersion: 1,\n id: issue.id,\n number: issue.number,\n source: existing?.source ?? 'local',\n title: issue.title,\n labels: issue.labels,\n state: 'closed',\n createdAt: issue.createdAt,\n updatedAt: isoNow(),\n contentHash: issue.contentHash,\n ...(existing?.remote ? { remote: existing.remote } : {}),\n });\n }\n\n /**\n * Next free identifier: above every local number and, when GitHub answers,\n * above every remote one too. Sharing a numbering space with the remote is\n * what makes a naive `localMax + 1` collide the moment someone opens an Issue\n * on GitHub.\n */\n async allocateNumber(): Promise<number> {\n const [local, remote] = await Promise.all([this.highestLocalNumber(), highestRemoteNumber()]);\n return Math.max(local, remote) + 1;\n }\n\n private async root(): Promise<string> {\n if (this.configuredRoot !== undefined) return this.configuredRoot;\n this.cachedRoot ??= await getProjectRoot();\n return this.cachedRoot;\n }\n\n /**\n * Every artifact of one issue, from the same resolver the pipeline commands\n * use — which is also what triggers the migration of a legacy-only issue.\n */\n private async paths(id: string): Promise<IssuePaths> {\n return resolveIssuePaths(id, { projectRoot: await this.root() });\n }\n\n private async issueFile(id: string): Promise<string> {\n return (await this.paths(id)).issueFile;\n }\n\n private async metadataFile(id: string): Promise<string> {\n return (await this.paths(id)).metadataFile;\n }\n\n /** Parsed metadata.json, or `null` when the file is absent. */\n private async readMetadata(id: string): Promise<IssueMetadata | null> {\n const path = await this.metadataFile(id);\n\n let raw: string;\n try {\n raw = await readFile(path, 'utf-8');\n } catch (err: unknown) {\n if (isNotFound(err)) return null;\n throw err;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err: unknown) {\n throw new Error(`Invalid JSON in ${path}: ${(err as Error).message}`);\n }\n\n try {\n return issueMetadataSchema.parse(parsed);\n } catch (err: unknown) {\n if (err instanceof ZodError) {\n const details = err.issues\n .map((issue) => ` - ${issue.path.join('.') || '(root)'}: ${issue.message}`)\n .join('\\n');\n throw new Error(`Invalid issue metadata at ${path}:\\n${details}`);\n }\n throw err;\n }\n }\n\n private async writeMetadata(id: string, metadata: IssueMetadata): Promise<void> {\n await writeFileAtomic(await this.metadataFile(id), `${JSON.stringify(metadata, null, 2)}\\n`);\n }\n\n /**\n * Highest number across every `<issuesDir>/<id>/metadata.json` and numeric\n * directory name.\n *\n * Resolving `issuesDir` also migrates the legacy tree when it is the only one\n * that exists, which is what keeps an already-taken number from being handed\n * out a second time after adopting the global storage.\n */\n private async highestLocalNumber(): Promise<number> {\n const { issuesDir: dir } = await resolveProjectPaths({ projectRoot: await this.root() });\n\n let entries: string[];\n try {\n entries = (await readdir(dir, { withFileTypes: true }))\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name);\n } catch (err: unknown) {\n if (isNotFound(err)) return 0;\n throw err;\n }\n\n const numbers = await Promise.all(\n entries.map(async (name) => {\n const fromName = toNumber(name) ?? 0;\n // A directory whose metadata is unreadable still occupies its number.\n const fromMetadata = await this.readMetadata(name)\n .then((metadata) => metadata?.number ?? 0)\n .catch(() => 0);\n return Math.max(fromName, fromMetadata);\n }),\n );\n\n return numbers.reduce((max, value) => Math.max(max, value), 0);\n }\n}\n\n/** How many of the most-recently-created issues/PRs to inspect per probe. */\nconst REMOTE_PROBE_SAMPLE_SIZE = 20;\n\n/**\n * Highest number already taken on GitHub, or 0 when the remote is unreachable.\n *\n * Issues and pull requests share one counter, so both are probed: allocating\n * above the newest Issue alone would still collide with an open PR. Every\n * failure degrades to 0 — being offline must not block local creation.\n *\n * `gh ... list` defaults to sorting by creation date descending, which lines\n * up with number order in the overwhelming majority of repos — but that sort\n * is an implementation detail, not a contract. Rather than trust that the\n * single most-recent entry is also the highest-numbered one, a small sample\n * is fetched and the max is taken across it, which also tolerates the rare\n * case of a transferred issue whose creation date and number disagree.\n */\nasync function highestRemoteNumber(): Promise<number> {\n const probes = [\n ['issue', 'list'],\n ['pr', 'list'],\n ];\n\n const results = await Promise.all(\n probes.map(async (args) => {\n try {\n const result = await run(\n 'gh',\n [\n ...args,\n '--state',\n 'all',\n '--limit',\n String(REMOTE_PROBE_SAMPLE_SIZE),\n '--json',\n 'number',\n ],\n { timeout: REMOTE_PROBE_TIMEOUT_MS },\n );\n if (result.exitCode !== 0) return 0;\n\n const parsed = JSON.parse(result.stdout);\n if (!Array.isArray(parsed)) return 0;\n return parsed.reduce((max: number, entry: unknown) => {\n const n = (entry as { number?: unknown } | null)?.number;\n return typeof n === 'number' ? Math.max(max, n) : max;\n }, 0);\n } catch {\n return 0;\n }\n }),\n );\n\n return results.reduce((max, value) => Math.max(max, value), 0);\n}\n\n/** Shared instance resolving the project root lazily via git. */\nexport const localFileIssueProvider = new LocalFileIssueProvider();\n","import { githubIssueProvider } from './providers/github.js';\nimport { localFileIssueProvider } from './providers/local.js';\nimport { getRegisteredSources, registerProvider } from './registry.js';\n\n/**\n * Register the providers that ship with issue-flow.\n *\n * Idempotent and non-destructive: an origin that is already registered is left\n * untouched, so a test (or a future plugin) can install its own provider before\n * the first `resolveIssue` call without having it replaced by the built-in one.\n */\nexport function ensureProvidersRegistered(): void {\n const registered = new Set(getRegisteredSources());\n\n if (!registered.has('github')) {\n registerProvider(githubIssueProvider);\n }\n if (!registered.has('local')) {\n registerProvider(localFileIssueProvider);\n }\n}\n","import { createInterface, type Interface as ReadlineInterface } from 'node:readline';\nimport { loadIssuesConfig } from '../config.js';\nimport { actionOf, type ClassifiedFailure, failureOf } from '../resilience/errors.js';\nimport { printInfo, printWarning } from '../ui/logger.js';\nimport { ensureProvidersRegistered } from './bootstrap.js';\nimport type { ProviderAvailability } from './provider.js';\nimport { getProvider, getRegisteredSources } from './registry.js';\nimport type { Issue, IssueSource, IssuesConfig, ResolvedIssue } from './types.js';\n\n/**\n * Failure to settle on an Issue. Carries the exit code the CLI should return,\n * so callers propagate it instead of inventing their own.\n */\nexport class IssueResolutionError extends Error {\n readonly exitCode: number;\n /**\n * The verdict of the origin that failed, when one origin failed for a reason\n * worth naming. It is what tells \"this Issue does not exist\" apart from\n * \"GitHub could not be reached\", which are the same message today.\n */\n readonly failure: ClassifiedFailure | undefined;\n /** What a human has to do, for a failure that waiting cannot fix. */\n readonly action: string | undefined;\n\n constructor(\n message: string,\n exitCode = 1,\n details: { failure?: ClassifiedFailure; action?: string } = {},\n ) {\n super(message);\n this.name = 'IssueResolutionError';\n this.exitCode = exitCode;\n this.failure = details.failure;\n this.action = details.action;\n }\n}\n\nexport interface ResolveIssueOptions {\n /** Already-resolved provider configuration. Defaults to loadIssuesConfig(). */\n config?: IssuesConfig;\n /** Origins to query. Defaults to every registered source. */\n sources?: IssueSource[];\n /**\n * Whether a prompt may be shown. Defaults to a real TTY outside CI, which is\n * what keeps `ask` from ever blocking a headless run.\n */\n interactive?: boolean;\n /** Input stream for the conflict prompt. Defaults to process.stdin. */\n stdin?: NodeJS.ReadableStream;\n /** Output stream for the conflict prompt. Defaults to process.stdout. */\n stdout?: NodeJS.WritableStream;\n /** Informational sink. Defaults to printInfo. */\n info?: (message: string) => void;\n /** Warning sink. Defaults to printWarning. */\n warn?: (message: string) => void;\n}\n\n/** How many invalid answers are tolerated before the prompt gives up. */\nconst MAX_PROMPT_ATTEMPTS = 3;\n\n/**\n * Labels shown to users for the built-in origins. An origin registered from\n * outside this package is displayed under its own name, so a new provider needs\n * no entry here.\n */\nconst SOURCE_LABELS: Record<string, string> = {\n github: 'GitHub',\n local: 'local',\n};\n\nfunction sourceLabel(source: IssueSource): string {\n return SOURCE_LABELS[source] ?? source;\n}\n\n/** Same label, capitalized for the numbered prompt ('local' -> 'Local'). */\nfunction promptLabel(source: IssueSource): string {\n const label = sourceLabel(source);\n return label.charAt(0).toUpperCase() + label.slice(1);\n}\n\ninterface Candidate {\n source: IssueSource;\n issue: Issue | null;\n /** Why the origin produced nothing, used only to explain a total miss. */\n reason: string | null;\n /** The classified verdict behind `reason`, when the origin could give one. */\n failure?: ClassifiedFailure;\n /** What a human has to do about it (`gh auth login`), when that applies. */\n action?: string;\n}\n\n/** A candidate that actually produced an Issue. */\ninterface FoundCandidate extends Candidate {\n issue: Issue;\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Read one origin without letting it break the others.\n *\n * An unavailable provider or a failed read degrades to \"no candidate\" plus a\n * reason: as long as another origin has the Issue the pipeline keeps going, and\n * when nothing is found the reasons are surfaced in the final error so a broken\n * environment is never reported as a missing Issue.\n */\nasync function fetchCandidate(\n source: IssueSource,\n id: string,\n warn: (message: string) => void,\n): Promise<Candidate> {\n let provider: ReturnType<typeof getProvider>;\n try {\n provider = getProvider(source);\n } catch (err) {\n return { source, issue: null, reason: errorMessage(err) };\n }\n\n let availability: ProviderAvailability;\n try {\n availability = (await provider.checkAvailability?.()) ?? {\n available: await provider.isAvailable(),\n };\n } catch (err) {\n return { source, issue: null, reason: `provider unavailable (${errorMessage(err)})` };\n }\n if (!availability.available) {\n // The classified reason replaces the flat \"provider unavailable\": a\n // credential that expired and a network that blipped were indistinguishable\n // before, and only one of them is worth telling a human about.\n const reason = availability.failure?.message ?? 'provider unavailable';\n return {\n source,\n issue: null,\n reason,\n ...(availability.failure === undefined ? {} : { failure: availability.failure }),\n ...(availability.action === undefined ? {} : { action: availability.action }),\n };\n }\n\n try {\n const issue = await provider.get(id);\n return { source, issue, reason: issue === null ? 'not found' : null };\n } catch (err) {\n const reason = errorMessage(err);\n // A real failure (network, auth, corrupted metadata) must be visible even\n // when the other origin answers.\n warn(`Could not read issue '${id}' from ${sourceLabel(source)}: ${reason}`);\n const failure = failureOf(err);\n const action = actionOf(err);\n return {\n source,\n issue: null,\n reason,\n ...(failure === null ? {} : { failure }),\n ...(action === null ? {} : { action }),\n };\n }\n}\n\nfunction shortHash(hash: string): string {\n const hex = hash.startsWith('sha256:') ? hash.slice('sha256:'.length) : hash;\n return hex.slice(0, 12);\n}\n\n/** One line per origin describing what differs, without dumping every body. */\nfunction describeCandidate(source: IssueSource, issue: Issue): string {\n const lines = issue.body.length === 0 ? 0 : issue.body.split('\\n').length;\n return (\n ` ${sourceLabel(source).padEnd(6)} title: \"${issue.title}\" | body: ${lines} line(s), ` +\n `${issue.body.length} char(s) | updated: ${issue.updatedAt} | hash: ${shortHash(issue.contentHash)}`\n );\n}\n\n/** 'local and GitHub', 'local, GitHub and memory' — origins in query order. */\nfunction listSources(candidates: FoundCandidate[]): string {\n const labels = candidates.map((candidate) => sourceLabel(candidate.source));\n if (labels.length <= 1) {\n return labels.join('');\n }\n return `${labels.slice(0, -1).join(', ')} and ${labels[labels.length - 1]}`;\n}\n\n/**\n * Turn a readline interface into an awaitable line reader.\n *\n * Lines are queued instead of read on demand: `rl.question` drops whatever\n * arrives between two questions, which silently loses a piped answer typed\n * ahead of the prompt. Resolves `null` once the input is exhausted, so EOF ends\n * the prompt instead of hanging the process.\n */\nfunction createLineReader(\n rl: ReadlineInterface,\n output: NodeJS.WritableStream,\n): (query: string) => Promise<string | null> {\n const queued: string[] = [];\n let pending: ((line: string | null) => void) | null = null;\n let closed = false;\n\n rl.on('line', (line: string) => {\n if (pending !== null) {\n const resolve = pending;\n pending = null;\n resolve(line);\n return;\n }\n queued.push(line);\n });\n rl.on('close', () => {\n closed = true;\n if (pending !== null) {\n const resolve = pending;\n pending = null;\n resolve(null);\n }\n });\n\n return (query: string) =>\n new Promise<string | null>((resolve) => {\n const buffered = queued.shift();\n if (buffered !== undefined) {\n resolve(buffered);\n return;\n }\n if (closed) {\n resolve(null);\n return;\n }\n output.write(query);\n pending = resolve;\n });\n}\n\n/**\n * Interactive choice between the divergent versions.\n *\n * The options are numbered from the origins that actually answered, so a third\n * provider simply shows up as `[3] Memory` without this function knowing which\n * origins exist. Cancel is always the last option.\n */\nasync function promptChoice(\n sources: IssueSource[],\n stdin: NodeJS.ReadableStream,\n stdout: NodeJS.WritableStream,\n warn: (message: string) => void,\n): Promise<IssueSource | 'cancel'> {\n const options = sources.map((source, index) => `[${index + 1}] ${promptLabel(source)}`);\n const cancelOption = sources.length + 1;\n const query = `Which version should be used? ${options.join(' ')} [${cancelOption}] Cancel: `;\n const numbers = Array.from({ length: cancelOption }, (_, index) => String(index + 1));\n const accepted = `${numbers.slice(0, -1).join(', ')} or ${numbers[numbers.length - 1]}`;\n\n const rl = createInterface({ input: stdin, output: stdout });\n const ask = createLineReader(rl, stdout);\n try {\n for (let attempt = 0; attempt < MAX_PROMPT_ATTEMPTS; attempt++) {\n const answer = await ask(query);\n if (answer === null) {\n return 'cancel';\n }\n const choice = answer.trim();\n const picked = sources[Number(choice) - 1];\n if (choice.length > 0 && picked !== undefined) {\n return picked;\n }\n if (choice === String(cancelOption)) {\n return 'cancel';\n }\n warn(`Invalid choice: '${choice}'. Enter ${accepted}.`);\n }\n return 'cancel';\n } finally {\n rl.close();\n }\n}\n\nfunction isInteractiveByDefault(): boolean {\n const ci = process.env.CI;\n const inCi = ci !== undefined && ci !== '' && ci !== '0' && ci.toLowerCase() !== 'false';\n return Boolean(process.stdin.isTTY) && !inCi;\n}\n\nfunction buildResolved(\n issue: Issue,\n source: IssueSource,\n local: Issue | null,\n github: Issue | null,\n divergent: boolean,\n): ResolvedIssue {\n return { issue, source, local, github, divergent };\n}\n\n/** Origin `conflictPolicy` points at, or `null` for 'ask'. */\nfunction policyTarget(policy: IssuesConfig['conflictPolicy']): IssueSource | null {\n if (policy === 'prefer-local') {\n return 'local';\n }\n if (policy === 'prefer-github') {\n return 'github';\n }\n return null;\n}\n\n/**\n * Single entry point every command uses to decide which Issue the pipeline\n * works on.\n *\n * The logic is written against the origins that answered, never against a fixed\n * list of sources: registering a new provider is enough for it to take part in\n * the resolution, be reported in a divergence and appear in the prompt.\n *\n * Scenarios:\n * - only one origin has it -> that one, no questions asked;\n * - several, same contentHash -> equivalence is reported and the preferred\n * origin wins, without a prompt;\n * - several, different content -> the divergence is reported and\n * `conflictPolicy` decides (`ask` prompts on a TTY, falls back to\n * `preferredProvider` with a warning anywhere else);\n * - none -> IssueResolutionError, which carries the CLI exit code.\n */\nexport async function resolveIssue(\n id: string,\n opts: ResolveIssueOptions = {},\n): Promise<ResolvedIssue> {\n const info = opts.info ?? printInfo;\n const warn = opts.warn ?? printWarning;\n const config = opts.config ?? (await loadIssuesConfig({ warn }));\n\n ensureProvidersRegistered();\n const sources = opts.sources ?? getRegisteredSources();\n\n // Each origin is an independent I/O call (network for GitHub, disk for\n // local); querying them concurrently instead of one-by-one keeps the total\n // latency at the slowest origin instead of the sum of all of them, without\n // changing which candidate wins (order is preserved by Promise.all).\n const candidates: Candidate[] = await Promise.all(\n sources.map((source) => fetchCandidate(source, id, warn)),\n );\n\n const issueOf = (source: IssueSource): Issue | null =>\n candidates.find((candidate) => candidate.source === source)?.issue ?? null;\n const local = issueOf('local');\n const github = issueOf('github');\n\n const found = candidates.filter(\n (candidate): candidate is FoundCandidate => candidate.issue !== null,\n );\n\n if (found.length === 0) {\n const details = candidates\n .map((candidate) => `${sourceLabel(candidate.source)}: ${candidate.reason ?? 'not found'}`)\n .join('; ');\n const where = details.length > 0 ? ` (${details})` : '';\n\n // An origin that needs a human is the answer, not a footnote: reporting\n // \"Issue not found\" for an expired credential sends the user looking for\n // the wrong problem, and no amount of retrying would have helped.\n const blocking = candidates.find((candidate) => candidate.action !== undefined);\n if (blocking !== undefined) {\n throw new IssueResolutionError(\n `Cannot read issue '${id}' from ${sourceLabel(blocking.source)}: ${blocking.reason}`,\n 1,\n {\n ...(blocking.failure === undefined ? {} : { failure: blocking.failure }),\n ...(blocking.action === undefined ? {} : { action: blocking.action }),\n },\n );\n }\n\n throw new IssueResolutionError(`Issue '${id}' not found in any registered origin${where}`);\n }\n\n const build = (candidate: FoundCandidate, divergent: boolean): ResolvedIssue =>\n buildResolved(candidate.issue, candidate.source, local, github, divergent);\n\n const firstFound = found[0] as FoundCandidate;\n if (found.length === 1) {\n return build(firstFound, false);\n }\n\n // Several origins have it. The preferred one wins whenever it is among them;\n // otherwise the first origin queried does, so an unrelated preference never\n // leaves the pipeline without an Issue.\n const preferred =\n found.find((candidate) => candidate.source === config.preferredProvider) ?? firstFound;\n\n const distinct = new Set(found.map((candidate) => candidate.issue.contentHash));\n if (distinct.size === 1) {\n info(\n `Issue '${id}' has identical content in ${listSources(found)}; using ${sourceLabel(preferred.source)}.`,\n );\n return build(preferred, false);\n }\n\n info(`Issue '${id}' differs between origins:`);\n for (const candidate of found) {\n info(describeCandidate(candidate.source, candidate.issue));\n }\n\n const target = policyTarget(config.conflictPolicy);\n if (target !== null) {\n const chosen = found.find((candidate) => candidate.source === target);\n if (chosen !== undefined) {\n info(`Conflict policy '${config.conflictPolicy}': using the ${sourceLabel(target)} version.`);\n return build(chosen, true);\n }\n // The policy names an origin that has no version of this Issue: say so\n // instead of silently picking for the user under its name.\n warn(\n `Conflict policy '${config.conflictPolicy}' does not apply to Issue '${id}' ` +\n `(${sourceLabel(target)} has no version of it); using ${sourceLabel(preferred.source)}.`,\n );\n return build(preferred, true);\n }\n\n const interactive = opts.interactive ?? isInteractiveByDefault();\n if (!interactive) {\n warn(\n `Divergent Issue '${id}' and conflict policy 'ask' in a non-interactive environment; ` +\n `using the preferred provider (${sourceLabel(preferred.source)}).`,\n );\n return build(preferred, true);\n }\n\n const choice = await promptChoice(\n found.map((candidate) => candidate.source),\n opts.stdin ?? process.stdin,\n opts.stdout ?? process.stdout,\n warn,\n );\n if (choice === 'cancel') {\n throw new IssueResolutionError(\n `Cancelled: Issue '${id}' diverges between ${listSources(found)}.`,\n );\n }\n const picked = found.find((candidate) => candidate.source === choice) as FoundCandidate;\n return build(picked, true);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,IAAM,YAAY,oBAAI,IAAgC;AAQ/C,SAAS,iBAAiB,UAA+B;AAC9D,YAAU,IAAI,SAAS,MAAM,QAAQ;AACvC;AAGO,SAAS,uBAAsC;AACpD,SAAO,CAAC,GAAG,UAAU,KAAK,CAAC;AAC7B;AAQO,SAAS,YAAY,QAAoC;AAC9D,QAAM,WAAW,UAAU,IAAI,MAAM;AACrC,MAAI,aAAa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