issue-flow 0.7.6 → 0.8.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 (73) hide show
  1. package/dist/{analyze-TNFTUMOO.js → analyze-RBNKXWL5.js} +10 -8
  2. package/dist/{analyze-TNFTUMOO.js.map → analyze-RBNKXWL5.js.map} +1 -1
  3. package/dist/{chunk-JECNPBBO.js → chunk-36ECROTC.js} +11 -9
  4. package/dist/{chunk-JECNPBBO.js.map → chunk-36ECROTC.js.map} +1 -1
  5. package/dist/{chunk-6S2XT3JE.js → chunk-A4M6AKIK.js} +10 -8
  6. package/dist/{chunk-6S2XT3JE.js.map → chunk-A4M6AKIK.js.map} +1 -1
  7. package/dist/{chunk-5NLLEWJD.js → chunk-BASRRXAM.js} +12 -2
  8. package/dist/{chunk-5NLLEWJD.js.map → chunk-BASRRXAM.js.map} +1 -1
  9. package/dist/{chunk-5Q2TMW7K.js → chunk-BH7DYADV.js} +11 -1
  10. package/dist/chunk-BH7DYADV.js.map +1 -0
  11. package/dist/chunk-F52S6ZGF.js +447 -0
  12. package/dist/chunk-F52S6ZGF.js.map +1 -0
  13. package/dist/{chunk-CD7BMWXW.js → chunk-HSGTZ3CT.js} +3 -3
  14. package/dist/{chunk-QLVAEDVD.js → chunk-J3PJBZXJ.js} +3 -3
  15. package/dist/{chunk-DWF46N65.js → chunk-J4SICTAN.js} +11 -9
  16. package/dist/{chunk-DWF46N65.js.map → chunk-J4SICTAN.js.map} +1 -1
  17. package/dist/{chunk-DF7SUHT5.js → chunk-JWZKV3CL.js} +2 -2
  18. package/dist/{chunk-5IRBHUYO.js → chunk-MK43N4X3.js} +11 -9
  19. package/dist/{chunk-5IRBHUYO.js.map → chunk-MK43N4X3.js.map} +1 -1
  20. package/dist/{chunk-I7FTA5FI.js → chunk-QO2MWMAZ.js} +2 -47
  21. package/dist/chunk-QO2MWMAZ.js.map +1 -0
  22. package/dist/{chunk-D56VWHSM.js → chunk-RQW5W4XC.js} +2 -2
  23. package/dist/chunk-SLHZPB3C.js +50 -0
  24. package/dist/chunk-SLHZPB3C.js.map +1 -0
  25. package/dist/{chunk-BMRBQ23Q.js → chunk-TGP6WK65.js} +9 -7
  26. package/dist/{chunk-BMRBQ23Q.js.map → chunk-TGP6WK65.js.map} +1 -1
  27. package/dist/{chunk-OE7RYTUT.js → chunk-VPDWTZ3F.js} +2 -2
  28. package/dist/{chunk-A42R36BX.js → chunk-VSF2CR3G.js} +10 -8
  29. package/dist/{chunk-A42R36BX.js.map → chunk-VSF2CR3G.js.map} +1 -1
  30. package/dist/cli.js +28 -13
  31. package/dist/cli.js.map +1 -1
  32. package/dist/{config-U3FC4WH6.js → config-R7O5YC65.js} +3 -3
  33. package/dist/execute-LU3HWA54.js +14 -0
  34. package/dist/{generate-RHPOWGDX.js → generate-TGJQLGMV.js} +10 -8
  35. package/dist/{generate-RHPOWGDX.js.map → generate-TGJQLGMV.js.map} +1 -1
  36. package/dist/init-WP7Z2LFQ.js +9 -0
  37. package/dist/plan-2MWMCKRY.js +16 -0
  38. package/dist/pr-XVQDEQ7B.js +16 -0
  39. package/dist/pr-review-VO6ZXAFM.js +16 -0
  40. package/dist/prd-FPZAHQEO.js +16 -0
  41. package/dist/review-AHALLMXO.js +14 -0
  42. package/dist/{run-Z6ZDXZB6.js → run-2CXVR3VZ.js} +23 -196
  43. package/dist/run-2CXVR3VZ.js.map +1 -0
  44. package/dist/web-JVPK2PIF.js +188 -0
  45. package/dist/web-JVPK2PIF.js.map +1 -0
  46. package/package.json +1 -1
  47. package/web/CLAUDE.md +48 -0
  48. package/web/public/app.css +266 -0
  49. package/web/public/app.js +237 -0
  50. package/web/public/index.html +26 -0
  51. package/dist/chunk-5Q2TMW7K.js.map +0 -1
  52. package/dist/chunk-I7FTA5FI.js.map +0 -1
  53. package/dist/execute-BNBA77WJ.js +0 -13
  54. package/dist/init-IF72GR7O.js +0 -9
  55. package/dist/plan-FITZZXZQ.js +0 -15
  56. package/dist/pr-GO244D7M.js +0 -15
  57. package/dist/pr-review-XY6VL62M.js +0 -15
  58. package/dist/prd-2Y6RMVTF.js +0 -15
  59. package/dist/review-ITKXJMX3.js +0 -13
  60. package/dist/run-Z6ZDXZB6.js.map +0 -1
  61. /package/dist/{chunk-CD7BMWXW.js.map → chunk-HSGTZ3CT.js.map} +0 -0
  62. /package/dist/{chunk-QLVAEDVD.js.map → chunk-J3PJBZXJ.js.map} +0 -0
  63. /package/dist/{chunk-DF7SUHT5.js.map → chunk-JWZKV3CL.js.map} +0 -0
  64. /package/dist/{chunk-D56VWHSM.js.map → chunk-RQW5W4XC.js.map} +0 -0
  65. /package/dist/{chunk-OE7RYTUT.js.map → chunk-VPDWTZ3F.js.map} +0 -0
  66. /package/dist/{config-U3FC4WH6.js.map → config-R7O5YC65.js.map} +0 -0
  67. /package/dist/{execute-BNBA77WJ.js.map → execute-LU3HWA54.js.map} +0 -0
  68. /package/dist/{init-IF72GR7O.js.map → init-WP7Z2LFQ.js.map} +0 -0
  69. /package/dist/{plan-FITZZXZQ.js.map → plan-2MWMCKRY.js.map} +0 -0
  70. /package/dist/{pr-GO244D7M.js.map → pr-XVQDEQ7B.js.map} +0 -0
  71. /package/dist/{pr-review-XY6VL62M.js.map → pr-review-VO6ZXAFM.js.map} +0 -0
  72. /package/dist/{prd-2Y6RMVTF.js.map → prd-FPZAHQEO.js.map} +0 -0
  73. /package/dist/{review-ITKXJMX3.js.map → review-AHALLMXO.js.map} +0 -0
