@aiwayds/dsh-opentui 0.9.2 → 0.9.4

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.
@@ -1,39 +1,59 @@
1
1
  // Idle-exit reaper (ADR-0005 decision 5, entry-side companion of
2
2
  // lifecycle.ts): the lifecycle's idle-exit timer is unref()ed — a
3
3
  // refcount-0 manager must stay free to exit — so a cleanly quitting TUI
4
- // cannot deliver "the host exits after idleExitSec of idleness" with an
5
- // in-process timer. The quitting client spawns this script DETACHED
6
- // instead (spawnIdleReaper in src/client-entry.tsx):
4
+ // cannot deliver "the host exits after DSH_OPENTUI_HOST_IDLE_MS of
5
+ // idleness" with an in-process timer. The quitting client spawns this
6
+ // script DETACHED instead (spawnIdleReaper in src/client/boot-shared.ts):
7
7
  //
8
- // bun idle-reaper.mjs <pid> <port> <lockfilePath> <graceSec>
8
+ // node idle-reaper.mjs <pid> <port> <lockfilePath> <idleMs>
9
+ //
10
+ // It owns the idle window after the last client disconnected. During the
11
+ // window it polls the port and the lockfile; a client coming back CANCELS
12
+ // the timer (exit 0, the host stays — that client's own quit arms the next
13
+ // reaper). It never touches a host it does not own:
14
+ //
15
+ // - the lockfile now describes a DIFFERENT pid (a fresh boot — or
16
+ // lifecycle's `booting` placeholder, pid = the booting client — replaced
17
+ // the host): exit without killing;
18
+ // - the lockfile GENERATION moved since the window started (lifecycle's
19
+ // adoptHost bumps startedAt/mtime): a client adopted the host and may
20
+ // still be minting its cookie (up to ~15s) before its first ESTABLISHED
21
+ // connection — spare it;
22
+ // - an ESTABLISHED TCP connection to the host port (the adoption path's
23
+ // liveness marker): a client re-attached, spare it;
24
+ // - the lockfile cannot be read: never kill what we cannot verify.
25
+ //
26
+ // After the window with none of the above, it appends one line to
27
+ // `<dshHome>/opentui-host.idle.log`
28
+ // <iso> reason=idle idleMs=<n> lastClientAt=<iso> host=<pid> port=<n>
29
+ // then SIGTERMs the host, escalates to SIGKILL after 2s, and clears the
30
+ // lockfile only while it still describes this host.
9
31
  //
10
- // After the grace window it shuts the host down — unless:
11
- // - the lockfile now describes a DIFFERENT pid (a fresh boot — or lifecycle's
12
- // `booting` placeholder, pid = the booting client — replaced the host):
13
- // never touch what we do not own;
14
- // - the lockfile was touched RECENTLY (lifecycle adoptHost bumps
15
- // startedAt/mtime on adoption): a client that adopted at the grace edge
16
- // can still be minting its cookie (up to ~15s) before it opens its first
17
- // ESTABLISHED connection, so a fresh lockfile touch counts as alive;
18
- // - a client re-attached inside the grace window (established TCP
19
- // connections to the host port — the adoption path keeps the host alive
20
- // under its new owner; that owner's own quit spawns the next reaper).
21
32
  // The probe is `lsof -sTCP:ESTABLISHED`; when the tool is unavailable the
22
33
  // reaper falls back to the plain lifecycle semantics (idle exit).
23
- import { readFileSync, rmSync, statSync } from 'node:fs'
34
+ //
35
+ // Idempotent and leak-free: no sockets are opened (lsof is a child
36
+ // process), the process exits by itself, and a replacement host's lock is
37
+ // never removed.
38
+ import { appendFileSync, readFileSync, rmSync, statSync } from 'node:fs'
24
39
  import { spawnSync } from 'node:child_process'
40
+ import { dirname, join } from 'node:path'
25
41
 
26
- const [pidArg, portArg, lockPath, graceArg] = process.argv.slice(2)
42
+ const [pidArg, portArg, lockPath, idleMsArg] = process.argv.slice(2)
27
43
  const pid = Number(pidArg)
28
44
  const port = Number(portArg)
