@luanpdd/kit-mcp 1.35.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.
- package/bin/cli.js +2 -2
- package/bin/mcp.js +6 -6
- package/bin/ui.js +74 -74
- package/gates/ai-prompt-stability.md +120 -120
- package/gates/budget-description.md +68 -68
- package/gates/confidence.md +29 -29
- package/gates/dependency-check.md +33 -33
- package/gates/dept-cycle-prevention.md +179 -179
- package/gates/golden-signals-coverage.md +133 -133
- package/gates/legacy-refactor-safety.md +178 -178
- package/gates/multi-tenant-rls-coverage.md +102 -102
- package/gates/no-personal-uuid.md +72 -72
- package/gates/obs-agents-mcp-supabase.md +86 -86
- package/gates/obs-skills-frontmatter.md +76 -76
- package/gates/observability-coverage.md +151 -151
- package/gates/omm-no-regression.md +83 -83
- package/gates/postmortem-template-required.md +127 -127
- package/gates/prr-checklist-coverage.md +128 -128
- package/gates/regression.md +32 -32
- package/gates/release-pipeline-policy.md +132 -132
- package/gates/secrets-scan.md +33 -33
- package/gates/service-role-not-in-user-facing.md +113 -113
- package/gates/skill-must-include.md +71 -71
- package/gates/sync-idempotent.md +62 -62
- package/gates/verify-phase-goal.md +34 -34
- package/kit/agents/designer-ui.md +216 -216
- package/kit/agents/workflow-generator.md +537 -167
- package/kit/commands/adicionar-backlog.md +1 -1
- package/kit/commands/adicionar-fase.md +1 -1
- package/kit/commands/adicionar-tarefa.md +1 -1
- package/kit/commands/auditar-observabilidade.md +103 -103
- package/kit/commands/auditar-toil.md +129 -129
- package/kit/commands/caracterizar-prompt.md +195 -195
- package/kit/commands/criar-workflow.md +158 -158
- package/kit/commands/definir-perfil.md +1 -1
- package/kit/commands/definir-slo.md +108 -108
- package/kit/commands/fio.md +1 -1
- package/kit/commands/golden-signals.md +142 -142
- package/kit/commands/instrumentar-fase.md +200 -200
- package/kit/commands/investigar-producao.md +162 -162
- package/kit/commands/observabilidade.md +118 -118
- package/kit/commands/postmortem.md +179 -179
- package/kit/commands/prr.md +205 -205
- package/kit/commands/publicar-rapido.md +207 -207
- package/kit/commands/risk-budget.md +220 -220
- package/kit/commands/sre.md +230 -230
- package/kit/file-manifest.json +424 -424
- package/kit/framework/references/output-style.md +22 -22
- package/kit/hooks/post-apply-migration.js +199 -199
- package/kit/hooks/sidecar-tool-publisher.js +210 -210
- package/kit/skills/_shared-dados-distribuidos/glossary.md +224 -224
- package/kit/skills/_shared-legacy/glossary.md +389 -389
- package/kit/skills/_shared-multi-tenant/glossary.md +186 -186
- package/kit/skills/_shared-observability/glossary.md +396 -396
- package/kit/skills/_shared-sre/glossary.md +712 -712
- package/kit/skills/_shared-supabase/glossary.md +234 -234
- package/kit/skills/blameless-postmortems/SKILL.md +340 -340
- package/kit/skills/burn-rate-alerting/SKILL.md +258 -258
- package/kit/skills/cascading-failures/SKILL.md +311 -311
- package/kit/skills/core-analysis-loop/SKILL.md +352 -352
- package/kit/skills/distributed-tracing/SKILL.md +362 -362
- package/kit/skills/dynamic-workflow-authoring/SKILL.md +327 -223
- package/kit/skills/eliminating-toil/SKILL.md +243 -243
- package/kit/skills/event-based-slos/SKILL.md +296 -296
- package/kit/skills/four-golden-signals/SKILL.md +314 -314
- package/kit/skills/hermetic-builds/SKILL.md +323 -323
- package/kit/skills/legacy-monster-methods/SKILL.md +444 -444
- package/kit/skills/llm-as-dependency/SKILL.md +436 -436
- package/kit/skills/load-shedding-graceful-degradation/SKILL.md +396 -396
- package/kit/skills/observability-driven-development/SKILL.md +315 -315
- package/kit/skills/observability-maturity-model/SKILL.md +222 -222
- package/kit/skills/opentelemetry-standard/SKILL.md +351 -351
- package/kit/skills/production-readiness-review/SKILL.md +305 -305
- package/kit/skills/release-engineering/SKILL.md +367 -367
- package/kit/skills/retry-strategies/SKILL.md +372 -372
- package/kit/skills/sre-risk-management/SKILL.md +221 -221
- package/kit/skills/structured-events/SKILL.md +265 -265
- package/kit/skills/supabase-cron-queues/SKILL.md +275 -275
- package/kit/skills/supabase-database-functions/SKILL.md +332 -332
- package/kit/skills/supabase-declarative-schema/SKILL.md +183 -183
- package/kit/skills/supabase-pgvector-rag/SKILL.md +253 -253
- package/kit/skills/supabase-postgres-style/SKILL.md +138 -138
- package/kit/skills/supabase-storage/SKILL.md +234 -234
- package/kit/skills/telemetry-pipelines/SKILL.md +259 -259
- package/kit/skills/telemetry-sampling/SKILL.md +256 -256
- package/kit/skills/ui-anti-padroes-ia/SKILL.md +261 -261
- package/kit/skills/ui-contexto-produto/SKILL.md +248 -248
- package/kit/skills/ui-cor-estrategia/SKILL.md +213 -213
- package/kit/skills/ui-critica-auditoria/SKILL.md +260 -260
- package/kit/skills/ui-motion-funcional/SKILL.md +264 -264
- package/kit/skills/ui-ritmo-espacial/SKILL.md +259 -259
- package/kit/skills/ui-tipografia/SKILL.md +211 -211
- package/package.json +1 -1
- package/src/cli/index.js +1114 -1114
- package/src/cli/render.js +194 -194
- package/src/cli/upgrade-check.js +135 -135
- package/src/core/error-redaction.js +76 -76
- package/src/core/failures.js +153 -153
- package/src/core/gate-runner.js +205 -205
- package/src/core/gates.js +82 -82
- package/src/core/logger.js +170 -170
- package/src/core/manifest-verify.js +174 -174
- package/src/core/metrics.js +268 -268
- package/src/core/notify.js +60 -60
- package/src/core/path-safety.js +141 -141
- package/src/core/replays.js +120 -120
- package/src/core/ui.js +185 -185
- package/src/mcp-server/install.js +149 -149
- package/src/mcp-server/roots.js +124 -124
- package/src/ui/auto-spawn.js +113 -113
- package/src/ui/browser.js +78 -78
- package/src/ui/client.js +130 -130
- package/src/ui/events.js +65 -65
- package/src/ui/lockfile.js +191 -191
- package/src/ui/port.js +67 -67
- package/src/ui/server.js +547 -547
- package/src/ui/wrapper.js +129 -129
package/src/ui/lockfile.js
CHANGED
|
@@ -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
|
+
}
|