@hmharness/cli 0.23.52 → 0.23.55

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.
@@ -78,11 +78,11 @@ let PACKAGES = ['cli', 'web', 'agent', 'kernel', 'sandbox', 'evolution',
78
78
  // the offline path tried <name>-undefined.tgz → 404 → INSTALL FAILED (directly
79
79
  // contradicting the promise above; evidence: cli 0.23.42 declares 14 deps).
80
80
  const FALLBACK_PINS = {
81
- cli: '0.23.52', web: '0.23.52', agent: '0.23.52', kernel: '0.23.52',
82
- sandbox: '0.23.52', evolution: '0.23.52', 'domain-ops': '0.23.52',
83
- evaluation: '0.23.52', observability: '0.23.52', 'domain-harmony': '0.23.52',
84
- cognitive: '0.23.52', environments: '0.23.52', lsp: '0.23.52',
85
- browser: '0.23.52', extension: '0.23.52',
81
+ cli: '0.23.55', web: '0.23.55', agent: '0.23.55', kernel: '0.23.55',
82
+ sandbox: '0.23.55', evolution: '0.23.55', 'domain-ops': '0.23.55',
83
+ evaluation: '0.23.55', observability: '0.23.55', 'domain-harmony': '0.23.55',
84
+ cognitive: '0.23.55', environments: '0.23.55', lsp: '0.23.55',
85
+ browser: '0.23.55', extension: '0.23.55',
86
86
  };
87
87
 
88
88
  // ---------- helpers ---------------------------------------------------------
@@ -0,0 +1,7 @@
1
+ /** The package an entry point is installed in: <package>/dist/main.js -> <package>. */
2
+ export declare function packageRootOf(entry: string): string;
3
+ /** Is `path` the directory `dir` itself or somewhere below it? (Case-insensitive on Windows.) */
4
+ export declare function isInside(dir: string, path: string): boolean;
5
+ /** The directory a daemon is spawned with: the caller's, unless that is the
6
+ * installed package (then HMH_HOME). `entry` is the CLI's own entry path. */
7
+ export declare function daemonCwd(origin: string, entry: string): string;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * @hmharness/cli - working directory for detached daemons
3
+ *
4
+ * A process holds its working directory for as long as it lives, and on Windows
5
+ * that handle locks the directory against rename and delete. A daemon started
6
+ * from inside the installed package (a launcher that cd's there first) therefore
7
+ * blocked the next `npm i -g` with EBUSY until it was killed (seen on the
8
+ * v0.23.53 upgrade, 2026-11-26). No daemon needs that directory: HMH_HOME is
9
+ * theirs and is never replaced.
10
+ *
11
+ * The caller's directory is otherwise kept on purpose. The web daemon seeds its
12
+ * first workspace from the directory it was started in (web/server.ts), and
13
+ * relative paths resolve against it - so only the one harmful case is swapped out.
14
+ */
15
+ import { dirname, resolve, sep } from 'node:path';
16
+ import { homeDir } from '@hmharness/kernel';
17
+ /** The package an entry point is installed in: <package>/dist/main.js -> <package>. */
18
+ export function packageRootOf(entry) {
19
+ return dirname(dirname(resolve(entry)));
20
+ }
21
+ /** Is `path` the directory `dir` itself or somewhere below it? (Case-insensitive on Windows.) */
22
+ export function isInside(dir, path) {
23
+ const fold = (p) => (process.platform === 'win32' ? resolve(p).toLowerCase() : resolve(p));
24
+ const a = fold(dir);
25
+ const b = fold(path);
26
+ return b === a || b.startsWith(a.endsWith(sep) ? a : a + sep);
27
+ }
28
+ /** The directory a daemon is spawned with: the caller's, unless that is the
29
+ * installed package (then HMH_HOME). `entry` is the CLI's own entry path. */
30
+ export function daemonCwd(origin, entry) {
31
+ return isInside(packageRootOf(entry), origin) ? homeDir() : origin;
32
+ }
@@ -1,3 +1,5 @@
1
+ /** The running daemon's pid (null when none) - read-only, for `hmh web status`. */
2
+ export declare function evolutionDaemonPid(home?: string): number | null;
1
3
  export interface EvolDaemonStatus {
2
4
  running: boolean;
3
5
  pid?: number;
@@ -15,5 +17,15 @@ export declare function daemonRunnerSource(pidFile: string, entryAbs: string): s
15
17
  * Never blocks the caller - fire-and-forget.
16
18
  */
17
19
  export declare function ensureEvolutionDaemon(): EvolDaemonStatus;
20
+ /** The runner file and the directory it is launched in. The runner's cwd is
21
+ * inherited by every `hmh evolve` / `auto-finetune` child, and the bench
22
+ * cases run their tools in it, so it must be a directory of the daemon's own -
23
+ * not whichever folder happened to launch it (the Startup folder's, a
24
+ * project's, the installed package's: a live cwd handle there blocks the next
25
+ * upgrade on Windows). Created on demand. */
26
+ export declare function evolutionSpawnOptions(home: string): {
27
+ runnerPath: string;
28
+ cwd: string;
29
+ };
18
30
  export declare function stopEvolutionDaemon(): boolean;
19
31
  export declare function daemonPidFileAlive(home: string): boolean;
@@ -4,9 +4,10 @@
4
4
  * The evolution engine runs as a SILENT BACKGROUND PROCESS, exactly like the
5
5
  * web daemon. The user NEVER runs `hmh evolve` manually - it just happens.
6
6
  *
7
- * Lifecycle: starts automatically on `hmh tui` / `hmh web` / any command that
8
- * calls ensureEvolutionDaemon(). Runs one evolution cycle every
9
- * `evolution.autoEveryHours` hours (default 6h), then sleeps. After each
7
+ * Lifecycle: starts automatically on `hmh web start` (and `hmh evolve-auto`).
8
+ * Runs one evolution cycle every `evolution.autoEveryHours` hours (default
9
+ * 6h), then sleeps. `hmh web stop` stops it again (0.23.55: until then nothing
10
+ * could - it kept cycling, and spending model quota, after "stop"). After each
10
11
  * evolve cycle it also runs the auto-finetune gate (2026-09-25: labels past
11
12
  * threshold -> pairs exported -> uploaded -> cloud training submitted, all
12
13
  * unattended; `hmh auto-finetune` itself decides whether anything is due).
@@ -17,29 +18,37 @@
17
18
  * The runner is now plain CJS (require only) and verified with node --check.
18
19
  */
19
20
  import { spawn } from 'node:child_process';
20
- import { existsSync, readFileSync, writeFileSync, mkdirSync, openSync } from 'node:fs';
21
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, openSync, closeSync, unlinkSync } from 'node:fs';
21
22
  import { join } from 'node:path';
22
23
  import { homeDir } from '@hmharness/kernel';
24
+ import { identifyProcess, isAlive, killProcessTree } from "./process-identity.js";
23
25
  const EVOL_DAEMON_PID = 'evolution-daemon.pid';
24
26
  const EVOL_DAEMON_LOG = 'evolution-daemon.log';
27
+ const RUNNER_NAME = 'evolution-daemon-runner';
28
+ /** The pid of the RUNNING evolution daemon, or null. The pid file alone proves
29
+ * nothing: it outlives its process (a runner killed on Windows gets no
30
+ * SIGTERM, so it never cleans up after itself) and pids are reused. Until
31
+ * 0.23.55 a stranger wearing the old number read as "daemon alive" - evolution
32
+ * silently never restarted - and `hmh web stop` would have killed it.
33
+ * A command line that cannot be read at all keeps the old trust in the pid. */
25
34
  function daemonPid(home) {
35
+ let pid;
26
36
  try {
27
- const raw = readFileSync(join(home, EVOL_DAEMON_PID), 'utf8').trim();
28
- const pid = Number(raw);
29
- if (!Number.isFinite(pid))
37
+ const n = Number(readFileSync(join(home, EVOL_DAEMON_PID), 'utf8').trim());
38
+ if (!Number.isInteger(n) || n <= 0)
30
39
  return null;
31
- // check alive (Windows: process.kill with signal 0 throws if dead)
32
- try {
33
- process.kill(pid, 0);
34
- return pid;
35
- }
36
- catch {
37
- return null;
38
- }
40
+ pid = n;
39
41
  }
40
42
  catch {
41
43
  return null;
42
44
  }
45
+ if (!isAlive(pid))
46
+ return null;
47
+ return identifyProcess(pid, (cmd) => cmd.includes(RUNNER_NAME)) === 'other' ? null : pid;
48
+ }
49
+ /** The running daemon's pid (null when none) - read-only, for `hmh web status`. */
50
+ export function evolutionDaemonPid(home = homeDir()) {
51
+ return daemonPid(home);
43
52
  }
44
53
  /** Build the runner source. Plain CJS - verified with node --check in the
45
54
  * daemon tests (the 0.14.25 version was silently broken ESM-in-CJS).
@@ -100,7 +109,7 @@ export function ensureEvolutionDaemon() {
100
109
  const existing = daemonPid(home);
101
110
  if (existing)
102
111
  return { running: true, pid: existing, started: false };
103
- const runnerPath = join(home, 'evolution-daemon-runner.cjs');
112
+ const { runnerPath, cwd } = evolutionSpawnOptions(home);
104
113
  const entryAbs = join(import.meta.dirname ?? '.', 'main.js');
105
114
  writeFileSync(runnerPath, daemonRunnerSource(EVOL_DAEMON_PID, entryAbs), 'utf8');
106
115
  const log = openSync(join(home, EVOL_DAEMON_LOG), 'a');
@@ -108,30 +117,45 @@ export function ensureEvolutionDaemon() {
108
117
  detached: true,
109
118
  stdio: ['ignore', log, log],
110
119
  windowsHide: true,
120
+ cwd,
111
121
  env: { ...process.env, HMH_HOME: home },
112
122
  });
113
123
  child.unref();
114
124
  // the child inherited a dup of this fd; closing ours prevents the
115
- // "Closing file descriptor on garbage collection" startup warnings
125
+ // "Closing file descriptor on garbage collection" startup warnings.
126
+ // (An ESM module has no `require`: the old `require('node:fs').closeSync`
127
+ // here always threw and was swallowed by the empty catch.)
116
128
  try {
117
- require('node:fs').closeSync(log);
129
+ closeSync(log);
118
130
  }
119
131
  catch { /* already gone */ }
120
132
  return { running: true, pid: child.pid, started: true };
121
133
  }
