@luanpdd/kit-mcp 1.34.0 → 1.36.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 (118) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.js +2 -2
  3. package/bin/mcp.js +6 -6
  4. package/bin/ui.js +74 -74
  5. package/gates/ai-prompt-stability.md +120 -120
  6. package/gates/budget-description.md +68 -68
  7. package/gates/confidence.md +29 -29
  8. package/gates/dependency-check.md +33 -33
  9. package/gates/dept-cycle-prevention.md +179 -179
  10. package/gates/golden-signals-coverage.md +133 -133
  11. package/gates/legacy-refactor-safety.md +178 -178
  12. package/gates/multi-tenant-rls-coverage.md +102 -102
  13. package/gates/no-personal-uuid.md +72 -72
  14. package/gates/obs-agents-mcp-supabase.md +86 -86
  15. package/gates/obs-skills-frontmatter.md +76 -76
  16. package/gates/observability-coverage.md +151 -151
  17. package/gates/omm-no-regression.md +83 -83
  18. package/gates/postmortem-template-required.md +127 -127
  19. package/gates/prr-checklist-coverage.md +128 -128
  20. package/gates/regression.md +32 -32
  21. package/gates/release-pipeline-policy.md +132 -132
  22. package/gates/secrets-scan.md +33 -33
  23. package/gates/service-role-not-in-user-facing.md +113 -113
  24. package/gates/skill-must-include.md +71 -71
  25. package/gates/sync-idempotent.md +62 -62
  26. package/gates/verify-phase-goal.md +34 -34
  27. package/kit/agents/designer-ui.md +216 -216
  28. package/kit/agents/workflow-generator.md +537 -0
  29. package/kit/commands/adicionar-backlog.md +1 -1
  30. package/kit/commands/adicionar-fase.md +1 -1
  31. package/kit/commands/adicionar-tarefa.md +1 -1
  32. package/kit/commands/auditar-observabilidade.md +103 -103
  33. package/kit/commands/auditar-toil.md +129 -129
  34. package/kit/commands/caracterizar-prompt.md +195 -195
  35. package/kit/commands/criar-workflow.md +158 -0
  36. package/kit/commands/definir-perfil.md +1 -1
  37. package/kit/commands/definir-slo.md +108 -108
  38. package/kit/commands/fio.md +1 -1
  39. package/kit/commands/golden-signals.md +142 -142
  40. package/kit/commands/instrumentar-fase.md +200 -200
  41. package/kit/commands/investigar-producao.md +162 -162
  42. package/kit/commands/observabilidade.md +118 -118
  43. package/kit/commands/postmortem.md +179 -179
  44. package/kit/commands/prr.md +205 -205
  45. package/kit/commands/publicar-rapido.md +207 -207
  46. package/kit/commands/risk-budget.md +220 -220
  47. package/kit/commands/sre.md +230 -230
  48. package/kit/file-manifest.json +5 -2
  49. package/kit/framework/references/output-style.md +22 -22
  50. package/kit/hooks/post-apply-migration.js +199 -199
  51. package/kit/hooks/sidecar-tool-publisher.js +210 -210
  52. package/kit/skills/_shared-dados-distribuidos/glossary.md +224 -224
  53. package/kit/skills/_shared-legacy/glossary.md +389 -389
  54. package/kit/skills/_shared-multi-tenant/glossary.md +186 -186
  55. package/kit/skills/_shared-observability/glossary.md +396 -396
  56. package/kit/skills/_shared-sre/glossary.md +712 -712
  57. package/kit/skills/_shared-supabase/glossary.md +234 -234
  58. package/kit/skills/blameless-postmortems/SKILL.md +340 -340
  59. package/kit/skills/burn-rate-alerting/SKILL.md +258 -258
  60. package/kit/skills/cascading-failures/SKILL.md +311 -311
  61. package/kit/skills/core-analysis-loop/SKILL.md +352 -352
  62. package/kit/skills/distributed-tracing/SKILL.md +362 -362
  63. package/kit/skills/dynamic-workflow-authoring/SKILL.md +327 -0
  64. package/kit/skills/eliminating-toil/SKILL.md +243 -243
  65. package/kit/skills/event-based-slos/SKILL.md +296 -296
  66. package/kit/skills/four-golden-signals/SKILL.md +314 -314
  67. package/kit/skills/hermetic-builds/SKILL.md +323 -323
  68. package/kit/skills/legacy-monster-methods/SKILL.md +444 -444
  69. package/kit/skills/llm-as-dependency/SKILL.md +436 -436
  70. package/kit/skills/load-shedding-graceful-degradation/SKILL.md +396 -396
  71. package/kit/skills/observability-driven-development/SKILL.md +315 -315
  72. package/kit/skills/observability-maturity-model/SKILL.md +222 -222
  73. package/kit/skills/opentelemetry-standard/SKILL.md +351 -351
  74. package/kit/skills/production-readiness-review/SKILL.md +305 -305
  75. package/kit/skills/release-engineering/SKILL.md +367 -367
  76. package/kit/skills/retry-strategies/SKILL.md +372 -372
  77. package/kit/skills/sre-risk-management/SKILL.md +221 -221
  78. package/kit/skills/structured-events/SKILL.md +265 -265
  79. package/kit/skills/supabase-cron-queues/SKILL.md +275 -275
  80. package/kit/skills/supabase-database-functions/SKILL.md +332 -332
  81. package/kit/skills/supabase-declarative-schema/SKILL.md +183 -183
  82. package/kit/skills/supabase-pgvector-rag/SKILL.md +253 -253
  83. package/kit/skills/supabase-postgres-style/SKILL.md +138 -138
  84. package/kit/skills/supabase-storage/SKILL.md +234 -234
  85. package/kit/skills/telemetry-pipelines/SKILL.md +259 -259
  86. package/kit/skills/telemetry-sampling/SKILL.md +256 -256
  87. package/kit/skills/ui-anti-padroes-ia/SKILL.md +261 -261
  88. package/kit/skills/ui-contexto-produto/SKILL.md +248 -248
  89. package/kit/skills/ui-cor-estrategia/SKILL.md +213 -213
  90. package/kit/skills/ui-critica-auditoria/SKILL.md +260 -260
  91. package/kit/skills/ui-motion-funcional/SKILL.md +264 -264
  92. package/kit/skills/ui-ritmo-espacial/SKILL.md +259 -259
  93. package/kit/skills/ui-tipografia/SKILL.md +211 -211
  94. package/package.json +1 -1
  95. package/src/cli/index.js +1114 -1114
  96. package/src/cli/render.js +194 -194
  97. package/src/cli/upgrade-check.js +135 -135
  98. package/src/core/error-redaction.js +76 -76
  99. package/src/core/failures.js +153 -153
  100. package/src/core/gate-runner.js +205 -205
  101. package/src/core/gates.js +82 -82
  102. package/src/core/logger.js +170 -170
  103. package/src/core/manifest-verify.js +174 -174
  104. package/src/core/metrics.js +268 -268
  105. package/src/core/notify.js +60 -60
  106. package/src/core/path-safety.js +141 -141
  107. package/src/core/replays.js +120 -120
  108. package/src/core/ui.js +185 -185
  109. package/src/mcp-server/install.js +149 -149
  110. package/src/mcp-server/roots.js +124 -124
  111. package/src/ui/auto-spawn.js +113 -113
  112. package/src/ui/browser.js +78 -78
  113. package/src/ui/client.js +130 -130
  114. package/src/ui/events.js +65 -65
  115. package/src/ui/lockfile.js +191 -191
  116. package/src/ui/port.js +67 -67
  117. package/src/ui/server.js +547 -547
  118. package/src/ui/wrapper.js +129 -129