29
- const graceSec = Number(graceArg ?? 60)
30
- /** A lockfile touched within this window counts as alive even without an
31
- * ESTABLISHED connection (see the adoption bump above): it must cover the
32
- * adopted client's whole mint budget (~15s) plus slack, while staying well
33
- * below the minimum untouched-lock age at reaper time (the grace window —
34
- * the lock was written before the quitting client even started using the
35
- * host). */
36
- const LOCK_RECENT_MS = 30_000
45
+ const idleMs = Number(idleMsArg)
46
+
47
+ // Defensive argument handling: the spawner always passes valid values, but
48
+ // a stray manual invocation must exit quietly instead of throwing.
49
+ if (!lockPath || !Number.isFinite(pid) || pid <= 0 || !Number.isFinite(idleMs) || idleMs < 0) {
50
+ process.exit(2)
51
+ }
52
+
53
+ const startedAt = Date.now()
54
+ /** Poll cadence inside the window: fine enough to notice a re-attach well
55
+ * before the deadline, coarse enough to keep `lsof` cheap. */
56
+ const POLL_MS = Math.max(50, Math.min(500, Math.round(idleMs / 10) || 50))
37
57
 
38
58
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
39
59
 
@@ -57,42 +77,91 @@ function establishedTo(targetPort) {
57
77
  return Math.max(0, lines.slice(1).filter((l) => l.trim().length > 0).length)
58
78
  }
59
79
 
80
+ /** Lockfile snapshot: the ownership fields plus the mtime used as the
81
+ * generation token. null when the lock is missing or unreadable. */
60
82
  function readLock() {
61
83
  try {
62
84
  const raw = JSON.parse(readFileSync(lockPath, 'utf8'))
63
- return typeof raw?.pid === 'number' ? raw : null
85
+ if (typeof raw?.pid !== 'number') return null
86
+ let mtimeMs = 0
87
+ try {
88
+ mtimeMs = statSync(lockPath).mtimeMs
89
+ } catch {
90
+ mtimeMs = 0
91
+ }
92
+ return { pid: raw.pid, port: raw.port, startedAt: typeof raw.startedAt === 'string' ? raw.startedAt : '', mtimeMs }
64
93
  } catch {
65
94
  return null
66
95
  }
67
96
  }
68
97
 
69
- await sleep(graceSec * 1000)
98
+ /** Has this lockfile moved to a new generation since `base`? Adoption
99
+ * rewrites `startedAt`; the mtime comparison is the belt-and-braces for a
100
+ * writer that keeps the field identical. */
101
+ function generationMoved(base, current) {
102
+ if (!base || !current) return false
103
+ if (current.startedAt !== base.startedAt) return true
104
+ return current.mtimeMs > base.mtimeMs + 1
105
+ }
70
106
 
71
- const lock = readLock()
72
- if (!lock || lock.pid !== pid) process.exit(0) // replaced by a fresh boot — not ours
107
+ const logPath = join(dirname(lockPath), 'opentui-host.idle.log')
108
+ function logIdleExit(hostPort) {
109
+ const line =
110
+ `${new Date().toISOString()} reason=idle idleMs=${idleMs} ` +
111
+ `lastClientAt=${new Date(startedAt).toISOString()} host=${pid} port=${hostPort}\n`
112
+ try {
113
+ appendFileSync(logPath, line)
114
+ } catch {}
115
+ try {
116
+ process.stderr.write(line) // usually /dev/null (detached, stdio ignore)
117
+ } catch {}
118
+ }
73
119
 
74
- // A client that adopted at the grace edge bumps the lockfile (fresh
75
- // startedAt/mtime) and may still be minting — spare recently-touched locks.
76
- try {
77
- if (Date.now() - statSync(lockPath).mtimeMs < LOCK_RECENT_MS) process.exit(0)
78
- } catch {} // stat failed (lock vanished) → fall through to the TCP probe
120
+ const initial = readLock()
121
+ if (!initial || initial.pid !== pid) process.exit(0) // nothing of ours to reap
122
+
123
+ const deadline = startedAt + idleMs
124
+ for (;;) {
125
+ const remaining = deadline - Date.now()
126
+ if (remaining <= 0) break
127
+ await sleep(Math.min(POLL_MS, remaining))
128
+
129
+ const current = readLock()
130
+ if (!current) continue // mid-rewrite or vanished: re-check at the deadline
131
+ if (current.pid !== pid) process.exit(0) // replaced by a fresh boot — not ours
132
+ if (generationMoved(initial, current)) process.exit(0) // adopted mid-window — a client is coming
133
+ if (establishedTo(port) > 0) process.exit(0) // a client re-attached — cancel the idle exit
134
+ }
79
135
 