134
+ /** The runner file and the directory it is launched in. The runner's cwd is
135
+ * inherited by every `hmh evolve` / `auto-finetune` child, and the bench
136
+ * cases run their tools in it, so it must be a directory of the daemon's own -
137
+ * not whichever folder happened to launch it (the Startup folder's, a
138
+ * project's, the installed package's: a live cwd handle there blocks the next
139
+ * upgrade on Windows). Created on demand. */
140
+ export function evolutionSpawnOptions(home) {
141
+ const cwd = join(home, 'evolution', 'scratch');
142
+ mkdirSync(cwd, { recursive: true });
143
+ return { runnerPath: join(home, `${RUNNER_NAME}.cjs`), cwd };
144
+ }
122
145
  export function stopEvolutionDaemon() {
123
146
  const home = homeDir();
124
147
  const pid = daemonPid(home);
125
- if (!pid)
126
- return false;
127
- try {
128
- process.kill(pid);
129
- }
130
- catch { }
148
+ // gone either way: the file names a dead runner, or a stranger - and a
149
+ // stranger is NOT killed (the old code trusted the number)
131
150
  try {
132
- require('node:fs').unlinkSync(join(home, EVOL_DAEMON_PID));
151
+ unlinkSync(join(home, EVOL_DAEMON_PID));
133
152
  }
134
- catch { }
153
+ catch { /* absent */ }
154
+ if (!pid)
155
+ return false;
156
+ // the whole tree: a cycle in flight is a child of the runner, and on Windows
157
+ // ending the runner alone left that child calling the model for up to 30 minutes
158
+ killProcessTree(pid);
135
159
  return true;
136
160
  }
137
161
  export function daemonPidFileAlive(home) {
@@ -8,7 +8,7 @@
8
8
  * hmharness capability set, with a CONVERSATIONAL approval gate for the
9
9
  * dangerous ones: the model proposes, the user types 「确认」).
10
10
  */
11
- import { loadConfig, resolveProvider, chat } from '@hmharness/kernel';
11
+ import { loadConfig, resolveProvider, chat, sanitizeToolCalls } from '@hmharness/kernel';
12
12
  import { formatPageSnapshot, summarizePage } from '@hmharness/extension';