@@ -1,191 +1,191 @@
1
- // src/ui/lockfile.js
2
- // Single-instance lockfile per projectRoot, located in os.tmpdir().
3
- //
4
- // Atomic create via fs.openSync(path, 'wx') (O_EXCL semantics — fails if file exists).
5
- // Stale detection in two layers:
6
- // 1. process.kill(pid, 0) — ESRCH/EPERM means the holder is gone
7
- // 2. optional HTTP healthz probe (injected by caller; keeps this module pure of net)
8
-
9
- import { createHash, randomBytes } from 'node:crypto';
10
- import fs from 'node:fs';
11
- import os from 'node:os';
12
- import path from 'node:path';
13
- import process from 'node:process';
14
-
15
- export const LOCK_VERSION = 1;
16
-
17
- export function lockPathFor(projectRoot) {
18
- if (typeof projectRoot !== 'string' || projectRoot.length === 0) {
19
- throw new TypeError('projectRoot must be a non-empty string');
20
- }
21
- const hash = createHash('sha1').update(projectRoot).digest('hex').slice(0, 16);
22
- return path.join(os.tmpdir(), `kit-mcp-ui-${hash}.lock`);
23
- }
24
-
25
- // readLock returns parsed lockfile content, or null if the file doesn't exist
26
- // or is unreadable/unparseable. Never throws.
27
- export function readLock(projectRoot) {
28
- const file = lockPathFor(projectRoot);
29
- let raw;
30
- try {
31
- raw = fs.readFileSync(file, 'utf8');
32
- } catch (err) {
33
- if (err.code === 'ENOENT') return null;
34
- return null;
35
- }
36
- try {
37
- const parsed = JSON.parse(raw);
38
- if (parsed && typeof parsed === 'object' && typeof parsed.pid === 'number') {
39
- return { ...parsed, _path: file };
40
- }
41
- return null;
42
- } catch {
43
- return null;
44
- }
45
- }
46
-
47
- // acquireLock attempts to create the lockfile atomically. On success returns
48
- // the lock metadata. On EEXIST, throws an Error tagged with .code = 'ELOCKED'
49
- // — the caller is expected to call probeStale + maybe retry.
50
- export function acquireLock({ projectRoot, port, version, startedAt }) {
51
- const file = lockPathFor(projectRoot);
52
- const meta = {
53
- pid: process.pid,
54
- port,
55
- version: version ?? null,
56
- startedAt: startedAt ?? Date.now(),
57
- lockSchema: LOCK_VERSION,
58
- // SEC-14-02: per-process auth token. 32 random bytes hex-encoded = 64 chars.
59
- // Required by /publish, /shutdown, /events, /state. Lifetime = process lifetime;
60
- // not logged, not telemetered. See docs/sidecar-security.md.
61
- token: randomBytes(32).toString('hex'),
62
- };
63
- let fd;
64
- try {
65
- fd = fs.openSync(file, 'wx');
66
- } catch (err) {
67
- if (err.code === 'EEXIST') {
68
- const lockErr = new Error(`Lockfile already exists: ${file}`);
69
- lockErr.code = 'ELOCKED';
70
- lockErr.path = file;
71
- throw lockErr;
72
- }
73
- throw err;
74
- }
75
- try {
76
- fs.writeSync(fd, JSON.stringify(meta, null, 2));
77
- } finally {
78
- fs.closeSync(fd);
79
- }
80
- return { ...meta, _path: file };
81
- }
82
-
83
- export function releaseLock(projectRoot) {
84
- const file = lockPathFor(projectRoot);
85
- try {
86
- fs.unlinkSync(file);
87
- return true;
88
- } catch (err) {
89
- if (err.code === 'ENOENT') return false;
90
- throw err;
91
- }
92
- }
93
-
94
- // probeStale checks if the lockfile holder is still alive.
95
- // Uses two strategies in order:
96
- // 1. process.kill(pid, 0) — synchronous, no network. ESRCH = dead, EPERM = different user (rare on dev box, treat as alive to be safe).
97
- // 2. healthzProbe(port) — optional async function injected by caller. Should return truthy if the holder responds OK.
98
- //
99
- // Returns:
100
- // { stale: false, reason: 'pid_alive' } — process exists
101
- // { stale: false, reason: 'healthz_ok' } — process exists AND healthz responded
102
- // { stale: true, reason: 'pid_gone' } — pid is ESRCH
103
- // { stale: true, reason: 'healthz_failed' } — pid alive but no healthz response (used when healthzProbe provided)
104
- // PERF-04: budget for healthz probe inside acquireLockOrReclaim. A misbehaving
105
- // sidecar that accepts the connection but never responds shouldn't block startup
106
- // of a fresh sidecar — we treat slow-as-dead and reclaim.
107
- const HEALTHZ_PROBE_TIMEOUT_MS = 500;
108
-
109
- function withTimeout(promise, ms, fallback) {
110
- return new Promise((resolve) => {
111
- let settled = false;
112
- const timer = setTimeout(() => {
113
- if (!settled) { settled = true; resolve(fallback); }
114
- }, ms);
115
- if (typeof timer.unref === 'function') timer.unref();
116
- Promise.resolve(promise).then(
117
- (v) => { if (!settled) { settled = true; clearTimeout(timer); resolve(v); } },
118
- () => { if (!settled) { settled = true; clearTimeout(timer); resolve(fallback); } },
119
- );
120
- });
121
- }
122
-
123
- export async function probeStale(lock, { healthzProbe, probeTimeoutMs } = {}) {
124
- if (!lock || typeof lock.pid !== 'number') {
125
- return { stale: true, reason: 'invalid_lock' };
126
- }
127
- let pidAlive = false;
128
- try {
129
- process.kill(lock.pid, 0);
130
- pidAlive = true;
131
- } catch (err) {
132
- if (err.code === 'ESRCH') {
133
- return { stale: true, reason: 'pid_gone' };
134
- }
135
- // EPERM: pid exists but is owned by another user. Treat as alive (safe default).
136
- pidAlive = true;
137
- }
138
- if (!healthzProbe) {
139
- return { stale: false, reason: 'pid_alive' };
140
- }
141
- // PERF-04: bound the probe so a hung sidecar can't stall startup forever.
142
- const ms = probeTimeoutMs ?? HEALTHZ_PROBE_TIMEOUT_MS;
143
- const ok = await withTimeout(healthzProbe(lock.port), ms, false);
144
- if (ok) return { stale: false, reason: 'healthz_ok' };
145
- return { stale: true, reason: 'healthz_failed' };
146
- }
147
-
148
- // Convenience: take + retry once if stale lock is detected.
149
- // SEC-01: re-prove staleness after releaseLock and before the retry acquire to
150
- // close the TOCTOU window where a competing process could have raced into the
151
- // lockfile between our probe and our retry.
152
- export async function acquireLockOrReclaim(opts) {
153
- try {
154
- return acquireLock(opts);
155
- } catch (err) {
156
- if (err.code !== 'ELOCKED') throw err;
157
- const existing = readLock(opts.projectRoot);
158
- const probe = await probeStale(existing, { healthzProbe: opts.healthzProbe, probeTimeoutMs: opts.probeTimeoutMs });
159
- if (probe.stale) {
160
- releaseLock(opts.projectRoot);
161
- // SEC-01: second prove. If something raced into the lock between our
162
- // releaseLock and our retry-acquire, surface ELIVE instead of clobbering.
163
- try {
164
- return acquireLock(opts);
165
- } catch (retryErr) {
166
- if (retryErr.code !== 'ELOCKED') throw retryErr;
167
- const racer = readLock(opts.projectRoot);
168
- const racerProbe = await probeStale(racer, { healthzProbe: opts.healthzProbe, probeTimeoutMs: opts.probeTimeoutMs });
169
- if (racerProbe.stale) {
170
- // Genuinely dead again — third try. If THIS fails too, give up.
171
- releaseLock(opts.projectRoot);
172
- return acquireLock(opts);
173
- }
174
- const liveErr = new Error(
175
- `Sidecar reclaimed by another process during retry (pid=${racer?.pid}, port=${racer?.port}). ` +
176
- `Use \`kit ui status\` to inspect.`,
177
- );
178
- liveErr.code = 'ELIVE';
179
- liveErr.lock = racer;
180
- throw liveErr;
181
- }
182
- }
183
- const liveErr = new Error(
184
- `Sidecar already running for this project (pid=${existing?.pid}, port=${existing?.port}). ` +
185
- `Use \`kit ui status\` to inspect or \`kit ui stop\` to shut it down.`,
186
- );
187
- liveErr.code = 'ELIVE';
188
- liveErr.lock = existing;
189
- throw liveErr;
190
- }
191
- }
1
+ // src/ui/lockfile.js
2
+ // Single-instance lockfile per projectRoot, located in os.tmpdir().
3
+ //
4
+ // Atomic create via fs.openSync(path, 'wx') (O_EXCL semantics — fails if file exists).
5
+ // Stale detection in two layers:
6
+ // 1. process.kill(pid, 0) — ESRCH/EPERM means the holder is gone
7
+ // 2. optional HTTP healthz probe (injected by caller; keeps this module pure of net)
8
+
9
+ import { createHash, randomBytes } from 'node:crypto';
10
+ import fs from 'node:fs';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import process from 'node:process';
14
+
15
+ export const LOCK_VERSION = 1;
16
+
17
+ export function lockPathFor(projectRoot) {
18
+ if (typeof projectRoot !== 'string' || projectRoot.length === 0) {
19
+ throw new TypeError('projectRoot must be a non-empty string');
20
+ }
21
+ const hash = createHash('sha1').update(projectRoot).digest('hex').slice(0, 16);
22
+ return path.join(os.tmpdir(), `kit-mcp-ui-${hash}.lock`);
23
+ }
24
+
25
+ // readLock returns parsed lockfile content, or null if the file doesn't exist
26
+ // or is unreadable/unparseable. Never throws.
27
+ export function readLock(projectRoot) {
28
+ const file = lockPathFor(projectRoot);
29
+ let raw;
30
+ try {
31
+ raw = fs.readFileSync(file, 'utf8');
32
+ } catch (err) {
33
+ if (err.code === 'ENOENT') return null;
34
+ return null;
35
+ }
36
+ try {
37
+ const parsed = JSON.parse(raw);
38
+ if (parsed && typeof parsed === 'object' && typeof parsed.pid === 'number') {
39
+ return { ...parsed, _path: file };
40
+ }
41
+ return null;
42
+ } catch {
43
+ return null;
44
+ }
45
+ }
46
+
47
+ // acquireLock attempts to create the lockfile atomically. On success returns
48
+ // the lock metadata. On EEXIST, throws an Error tagged with .code = 'ELOCKED'
49
+ // — the caller is expected to call probeStale + maybe retry.
50
+ export function acquireLock({ projectRoot, port, version, startedAt }) {
51
+ const file = lockPathFor(projectRoot);
52
+ const meta = {
53
+ pid: process.pid,
54
+ port,
55
+ version: version ?? null,
56
+ startedAt: startedAt ?? Date.now(),
57
+ lockSchema: LOCK_VERSION,
58
+ // SEC-14-02: per-process auth token. 32 random bytes hex-encoded = 64 chars.
59
+ // Required by /publish, /shutdown, /events, /state. Lifetime = process lifetime;
60
+ // not logged, not telemetered. See docs/sidecar-security.md.
61
+ token: randomBytes(32).toString('hex'),
62
+ };
63
+ let fd;
64
+ try {
65
+ fd = fs.openSync(file, 'wx');
66
+ } catch (err) {
67
+ if (err.code === 'EEXIST') {
68
+ const lockErr = new Error(`Lockfile already exists: ${file}`);
69
+ lockErr.code = 'ELOCKED';
70
+ lockErr.path = file;
71
+ throw lockErr;
72
+ }
73
+ throw err;
74
+ }
75
+ try {
76
+ fs.writeSync(fd, JSON.stringify(meta, null, 2));
77
+ } finally {
78
+ fs.closeSync(fd);
79
+ }
80
+ return { ...meta, _path: file };
81
+ }
82
+
83
+ export function releaseLock(projectRoot) {
84
+ const file = lockPathFor(projectRoot);
85
+ try {
86
+ fs.unlinkSync(file);
87
+ return true;
88
+ } catch (err) {
89
+ if (err.code === 'ENOENT') return false;
90
+ throw err;
91
+ }
92
+ }
93
+
94
+ // probeStale checks if the lockfile holder is still alive.
95
+ // Uses two strategies in order:
96
+ // 1. process.kill(pid, 0) — synchronous, no network. ESRCH = dead, EPERM = different user (rare on dev box, treat as alive to be safe).
97
+ // 2. healthzProbe(port) — optional async function injected by caller. Should return truthy if the holder responds OK.
98
+ //
99
+ // Returns:
100
+ // { stale: false, reason: 'pid_alive' } — process exists
101
+ // { stale: false, reason: 'healthz_ok' } — process exists AND healthz responded
102
+ // { stale: true, reason: 'pid_gone' } — pid is ESRCH
103
+ // { stale: true, reason: 'healthz_failed' } — pid alive but no healthz response (used when healthzProbe provided)
104
+ // PERF-04: budget for healthz probe inside acquireLockOrReclaim. A misbehaving
105
+ // sidecar that accepts the connection but never responds shouldn't block startup
106
+ // of a fresh sidecar — we treat slow-as-dead and reclaim.
107
+ const HEALTHZ_PROBE_TIMEOUT_MS = 500;
108
+
109
+ function withTimeout(promise, ms, fallback) {
110
+ return new Promise((resolve) => {
111
+ let settled = false;
112
+ const timer = setTimeout(() => {
113
+ if (!settled) { settled = true; resolve(fallback); }
114
+ }, ms);
115
+ if (typeof timer.unref === 'function') timer.unref();
116
+ Promise.resolve(promise).then(
117
+ (v) => { if (!settled) { settled = true; clearTimeout(timer); resolve(v); } },
118
+ () => { if (!settled) { settled = true; clearTimeout(timer); resolve(fallback); } },
119
+ );
120
+ });
121
+ }
122
+
123
+ export async function probeStale(lock, { healthzProbe, probeTimeoutMs } = {}) {
124
+ if (!lock || typeof lock.pid !== 'number') {
125
+ return { stale: true, reason: 'invalid_lock' };
126
+ }
127
+ let pidAlive = false;
128
+ try {
129
+ process.kill(lock.pid, 0);
130
+ pidAlive = true;
131
+ } catch (err) {
132
+ if (err.code === 'ESRCH') {
133
+ return { stale: true, reason: 'pid_gone' };
134
+ }
135
+ // EPERM: pid exists but is owned by another user. Treat as alive (safe default).
136
+ pidAlive = true;
137
+ }
138
+ if (!healthzProbe) {
139
+ return { stale: false, reason: 'pid_alive' };
140
+ }
141
+ // PERF-04: bound the probe so a hung sidecar can't stall startup forever.
142
+ const ms = probeTimeoutMs ?? HEALTHZ_PROBE_TIMEOUT_MS;
143
+ const ok = await withTimeout(healthzProbe(lock.port), ms, false);
144
+ if (ok) return { stale: false, reason: 'healthz_ok' };
145
+ return { stale: true, reason: 'healthz_failed' };
146
+ }
147
+
148
+ // Convenience: take + retry once if stale lock is detected.
149
+ // SEC-01: re-prove staleness after releaseLock and before the retry acquire to
150
+ // close the TOCTOU window where a competing process could have raced into the
151
+ // lockfile between our probe and our retry.
152
+ export async function acquireLockOrReclaim(opts) {
153
+ try {
154
+ return acquireLock(opts);
155
+ } catch (err) {
156
+ if (err.code !== 'ELOCKED') throw err;
157
+ const existing = readLock(opts.projectRoot);
158
+ const probe = await probeStale(existing, { healthzProbe: opts.healthzProbe, probeTimeoutMs: opts.probeTimeoutMs });
159
+ if (probe.stale) {
160
+ releaseLock(opts.projectRoot);
161
+ // SEC-01: second prove. If something raced into the lock between our
162
+ // releaseLock and our retry-acquire, surface ELIVE instead of clobbering.
163
+ try {
164
+ return acquireLock(opts);
165
+ } catch (retryErr) {
166
+ if (retryErr.code !== 'ELOCKED') throw retryErr;
167
+ const racer = readLock(opts.projectRoot);
168
+ const racerProbe = await probeStale(racer, { healthzProbe: opts.healthzProbe, probeTimeoutMs: opts.probeTimeoutMs });
169
+ if (racerProbe.stale) {
170
+ // Genuinely dead again — third try. If THIS fails too, give up.
171
+ releaseLock(opts.projectRoot);
172
+ return acquireLock(opts);
173
+ }
174
+ const liveErr = new Error(
175
+ `Sidecar reclaimed by another process during retry (pid=${racer?.pid}, port=${racer?.port}). ` +
176
+ `Use \`kit ui status\` to inspect.`,
177
+ );
178
+ liveErr.code = 'ELIVE';
179
+ liveErr.lock = racer;
180
+ throw liveErr;
181
+ }
182
+ }
183
+ const liveErr = new Error(
184
+ `Sidecar already running for this project (pid=${existing?.pid}, port=${existing?.port}). ` +
185
+ `Use \`kit ui status\` to inspect or \`kit ui stop\` to shut it down.`,
186
+ );
187
+ liveErr.code = 'ELIVE';
188
+ liveErr.lock = existing;
189
+ throw liveErr;
190
+ }
191
+ }
package/src/ui/port.js CHANGED
@@ -1,67 +1,67 @@
1
- // src/ui/port.js
2
- // Find a free TCP port within a bounded range.
3
- // Pure utility: no module-level state, no logging.
4
-
5
- import net from 'node:net';
6
-
7
- export const DEFAULT_PORT_RANGE = Object.freeze({ start: 7100, end: 7199 });
8
-
9
- // Probes a single port: resolves to true if free (could bind+close), false if taken.
10
- function probePort(port, host) {
11
- return new Promise((resolve) => {
12
- const server = net.createServer();
13
- let settled = false;
14
- const finish = (free) => {
15
- if (settled) return;
16
- settled = true;
17
- server.removeAllListeners();
18
- try { server.close(); } catch { /* ignore */ }
19
- resolve(free);
20
- };
21
- server.once('error', () => finish(false));
22
- server.once('listening', () => finish(true));
23
- try {
24
- server.listen(port, host);
25
- } catch {
26
- finish(false);
27
- }
28
- });
29
- }
30
-
31
- // findFreePort scans [start..end] inclusive on host (default 127.0.0.1) and
32
- // returns the first port where a transient bind succeeds. Returns null if none.
33
- //
34
- // Race note: between probe-close and the caller's bind, the port can be
35
- // reclaimed by another process. The lockfile + healthz probe in upper layers
36
- // covers this — port.js is best-effort discovery, not exclusive reservation.
37
- export async function findFreePort({
38
- start = DEFAULT_PORT_RANGE.start,
39
- end = DEFAULT_PORT_RANGE.end,
40
- host = '127.0.0.1',
41
- } = {}) {
42
- if (!Number.isInteger(start) || !Number.isInteger(end) || start > end) {
43
- throw new TypeError(`invalid port range: ${start}..${end}`);
44
- }
45
- for (let port = start; port <= end; port += 1) {
46
- // eslint-disable-next-line no-await-in-loop
47
- if (await probePort(port, host)) {
48
- return port;
49
- }
50
- }
51
- return null;
52
- }
53
-
54
- // findFreePortOrThrow is the eager variant — surfaces an error message that
55
- // includes the exhausted range, so callers don't have to format it.
56
- export async function findFreePortOrThrow(opts = {}) {
57
- const port = await findFreePort(opts);
58
- if (port === null) {
59
- const start = opts.start ?? DEFAULT_PORT_RANGE.start;
60
- const end = opts.end ?? DEFAULT_PORT_RANGE.end;
61
- throw new Error(
62
- `No free TCP port in ${start}..${end} (host ${opts.host ?? '127.0.0.1'}). ` +
63
- `Run \`kit ui status\` to inspect a running sidecar, or kill whatever is using these ports.`,
64
- );
65
- }
66
- return port;
67
- }
1
+ // src/ui/port.js
2
+ // Find a free TCP port within a bounded range.
3
+ // Pure utility: no module-level state, no logging.
4
+
5
+ import net from 'node:net';
6
+
7
+ export const DEFAULT_PORT_RANGE = Object.freeze({ start: 7100, end: 7199 });
8
+
9
+ // Probes a single port: resolves to true if free (could bind+close), false if taken.
10
+ function probePort(port, host) {
11
+ return new Promise((resolve) => {
12
+ const server = net.createServer();
13
+ let settled = false;
14
+ const finish = (free) => {
15
+ if (settled) return;
16
+ settled = true;
17
+ server.removeAllListeners();
18
+ try { server.close(); } catch { /* ignore */ }
19
+ resolve(free);
20
+ };
21
+ server.once('error', () => finish(false));
22
+ server.once('listening', () => finish(true));
23
+ try {
24
+ server.listen(port, host);
25
+ } catch {
26
+ finish(false);
27
+ }
28
+ });
29
+ }
30
+
31
+ // findFreePort scans [start..end] inclusive on host (default 127.0.0.1) and
32
+ // returns the first port where a transient bind succeeds. Returns null if none.
33
+ //
34
+ // Race note: between probe-close and the caller's bind, the port can be
35
+ // reclaimed by another process. The lockfile + healthz probe in upper layers
36
+ // covers this — port.js is best-effort discovery, not exclusive reservation.
37
+ export async function findFreePort({
38
+ start = DEFAULT_PORT_RANGE.start,
39
+ end = DEFAULT_PORT_RANGE.end,
40
+ host = '127.0.0.1',
41
+ } = {}) {
42
+ if (!Number.isInteger(start) || !Number.isInteger(end) || start > end) {
43
+ throw new TypeError(`invalid port range: ${start}..${end}`);
44
+ }
45
+ for (let port = start; port <= end; port += 1) {
46
+ // eslint-disable-next-line no-await-in-loop
47
+ if (await probePort(port, host)) {
48
+ return port;
49
+ }
50
+ }
51
+ return null;
52
+ }
53
+
54
+ // findFreePortOrThrow is the eager variant — surfaces an error message that
55
+ // includes the exhausted range, so callers don't have to format it.
56
+ export async function findFreePortOrThrow(opts = {}) {
57
+ const port = await findFreePort(opts);
58
+ if (port === null) {
59
+ const start = opts.start ?? DEFAULT_PORT_RANGE.start;
60
+ const end = opts.end ?? DEFAULT_PORT_RANGE.end;
61
+ throw new Error(
62
+ `No free TCP port in ${start}..${end} (host ${opts.host ?? '127.0.0.1'}). ` +
63
+ `Run \`kit ui status\` to inspect a running sidecar, or kill whatever is using these ports.`,
64
+ );
65
+ }
66
+ return port;
67
+ }