@@ -0,0 +1,447 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ resolvePackageDir
4
+ } from "./chunk-SLHZPB3C.js";
5
+ import {
6
+ getGlobalRoot,
7
+ webLockSchema
8
+ } from "./chunk-BASRRXAM.js";
9
+ import {
10
+ NullPublisher,
11
+ isoNow,
12
+ printInfo,
13
+ printWarning
14
+ } from "./chunk-BH7DYADV.js";
15
+
16
+ // src/web/lock.ts
17
+ import { spawn as nodeSpawn } from "child_process";
18
+ import { readFile as readFile2, rm, writeFile } from "fs/promises";
19
+ import { join as join2 } from "path";
20
+ import chalk2 from "chalk";
21
+
22
+ // src/web/server.ts
23
+ import { createHash } from "crypto";
24
+ import { readFile } from "fs/promises";
25
+ import { createServer } from "http";
26
+ import { createRequire } from "module";
27
+ import { join } from "path";
28
+ import chalk from "chalk";
29
+ var require2 = createRequire(import.meta.url);
30
+ function readPackageVersion() {
31
+ try {
32
+ return require2("../../package.json").version;
33
+ } catch {
34
+ return "0.0.0";
35
+ }
36
+ }
37
+ var JSON_TYPE = "application/json; charset=utf-8";
38
+ function publisherSessionSource(publisher) {
39
+ return {
40
+ list: () => {
41
+ const snapshot = publisher.snapshot();
42
+ return snapshot.sessionId === null ? [] : [snapshot];
43
+ },
44
+ get: (sessionId) => {
45
+ const snapshot = publisher.snapshot();
46
+ return snapshot.sessionId === sessionId ? snapshot : void 0;
47
+ }
48
+ };
49
+ }
50
+ function directorySessionSource(handle) {
51
+ return {
52
+ list: () => handle.sessions().map((entry) => entry.snapshot),
53
+ get: (sessionId) => handle.getSession(sessionId)?.snapshot
54
+ };
55
+ }
56
+ function resolveSessionSource(options) {
57
+ if (options.sessions) return directorySessionSource(options.sessions);
58
+ return publisherSessionSource(options.publisher ?? new NullPublisher());
59
+ }
60
+ var STATIC_ROUTES = {
61
+ "/": { file: "index.html", contentType: "text/html; charset=utf-8" },
62
+ "/app.css": { file: "app.css", contentType: "text/css; charset=utf-8" },
63
+ "/app.js": { file: "app.js", contentType: "text/javascript; charset=utf-8" }
64
+ };
65
+ async function loadStaticAssets(publicDir) {
66
+ const assets = /* @__PURE__ */ new Map();
67
+ if (publicDir === null) return assets;
68
+ for (const [route, { file, contentType }] of Object.entries(STATIC_ROUTES)) {
69
+ try {
70
+ const body = await readFile(join(publicDir, file), "utf-8");
71
+ assets.set(route, { body, contentType });
72
+ } catch {
73
+ }
74
+ }
75
+ return assets;
76
+ }
77
+ function baseHeaders(res) {
78
+ res.setHeader("Cache-Control", "no-store");
79
+ res.setHeader("X-Content-Type-Options", "nosniff");
80
+ res.setHeader("Referrer-Policy", "no-referrer");
81
+ res.setHeader("X-Robots-Tag", "noindex, nofollow");
82
+ }
83
+ function respond(res, status, contentType, body) {
84
+ res.statusCode = status;
85
+ res.setHeader("Content-Type", contentType);
86
+ res.end(body);
87
+ }
88
+ function respondJson(res, status, payload) {
89
+ respond(res, status, JSON_TYPE, JSON.stringify(payload));
90
+ }
91
+ async function startWebServer(options) {
92
+ const info = options.info ?? printInfo;
93
+ const warn = options.warn ?? printWarning;
94
+ const version = options.version ?? readPackageVersion();
95
+ const startedAtMs = Date.now();
96
+ const assets = await loadStaticAssets(
97
+ options.publicDir ?? resolvePackageDir(join("web", "public"))
98
+ );
99
+ const source = resolveSessionSource(options);
100
+ const statusCache = /* @__PURE__ */ new Map();
101
+ const statusPayload = (snapshot) => {
102
+ const key = snapshot.sessionId ?? "";
103
+ const body = JSON.stringify(snapshot);
104
+ const cached = statusCache.get(key);
105
+ if (cached !== void 0 && cached.body === body) return cached;
106
+ const etag = `"${createHash("sha1").update(body).digest("hex")}"`;
107
+ const entry = { body, etag };
108
+ statusCache.set(key, entry);
109
+ return entry;
110
+ };
111
+ const handleRequest = (req, res) => {
112
+ baseHeaders(res);
113
+ const requestUrl = new URL(req.url ?? "/", "http://localhost");
114
+ const path = requestUrl.pathname;
115
+ if (req.method !== "GET" && req.method !== "HEAD") {
116
+ respondJson(res, 404, { error: "Not found" });
117
+ return;
118
+ }
119
+ if (path === "/api/status" || path === "/status.json") {
120
+ const sessionId = requestUrl.searchParams.get("session");
121
+ let snapshot;
122
+ if (sessionId !== null) {
123
+ snapshot = source.get(sessionId);
124
+ if (snapshot === void 0) {
125
+ respondJson(res, 404, { error: `No active session with id '${sessionId}'.` });
126
+ return;
127
+ }
128
+ } else {
129
+ const active = source.list();
130
+ if (active.length === 0) {
131
+ respondJson(res, 404, {
132
+ error: "No active session. Pass ?session=<id> \u2014 see GET /api/sessions."
133
+ });
134
+ return;
135
+ }
136
+ if (active.length > 1) {
137
+ respondJson(res, 409, {
138
+ error: "Multiple active sessions; specify ?session=<id>.",
139
+ sessions: active.map((entry) => entry.sessionId)
140
+ });
141
+ return;
142
+ }
143
+ snapshot = active[0];
144
+ }
145
+ const { body, etag } = statusPayload(snapshot);
146
+ res.setHeader("ETag", etag);
147
+ if (req.headers["if-none-match"] === etag) {
148
+ res.statusCode = 304;
149
+ res.end();
150
+ return;
151
+ }
152
+ respond(res, 200, JSON_TYPE, body);
153
+ return;
154
+ }
155
+ if (path === "/api/sessions") {
156
+ respondJson(
157
+ res,
158
+ 200,
159
+ source.list().map((snapshot) => ({
160
+ sessionId: snapshot.sessionId,
161
+ issueNumber: snapshot.issue.number,
162
+ status: snapshot.status,
163
+ startedAt: snapshot.startedAt,
164
+ updatedAt: snapshot.updatedAt,
165
+ statusUrl: `/api/status?session=${encodeURIComponent(snapshot.sessionId ?? "")}`
166
+ }))
167
+ );
168
+ return;
169
+ }
170
+ if (path === "/api/health") {
171
+ respondJson(res, 200, {
172
+ ok: true,
173
+ uptime: Math.round((Date.now() - startedAtMs) / 1e3),
174
+ version,
175
+ refreshSeconds: options.refreshSeconds ?? 5
176
+ });
177
+ return;
178
+ }
179
+ const asset = assets.get(path);
180
+ if (asset) {
181
+ respond(res, 200, asset.contentType, asset.body);
182
+ return;
183
+ }
184
+ respondJson(res, 404, { error: "Not found" });
185
+ };
186
+ const server = createServer((req, res) => {
187
+ try {
188
+ handleRequest(req, res);
189
+ } catch (err) {
190
+ try {
191
+ respondJson(res, 500, { error: err instanceof Error ? err.message : String(err) });
192
+ } catch {
193
+ }
194
+ }
195
+ });
196
+ const listening = await new Promise((resolve) => {
197
+ const onError = (err) => {
198
+ if (err.code === "EADDRINUSE") {
199
+ warn(
200
+ `Web monitor port ${options.port} is already in use. Continuing without the web server.`
201
+ );
202
+ } else {
203
+ warn(`Web monitor failed to start (${err.message}). Continuing without the web server.`);
204
+ }
205
+ resolve(false);
206
+ };
207
+ server.once("error", onError);
208
+ server.listen(options.port, options.host, () => {
209
+ server.removeListener("error", onError);
210
+ resolve(true);
211
+ });
212
+ });
213
+ if (!listening) return null;
214
+ if (options.unref !== false) {
215
+ server.unref();
216
+ }
217
+ server.on("error", (err) => {
218
+ warn(`Web monitor server error: ${err.message}`);
219
+ });
220
+ const address = server.address();
221
+ const port = address.port;
222
+ const displayHost = options.host === "0.0.0.0" ? "localhost" : options.host;
223
+ const url = `http://${displayHost}:${port}`;
224
+ if (options.host === "0.0.0.0") {
225
+ warn("Web monitor bound to 0.0.0.0: anyone on your local network can view the session state.");
226
+ }
227
+ info(`Web monitor running at ${chalk.bold.cyan(url)}`);
228
+ let closed = false;
229
+ let closePromise = null;
230
+ const doClose = () => new Promise((resolve) => {
231
+ process.removeListener("SIGINT", onSignal);
232
+ process.removeListener("SIGTERM", onSignal);
233
+ server.close(() => resolve());
234
+ server.closeAllConnections();
235
+ });
236
+ const close = () => {
237
+ if (closed) return closePromise ?? Promise.resolve();
238
+ closed = true;
239
+ closePromise = doClose();
240
+ return closePromise;
241
+ };
242
+ const handle = { server, host: options.host, port, url, close };
243
+ const onSignal = (signal) => {
244
+ void handle.close().finally(() => {
245
+ process.kill(process.pid, signal);
246
+ });
247
+ };
248
+ process.once("SIGINT", onSignal);
249
+ process.once("SIGTERM", onSignal);
250
+ return handle;
251
+ }
252
+
253
+ // src/web/lock.ts
254
+ var WEB_LOCK_FILENAME = "web.lock";
255
+ var HEALTH_PROBE_TIMEOUT_MS = 1e3;
256
+ var LOCK_CLAIM_RETRIES = 5;
257
+ var LOCK_CLAIM_RETRY_DELAY_MS = 100;
258
+ function getWebLockFile(options = {}) {
259
+ return join2(getGlobalRoot(options), WEB_LOCK_FILENAME);
260
+ }
261
+ function sleep(ms) {
262
+ return new Promise((resolve) => setTimeout(resolve, ms));
263
+ }
264
+ function isProcessAlive(pid) {
265
+ try {
266
+ process.kill(pid, 0);
267
+ return true;
268
+ } catch (err) {
269
+ return err.code === "EPERM";
270
+ }
271
+ }
272
+ function probeUrl(host, port) {
273
+ const probeHost = host === "0.0.0.0" ? "127.0.0.1" : host;
274
+ return `http://${probeHost}:${port}/api/health`;
275
+ }
276
+ async function probeHealth(host, port) {
277
+ try {
278
+ const res = await fetch(probeUrl(host, port), {
279
+ signal: AbortSignal.timeout(HEALTH_PROBE_TIMEOUT_MS)
280
+ });
281
+ return res.ok;
282
+ } catch {
283
+ return false;
284
+ }
285
+ }
286
+ async function readWebLock(lockFile) {
287
+ let raw;
288
+ try {
289
+ raw = await readFile2(lockFile, "utf-8");
290
+ } catch {
291
+ return null;
292
+ }
293
+ try {
294
+ const result = webLockSchema.safeParse(JSON.parse(raw));
295
+ return result.success ? result.data : null;
296
+ } catch {
297
+ return null;
298
+ }
299
+ }
300
+ async function removeWebLock(lockFile) {
301
+ try {
302
+ await rm(lockFile, { force: true });
303
+ } catch {
304
+ }
305
+ }
306
+ async function detectActiveInstance(lockFile) {
307
+ const lock = await readWebLock(lockFile);
308
+ if (lock === null) return null;
309
+ if (isProcessAlive(lock.pid) && await probeHealth(lock.host, lock.port)) {
310
+ return lock;
311
+ }
312
+ await removeWebLock(lockFile);
313
+ return null;
314
+ }
315
+ async function claimWebLock(lockFile, lock) {
316
+ try {
317
+ await writeFile(lockFile, JSON.stringify(lock, null, 2), { encoding: "utf-8", flag: "wx" });
318
+ return true;
319
+ } catch (err) {
320
+ if (err.code === "EEXIST") return false;
321
+ throw err;
322
+ }
323
+ }
324
+ function reusedHandle(lock) {
325
+ const displayHost = lock.host === "0.0.0.0" ? "localhost" : lock.host;
326
+ return {
327
+ host: lock.host,
328
+ port: lock.port,
329
+ url: `http://${displayHost}:${lock.port}`,
330
+ close: async () => {
331
+ }
332
+ };
333
+ }
334
+ async function ensureSingleWebServer(options, lockOptions = {}) {
335
+ const warn = options.warn ?? printWarning;
336
+ const info = options.info ?? printInfo;
337
+ const lockFile = getWebLockFile(lockOptions);
338
+ for (let attempt = 0; attempt <= LOCK_CLAIM_RETRIES; attempt++) {
339
+ const active = await detectActiveInstance(lockFile);
340
+ if (active !== null) {
341
+ info(`Reusing existing web monitor at ${reusedHandle(active).url}`);
342
+ return reusedHandle(active);
343
+ }
344
+ const handle = await startWebServer(options);
345
+ if (handle === null) {
346
+ await sleep(LOCK_CLAIM_RETRY_DELAY_MS);
347
+ continue;
348
+ }
349
+ let claimed;
350
+ try {
351
+ claimed = await claimWebLock(lockFile, {
352
+ pid: process.pid,
353
+ port: handle.port,
354
+ host: handle.host,
355
+ startedAt: isoNow()
356
+ });
357
+ } catch (err) {
358
+ await handle.close();
359
+ throw err;
360
+ }
361
+ if (!claimed) {
362
+ await handle.close();
363
+ await sleep(LOCK_CLAIM_RETRY_DELAY_MS);
364
+ continue;
365
+ }
366
+ const originalClose = handle.close;
367
+ handle.close = async () => {
368
+ await originalClose();
369
+ await removeWebLock(lockFile);
370
+ };
371
+ return handle;
372
+ }
373
+ warn("Could not determine the web monitor lock ownership. Continuing without the web server.");
374
+ return null;
375
+ }
376
+ var DETACHED_CLAIM_TIMEOUT_MS = 5e3;
377
+ var DETACHED_CLAIM_POLL_MS = 150;
378
+ async function ensureWebMonitor(options, monitorOptions = {}) {
379
+ const warn = options.warn ?? printWarning;
380
+ const info = options.info ?? printInfo;
381
+ let lockFile;
382
+ try {
383
+ lockFile = getWebLockFile(monitorOptions);
384
+ } catch (err) {
385
+ warn(
386
+ `Web monitor: global storage unavailable (${err instanceof Error ? err.message : String(err)}). Falling back to legacy in-process mode.`
387
+ );
388
+ return startWebServer(options);
389
+ }
390
+ const active = await detectActiveInstance(lockFile);
391
+ if (active !== null) {
392
+ info(`Reusing existing web monitor at ${reusedHandle(active).url}`);
393
+ return reusedHandle(active);
394
+ }
395
+ const execPath = monitorOptions.execPath ?? process.execPath;
396
+ const entryScript = monitorOptions.entryScript ?? process.argv[1];
397
+ if (entryScript === void 0) {
398
+ warn("Web monitor: could not determine the CLI entry point to spawn a detached server.");
399
+ return null;
400
+ }
401
+ const args = [
402
+ entryScript,
403
+ "web",
404
+ "serve",
405
+ "--port",
406
+ String(options.port),
407
+ "--host",
408
+ options.host
409
+ ];
410
+ if (options.refreshSeconds !== void 0) {
411
+ args.push("--refresh", String(options.refreshSeconds));
412
+ }
413
+ const spawnFn = monitorOptions.spawn ?? nodeSpawn;
414
+ try {
415
+ const child = spawnFn(execPath, args, { detached: true, stdio: "ignore" });
416
+ child.unref();
417
+ } catch (err) {
418
+ warn(
419
+ `Web monitor: failed to start the detached server (${err instanceof Error ? err.message : String(err)}). Continuing without the web server.`
420
+ );
421
+ return null;
422
+ }
423
+ const timeoutMs = monitorOptions.claimTimeoutMs ?? DETACHED_CLAIM_TIMEOUT_MS;
424
+ const pollMs = monitorOptions.claimPollIntervalMs ?? DETACHED_CLAIM_POLL_MS;
425
+ const deadline = Date.now() + timeoutMs;
426
+ while (Date.now() < deadline) {
427
+ const claimed = await detectActiveInstance(lockFile);
428
+ if (claimed !== null) {
429
+ info(`Web monitor running at ${chalk2.bold.cyan(reusedHandle(claimed).url)}`);
430
+ return reusedHandle(claimed);
431
+ }
432
+ await sleep(pollMs);
433
+ }
434
+ warn(
435
+ "Web monitor: the detached server did not start in time. Continuing without the web server."
436
+ );
437
+ return null;
438
+ }
439
+
440
+ export {
441
+ getWebLockFile,
442
+ readWebLock,
443
+ removeWebLock,
444
+ ensureSingleWebServer,
445
+ ensureWebMonitor
446
+ };
447
+ //# sourceMappingURL=chunk-F52S6ZGF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/web/lock.ts","../src/web/server.ts"],"sourcesContent":["import { type ChildProcess, spawn as nodeSpawn } from 'node:child_process';\nimport { readFile, rm, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport chalk from 'chalk';\nimport { isoNow } from '../core/state-manager.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 { 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';\n\n/** How long a health probe against a candidate instance waits before giving up. */\nconst HEALTH_PROBE_TIMEOUT_MS = 1000;\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 sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/** `process.kill(pid, 0)` throws ESRCH when the pid is gone, EPERM when it is\n * alive but owned by another user — only ESRCH means \"not alive\". */\nfunction isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === 'EPERM';\n }\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<boolean> {\n try {\n const res = await fetch(probeUrl(host, port), {\n signal: AbortSignal.timeout(HEALTH_PROBE_TIMEOUT_MS),\n });\n return res.ok;\n } catch {\n return false;\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 if (isProcessAlive(lock.pid) && (await probeHealth(lock.host, lock.port))) {\n return lock;\n }\n\n await removeWebLock(lockFile);\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\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 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 });\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}\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 try {\n lockFile = getWebLockFile(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 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 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 info(`Web monitor running at ${chalk.bold.cyan(reusedHandle(claimed).url)}`);\n return reusedHandle(claimed);\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}\n","import { createHash } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';\nimport { createRequire } from 'node:module';\nimport type { AddressInfo } from 'node:net';\nimport { join } from 'node:path';\nimport chalk from 'chalk';\nimport { resolvePackageDir } from '../core/prompt-resolver.js';\nimport {\n NullPublisher,\n type SessionPublisher,\n type SessionSnapshot,\n} from '../core/session-state.js';\nimport { printInfo, printWarning } from '../ui/logger.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\nconst require = createRequire(import.meta.url);\n\nfunction readPackageVersion(): string {\n try {\n return (require('../../package.json') as { version: string }).version;\n } catch {\n return '0.0.0';\n }\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 /** 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 /** 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}\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 };\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 };\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): void {\n res.setHeader('Cache-Control', 'no-store');\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\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 ?? readPackageVersion();\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 = (req: IncomingMessage, res: ServerResponse): void => {\n baseHeaders(res);\n\n const requestUrl = new URL(req.url ?? '/', 'http://localhost');\n const path = requestUrl.pathname;\n\n // POST /api/control/* is reserved for future write operations (pause,\n // retry, ...); intentionally NOT registered — the v1 surface is\n // read-only (snapshot.readOnly is true and capabilities is empty).\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 respondJson(\n res,\n 200,\n source.list().map((snapshot) => ({\n sessionId: snapshot.sessionId,\n issueNumber: snapshot.issue.number,\n status: snapshot.status,\n startedAt: snapshot.startedAt,\n updatedAt: snapshot.updatedAt,\n statusUrl: `/api/status?session=${encodeURIComponent(snapshot.sessionId ?? '')}`,\n })),\n );\n return;\n }\n\n if (path === '/api/health') {\n respondJson(res, 200, {\n ok: true,\n uptime: Math.round((Date.now() - startedAtMs) / 1000),\n version,\n refreshSeconds: options.refreshSeconds ?? 5,\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 try {\n handleRequest(req, res);\n } 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, 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,YAAAA,WAAU,IAAI,iBAAiB;AACxC,SAAS,QAAAC,aAAY;AACrB,OAAOC,YAAW;;;ACHlB,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;AACzB,SAAS,oBAA4E;AACrF,SAAS,qBAAqB;AAE9B,SAAS,YAAY;AACrB,OAAO,WAAW;AAsBlB,IAAMC,WAAU,cAAc,YAAY,GAAG;AAE7C,SAAS,qBAA6B;AACpC,MAAI;AACF,WAAQA,SAAQ,oBAAoB,EAA0B;AAAA,EAChE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AA2DA,IAAM,YAAY;AAclB,SAAS,uBAAuB,WAA4C;AAC1E,SAAO;AAAA,IACL,MAAM,MAAM;AACV,YAAM,WAAW,UAAU,SAAS;AACpC,aAAO,SAAS,cAAc,OAAO,CAAC,IAAI,CAAC,QAAQ;AAAA,IACrD;AAAA,IACA,KAAK,CAAC,cAAc;AAClB,YAAM,WAAW,UAAU,SAAS;AACpC,aAAO,SA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OAAO;AAAA,IAC7B;AACA,UAAM,MAAM,MAAM;AAAA,EACpB;AAEA;AAAA,IACE;AAAA,EACF;AACA,SAAO;AACT;","names":["readFile","join","chalk","require","join","readFile","chalk"]}
@@ -5,7 +5,7 @@ import {
5
5
  resolveIssuePaths,
6
6
  resolveProjectPaths,
7
7
  run
8
- } from "./chunk-5NLLEWJD.js";
8
+ } from "./chunk-BASRRXAM.js";
9
9
  import {
10
10
  isoNow,
11
11
  issueMetadataSchema,
@@ -13,7 +13,7 @@ import {
13
13
  printInfo,
14
14
  printWarning,
15
15
  writeFileAtomic
16
- } from "./chunk-5Q2TMW7K.js";
16
+ } from "./chunk-BH7DYADV.js";
17
17
 
