File size: 22,715 Bytes
eb3f11e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 | import { randomUUID } from "node:crypto";
import { isDeepStrictEqual } from "node:util";
import { resolveServiceManagerEnv } from "../../daemon/service-process-env.js";
import { resolveUpdateInstallRoot } from "../../infra/update-install-root.js";
import {
captureManagedUpdateLeaseDatabaseIdentity,
type ManagedUpdateLeaseDatabaseIdentity,
} from "../../infra/update-managed-service-handoff-database.js";
import {
createManagedHandoffLeaseStore,
resolveManagedUpdateLeaseDatabasePath,
type ManagedHandoffLease,
} from "../../infra/update-managed-service-handoff-lease.js";
import { isCurrentManagedServiceUpdateHandoffProcess } from "../../infra/update-managed-service-handoff.js";
import type { UpdateRecoveryFence } from "../../infra/update-run-recovery.js";
import { withCommandProcessScope } from "../../process/exec-spawn.js";
import { createUpdateActivationDeadline } from "./update-command-activation.js";
import {
childLineageDigest,
createChildOwner,
type ChildOperation,
type UpdateCommandChildGrant,
} from "./update-command-executor-children.js";
import { createUpdateIdentityWarningReporter } from "./update-command-identity-warning.js";
import { UpdateCommandRecoveryPendingError } from "./update-command-recovery.js";
/** A live invocation, never a serialized claim, PID or recovered history row. */
export type UpdateCommandExecutor = {
/** Acquire only after read-only service admission, before the first mutable phase. */
enter(
root: string,
options?: { preflight?: true; activationTimeoutMs?: number },
): Promise<UpdateRecoveryFence>;
};
type ManagedUpdateLeaseAuthority = ManagedUpdateLeaseDatabaseIdentity &
Readonly<{ installKey: string; owner: string }>;
const admittedAuthorities = new WeakMap<UpdateRecoveryFence, ManagedUpdateLeaseAuthority>();
export function captureUpdateCommandExecutorAuthority(
fence: UpdateRecoveryFence,
): ManagedUpdateLeaseAuthority {
fence.assertCurrent();
const authority = admittedAuthorities.get(fence);
if (!authority) {
throw new UpdateCommandRecoveryPendingError("Package recovery requires its admitted executor.");
}
return authority;
}
// Only a direct preflight owner can release before a supervised handoff. Neither
// a saved fence nor a borrowed helper lease grants this one-way transition.
const preflightReleases = new WeakMap<UpdateRecoveryFence, () => void>();
export function releaseUpdateCommandPreflightForHandoff(fence: UpdateRecoveryFence): void {
const release = preflightReleases.get(fence);
if (!release) {
throw new UpdateCommandRecoveryPendingError("Update preflight handoff is not current.");
}
release();
}
export type { UpdateCommandChildGrant } from "./update-command-executor-children.js";
const childOwners = new WeakMap<
UpdateRecoveryFence,
<T>(root: string, operation: ChildOperation<T>) => Promise<T>
>();
export async function withUpdateCommandExecutorChild<T>(
fence: UpdateRecoveryFence,
root: string,
operation: ChildOperation<T>,
): Promise<T> {
const owner = childOwners.get(fence);
if (!owner) {
throw new UpdateCommandRecoveryPendingError("Child continuation requires its live executor.");
}
return await owner(root, operation);
}
/** A delegated executor retains both its original root and immediate spawner.
* Neither the transported grant nor a lease row without live identity grants effects. */
export async function withDelegatedUpdateCommandExecutor<T>(
grant: UpdateCommandChildGrant,
runId: string,
root: string,
operation: (fence: UpdateRecoveryFence) => Promise<T>,
options?: { activationTimeoutMs: number },
): Promise<T> {
const activation = createUpdateActivationDeadline();
return await activation.run(() =>
withCommandProcessScope(async () => {
const original = grant.originalParent ?? grant.parent;
const spawner = grant.spawner ?? original;
const childPrefix = `${original.key}/.openclaw-update-child-`;
const childName = grant.childKey.slice(
grant.childKey.lastIndexOf("/.openclaw-update-child-") + "/.openclaw-update-child-".length,
);
// v2026.9.4 sent this exact private-stdin format. Pin its existing database
// before reading/admitting the live parent and registered receiver. Modern
// names cannot downgrade by stripping their lineage or supplied physical pin.
const legacyGrant =
!grant.originalParent &&
!grant.spawner &&
!grant.originalChildKey &&
!grant.databaseIdentity &&
grant.childKey === `${grant.parent.key}/.openclaw-update-child-${childName}` &&
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(childName);
const databaseIdentity = legacyGrant
? captureManagedUpdateLeaseDatabaseIdentity(grant.databasePath)
: grant.databaseIdentity;
const databasePath = databaseIdentity?.databasePath ?? grant.databasePath;
const identityWarnings = createUpdateIdentityWarningReporter(runId);
const store = createManagedHandoffLeaseStore({
databasePath,
serviceManagerEnv: resolveServiceManagerEnv(),
existingIdentity: databaseIdentity,
onProcessIdentityWarning: identityWarnings.warn,
});
const parent = store.read(resolveUpdateInstallRoot(root));
const originalChild = store.read(grant.originalChildKey ?? grant.childKey);
const child = store.read(grant.childKey);
const lineageBound = Boolean(
grant.originalParent &&
grant.databaseIdentity &&
grant.spawner &&
grant.originalChildKey &&
grant.originalChildKey === `${spawner.key}/.openclaw-update-child-${childName}` &&
grant.childKey ===
`${grant.parent.key === original.key ? spawner.key : grant.parent.key}/.openclaw-update-child-${childName}` &&
/^[0-9a-f-]{36}-lineage-[0-9a-f]{64}$/.test(childName) &&
childName.endsWith(
`-lineage-${childLineageDigest(original, spawner, grant.parent, grant.databaseIdentity)}`,
),
);
if (
(!lineageBound && !legacyGrant) ||
(!legacyGrant && databasePath !== grant.databasePath) ||
grant.runId !== runId ||
grant.root !== resolveUpdateInstallRoot(root) ||
parent.kind !== "current" ||
!isDeepStrictEqual(parent.lease, grant.parent) ||
parent.lease.action.kind !== "update" ||
parent.lease.version === 3 ||
!store.current(original) ||
original.action.kind !== "update" ||
original.version === 3 ||
!store.current(spawner) ||
spawner.action.kind !== "update" ||
spawner.version === 3 ||
(spawner.key !== original.key &&
(!spawner.key.startsWith(childPrefix) || spawner.owner !== runId)) ||
process.ppid !== spawner.executor.pid ||
!(grant.originalChildKey ?? grant.childKey).startsWith(
`${spawner.key}/.openclaw-update-child-`,
) ||
!grant.childKey.startsWith(`${parent.lease.key}/.openclaw-update-child-`) ||
originalChild.kind !== "current" ||
originalChild.lease.owner !== runId ||
originalChild.lease.action.kind !== "update" ||
originalChild.lease.version === 3 ||
!isDeepStrictEqual(originalChild.lease.helper, spawner.executor) ||
child.kind !== "current" ||
child.lease.owner !== runId ||
child.lease.action.kind !== "update" ||
child.lease.version === 3 ||
!isDeepStrictEqual(child.lease.helper, spawner.executor)
) {
throw new UpdateCommandRecoveryPendingError(
"Candidate executor binding does not match its parent.",
);
}
let active = true;
const isLive = (identity: ManagedHandoffLease["executor"]) =>
store.isProcessIdentityCurrent(identity);
if (
!store.acceptParentBoundExecutor(originalChild.lease) ||
!store.acceptParentBoundExecutor(child.lease)
) {
throw new UpdateCommandRecoveryPendingError(
"Candidate executor ownership is no longer current.",
);
}
const assertBase = () => {
activation.assertCurrent();
if (
!active ||
!store.current(original) ||
!isLive(original.helper) ||
!isLive(original.executor) ||
!store.current(parent.lease) ||
!isLive(parent.lease.helper) ||
!isLive(parent.lease.executor) ||
!store.current(spawner) ||
!isLive(spawner.helper) ||
!isLive(spawner.executor) ||
!store.owns(originalChild.lease, "executor") ||
!store.owns(child.lease, "executor")
) {
throw new UpdateCommandRecoveryPendingError(
"Candidate executor ownership is no longer current.",
);
}
};
const owner = createChildOwner({
runId,
binding: () => ({
store,
parent: parent.lease,
original,
spawner: originalChild.lease,
databasePath,
databaseIdentity,
}),
assertBase,
});
activation.signal.addEventListener("abort", () => owner.close(), { once: true });
const fence = {
assertCurrent() {
assertBase();
owner.assertIdle();
},
};
childOwners.set(fence, (childRoot, childOperation) => owner.run(childRoot, childOperation));
let outcome: { result: T } | { error: unknown };
try {
fence.assertCurrent();
if (databaseIdentity) {
admittedAuthorities.set(
fence,
Object.freeze({
...databaseIdentity,
installKey: original.key,
owner: original.owner,
}),
);
}
if (options) {
activation.start(root, options.activationTimeoutMs);
}
outcome = { result: await operation(fence) };
} catch (error) {
outcome = { error };
}
owner.close();
try {
await owner.settle();
fence.assertCurrent();
identityWarnings.flush();
} catch (cause) {
outcome = {
error:
"error" in outcome && outcome.error !== cause
? new AggregateError(
[outcome.error, cause],
"Candidate and descendant settlement failed",
{ cause },
)
: cause,
};
} finally {
active = false;
childOwners.delete(fence);
admittedAuthorities.delete(fence);
}
if ("error" in outcome) {
throw outcome.error;
}
return outcome.result;
}, activation.signal),
);
}
/**
* Reuse the native handoff owner for direct invocations too. Its database is
* outside the canonical state family, so checking this fence never opens a
* displaced/migrated source. Physical source exclusion remains a separate duty.
*/
export async function withUpdateCommandExecutor<T>(
runId: string,
operation: (executor: UpdateCommandExecutor) => Promise<T>,
options?:
| {
existingAuthority: Omit<ManagedUpdateLeaseAuthority, "owner">;
legacyManagedParent?: never;
}
| {
existingAuthority?: never;
legacyManagedParent: { runId: string; handoffId: string; root: string };
},
): Promise<T> {
const activation = createUpdateActivationDeadline();
return await activation.run(() =>
withCommandProcessScope(async () => {
let active = true;
let entering = false;
let databasePath: string | undefined;
let store: ReturnType<typeof createManagedHandoffLeaseStore> | undefined;
let lease: ManagedHandoffLease | undefined;
let borrowed = false;
let legacyChild: ManagedHandoffLease | undefined;
const identityWarnings = createUpdateIdentityWarningReporter(runId);
const assertBase = () => {
activation.assertCurrent();
if (
!active ||
!store ||
!lease ||
(legacyChild
? !store.current(lease) ||
lease.executor.pid !== process.ppid ||
!store.isProcessIdentityCurrent(lease.helper) ||
!store.isProcessIdentityCurrent(lease.executor) ||
!store.owns(legacyChild, "executor")
: !store.owns(lease, "executor"))
) {
throw new UpdateCommandRecoveryPendingError(
"Update executor ownership is no longer current.",
);
}
};
const assertCurrent = () => {
assertBase();
if (lease?.version === 3) {
throw new UpdateCommandRecoveryPendingError(
"Parent executor has unresolved native custody.",
);
}
children.assertIdle();
};
const fence = { assertCurrent };
const children = createChildOwner({
runId,
assertBase,
onStart: () => preflightReleases.delete(fence),
binding: () => {
if (!store || !lease || !databasePath) {
throw new UpdateCommandRecoveryPendingError("Child executor admission is closed.");
}
return {
store,
parent: lease,
original: lease,
spawner: legacyChild ?? lease,
databasePath,
databaseIdentity: admittedAuthorities.get(fence),
};
},
});
activation.signal.addEventListener("abort", () => children.close(), { once: true });
childOwners.set(fence, (root, childOperation) => {
assertCurrent();
return children.run(root, childOperation);
});
const executor: UpdateCommandExecutor = {
async enter(root, enterOptions) {
activation.assertCurrent();
if (!active || entering) {
throw new UpdateCommandRecoveryPendingError(
"Update executor admission is closed or busy.",
);
}
// A missing canonical package is a recorded publication state, not an
// invitation to resolve a different installation through the current cwd.
const key = options?.existingAuthority?.installKey ?? resolveUpdateInstallRoot(root);
if (options?.existingAuthority && root !== key) {
throw new UpdateCommandRecoveryPendingError("Recovery installation key changed.");
}
if (lease) {
assertCurrent();
identityWarnings.flush();
if (lease.key !== key) {
throw new UpdateCommandRecoveryPendingError("Update executor installation changed.");
}
if (!enterOptions?.preflight) {
preflightReleases.delete(fence);
}
if (enterOptions?.activationTimeoutMs !== undefined) {
activation.start(key, enterOptions.activationTimeoutMs);
}
return fence;
}
entering = true;
try {
databasePath =
options?.existingAuthority?.databasePath ?? resolveManagedUpdateLeaseDatabasePath();
store = createManagedHandoffLeaseStore({
databasePath,
serviceManagerEnv: resolveServiceManagerEnv(),
existingIdentity: options?.existingAuthority,
onProcessIdentityWarning: identityWarnings.warn,
});
const found = store.read(key);
if (found.kind === "unreadable") {
throw new UpdateCommandRecoveryPendingError("Update executor state is unreadable.");
}
if (options?.legacyManagedParent) {
const parent = options.legacyManagedParent;
if (
found.kind !== "current" ||
parent.runId !== runId ||
parent.root !== key ||
found.lease.owner !== parent.handoffId ||
found.lease.version !== 2 ||
found.lease.action.kind !== "update" ||
found.lease.executor.pid !== process.ppid ||
!store.isProcessIdentityCurrent(found.lease.helper) ||
!store.isProcessIdentityCurrent(found.lease.executor) ||
store.hasUnsettledChildren(found.lease)
) {
throw new UpdateCommandRecoveryPendingError(
"Legacy finalizer does not match its live managed parent.",
);
}
lease = found.lease;
borrowed = true;
const child = store.acquire(`${key}/.openclaw-update-child-${randomUUID()}`, runId, {
kind: "update",
});
if (child.kind !== "acquired") {
throw new UpdateCommandRecoveryPendingError(
"Legacy finalizer lifetime could not be acquired.",
);
}
legacyChild = child.lease;
} else if (
found.kind === "current" &&
!options?.existingAuthority &&
found.lease.helper.pid !== process.pid &&
found.lease.executor.pid === process.pid
) {
const handedOff = await isCurrentManagedServiceUpdateHandoffProcess({
root: key,
runId,
});
// Retain the exact row observed before the await. Matching the run in
// a later metadata read cannot authorize a different lease generation.
if (
!active ||
!handedOff ||
found.lease.action.kind !== "update" ||
(!store.owns(found.lease, "executor") &&
!(process.connected && store.acceptParentBoundExecutor(found.lease)))
) {
throw new UpdateCommandRecoveryPendingError(
"Managed update executor changed during admission.",
);
}
lease = found.lease;
borrowed = true;
} else {
const acquired = store.acquire(key, randomUUID(), { kind: "update" });
if (acquired.kind !== "acquired") {
throw new UpdateCommandRecoveryPendingError(
"Another update executor owns this installation.",
);
}
lease = acquired.lease;
}
assertCurrent();
const authority = Object.freeze({
...(options?.existingAuthority ??
captureManagedUpdateLeaseDatabaseIdentity(databasePath)),
installKey: key,
owner: lease.owner,
});
// Switch the live owner too: capture, later child admission and final
// release must not recreate a database lost after initial admission.
databasePath = authority.databasePath;
store = createManagedHandoffLeaseStore({
databasePath,
serviceManagerEnv: resolveServiceManagerEnv(),
existingIdentity: authority,
onProcessIdentityWarning: identityWarnings.warn,
});
if (
borrowed &&
!legacyChild &&
!store.owns(lease, "executor") &&
!(process.connected && store.acceptParentBoundExecutor(lease))
) {
throw new UpdateCommandRecoveryPendingError(
"Managed update executor changed during admission.",
);
}
assertCurrent();
admittedAuthorities.set(fence, authority);
if (enterOptions?.preflight && !borrowed) {
preflightReleases.set(fence, () => {
assertCurrent();
if (!store || !lease || children.pending || !store.release(lease)) {
throw new UpdateCommandRecoveryPendingError("Preflight executor release failed.");
}
// Never reactivate this fence; the supervised helper must acquire its own.
active = false;
lease = undefined;
children.close();
childOwners.delete(fence);
admittedAuthorities.delete(fence);
preflightReleases.delete(fence);
});
}
if (enterOptions?.activationTimeoutMs !== undefined) {
activation.start(key, enterOptions.activationTimeoutMs);
}
return fence;
} finally {
entering = false;
}
},
};
let outcome: { result: T } | { error: Error };
try {
const result = await operation(executor);
children.close();
await children.settle();
if (lease) {
assertCurrent();
}
identityWarnings.flush();
outcome = { result };
} catch (cause) {
outcome = {
error: cause instanceof Error ? cause : new Error("Update execution failed", { cause }),
};
}
children.close();
try {
await children.settle();
} catch (cause) {
outcome = {
error:
"error" in outcome && outcome.error !== cause
? new AggregateError(
[outcome.error, cause],
"Update and candidate settlement failed",
{
cause,
},
)
: cause instanceof Error
? cause
: new Error("Candidate settlement failed", { cause }),
};
}
active = false;
preflightReleases.delete(fence);
childOwners.delete(fence);
admittedAuthorities.delete(fence);
try {
if (legacyChild && store && !store.release(legacyChild)) {
throw new UpdateCommandRecoveryPendingError("Legacy finalizer has not settled.");
}
if (lease && store && (lease.version === 3 || (!borrowed && !store.release(lease)))) {
throw new UpdateCommandRecoveryPendingError(
"Update executor release could not be confirmed.",
);
}
} catch (cause) {
if ("error" in outcome) {
throw new UpdateCommandRecoveryPendingError(
"Update failed and executor release remains pending",
{
cause: new AggregateError([outcome.error, cause], "Update executor cleanup failed", {
cause: outcome.error,
}),
},
);
}
throw cause;
}
if ("error" in outcome) {
throw outcome.error;
}
return outcome.result;
}, activation.signal),
);
}
|