issue-flow 0.7.7 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -0
- package/dist/{analyze-2RVGY5OK.js → analyze-VSWAEVN3.js} +6 -6
- package/dist/{chunk-WO6ERABE.js → chunk-57MH6RYJ.js} +106 -7
- package/dist/chunk-57MH6RYJ.js.map +1 -0
- package/dist/{chunk-6UTVPKNF.js → chunk-66ZGYXTH.js} +53 -9
- package/dist/chunk-66ZGYXTH.js.map +1 -0
- package/dist/{chunk-WGDLUPSF.js → chunk-DP43WJY4.js} +75 -11
- package/dist/chunk-DP43WJY4.js.map +1 -0
- package/dist/{chunk-ZYBYMEWG.js → chunk-DTNM3LTO.js} +33 -10
- package/dist/chunk-DTNM3LTO.js.map +1 -0
- package/dist/{chunk-KHTLN54U.js → chunk-JGKPSWOA.js} +2 -2
- package/dist/{chunk-EYVXLRRD.js → chunk-KXAG24DD.js} +219 -3
- package/dist/chunk-KXAG24DD.js.map +1 -0
- package/dist/{chunk-XPW46TI5.js → chunk-M37YZYDO.js} +3 -3
- package/dist/{chunk-G37JNQKB.js → chunk-M72ZEPWD.js} +2 -2
- package/dist/{chunk-RUTDK6ZF.js → chunk-MTJQOOMG.js} +105 -4
- package/dist/chunk-MTJQOOMG.js.map +1 -0
- package/dist/{chunk-OPIDR2DC.js → chunk-NB6WKTBL.js} +2 -2
- package/dist/chunk-TJMZWRS6.js +265 -0
- package/dist/chunk-TJMZWRS6.js.map +1 -0
- package/dist/{chunk-6IOPYFUM.js → chunk-TLSIK656.js} +6 -6
- package/dist/{chunk-JOK7VXRV.js → chunk-VNKSMWDN.js} +17 -3
- package/dist/chunk-VNKSMWDN.js.map +1 -0
- package/dist/{chunk-6L2BPOE3.js → chunk-WHEU55ZP.js} +7 -7
- package/dist/{chunk-EOTULFWV.js → chunk-X7XBF5TS.js} +6 -6
- package/dist/cli.js +91 -29
- package/dist/cli.js.map +1 -1
- package/dist/{config-OAZG7KIK.js → config-J5DW6HSY.js} +3 -3
- package/dist/execute-Z2DKGVLR.js +14 -0
- package/dist/{generate-BEJF3SVJ.js → generate-ERDPOTKX.js} +6 -6
- package/dist/init-UY6ZCIFT.js +9 -0
- package/dist/plan-REMAMCX4.js +16 -0
- package/dist/pr-KERP52TI.js +20 -0
- package/dist/pr-review-IU4N3TEK.js +16 -0
- package/dist/prd-SHVQW6RM.js +16 -0
- package/dist/review-L5F77QAC.js +14 -0
- package/dist/run-BRBFHVUO.js +1860 -0
- package/dist/run-BRBFHVUO.js.map +1 -0
- package/dist/{web-3SBYL7QJ.js → web-WQISLO66.js} +4 -4
- package/package.json +1 -1
- package/prompts/execute.md +2 -2
- package/prompts/plan.md +10 -1
- package/prompts/pr.md +9 -4
- package/web/CLAUDE.md +70 -8
- package/web/public/app.css +444 -0
- package/web/public/app.js +573 -17
- package/web/public/index.html +50 -0
- package/dist/chunk-3E6KASSE.js +0 -123
- package/dist/chunk-3E6KASSE.js.map +0 -1
- package/dist/chunk-6UTVPKNF.js.map +0 -1
- package/dist/chunk-EYVXLRRD.js.map +0 -1
- package/dist/chunk-JOK7VXRV.js.map +0 -1
- package/dist/chunk-RUTDK6ZF.js.map +0 -1
- package/dist/chunk-WGDLUPSF.js.map +0 -1
- package/dist/chunk-WO6ERABE.js.map +0 -1
- package/dist/chunk-ZYBYMEWG.js.map +0 -1
- package/dist/execute-AOEM52CD.js +0 -14
- package/dist/init-TBC3WI74.js +0 -9
- package/dist/plan-YDZYB2BO.js +0 -16
- package/dist/pr-SIXMJIZF.js +0 -16
- package/dist/pr-review-AY56ZPJR.js +0 -16
- package/dist/prd-MBSSBLGO.js +0 -16
- package/dist/review-2MDDHZ4X.js +0 -14
- package/dist/run-SEB6F3W4.js +0 -733
- package/dist/run-SEB6F3W4.js.map +0 -1
- /package/dist/{analyze-2RVGY5OK.js.map → analyze-VSWAEVN3.js.map} +0 -0
- /package/dist/{chunk-KHTLN54U.js.map → chunk-JGKPSWOA.js.map} +0 -0
- /package/dist/{chunk-XPW46TI5.js.map → chunk-M37YZYDO.js.map} +0 -0
- /package/dist/{chunk-G37JNQKB.js.map → chunk-M72ZEPWD.js.map} +0 -0
- /package/dist/{chunk-OPIDR2DC.js.map → chunk-NB6WKTBL.js.map} +0 -0
- /package/dist/{chunk-6IOPYFUM.js.map → chunk-TLSIK656.js.map} +0 -0
- /package/dist/{chunk-6L2BPOE3.js.map → chunk-WHEU55ZP.js.map} +0 -0
- /package/dist/{chunk-EOTULFWV.js.map → chunk-X7XBF5TS.js.map} +0 -0
- /package/dist/{config-OAZG7KIK.js.map → config-J5DW6HSY.js.map} +0 -0
- /package/dist/{execute-AOEM52CD.js.map → execute-Z2DKGVLR.js.map} +0 -0
- /package/dist/{generate-BEJF3SVJ.js.map → generate-ERDPOTKX.js.map} +0 -0
- /package/dist/{init-TBC3WI74.js.map → init-UY6ZCIFT.js.map} +0 -0
- /package/dist/{plan-YDZYB2BO.js.map → plan-REMAMCX4.js.map} +0 -0
- /package/dist/{pr-SIXMJIZF.js.map → pr-KERP52TI.js.map} +0 -0
- /package/dist/{pr-review-AY56ZPJR.js.map → pr-review-IU4N3TEK.js.map} +0 -0
- /package/dist/{prd-MBSSBLGO.js.map → prd-SHVQW6RM.js.map} +0 -0
- /package/dist/{review-2MDDHZ4X.js.map → review-L5F77QAC.js.map} +0 -0
- /package/dist/{web-3SBYL7QJ.js.map → web-WQISLO66.js.map} +0 -0
package/web/public/index.html
CHANGED
|
@@ -15,8 +15,31 @@
|
|
|
15
15
|
</div>
|
|
16
16
|
|
|
17
17
|
<main>
|
|
18
|
+
<div id="view-dashboard" class="view" hidden>
|
|
19
|
+
<header class="card header">
|
|
20
|
+
<div class="header-main">
|
|
21
|
+
<h1><span class="brand">issue-flow</span></h1>
|
|
22
|
+
<p class="muted">Execuções ativas</p>
|
|
23
|
+
</div>
|
|
24
|
+
<div class="header-side">
|
|
25
|
+
<label class="refresh-control">
|
|
26
|
+
Atualizar
|
|
27
|
+
<select id="refresh-select-dashboard" aria-label="Intervalo de atualização"></select>
|
|
28
|
+
</label>
|
|
29
|
+
</div>
|
|
30
|
+
</header>
|
|
31
|
+
<div id="dashboard" class="dashboard-grid"></div>
|
|
32
|
+
<footer class="muted footer">
|
|
33
|
+
<span id="dashboard-meta" aria-live="polite"></span>
|
|
34
|
+
</footer>
|
|
35
|
+
</div>
|
|
36
|
+
|
|
37
|
+
<div id="view-detail" class="view">
|
|
18
38
|
<header class="card header">
|
|
19
39
|
<div class="header-main">
|
|
40
|
+
<button type="button" id="back-to-dashboard" class="back-link" hidden>
|
|
41
|
+
← Todas as execuções
|
|
42
|
+
</button>
|
|
20
43
|
<h1>
|
|
21
44
|
<span class="brand">issue-flow</span>
|
|
22
45
|
<a id="issue-link" class="issue-link" target="_blank" rel="noopener" hidden>#—</a>
|
|
@@ -41,6 +64,14 @@
|
|
|
41
64
|
<div id="alerts-body"></div>
|
|
42
65
|
</section>
|
|
43
66
|
|
|
67
|
+
<div class="tabs" role="tablist" aria-label="Visualizações do painel">
|
|
68
|
+
<button type="button" class="tab" role="tab" id="tab-execution"
|
|
69
|
+
aria-controls="panel-execution" aria-selected="true">Execução</button>
|
|
70
|
+
<button type="button" class="tab" role="tab" id="tab-kanban"
|
|
71
|
+
aria-controls="panel-kanban" aria-selected="false">Kanban</button>
|
|
72
|
+
</div>
|
|
73
|
+
|
|
74
|
+
<div class="tab-panel" id="panel-execution" role="tabpanel" aria-labelledby="tab-execution" tabindex="0">
|
|
44
75
|
<div class="columns">
|
|
45
76
|
<section class="card">
|
|
46
77
|
<h2>Resumo da issue</h2>
|
|
@@ -108,12 +139,31 @@
|
|
|
108
139
|
</div>
|
|
109
140
|
<ol id="logs" class="plain-list logs"></ol>
|
|
110
141
|
</section>
|
|
142
|
+
</div>
|
|
143
|
+
|
|
144
|
+
<div class="tab-panel" id="panel-kanban" role="tabpanel" aria-labelledby="tab-kanban" tabindex="0" hidden>
|
|
145
|
+
<section class="card">
|
|
146
|
+
<h2>Kanban de user stories</h2>
|
|
147
|
+
<div id="kanban" class="kanban"></div>
|
|
148
|
+
</section>
|
|
149
|
+
</div>
|
|
111
150
|
|
|
112
151
|
<footer class="muted footer">
|
|
113
152
|
<span id="session-meta"></span>
|
|
114
153
|
</footer>
|
|
154
|
+
</div>
|
|
115
155
|
</main>
|
|
116
156
|
|
|
157
|
+
<div id="drawer-overlay" class="drawer-overlay" hidden></div>
|
|
158
|
+
<aside id="drawer" class="drawer" role="dialog" aria-modal="true"
|
|
159
|
+
aria-labelledby="drawer-title" tabindex="-1" hidden>
|
|
160
|
+
<div class="drawer-head">
|
|
161
|
+
<h2 id="drawer-title">Detalhes da user story</h2>
|
|
162
|
+
<button type="button" id="drawer-close" class="drawer-close" aria-label="Fechar detalhes">✕</button>
|
|
163
|
+
</div>
|
|
164
|
+
<div id="drawer-body" class="drawer-body"></div>
|
|
165
|
+
</aside>
|
|
166
|
+
|
|
117
167
|
<noscript>
|
|
118
168
|
<p class="noscript">Esta interface precisa de JavaScript. O estado bruto está disponível em
|
|
119
169
|
<a href="status.json">status.json</a>.</p>
|
package/dist/chunk-3E6KASSE.js
DELETED
|
@@ -1,123 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
readFileWithGrace,
|
|
4
|
-
runPhaseWithRetry
|
|
5
|
-
} from "./chunk-OPIDR2DC.js";
|
|
6
|
-
import {
|
|
7
|
-
issuePlaceholders,
|
|
8
|
-
resolveCommandIssue
|
|
9
|
-
} from "./chunk-EYVXLRRD.js";
|
|
10
|
-
import {
|
|
11
|
-
isTransientFailure
|
|
12
|
-
} from "./chunk-HDV3YDTG.js";
|
|
13
|
-
import {
|
|
14
|
-
runHeadless
|
|
15
|
-
} from "./chunk-KHTLN54U.js";
|
|
16
|
-
import {
|
|
17
|
-
publishPhaseMetrics
|
|
18
|
-
} from "./chunk-ZYBYMEWG.js";
|
|
19
|
-
import {
|
|
20
|
-
applyPlaceholders,
|
|
21
|
-
loadPrompt
|
|
22
|
-
} from "./chunk-SLHZPB3C.js";
|
|
23
|
-
import {
|
|
24
|
-
resolveIssuePaths
|
|
25
|
-
} from "./chunk-RUTDK6ZF.js";
|
|
26
|
-
import {
|
|
27
|
-
getGlobalTimeout,
|
|
28
|
-
loadTaskPlan,
|
|
29
|
-
printError,
|
|
30
|
-
printSuccess,
|
|
31
|
-
saveTaskPlan,
|
|
32
|
-
taskPlanSchema
|
|
33
|
-
} from "./chunk-WO6ERABE.js";
|
|
34
|
-
|
|
35
|
-
// src/commands/plan.ts
|
|
36
|
-
import { mkdir, readFile } from "fs/promises";
|
|
37
|
-
async function runPlan(issue, resolvedIssue) {
|
|
38
|
-
const issueNumber = issue.replace(/^#/, "");
|
|
39
|
-
const paths = await resolveIssuePaths(issueNumber);
|
|
40
|
-
const resolution = await resolveCommandIssue(issueNumber, resolvedIssue);
|
|
41
|
-
if (!resolution.ok) {
|
|
42
|
-
return resolution.code;
|
|
43
|
-
}
|
|
44
|
-
const prdPath = paths.prdFile;
|
|
45
|
-
let prdContent;
|
|
46
|
-
try {
|
|
47
|
-
prdContent = await readFile(prdPath, "utf-8");
|
|
48
|
-
} catch {
|
|
49
|
-
printError(`PRD not found at ${prdPath}. Run 'issue-flow prd ${issueNumber}' first.`);
|
|
50
|
-
return 1;
|
|
51
|
-
}
|
|
52
|
-
const tasksPath = paths.tasksFile;
|
|
53
|
-
const template = await loadPrompt("plan");
|
|
54
|
-
const prompt = applyPlaceholders(template, {
|
|
55
|
-
__ISSUE_NUMBER__: issueNumber,
|
|
56
|
-
__PRD_CONTENT__: prdContent,
|
|
57
|
-
__TASKS_PATH__: tasksPath,
|
|
58
|
-
...issuePlaceholders(resolution.resolved)
|
|
59
|
-
});
|
|
60
|
-
await mkdir(paths.issueDir, { recursive: true });
|
|
61
|
-
const outcome = await runPhaseWithRetry({
|
|
62
|
-
phase: "plan",
|
|
63
|
-
attempt: async () => {
|
|
64
|
-
const startedAtMs = Date.now();
|
|
65
|
-
const result = await runHeadless({
|
|
66
|
-
prompt,
|
|
67
|
-
maxTurns: 25,
|
|
68
|
-
timeout: getGlobalTimeout() ?? 3e5,
|
|
69
|
-
// json (not text) so the CLI reports usage: the envelope's `result`
|
|
70
|
-
// field carries the same assistant text this phase already consumed.
|
|
71
|
-
outputFormat: "json",
|
|
72
|
-
allowedTools: ["Bash", "Read", "Glob", "Grep", "Write"],
|
|
73
|
-
addDirs: [paths.issueDir],
|
|
74
|
-
statusMessage: `Converting PRD to task plan for issue #${issueNumber}...`
|
|
75
|
-
});
|
|
76
|
-
publishPhaseMetrics("plan", result.cost, startedAtMs);
|
|
77
|
-
if (!result.success) {
|
|
78
|
-
return {
|
|
79
|
-
ok: false,
|
|
80
|
-
transient: isTransientFailure(1, result.error ?? ""),
|
|
81
|
-
error: `Task plan generation failed: ${result.error}`
|
|
82
|
-
};
|
|
83
|
-
}
|
|
84
|
-
let rawContent;
|
|
85
|
-
try {
|
|
86
|
-
rawContent = await readFileWithGrace(tasksPath);
|
|
87
|
-
} catch {
|
|
88
|
-
return { ok: false, transient: true, error: `tasks.json was not created at ${tasksPath}` };
|
|
89
|
-
}
|
|
90
|
-
let parsed;
|
|
91
|
-
try {
|
|
92
|
-
parsed = JSON.parse(rawContent);
|
|
93
|
-
} catch {
|
|
94
|
-
return { ok: false, transient: true, error: "tasks.json contains invalid JSON" };
|
|
95
|
-
}
|
|
96
|
-
const validation = taskPlanSchema.safeParse(parsed);
|
|
97
|
-
if (!validation.success) {
|
|
98
|
-
const issues = validation.error.issues.map((i) => ` - ${i.path.join(".")}: ${i.message}`).join("\n");
|
|
99
|
-
return {
|
|
100
|
-
ok: false,
|
|
101
|
-
transient: true,
|
|
102
|
-
error: `tasks.json does not match expected schema:
|
|
103
|
-
${issues}`
|
|
104
|
-
};
|
|
105
|
-
}
|
|
106
|
-
return { ok: true };
|
|
107
|
-
}
|
|
108
|
-
});
|
|
109
|
-
if (!outcome.ok) {
|
|
110
|
-
printError(outcome.error ?? `Task plan generation failed for issue #${issueNumber}`);
|
|
111
|
-
return 1;
|
|
112
|
-
}
|
|
113
|
-
const plan = await loadTaskPlan(tasksPath);
|
|
114
|
-
plan.pipeline.jsonCompleted = true;
|
|
115
|
-
await saveTaskPlan(tasksPath, plan);
|
|
116
|
-
printSuccess(`Task plan saved to ${tasksPath} (${plan.userStories.length} stories)`);
|
|
117
|
-
return 0;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
export {
|
|
121
|
-
runPlan
|
|
122
|
-
};
|
|
123
|
-
//# sourceMappingURL=chunk-3E6KASSE.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/plan.ts"],"sourcesContent":["import { mkdir, readFile } from 'node:fs/promises';\nimport { runHeadless } from '../core/headless.js';\nimport { readFileWithGrace, runPhaseWithRetry } from '../core/phase-runner.js';\nimport { applyPlaceholders, loadPrompt } from '../core/prompt-resolver.js';\nimport { publishPhaseMetrics } from '../core/session-metrics.js';\nimport { loadTaskPlan, saveTaskPlan } from '../core/state-manager.js';\nimport { getGlobalTimeout } from '../core/verbose.js';\nimport { issuePlaceholders, resolveCommandIssue } from '../issues/context.js';\nimport type { ResolvedIssue } from '../issues/types.js';\nimport { taskPlanSchema } from '../schemas.js';\nimport { resolveIssuePaths } from '../storage/resolve.js';\nimport { printError, printSuccess } from '../ui/logger.js';\nimport { isTransientFailure } from '../utils/retry.js';\n\nexport async function runPlan(issue: string, resolvedIssue?: ResolvedIssue): Promise<number> {\n const issueNumber = issue.replace(/^#/, '');\n const paths = await resolveIssuePaths(issueNumber);\n\n const resolution = await resolveCommandIssue(issueNumber, resolvedIssue);\n if (!resolution.ok) {\n return resolution.code;\n }\n\n // Read the PRD\n const prdPath = paths.prdFile;\n let prdContent: string;\n try {\n prdContent = await readFile(prdPath, 'utf-8');\n } catch {\n printError(`PRD not found at ${prdPath}. Run 'issue-flow prd ${issueNumber}' first.`);\n return 1;\n }\n\n const tasksPath = paths.tasksFile;\n\n const template = await loadPrompt('plan');\n const prompt = applyPlaceholders(template, {\n __ISSUE_NUMBER__: issueNumber,\n __PRD_CONTENT__: prdContent,\n __TASKS_PATH__: tasksPath,\n ...issuePlaceholders(resolution.resolved),\n });\n\n await mkdir(paths.issueDir, { recursive: true });\n\n const outcome = await runPhaseWithRetry({\n phase: 'plan',\n attempt: async () => {\n const startedAtMs = Date.now();\n const result = await runHeadless({\n prompt,\n maxTurns: 25,\n timeout: getGlobalTimeout() ?? 300_000,\n // json (not text) so the CLI reports usage: the envelope's `result`\n // field carries the same assistant text this phase already consumed.\n outputFormat: 'json',\n allowedTools: ['Bash', 'Read', 'Glob', 'Grep', 'Write'],\n addDirs: [paths.issueDir],\n statusMessage: `Converting PRD to task plan for issue #${issueNumber}...`,\n });\n // One event per attempt; the reducer sums them into the phase total.\n publishPhaseMetrics('plan', result.cost, startedAtMs);\n\n if (!result.success) {\n return {\n ok: false,\n transient: isTransientFailure(1, result.error ?? ''),\n error: `Task plan generation failed: ${result.error}`,\n };\n }\n\n // Verify the file was created, tolerating a brief FS-visibility lag.\n let rawContent: string;\n try {\n rawContent = await readFileWithGrace(tasksPath);\n } catch {\n return { ok: false, transient: true, error: `tasks.json was not created at ${tasksPath}` };\n }\n\n // Validate JSON structure — a content defect, not a timing issue, but\n // still worth a bounded retry since it's a fresh Claude invocation.\n let parsed: unknown;\n try {\n parsed = JSON.parse(rawContent);\n } catch {\n return { ok: false, transient: true, error: 'tasks.json contains invalid JSON' };\n }\n\n // Validate with zod schema\n const validation = taskPlanSchema.safeParse(parsed);\n if (!validation.success) {\n const issues = validation.error.issues\n .map((i) => ` - ${i.path.join('.')}: ${i.message}`)\n .join('\\n');\n return {\n ok: false,\n transient: true,\n error: `tasks.json does not match expected schema:\\n${issues}`,\n };\n }\n\n return { ok: true };\n },\n });\n\n if (!outcome.ok) {\n printError(outcome.error ?? `Task plan generation failed for issue #${issueNumber}`);\n return 1;\n }\n\n // Ensure pipeline state reflects completion of this phase\n const plan = await loadTaskPlan(tasksPath);\n plan.pipeline.jsonCompleted = true;\n await saveTaskPlan(tasksPath, plan);\n\n printSuccess(`Task plan saved to ${tasksPath} (${plan.userStories.length} stories)`);\n return 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,gBAAgB;AAchC,eAAsB,QAAQ,OAAe,eAAgD;AAC3F,QAAM,cAAc,MAAM,QAAQ,MAAM,EAAE;AAC1C,QAAM,QAAQ,MAAM,kBAAkB,WAAW;AAEjD,QAAM,aAAa,MAAM,oBAAoB,aAAa,aAAa;AACvE,MAAI,CAAC,WAAW,IAAI;AAClB,WAAO,WAAW;AAAA,EACpB;AAGA,QAAM,UAAU,MAAM;AACtB,MAAI;AACJ,MAAI;AACF,iBAAa,MAAM,SAAS,SAAS,OAAO;AAAA,EAC9C,QAAQ;AACN,eAAW,oBAAoB,OAAO,yBAAyB,WAAW,UAAU;AACpF,WAAO;AAAA,EACT;AAEA,QAAM,YAAY,MAAM;AAExB,QAAM,WAAW,MAAM,WAAW,MAAM;AACxC,QAAM,SAAS,kBAAkB,UAAU;AAAA,IACzC,kBAAkB;AAAA,IAClB,iBAAiB;AAAA,IACjB,gBAAgB;AAAA,IAChB,GAAG,kBAAkB,WAAW,QAAQ;AAAA,EAC1C,CAAC;AAED,QAAM,MAAM,MAAM,UAAU,EAAE,WAAW,KAAK,CAAC;AAE/C,QAAM,UAAU,MAAM,kBAAkB;AAAA,IACtC,OAAO;AAAA,IACP,SAAS,YAAY;AACnB,YAAM,cAAc,KAAK,IAAI;AAC7B,YAAM,SAAS,MAAM,YAAY;AAAA,QAC/B;AAAA,QACA,UAAU;AAAA,QACV,SAAS,iBAAiB,KAAK;AAAA;AAAA;AAAA,QAG/B,cAAc;AAAA,QACd,cAAc,CAAC,QAAQ,QAAQ,QAAQ,QAAQ,OAAO;AAAA,QACtD,SAAS,CAAC,MAAM,QAAQ;AAAA,QACxB,eAAe,0CAA0C,WAAW;AAAA,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":["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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AA,EACtC;AACA,SAAO;AACT;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
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","../src/issues/context.ts"],"sourcesContent":["import type { IssueProvider } from './provider.js';\nimport type { IssueSource } from './types.js';\n\n/**\n * Registry of Issue providers.\n *\n * Adding an origin is creating a provider file and registering one line here\n * (or from the caller's side), so nothing in src/commands/ needs to know the\n * list of sources.\n */\nconst providers = new Map<IssueSource, IssueProvider>();\n\n/**\n * Register a provider under its own `name`.\n *\n * Registering the same source twice replaces the previous entry, which is what\n * lets tests substitute a real provider with a fake one.\n */\nexport function registerProvider(provider: IssueProvider): void {\n providers.set(provider.name, provider);\n}\n\n/** Sources currently registered, in registration order. */\nexport function getRegisteredSources(): IssueSource[] {\n return [...providers.keys()];\n}\n\n/**\n * Look up a provider by origin.\n *\n * @throws when the origin is not registered, listing what is available so the\n * caller knows which sources they can pick instead.\n */\nexport function getProvider(source: IssueSource): IssueProvider {\n const provider = providers.get(source);\n if (provider === undefined) {\n const available = getRegisteredSources();\n const hint =\n available.length > 0\n ? `Available sources: ${available.join(', ')}.`\n : 'No Issue providers are registered.';\n throw new Error(`Unknown Issue source: '${source}'. ${hint}`);\n }\n return provider;\n}\n\n/** Drop every registration. Intended for test isolation. */\nexport function clearProviders(): void {\n providers.clear();\n}\n","import { createHash } from 'node:crypto';\n\n/**\n * Content hashing shared by every Issue provider.\n *\n * The hash is what lets the resolver tell \"the local and the remote Issue are\n * the same demand\" from \"they diverged\", so it has to be stable across\n * platforms: Windows checkouts store CRLF, editors add or drop trailing\n * newlines, and neither should count as a content change.\n */\n\n/** Normalizes line endings (CRLF/CR to LF) and trims the edges. */\nfunction normalizeText(value: string): string {\n return value.replace(/\\r\\n?/g, '\\n').trim();\n}\n\n/**\n * Returns `sha256:<hex>` for the given title and body.\n *\n * The payload is a canonical JSON object rather than a concatenation, so text\n * moved from the title into the body always changes the hash.\n */\nexport function hashIssueContent(title: string, body: string): string {\n const payload = JSON.stringify({\n title: normalizeText(title),\n body: normalizeText(body),\n });\n const digest = createHash('sha256').update(payload, 'utf8').digest('hex');\n return `sha256:${digest}`;\n}\n","import { run } from '../../utils/shell.js';\nimport { hashIssueContent } from '../hash.js';\nimport type { IssueProvider } from '../provider.js';\nimport type { Issue, IssueDraft, IssueState } from '../types.js';\n\n/** Fields requested from `gh issue view`, in the order the PRD specifies. */\nconst VIEW_FIELDS = 'number,title,body,labels,state,url,createdAt,updatedAt';\n\n/** Timeout for the availability probes, matching the `init` prerequisite checks. */\nconst PROBE_TIMEOUT_MS = 10_000;\n\n/**\n * gh reports a missing Issue on stderr with one of these phrasings. The match\n * must stay issue-specific: a bare /not found/ would also swallow\n * `gh: command not found`, turning a broken environment into \"issue absent\".\n * Anything else on a non-zero exit is a real failure (network, auth, gh not\n * installed) and must surface as a thrown error.\n */\nconst NOT_FOUND_PATTERN =\n /could not resolve to an issue|no issues? found|issue not found|could not find any issue/i;\n\ninterface GhLabel {\n name?: unknown;\n}\n\ninterface GhIssuePayload {\n number?: unknown;\n title?: unknown;\n body?: unknown;\n labels?: unknown;\n state?: unknown;\n url?: unknown;\n createdAt?: unknown;\n updatedAt?: unknown;\n}\n\nfunction normalizeState(state: unknown): IssueState {\n return String(state ?? '').toUpperCase() === 'CLOSED' ? 'closed' : 'open';\n}\n\nfunction normalizeLabels(labels: unknown): string[] {\n if (!Array.isArray(labels)) return [];\n return labels\n .map((label: GhLabel | string) => (typeof label === 'string' ? label : label?.name))\n .filter((name): name is string => typeof name === 'string' && name.length > 0);\n}\n\nfunction toIssue(payload: GhIssuePayload): Issue {\n const title = typeof payload.title === 'string' ? payload.title : '';\n const body = typeof payload.body === 'string' ? payload.body : '';\n const number = typeof payload.number === 'number' ? payload.number : null;\n const url = typeof payload.url === 'string' && payload.url.length > 0 ? payload.url : null;\n\n return {\n id: number === null ? '' : String(number),\n number,\n title,\n body,\n labels: normalizeLabels(payload.labels),\n state: normalizeState(payload.state),\n source: 'github',\n remoteRef: url,\n createdAt: typeof payload.createdAt === 'string' ? payload.createdAt : '',\n updatedAt: typeof payload.updatedAt === 'string' ? payload.updatedAt : '',\n contentHash: hashIssueContent(title, body),\n raw: payload,\n };\n}\n\n/** Strip a leading `#` so both `23` and `#23` are accepted. */\nfunction normalizeId(id: string): string {\n return id.trim().replace(/^#/, '');\n}\n\nfunction extractIssueNumber(output: string): string | null {\n return output.match(/\\/issues\\/(\\d+)/)?.[1] ?? null;\n}\n\n/**\n * Issue provider backed by the GitHub CLI.\n *\n * Every call goes through `run` (execa, no shell) so tests can mock the shell\n * layer instead of the network, and so the Issue content is identical across\n * every pipeline phase.\n */\nexport class GitHubIssueProvider implements IssueProvider {\n readonly name = 'github' as const;\n\n /** True when gh is installed and authenticated. Never throws. */\n async isAvailable(): Promise<boolean> {\n try {\n const version = await run('gh', ['--version'], { timeout: PROBE_TIMEOUT_MS });\n if (version.exitCode !== 0) return false;\n\n const auth = await run('gh', ['auth', 'status'], { timeout: PROBE_TIMEOUT_MS });\n return auth.exitCode === 0;\n } catch {\n return false;\n }\n }\n\n async get(id: string): Promise<Issue | null> {\n const issueId = normalizeId(id);\n const result = await run('gh', ['issue', 'view', issueId, '--json', VIEW_FIELDS]);\n\n if (result.exitCode !== 0) {\n const detail = (result.stderr || result.stdout).trim();\n if (NOT_FOUND_PATTERN.test(detail)) return null;\n throw new Error(\n `Failed to fetch GitHub issue #${issueId}: ${detail || 'gh issue view failed'}`,\n );\n }\n\n let payload: GhIssuePayload;\n try {\n payload = JSON.parse(result.stdout);\n } catch {\n throw new Error(\n `Failed to parse gh output for issue #${issueId}: ${result.stdout.slice(0, 200)}`,\n );\n }\n\n return toIssue(payload);\n }\n\n async create(draft: IssueDraft): Promise<Issue> {\n const args = ['issue', 'create', '--title', draft.title, '--body', draft.body];\n for (const label of draft.labels) {\n args.push('--label', label);\n }\n\n const result = await run('gh', args);\n if (result.exitCode !== 0) {\n const detail = (result.stderr || result.stdout).trim();\n throw new Error(`Failed to create GitHub issue: ${detail || 'gh issue create failed'}`);\n }\n\n const number = extractIssueNumber(result.stdout);\n if (!number) {\n throw new Error(\n `GitHub issue creation did not report an issue URL: ${result.stdout.trim() || '(no output)'}`,\n );\n }\n\n const created = await this.get(number);\n if (!created) {\n throw new Error(`GitHub issue #${number} was created but could not be read back`);\n }\n return created;\n }\n\n async close(id: string): Promise<void> {\n const issueId = normalizeId(id);\n const result = await run('gh', ['issue', 'close', issueId]);\n\n if (result.exitCode !== 0) {\n const detail = (result.stderr || result.stdout).trim();\n throw new Error(\n `Failed to close GitHub issue #${issueId}: ${detail || 'gh issue close failed'}`,\n );\n }\n }\n}\n\n/** Shared instance; providers are stateless, so a singleton is enough. */\nexport const githubIssueProvider = new GitHubIssueProvider();\n","import { constants } from 'node:fs';\nimport { access, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { ZodError } from 'zod';\nimport { isoNow } from '../../core/state-manager.js';\nimport { issueMetadataSchema } from '../../schemas.js';\nimport type { IssuePaths } from '../../storage/paths.js';\nimport { resolveIssuePaths, resolveProjectPaths } from '../../storage/resolve.js';\nimport { writeFileAtomic } from '../../utils/fs.js';\nimport { getProjectRoot } from '../../utils/git.js';\nimport { run } from '../../utils/shell.js';\nimport { hashIssueContent } from '../hash.js';\nimport type { IssueProvider } from '../provider.js';\nimport type { Issue, IssueDraft, IssueMetadata } from '../types.js';\n\n/** Timeout for the optional remote probes done while allocating an identifier. */\nconst REMOTE_PROBE_TIMEOUT_MS = 10_000;\n\nfunction isNotFound(err: unknown): boolean {\n const code = (err as NodeJS.ErrnoException).code;\n return code === 'ENOENT' || code === 'ENOTDIR';\n}\n\n/**\n * True when `dir` already is a writable directory, or does not exist yet but\n * would be created successfully by `mkdir(dir, { recursive: true })` — i.e.\n * its nearest existing ancestor is a writable directory.\n *\n * Never mutates the filesystem: `isAvailable()` only needs to answer \"could\n * this work\", which must not leave a `~/.issue-flow/projects/<id>/` directory\n * behind for a project that ends up never using local issues (every other\n * source is queried on every resolution, so this runs far more often than the\n * provider is actually chosen).\n */\nasync function isWritableDirectory(dir: string): Promise<boolean> {\n let current = dir;\n for (;;) {\n let stats: Awaited<ReturnType<typeof stat>>;\n try {\n stats = await stat(current);\n } catch (err: unknown) {\n if (!isNotFound(err)) return false;\n const parent = dirname(current);\n if (parent === current) return false; // reached the filesystem root\n current = parent;\n continue;\n }\n if (!stats.isDirectory()) return false;\n try {\n await access(current, constants.W_OK);\n return true;\n } catch {\n return false;\n }\n }\n}\n\n/**\n * Identifiers become path segments, so anything that could escape the issues\n * directory is rejected before it reaches `join`.\n */\nfunction normalizeId(id: string): string {\n const normalized = id.trim().replace(/^#/, '');\n if (normalized.length === 0) {\n throw new Error('Local issue identifier cannot be empty');\n }\n if (/[/\\\\]/.test(normalized) || normalized === '.' || normalized === '..') {\n throw new Error(`Invalid local issue identifier: '${id}'`);\n }\n return normalized;\n}\n\nfunction toNumber(id: string): number | null {\n return /^\\d+$/.test(id) ? Number.parseInt(id, 10) : null;\n}\n\n/**\n * Title lives in the leading H1, body is everything after it.\n *\n * Only the first non-empty line is considered: an H1 further down belongs to\n * the body (issue descriptions routinely use headings), so promoting it would\n * silently retitle the Issue.\n */\nexport function parseIssueMarkdown(content: string): { title: string; body: string } {\n const lines = content.replace(/\\r\\n?/g, '\\n').split('\\n');\n const headingIndex = lines.findIndex((line) => line.trim().length > 0);\n const heading = headingIndex === -1 ? undefined : lines[headingIndex].match(/^#[ \\t]+(.*)$/);\n\n if (!heading) {\n return { title: '', body: lines.join('\\n').trim() };\n }\n\n return {\n title: heading[1].trim(),\n body: lines\n .slice(headingIndex + 1)\n .join('\\n')\n .trim(),\n };\n}\n\nfunction renderIssueMarkdown(title: string, body: string): string {\n return `# ${title}\\n\\n${body.trim()}\\n`;\n}\n\n/**\n * Issue provider backed by plain files in the project's global storage\n * directory (`~/.issue-flow/projects/<project-id>/issues/<id>/`).\n *\n * Enables the whole pipeline without any network access: no gh, no remote, no\n * authentication. `issue.md` is the source of truth for the content and\n * `metadata.json` for everything else; the content hash is always recomputed\n * from the file so a hand-edited issue.md is never reported as unchanged.\n *\n * Every path goes through `resolveIssuePaths()`, exactly like the pipeline\n * commands, so an issue that still only exists under the legacy\n * `<projectRoot>/issues/` tree is migrated on first read instead of coming back\n * as \"not found\".\n */\nexport class LocalFileIssueProvider implements IssueProvider {\n readonly name = 'local' as const;\n\n private readonly configuredRoot?: string;\n private cachedRoot?: string;\n\n /**\n * @param projectRoot Repository the issues belong to. It is no longer the\n * literal parent of an `issues/` directory: it is the root the project id —\n * and therefore the global storage directory — is derived from.\n */\n constructor(projectRoot?: string) {\n this.configuredRoot = projectRoot;\n }\n\n /**\n * True whenever the project's global storage directory already is — or\n * could be — a writable directory. Never mutates the filesystem, never\n * throws.\n *\n * A brand new project has no directory of its own until something writes, so\n * \"does it already exist\" would report the provider as unavailable exactly\n * when it is about to create the very first issue — `isWritableDirectory`\n * walks up to the nearest existing ancestor instead of requiring the leaf to\n * be there already.\n */\n async isAvailable(): Promise<boolean> {\n try {\n const { projectDir } = await resolveProjectPaths({ projectRoot: await this.root() });\n return await isWritableDirectory(projectDir);\n } catch {\n return false;\n }\n }\n\n async get(id: string): Promise<Issue | null> {\n const issueId = normalizeId(id);\n const markdownPath = await this.issueFile(issueId);\n\n let raw: string;\n try {\n raw = await readFile(markdownPath, 'utf-8');\n } catch (err: unknown) {\n if (isNotFound(err)) return null;\n throw err;\n }\n\n const { title: headingTitle, body } = parseIssueMarkdown(raw);\n const metadata = await this.readMetadata(issueId);\n const title = headingTitle || metadata?.title || '';\n\n if (metadata) {\n return {\n id: metadata.id,\n number: metadata.number,\n title,\n body,\n labels: metadata.labels,\n state: metadata.state,\n source: 'local',\n remoteRef: metadata.remote?.ref ?? null,\n createdAt: metadata.createdAt,\n updatedAt: metadata.updatedAt,\n contentHash: hashIssueContent(title, body),\n raw: metadata,\n };\n }\n\n // metadata.json is optional: an issue.md dropped in by hand still works,\n // with timestamps taken from the file itself.\n const stats = await stat(markdownPath);\n return {\n id: issueId,\n number: toNumber(issueId),\n title,\n body,\n labels: [],\n state: 'open',\n source: 'local',\n remoteRef: null,\n createdAt: stats.birthtime.toISOString(),\n updatedAt: stats.mtime.toISOString(),\n contentHash: hashIssueContent(title, body),\n };\n }\n\n async create(draft: IssueDraft): Promise<Issue> {\n // An explicit id is how a mirror keeps the identifier of the Issue it\n // mirrors: allocating a fresh one would make `issue-flow run <n>` see two\n // unrelated Issues instead of one demand in two places.\n const id = draft.id === undefined ? String(await this.allocateNumber()) : normalizeId(draft.id);\n const paths = await this.paths(id);\n\n await mkdir(paths.issueDir, { recursive: true });\n\n // Exclusive create (the 'wx' flag, O_EXCL under the hood) instead of a\n // check-then-write: two concurrent `create()` calls racing the same id\n // would both pass a plain existence check before either writes, and the\n // second would then silently overwrite the first through the atomic\n // temp+rename writer. The OS now rejects the loser instead.\n try {\n await writeFile(paths.issueFile, renderIssueMarkdown(draft.title, draft.body), {\n encoding: 'utf-8',\n flag: 'wx',\n });\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'EEXIST') {\n throw new Error(\n `Local issue '${id}' already exists at ${paths.issueFile}. ` +\n 'Remove it or pick another identifier before creating a new Issue.',\n );\n }\n throw err;\n }\n\n const timestamp = isoNow();\n const metadata: IssueMetadata = {\n schemaVersion: 1,\n id,\n number: toNumber(id),\n source: 'local',\n title: draft.title,\n labels: draft.labels,\n state: 'open',\n createdAt: timestamp,\n updatedAt: timestamp,\n contentHash: hashIssueContent(draft.title, draft.body),\n ...(draft.remote ? { remote: draft.remote } : {}),\n };\n\n await this.writeMetadata(id, metadata);\n\n return {\n id,\n number: metadata.number,\n title: draft.title,\n body: draft.body.trim(),\n labels: draft.labels,\n state: 'open',\n source: 'local',\n remoteRef: draft.remote?.ref ?? null,\n createdAt: timestamp,\n updatedAt: timestamp,\n contentHash: metadata.contentHash,\n raw: metadata,\n };\n }\n\n async close(id: string): Promise<void> {\n const issue = await this.get(id);\n if (!issue) {\n const issueDir = (await this.paths(normalizeId(id))).issueDir;\n throw new Error(`Local issue '${normalizeId(id)}' not found at ${issueDir}`);\n }\n\n const issueId = normalizeId(id);\n const existing = await this.readMetadata(issueId);\n\n await this.writeMetadata(issueId, {\n schemaVersion: 1,\n id: issue.id,\n number: issue.number,\n source: existing?.source ?? 'local',\n title: issue.title,\n labels: issue.labels,\n state: 'closed',\n createdAt: issue.createdAt,\n updatedAt: isoNow(),\n contentHash: issue.contentHash,\n ...(existing?.remote ? { remote: existing.remote } : {}),\n });\n }\n\n /**\n * Next free identifier: above every local number and, when GitHub answers,\n * above every remote one too. Sharing a numbering space with the remote is\n * what makes a naive `localMax + 1` collide the moment someone opens an Issue\n * on GitHub.\n */\n async allocateNumber(): Promise<number> {\n const [local, remote] = await Promise.all([this.highestLocalNumber(), highestRemoteNumber()]);\n return Math.max(local, remote) + 1;\n }\n\n private async root(): Promise<string> {\n if (this.configuredRoot !== undefined) return this.configuredRoot;\n this.cachedRoot ??= await getProjectRoot();\n return this.cachedRoot;\n }\n\n /**\n * Every artifact of one issue, from the same resolver the pipeline commands\n * use — which is also what triggers the migration of a legacy-only issue.\n */\n private async paths(id: string): Promise<IssuePaths> {\n return resolveIssuePaths(id, { projectRoot: await this.root() });\n }\n\n private async issueFile(id: string): Promise<string> {\n return (await this.paths(id)).issueFile;\n }\n\n private async metadataFile(id: string): Promise<string> {\n return (await this.paths(id)).metadataFile;\n }\n\n /** Parsed metadata.json, or `null` when the file is absent. */\n private async readMetadata(id: string): Promise<IssueMetadata | null> {\n const path = await this.metadataFile(id);\n\n let raw: string;\n try {\n raw = await readFile(path, 'utf-8');\n } catch (err: unknown) {\n if (isNotFound(err)) return null;\n throw err;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err: unknown) {\n throw new Error(`Invalid JSON in ${path}: ${(err as Error).message}`);\n }\n\n try {\n return issueMetadataSchema.parse(parsed);\n } catch (err: unknown) {\n if (err instanceof ZodError) {\n const details = err.issues\n .map((issue) => ` - ${issue.path.join('.') || '(root)'}: ${issue.message}`)\n .join('\\n');\n throw new Error(`Invalid issue metadata at ${path}:\\n${details}`);\n }\n throw err;\n }\n }\n\n private async writeMetadata(id: string, metadata: IssueMetadata): Promise<void> {\n await writeFileAtomic(await this.metadataFile(id), `${JSON.stringify(metadata, null, 2)}\\n`);\n }\n\n /**\n * Highest number across every `<issuesDir>/<id>/metadata.json` and numeric\n * directory name.\n *\n * Resolving `issuesDir` also migrates the legacy tree when it is the only one\n * that exists, which is what keeps an already-taken number from being handed\n * out a second time after adopting the global storage.\n */\n private async highestLocalNumber(): Promise<number> {\n const { issuesDir: dir } = await resolveProjectPaths({ projectRoot: await this.root() });\n\n let entries: string[];\n try {\n entries = (await readdir(dir, { withFileTypes: true }))\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name);\n } catch (err: unknown) {\n if (isNotFound(err)) return 0;\n throw err;\n }\n\n const numbers = await Promise.all(\n entries.map(async (name) => {\n const fromName = toNumber(name) ?? 0;\n // A directory whose metadata is unreadable still occupies its number.\n const fromMetadata = await this.readMetadata(name)\n .then((metadata) => metadata?.number ?? 0)\n .catch(() => 0);\n return Math.max(fromName, fromMetadata);\n }),\n );\n\n return numbers.reduce((max, value) => Math.max(max, value), 0);\n }\n}\n\n/** How many of the most-recently-created issues/PRs to inspect per probe. */\nconst REMOTE_PROBE_SAMPLE_SIZE = 20;\n\n/**\n * Highest number already taken on GitHub, or 0 when the remote is unreachable.\n *\n * Issues and pull requests share one counter, so both are probed: allocating\n * above the newest Issue alone would still collide with an open PR. Every\n * failure degrades to 0 — being offline must not block local creation.\n *\n * `gh ... list` defaults to sorting by creation date descending, which lines\n * up with number order in the overwhelming majority of repos — but that sort\n * is an implementation detail, not a contract. Rather than trust that the\n * single most-recent entry is also the highest-numbered one, a small sample\n * is fetched and the max is taken across it, which also tolerates the rare\n * case of a transferred issue whose creation date and number disagree.\n */\nasync function highestRemoteNumber(): Promise<number> {\n const probes = [\n ['issue', 'list'],\n ['pr', 'list'],\n ];\n\n const results = await Promise.all(\n probes.map(async (args) => {\n try {\n const result = await run(\n 'gh',\n [\n ...args,\n '--state',\n 'all',\n '--limit',\n String(REMOTE_PROBE_SAMPLE_SIZE),\n '--json',\n 'number',\n ],\n { timeout: REMOTE_PROBE_TIMEOUT_MS },\n );\n if (result.exitCode !== 0) return 0;\n\n const parsed = JSON.parse(result.stdout);\n if (!Array.isArray(parsed)) return 0;\n return parsed.reduce((max: number, entry: unknown) => {\n const n = (entry as { number?: unknown } | null)?.number;\n return typeof n === 'number' ? Math.max(max, n) : max;\n }, 0);\n } catch {\n return 0;\n }\n }),\n );\n\n return results.reduce((max, value) => Math.max(max, value), 0);\n}\n\n/** Shared instance resolving the project root lazily via git. */\nexport const localFileIssueProvider = new LocalFileIssueProvider();\n","import { githubIssueProvider } from './providers/github.js';\nimport { localFileIssueProvider } from './providers/local.js';\nimport { getRegisteredSources, registerProvider } from './registry.js';\n\n/**\n * Register the providers that ship with issue-flow.\n *\n * Idempotent and non-destructive: an origin that is already registered is left\n * untouched, so a test (or a future plugin) can install its own provider before\n * the first `resolveIssue` call without having it replaced by the built-in one.\n */\nexport function ensureProvidersRegistered(): void {\n const registered = new Set(getRegisteredSources());\n\n if (!registered.has('github')) {\n registerProvider(githubIssueProvider);\n }\n if (!registered.has('local')) {\n registerProvider(localFileIssueProvider);\n }\n}\n","import { createInterface, type Interface as ReadlineInterface } from 'node:readline';\nimport { loadIssuesConfig } from '../config.js';\nimport { printInfo, printWarning } from '../ui/logger.js';\nimport { ensureProvidersRegistered } from './bootstrap.js';\nimport { getProvider, getRegisteredSources } from './registry.js';\nimport type { Issue, IssueSource, IssuesConfig, ResolvedIssue } from './types.js';\n\n/**\n * Failure to settle on an Issue. Carries the exit code the CLI should return,\n * so callers propagate it instead of inventing their own.\n */\nexport class IssueResolutionError extends Error {\n readonly exitCode: number;\n\n constructor(message: string, exitCode = 1) {\n super(message);\n this.name = 'IssueResolutionError';\n this.exitCode = exitCode;\n }\n}\n\nexport interface ResolveIssueOptions {\n /** Already-resolved provider configuration. Defaults to loadIssuesConfig(). */\n config?: IssuesConfig;\n /** Origins to query. Defaults to every registered source. */\n sources?: IssueSource[];\n /**\n * Whether a prompt may be shown. Defaults to a real TTY outside CI, which is\n * what keeps `ask` from ever blocking a headless run.\n */\n interactive?: boolean;\n /** Input stream for the conflict prompt. Defaults to process.stdin. */\n stdin?: NodeJS.ReadableStream;\n /** Output stream for the conflict prompt. Defaults to process.stdout. */\n stdout?: NodeJS.WritableStream;\n /** Informational sink. Defaults to printInfo. */\n info?: (message: string) => void;\n /** Warning sink. Defaults to printWarning. */\n warn?: (message: string) => void;\n}\n\n/** How many invalid answers are tolerated before the prompt gives up. */\nconst MAX_PROMPT_ATTEMPTS = 3;\n\n/**\n * Labels shown to users for the built-in origins. An origin registered from\n * outside this package is displayed under its own name, so a new provider needs\n * no entry here.\n */\nconst SOURCE_LABELS: Record<string, string> = {\n github: 'GitHub',\n local: 'local',\n};\n\nfunction sourceLabel(source: IssueSource): string {\n return SOURCE_LABELS[source] ?? source;\n}\n\n/** Same label, capitalized for the numbered prompt ('local' -> 'Local'). */\nfunction promptLabel(source: IssueSource): string {\n const label = sourceLabel(source);\n return label.charAt(0).toUpperCase() + label.slice(1);\n}\n\ninterface Candidate {\n source: IssueSource;\n issue: Issue | null;\n /** Why the origin produced nothing, used only to explain a total miss. */\n reason: string | null;\n}\n\n/** A candidate that actually produced an Issue. */\ninterface FoundCandidate extends Candidate {\n issue: Issue;\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Read one origin without letting it break the others.\n *\n * An unavailable provider or a failed read degrades to \"no candidate\" plus a\n * reason: as long as another origin has the Issue the pipeline keeps going, and\n * when nothing is found the reasons are surfaced in the final error so a broken\n * environment is never reported as a missing Issue.\n */\nasync function fetchCandidate(\n source: IssueSource,\n id: string,\n warn: (message: string) => void,\n): Promise<Candidate> {\n let provider: ReturnType<typeof getProvider>;\n try {\n provider = getProvider(source);\n } catch (err) {\n return { source, issue: null, reason: errorMessage(err) };\n }\n\n let available: boolean;\n try {\n available = await provider.isAvailable();\n } catch (err) {\n return { source, issue: null, reason: `provider unavailable (${errorMessage(err)})` };\n }\n if (!available) {\n return { source, issue: null, reason: 'provider unavailable' };\n }\n\n try {\n const issue = await provider.get(id);\n return { source, issue, reason: issue === null ? 'not found' : null };\n } catch (err) {\n const reason = errorMessage(err);\n // A real failure (network, auth, corrupted metadata) must be visible even\n // when the other origin answers.\n warn(`Could not read issue '${id}' from ${sourceLabel(source)}: ${reason}`);\n return { source, issue: null, reason };\n }\n}\n\nfunction shortHash(hash: string): string {\n const hex = hash.startsWith('sha256:') ? hash.slice('sha256:'.length) : hash;\n return hex.slice(0, 12);\n}\n\n/** One line per origin describing what differs, without dumping every body. */\nfunction describeCandidate(source: IssueSource, issue: Issue): string {\n const lines = issue.body.length === 0 ? 0 : issue.body.split('\\n').length;\n return (\n ` ${sourceLabel(source).padEnd(6)} title: \"${issue.title}\" | body: ${lines} line(s), ` +\n `${issue.body.length} char(s) | updated: ${issue.updatedAt} | hash: ${shortHash(issue.contentHash)}`\n );\n}\n\n/** 'local and GitHub', 'local, GitHub and memory' — origins in query order. */\nfunction listSources(candidates: FoundCandidate[]): string {\n const labels = candidates.map((candidate) => sourceLabel(candidate.source));\n if (labels.length <= 1) {\n return labels.join('');\n }\n return `${labels.slice(0, -1).join(', ')} and ${labels[labels.length - 1]}`;\n}\n\n/**\n * Turn a readline interface into an awaitable line reader.\n *\n * Lines are queued instead of read on demand: `rl.question` drops whatever\n * arrives between two questions, which silently loses a piped answer typed\n * ahead of the prompt. Resolves `null` once the input is exhausted, so EOF ends\n * the prompt instead of hanging the process.\n */\nfunction createLineReader(\n rl: ReadlineInterface,\n output: NodeJS.WritableStream,\n): (query: string) => Promise<string | null> {\n const queued: string[] = [];\n let pending: ((line: string | null) => void) | null = null;\n let closed = false;\n\n rl.on('line', (line: string) => {\n if (pending !== null) {\n const resolve = pending;\n pending = null;\n resolve(line);\n return;\n }\n queued.push(line);\n });\n rl.on('close', () => {\n closed = true;\n if (pending !== null) {\n const resolve = pending;\n pending = null;\n resolve(null);\n }\n });\n\n return (query: string) =>\n new Promise<string | null>((resolve) => {\n const buffered = queued.shift();\n if (buffered !== undefined) {\n resolve(buffered);\n return;\n }\n if (closed) {\n resolve(null);\n return;\n }\n output.write(query);\n pending = resolve;\n });\n}\n\n/**\n * Interactive choice between the divergent versions.\n *\n * The options are numbered from the origins that actually answered, so a third\n * provider simply shows up as `[3] Memory` without this function knowing which\n * origins exist. Cancel is always the last option.\n */\nasync function promptChoice(\n sources: IssueSource[],\n stdin: NodeJS.ReadableStream,\n stdout: NodeJS.WritableStream,\n warn: (message: string) => void,\n): Promise<IssueSource | 'cancel'> {\n const options = sources.map((source, index) => `[${index + 1}] ${promptLabel(source)}`);\n const cancelOption = sources.length + 1;\n const query = `Which version should be used? ${options.join(' ')} [${cancelOption}] Cancel: `;\n const numbers = Array.from({ length: cancelOption }, (_, index) => String(index + 1));\n const accepted = `${numbers.slice(0, -1).join(', ')} or ${numbers[numbers.length - 1]}`;\n\n const rl = createInterface({ input: stdin, output: stdout });\n const ask = createLineReader(rl, stdout);\n try {\n for (let attempt = 0; attempt < MAX_PROMPT_ATTEMPTS; attempt++) {\n const answer = await ask(query);\n if (answer === null) {\n return 'cancel';\n }\n const choice = answer.trim();\n const picked = sources[Number(choice) - 1];\n if (choice.length > 0 && picked !== undefined) {\n return picked;\n }\n if (choice === String(cancelOption)) {\n return 'cancel';\n }\n warn(`Invalid choice: '${choice}'. Enter ${accepted}.`);\n }\n return 'cancel';\n } finally {\n rl.close();\n }\n}\n\nfunction isInteractiveByDefault(): boolean {\n const ci = process.env.CI;\n const inCi = ci !== undefined && ci !== '' && ci !== '0' && ci.toLowerCase() !== 'false';\n return Boolean(process.stdin.isTTY) && !inCi;\n}\n\nfunction buildResolved(\n issue: Issue,\n source: IssueSource,\n local: Issue | null,\n github: Issue | null,\n divergent: boolean,\n): ResolvedIssue {\n return { issue, source, local, github, divergent };\n}\n\n/** Origin `conflictPolicy` points at, or `null` for 'ask'. */\nfunction policyTarget(policy: IssuesConfig['conflictPolicy']): IssueSource | null {\n if (policy === 'prefer-local') {\n return 'local';\n }\n if (policy === 'prefer-github') {\n return 'github';\n }\n return null;\n}\n\n/**\n * Single entry point every command uses to decide which Issue the pipeline\n * works on.\n *\n * The logic is written against the origins that answered, never against a fixed\n * list of sources: registering a new provider is enough for it to take part in\n * the resolution, be reported in a divergence and appear in the prompt.\n *\n * Scenarios:\n * - only one origin has it -> that one, no questions asked;\n * - several, same contentHash -> equivalence is reported and the preferred\n * origin wins, without a prompt;\n * - several, different content -> the divergence is reported and\n * `conflictPolicy` decides (`ask` prompts on a TTY, falls back to\n * `preferredProvider` with a warning anywhere else);\n * - none -> IssueResolutionError, which carries the CLI exit code.\n */\nexport async function resolveIssue(\n id: string,\n opts: ResolveIssueOptions = {},\n): Promise<ResolvedIssue> {\n const info = opts.info ?? printInfo;\n const warn = opts.warn ?? printWarning;\n const config = opts.config ?? (await loadIssuesConfig({ warn }));\n\n ensureProvidersRegistered();\n const sources = opts.sources ?? getRegisteredSources();\n\n // Each origin is an independent I/O call (network for GitHub, disk for\n // local); querying them concurrently instead of one-by-one keeps the total\n // latency at the slowest origin instead of the sum of all of them, without\n // changing which candidate wins (order is preserved by Promise.all).\n const candidates: Candidate[] = await Promise.all(\n sources.map((source) => fetchCandidate(source, id, warn)),\n );\n\n const issueOf = (source: IssueSource): Issue | null =>\n candidates.find((candidate) => candidate.source === source)?.issue ?? null;\n const local = issueOf('local');\n const github = issueOf('github');\n\n const found = candidates.filter(\n (candidate): candidate is FoundCandidate => candidate.issue !== null,\n );\n\n if (found.length === 0) {\n const details = candidates\n .map((candidate) => `${sourceLabel(candidate.source)}: ${candidate.reason ?? 'not found'}`)\n .join('; ');\n const where = details.length > 0 ? ` (${details})` : '';\n throw new IssueResolutionError(`Issue '${id}' not found in any registered origin${where}`);\n }\n\n const build = (candidate: FoundCandidate, divergent: boolean): ResolvedIssue =>\n buildResolved(candidate.issue, candidate.source, local, github, divergent);\n\n const firstFound = found[0] as FoundCandidate;\n if (found.length === 1) {\n return build(firstFound, false);\n }\n\n // Several origins have it. The preferred one wins whenever it is among them;\n // otherwise the first origin queried does, so an unrelated preference never\n // leaves the pipeline without an Issue.\n const preferred =\n found.find((candidate) => candidate.source === config.preferredProvider) ?? firstFound;\n\n const distinct = new Set(found.map((candidate) => candidate.issue.contentHash));\n if (distinct.size === 1) {\n info(\n `Issue '${id}' has identical content in ${listSources(found)}; using ${sourceLabel(preferred.source)}.`,\n );\n return build(preferred, false);\n }\n\n info(`Issue '${id}' differs between origins:`);\n for (const candidate of found) {\n info(describeCandidate(candidate.source, candidate.issue));\n }\n\n const target = policyTarget(config.conflictPolicy);\n if (target !== null) {\n const chosen = found.find((candidate) => candidate.source === target);\n if (chosen !== undefined) {\n info(`Conflict policy '${config.conflictPolicy}': using the ${sourceLabel(target)} version.`);\n return build(chosen, true);\n }\n // The policy names an origin that has no version of this Issue: say so\n // instead of silently picking for the user under its name.\n warn(\n `Conflict policy '${config.conflictPolicy}' does not apply to Issue '${id}' ` +\n `(${sourceLabel(target)} has no version of it); using ${sourceLabel(preferred.source)}.`,\n );\n return build(preferred, true);\n }\n\n const interactive = opts.interactive ?? isInteractiveByDefault();\n if (!interactive) {\n warn(\n `Divergent Issue '${id}' and conflict policy 'ask' in a non-interactive environment; ` +\n `using the preferred provider (${sourceLabel(preferred.source)}).`,\n );\n return build(preferred, true);\n }\n\n const choice = await promptChoice(\n found.map((candidate) => candidate.source),\n opts.stdin ?? process.stdin,\n opts.stdout ?? process.stdout,\n warn,\n );\n if (choice === 'cancel') {\n throw new IssueResolutionError(\n `Cancelled: Issue '${id}' diverges between ${listSources(found)}.`,\n );\n }\n const picked = found.find((candidate) => candidate.source === choice) as FoundCandidate;\n return build(picked, true);\n}\n","import { printError } from '../ui/logger.js';\nimport { IssueResolutionError, type ResolveIssueOptions, resolveIssue } from './resolver.js';\nimport type { Issue, ResolvedIssue } from './types.js';\n\n/**\n * Bridge between the resolved Issue and the phase prompts.\n *\n * Commands never fetch the Issue themselves: they resolve it once through\n * `resolveIssue` and hand the content to the template, so every phase sees the\n * exact same title/body regardless of where the demand came from.\n */\n\n/** Path of the markdown file a local Issue lives in. */\nexport function localIssueRef(id: string): string {\n return `issues/${id}/issue.md`;\n}\n\n/**\n * Reference a human (or an agent) can follow to read the Issue: the remote URL\n * when there is one, the local file otherwise.\n */\nexport function issueReference(issue: Issue): string {\n return issue.remoteRef ?? localIssueRef(issue.id);\n}\n\n/** Shown instead of an empty list so the prompt never renders a dangling label. */\nconst NO_LABELS = '(none)';\n\n/**\n * Placeholder values every phase template consumes, replacing the former\n * `gh issue view` instruction.\n */\nexport function issuePlaceholders(resolved: ResolvedIssue): Record<string, string> {\n const { issue } = resolved;\n return {\n __ISSUE_TITLE__: issue.title,\n __ISSUE_BODY__: issue.body,\n __ISSUE_LABELS__: issue.labels.length > 0 ? issue.labels.join(', ') : NO_LABELS,\n __ISSUE_SOURCE__: resolved.source,\n __ISSUE_URL__: issueReference(issue),\n };\n}\n\nexport type CommandIssue = { ok: true; resolved: ResolvedIssue } | { ok: false; code: number };\n\n/**\n * Resolve the Issue a command works on, turning a resolution failure into the\n * exit code the command returns.\n *\n * `preResolved` short-circuits the lookup: the pipeline decides the origin once\n * and passes the decision down, so a phase never re-queries the providers (and\n * never asks the user twice about the same divergence).\n *\n * `options` forwards resolver options — `run.ts` passes the configuration it\n * already loaded so `.issue-flow.json` is read (and warned about) only once.\n */\nexport async function resolveCommandIssue(\n id: string,\n preResolved?: ResolvedIssue,\n options?: ResolveIssueOptions,\n): Promise<CommandIssue> {\n if (preResolved !== undefined) {\n return { ok: true, resolved: preResolved };\n }\n\n try {\n return { ok: true, resolved: await resolveIssue(id, options) };\n } catch (err) {\n if (err instanceof IssueResolutionError) {\n printError(err.message);\n return { ok: false, code: err.exitCode };\n }\n const message = err instanceof Error ? err.message : String(err);\n printError(`Could not resolve issue '${id}': ${message}`);\n return { ok: false, code: 1 };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAUA,IAAM,YAAY,oBAAI,IAAgC;AAQ/C,SAAS,iBAAiB,UAA+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,QAAW;AAC1B,UAAM,YAAY,qBAAqB;AACvC,UAAM,OACJ,UAAU,SAAS,IACf,sBAAsB,UAAU,KAAK,IAAI,CAAC,MAC1C;AACN,UAAM,IAAI,MAAM,0BAA0B,MAAM,MAAM,IAAI,EAAE;AAAA,EAC9D;AACA,SAAO;AACT;;;AC5CA,SAAS,kBAAkB;AAY3B,SAAS,cAAc,OAAuB;AAC5C,SAAO,MAAM,QAAQ,UAAU,IAAI,EAAE,KAAK;AAC5C;AAQO,SAAS,iBAAiB,OAAe,MAAsB;AACpE,QAAM,UAAU,KAAK,UAAU;AAAA,IAC7B,OAAO,cAAc,KAAK;AAAA,IAC1B,MAAM,cAAc,IAAI;AAAA,EAC1B,CAAC;AACD,QAAM,SAAS,WAAW,QAAQ,EAAE,OAAO,SAAS,MAAM,EAAE,OAAO,KAAK;AACxE,SAAO,UAAU,MAAM;AACzB;;;ACvBA,IAAM,cAAc;AAGpB,IAAM,mBAAmB;AASzB,IAAM,oBACJ;AAiBF,SAAS,eAAe,OAA4B;AAClD,SAAO,OAAO,SAAS,EAAE,EAAE,YAAY,MAAM,WAAW,WAAW;AACrE;AAEA,SAAS,gBAAgB,QAA2B;AAClD,MAAI,CAAC,MAAM,QAAQ,MAAM,E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AAM,UAAU,MAAM,aAAa,IAAI,OAAO,EAAE;AAAA,EAC/D,SAAS,KAAK;AACZ,QAAI,eAAe,sBAAsB;AACvC,iBAAW,IAAI,OAAO;AACtB,aAAO,EAAE,IAAI,OAAO,MAAM,IAAI,SAAS;AAAA,IACzC;AACA,UAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,eAAW,4BAA4B,EAAE,MAAM,OAAO,EAAE;AACxD,WAAO,EAAE,IAAI,OAAO,MAAM,EAAE;AAAA,EAC9B;AACF;","names":["normalizeId"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/web/lock.ts","../src/web/server.ts"],"sourcesContent":["import { type ChildProcess, spawn as nodeSpawn } from 'node:child_process';\nimport { 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 };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