13
13
  /** round bound: the CLI's own maxTurns guard, floored at 50 for the sidebar
14
14
  * (round 49: hand over a task, get it FINISHED — the panel auto-continues
@@ -210,20 +210,43 @@ export async function runChatTurn(provider, input, deps, chatImpl, origin = 'ano
210
210
  step('已达单段时限,收尾汇报…');
211
211
  step(`第 ${round + 1} 轮思考中…(已用 ${Math.round((Date.now() - t0) / 1000)}s)`);
212
212
  const res = await chatImpl(provider, messages, last ? [] : [...tools], { timeoutMs: 120_000, retry: { attempts: 2 } });
213
+ // why the model stopped: 'length' means the output cap CUT the reply or a
214
+ // tool call's JSON mid-way, 'content_filter' an empty reply by design
215
+ const cut = res.finishReason === 'length';
213
216
  const calls = last ? [] : res.message.tool_calls ?? [];
214
217
  if (!calls.length) {
215
- const text = res.message.content?.trim() || '(模型返回了空回复)';
218
+ const text = res.message.content?.trim();
219
+ if (!text) {
220
+ // "the model returned an empty reply" sends the user looking for a bug that is not there
221
+ if (res.finishReason === 'content_filter')
222
+ return '模型供应商以内容安全为由中止了本次回复(content_filter),没有返回内容。换个说法再试一次。';
223
+ return '(模型返回了空回复)';
224
+ }
216
225
  // AUTONOMOUS CONTINUATION (round 49): the task is not done, the round
217
226
  // budget is — the panel auto-sends 「继续」 when it sees this sentinel,
218
- // so the user hands over a task and gets it finished, no babysitting
219
- return last ? text + '\n[[hmh:auto-continue]]' : text;
227
+ // so the user hands over a task and gets it finished, no babysitting.
228
+ // A reply the output cap severed joins it: a cut-off sentence is not a finished answer either.
229
+ return last || cut ? text + '\n[[hmh:auto-continue]]' : text;
220
230
  }
221
231
  step(`第 ${round + 1} 轮: ${calls.map((c) => c.function.name).join(', ')}`);
222
- messages.push(res.message);
232
+ // the wire-boundary copy: arguments the output cap severed must not re-enter the
233
+ // next request raw - every strict provider 400s it (same rule as the main loop;
234
+ // the tool result below tells the model what happened)
235
+ messages.push({ ...res.message, tool_calls: sanitizeToolCalls(calls) });
223
236
  for (const call of calls) {
224
237
  let result;
238
+ // the parse is kept apart from the dispatch: only a PARSE failure can be the output cap's doing
239
+ let args = {};
240
+ let parseError = null;
241
+ try {
242
+ args = JSON.parse(call.function.arguments || '{}');
243
+ }
244
+ catch (err) {
245
+ parseError = err;
246
+ }
225
247
  try {
226
- const args = JSON.parse(call.function.arguments || '{}');
248
+ if (parseError)
249
+ throw parseError;
227
250
  if (pageFails >= 3 && (name => name === 'page_read' || name === 'page_act' || name === 'page_goto')(call.function.name)) {
228
251
  result = JSON.stringify({ ok: false, error: '页面通道连续失败(扩展断连?)——已熔断。请停止页面操作:基于已有信息回答,或让用户重连扩展后重试。' });
229
252
  }
@@ -236,7 +259,12 @@ export async function runChatTurn(provider, input, deps, chatImpl, origin = 'ano
236
259
  }
237
260
  }
238
261
  catch (err) {
239
- result = JSON.stringify({ ok: false, error: String(err instanceof Error ? err.message : err).slice(0, 200) });
262
+ // arguments the output cap severed (finish_reason 'length'): the bare parse
263
+ // error reads as "be more careful", and the model repeats the same
264
+ // oversized call - name the real limit instead
265
+ result = parseError && cut
266
+ ? JSON.stringify({ ok: false, error: `模型单次输出长度已到上限,${call.function.name} 的参数在写完之前被截断。请大幅缩短参数(长文件分几次写)后重试。` })
267
+ : JSON.stringify({ ok: false, error: String(err instanceof Error ? err.message : err).slice(0, 200) });
240
268
  if (/^page_/.test(call.function.name))
241
269
  pageFails++;
242
270
  }
@@ -14,6 +14,8 @@ import { pathToFileURL } from 'node:url';
14
14
  import { openSync, readFileSync, unlinkSync, writeFileSync, closeSync } from 'node:fs';
15
15
  import { join } from 'node:path';
16
16
  import { homeDir } from '@hmharness/kernel';
17
+ import { daemonCwd } from "./daemon-cwd.js";
18
+ import { identifyProcess, isAlive, killProcessTree } from "./process-identity.js";
17
19
  export const DEFAULT_EXTENSION_PORT = 7789;
18
20
  export function readExtensionPid() {
19
21
  try {
@@ -24,14 +26,21 @@ export function readExtensionPid() {
24
26
  return 0;
25
27
  }
26
28
  }
27
- function alive(pid) {
28
- try {
29
- process.kill(pid, 0);
30
- return true;
31
- }
32
- catch {
33
- return false;
34
- }
29
+ /** Is the process the bridge of ours (`main.js extension serve`), or one of
30
+ * its watchdogs (the detached one, or the scheduled task's entry script)?
31
+ * Every kill below is gated on this. The bridge used to be stopped BLIND:
32
+ * `extension stop` and the watchdog's 60s sweep taskkilled whatever the pid
33
+ * file or the port named - a stranger behind a stale pid, or another program
34
+ * that happened to sit on 7789, killed over and over, once a minute. */
35
+ function bridgeIdentity(pid) {
36
+ return identifyProcess(pid, (cmd) => /(^|\s)extension\s+serve\b/.test(cmd)
37
+ || /extension-watchdog-task\.cjs/.test(cmd)
38
+ || (/extension-daemon\.js/.test(cmd) && /runWatchdogLoop/.test(cmd)));
39
+ }
40
+ /** May the holder of the bridge port be evicted? Only something we can name as
41
+ * ours; where the command line cannot be read, the old trust stands off Windows. */
42
+ function evictable(id) {
43
+ return id === 'self' || (id === 'unknown' && process.platform !== 'win32');
35
44
  }