18
18
  // src/issues/registry.ts
19
19
  var providers = /* @__PURE__ */ new Map();
@@ -753,4 +753,4 @@ export {
753
753
  issuePlaceholders,
754
754
  resolveCommandIssue
755
755
  };
756
- //# sourceMappingURL=chunk-CD7BMWXW.js.map
756
+ //# sourceMappingURL=chunk-HSGTZ3CT.js.map
@@ -9,11 +9,11 @@ import {
9
9
  normalizeRemoteUrl,
10
10
  run,
11
11
  stripRemoteUrlCredentials
12
- } from "./chunk-5NLLEWJD.js";
12
+ } from "./chunk-BASRRXAM.js";
13
13
  import {
14
14
  NullPublisher,
15
15
  isoNow
16
- } from "./chunk-5Q2TMW7K.js";
16
+ } from "./chunk-BH7DYADV.js";
17
17
 
18
18
  // src/core/session-git.ts
19
19
  async function listPullRequests(branch) {
@@ -109,4 +109,4 @@ export {
109
109
  listPullRequests,
110
110
  publishGitState
111
111
  };
112
- //# sourceMappingURL=chunk-QLVAEDVD.js.map
112
+ //# sourceMappingURL=chunk-J3PJBZXJ.js.map
@@ -1,25 +1,27 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  runPhaseWithRetry
4
- } from "./chunk-D56VWHSM.js";
4
+ } from "./chunk-RQW5W4XC.js";
5
5
  import {
6
6
  issuePlaceholders,
7
7
  resolveCommandIssue
8
- } from "./chunk-CD7BMWXW.js";
8
+ } from "./chunk-HSGTZ3CT.js";
9
9
  import {
10
10
  isTransientFailure
11
11
  } from "./chunk-HDV3YDTG.js";