80
- const established = establishedTo(port)
81
- if (established > 0) process.exit(0) // a client re-attached — the host stays under its new owner
136
+ // Final gate: re-verify everything we saw during the window. Anything
137
+ // ambiguous (unreadable lock) means "do not kill".
138
+ const finalLock = readLock()
139
+ if (!finalLock) process.exit(0)
140
+ if (finalLock.pid !== pid) process.exit(0)
141
+ if (generationMoved(initial, finalLock)) process.exit(0)
142
+ if (establishedTo(port) > 0) process.exit(0)
82
143
 
144
+ logIdleExit(finalLock.port ?? port)
83
145
  try {
84
146
  process.kill(pid, 'SIGTERM')
85
147
  } catch {}
86
- await sleep(2000)
148
+ // Graceful window for the host's own SIGTERM disposer; escalate only when
149
+ // it is still alive afterwards. Polling (not a flat sleep) lets the lockfile
150
+ // cleanup happen as soon as the host is gone, so a new client booting right
151
+ // after the exit does not see a stale lock.
152
+ const killDeadline = Date.now() + 2000
153
+ while (Date.now() < killDeadline && pidAlive(pid)) await sleep(50)
87
154
  if (pidAlive(pid)) {
88
155
  try {
89
156
  process.kill(pid, 'SIGKILL')
90
157
  } catch {}
158
+ const hardDeadline = Date.now() + 500
159
+ while (Date.now() < hardDeadline && pidAlive(pid)) await sleep(25)
91
160
  }
92
161
  // Clear the lockfile only if it still describes THIS host (never clobber
93
162
  // a newer host's lock — lifecycle parity).
94
163
  try {
95
164
  const now = readLock()
96
- if (now && now.pid === pid && now.port === port) rmSync(lockPath, { force: true })
165
+ if (now && now.pid === pid && now.port === finalLock.port) rmSync(lockPath, { force: true })
97
166
  } catch {}
98
167
  process.exit(0)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiwayds/dsh-opentui",
