@marktrue/dsh-mobile-remote 3.2.4-alpha.9 → 3.2.4-rc.1

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.
@@ -89,14 +89,22 @@ export async function resolveNpmUpdateCandidate({ packageName, localVersion, pac
89
89
  }
90
90
  record(`→ ${channel.channel}=${candidateVersion}`);
91
91
 
92
- let plugin;
92
+ // issue #96:dist-tags 只取一次;插件与 carrier 元数据**并行**取(两者版本都可从
93
+ // dist-tag 候选版本推出),把总检查耗时压到一次 npm view 的量级。
94
+ const carrierVersion = appCarrierVersion(candidateVersion);
95
+ const alias = appCarrierAlias(packageName);
96
+ const expectedAliasSpec = `npm:${packageName}@${carrierVersion}`;
93
97
  record(`$ npm view ${packageName}@${candidateVersion} --json`);
94
- try {
95
- plugin = await packageView(`${packageName}@${candidateVersion}`);
96
- } catch (error) {
97
- record(`→ 失败:${viewFailureReason(error)}`);
98
+ record(`$ npm view ${packageName}@${carrierVersion} --json`);
99
+ const [pluginOutcome, carrierOutcome] = await Promise.all([
100
+ packageView(`${packageName}@${candidateVersion}`).then((value) => ({ ok: true, value }), (error) => ({ ok: false, error })),
101
+ packageView(`${packageName}@${carrierVersion}`).then((value) => ({ ok: true, value }), (error) => ({ ok: false, error })),
102
+ ]);
103
+ if (!pluginOutcome.ok) {
104
+ record(`→ 失败:${viewFailureReason(pluginOutcome.error)}`);
98
105
  return { ok: false, reason: "npm-plugin-metadata-unavailable" };
99
106
  }
107
+ const plugin = pluginOutcome.value;
100
108
  if (!plugin || plugin.version !== candidateVersion) {
101
109
  record(`→ 版本不符:${String(plugin?.version ?? "缺失")} ≠ ${candidateVersion}`);
102
110
  return { ok: false, reason: "npm-plugin-version-mismatch" };
@@ -107,23 +115,15 @@ export async function resolveNpmUpdateCandidate({ packageName, localVersion, pac
107
115
  return { ok: false, reason: "npm-plugin-integrity-missing" };
108
116
  }
109
117
  record(`→ 插件 v${candidateVersion}`);
110
-
111
- const carrierVersion = appCarrierVersion(candidateVersion);
112
- const alias = appCarrierAlias(packageName);
113
- const expectedAliasSpec = `npm:${packageName}@${carrierVersion}`;
114
118
  if (plugin.optionalDependencies?.[alias] !== expectedAliasSpec) {
115
119
  record(`→ 载体别名不匹配:${String(plugin.optionalDependencies?.[alias] ?? "缺失")}(期望 ${expectedAliasSpec})`);
116
120
  return { ok: false, reason: "npm-carrier-alias-mismatch" };
117
121
  }
118
-
119
- let carrier;
120
- record(`$ npm view ${packageName}@${carrierVersion} --json`);
121
- try {
122
- carrier = await packageView(`${packageName}@${carrierVersion}`);
123
- } catch (error) {
124
- record(`→ 失败:${viewFailureReason(error)}`);
122
+ if (!carrierOutcome.ok) {
123
+ record(`→ 失败:${viewFailureReason(carrierOutcome.error)}`);
125
124
  return { ok: false, reason: "npm-carrier-metadata-unavailable" };
126
125
  }
126
+ const carrier = carrierOutcome.value;
127
127
  if (!carrier || carrier.version !== carrierVersion) {
128
128
  record(`→ 版本不符:${String(carrier?.version ?? "缺失")} ≠ ${carrierVersion}`);
129
129
  return { ok: false, reason: "npm-carrier-version-mismatch" };
@@ -1063,20 +1063,34 @@ export async function runSelfUpdate({
1063
1063
  * 但**任何非终态**(staging / installing / restart-pending)在持有者已死且超时后
1064
1064
  * 都必须收敛为 FAILED,否则后续更新会永久 busy。
1065
1065
  */
1066
- export function reportPendingUpdate({ stateFile, lockPath = "", localContentSha256 = "", supervisorAlive = false, timeoutMs = 10 * 60 * 1000, now = () => Date.now() } = {}) {
1066
+ export function reportPendingUpdate({ stateFile, lockPath = "", localContentSha256 = "", holderAlive = false, supervisorAlive = false, timeoutMs = 10 * 60 * 1000, now = () => Date.now() } = {}) {
1067
1067
  const tx = readTransaction(stateFile);
1068
1068
  if (!tx) return { action: "none", reason: "no-transaction", transaction: null };
1069
1069
  if (isTerminalPhase(tx.phase)) return { action: "none", reason: `phase-${tx.phase}`, transaction: tx };
1070
1070
  if (tx.phase === TRANSACTION_PHASE.RESTART_PENDING) {
1071
1071
  const target = String(tx.targetContentSha256 ?? "").toLowerCase();
1072
1072
  if (target !== "" && String(localContentSha256 ?? "").toLowerCase() === target) {
1073
+ // issue #110 P1-B:内容已生效且 holder 已死 → 启动方可认领并结算;
1074
+ // holder 仍活着时插件只报告,不抢监督器。
1075
+ if (!holderAlive) {
1076
+ return { action: "adoptable", reason: "loaded-target-content-adopted", transaction: tx };
1077
+ }
1073
1078
  return { action: "matched", reason: "loaded-target-content", transaction: tx };
1074
1079
  }
1075
1080
  }
1076
1081
  if (!lockPath) return { action: "waiting", reason: "no-lock-path", transaction: tx };
1077
- const converged = convergeStaleTransaction({ stateFile, lockPath, now, staleMs: timeoutMs });
1082
+ const converged = convergeStaleTransaction({
1083
+ stateFile,
1084
+ lockPath,
1085
+ localContentSha256,
1086
+ now,
1087
+ staleMs: timeoutMs,
1088
+ });
1089
+ if (converged.action === "settled") {
1090
+ return { action: "matched", reason: "loaded-target-content-adopted", transaction: converged.transaction };
1091
+ }
1078
1092
  if (converged.action === "converged") {
1079
- return { action: "expired", reason: "holder-gone", transaction: converged.transaction };
1093
+ return { action: "expired", reason: "converged-after-holder-gone", transaction: converged.transaction };
1080
1094
  }
1081
1095
  if (converged.action === "active") {
1082
1096
  return { action: "waiting", reason: supervisorAlive ? "supervisor-running" : "update-in-progress", transaction: tx };
@@ -0,0 +1,268 @@
1
+ // issue #96:插件更新检查快照 + 有界异步检查任务。
2
+ //
3
+ // - 一次检查总 deadline(默认 12s)严格小于旧 App 的 15s 兼容窗口;
4
+ // 单次 npm view 仍可 20s,但整次检查 race 到 deadline 时返回明确 check-timeout,
5
+ // 绝不返回半结果。
6
+ // - 成功快照 5min、失败/unavailable 30s;force 绕过读缓存;cache key 含更新源/本地版本,
7
+ // 源配置或本地版本变化自然失效;宿主更新成功后调用 invalidate()。
8
+ // - 异步任务只存内存 map + TTL;同 key in-flight 去重;不持久化、不复用更新事务。
9
+ import { randomUUID } from "node:crypto";
10
+
11
+ export const UPDATE_CHECK_STATE = Object.freeze({
12
+ CHECKING: "checking",
13
+ DONE: "done",
14
+ ERROR: "error",
15
+ });
16
+
17
+ const TIMEOUT_RESULT = {
18
+ state: "unavailable",
19
+ reason: "check-timeout",
20
+ source: "npm",
21
+ };
22
+
23
+ function isFailureResult(result) {
24
+ return result?.state !== "update-available" && result?.state !== "up-to-date" && result?.state !== "local-ahead";
25
+ }
26
+
27
+ /**
28
+ * @param {object} options
29
+ * @param {() => Promise<object>} options.checkFn 真正的 update check(不得自行吞掉总超时)
30
+ * @param {() => string} [options.cacheKey] 更新源/本地版本指纹
31
+ * @param {number} [options.checkTimeoutMs] 整次检查 deadline;必须 < 15000
32
+ * @param {number} [options.successTtlMs]
33
+ * @param {number} [options.failureTtlMs]
34
+ * @param {number} [options.taskTtlMs] checkId 结果保留时长
35
+ */
36
+ export function createUpdateCheckService({
37
+ checkFn,
38
+ cacheKey = () => "",
39
+ checkTimeoutMs = 12_000,
40
+ successTtlMs = 5 * 60 * 1000,
41
+ failureTtlMs = 30 * 1000,
42
+ taskTtlMs = 10 * 60 * 1000,
43
+ now = () => Date.now(),
44
+ newCheckId = () => randomUUID(),
45
+ } = {}) {
46
+ if (typeof checkFn !== "function") throw new TypeError("checkFn is required");
47
+ // 成功快照与失败短缓存分开:失败结果不进入“更新检查快照”(CONTEXT 契约),
48
+ // 只有成功结果可供展示/提交复用;失败/unavailable 单独 30s 短缓存防止风暴。
49
+ const snapshot = { key: "", result: null, at: 0 };
50
+ const failureCache = { key: "", result: null, at: 0 };
51
+ const tasks = new Map();
52
+ let activeTask = null;
53
+ let inFlight = null; // { key, promise }
54
+ // 代际:invalidate/强制重查后旧 runCheck 的迟到写回必须被丢弃。
55
+ let generation = 0;
56
+
57
+ function freshResult(key) {
58
+ if (snapshot.result !== null &&
59
+ snapshot.key === key &&
60
+ now() - snapshot.at < successTtlMs) return snapshot.result;
61
+ if (failureCache.result !== null &&
62
+ failureCache.key === key &&
63
+ now() - failureCache.at < failureTtlMs) return failureCache.result;
64
+ return null;
65
+ }
66
+
67
+ function staleResult() {
68
+ return {
69
+ state: "unavailable",
70
+ reason: "check-stale",
71
+ source: "npm",
72
+ checkedAt: new Date().toISOString(),
73
+ };
74
+ }
75
+ function rememberFailure(key, result) {
76
+ failureCache.key = key;
77
+ failureCache.result = result;
78
+ failureCache.at = now();
79
+ // 更新检查失败后,旧成功快照不再代表当前检查结果,必须失效。
80
+ snapshot.result = null;
81
+ snapshot.key = "";
82
+ snapshot.at = 0;
83
+ }
84
+ function rememberSuccess(key, result) {
85
+ snapshot.key = key;
86
+ snapshot.result = result;
87
+ snapshot.at = now();
88
+ failureCache.result = null;
89
+ failureCache.key = "";
90
+ failureCache.at = 0;
91
+ }
92
+
93
+ function timeoutError() {
94
+ return Object.assign(new Error("check-timeout"), { code: "check-timeout" });
95
+ }
96
+
97
+ function runWithDeadline() {
98
+ let timer = null;
99
+ const deadline = new Promise((_, reject) => {
100
+ timer = setTimeout(() => reject(timeoutError()), checkTimeoutMs);
101
+ timer.unref?.();
102
+ });
103
+ return Promise.race([Promise.resolve().then(checkFn), deadline]).finally(() => {
104
+ if (timer) clearTimeout(timer);
105
+ });
106
+ }
107
+
108
+ async function runCheck(key, runGeneration) {
109
+ let result;
110
+ try {
111
+ result = await runWithDeadline();
112
+ if (result?.state === "checking") return result;
113
+ } catch (error) {
114
+ if (error?.code === "check-timeout") {
115
+ result = { ...TIMEOUT_RESULT, checkedAt: new Date().toISOString() };
116
+ } else {
117
+ // review P2:checkFn 任意异常都脱敏成稳定失败结果并进入失败短缓存,
118
+ // 不原样返回 message,也避免连续两次 throw 都打 npm。
119
+ result = {
120
+ state: "unavailable",
121
+ reason: "check-failed",
122
+ source: "npm",
123
+ checkedAt: new Date().toISOString(),
124
+ };
125
+ }
126
+ }
127
+ if (!result || typeof result !== "object") {
128
+ result = {
129
+ state: "unavailable",
130
+ reason: "check-failed",
131
+ source: "npm",
132
+ checkedAt: new Date().toISOString(),
133
+ };
134
+ }
135
+ const stamped = typeof result.checkedAt === "string" ? result : { ...result, checkedAt: new Date().toISOString() };
136
+ // 旧代结果不写缓存,但调用方必须拿到明确的非 null stale 结果(可重试)。
137
+ if (runGeneration !== generation) return staleResult();
138
+ if (isFailureResult(stamped)) rememberFailure(key, stamped);
139
+ else rememberSuccess(key, stamped);
140
+ return stamped;
141
+ }
142
+
143
+ async function check({ force = false } = {}) {
144
+ const key = String(cacheKey() ?? "");
145
+ if (!force) {
146
+ const cached = freshResult(key);
147
+ if (cached) return cached;
148
+ }
149
+ // bootstrap + 立即 force:仍复用同一个 in-flight(不重复出网)。
150
+ if (inFlight && inFlight.key === key) return inFlight.promise;
151
+ // force 且没有可复用 in-flight:换代,旧在途结果不得回填。
152
+ if (force) generation += 1;
153
+ const runGeneration = generation;
154
+ const promise = (async () => {
155
+ try {
156
+ return await runCheck(key, runGeneration);
157
+ } finally {
158
+ if (inFlight?.promise === promise) inFlight = null;
159
+ }
160
+ })();
161
+ inFlight = { key, promise };
162
+ return promise;
163
+ }
164
+
165
+ function scheduleTaskExpiry(task) {
166
+ const timer = setTimeout(() => {
167
+ if (tasks.get(task.checkId) === task) tasks.delete(task.checkId);
168
+ }, taskTtlMs);
169
+ timer.unref?.();
170
+ task.expiryTimer = timer;
171
+ if (activeTask === task) activeTask = null;
172
+ return () => clearTimeout(timer);
173
+ }
174
+
175
+ function startAsync({ force = false } = {}) {
176
+ const key = String(cacheKey() ?? "");
177
+ if (activeTask && activeTask.state === UPDATE_CHECK_STATE.CHECKING && activeTask.key === key) {
178
+ return { state: UPDATE_CHECK_STATE.CHECKING, checkId: activeTask.checkId };
179
+ }
180
+ const checkId = newCheckId();
181
+ const task = {
182
+ checkId,
183
+ key,
184
+ state: UPDATE_CHECK_STATE.CHECKING,
185
+ startedAt: now(),
186
+ result: null,
187
+ error: null,
188
+ promise: null,
189
+ expiryTimer: null,
190
+ };
191
+ tasks.set(checkId, task);
192
+ activeTask = task;
193
+ // 异步任务与同步 GET 共享同一个 check promise(含 deadline、缓存、in-flight 去重)。
194
+ task.promise = check({ force }).then(
195
+ (result) => {
196
+ task.result = result;
197
+ task.state = UPDATE_CHECK_STATE.DONE;
198
+ task.finishedAt = now();
199
+ scheduleTaskExpiry(task);
200
+ return result;
201
+ },
202
+ (error) => {
203
+ task.state = UPDATE_CHECK_STATE.ERROR;
204
+ // issue #96 review P2:HTTP 只回稳定 code,绝不返回 error.message(可能含路径)。
205
+ task.error = error?.code === "check-timeout" ? "check-timeout" : "check-failed";
206
+ task.finishedAt = now();
207
+ scheduleTaskExpiry(task);
208
+ return null;
209
+ },
210
+ );
211
+ return { state: UPDATE_CHECK_STATE.CHECKING, checkId };
212
+ }
213
+
214
+ function getAsync(checkId) {
215
+ const task = tasks.get(String(checkId ?? ""));
216
+ if (!task) return { status: 404, body: { state: "error", error: "check-not-found" } };
217
+ if (task.state === UPDATE_CHECK_STATE.CHECKING) {
218
+ const age = now() - (task.startedAt ?? now());
219
+ if (age > taskTtlMs) {
220
+ tasks.delete(task.checkId);
221
+ return { status: 410, body: { state: "error", error: "check-expired" } };
222
+ }
223
+ return { status: 200, body: { state: "checking", checkId: task.checkId } };
224
+ }
225
+ if (task.state === UPDATE_CHECK_STATE.ERROR) {
226
+ return { status: 200, body: { state: "error", checkId: task.checkId, error: task.error } };
227
+ }
228
+ return { status: 200, body: { state: "done", checkId: task.checkId, result: task.result } };
229
+ }
230
+
231
+ async function checkSync() {
232
+ return check({ force: false });
233
+ }
234
+
235
+ async function checkForSubmit() {
236
+ // 优先 5min 成功快照;过期时等待当前 async 任务(同一 in-flight)或启动有 deadline 检查。
237
+ return check({ force: false });
238
+ }
239
+
240
+ function invalidate() {
241
+ generation += 1;
242
+ snapshot.result = null;
243
+ snapshot.key = "";
244
+ snapshot.at = 0;
245
+ failureCache.result = null;
246
+ failureCache.key = "";
247
+ failureCache.at = 0;
248
+ // issue #96 review P2:同时清掉 checkId 结果与 in-flight 去重;旧 checkId 不再 done。
249
+ for (const task of tasks.values()) {
250
+ if (task.expiryTimer) clearTimeout(task.expiryTimer);
251
+ }
252
+ tasks.clear();
253
+ activeTask = null;
254
+ inFlight = null;
255
+ }
256
+
257
+ return {
258
+ check,
259
+ checkSync,
260
+ checkForSubmit,
261
+ startAsync,
262
+ getAsync,
263
+ invalidate,
264
+ snapshot: () => snapshot.result,
265
+ failureSnapshot: () => failureCache.result,
266
+ _checkTimeoutMs: checkTimeoutMs,
267
+ };
268
+ }
@@ -7,6 +7,7 @@ import { acquireLock, newOperationId, readTransaction, releaseLock, serverOperat
7
7
  transactionFile, updateLockPath, validOperationId, writeOwnedTransaction, convergeStaleTransaction, workRoot } from './plugin-update-transaction.js';
8
8
  import { checkForUpdate, prepareNpmArtifacts, runSelfUpdate, isTerminalPhase, resolvePluginUpdateSource, UPDATE_SOURCE_KIND } from './plugin-self-update.js';
9
9
  import { createOperationLog } from './plugin-update-log.js';
10
+ import { createUpdateCheckService } from './plugin-update-check.js';
10
11
 
11
12
  /// 客户端可达视图:只改写属于**本机回环主机源**的 artifact 路由,外部发布源保持原样(F1)。
12
13
  export function clientReleaseView(release, { clientOrigin = '', basePath = '/m', loopback = false } = {}) {
@@ -40,6 +41,8 @@ export function publicTransaction(tx, view = {}) {
40
41
  export function createPluginUpdateController(options) {
41
42
  const { home = homedir(), configValue, profileDir, packageName = '', npmPackageView, capabilities, localVersion, localContentSha256,
42
43
  status, log = () => {}, fetchImpl = fetch, auth = {}, basePath = '/m', workerOptions = {},
44
+ checkTimeoutMs = 12_000, checkSuccessTtlMs = 5 * 60 * 1000, checkFailureTtlMs = 30 * 1000,
45
+ asyncCheckTtlMs = 10 * 60 * 1000,
43
46
  schedule = fn => setImmediate(fn), runSelfUpdate: runner = runSelfUpdate, prepareNpmArtifacts: prepareRunner = prepareNpmArtifacts,
44
47
  runHostUpdate: hostRunner, persist = writeOwnedTransaction } = options;
45
48
  // 只有调用方显式提供宿主更新执行器时才启用该通道(旧宿主/测试不提供即自动关闭)。
@@ -84,9 +87,19 @@ export function createPluginUpdateController(options) {
84
87
  } catch { /* cleanup is best-effort; never disrupt update checks */ }
85
88
  };
86
89
  cleanupPreparedUpdates();
90
+ const localContentNow = () => (typeof localContentSha256 === 'function' ? localContentSha256() : localContentSha256);
87
91
  const checking = () => checkForUpdate({ configValue, packageName, npmCwd: profileDir, npmPackageView,
88
- localVersion: typeof localVersion === 'function' ? localVersion() : localVersion, localContentSha256,
92
+ localVersion: typeof localVersion === 'function' ? localVersion() : localVersion, localContentSha256: localContentNow(),
89
93
  capabilities: capabilities(), fetchImpl, auth });
94
+ // issue #96:检查快照 + 有界异步任务(只读、内存、不持久化)。
95
+ const checkService = createUpdateCheckService({
96
+ checkFn: checking,
97
+ cacheKey: () => `${configValue}|${typeof localVersion === 'function' ? localVersion() : localVersion}|${localContentSha256 ?? ''}`,
98
+ checkTimeoutMs,
99
+ successTtlMs: checkSuccessTtlMs,
100
+ failureTtlMs: checkFailureTtlMs,
101
+ taskTtlMs: asyncCheckTtlMs,
102
+ });
90
103
  /// 手机视图:**只用于 HTTP 出口**,绝不写回内部事务(F1)。
91
104
  /// 内部 worker 必须继续用受信定位;当前 NPM 来源不会把 registry URL 投影给客户端。
92
105
  const clientView = clientOrigin => ({
@@ -109,7 +122,7 @@ export function createPluginUpdateController(options) {
109
122
  } };
110
123
  const old = readTransaction(currentFile);
111
124
  if (old && !isTerminalPhase(old.phase)) return { status: 409, body: { error: 'update-busy', transaction: publicTransaction(old) } };
112
- const checked = await checking(); Object.assign(status, checked);
125
+ const checked = await checkService.checkForSubmit(); Object.assign(status, checked);
113
126
  if (checked.state !== 'update-available') return { status: 200, body: { ok: true, action: 'none', check: checked } };
114
127
  const candidate = checked.candidate;
115
128
  if (!candidate?.carrier?.legacyMetadataMissing) {
@@ -170,11 +183,43 @@ export function createPluginUpdateController(options) {
170
183
  if (old && body.opId === old.opId) return { status: 200, body: { ok: true, action: 'accepted', opId: old.opId,
171
184
  transaction: publicTransaction(old, view), check: { ...status, release: clientReleaseView(status.release, view) } } };
172
185
  if (old && !isTerminalPhase(old.phase)) {
173
- const convergence = convergeStaleTransaction({ stateFile: currentFile, lockPath });
174
- if (!['converged','terminal'].includes(convergence.action)) return { status: 409, body: {
186
+ // issue #110 P3:收敛时带上当前运行内容哈希,避免把已生效的旧 restart-pending 一律 failed。
187
+ const convergence = convergeStaleTransaction({
188
+ stateFile: currentFile,
189
+ lockPath,
190
+ localContentSha256: localContentNow() ?? '',
191
+ });
192
+ if (!['converged','settled','terminal'].includes(convergence.action)) return { status: 409, body: {
175
193
  error: convergence.action === 'recovery-required' ? 'recovery-required' : 'update-busy', transaction: publicTransaction(old, view) } };
176
194
  }
177
- const checked = await checking(); Object.assign(status, checked);
195
+ let checked = await checkService.checkForSubmit(); Object.assign(status, checked);
196
+ // issue #96 review P2:检查本身不可用/超时时如实返回 503 check-unavailable,
197
+ // 不得被 targetVersion 比对误判成 candidate-changed,也不无意义重查。
198
+ if (checked.state === 'unavailable') {
199
+ return { status: 503, body: {
200
+ error: 'check-unavailable',
201
+ reason: checked.reason ?? 'update-check-unavailable',
202
+ check: checked,
203
+ } };
204
+ }
205
+ // 只有成功检查且 targetVersion 与候选确实不同,才强制重查一次;仍不同才 409。
206
+ if (typeof body.targetVersion === 'string') {
207
+ const snapshotTarget = () => checked.release?.plugin ?? checked.candidate?.plugin;
208
+ if (!snapshotTarget() || snapshotTarget()?.version !== body.targetVersion) {
209
+ checked = await checkService.check({ force: true });
210
+ Object.assign(status, checked);
211
+ if (checked.state === 'unavailable') {
212
+ return { status: 503, body: {
213
+ error: 'check-unavailable',
214
+ reason: checked.reason ?? 'update-check-unavailable',
215
+ check: checked,
216
+ } };
217
+ }
218
+ if (!snapshotTarget() || snapshotTarget()?.version !== body.targetVersion) {
219
+ return { status: 409, body: { error: 'candidate-changed', check: checked } };
220
+ }
221
+ }
222
+ }
178
223
  // **内部 release 原样保留**(持久化与 worker 都用它);只有响应体走手机视图。
179
224
  if (checked.state !== 'update-available') {
180
225
  return { status: 200, body: { ok: true, action: 'none', check: { ...checked, release: clientReleaseView(checked.release, view) } } };
@@ -220,6 +265,7 @@ export function createPluginUpdateController(options) {
220
265
  finishOwnedTerminal(stateFile, { phase: 'settled', result: { ok: true, matched: 'host-manager' } },
221
266
  { lockPath, lease, currentFile });
222
267
  Object.assign(status, { state: 'up-to-date', reason: 'host-manager-applied', opId });
268
+ checkService.invalidate();
223
269
  } else {
224
270
  const reason = safeUpdateReason(run.reason);
225
271
  operationLog.setStage('failed', `Host plugin manager update failed: ${reason}`);
@@ -312,6 +358,7 @@ export function createPluginUpdateController(options) {
312
358
  if (run.ok) {
313
359
  operationLog.setStage('restart', 'Plugin install finished; waiting for host restart and health confirmation.');
314
360
  Object.assign(status, { state: 'restarting', reason: 'update-staged', opId });
361
+ checkService.invalidate();
315
362
  } else {
316
363
  const reason = safeUpdateReason(run.error);
317
364
  // 失败原因必须进日志:详情页要能直接看到,而不是只有一句“看安装输出”。
@@ -336,5 +383,14 @@ export function createPluginUpdateController(options) {
336
383
  return { status: 200, body: { ok: true, action: 'accepted', opId,
337
384
  transaction: publicTransaction(tx, view), check: { ...effectiveCheck, release: clientReleaseView(effectiveCheck.release, view) } } };
338
385
  }
339
- return { submit, check: checking, prepare };
386
+ return {
387
+ submit,
388
+ check: checking,
389
+ prepare,
390
+ checkSync: () => checkService.checkSync(),
391
+ checkForSubmit: () => checkService.checkForSubmit(),
392
+ startAsyncCheck: (options) => checkService.startAsync(options),
393
+ getAsyncCheck: (checkId) => checkService.getAsync(checkId),
394
+ invalidateCheck: () => checkService.invalidate(),
395
+ };
340
396
  }
@@ -105,8 +105,8 @@ export function clearTransaction(file) {
105
105
  }
106
106
 
107
107
  /** Converge only under the same OS arbitration as acquire/release/state writes. */
108
- export function convergeStaleTransaction({ stateFile, lockPath, expectedLease, now = () => Date.now(), staleMs = 600_000 } = {}) {
109
- const result = arbitrate(lockPath, { operation: "converge", stateFile, expectedLease, now: now(), staleMs });
108
+ export function convergeStaleTransaction({ stateFile, lockPath, expectedLease, localContentSha256 = "", now = () => Date.now(), staleMs = 600_000 } = {}) {
109
+ const result = arbitrate(lockPath, { operation: "converge", stateFile, expectedLease, localContentSha256, now: now(), staleMs });
110
110
  if (!result.ok) return { action: "blocked", error: result.error, transaction: readTransaction(stateFile) };
111
111
  return result;
112
112
  }
@@ -198,6 +198,42 @@ export function defaultIsPidAlive(pid) {
198
198
  if (!Number.isInteger(pid) || pid <= 0) return false;
199
199
  try { process.kill(pid, 0); return true; } catch(e) { return e.code === "EPERM"; }
200
200
  }
201
+
202
+ /** `/proc/<pid>/stat` 的 starttime(field 22);读不到返回 null。 */
203
+ export function processStartTime(pid) {
204
+ if (!Number.isInteger(pid) || pid <= 0) return null;
205
+ try {
206
+ const text = readFileSync(`/proc/${pid}/stat`, "utf8");
207
+ return text.slice(text.lastIndexOf(")") + 2).split(" ")[19] ?? null;
208
+ } catch {
209
+ return null;
210
+ }
211
+ }
212
+
213
+ /**
214
+ * issue #110 P1:按 `/proc/<pid>/stat` starttime 判断记录里的进程身份是否仍存活,
215
+ * 不能只用 kill(pid,0)(容器重建后 pid 会被复用)。
216
+ * - 记录带 start:必须与当前 starttime 完全一致;
217
+ * - 旧 holder 无 start:只能保守认为可能存活(不据此认领);
218
+ * - procfs 不可读:视为不存活。
219
+ */
220
+ export function processIdentityAlive(person) {
221
+ if (!person || !Number.isInteger(person.pid) || person.pid <= 0) return false;
222
+ const current = processStartTime(person.pid);
223
+ // 无 procfs(或 /proc/<pid> 读不到)时退回 kill(pid,0):宁可保守判活,不能误认领。
224
+ if (current === null) return defaultIsPidAlive(person.pid);
225
+ if (!person.start) return true;
226
+ return String(person.start) === String(current);
227
+ }
228
+
229
+ /** 锁 holder(worker/supervisor 任一)是否仍存活;用于启动认领判定。 */
230
+ export function lockHolderAlive(dir) {
231
+ const holder = readLock(dir);
232
+ if (!holder) return false;
233
+ if ([holder.worker, holder.supervisor].some(processIdentityAlive)) return true;
234
+ // 旧 holder 只写 pid(无 starttime):按 pid 保守判活,避免把活监督器当死。
235
+ return Number.isInteger(holder.pid) && processIdentityAlive({ pid: holder.pid, start: holder.start });
236
+ }
201
237
  export function lockHeld(dir) { return readLock(dir) !== null; }
202
238
  export function acquireLock(dir, { opId, pid = process.pid, now = Date.now(), lease, stateFile } = {}) {
203
239
  if (!validOperationId(opId)) return { ok: false, error: "invalid-operation-id" };
@@ -14,10 +14,23 @@ function identity(pid) {
14
14
  try { const text = readFileSync(`/proc/${pid}/stat`, 'utf8'); return { pid, start: text.slice(text.lastIndexOf(')') + 2).split(' ')[19] }; }
15
15
  catch { return { pid, start: null }; }
16
16
  }
17
+ function killAlive(pid) {
18
+ try { process.kill(pid, 0); return true; } catch(e) { return e.code === 'EPERM'; }
19
+ }
17
20
  function alive(person) {
18
21
  if (!person?.pid || !Number.isInteger(person.pid)) return false;
19
- try { process.kill(person.pid, 0); } catch(e) { return e.code === 'EPERM'; }
20
- return !person.start || identity(person.pid).start === person.start;
22
+ const current = identity(person.pid).start;
23
+ // 无 /proc 平台:回退 kill(pid,0) 保守判活,与 processIdentityAlive 口径一致。
24
+ if (current === null) return killAlive(person.pid);
25
+ if (!person.start) return true;
26
+ return String(person.start) === String(current);
27
+ }
28
+ function holderAlive(holder) {
29
+ if (!holder) return false;
30
+ const candidates = [holder.worker, holder.supervisor];
31
+ // 旧 holder 兼容:只有顶层 pid/starttime。
32
+ if (Number.isInteger(holder.pid)) candidates.push({ pid: holder.pid, start: holder.start });
33
+ return candidates.some(alive);
21
34
  }
22
35
  function owns(holder, lease) { return !!lease?.generation && holder?.generation === lease.generation && holder.opId === lease.opId; }
23
36
  function fence(holder, lease) { if (!owns(holder, lease)) throw new Error('lease-lost'); }
@@ -27,7 +40,7 @@ function execute(input) {
27
40
  const { lockPath, operation, lease, stateFile } = input;
28
41
  const holderFile = join(lockPath, 'holder.json');
29
42
  let holder = read(holderFile);
30
- const available = !holder || ![holder.worker, holder.supervisor].some(alive);
43
+ const available = !holderAlive(holder);
31
44
  if (operation === 'acquire') {
32
45
  if (holder && owns(holder, lease)) return { ok: true, lease, holder, reentrant: true };
33
46
  // Missing publication is not evidence of owner death. Legacy half-locks require manual repair.
@@ -154,10 +167,37 @@ function execute(input) {
154
167
  if (!tx) return { ok: true, action: 'none', transaction: null };
155
168
  if (terminal(tx.phase)) return { ok: true, action: 'terminal', transaction: tx };
156
169
  if (input.expectedLease && !owns(holder, input.expectedLease)) return { ok: true, action: 'superseded', transaction: tx };
157
- if (holder && [holder.worker, holder.supervisor].some(alive)) return { ok: true, action: 'active', transaction: tx };
158
- if (existsSync(lockPath) && !existsSync(holderFile)) return { ok: true, action: 'recent', transaction: tx };
170
+ if (holderAlive(holder)) return { ok: true, action: 'active', transaction: tx };
171
+ // holder.json 缺失:restart-pending 仍需按 stale 结算(不能因缺 holder 永久 recent);
172
+ // 其他阶段维持保守 recent。
173
+ if (existsSync(lockPath) && !existsSync(holderFile) && tx.phase !== 'restart-pending') {
174
+ return { ok: true, action: 'recent', transaction: tx };
175
+ }
176
+ // issue #110 P1-C:restart-pending + holder 全死 + stale:
177
+ // - 运行内容 == target → settled(保留 artifact/snapshot 元数据,不假称回滚成功);
178
+ // - 内容不匹配 → failed(confirmation-lost),不无限 pending。
179
+ if (tx.phase === 'restart-pending') {
180
+ const startedAt = Date.parse(tx.startedAt ?? tx.updatedAt ?? '');
181
+ // 缺时间戳视为 stale:restart-pending 不能因坏元数据永久 pending。
182
+ const stale = Number.isFinite(startedAt) ? input.now - startedAt >= input.staleMs : true;
183
+ if (!stale) return { ok: true, action: 'recent', transaction: tx };
184
+ const target = String(tx.targetContentSha256 ?? '').toLowerCase();
185
+ const local = String(input.localContentSha256 ?? '').toLowerCase();
186
+ const matched = target !== '' && local === target;
187
+ const next = {
188
+ ...tx,
189
+ phase: matched ? 'settled' : 'failed',
190
+ result: matched
191
+ ? { ok: true, matched: 'loaded-target-content-adopted' }
192
+ : { ok: false, reason: 'confirmation-lost' },
193
+ updatedAt: new Date(input.now).toISOString(),
194
+ };
195
+ atomic(stateFile, next);
196
+ if (holder) atomic(holderFile, null);
197
+ return { ok: true, action: matched ? 'settled' : 'converged', transaction: next };
198
+ }
159
199
  // Never relabel a possibly damaged install as an ordinary terminal failure.
160
- if (['installing','restart-pending','rolling-back'].includes(tx.phase)) return { ok: true, action: 'recovery-required', transaction: tx };
200
+ if (['installing','rolling-back'].includes(tx.phase)) return { ok: true, action: 'recovery-required', transaction: tx };
161
201
  if (input.now - Date.parse(tx.startedAt) < input.staleMs) return { ok: true, action: 'recent', transaction: tx };
162
202
  if (tx.lease && holder && !owns(holder, tx.lease)) return { ok: true, action: 'superseded', transaction: tx };
163
203
  const next = { ...tx, phase: 'failed', result: { ok: false, reason: 'holder-gone' } };