12
12
  import {
13
13
  runHeadless
14
- } from "./chunk-DF7SUHT5.js";
14
+ } from "./chunk-JWZKV3CL.js";
15
15
  import {
16
- applyPlaceholders,
17
- loadPrompt,
18
16
  publishPhaseMetrics
19
- } from "./chunk-I7FTA5FI.js";
17
+ } from "./chunk-QO2MWMAZ.js";
18
+ import {
19
+ applyPlaceholders,
20
+ loadPrompt
21
+ } from "./chunk-SLHZPB3C.js";
20
22
  import {
21
23
  resolveIssuePaths
22
- } from "./chunk-5NLLEWJD.js";
24
+ } from "./chunk-BASRRXAM.js";
23
25
  import {
24
26
  getGlobalTimeout,
25
27
  isoNow,
@@ -27,7 +29,7 @@ import {
27
29
  printError,
28
30
  printSuccess,
29
31
  saveTaskPlan
30
- } from "./chunk-5Q2TMW7K.js";
32
+ } from "./chunk-BH7DYADV.js";
31
33
 
32
34
  // src/commands/pr.ts
33
35
  import { execa } from "execa";
@@ -132,4 +134,4 @@ async function runPr(issue, resolvedIssue) {
132
134
  export {
133
135
  runPr
134
136
  };
135
- //# sourceMappingURL=chunk-DWF46N65.js.map
137
+ //# sourceMappingURL=chunk-J4SICTAN.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/commands/pr.ts"],"sourcesContent":["import { execa } from 'execa';\nimport { runHeadless } from '../core/headless.js';\nimport { runPhaseWithRetry } from '../core/phase-runner.js';\nimport { applyPlaceholders, loadPrompt } from '../core/prompt-resolver.js';\nimport { publishPhaseMetrics } from '../core/session-metrics.js';\nimport { isoNow, loadTaskPlan, saveTaskPlan } from '../core/state-manager.js';\nimport { getGlobalTimeout } from '../core/verbose.js';\nimport { issuePlaceholders, resolveCommandIssue } from '../issues/context.js';\nimport type { Issue, ResolvedIssue } from '../issues/types.js';\nimport { resolveIssuePaths } from '../storage/resolve.js';\nimport { printError, printSuccess } from '../ui/logger.js';\nimport { isTransientFailure } from '../utils/retry.js';\n\n/**\n * Extract a PR URL from headless output.\n */\nfunction parsePrUrl(output: string): string | null {\n const match = output.match(/(https:\\/\\/github\\.com\\/[^\\s]+\\/pull\\/\\d+)/);\n return match?.[1] ?? null;\n}\n\n/**\n * The numeric id inside a PR URL, so later phases (`pr-review`) address the\n * Pull Request without querying GitHub again.\n */\nfunction parsePrNumber(url: string): number | null {\n const match = url.match(/\\/pull\\/(\\d+)/);\n return match?.[1] === undefined ? null : Number(match[1]);\n}\n\n/**\n * The `Closes #N` line for the PR body, empty when the Issue has no remote\n * counterpart: GitHub only understands the reference for Issues it hosts, and\n * an invented `#N` would silently point at an unrelated Issue.\n */\nfunction issueClosesLine(issue: Issue, fallbackId: string): string {\n if (issue.remoteRef === null) {\n return '';\n }\n return `Closes #${issue.number ?? fallbackId}`;\n}\n\nexport async function runPr(issue: string, resolvedIssue?: ResolvedIssue): Promise<number> {\n const issueNumber = issue.replace(/^#/, '');\n const paths = await resolveIssuePaths(issueNumber);\n const tasksPath = paths.tasksFile;\n\n const resolution = await resolveCommandIssue(issueNumber, resolvedIssue);\n if (!resolution.ok) {\n return resolution.code;\n }\n\n // Get current branch\n let branchName: string;\n try {\n const proc = await execa('git', ['branch', '--show-current'], { reject: false });\n branchName = proc.stdout?.toString().trim() ?? '';\n if (!branchName) {\n printError('Could not determine current branch');\n return 1;\n }\n } catch {\n printError('Failed to get current branch');\n return 1;\n }\n\n const template = await loadPrompt('pr');\n const prompt = applyPlaceholders(template, {\n __ISSUE_NUMBER__: issueNumber,\n __BRANCH_NAME__: branchName,\n __TASKS_PATH__: tasksPath,\n __ISSUE_CLOSES__: issueClosesLine(resolution.resolved.issue, issueNumber),\n ...issuePlaceholders(resolution.resolved),\n });\n\n let headlessOutput = '';\n\n const outcome = await runPhaseWithRetry({\n phase: 'pr',\n attempt: async () => {\n const startedAtMs = Date.now();\n const result = await runHeadless({\n prompt,\n maxTurns: 15,\n timeout: getGlobalTimeout() ?? 300_000,\n // json (not text) so the CLI reports usage: the envelope's `result`\n // field carries the same assistant text parsePrUrl() already consumed.\n outputFormat: 'json',\n allowedTools: ['Bash', 'Read', 'Glob', 'Grep'],\n addDirs: [paths.issueDir],\n statusMessage: `Creating PR for issue #${issueNumber}...`,\n });\n // One event per attempt; the reducer sums them into the phase total.\n publishPhaseMetrics('pr', result.cost, startedAtMs);\n\n if (!result.success) {\n return {\n ok: false,\n transient: isTransientFailure(1, result.error ?? ''),\n error: `PR creation failed: ${result.error}`,\n };\n }\n\n headlessOutput = result.result;\n return { ok: true };\n },\n });\n\n if (!outcome.ok) {\n printError(outcome.error ?? `PR creation failed for issue #${issueNumber}`);\n return 1;\n }\n\n const prUrl = parsePrUrl(headlessOutput);\n\n // Update pipeline state\n try {\n const plan = await loadTaskPlan(tasksPath);\n plan.pipeline.prCreated = true;\n const prNumber = prUrl === null ? null : parsePrNumber(prUrl);\n // Without a URL the PR is still assumed created (the phase succeeded), but\n // there is nothing trustworthy to record: an invented number would send\n // `pr-review` at an unrelated Pull Request.\n if (prUrl !== null && prNumber !== null) {\n plan.pullRequest = {\n number: prNumber,\n url: prUrl,\n headBranch: branchName,\n createdAt: isoNow(),\n };\n }\n await saveTaskPlan(tasksPath, plan);\n } catch {\n // tasks.json may not exist\n }\n\n if (prUrl) {\n printSuccess(`PR created: ${prUrl}`);\n } else {\n printSuccess('PR creation completed');\n }\n return 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AAgBtB,SAAS,WAAW,QAA+B;AACjD,QAAM,QAAQ,OAAO,MAAM,4CAA4C;AACvE,SAAO,QAAQ,CAAC,KAAK;AACvB;AAMA,SAAS,cAAc,KAA4B;AACjD,QAAM,QAAQ,IAAI,MAAM,eAAe;AACvC,SAAO,QAAQ,CAAC,MAAM,SAAY,OAAO,OAAO,MAAM,CAAC,CAAC;AAC1D;AAOA,SAAS,gBAAgB,OAAc,YAA4B;AACjE,MAAI,MAAM,cAAc,MAAM;AAC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,0BAAoB,MAAM,OAAO,MAAM,WAAW;AAElD,UAAI,CAAC,OAAO,SAAS;AACnB,eAAO;AAAA,UACL,IAAI;AAAA,UACJ,WAAW,mBAAmB,GAAG,OAAO,SAAS,EAAE;AAAA,UACnD,OAAO,uBAAuB,OAAO,KAAK;AAAA,QAC5C;AAAA,MACF;AAEA,uBAAiB,OAAO;AACxB,aAAO,EAAE,IAAI,KAAK;AAAA,IACpB;AAAA,EACF,CAAC;AAED,MAAI,CAAC,QAAQ,IAAI;AACf,eAAW,QAAQ,SAAS,iCAAiC,WAAW,EAAE;AAC1E,WAAO;AAAA,EACT;AAEA,QAAM,QAAQ,WAAW,cAAc;AAGvC,MAAI;AACF,UAAM,OAAO,MAAM,aAAa,SAAS;AACzC,SAAK,SAAS,YAAY;AAC1B,UAAM,WAAW,UAAU,OAAO,OAAO,cAAc,KAAK;AAI5D,QAAI,UAAU,QAAQ,aAAa,MAAM;AACvC,WAAK,cAAc;AAAA,QACjB,QAAQ;AAAA,QACR,KAAK;AAAA,QACL,YAAY;AAAA,QACZ,WAAW,OAAO;AAAA,MACpB;AAAA,IACF;AACA,UAAM,aAAa,WAAW,IAAI;AAAA,EACpC,QAAQ;AAAA,EAER;AAEA,MAAI,OAAO;AACT,iBAAa,eAAe,KAAK,EAAE;AAAA,EACrC,OAAO;AACL,iBAAa,uBAAuB;AAAA,EACtC;AACA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/commands/pr.ts"],"sourcesContent":["import { execa } from 'execa';\nimport { runHeadless } from '../core/headless.js';\nimport { runPhaseWithRetry } from '../core/phase-runner.js';\nimport { applyPlaceholders, loadPrompt } from '../core/prompt-resolver.js';\nimport { publishPhaseMetrics } from '../core/session-metrics.js';\nimport { isoNow, loadTaskPlan, saveTaskPlan } from '../core/state-manager.js';\nimport { getGlobalTimeout } from '../core/verbose.js';\nimport { issuePlaceholders, resolveCommandIssue } from '../issues/context.js';\nimport type { Issue, ResolvedIssue } from '../issues/types.js';\nimport { resolveIssuePaths } from '../storage/resolve.js';\nimport { printError, printSuccess } from '../ui/logger.js';\nimport { isTransientFailure } from '../utils/retry.js';\n\n/**\n * Extract a PR URL from headless output.\n */\nfunction parsePrUrl(output: string): string | null {\n const match = output.match(/(https:\\/\\/github\\.com\\/[^\\s]+\\/pull\\/\\d+)/);\n return match?.[1] ?? null;\n}\n\n/**\n * The numeric id inside a PR URL, so later phases (`pr-review`) address the\n * Pull Request without querying GitHub again.\n */\nfunction parsePrNumber(url: string): number | null {\n const match = url.match(/\\/pull\\/(\\d+)/);\n return match?.[1] === undefined ? null : Number(match[1]);\n}\n\n/**\n * The `Closes #N` line for the PR body, empty when the Issue has no remote\n * counterpart: GitHub only understands the reference for Issues it hosts, and\n * an invented `#N` would silently point at an unrelated Issue.\n */\nfunction issueClosesLine(issue: Issue, fallbackId: string): string {\n if (issue.remoteRef === null) {\n return '';\n }\n return `Closes #${issue.number ?? fallbackId}`;\n}\n\nexport async function runPr(issue: string, resolvedIssue?: ResolvedIssue): Promise<number> {\n const issueNumber = issue.replace(/^#/, '');\n const paths = await resolveIssuePaths(issueNumber);\n const tasksPath = paths.tasksFile;\n\n const resolution = await resolveCommandIssue(issueNumber, resolvedIssue);\n if (!resolution.ok) {\n return resolution.code;\n }\n\n // Get current branch\n let branchName: string;\n try {\n const proc = await execa('git', ['branch', '--show-current'], { reject: false });\n branchName = proc.stdout?.toString().trim() ?? '';\n if (!branchName) {\n printError('Could not determine current branch');\n return 1;\n }\n } catch {\n printError('Failed to get current branch');\n return 1;\n }\n\n const template = await loadPrompt('pr');\n const prompt = applyPlaceholders(template, {\n __ISSUE_NUMBER__: issueNumber,\n __BRANCH_NAME__: branchName,\n __TASKS_PATH__: tasksPath,\n __ISSUE_CLOSES__: issueClosesLine(resolution.resolved.issue, issueNumber),\n ...issuePlaceholders(resolution.resolved),\n });\n\n let headlessOutput = '';\n\n const outcome = await runPhaseWithRetry({\n phase: 'pr',\n attempt: async () => {\n const startedAtMs = Date.now();\n const result = await runHeadless({\n prompt,\n maxTurns: 15,\n timeout: getGlobalTimeout() ?? 300_000,\n // json (not text) so the CLI reports usage: the envelope's `result`\n // field carries the same assistant text parsePrUrl() already consumed.\n outputFormat: 'json',\n allowedTools: ['Bash', 'Read', 'Glob', 'Grep'],\n addDirs: [paths.issueDir],\n statusMessage: `Creating PR for issue #${issueNumber}...`,\n });\n // One event per attempt; the reducer sums them into the phase total.\n publishPhaseMetrics('pr', result.cost, startedAtMs);\n\n if (!result.success) {\n return {\n ok: false,\n transient: isTransientFailure(1, result.error ?? ''),\n error: `PR creation failed: ${result.error}`,\n };\n }\n\n headlessOutput = result.result;\n return { ok: true };\n },\n });\n\n if (!outcome.ok) {\n printError(outcome.error ?? `PR creation failed for issue #${issueNumber}`);\n return 1;\n }\n\n const prUrl = parsePrUrl(headlessOutput);\n\n // Update pipeline state\n try {\n const plan = await loadTaskPlan(tasksPath);\n plan.pipeline.prCreated = true;\n const prNumber = prUrl === null ? null : parsePrNumber(prUrl);\n // Without a URL the PR is still assumed created (the phase succeeded), but\n // there is nothing trustworthy to record: an invented number would send\n // `pr-review` at an unrelated Pull Request.\n if (prUrl !== null && prNumber !== null) {\n plan.pullRequest = {\n number: prNumber,\n url: prUrl,\n headBranch: branchName,\n createdAt: isoNow(),\n };\n }\n await saveTaskPlan(tasksPath, plan);\n } catch {\n // tasks.json may not exist\n }\n\n if (prUrl) {\n printSuccess(`PR created: ${prUrl}`);\n } else {\n printSuccess('PR creation completed');\n }\n return 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AAgBtB,SAAS,WAAW,QAA+B;AACjD,QAAM,QAAQ,OAAO,MAAM,4CAA4C;AACvE,SAAO,QAAQ,CAAC,KAAK;AACvB;AAMA,SAAS,cAAc,KAA4B;AACjD,QAAM,QAAQ,IAAI,MAAM,eAAe;AACvC,SAAO,QAAQ,CAAC,MAAM,SAAY,OAAO,OAAO,MAAM,CAAC,CAAC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