36
45
  export async function probeExtensionDaemon(port = DEFAULT_EXTENSION_PORT) {
37
46
  try {
@@ -74,31 +83,40 @@ export async function waitExtensionPortFree(port = DEFAULT_EXTENSION_PORT, maxMs
74
83
  export function stopExtensionDaemon(port = DEFAULT_EXTENSION_PORT) {
75
84
  const pid = readExtensionPid();
76
85
  let killed = false;
77
- if (pid && alive(pid)) {
78
- if (process.platform === 'win32')
79
- spawn('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true });
86
+ if (pid && isAlive(pid)) {
87
+ // only the bridge of OURS: a stale pid file plus a reused pid names a stranger
88
+ if (bridgeIdentity(pid) !== 'other') {
89
+ killProcessTree(pid);
90
+ killed = true;
91
+ }
80
92
  else {
81
- try {
82
- process.kill(pid);
83
- }
84
- catch { /* gone */ }
93
+ console.error(`[extension] extension.pid names pid ${pid}, which is not an hmh bridge - left alone`);
85
94
  }
86
- killed = true;
87
95
  }
88
96
  try {
89
97
  unlinkSync(join(homeDir(), 'extension.pid'));
90
98
  }
91
99
  catch { /* absent */ }
100
+ // a stale pid file while the port is still held: evict only our own orphan.
101
+ // A foreign program on the port is NOT ours to kill - and the watchdog
102
+ // runs this every minute, so a blind kill here meant killing it once a minute
92
103
  const owner = portOwnerPid(port);
93
104
  if (owner && owner !== pid) {
94
- try {
95
- spawn('taskkill', ['/PID', String(owner), '/T', '/F'], { windowsHide: true });
105
+ if (evictable(bridgeIdentity(owner))) {
106
+ killProcessTree(owner);
96
107
  killed = true;
97
108
  }
98
- catch { /* best effort */ }
109
+ else {
110
+ console.error(`[extension] port ${port} is held by a non-hmh process - not evicting`);
111
+ }
99
112
  }
100
113
  return killed;
101
114
  }
115
+ /** Is the port held by a process that is not ours (so no bridge may be spawned into it)? */
116
+ function foreignHolder(port) {
117
+ const owner = portOwnerPid(port);
118
+ return !!owner && !evictable(bridgeIdentity(owner));
119
+ }
102
120
  /** Spawn the bridge detached (no window). extraArgs carries --port through. */
103
121
  function spawnExtensionDaemon(entry, port) {
104
122
  const home = homeDir();
@@ -107,7 +125,7 @@ function spawnExtensionDaemon(entry, port) {
107
125
  detached: true,
108
126
  stdio: ['ignore', log, log],
109
127
  windowsHide: true,
110
- cwd: process.cwd(),
128
+ cwd: daemonCwd(process.cwd(), entry),
111
129
  });
112
130
  child.unref();
113
131
  try {
@@ -150,13 +168,17 @@ function cliVersion() {
150
168
  export async function ensureExtensionDaemon(port = DEFAULT_EXTENSION_PORT, entry = process.argv[1]) {
151
169
  const pid = readExtensionPid();
152
170
  const served = await probeExtensionDaemon(port);
153
- const stale = pid > 0 && alive(pid) && recordedVersion() !== cliVersion();
171
+ // stale = a bridge of OURS from an older CLI (a stranger behind the pid file is not a stale bridge)
172
+ const stale = pid > 0 && isAlive(pid) && recordedVersion() !== cliVersion() && bridgeIdentity(pid) !== 'other';
154
173
  if (served.up && !stale)
155
174
  return served;
156
- if (stale) {
157
- stopExtensionDaemon(port);
158
- await waitExtensionPortFree(port);
159
- }
175
+ // dead or stale: clear whatever is OURS off the port, then bring the bridge back
176
+ stopExtensionDaemon(port);
177
+ await waitExtensionPortFree(port);
178
+ // someone else holds the port: stay down. A bridge spawned into it only dies
179
+ // on EADDRINUSE - and from the watchdog that meant a dead spawn once a minute
180
+ if (foreignHolder(port))
181
+ return { up: false, connected: false };
160
182
  spawnExtensionDaemon(entry, port);
161
183
  for (let i = 0; i < 12; i++) {
162
184
  await new Promise((r) => setTimeout(r, 500));
@@ -169,7 +191,8 @@ export async function ensureExtensionDaemon(port = DEFAULT_EXTENSION_PORT, entry
169
191
  /** Simple start (no staleness handling): used by the explicit `start` command. */
170
192
  export function startExtensionDaemon(port = DEFAULT_EXTENSION_PORT, entry = process.argv[1]) {
171
193
  const pid = readExtensionPid();
172
- if (pid && alive(pid))
194
+ // "already running" only for the bridge of ours (a stale pid file may name a stranger)
195
+ if (pid && isAlive(pid) && bridgeIdentity(pid) !== 'other')
173
196
  return { already: true, pid };
174
197
  return { already: false, pid: spawnExtensionDaemon(entry, port) };
175
198
  }
@@ -189,8 +212,10 @@ export async function runWatchdogLoop(port, entry) {
189
212
  const wp = watchdogPidPath();
190
213
  try {
191
214
  const existing = Number(readFileSync(wp, 'utf8').trim());
192
- if (Number.isFinite(existing) && existing > 0 && existing !== process.pid && alive(existing)) {
193
- process.exit(0); // another watchdog is on duty
215
+ // another watchdog is on duty - but only a real one: a stranger behind a stale
216
+ // pid file used to make every new watchdog exit at once, leaving nobody on duty
217
+ if (Number.isFinite(existing) && existing > 0 && existing !== process.pid && isAlive(existing) && bridgeIdentity(existing) !== 'other') {
218
+ process.exit(0);
194
219
  }
195
220
  }
196
221
  catch { /* no pid file yet */ }
@@ -199,12 +224,14 @@ export async function runWatchdogLoop(port, entry) {
199
224
  try {
200
225
  const served = await probeExtensionDaemon(port);
201
226
  const pid = readExtensionPid();
202
- const stale = pid > 0 && alive(pid) && recordedVersion() !== cliVersion();
227
+ const stale = pid > 0 && isAlive(pid) && recordedVersion() !== cliVersion() && bridgeIdentity(pid) !== 'other';
203
228
  if (!served.up || stale) {
204
- if (stale)
205
- stopExtensionDaemon(port);
229
+ // what is ours gets cleared off the port (a hung bridge included); a
230
+ // foreign holder is left alone and no doomed spawn is made into it
231
+ stopExtensionDaemon(port);
206
232
  await waitExtensionPortFree(port, 3000);
207
- spawnExtensionDaemon(entry, port);
233
+ if (!foreignHolder(port))
234
+ spawnExtensionDaemon(entry, port);
208
235
  }
209
236
  }
210
237
  catch { /* a watchdog that throws is a watchdog that dies — never */ }
@@ -216,7 +243,7 @@ export function startWatchdog(port = DEFAULT_EXTENSION_PORT, entry = process.arg
216
243
  try {
217
244
  const wp = watchdogPidPath();
218
245
  const existing = Number(readFileSync(wp, 'utf8').trim());
219
- if (Number.isFinite(existing) && existing > 0 && alive(existing))
246
+ if (Number.isFinite(existing) && existing > 0 && isAlive(existing) && bridgeIdentity(existing) !== 'other')
220
247
  return existing;
221
248
  }
222
249
  catch { /* none yet */ }
@@ -224,7 +251,7 @@ export function startWatchdog(port = DEFAULT_EXTENSION_PORT, entry = process.arg
224
251
  const child = spawn(process.execPath, [
225
252
  '-e',
226
253
  `import('${pathToFileURL(entry).href.replace(/main\.js$/, 'extension-daemon.js')}').then(m => m.runWatchdogLoop(${port}, ${JSON.stringify(entry)}))`,
227
- ], { detached: true, stdio: ['ignore', log, log], windowsHide: true });
254
+ ], { detached: true, stdio: ['ignore', log, log], windowsHide: true, cwd: daemonCwd(process.cwd(), entry) });
228
255
  child.unref();
229
256
  try {
230
257
  closeSync(log);
@@ -298,11 +325,9 @@ export function stopWatchdog() {
298
325
  try {
299
326
  const wp = watchdogPidPath();
300
327
  const pid = Number(readFileSync(wp, 'utf8').trim());
301
- if (Number.isFinite(pid) && pid > 0 && alive(pid)) {
302
- if (process.platform === 'win32')
303
- spawn('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true });
304
- else
305
- process.kill(pid);
328
+ // only a watchdog of ours gets killed - a stale pid file may name anyone
329
+ if (Number.isFinite(pid) && pid > 0 && isAlive(pid) && bridgeIdentity(pid) !== 'other') {
330
+ killProcessTree(pid);
306
331
  try {
307
332
  unlinkSync(wp);
308
333
  }
package/dist/main.js CHANGED
@@ -493,8 +493,10 @@ usage:
493
493
  hmh readiness the RL gate: six conditions measured from real evidence (V2 M11)
494
494
  hmh pipeline "<task>" role pipeline: plan→code→test→review→judge (+repair loop,
495
495
  VERDICT gate) - V3 first slice (ADR-0006)
496
- hmh web start|stop|status web UI as a silent background daemon (no window,
497
- survives closing everything; log ~/.hmharness/web.log)
496
+ hmh web start|stop|status [--port=7788]
497
+ web UI as a silent background daemon (no window,
498
+ survives closing everything; log ~/.hmharness/web.log);
499
+ stop also stops the background evolution daemon
498
500
  hmh web [--port=7788] web UI in the foreground (debugging)
499
501
  hmh tui [--no-web] fullscreen terminal UI (slash palette, mouse wheel);
500
502
  also starts the web UI in the background (--no-web skips)
@@ -532,9 +534,22 @@ flags:
532
534
  --yes / -y auto-approve gated tools (else they prompt; non-TTY denies)
533
535
  --locale=zh|en override the UI locale for this run
534
536
  --help | -h this help
537
+ --version | -v print the version and exit
535
538
  `);
536
539
  return;
537
540
  }
541
+ if (cmd === 'version' || cmd === '--version' || cmd === '-v' || cmd === '-V') {
542
+ // until 0.23.55 this fell through into the interactive REPL
543
+ const { createRequire } = await import('node:module');
544
+ stdout.write(`hmh ${createRequire(import.meta.url)('../package.json').version ?? ''}\n`);
545
+ return;
546
+ }
547
+ if (cmd && cmd.startsWith('-')) {
548
+ // an option nobody knows used to fall through into the interactive REPL
549
+ process.stderr.write(`hmh: unknown option ${cmd} (hmh --help lists the commands and flags)\n`);
550
+ process.exitCode = 2;
551
+ return;
552
+ }
538
553
  if (cmd === 'init') {
539
554
  const { home, created } = await initHome();
540
555
  stdout.write(`home: ${home}\n${created.length ? 'created: ' + created.join(', ') : 'already initialized.'}\n`);
@@ -1177,9 +1192,9 @@ flags:
1177
1192
  }
1178
1193
  if (sub === 'start' || sub === 'stop') {
1179
1194
  // 后台守护(与 hmh web start 同款):装完扩展后终端侧零操作常驻
1180
- const pArg = rest.find((a) => a.startsWith('--port='));
1181
- const port = pArg ? Number(pArg.slice(7)) : undefined;
1195
+ const { parsePort } = await import("./web-daemon.js");
1182
1196
  const ed = await import("./extension-daemon.js");
1197
+ const port = parsePort(rest, ed.DEFAULT_EXTENSION_PORT);
1183
1198
  if (sub === 'stop') {
1184
1199
  const w = ed.stopWatchdog();
1185
1200
  const killed = ed.stopExtensionDaemon(port);
@@ -1188,7 +1203,7 @@ flags:
1188
1203
  return;
1189
1204
  }
1190
1205
  const { probeExtensionDaemon, ensureExtensionDaemon, startWatchdog, installScheduledWatchdog, DEFAULT_EXTENSION_PORT } = ed;
1191
- const p = port ?? DEFAULT_EXTENSION_PORT;
1206
+ const p = port;
1192
1207
  const already = await probeExtensionDaemon(p);
1193
1208
  if (already.up) {
1194
1209
  stdout.write(`✓ 扩展桥已在运行: 127.0.0.1:${p} — 无需重复启动\n`);
@@ -1843,7 +1858,10 @@ flags:
1843
1858
  }
1844
1859
  if (cmd === 'web') {
1845
1860
  await initHome();
1846
- const port = Number(rest.find((a) => a.startsWith('--port='))?.slice(7) ?? 7788);
1861
+ // --port=N; an empty or out-of-range value is the default (until 0.23.55 a
1862
+ // bare `--port=` silently became port 0)
1863
+ const { parsePort } = await import("./web-daemon.js");
1864
+ const port = parsePort(rest, 7788);
1847
1865
  // remote control (2026-09-28): --exposure=lan|wan opens the UI to other
1848
1866
  // devices; web.token in config.json is the auth (REQUIRED for lan/wan).
1849
1867
  // CLI flags win over config: --exposure / --token=... / --token-gen.
@@ -1920,23 +1938,36 @@ flags:
1920
1938
  return;
1921
1939
  }
1922
1940
  if (sub === 'stop') {
1923
- stdout.write(stopWebDaemon() ? t.webStopped + '\n' : t.webNotRunning + '\n');
1941
+ // The evolution daemon rides along (`web start` brings it up): stopping the
1942
+ // UI stops it too. Until 0.23.55 nothing could - it kept cycling, and
1943
+ // spending model quota, after "stop".
1944
+ const { stopEvolutionDaemon } = await import("./evolution-daemon.js");
1945
+ const evoStopped = stopEvolutionDaemon();
1946
+ // the port asked for, not always the default one: `web stop --port=7799`
1947
+ // used to stop 7788 (until 0.23.55) - the main instance instead of the dev one
1948
+ stdout.write(stopWebDaemon(port) ? t.webStopped + '\n' : t.webNotRunning + '\n');
1949
+ if (evoStopped)
1950
+ stdout.write(t.evoStopped + '\n');
1924
1951
  return;
1925
1952
  }
1926
1953
  if (sub === 'status') {
1927
- const up = await hmhWebUp(Number.isFinite(port) ? port : 7788);
1954
+ const up = await hmhWebUp(port);
1928
1955
  stdout.write(up ? t.webRunning(readWebPid() || 0, port) + '\n' : t.webNotRunning + '\n');
1929
1956
  // stale-daemon warning: the daemon is a code snapshot from spawn time;
1930
1957
  // after an upgrade it keeps serving old code until restarted. The
1931
1958
  // comparison uses the SERVED process's self-reported version.
1932
1959
  const { webDaemonStale } = await import("./web-daemon.js");
1933
- const v = await webDaemonStale(Number.isFinite(port) ? port : 7788);
1960
+ const v = await webDaemonStale(port);
1934
1961
  if (up && v.stale) {
1935
1962
  stdout.write(YELLOW(`⚠ daemon is running v${v.daemon} but CLI is v${v.cli} — stale code (new features missing). Run: hmh web stop && hmh web start\n`));
1936
1963
  }
1937
1964
  else if (up && v.daemon) {
1938
1965
  stdout.write(DIM(`daemon v${v.daemon}\n`));
1939
1966
  }
1967
+ // the evolution daemon runs on its own schedule and is otherwise invisible
1968
+ const { evolutionDaemonPid } = await import("./evolution-daemon.js");
1969
+ const evoPid = evolutionDaemonPid();
1970
+ stdout.write(DIM((evoPid ? t.evoRunning(evoPid) : t.evoNotRunning) + '\n'));
1940
1971
  return;
1941
1972
  }
1942
1973
  if (sub === 'start') {
@@ -1949,7 +1980,7 @@ flags:
1949
1980
  const tk = rest.find((a) => a.startsWith('--token='));
1950
1981
  if (tk)
1951
1982
  passThrough.push(tk);
1952
- const r = startWebDaemon(Number.isFinite(port) ? port : 7788, undefined, passThrough);
1983
+ const r = startWebDaemon(port, undefined, passThrough);
1953
1984
  // 2026-09-23: evolution runs silently alongside the web daemon - the
1954
1985
  // user never triggers `hmh evolve` manually (zero-config direction fix)
1955
1986
  try {
@@ -1962,7 +1993,7 @@ flags:
1962
1993
  stdout.write(t.webRunning(r.pid, port) + '\n');
1963
1994
  }
1964
1995
  else {
1965
- stdout.write(t.webStarted(Number.isFinite(port) ? port : 7788, join(homeDir(), 'web.log')) + '\n');
1996
+ stdout.write(t.webStarted(port, join(homeDir(), 'web.log')) + '\n');
1966
1997
  }
1967
1998
  return;
1968
1999
  }
@@ -1973,7 +2004,7 @@ flags:
1973
2004
  const ver = cr(import.meta.url)('../package.json').version ?? '';
1974
2005
  try {
1975
2006
  await startServer({
1976
- port: Number.isFinite(port) ? port : 7788,
2007
+ port: port,
1977
2008
  host: exposure === 'loopback' ? '127.0.0.1' : '0.0.0.0',
1978
2009
  version: ver,
1979
2010
  });
@@ -2113,7 +2144,7 @@ flags:
2113
2144
  // cooldown counts real SUBMISSIONS only - a 'staged' row means the last
2114
2145
  // attempt FAILED before creating a job (files parked, nothing trained),
2115
2146
  // so it must not block the retry that finally lands (2026-09-27)
2116
- const lastSubmit = [...localJobs].reverse().find((j) => String(j.status) !== 'staged');
2147
+ const lastSubmit = localJobs.findLast((j) => String(j.status) !== 'staged');
2117
2148
  const lastAt = lastSubmit ? new Date(lastSubmit.time).getTime() : 0;
2118
2149
  const dueMs = cooldownDays * 86400000;
2119
2150
  if (Date.now() - lastAt < dueMs) {
@@ -2416,7 +2447,10 @@ flags:
2416
2447
  stdout.write('no dpo-pairs.jsonl - run: hmh reward export-dpo\n');
2417
2448
  return;
2418
2449
  }
2419
- const outDir = rest[1] ? require('node:path').resolve(rest[1]) : join(home, 'evolution', 'dpo-export');
2450
+ // (an ESM module has no `require`: with a directory argument this line
2451
+ // threw ReferenceError and the command died)
2452
+ const { resolve: resolvePath } = await import('node:path');
2453
+ const outDir = rest[1] ? resolvePath(rest[1]) : join(home, 'evolution', 'dpo-export');
2420
2454
  const { mkdir, writeFile: wf2 } = await import('node:fs/promises');
2421
2455
  await mkdir(outDir, { recursive: true });
2422
2456
  const train = rows.filter((r) => r.split !== 'eval');
@@ -0,0 +1,11 @@
1
+ export type ProcessIdentity = 'self' | 'other' | 'unknown';
2
+ export declare function isAlive(pid: number): boolean;
3
+ /** Kill a daemon and whatever it spawned. Best effort - a process that is already gone is not an error. */
4
+ export declare function killProcessTree(pid: number): void;
5
+ /** The command line of a process, or null when it cannot be read
6
+ * (not running under this account, no query tool on this platform). */
7
+ export declare function commandLineOf(pid: number): string | null;
8
+ /** Is the live process behind `pid` one of ours, judged by its command line? */
9
+ export declare function identifyProcess(pid: number, isOurs: (commandLine: string) => boolean): ProcessIdentity;
10
+ /** Test hook: forget every remembered identity. */
11
+ export declare function forgetIdentities(): void;
@@ -0,0 +1,77 @@
1
+ /**
2
+ * @hmharness/cli - is that process ours?
3
+ *
4
+ * Every daemon here is managed through a pid file under HMH_HOME, and a pid
5
+ * file outlives its process: a daemon killed on Windows (taskkill, logoff) gets
6
+ * no SIGTERM and never cleans up after itself, and every OS reuses pids. So
7
+ * "the pid is alive" does not mean "the daemon is running" - it may be a
8
+ * stranger wearing the old number. Killing it (`hmh web stop`, the extension
9
+ * watchdog's 60s sweep) is the worst outcome; trusting it is quieter but just
10
+ * as real, because a daemon that "is running" is never started again.
11
+ *
12
+ * The command line tells them apart. It is read with the platform's own tool
13
+ * (PowerShell CIM on Windows, /proc or ps elsewhere). When it cannot be read
14
+ * at all the answer is `unknown`, and each caller then falls back to what it
15
+ * always did - it just no longer acts on a process it can see is not ours.
16
+ */
17
+ import { execSync, spawn } from 'node:child_process';
18
+ import { readFileSync } from 'node:fs';
19
+ export function isAlive(pid) {
20
+ try {
21
+ process.kill(pid, 0);
22
+ return true;
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ }
28
+ /** Kill a daemon and whatever it spawned. Best effort - a process that is already gone is not an error. */
29
+ export function killProcessTree(pid) {
30
+ if (process.platform === 'win32')
31
+ spawn('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true });
32
+ else {
33
+ try {
34
+ process.kill(pid);
35
+ }
36
+ catch { /* gone */ }
37
+ }
38
+ }
39
+ /** The command line of a process, or null when it cannot be read
40
+ * (not running under this account, no query tool on this platform). */
41
+ export function commandLineOf(pid) {
42
+ try {
43
+ if (process.platform === 'win32') {
44
+ const out = execSync(`powershell -NoProfile -Command "(Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}').CommandLine"`, { encoding: 'utf8', timeout: 8000 }).trim();
45
+ return out || null;
46
+ }
47
+ try {
48
+ // Linux: /proc is exact and needs no tool (absent on macOS -> ps)
49
+ return readFileSync(`/proc/${pid}/cmdline`, 'utf8').replace(/\0/g, ' ').trim() || null;
50
+ }
51
+ catch {
52
+ return execSync(`ps -o args= -p ${pid}`, { encoding: 'utf8', timeout: 5000 }).trim() || null;
53
+ }
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
59
+ // A pid's identity does not change while it lives, but one CLI run asks about
60
+ // the same daemon several times (stop, evict, respawn) and each query is a
61
+ // PowerShell start on Windows - remember the answer for a moment.
62
+ const recent = new Map();
63
+ const REMEMBER_MS = 10_000;
64
+ /** Is the live process behind `pid` one of ours, judged by its command line? */
65
+ export function identifyProcess(pid, isOurs) {
66
+ const hit = recent.get(pid);
67
+ if (hit && Date.now() - hit.at < REMEMBER_MS)
68
+ return hit.id;
69
+ const cmd = commandLineOf(pid);
70
+ const id = cmd === null ? 'unknown' : isOurs(cmd) ? 'self' : 'other';
71
+ recent.set(pid, { at: Date.now(), id });
72
+ return id;
73
+ }
74
+ /** Test hook: forget every remembered identity. */
75
+ export function forgetIdentities() {
76
+ recent.clear();
77
+ }
@@ -1,4 +1,8 @@
1
1
  export declare const DEFAULT_WEB_PORT = 7788;
2
+ /** `--port=N` from a command line. Anything else - missing, empty, not a
3
+ * number, out of range - is the caller's default. (`hmh web stop --port=`
4
+ * used to evaluate to port 0 and then stop the DEFAULT instance anyway.) */
5
+ export declare function parsePort(args: string[], fallback: number): number;
2
6
  export declare function readWebPid(): number;
3
7
  /** Probe the SERVED web server: is it up, and what version does the RUNNING
4
8
  * process report? The daemon self-reports its own code version via
@@ -16,7 +16,17 @@ import { createRequire } from 'node:module';
16
16
  import { openSync, readFileSync, unlinkSync, writeFileSync, closeSync, mkdirSync, existsSync } from 'node:fs';
17
17
  import { join } from 'node:path';
18
18
  import { homeDir } from '@hmharness/kernel';
19
+ import { daemonCwd } from "./daemon-cwd.js";
20
+ import { identifyProcess, isAlive, killProcessTree } from "./process-identity.js";
19
21
  export const DEFAULT_WEB_PORT = 7788;
22
+ /** `--port=N` from a command line. Anything else - missing, empty, not a
23
+ * number, out of range - is the caller's default. (`hmh web stop --port=`
24
+ * used to evaluate to port 0 and then stop the DEFAULT instance anyway.) */
25
+ export function parsePort(args, fallback) {
26
+ const raw = args.find((a) => a.startsWith('--port='))?.slice(7);
27
+ const n = Number(raw);
28
+ return raw !== undefined && Number.isInteger(n) && n > 0 && n < 65536 ? n : fallback;
29
+ }
20
30
  export function readWebPid() {
21
31
  try {
22
32
  const p = Number(readFileSync(join(homeDir(), 'web.pid'), 'utf8').trim());
@@ -26,14 +36,21 @@ export function readWebPid() {
26
36
  return 0;
27
37
  }
28
38
  }
29
- function alive(pid) {
30
- try {
31
- process.kill(pid, 0);
32
- return true;
33
- }
34
- catch {
35
- return false;
36
- }
39
+ /** Is the process a WEB daemon of ours (`main.js web --port=`)? Port eviction
40
+ * may ONLY target self-family processes: other hmh surfaces (extension serve,
41
+ * mcp-serve, dev-tree servers) legitimately occupy adjacent ports, and the
42
+ * old blind taskkill kept murdering them on every version-aware restart
43
+ * (the "并行活动又抢了端口" port war). The same test now guards the pid file:
44
+ * a stale web.pid plus a reused pid names a stranger, which `hmh web stop`
45
+ * used to kill (0.23.55). */
46
+ function webDaemonIdentity(pid) {
47
+ return identifyProcess(pid, (cmd) => cmd.includes(' web ') || /main\.js(\.ts)?\s+web\b/.test(cmd) || /\bweb\b\s*--port=/.test(cmd));
48
+ }
49
+ /** May the holder of our port be evicted? Only a daemon we can NAME as ours.
50
+ * Where the command line cannot be read the old platform rule stands:
51
+ * trusted off Windows (no query tool was ever used there), never on Windows. */
52
+ function evictable(id) {
53
+ return id === 'self' || (id === 'unknown' && process.platform !== 'win32');
37
54
  }
38
55
  export async function probeWeb(port) {
39
56
  try {
@@ -68,23 +85,6 @@ function portOwnerPid(port) {
68
85
  catch { /* netstat unavailable - give up quietly */ }
69
86
  return 0;
70
87
  }
71
- /** Is the pid a WEB daemon of ours (`main.js web --port=`)? Port eviction may
72
- * ONLY target self-family processes: other hmh surfaces (extension serve,
73
- * mcp-serve, dev-tree servers) legitimately occupy adjacent ports, and the
74
- * old blind taskkill kept murdering them on every version-aware restart
75
- * (the "并行活动又抢了端口" port war). */
76
- function isSelfWebDaemon(pid) {
77
- if (!pid || process.platform !== 'win32')
78
- return process.platform !== 'win32';
79
- try {
80
- const out = execSync(`powershell -NoProfile -Command "(Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}').CommandLine"`, { encoding: 'utf8', timeout: 8000 });
81
- const cmd = out.trim();
82
- return cmd.includes(' web ') || /main\.js(\.ts)?\s+web\b/.test(cmd) || /\bweb\b\s*--port=/.test(cmd);
83
- }
84
- catch {
85
- return false;
86
- }
87
- }
88
88
  /** Describe a foreign occupier for the warning line (best effort). */
89
89
  function foreignOwnerDesc(pid) {
90
90
  try {
@@ -109,16 +109,16 @@ export async function waitPortFree(port, maxMs = 4000) {
109
109
  export function stopWebDaemon(port = DEFAULT_WEB_PORT) {
110
110
  const pid = readWebPid();
111
111
  let killed = false;
112
- if (pid && alive(pid)) {
113
- if (process.platform === 'win32')
114
- spawn('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true });
112
+ if (pid && isAlive(pid)) {
113
+ // only a daemon of OURS: a stale pid file plus a reused pid names a
114
+ // stranger, and this is the command that used to kill it
115
+ if (webDaemonIdentity(pid) !== 'other') {
116
+ killProcessTree(pid);
117
+ killed = true;
118
+ }
115
119
  else {
116
- try {
117
- process.kill(pid);
118
- }
119
- catch { /* gone */ }
120
+ console.error(`[web] web.pid names pid ${pid}, which is not an hmh web daemon - left alone`);
120
121
  }
121
- killed = true;
122
122
  }
123
123
  try {
124
124
  unlinkSync(join(homeDir(), 'web.pid'));
@@ -128,17 +128,12 @@ export function stopWebDaemon(port = DEFAULT_WEB_PORT) {
128
128
  // one of OUR web daemons - a foreign hmh surface (extension serve,
129
129
  // dev-tree server) owns its port legitimately and must not be murdered
130
130
  const owner = portOwnerPid(port);
131
- if (owner && owner !== pid) {
132
- if (isSelfWebDaemon(owner)) {
133
- try {
134
- spawn('taskkill', ['/PID', String(owner), '/T', '/F'], { windowsHide: true });
135
- killed = true;
136
- }
137
- catch { /* best effort */ }
138
- }
139
- else {
140
- console.error(`[web] port ${port} is held by a NON-web process - not evicting: ${foreignOwnerDesc(owner)}`);
141
- }
131
+ if (owner && owner !== pid && !evictable(webDaemonIdentity(owner))) {
132
+ console.error(`[web] port ${port} is held by a NON-web process - not evicting: ${foreignOwnerDesc(owner)}`);
133
+ }
134
+ else if (owner && owner !== pid) {
135
+ killProcessTree(owner);
136
+ killed = true;
142
137
  }
143
138
  return killed;
144
139
  }
@@ -153,7 +148,9 @@ function spawnWebDaemon(port, entry = process.argv[1], extraArgs = []) {
153
148
  detached: true,
154
149
  stdio: ['ignore', log, log],
155
150
  windowsHide: true,
156
- cwd: process.cwd(),
151
+ // the caller's directory - it seeds the first workspace - but never the
152
+ // installed package's: a live cwd handle there blocks the next upgrade
153
+ cwd: daemonCwd(process.cwd(), entry),
157
154
  });
158
155
  child.unref();
159
156
  // the child inherited a dup; closing ours prevents GC-close fd warnings
@@ -209,10 +206,14 @@ export async function ensureWebDaemon(port = DEFAULT_WEB_PORT, entry = process.a
209
206
  const daemonV = served.version || daemonVersion();
210
207
  const stale = myV !== '' && daemonV !== '' && daemonV !== myV;
211
208
  if (!stale) {
212
- if (pid && alive(pid))
213
- return true;
209
+ // the port answering as hmh is the proof that needs no further query
214
210
  if (served.up)
215
211
  return true;
212
+ // the pid is alive but the port is silent: count it only if it really is one
213
+ // of ours. A stale pid file plus a reused pid used to read as "up" here -
214
+ // nothing served, and nothing started either
215
+ if (pid && isAlive(pid) && webDaemonIdentity(pid) !== 'other')
216
+ return true;
216
217
  }
217
218
  else {
218
219
  // stale daemon: kill it (it may hold the pid OR just the port) and wait
@@ -222,7 +223,7 @@ export async function ensureWebDaemon(port = DEFAULT_WEB_PORT, entry = process.a
222
223
  // a foreign surface still holding the port (stop refused to murder it):
223
224
  // do NOT crash-loop a doomed respawn - say so and stay down
224
225
  const holder = portOwnerPid(port);
225
- if (holder && !isSelfWebDaemon(holder)) {
226
+ if (holder && !evictable(webDaemonIdentity(holder))) {
226
227
  console.error(`[web] port ${port} is held by another process - not evicting: ${foreignOwnerDesc(holder)}`);
227
228
  console.error(`[web] stop it, or start the web UI elsewhere: hmh web --port=<port>`);
228
229
  return false;
@@ -247,7 +248,9 @@ export async function webDaemonStale(port = DEFAULT_WEB_PORT) {
247
248
  }
248
249
  export function startWebDaemon(port = DEFAULT_WEB_PORT, entry = process.argv[1], extraArgs = []) {
249
250
  const pid = readWebPid();
250
- if (pid && alive(pid))
251
+ // "already running" only for a daemon of ours: a stranger behind a stale pid
252
+ // file used to answer every `hmh web start` with "running" while nothing served
253
+ if (pid && isAlive(pid) && webDaemonIdentity(pid) !== 'other')
251
254
  return { already: true, pid };
252
255
  return { already: false, pid: spawnWebDaemon(port, entry, extraArgs) };
253
256
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/cli",
3
- "version": "0.23.52",
3
+ "version": "0.23.55",
4
4
  "description": "hmharness command line: one-shot tasks, an interactive REPL, a fullscreen TUI, the web frontend, and direct tool invocation.",
5
5
  "type": "module",
6
6
  "main": "dist/main.js",
@@ -45,20 +45,20 @@
45
45
  "build": "tsc -p tsconfig.build.json"
46
46
  },
47
47
  "dependencies": {
48
- "@hmharness/agent": "0.23.52",
49
- "@hmharness/browser": "0.23.52",
50
- "@hmharness/cognitive": "0.23.52",
51
- "@hmharness/domain-harmony": "0.23.52",
52
- "@hmharness/domain-ops": "0.23.52",
53
- "@hmharness/environments": "0.23.52",
54
- "@hmharness/evaluation": "0.23.52",
55
- "@hmharness/evolution": "0.23.52",
56
- "@hmharness/extension": "0.23.52",
57
- "@hmharness/kernel": "0.23.52",
58
- "@hmharness/observability": "0.23.52",
59
- "@hmharness/sandbox": "0.23.52",
60
- "@hmharness/web": "0.23.52",
48
+ "@hmharness/agent": "0.23.55",
49
+ "@hmharness/browser": "0.23.55",
50
+ "@hmharness/cognitive": "0.23.55",
51
+ "@hmharness/domain-harmony": "0.23.55",
52
+ "@hmharness/domain-ops": "0.23.55",
53
+ "@hmharness/environments": "0.23.55",
54
+ "@hmharness/evaluation": "0.23.55",
55
+ "@hmharness/evolution": "0.23.55",
56
+ "@hmharness/extension": "0.23.55",
57
+ "@hmharness/kernel": "0.23.55",
58
+ "@hmharness/observability": "0.23.55",
59
+ "@hmharness/sandbox": "0.23.55",
60
+ "@hmharness/web": "0.23.55",
61
61
  "qrcode": "^1.5.4",
62
- "@hmharness/lsp": "0.23.52"
62
+ "@hmharness/lsp": "0.23.55"
63
63
  }
64
64
  }
@@ -1,5 +1,15 @@
1
1
  {
2
2
  "notes": [
3
+ {
4
+ "v": "0.23.55",
5
+ "date": "2026-11-26",
6
+ "note": "全面复查修复批:网页端\"询问\"被忽略/状态刷新崩溃/流中停止显示报错/工作区移除返回旧列表/执行器退出崩溃,排队提示、回合卡片、文件树键盘、手机抽屉、当前工作区移除按钮;hmh --version、web stop 一并停进化守护并真正使用 --port、三个守护按命令行核身份(不误杀)、守护工作目录、ESM 裸 require 三处;finish_reason 贯通(截断答复有提示)、write_file 自动建父目录;证据清单哈希修正并以已提交字节为准、严格审计进 CI"
7
+ },
8
+ {
9
+ "v": "0.23.53",
10
+ "date": "2026-11-26",
11
+ "note": "现代 Web 改造:网页端随机数 CSP + 安全头 + 无障碍(去 GSAP CDN,修 Shift+Enter 换行与命令面板输入法回车);官网去 CDN + 动效开关 + 地标/跳转链接,320–1280 零横向溢出;扩展侧栏无障碍;1126 测试"
12
+ },
3
13
  {
4
14
  "v": "0.23.52",
5
15
  "date": "2026-11-25",