3
- "version": "0.9.2",
3
+ "version": "0.9.4",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "bin": {
@@ -600,7 +600,7 @@ const scenarioB = async () => {
600
600
  notes.push(`quits: client1=${q1} client2=${q2}`)
601
601
 
602
602
  // the idle-reaper path: the last quit spawned the detached reaper with
603
- // graceSec = idleExitSec (60) — the host exits inside ~60-75s
603
+ // the 5s window (DSH_OPENTUI_HOST_IDLE_MS) — the host exits inside ~5-10s
604
604
  const hostGone = await waitPidGone(lock1.pid, 110_000)
605
605
  const lockAfter = readLock()
606
606
  notes.push(`host dead after grace=${hostGone} · lockfile now: ${lockAfter ? `pid=${lockAfter.pid}` : 'gone'}`)
@@ -11,7 +11,7 @@
11
11
  // · every TUI slash command from ShellHost's COMMANDS array (read-only
12
12
  // forms), each with open → render → action → close-clean → crash-scan
13
13
  // · the overlay pickers (/preset /model /theme /settings /agents /history
14
- // /sessions /resume /search) with item-text anchors (kit Select title
14
+ // /resume /search) with item-text anchors (kit Select title
15
15
  // rows paint BLANK — anchor on items, never the title)
16
16
  // · /config bare + set + invalid-key forms; /login|/logout headless REF
17
17
  // forms and the PANEL flow (directory → key entry → esc), including the
@@ -575,9 +575,9 @@ try {
575
575
  // closeAllOverlays guards the nesting; a leftover list layer would eat
576
576
  // every later typed command)
577
577
  await submit('/agents')
578
- const ag = await waitPane((o) => o.includes('no agent definitions') || !idle(o), 8000)
579
- const agOpen = ag.ok && !ag.out.includes('no agent definitions')
580
- record('/agents list', ag.ok ? 'PASS' : 'FAIL', ag.out.includes('no agent definitions') ? ['no agents seeded'] : [])
578
+ const ag = await waitPane((o) => o.includes('no agents in') || !idle(o), 8000)
579
+ const agOpen = ag.ok && !ag.out.includes('no agents in')
580
+ record('/agents list', ag.ok ? 'PASS' : 'FAIL', ag.out.includes('no agents in') ? ['no agents seeded'] : [])
581
581
  writeFileSync(join(capsDir, 'agents.txt'), ag.out)
582
582
  if (agOpen) {
583
583
  const fields = await pressUntil((o) => o.includes('model:') || o.includes('thinking:'), 'Enter')
@@ -801,15 +801,15 @@ try {
801
801
  await waitPane((o) => idle(o), 180_000)
802
802
  await cleanBuffer()
803
803
 
804
- // /sessions picker + resume replay
805
- await submit('/sessions')
804
+ // /resume picker + resume replay
805
+ await submit('/resume')
806
806
  const sess = await waitPane((o) => !idle(o), 10_000)
807
807
  cap = capture()
808
- record('/sessions picker lists stored', /sweepok|count|reply with/.test(cap) ? 'PASS' : 'FAIL')
808
+ record('/resume picker lists stored', /sweepok|count|reply with/.test(cap) ? 'PASS' : 'FAIL')
809
809
  if (sess.ok) {
810
810
  await pressUntil((o) => hasAny(o, ['resumed', '已恢复', '已挂载']), 'Enter', 2, 2500)
811
811
  cap = capture({ full: true })
812
- record('/sessions resume replays rows', /resumed|已恢复|已挂载/.test(cap) ? 'PASS' : 'CHECK')
812
+ record('/resume resume replays rows', /resumed|已恢复|已挂载/.test(cap) ? 'PASS' : 'CHECK')
813
813
  await submit('/new'); await waitPane((o) => idle(o), 8000)
814
814
  }
815
815
 
@@ -885,7 +885,7 @@ try {
885
885
  }
886
886
  } catch { record('/tail sessionId', 'CHECK', ['sessions dir unreadable']) }
887
887
  } else {
888
- for (const item of ['turn: real reply', 'stop-confirm arm/n/y', '/sessions resume', '/search hit', '/queue drain', '/btw', '/history fork']) {
888
+ for (const item of ['turn: real reply', 'stop-confirm arm/n/y', '/resume resume', '/search hit', '/queue drain', '/btw', '/history fork']) {
889
889
  record(item, 'BLOCKED', ['no route answers (probe: ' + (ROUTE_PROBE.tried.join(' | ') || 'empty') + ')'])
890
890
  }
891
891
  }
@@ -1,39 +1,59 @@
1
1
  // Idle-exit reaper (ADR-0005 decision 5, entry-side companion of
2
2
  // lifecycle.ts): the lifecycle's idle-exit timer is unref()ed — a
3
3
  // refcount-0 manager must stay free to exit — so a cleanly quitting TUI
4
- // cannot deliver "the host exits after idleExitSec of idleness" with an
5
- // in-process timer. The quitting client spawns this script DETACHED
6
- // instead (spawnIdleReaper in src/client-entry.tsx):
4
+ // cannot deliver "the host exits after DSH_OPENTUI_HOST_IDLE_MS of
5
+ // idleness" with an in-process timer. The quitting client spawns this
6
+ // script DETACHED instead (spawnIdleReaper in src/client/boot-shared.ts):
7
7
  //
8
- // bun idle-reaper.mjs <pid> <port> <lockfilePath> <graceSec>
8
+ // node idle-reaper.mjs <pid> <port> <lockfilePath> <idleMs>
9
+ //
10
+ // It owns the idle window after the last client disconnected. During the
11
+ // window it polls the port and the lockfile; a client coming back CANCELS
12
+ // the timer (exit 0, the host stays — that client's own quit arms the next
13
+ // reaper). It never touches a host it does not own:
14
+ //
15
+ // - the lockfile now describes a DIFFERENT pid (a fresh boot — or
16
+ // lifecycle's `booting` placeholder, pid = the booting client — replaced
17
+ // the host): exit without killing;
18
+ // - the lockfile GENERATION moved since the window started (lifecycle's
19
+ // adoptHost bumps startedAt/mtime): a client adopted the host and may
20
+ // still be minting its cookie (up to ~15s) before its first ESTABLISHED
21
+ // connection — spare it;
22
+ // - an ESTABLISHED TCP connection to the host port (the adoption path's
23
+ // liveness marker): a client re-attached, spare it;
24
+ // - the lockfile cannot be read: never kill what we cannot verify.
25
+ //
26
+ // After the window with none of the above, it appends one line to
27
+ // `<dshHome>/opentui-host.idle.log`
28
+ // <iso> reason=idle idleMs=<n> lastClientAt=<iso> host=<pid> port=<n>
29
+ // then SIGTERMs the host, escalates to SIGKILL after 2s, and clears the
30
+ // lockfile only while it still describes this host.
9
31
  //
10
- // After the grace window it shuts the host down — unless:
11
- // - the lockfile now describes a DIFFERENT pid (a fresh boot — or lifecycle's
12
- // `booting` placeholder, pid = the booting client — replaced the host):
13
- // never touch what we do not own;
14
- // - the lockfile was touched RECENTLY (lifecycle adoptHost bumps
15
- // startedAt/mtime on adoption): a client that adopted at the grace edge
16
- // can still be minting its cookie (up to ~15s) before it opens its first
17
- // ESTABLISHED connection, so a fresh lockfile touch counts as alive;
18
- // - a client re-attached inside the grace window (established TCP
19
- // connections to the host port — the adoption path keeps the host alive
20
- // under its new owner; that owner's own quit spawns the next reaper).
21
32
  // The probe is `lsof -sTCP:ESTABLISHED`; when the tool is unavailable the
22
33
  // reaper falls back to the plain lifecycle semantics (idle exit).
23
- import { readFileSync, rmSync, statSync } from 'node:fs'
34
+ //
35
+ // Idempotent and leak-free: no sockets are opened (lsof is a child
36
+ // process), the process exits by itself, and a replacement host's lock is
37
+ // never removed.
38
+ import { appendFileSync, readFileSync, rmSync, statSync } from 'node:fs'
24
39
  import { spawnSync } from 'node:child_process'
40
+ import { dirname, join } from 'node:path'
25
41
 
26
- const [pidArg, portArg, lockPath, graceArg] = process.argv.slice(2)
42
+ const [pidArg, portArg, lockPath, idleMsArg] = process.argv.slice(2)
27
43
  const pid = Number(pidArg)
28
44
  const port = Number(portArg)
29
- const graceSec = Number(graceArg ?? 60)
30
- /** A lockfile touched within this window counts as alive even without an
31
- * ESTABLISHED connection (see the adoption bump above): it must cover the
32
- * adopted client's whole mint budget (~15s) plus slack, while staying well
33
- * below the minimum untouched-lock age at reaper time (the grace window —
34
- * the lock was written before the quitting client even started using the
35
- * host). */
36
- const LOCK_RECENT_MS = 30_000
45
+ const idleMs = Number(idleMsArg)
46
+
47
+ // Defensive argument handling: the spawner always passes valid values, but
48
+ // a stray manual invocation must exit quietly instead of throwing.
49
+ if (!lockPath || !Number.isFinite(pid) || pid <= 0 || !Number.isFinite(idleMs) || idleMs < 0) {
50
+ process.exit(2)
51
+ }
52
+
53
+ const startedAt = Date.now()
54
+ /** Poll cadence inside the window: fine enough to notice a re-attach well
55
+ * before the deadline, coarse enough to keep `lsof` cheap. */
56
+ const POLL_MS = Math.max(50, Math.min(500, Math.round(idleMs / 10) || 50))
37
57
 
38
58
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
39
59
 
@@ -57,42 +77,91 @@ function establishedTo(targetPort) {
57
77
  return Math.max(0, lines.slice(1).filter((l) => l.trim().length > 0).length)
58
78
  }
59
79
 
80
+ /** Lockfile snapshot: the ownership fields plus the mtime used as the
81
+ * generation token. null when the lock is missing or unreadable. */
60
82
  function readLock() {
61
83
  try {
62
84
  const raw = JSON.parse(readFileSync(lockPath, 'utf8'))
63
- return typeof raw?.pid === 'number' ? raw : null
85
+ if (typeof raw?.pid !== 'number') return null
86
+ let mtimeMs = 0
87
+ try {
88
+ mtimeMs = statSync(lockPath).mtimeMs
89
+ } catch {
90
+ mtimeMs = 0
91
+ }
92
+ return { pid: raw.pid, port: raw.port, startedAt: typeof raw.startedAt === 'string' ? raw.startedAt : '', mtimeMs }
64
93
  } catch {
65
94
  return null
66
95
  }
67
96
  }
68
97
 
69
- await sleep(graceSec * 1000)
98
+ /** Has this lockfile moved to a new generation since `base`? Adoption
99
+ * rewrites `startedAt`; the mtime comparison is the belt-and-braces for a
100
+ * writer that keeps the field identical. */
101
+ function generationMoved(base, current) {
102
+ if (!base || !current) return false
103
+ if (current.startedAt !== base.startedAt) return true
104
+ return current.mtimeMs > base.mtimeMs + 1
105
+ }
70
106
 
71
- const lock = readLock()
72
- if (!lock || lock.pid !== pid) process.exit(0) // replaced by a fresh boot — not ours
107
+ const logPath = join(dirname(lockPath), 'opentui-host.idle.log')
108
+ function logIdleExit(hostPort) {
109
+ const line =
110
+ `${new Date().toISOString()} reason=idle idleMs=${idleMs} ` +
111
+ `lastClientAt=${new Date(startedAt).toISOString()} host=${pid} port=${hostPort}\n`
112
+ try {
113
+ appendFileSync(logPath, line)
114
+ } catch {}
115
+ try {
116
+ process.stderr.write(line) // usually /dev/null (detached, stdio ignore)
117
+ } catch {}
118
+ }
73
119
 
74
- // A client that adopted at the grace edge bumps the lockfile (fresh
75
- // startedAt/mtime) and may still be minting — spare recently-touched locks.
76
- try {
77
- if (Date.now() - statSync(lockPath).mtimeMs < LOCK_RECENT_MS) process.exit(0)
78
- } catch {} // stat failed (lock vanished) → fall through to the TCP probe
120
+ const initial = readLock()
121
+ if (!initial || initial.pid !== pid) process.exit(0) // nothing of ours to reap
122
+
123
+ const deadline = startedAt + idleMs
124
+ for (;;) {
125
+ const remaining = deadline - Date.now()
126
+ if (remaining <= 0) break
127
+ await sleep(Math.min(POLL_MS, remaining))
128
+
129
+ const current = readLock()
130
+ if (!current) continue // mid-rewrite or vanished: re-check at the deadline
131
+ if (current.pid !== pid) process.exit(0) // replaced by a fresh boot — not ours
132
+ if (generationMoved(initial, current)) process.exit(0) // adopted mid-window — a client is coming
133
+ if (establishedTo(port) > 0) process.exit(0) // a client re-attached — cancel the idle exit
134
+ }
79
135
 
80
- const established = establishedTo(port)
81
- if (established > 0) process.exit(0) // a client re-attached — the host stays under its new owner
136
+ // Final gate: re-verify everything we saw during the window. Anything
137
+ // ambiguous (unreadable lock) means "do not kill".
138
+ const finalLock = readLock()
139
+ if (!finalLock) process.exit(0)
140
+ if (finalLock.pid !== pid) process.exit(0)
141
+ if (generationMoved(initial, finalLock)) process.exit(0)
142
+ if (establishedTo(port) > 0) process.exit(0)
82
143
 
144
+ logIdleExit(finalLock.port ?? port)
83
145
  try {
84
146
  process.kill(pid, 'SIGTERM')
85
147
  } catch {}
86
- await sleep(2000)
148
+ // Graceful window for the host's own SIGTERM disposer; escalate only when
149
+ // it is still alive afterwards. Polling (not a flat sleep) lets the lockfile
150
+ // cleanup happen as soon as the host is gone, so a new client booting right
151
+ // after the exit does not see a stale lock.
152
+ const killDeadline = Date.now() + 2000
153
+ while (Date.now() < killDeadline && pidAlive(pid)) await sleep(50)
87
154
  if (pidAlive(pid)) {
88
155
  try {
89
156
  process.kill(pid, 'SIGKILL')
90
157
  } catch {}
158
+ const hardDeadline = Date.now() + 500
159
+ while (Date.now() < hardDeadline && pidAlive(pid)) await sleep(25)
91
160
  }
92
161
  // Clear the lockfile only if it still describes THIS host (never clobber
93
162
  // a newer host's lock — lifecycle parity).
94
163
  try {
95
164
  const now = readLock()
96
- if (now && now.pid === pid && now.port === port) rmSync(lockPath, { force: true })
165
+ if (now && now.pid === pid && now.port === finalLock.port) rmSync(lockPath, { force: true })
97
166
  } catch {}
98
167
  process.exit(0)