create-principles-disciple 1.156.1 → 1.157.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/_release/product-identity.json +2 -2
- package/codex-adapter/dist/worker/workspace-worker.d.ts +11 -3
- package/codex-adapter/dist/worker/workspace-worker.js +30 -16
- package/codex-adapter/package.json +1 -1
- package/console/dist/server/models/OwnerDecisionConsoleModel.js +33 -1
- package/console/dist/web/assets/app.js +3 -3
- package/core/dist/runtime/adversarial-loop.d.ts +8 -0
- package/core/dist/runtime/adversarial-loop.d.ts.map +1 -1
- package/core/dist/runtime/adversarial-loop.js +432 -45
- package/core/dist/runtime/adversarial-loop.js.map +1 -1
- package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +3 -3
- package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
- package/core/dist/runtime/feature-flags/plugin-surface-registry.d.ts.map +1 -1
- package/core/dist/runtime/feature-flags/plugin-surface-registry.js +0 -16
- package/core/dist/runtime/feature-flags/plugin-surface-registry.js.map +1 -1
- package/core/dist/runtime/index.d.ts +11 -1
- package/core/dist/runtime/index.d.ts.map +1 -1
- package/core/dist/runtime/index.js +18 -1
- package/core/dist/runtime/index.js.map +1 -1
- package/core/dist/runtime/internalization/artificer-runner.d.ts +9 -0
- package/core/dist/runtime/internalization/artificer-runner.d.ts.map +1 -1
- package/core/dist/runtime/internalization/artificer-runner.js +52 -0
- package/core/dist/runtime/internalization/artificer-runner.js.map +1 -1
- package/core/dist/runtime/internalization/correlation-lineage.d.ts +126 -0
- package/core/dist/runtime/internalization/correlation-lineage.d.ts.map +1 -0
- package/core/dist/runtime/internalization/correlation-lineage.js +431 -0
- package/core/dist/runtime/internalization/correlation-lineage.js.map +1 -0
- package/core/dist/runtime/internalization/evaluator-runner.d.ts +35 -0
- package/core/dist/runtime/internalization/evaluator-runner.d.ts.map +1 -1
- package/core/dist/runtime/internalization/evaluator-runner.js +390 -91
- package/core/dist/runtime/internalization/evaluator-runner.js.map +1 -1
- package/core/dist/runtime/internalization/internalization-orchestrator.d.ts +97 -17
- package/core/dist/runtime/internalization/internalization-orchestrator.d.ts.map +1 -1
- package/core/dist/runtime/internalization/internalization-orchestrator.js +730 -139
- package/core/dist/runtime/internalization/internalization-orchestrator.js.map +1 -1
- package/core/dist/runtime/internalization/internalization-state-machine.d.ts +14 -0
- package/core/dist/runtime/internalization/internalization-state-machine.d.ts.map +1 -1
- package/core/dist/runtime/internalization/internalization-state-machine.js +22 -0
- package/core/dist/runtime/internalization/internalization-state-machine.js.map +1 -1
- package/core/dist/runtime/internalization/internalization-transition-decision.js +1 -1
- package/core/dist/runtime/internalization/internalization-transition-decision.js.map +1 -1
- package/core/dist/runtime/internalization/owner-resolution-service.d.ts.map +1 -1
- package/core/dist/runtime/internalization/owner-resolution-service.js +10 -8
- package/core/dist/runtime/internalization/owner-resolution-service.js.map +1 -1
- package/core/dist/runtime/internalization/owner-review.d.ts +2 -0
- package/core/dist/runtime/internalization/owner-review.d.ts.map +1 -1
- package/core/dist/runtime/internalization/owner-review.js +17 -11
- package/core/dist/runtime/internalization/owner-review.js.map +1 -1
- package/core/dist/runtime/internalization/peer-runner-contracts.d.ts +4 -0
- package/core/dist/runtime/internalization/peer-runner-contracts.d.ts.map +1 -1
- package/core/dist/runtime/internalization/peer-runner-contracts.js.map +1 -1
- package/core/dist/runtime/internalization/pitask-metadata.d.ts +67 -1
- package/core/dist/runtime/internalization/pitask-metadata.d.ts.map +1 -1
- package/core/dist/runtime/internalization/pitask-metadata.js +77 -3
- package/core/dist/runtime/internalization/pitask-metadata.js.map +1 -1
- package/core/dist/runtime/internalization/repair-create.d.ts +73 -0
- package/core/dist/runtime/internalization/repair-create.d.ts.map +1 -0
- package/core/dist/runtime/internalization/repair-create.js +200 -0
- package/core/dist/runtime/internalization/repair-create.js.map +1 -0
- package/core/dist/runtime/internalization/repair-lineage-backfill.d.ts +94 -0
- package/core/dist/runtime/internalization/repair-lineage-backfill.d.ts.map +1 -0
- package/core/dist/runtime/internalization/repair-lineage-backfill.js +123 -0
- package/core/dist/runtime/internalization/repair-lineage-backfill.js.map +1 -0
- package/core/dist/runtime/internalization/repair-task-identity.d.ts +138 -0
- package/core/dist/runtime/internalization/repair-task-identity.d.ts.map +1 -0
- package/core/dist/runtime/internalization/repair-task-identity.js +320 -0
- package/core/dist/runtime/internalization/repair-task-identity.js.map +1 -0
- package/core/dist/runtime/internalization/revision-reopen.d.ts +93 -1
- package/core/dist/runtime/internalization/revision-reopen.d.ts.map +1 -1
- package/core/dist/runtime/internalization/revision-reopen.js +215 -35
- package/core/dist/runtime/internalization/revision-reopen.js.map +1 -1
- package/core/dist/runtime/internalization/rollout-reviewer-runner.d.ts +8 -9
- package/core/dist/runtime/internalization/rollout-reviewer-runner.d.ts.map +1 -1
- package/core/dist/runtime/internalization/rollout-reviewer-runner.js +15 -70
- package/core/dist/runtime/internalization/rollout-reviewer-runner.js.map +1 -1
- package/core/dist/runtime/internalization/rule-binding-revision.js +3 -3
- package/core/dist/runtime/internalization/rule-binding-revision.js.map +1 -1
- package/core/dist/runtime/internalization/successor-create.d.ts +69 -0
- package/core/dist/runtime/internalization/successor-create.d.ts.map +1 -0
- package/core/dist/runtime/internalization/successor-create.js +173 -0
- package/core/dist/runtime/internalization/successor-create.js.map +1 -0
- package/core/dist/runtime/internalization/successor-lookup.d.ts +50 -0
- package/core/dist/runtime/internalization/successor-lookup.d.ts.map +1 -0
- package/core/dist/runtime/internalization/successor-lookup.js +213 -0
- package/core/dist/runtime/internalization/successor-lookup.js.map +1 -0
- package/core/dist/runtime/runner/succeeded-result-recovery.d.ts +58 -0
- package/core/dist/runtime/runner/succeeded-result-recovery.d.ts.map +1 -0
- package/core/dist/runtime/runner/succeeded-result-recovery.js +117 -0
- package/core/dist/runtime/runner/succeeded-result-recovery.js.map +1 -0
- package/core/dist/runtime/store/runtime-state-manager.d.ts +1 -0
- package/core/dist/runtime/store/runtime-state-manager.d.ts.map +1 -1
- package/core/dist/runtime/store/runtime-state-manager.js +4 -0
- package/core/dist/runtime/store/runtime-state-manager.js.map +1 -1
- package/core/dist/runtime/store/task/memory-task-store.d.ts +3 -3
- package/core/dist/runtime/store/task/memory-task-store.d.ts.map +1 -1
- package/core/dist/runtime/store/task/memory-task-store.js +52 -0
- package/core/dist/runtime/store/task/memory-task-store.js.map +1 -1
- package/core/dist/runtime/store/task/sqlite-task-store.d.ts +3 -0
- package/core/dist/runtime/store/task/sqlite-task-store.d.ts.map +1 -1
- package/core/dist/runtime/store/task/sqlite-task-store.js +204 -135
- package/core/dist/runtime/store/task/sqlite-task-store.js.map +1 -1
- package/core/dist/runtime/store/task/task-store.d.ts +17 -0
- package/core/dist/runtime/store/task/task-store.d.ts.map +1 -1
- package/core/dist/telemetry-event.d.ts +2 -2
- package/core/dist/telemetry-event.d.ts.map +1 -1
- package/core/dist/telemetry-event.js +4 -0
- package/core/dist/telemetry-event.js.map +1 -1
- package/core/package.json +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/installer.d.ts +69 -11
- package/dist/installer.d.ts.map +1 -1
- package/dist/installer.js +432 -120
- package/dist/installer.js.map +1 -1
- package/dist/service-host-bridge.d.ts +0 -5
- package/dist/service-host-bridge.d.ts.map +1 -1
- package/dist/service-host-bridge.js.map +1 -1
- package/dist/service-host-provisioning.d.ts +123 -18
- package/dist/service-host-provisioning.d.ts.map +1 -1
- package/dist/service-host-provisioning.js +645 -77
- package/dist/service-host-provisioning.js.map +1 -1
- package/dist/utils/env.d.ts +9 -0
- package/dist/utils/env.d.ts.map +1 -1
- package/dist/utils/env.js +269 -49
- package/dist/utils/env.js.map +1 -1
- package/host-runtime/dist/codex-worker-status.d.ts +6 -4
- package/host-runtime/dist/codex-worker-status.js +7 -5
- package/host-runtime/dist/diagnostician-auto-run.js +2 -2
- package/host-runtime/dist/governance-signal-admission.d.ts +2 -1
- package/host-runtime/dist/governance-signal-admission.js +2 -1
- package/host-runtime/dist/index.d.ts +4 -1
- package/host-runtime/dist/index.js +16 -2
- package/host-runtime/dist/internalization-consumer-cycle.d.ts +12 -4
- package/host-runtime/dist/internalization-consumer-cycle.js +103 -99
- package/host-runtime/dist/internalization-consumer-governance.d.ts +4 -3
- package/host-runtime/dist/internalization-consumer-governance.js +17 -41
- package/host-runtime/dist/internalization-task-executor.d.ts +127 -0
- package/host-runtime/dist/internalization-task-executor.js +121 -0
- package/host-runtime/dist/workbuddy-worker-status.d.ts +6 -3
- package/host-runtime/dist/workbuddy-worker-status.js +7 -4
- package/host-runtime/dist/workspace-telemetry-emitter.js +1 -1
- package/host-runtime/package.json +1 -1
- package/install-layout/dist/background-execution-transition.d.ts +25 -29
- package/install-layout/dist/background-execution-transition.js +90 -138
- package/install-layout/dist/index.d.ts +45 -33
- package/install-layout/dist/index.js +24 -18
- package/install-layout/package.json +1 -1
- package/package.json +5 -4
- package/pd-cli/dist/commands/codex-worker.d.ts +7 -3
- package/pd-cli/dist/commands/codex-worker.d.ts.map +1 -1
- package/pd-cli/dist/commands/codex-worker.js +125 -101
- package/pd-cli/dist/commands/codex-worker.js.map +1 -1
- package/pd-cli/dist/commands/runtime-internalization-enqueue-successors.d.ts.map +1 -1
- package/pd-cli/dist/commands/runtime-internalization-enqueue-successors.js +263 -78
- package/pd-cli/dist/commands/runtime-internalization-enqueue-successors.js.map +1 -1
- package/pd-cli/dist/commands/runtime-internalization-run-once.d.ts.map +1 -1
- package/pd-cli/dist/commands/runtime-internalization-run-once.js +213 -127
- package/pd-cli/dist/commands/runtime-internalization-run-once.js.map +1 -1
- package/pd-cli/dist/commands/runtime-internalization-run-rulehost.js +1 -1
- package/pd-cli/dist/commands/runtime-internalization-run-rulehost.js.map +1 -1
- package/pd-cli/dist/commands/service-run-once.d.ts +12 -27
- package/pd-cli/dist/commands/service-run-once.d.ts.map +1 -1
- package/pd-cli/dist/commands/service-run-once.js +15 -206
- package/pd-cli/dist/commands/service-run-once.js.map +1 -1
- package/pd-cli/dist/commands/workbuddy-worker.d.ts +7 -2
- package/pd-cli/dist/commands/workbuddy-worker.d.ts.map +1 -1
- package/pd-cli/dist/commands/workbuddy-worker.js +133 -99
- package/pd-cli/dist/commands/workbuddy-worker.js.map +1 -1
- package/pd-cli/dist/commands/worker-service-host-gate.d.ts +38 -0
- package/pd-cli/dist/commands/worker-service-host-gate.d.ts.map +1 -0
- package/pd-cli/dist/commands/worker-service-host-gate.js +110 -0
- package/pd-cli/dist/commands/worker-service-host-gate.js.map +1 -0
- package/pd-cli/dist/program.d.ts.map +1 -1
- package/pd-cli/dist/program.js +20 -84
- package/pd-cli/dist/program.js.map +1 -1
- package/pd-cli/dist/services/rulehost-pipeline-runner.d.ts.map +1 -1
- package/pd-cli/dist/services/rulehost-pipeline-runner.js +202 -97
- package/pd-cli/dist/services/rulehost-pipeline-runner.js.map +1 -1
- package/pd-cli/dist/services/service-host/coordinator-common.d.ts.map +1 -1
- package/pd-cli/dist/services/service-host/coordinator-common.js +4 -5
- package/pd-cli/dist/services/service-host/coordinator-common.js.map +1 -1
- package/pd-cli/dist/services/service-host/index.d.ts +7 -10
- package/pd-cli/dist/services/service-host/index.d.ts.map +1 -1
- package/pd-cli/dist/services/service-host/index.js +8 -11
- package/pd-cli/dist/services/service-host/index.js.map +1 -1
- package/pd-cli/dist/services/service-host/install-identity.d.ts +5 -5
- package/pd-cli/dist/services/service-host/managed-run.d.ts.map +1 -1
- package/pd-cli/dist/services/service-host/managed-run.js +19 -22
- package/pd-cli/dist/services/service-host/managed-run.js.map +1 -1
- package/pd-cli/dist/services/service-host/scheduler/linux.d.ts.map +1 -1
- package/pd-cli/dist/services/service-host/scheduler/linux.js +21 -2
- package/pd-cli/dist/services/service-host/scheduler/linux.js.map +1 -1
- package/pd-cli/dist/services/service-host/scheduler/service-status.d.ts +1 -1
- package/pd-cli/dist/services/service-host/scheduler/service-status.d.ts.map +1 -1
- package/pd-cli/dist/services/service-host/scheduler/service-status.js +0 -2
- package/pd-cli/dist/services/service-host/scheduler/service-status.js.map +1 -1
- package/pd-cli/dist/services/service-host/status/service-run-status.d.ts +7 -51
- package/pd-cli/dist/services/service-host/status/service-run-status.d.ts.map +1 -1
- package/pd-cli/dist/services/service-host/status/service-run-status.js.map +1 -1
- package/pd-cli/dist/services/service-host/worker-adapter-openclaw.js +3 -3
- package/pd-cli/dist/services/service-host/worker-adapter.d.ts +0 -10
- package/pd-cli/dist/services/service-host/worker-adapter.d.ts.map +1 -1
- package/pd-cli/dist/services/service-host/worker-adapter.js +4 -12
- package/pd-cli/dist/services/service-host/worker-adapter.js.map +1 -1
- package/pd-cli/dist/services/service-host/worker-env.d.ts +1 -1
- package/pd-cli/dist/services/service-host/workspace-dispatch.d.ts +5 -7
- package/pd-cli/dist/services/service-host/workspace-dispatch.d.ts.map +1 -1
- package/pd-cli/dist/services/service-host/workspace-dispatch.js +1 -3
- package/pd-cli/dist/services/service-host/workspace-dispatch.js.map +1 -1
- package/pd-cli/package.json +1 -1
- package/plugin/dist/bundle.js +616 -1319
- package/plugin/dist/core/openclaw-tool-declaration.d.ts +13 -0
- package/plugin/dist/index.d.ts +0 -9
- package/plugin/dist/openclaw-worker.d.ts +21 -8
- package/plugin/dist/openclaw-worker.js +271 -271
- package/plugin/dist/openclaw.plugin.json +1 -1
- package/plugin/openclaw.plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/release-manager/dist/installer.js +432 -120
- package/release-manager/dist/service-host-provisioning.js +645 -77
- package/release-manager/dist/utils/env.js +269 -49
- package/release-manager/package.json +3 -2
- package/workbuddy-adapter/dist/worker/workspace-worker.d.ts +9 -1
- package/workbuddy-adapter/dist/worker/workspace-worker.js +21 -9
- package/workbuddy-adapter/package.json +1 -1
- package/pd-cli/dist/commands/service-handover.d.ts +0 -12
- package/pd-cli/dist/commands/service-handover.d.ts.map +0 -1
- package/pd-cli/dist/commands/service-handover.js +0 -117
- package/pd-cli/dist/commands/service-handover.js.map +0 -1
- package/pd-cli/dist/commands/worker-drain.d.ts +0 -7
- package/pd-cli/dist/commands/worker-drain.d.ts.map +0 -1
- package/pd-cli/dist/commands/worker-drain.js +0 -51
- package/pd-cli/dist/commands/worker-drain.js.map +0 -1
- package/pd-cli/dist/services/service-host/handover-claims.d.ts +0 -14
- package/pd-cli/dist/services/service-host/handover-claims.d.ts.map +0 -1
- package/pd-cli/dist/services/service-host/handover-claims.js +0 -50
- package/pd-cli/dist/services/service-host/handover-claims.js.map +0 -1
- package/pd-cli/dist/services/service-host/shadow-run.d.ts +0 -87
- package/pd-cli/dist/services/service-host/shadow-run.d.ts.map +0 -1
- package/pd-cli/dist/services/service-host/shadow-run.js +0 -549
- package/pd-cli/dist/services/service-host/shadow-run.js.map +0 -1
- package/pd-cli/dist/services/service-host/workspace-handover.d.ts +0 -190
- package/pd-cli/dist/services/service-host/workspace-handover.d.ts.map +0 -1
- package/pd-cli/dist/services/service-host/workspace-handover.js +0 -1393
- package/pd-cli/dist/services/service-host/workspace-handover.js.map +0 -1
- package/plugin/dist/service/gateway-consumer-lease.d.ts +0 -142
- package/plugin/dist/service/gateway-quiesce-ack.d.ts +0 -40
- package/plugin/dist/service/internalization-auto-consumer-service.d.ts +0 -100
|
@@ -1,1393 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Per-Workspace §8.4 atomic handover / rollback orchestration
|
|
3
|
-
* (SPEC-PD-SERVICE-HOST-001 §8.4, TD §9; PRI-1282 Phase 4).
|
|
4
|
-
*
|
|
5
|
-
* The state machine itself lives in `@principles/install-layout`
|
|
6
|
-
* (`transitionWorkspaceBackgroundExecution` — cross-process lock,
|
|
7
|
-
* generation fencing, operationId idempotency). This module is the SEQUENCE
|
|
8
|
-
* orchestrator the Operator drives:
|
|
9
|
-
*
|
|
10
|
-
* HANDOVER (irreversible-order steps, none may be skipped):
|
|
11
|
-
* 1. verify ownership readability + openclaw host binding (claims);
|
|
12
|
-
* 2. begin_handover (registers the workspace in the manifest in the SAME
|
|
13
|
-
* atomic write; effectiveOwner stays legacy — PREPARING grants no
|
|
14
|
-
* rights);
|
|
15
|
-
* 3. no-consume readiness via the ACTIVE-RELEASE worker
|
|
16
|
-
* (`openclaw worker --readiness`) — proves install wiring, declaration,
|
|
17
|
-
* evidence port and credentials WITHOUT consuming;
|
|
18
|
-
* 4. wait for the Gateway's persisted quiesce acknowledgment
|
|
19
|
-
* (`pd.gateway-quiesce.v1`, bound to this operationId + generation) —
|
|
20
|
-
* clearTimeout / PID absence / process exit are never substitutes;
|
|
21
|
-
* 5. ONE CAS transition to service_host_owned;
|
|
22
|
-
* 6. drive one real worker cycle through the same managed adapter the
|
|
23
|
-
* scheduler uses;
|
|
24
|
-
* 7. persist the completion evidence under <pdHome>/service/handover/.
|
|
25
|
-
*
|
|
26
|
-
* ROLLBACK mirrors it: stop new cycles (run-lock busy check) →
|
|
27
|
-
* begin_rollback → complete_rollback (CAS back to legacy) → observe the
|
|
28
|
-
* Gateway's resumption evidence (or record NOT_VERIFIED when the Gateway
|
|
29
|
-
* is not running) → evidence.
|
|
30
|
-
*
|
|
31
|
-
* Crash recovery is deterministic: every step re-derives from the persisted
|
|
32
|
-
* `state + operationId + generation` (design §7.3). Process liveness is
|
|
33
|
-
* never consulted.
|
|
34
|
-
*/
|
|
35
|
-
import * as crypto from 'node:crypto';
|
|
36
|
-
import * as fs from 'node:fs';
|
|
37
|
-
import * as path from 'node:path';
|
|
38
|
-
import { readWorkspaceBackgroundOwnership, transitionWorkspaceBackgroundExecution, } from '@principles/install-layout';
|
|
39
|
-
import { resolveCoordinatorInstallIdentity } from './install-identity.js';
|
|
40
|
-
import { collectHostWorkspaceClaimsFor } from './handover-claims.js';
|
|
41
|
-
import { acquireServiceRunLock, probeServiceRunLockState, releaseServiceRunLock, workspaceServiceRunLockPath } from './locking/service-run-lock.js';
|
|
42
|
-
import { runSchedulerLifecycle } from './scheduler/index.js';
|
|
43
|
-
import { readActiveReleaseFacts } from './status/service-run-status.js';
|
|
44
|
-
import { buildWorkerEnvironment } from './worker-env.js';
|
|
45
|
-
import { readConfigCredentialEnvNames, resolveActiveReleaseCliEntry } from './worker-adapter.js';
|
|
46
|
-
import { createOpenClawWorkerAdapter } from './worker-adapter-openclaw.js';
|
|
47
|
-
import { runWorkerProcess } from './worker-process.js';
|
|
48
|
-
/* eslint-disable @typescript-eslint/no-use-before-define -- helpers declared after main, matching codebase convention */
|
|
49
|
-
export const DEFAULT_HANDOVER_ACK_WAIT_MS = 15 * 60_000;
|
|
50
|
-
export const DEFAULT_HANDOVER_STEP_TIMEOUT_MS = 2 * 60_000;
|
|
51
|
-
export const DEFAULT_ROLLBACK_RESUME_WAIT_MS = 90_000;
|
|
52
|
-
/**
|
|
53
|
-
* Bounded wait for the last in-flight worker cycle to release the workspace
|
|
54
|
-
* run mutex during rollback (PRI-1282 P1-1). Matches the consumer cycle's
|
|
55
|
-
* own bound; on expiry the workspace stays rollback_pending and resumable.
|
|
56
|
-
*/
|
|
57
|
-
export const DEFAULT_ROLLBACK_DRAIN_WAIT_MS = 10 * 60_000;
|
|
58
|
-
const HANDOVER_EVIDENCE_SCHEMA = 'pd.service-handover-evidence.v1';
|
|
59
|
-
const HANDOVER_INTENT_SCHEMA = 'pd.service-handover-intent.v1';
|
|
60
|
-
export function establishHandoverContext(workspaceDir, input) {
|
|
61
|
-
const identity = resolveCoordinatorInstallIdentity(input.env ?? process.env, input.pdHomeOverride !== undefined ? { trustedHomeDir: input.pdHomeOverride } : {});
|
|
62
|
-
if (!identity.ok) {
|
|
63
|
-
return { ok: false, reason: `install_identity_unresolved:${identity.reason}`, nextAction: identity.nextAction };
|
|
64
|
-
}
|
|
65
|
-
const manifestPath = path.join(identity.identity.pdHome, 'install.json');
|
|
66
|
-
let workspace;
|
|
67
|
-
try {
|
|
68
|
-
workspace = path.resolve(workspaceDir);
|
|
69
|
-
}
|
|
70
|
-
catch {
|
|
71
|
-
return { ok: false, reason: 'workspace_path_invalid', nextAction: 'Pass an absolute canonical workspace directory.' };
|
|
72
|
-
}
|
|
73
|
-
// Pin the workspace to its REAL directory: intent files, evidence files,
|
|
74
|
-
// the worker launch and the workspace run mutex are all keyed off this
|
|
75
|
-
// spelling, so a symlinked and a real-path invocation meet the SAME
|
|
76
|
-
// operation and either spelling resumes it (PRI-1282 review).
|
|
77
|
-
try {
|
|
78
|
-
workspace = fs.realpathSync.native(workspace);
|
|
79
|
-
}
|
|
80
|
-
catch {
|
|
81
|
-
// Unresolvable target: keep the lexical spelling — the readiness probe
|
|
82
|
-
// reports the missing directory as the honest failure.
|
|
83
|
-
}
|
|
84
|
-
return { ok: true, pdHome: identity.identity.pdHome, homeDir: identity.identity.homeDir, manifestPath, workspaceDir: workspace };
|
|
85
|
-
}
|
|
86
|
-
function wait(ms) {
|
|
87
|
-
// REF'd on purpose: these are operator-command orchestration waits (ack
|
|
88
|
-
// polling, resumption observation) with hard deadlines. An unref'd timer
|
|
89
|
-
// here let Node exit mid-await with a pending promise — transitions
|
|
90
|
-
// applied, stdout empty, exit 0 (found in Stage 9 acceptance).
|
|
91
|
-
return new Promise((resolve) => {
|
|
92
|
-
setTimeout(resolve, ms);
|
|
93
|
-
});
|
|
94
|
-
}
|
|
95
|
-
function nowIso() {
|
|
96
|
-
return new Date().toISOString();
|
|
97
|
-
}
|
|
98
|
-
/**
|
|
99
|
-
* Sanitized single-line key for the evidence directory (no path
|
|
100
|
-
* separators). A readable stem ALONE is a real collision surface
|
|
101
|
-
* (`/tmp/a b` vs `/tmp/a_b` → same key → cross-workspace evidence mixing,
|
|
102
|
-
* PRI-1282 review P1-6), so the full path's SHA-256 suffix is the actual
|
|
103
|
-
* identity; the stem only keeps the directory browsable.
|
|
104
|
-
*/
|
|
105
|
-
function workspaceEvidenceKey(canonicalDir) {
|
|
106
|
-
const stem = canonicalDir.replace(/[^A-Za-z0-9._-]+/g, '_').slice(-48);
|
|
107
|
-
const digest = crypto.createHash('sha256').update(canonicalDir, 'utf8').digest('hex').slice(0, 16);
|
|
108
|
-
return `${stem}-${digest}`;
|
|
109
|
-
}
|
|
110
|
-
/**
|
|
111
|
-
* operationId is the operation's idempotency key AND a filename component
|
|
112
|
-
* under <pdHome>/service/handover/ — an operator-supplied value that
|
|
113
|
-
* reached the filesystem unchecked allowed path traversal (PRI-1282 review
|
|
114
|
-
* P1-6). Whitelisted to characters that are safe on every filesystem.
|
|
115
|
-
*/
|
|
116
|
-
const SAFE_OPERATION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
117
|
-
function isSafeOperationId(operationId) {
|
|
118
|
-
return SAFE_OPERATION_ID.test(operationId);
|
|
119
|
-
}
|
|
120
|
-
/**
|
|
121
|
-
* Canonical-directory equality for the persisted quiesce ack (PRI-1282 r4
|
|
122
|
-
* §11): writer, reader and this context all key off REAL directory
|
|
123
|
-
* identity — an ack recorded under a symlinked alias spelling of the same
|
|
124
|
-
* directory binds it; a spelling that resolves elsewhere does not. An
|
|
125
|
-
* unresolvable spelling fails closed (no match).
|
|
126
|
-
*/
|
|
127
|
-
function ackWorkspaceMatches(recorded, canonicalDir) {
|
|
128
|
-
let realRecorded;
|
|
129
|
-
try {
|
|
130
|
-
realRecorded = fs.realpathSync.native(recorded);
|
|
131
|
-
}
|
|
132
|
-
catch {
|
|
133
|
-
realRecorded = path.resolve(recorded);
|
|
134
|
-
}
|
|
135
|
-
let realCanonical;
|
|
136
|
-
try {
|
|
137
|
-
realCanonical = fs.realpathSync.native(canonicalDir);
|
|
138
|
-
}
|
|
139
|
-
catch {
|
|
140
|
-
realCanonical = path.resolve(canonicalDir);
|
|
141
|
-
}
|
|
142
|
-
return realRecorded === realCanonical;
|
|
143
|
-
}
|
|
144
|
-
function errnoOf(error) {
|
|
145
|
-
return typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
|
|
146
|
-
? String(Reflect.get(error, 'code'))
|
|
147
|
-
: '';
|
|
148
|
-
}
|
|
149
|
-
export function handoverEvidencePath(pdHome, canonicalDir, operationId) {
|
|
150
|
-
return path.join(pdHome, 'service', 'handover', workspaceEvidenceKey(canonicalDir), `${operationId}.json`);
|
|
151
|
-
}
|
|
152
|
-
export function writeHandoverEvidence(evidence, pdHome) {
|
|
153
|
-
if (!isSafeOperationId(evidence.operationId)) {
|
|
154
|
-
return { ok: false, path: handoverEvidencePath(pdHome, evidence.workspaceDir, 'invalid'), reason: 'operation_id_invalid' };
|
|
155
|
-
}
|
|
156
|
-
const target = handoverEvidencePath(pdHome, evidence.workspaceDir, evidence.operationId);
|
|
157
|
-
try {
|
|
158
|
-
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
159
|
-
const tmp = `${target}.${process.pid}.${crypto.randomUUID().slice(0, 8)}.tmp`;
|
|
160
|
-
const fd = fs.openSync(tmp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
|
|
161
|
-
try {
|
|
162
|
-
fs.writeFileSync(fd, JSON.stringify(evidence, null, 2) + '\n');
|
|
163
|
-
}
|
|
164
|
-
finally {
|
|
165
|
-
fs.closeSync(fd);
|
|
166
|
-
}
|
|
167
|
-
try {
|
|
168
|
-
// Write-once, ATOMICALLY: link() fails with EEXIST instead of
|
|
169
|
-
// replacing — rename() would silently overwrite a concurrently
|
|
170
|
-
// published document (PRI-1282 review P1-6).
|
|
171
|
-
fs.linkSync(tmp, target);
|
|
172
|
-
}
|
|
173
|
-
catch (linkError) {
|
|
174
|
-
try {
|
|
175
|
-
fs.unlinkSync(tmp);
|
|
176
|
-
}
|
|
177
|
-
catch { /* best effort */ }
|
|
178
|
-
if (errnoOf(linkError) === 'EEXIST') {
|
|
179
|
-
// An existing document is accepted ONLY when its FULL immutable
|
|
180
|
-
// identity is this operation's: schemaVersion + kind + operationId
|
|
181
|
-
// + workspaceDir are already proven by readHandoverEvidence's field
|
|
182
|
-
// check; outcome and the final ownership identity (status +
|
|
183
|
-
// generation) must also match — a same-named different-identity
|
|
184
|
-
// document is a conflict, never a no-op (PRI-1282 review r4 §6.1).
|
|
185
|
-
// startedAt/completedAt/steps are NOT part of the identity: a
|
|
186
|
-
// legitimate crash-retry of the SAME operation records its own
|
|
187
|
-
// timestamps.
|
|
188
|
-
const existing = readHandoverEvidence(pdHome, evidence.workspaceDir, evidence.operationId);
|
|
189
|
-
const generationOf = (doc) => doc.finalOwnership.status === 'manifest_unreadable' ? -1 : doc.finalOwnership.generation;
|
|
190
|
-
if (existing !== null
|
|
191
|
-
&& existing.kind === evidence.kind
|
|
192
|
-
&& existing.outcome === evidence.outcome
|
|
193
|
-
&& existing.finalOwnership.status === evidence.finalOwnership.status
|
|
194
|
-
&& generationOf(existing) === generationOf(evidence)) {
|
|
195
|
-
return { ok: true, path: target, reason: 'already_exists' };
|
|
196
|
-
}
|
|
197
|
-
return { ok: false, path: target, reason: 'evidence_identity_conflict' };
|
|
198
|
-
}
|
|
199
|
-
throw linkError;
|
|
200
|
-
}
|
|
201
|
-
fs.unlinkSync(tmp);
|
|
202
|
-
return { ok: true, path: target };
|
|
203
|
-
}
|
|
204
|
-
catch (error) {
|
|
205
|
-
return { ok: false, path: target, reason: error instanceof Error ? error.message : String(error) };
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
function isJsonObject(value) {
|
|
209
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
210
|
-
}
|
|
211
|
-
function isNonEmptyString(value) {
|
|
212
|
-
return typeof value === 'string' && value.length > 0;
|
|
213
|
-
}
|
|
214
|
-
/** Field-level validation of one persisted evidence step (rc-3/rc-4). */
|
|
215
|
-
function parseEvidenceStep(value) {
|
|
216
|
-
if (!isJsonObject(value))
|
|
217
|
-
return null;
|
|
218
|
-
if (!isNonEmptyString(value.step) || !isNonEmptyString(value.at) || !isNonEmptyString(value.outcome))
|
|
219
|
-
return null;
|
|
220
|
-
if (value.detail !== undefined && !isNonEmptyString(value.detail))
|
|
221
|
-
return null;
|
|
222
|
-
return { step: value.step, at: value.at, outcome: value.outcome, ...(value.detail !== undefined ? { detail: value.detail } : {}) };
|
|
223
|
-
}
|
|
224
|
-
/**
|
|
225
|
-
* Field-level validation of one embedded BackgroundExecutionRecord
|
|
226
|
-
* (rc-3: required fields validated explicitly, never cast into shape).
|
|
227
|
-
*/
|
|
228
|
-
function parseEvidenceRecord(value, state) {
|
|
229
|
-
if (!isJsonObject(value))
|
|
230
|
-
return null;
|
|
231
|
-
if (value.state !== state)
|
|
232
|
-
return null;
|
|
233
|
-
if (value.effectiveOwner !== 'legacy' && value.effectiveOwner !== 'service_host')
|
|
234
|
-
return null;
|
|
235
|
-
if (typeof value.generation !== 'number' || !Number.isInteger(value.generation) || value.generation < 0)
|
|
236
|
-
return null;
|
|
237
|
-
if (value.operationId !== null && !isNonEmptyString(value.operationId))
|
|
238
|
-
return null;
|
|
239
|
-
if (value.previousOwner !== null && value.previousOwner !== 'legacy' && value.previousOwner !== 'service_host')
|
|
240
|
-
return null;
|
|
241
|
-
if (value.targetOwner !== null && value.targetOwner !== 'legacy' && value.targetOwner !== 'service_host')
|
|
242
|
-
return null;
|
|
243
|
-
if (!isNonEmptyString(value.updatedAt))
|
|
244
|
-
return null;
|
|
245
|
-
return {
|
|
246
|
-
state,
|
|
247
|
-
effectiveOwner: value.effectiveOwner,
|
|
248
|
-
generation: value.generation,
|
|
249
|
-
operationId: value.operationId ?? null,
|
|
250
|
-
previousOwner: value.previousOwner,
|
|
251
|
-
targetOwner: value.targetOwner,
|
|
252
|
-
updatedAt: value.updatedAt,
|
|
253
|
-
};
|
|
254
|
-
}
|
|
255
|
-
/**
|
|
256
|
-
* Field-level validation of the persisted ownership projection embedded in
|
|
257
|
-
* an evidence document (rc-2/rc-3: untrusted JSON until proven). Every
|
|
258
|
-
* branch constructs its exact variant from validated fields — no casts.
|
|
259
|
-
*/
|
|
260
|
-
function parseEvidenceOwnership(value) {
|
|
261
|
-
if (!isJsonObject(value))
|
|
262
|
-
return null;
|
|
263
|
-
if (typeof value.generation !== 'number' || !Number.isInteger(value.generation) || value.generation < 0)
|
|
264
|
-
return null;
|
|
265
|
-
if (value.status === 'legacy_owned') {
|
|
266
|
-
if (value.source !== 'record' && value.source !== 'no_record')
|
|
267
|
-
return null;
|
|
268
|
-
if (value.record === undefined) {
|
|
269
|
-
return { status: 'legacy_owned', source: value.source, generation: value.generation };
|
|
270
|
-
}
|
|
271
|
-
const record = parseEvidenceRecord(value.record, 'legacy_owned');
|
|
272
|
-
if (record === null)
|
|
273
|
-
return null;
|
|
274
|
-
return { status: 'legacy_owned', source: value.source, generation: value.generation, record };
|
|
275
|
-
}
|
|
276
|
-
if (value.status === 'manifest_unreadable') {
|
|
277
|
-
if (!isNonEmptyString(value.reason) || !isNonEmptyString(value.nextAction))
|
|
278
|
-
return null;
|
|
279
|
-
return { status: 'manifest_unreadable', reason: value.reason, nextAction: value.nextAction };
|
|
280
|
-
}
|
|
281
|
-
if (value.status !== 'handover_preparing' && value.status !== 'service_host_owned' && value.status !== 'rollback_pending') {
|
|
282
|
-
return null;
|
|
283
|
-
}
|
|
284
|
-
const record = parseEvidenceRecord(value.record, value.status);
|
|
285
|
-
if (record === null)
|
|
286
|
-
return null;
|
|
287
|
-
return {
|
|
288
|
-
status: value.status,
|
|
289
|
-
generation: value.generation,
|
|
290
|
-
record,
|
|
291
|
-
};
|
|
292
|
-
}
|
|
293
|
-
/**
|
|
294
|
-
* Read + field-validate the write-once evidence document (rc-2/rc-3:
|
|
295
|
-
* untrusted JSON until proven — an unreadable or malformed document is
|
|
296
|
-
* null, i.e. "no evidence", and the caller fails closed).
|
|
297
|
-
*/
|
|
298
|
-
export function readHandoverEvidence(pdHome, canonicalDir, operationId) {
|
|
299
|
-
try {
|
|
300
|
-
const parsed = JSON.parse(fs.readFileSync(handoverEvidencePath(pdHome, canonicalDir, operationId), 'utf8'));
|
|
301
|
-
if (!isJsonObject(parsed))
|
|
302
|
-
return null;
|
|
303
|
-
if (parsed.schemaVersion !== HANDOVER_EVIDENCE_SCHEMA)
|
|
304
|
-
return null;
|
|
305
|
-
if (parsed.kind !== 'handover' && parsed.kind !== 'rollback')
|
|
306
|
-
return null;
|
|
307
|
-
if (!isNonEmptyString(parsed.operationId) || !isNonEmptyString(parsed.workspaceDir))
|
|
308
|
-
return null;
|
|
309
|
-
// PRI-1282 review P1-6: the document must BE this operation's evidence
|
|
310
|
-
// for THIS workspace — a field check, not just path keying (path keying
|
|
311
|
-
// alone let a colliding wskey satisfy a foreign workspace's resume).
|
|
312
|
-
if (parsed.operationId !== operationId || parsed.workspaceDir !== canonicalDir)
|
|
313
|
-
return null;
|
|
314
|
-
if (!isNonEmptyString(parsed.startedAt) || !isNonEmptyString(parsed.completedAt))
|
|
315
|
-
return null;
|
|
316
|
-
if (parsed.outcome !== 'completed' && parsed.outcome !== 'aborted' && parsed.outcome !== 'failed')
|
|
317
|
-
return null;
|
|
318
|
-
if (!Array.isArray(parsed.steps))
|
|
319
|
-
return null;
|
|
320
|
-
const steps = [];
|
|
321
|
-
for (const rawStep of parsed.steps) {
|
|
322
|
-
const step = parseEvidenceStep(rawStep);
|
|
323
|
-
if (step === null)
|
|
324
|
-
return null;
|
|
325
|
-
steps.push(step);
|
|
326
|
-
}
|
|
327
|
-
const finalOwnership = parseEvidenceOwnership(parsed.finalOwnership);
|
|
328
|
-
if (finalOwnership === null)
|
|
329
|
-
return null;
|
|
330
|
-
return {
|
|
331
|
-
schemaVersion: HANDOVER_EVIDENCE_SCHEMA,
|
|
332
|
-
kind: parsed.kind,
|
|
333
|
-
operationId: parsed.operationId,
|
|
334
|
-
workspaceDir: parsed.workspaceDir,
|
|
335
|
-
startedAt: parsed.startedAt,
|
|
336
|
-
completedAt: parsed.completedAt,
|
|
337
|
-
outcome: parsed.outcome,
|
|
338
|
-
steps,
|
|
339
|
-
finalOwnership,
|
|
340
|
-
};
|
|
341
|
-
}
|
|
342
|
-
catch {
|
|
343
|
-
return null;
|
|
344
|
-
}
|
|
345
|
-
}
|
|
346
|
-
export function handoverIntentPath(pdHome, canonicalDir, operationId) {
|
|
347
|
-
return path.join(pdHome, 'service', 'handover', workspaceEvidenceKey(canonicalDir), `${operationId}.intent.json`);
|
|
348
|
-
}
|
|
349
|
-
export function writeHandoverIntent(intent, pdHome) {
|
|
350
|
-
if (!isSafeOperationId(intent.operationId)) {
|
|
351
|
-
return { ok: false, path: handoverIntentPath(pdHome, intent.workspaceDir, 'invalid'), reason: 'operation_id_invalid' };
|
|
352
|
-
}
|
|
353
|
-
const target = handoverIntentPath(pdHome, intent.workspaceDir, intent.operationId);
|
|
354
|
-
try {
|
|
355
|
-
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
356
|
-
const tmp = `${target}.${process.pid}.${crypto.randomUUID().slice(0, 8)}.tmp`;
|
|
357
|
-
const fd = fs.openSync(tmp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
|
|
358
|
-
try {
|
|
359
|
-
fs.writeFileSync(fd, JSON.stringify(intent, null, 2) + '\n');
|
|
360
|
-
}
|
|
361
|
-
finally {
|
|
362
|
-
fs.closeSync(fd);
|
|
363
|
-
}
|
|
364
|
-
try {
|
|
365
|
-
// Atomic no-replace publish, same posture as the evidence document.
|
|
366
|
-
fs.linkSync(tmp, target);
|
|
367
|
-
}
|
|
368
|
-
catch (linkError) {
|
|
369
|
-
try {
|
|
370
|
-
fs.unlinkSync(tmp);
|
|
371
|
-
}
|
|
372
|
-
catch { /* best effort */ }
|
|
373
|
-
if (errnoOf(linkError) === 'EEXIST') {
|
|
374
|
-
// Full-identity compare (PRI-1282 r4 §6.2): kind/schemaVersion are
|
|
375
|
-
// proven by the reader's field check, but the operation AND the
|
|
376
|
-
// generation pair must also match — an operationId reused across
|
|
377
|
-
// generations is a conflict, never an idempotent replay.
|
|
378
|
-
const existing = readHandoverIntent(pdHome, intent.workspaceDir, intent.operationId);
|
|
379
|
-
if (existing !== null
|
|
380
|
-
&& existing.workspaceDir === intent.workspaceDir
|
|
381
|
-
&& existing.preparingGeneration === intent.preparingGeneration
|
|
382
|
-
&& existing.committedGeneration === intent.committedGeneration) {
|
|
383
|
-
return { ok: true, path: target, reason: 'already_exists' };
|
|
384
|
-
}
|
|
385
|
-
return { ok: false, path: target, reason: 'intent_identity_conflict' };
|
|
386
|
-
}
|
|
387
|
-
throw linkError;
|
|
388
|
-
}
|
|
389
|
-
fs.unlinkSync(tmp);
|
|
390
|
-
return { ok: true, path: target };
|
|
391
|
-
}
|
|
392
|
-
catch (error) {
|
|
393
|
-
return { ok: false, path: target, reason: error instanceof Error ? error.message : String(error) };
|
|
394
|
-
}
|
|
395
|
-
}
|
|
396
|
-
/** Read + field-validate a persisted commit intent (null = absent/untrusted). */
|
|
397
|
-
export function readHandoverIntent(pdHome, canonicalDir, operationId) {
|
|
398
|
-
try {
|
|
399
|
-
const parsed = JSON.parse(fs.readFileSync(handoverIntentPath(pdHome, canonicalDir, operationId), 'utf8'));
|
|
400
|
-
if (!isJsonObject(parsed))
|
|
401
|
-
return null;
|
|
402
|
-
if (parsed.schemaVersion !== HANDOVER_INTENT_SCHEMA || parsed.kind !== 'handover')
|
|
403
|
-
return null;
|
|
404
|
-
if (!isNonEmptyString(parsed.operationId) || parsed.operationId !== operationId)
|
|
405
|
-
return null;
|
|
406
|
-
if (!isNonEmptyString(parsed.workspaceDir) || !isNonEmptyString(parsed.writtenAt))
|
|
407
|
-
return null;
|
|
408
|
-
if (typeof parsed.preparingGeneration !== 'number' || !Number.isInteger(parsed.preparingGeneration) || parsed.preparingGeneration < 0)
|
|
409
|
-
return null;
|
|
410
|
-
if (typeof parsed.committedGeneration !== 'number' || !Number.isInteger(parsed.committedGeneration) || parsed.committedGeneration < 1)
|
|
411
|
-
return null;
|
|
412
|
-
return {
|
|
413
|
-
schemaVersion: HANDOVER_INTENT_SCHEMA,
|
|
414
|
-
kind: 'handover',
|
|
415
|
-
operationId: parsed.operationId,
|
|
416
|
-
workspaceDir: parsed.workspaceDir,
|
|
417
|
-
preparingGeneration: parsed.preparingGeneration,
|
|
418
|
-
committedGeneration: parsed.committedGeneration,
|
|
419
|
-
writtenAt: parsed.writtenAt,
|
|
420
|
-
};
|
|
421
|
-
}
|
|
422
|
-
catch {
|
|
423
|
-
return null;
|
|
424
|
-
}
|
|
425
|
-
}
|
|
426
|
-
// ─── Rollback intent (crash recovery, PRI-1282 review r4 §8) ────────────────
|
|
427
|
-
//
|
|
428
|
-
// The rollback mirror of the handover commit intent: persisted AFTER
|
|
429
|
-
// begin_rollback and BEFORE the complete_rollback CAS, it binds
|
|
430
|
-
// operationId + workspace + pending/committed generations so a run killed
|
|
431
|
-
// between the CAS and the evidence write is resumable — `--resume` then
|
|
432
|
-
// only rewrites the missing evidence, never re-flips ownership.
|
|
433
|
-
const ROLLBACK_INTENT_SCHEMA = 'pd.service-rollback-intent.v1';
|
|
434
|
-
export function rollbackIntentPath(pdHome, canonicalDir, operationId) {
|
|
435
|
-
return path.join(pdHome, 'service', 'handover', workspaceEvidenceKey(canonicalDir), `${operationId}.rollback-intent.json`);
|
|
436
|
-
}
|
|
437
|
-
export function writeRollbackIntent(intent, pdHome) {
|
|
438
|
-
if (!isSafeOperationId(intent.operationId)) {
|
|
439
|
-
return { ok: false, path: rollbackIntentPath(pdHome, intent.workspaceDir, 'invalid'), reason: 'operation_id_invalid' };
|
|
440
|
-
}
|
|
441
|
-
const target = rollbackIntentPath(pdHome, intent.workspaceDir, intent.operationId);
|
|
442
|
-
try {
|
|
443
|
-
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
444
|
-
const tmp = `${target}.${process.pid}.${crypto.randomUUID().slice(0, 8)}.tmp`;
|
|
445
|
-
const fd = fs.openSync(tmp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
|
|
446
|
-
try {
|
|
447
|
-
fs.writeFileSync(fd, JSON.stringify(intent, null, 2) + '\n');
|
|
448
|
-
}
|
|
449
|
-
finally {
|
|
450
|
-
fs.closeSync(fd);
|
|
451
|
-
}
|
|
452
|
-
try {
|
|
453
|
-
fs.linkSync(tmp, target); // atomic no-replace publish
|
|
454
|
-
}
|
|
455
|
-
catch (linkError) {
|
|
456
|
-
try {
|
|
457
|
-
fs.unlinkSync(tmp);
|
|
458
|
-
}
|
|
459
|
-
catch { /* best effort */ }
|
|
460
|
-
if (errnoOf(linkError) === 'EEXIST') {
|
|
461
|
-
const existing = readRollbackIntent(pdHome, intent.workspaceDir, intent.operationId);
|
|
462
|
-
if (existing !== null
|
|
463
|
-
&& existing.workspaceDir === intent.workspaceDir
|
|
464
|
-
&& existing.pendingGeneration === intent.pendingGeneration
|
|
465
|
-
&& existing.committedGeneration === intent.committedGeneration) {
|
|
466
|
-
return { ok: true, path: target, reason: 'already_exists' };
|
|
467
|
-
}
|
|
468
|
-
return { ok: false, path: target, reason: 'intent_identity_conflict' };
|
|
469
|
-
}
|
|
470
|
-
throw linkError;
|
|
471
|
-
}
|
|
472
|
-
fs.unlinkSync(tmp);
|
|
473
|
-
return { ok: true, path: target };
|
|
474
|
-
}
|
|
475
|
-
catch (error) {
|
|
476
|
-
return { ok: false, path: target, reason: error instanceof Error ? error.message : String(error) };
|
|
477
|
-
}
|
|
478
|
-
}
|
|
479
|
-
/** Read + field-validate a persisted rollback intent (null = absent/untrusted). */
|
|
480
|
-
export function readRollbackIntent(pdHome, canonicalDir, operationId) {
|
|
481
|
-
try {
|
|
482
|
-
const parsed = JSON.parse(fs.readFileSync(rollbackIntentPath(pdHome, canonicalDir, operationId), 'utf8'));
|
|
483
|
-
if (!isJsonObject(parsed))
|
|
484
|
-
return null;
|
|
485
|
-
if (parsed.schemaVersion !== ROLLBACK_INTENT_SCHEMA || parsed.kind !== 'rollback')
|
|
486
|
-
return null;
|
|
487
|
-
if (!isNonEmptyString(parsed.operationId) || parsed.operationId !== operationId)
|
|
488
|
-
return null;
|
|
489
|
-
if (!isNonEmptyString(parsed.workspaceDir) || !isNonEmptyString(parsed.writtenAt))
|
|
490
|
-
return null;
|
|
491
|
-
if (typeof parsed.pendingGeneration !== 'number' || !Number.isInteger(parsed.pendingGeneration) || parsed.pendingGeneration < 0)
|
|
492
|
-
return null;
|
|
493
|
-
if (typeof parsed.committedGeneration !== 'number' || !Number.isInteger(parsed.committedGeneration) || parsed.committedGeneration < 1)
|
|
494
|
-
return null;
|
|
495
|
-
return {
|
|
496
|
-
schemaVersion: ROLLBACK_INTENT_SCHEMA,
|
|
497
|
-
kind: 'rollback',
|
|
498
|
-
operationId: parsed.operationId,
|
|
499
|
-
workspaceDir: parsed.workspaceDir,
|
|
500
|
-
pendingGeneration: parsed.pendingGeneration,
|
|
501
|
-
committedGeneration: parsed.committedGeneration,
|
|
502
|
-
writtenAt: parsed.writtenAt,
|
|
503
|
-
};
|
|
504
|
-
}
|
|
505
|
-
catch {
|
|
506
|
-
return null;
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
/** Default scheduler-enabled fact probe: `pd service status` on this install. */
|
|
510
|
-
async function probeSchedulerEnabled(context, env) {
|
|
511
|
-
const status = await runSchedulerLifecycle('status', { env: env ?? process.env, trustedHomeDir: context.homeDir });
|
|
512
|
-
if (!status.ok)
|
|
513
|
-
return { ok: false, reason: status.reason };
|
|
514
|
-
return { ok: true, registered: status.facts.registered, enabled: status.facts.enabled };
|
|
515
|
-
}
|
|
516
|
-
/** Spawn a bounded active-release CLI probe (readiness or one cycle). */
|
|
517
|
-
async function runActiveReleaseWorkerProbe(args) {
|
|
518
|
-
const identity = resolveCoordinatorInstallIdentity(process.env, { trustedHomeDir: args.homeDir });
|
|
519
|
-
if (!identity.ok)
|
|
520
|
-
return { ok: false, reason: `install_identity_unresolved:${identity.reason}`, nextAction: identity.nextAction };
|
|
521
|
-
const entry = resolveActiveReleaseCliEntry(identity.identity);
|
|
522
|
-
if (entry.kind === 'missing') {
|
|
523
|
-
return { ok: false, reason: `active_release_missing:${entry.reason}`, nextAction: entry.nextAction };
|
|
524
|
-
}
|
|
525
|
-
const { env } = buildWorkerEnvironment({
|
|
526
|
-
identity: identity.identity,
|
|
527
|
-
hostKind: 'openclaw',
|
|
528
|
-
inheritedEnv: process.env,
|
|
529
|
-
// Same allowlist the managed adapter uses: the workspace's own
|
|
530
|
-
// `apiKeyEnv` names must reach the probe child or a console-saved /
|
|
531
|
-
// custom-named credential is stripped (PRI-1282 review).
|
|
532
|
-
credentialEnvAllowlist: readConfigCredentialEnvNames(args.workspaceDir),
|
|
533
|
-
});
|
|
534
|
-
const result = await runWorkerProcess({
|
|
535
|
-
cliEntry: entry.entry,
|
|
536
|
-
args: ['openclaw', 'worker', args.mode === 'readiness' ? '--readiness' : '--once', '--json', '--workspace', args.workspaceDir],
|
|
537
|
-
env,
|
|
538
|
-
timeoutMs: args.timeoutMs,
|
|
539
|
-
...(args.signal !== undefined ? { signal: args.signal } : {}),
|
|
540
|
-
});
|
|
541
|
-
return { ok: true, result };
|
|
542
|
-
}
|
|
543
|
-
/**
|
|
544
|
-
* One REAL worker cycle through the SAME managed adapter the scheduler's
|
|
545
|
-
* run-once uses (PRI-1282 review): entry resolution, allowlist env build
|
|
546
|
-
* (workspace credential names included), spawn, task-progress diffing,
|
|
547
|
-
* JSON/workspace/mode validation and liveness normalization are all the
|
|
548
|
-
* adapter's verified contract — the handover never trusts raw stdout.
|
|
549
|
-
*/
|
|
550
|
-
async function runManagedOpenClawCycle(args) {
|
|
551
|
-
const identity = resolveCoordinatorInstallIdentity(process.env, { trustedHomeDir: args.homeDir });
|
|
552
|
-
if (!identity.ok)
|
|
553
|
-
return { ok: false, reason: `install_identity_unresolved:${identity.reason}`, nextAction: identity.nextAction };
|
|
554
|
-
const result = await createOpenClawWorkerAdapter().executeOnce({
|
|
555
|
-
workspaceDir: args.workspaceDir,
|
|
556
|
-
activeRelease: readActiveReleaseFacts(identity.identity.activeRecordPath),
|
|
557
|
-
invocationId: args.invocationId,
|
|
558
|
-
timeoutMs: args.timeoutMs,
|
|
559
|
-
...(args.signal !== undefined ? { signal: args.signal } : {}),
|
|
560
|
-
identity: identity.identity,
|
|
561
|
-
inheritedEnv: process.env,
|
|
562
|
-
});
|
|
563
|
-
return { ok: true, result };
|
|
564
|
-
}
|
|
565
|
-
/** The cycle outcomes that prove a first managed cycle actually worked. */
|
|
566
|
-
function verifiedCycleOutcome(result) {
|
|
567
|
-
return result.cycleOutcome === 'cycle_completed' || result.cycleOutcome === 'cycle_completed_without_business_progress';
|
|
568
|
-
}
|
|
569
|
-
/**
|
|
570
|
-
* The consuming Worker child holds the per-workspace run mutex for its
|
|
571
|
-
* whole cycle — the lock survives the coordinator's own death because the
|
|
572
|
-
* CHILD is the recorded holder. Before launching (or rolling back around)
|
|
573
|
-
* a worker we probe that mutex: a live holder means the old cycle is still
|
|
574
|
-
* running and overlapping it would create two consumers on one workspace
|
|
575
|
-
* (PRI-1282 review). Returns the blocked/failed verdict or null to proceed.
|
|
576
|
-
*/
|
|
577
|
-
function refuseWhileWorkerRunning(context, operationId) {
|
|
578
|
-
const probe = probeServiceRunLockState(workspaceServiceRunLockPath(context.pdHome, context.workspaceDir));
|
|
579
|
-
if (probe.state === 'free')
|
|
580
|
-
return null;
|
|
581
|
-
if (probe.state === 'held') {
|
|
582
|
-
return {
|
|
583
|
-
ok: false,
|
|
584
|
-
outcome: 'blocked',
|
|
585
|
-
reason: 'service_host_worker_still_running',
|
|
586
|
-
nextAction: 'A worker cycle is still consuming this workspace (its process holds the workspace run mutex); wait for it to finish — cycles are bounded — and rerun the operation.',
|
|
587
|
-
operationId,
|
|
588
|
-
};
|
|
589
|
-
}
|
|
590
|
-
return {
|
|
591
|
-
ok: false,
|
|
592
|
-
outcome: 'blocked',
|
|
593
|
-
reason: `service_host_worker_lock_unverifiable:${probe.detail ?? 'unknown'}`,
|
|
594
|
-
nextAction: 'The workspace run mutex could not be verified; refusing to risk overlapping a still-running worker. Repair or remove the stale lock under <pdHome>/service/workspace-runs/ and rerun.',
|
|
595
|
-
operationId,
|
|
596
|
-
};
|
|
597
|
-
}
|
|
598
|
-
function parseWorkerJson(stdout) {
|
|
599
|
-
try {
|
|
600
|
-
const parsed = JSON.parse(stdout);
|
|
601
|
-
return isJsonObject(parsed) ? parsed : null;
|
|
602
|
-
}
|
|
603
|
-
catch {
|
|
604
|
-
return null;
|
|
605
|
-
}
|
|
606
|
-
}
|
|
607
|
-
export async function runWorkspaceHandover(workspaceDir, options) {
|
|
608
|
-
const context = establishHandoverContext(workspaceDir, options);
|
|
609
|
-
if (!context.ok)
|
|
610
|
-
return { ok: false, outcome: 'blocked', reason: context.reason, nextAction: context.nextAction };
|
|
611
|
-
// operationId enters file paths and CAS records — a filesystem-safe
|
|
612
|
-
// whitelist at the command boundary, before anything keys off it
|
|
613
|
-
// (PRI-1282 review P1-6).
|
|
614
|
-
if (options.resumeOperationId !== undefined && !isSafeOperationId(options.resumeOperationId)) {
|
|
615
|
-
return { ok: false, outcome: 'blocked', reason: 'operation_id_invalid', nextAction: 'operationId may only contain letters, digits, dots, underscores and hyphens (1-128 chars).' };
|
|
616
|
-
}
|
|
617
|
-
const ackWaitMs = options.ackWaitMs ?? DEFAULT_HANDOVER_ACK_WAIT_MS;
|
|
618
|
-
const stepTimeoutMs = options.stepTimeoutMs ?? DEFAULT_HANDOVER_STEP_TIMEOUT_MS;
|
|
619
|
-
const startedAt = nowIso();
|
|
620
|
-
const steps = [];
|
|
621
|
-
const record = (step, outcome, detail) => {
|
|
622
|
-
steps.push({ step, at: nowIso(), outcome, ...(detail !== undefined ? { detail } : {}) });
|
|
623
|
-
};
|
|
624
|
-
const aborted = () => options.signal?.aborted === true;
|
|
625
|
-
// ── 1. Ownership readability + host binding verification. ──
|
|
626
|
-
const initial = readWorkspaceBackgroundOwnership({ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir });
|
|
627
|
-
if (initial.status === 'manifest_unreadable') {
|
|
628
|
-
return { ok: false, outcome: 'blocked', reason: `ownership_unreadable:${initial.reason}`, nextAction: initial.nextAction };
|
|
629
|
-
}
|
|
630
|
-
// ── Crash-recovery continuation (design §7.3): a prior run already flipped
|
|
631
|
-
// the marker. Attribution comes from EITHER the completed evidence OR the
|
|
632
|
-
// commit intent the flip path persists first — a run killed between flip
|
|
633
|
-
// and evidence write is resumable because the intent carries
|
|
634
|
-
// workspace + operationId + committed generation (PRI-1282 review).
|
|
635
|
-
// ──
|
|
636
|
-
if (initial.status === 'service_host_owned') {
|
|
637
|
-
const priorOp = options.resumeOperationId ?? '';
|
|
638
|
-
const priorEvidence = priorOp !== '' ? readHandoverEvidence(context.pdHome, context.workspaceDir, priorOp) : null;
|
|
639
|
-
const priorIntent = priorOp !== '' ? readHandoverIntent(context.pdHome, context.workspaceDir, priorOp) : null;
|
|
640
|
-
// PRI-1282 review P1-6: 'completed' alone is not resumable — the
|
|
641
|
-
// evidence must be THIS workspace's handover whose committed ownership
|
|
642
|
-
// matches the CURRENT marker generation, else a stale/foreign document
|
|
643
|
-
// could impersonate the committed run.
|
|
644
|
-
const evidenceMatches = priorEvidence !== null
|
|
645
|
-
&& priorEvidence.kind === 'handover'
|
|
646
|
-
&& priorEvidence.outcome === 'completed'
|
|
647
|
-
&& priorEvidence.finalOwnership.status === 'service_host_owned'
|
|
648
|
-
&& priorEvidence.finalOwnership.generation === initial.generation;
|
|
649
|
-
const intentMatches = priorIntent !== null
|
|
650
|
-
&& priorIntent.workspaceDir === context.workspaceDir
|
|
651
|
-
&& priorIntent.committedGeneration === initial.generation;
|
|
652
|
-
if (priorOp !== '' && (evidenceMatches || intentMatches)) {
|
|
653
|
-
record('already_service_host_owned', intentMatches && priorEvidence?.outcome !== 'completed' ? 'verify_only_continuation_by_intent' : 'verify_only_continuation');
|
|
654
|
-
// A crashed run may have left its Worker child alive in its own
|
|
655
|
-
// process group — the child still holds the workspace run mutex, so
|
|
656
|
-
// resuming without this probe would overlap two consumers (PRI-1282).
|
|
657
|
-
const stillRunning = refuseWhileWorkerRunning(context, priorOp);
|
|
658
|
-
if (stillRunning !== null)
|
|
659
|
-
return stillRunning;
|
|
660
|
-
// The re-verification cycle joins the same install-level run mutex as
|
|
661
|
-
// the scheduler and rollback — a concurrent managed run must not
|
|
662
|
-
// overlap this verification (PRI-1282 review).
|
|
663
|
-
const contLock = acquireServiceRunLock(context.pdHome);
|
|
664
|
-
if (!contLock.ok) {
|
|
665
|
-
return { ok: false, outcome: 'blocked', reason: `service_run_in_progress:${contLock.kind}`, nextAction: 'A managed run-once is currently executing; wait for it to finish and rerun `pd service handover --resume` to re-verify.', operationId: priorOp };
|
|
666
|
-
}
|
|
667
|
-
try {
|
|
668
|
-
const cycleCont = await runManagedOpenClawCycle({ homeDir: context.homeDir, workspaceDir: context.workspaceDir, invocationId: priorOp, timeoutMs: Math.max(stepTimeoutMs, 10 * 60_000), ...(options.signal !== undefined ? { signal: options.signal } : {}) });
|
|
669
|
-
record('worker_cycle', cycleCont.ok ? `${cycleCont.result.cycleOutcome}${cycleCont.result.workerMode !== undefined ? `(${cycleCont.result.workerMode})` : ''}` : cycleCont.reason);
|
|
670
|
-
if (!cycleCont.ok || !verifiedCycleOutcome(cycleCont.result)) {
|
|
671
|
-
return {
|
|
672
|
-
ok: false,
|
|
673
|
-
outcome: 'failed',
|
|
674
|
-
reason: `first_cycle_unverified:${cycleCont.ok ? cycleCont.result.cycleOutcome : cycleCont.reason}`,
|
|
675
|
-
nextAction: 'The workspace is service_host_owned but the verification cycle did not complete; rerun `pd service handover --resume` to re-verify, or `pd service rollback` to return it to the Gateway.',
|
|
676
|
-
operationId: priorOp,
|
|
677
|
-
...(cycleCont.ok && cycleCont.result.reason !== undefined ? { detail: cycleCont.result.reason } : {}),
|
|
678
|
-
};
|
|
679
|
-
}
|
|
680
|
-
const ownershipAfter = readWorkspaceBackgroundOwnership({ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir });
|
|
681
|
-
const evidenceCont = {
|
|
682
|
-
schemaVersion: HANDOVER_EVIDENCE_SCHEMA,
|
|
683
|
-
kind: 'handover',
|
|
684
|
-
operationId: priorOp,
|
|
685
|
-
workspaceDir: context.workspaceDir,
|
|
686
|
-
startedAt,
|
|
687
|
-
completedAt: nowIso(),
|
|
688
|
-
outcome: 'completed',
|
|
689
|
-
steps,
|
|
690
|
-
finalOwnership: ownershipAfter,
|
|
691
|
-
};
|
|
692
|
-
const writtenCont = writeHandoverEvidence(evidenceCont, context.pdHome);
|
|
693
|
-
if (!writtenCont.ok) {
|
|
694
|
-
return { ok: false, outcome: 'failed', reason: `handover_evidence_write_failed:${writtenCont.reason ?? 'io'}`, nextAction: 'The verification cycle passed but the evidence could not be persisted; rerun `pd service handover --resume` after fixing the write failure.', operationId: priorOp };
|
|
695
|
-
}
|
|
696
|
-
return {
|
|
697
|
-
ok: true,
|
|
698
|
-
outcome: 'completed',
|
|
699
|
-
operationId: priorOp,
|
|
700
|
-
workspaceDir: context.workspaceDir,
|
|
701
|
-
generation: ownershipAfter.status === 'service_host_owned' ? ownershipAfter.generation : 0,
|
|
702
|
-
readiness: 'ready',
|
|
703
|
-
quiesceAck: { operationId: priorOp, generation: priorEvidence?.finalOwnership.status === 'service_host_owned' ? priorEvidence.finalOwnership.generation : (priorIntent?.committedGeneration ?? 0), outcome: 'verified_by_prior_evidence', startedVia: 'prior_run' },
|
|
704
|
-
workerCycle: { mode: cycleCont.result.workerMode ?? cycleCont.result.cycleOutcome, exitCode: cycleCont.result.worker.exitCode, evidencePath: writtenCont.path },
|
|
705
|
-
evidencePath: writtenCont.path,
|
|
706
|
-
};
|
|
707
|
-
}
|
|
708
|
-
finally {
|
|
709
|
-
releaseServiceRunLock(contLock.handle);
|
|
710
|
-
}
|
|
711
|
-
}
|
|
712
|
-
return {
|
|
713
|
-
ok: false,
|
|
714
|
-
outcome: 'blocked',
|
|
715
|
-
reason: 'already_service_host_owned',
|
|
716
|
-
nextAction: 'This workspace already belongs to the Service Host. Pass --resume <operationId> of the committed handover to re-verify, or use pd service rollback to return it to the legacy consumer.',
|
|
717
|
-
};
|
|
718
|
-
}
|
|
719
|
-
// ── Abort handling FIRST (PRI-1282 review P1-5): binding verification
|
|
720
|
-
// cannot gate an operator's abort — a workspace stuck in
|
|
721
|
-
// handover_preparing with a missing/broken OpenClaw binding would
|
|
722
|
-
// otherwise be unrecoverable by --abort. The abort must also name the
|
|
723
|
-
// EXACT in-flight operation: a marker's operationId no longer silently
|
|
724
|
-
// overrides an explicit --resume, and generation fencing keeps a stale
|
|
725
|
-
// caller from aborting a newer generation's work.
|
|
726
|
-
const markerOp = initial.status === 'handover_preparing' ? initial.record.operationId : undefined;
|
|
727
|
-
if (options.resumeOperationId !== undefined && markerOp !== undefined && options.resumeOperationId !== markerOp) {
|
|
728
|
-
return {
|
|
729
|
-
ok: false,
|
|
730
|
-
outcome: 'blocked',
|
|
731
|
-
reason: 'operation_id_mismatch',
|
|
732
|
-
nextAction: `The in-flight handover is ${markerOp}; --resume must name that exact operation (or omit --resume to adopt it).`,
|
|
733
|
-
operationId: markerOp ?? undefined,
|
|
734
|
-
};
|
|
735
|
-
}
|
|
736
|
-
if (options.abort === true) {
|
|
737
|
-
const target = markerOp;
|
|
738
|
-
if (target === undefined || target === null) {
|
|
739
|
-
return { ok: false, outcome: 'blocked', reason: 'abort_requires_operation', nextAction: 'No handover_preparing record exists for this workspace; nothing to abort.' };
|
|
740
|
-
}
|
|
741
|
-
const abortedTransition = transitionWorkspaceBackgroundExecution({
|
|
742
|
-
manifestPath: context.manifestPath, workspaceDir: context.workspaceDir, kind: 'abort_handover', operationId: target, expectedGeneration: initial.generation,
|
|
743
|
-
});
|
|
744
|
-
if (!abortedTransition.ok)
|
|
745
|
-
return { ok: false, outcome: 'failed', reason: `abort_failed:${abortedTransition.reason}`, nextAction: abortedTransition.nextAction ?? 'Inspect the manifest ownership record.', detail: abortedTransition.message };
|
|
746
|
-
record('aborted', 'legacy_owned');
|
|
747
|
-
return { ok: false, outcome: 'aborted', reason: 'handover_aborted_by_operator', nextAction: 'The workspace is back to legacy ownership; the Gateway consumer is the sole owner.', operationId: target };
|
|
748
|
-
}
|
|
749
|
-
// PRI-1282 review r4 §5: an explicit --resume may ONLY continue a real
|
|
750
|
-
// in-flight operation. With no handover_preparing marker there is nothing
|
|
751
|
-
// to resume — the command must NOT silently mint a new operationId out of
|
|
752
|
-
// the name the operator passed (and a completed operation can never
|
|
753
|
-
// re-enter the execution flow).
|
|
754
|
-
if (options.resumeOperationId !== undefined && markerOp === undefined) {
|
|
755
|
-
return {
|
|
756
|
-
ok: false,
|
|
757
|
-
outcome: 'blocked',
|
|
758
|
-
reason: 'no_resumable_operation',
|
|
759
|
-
nextAction: `No in-flight handover exists for this workspace to resume as '${options.resumeOperationId}'; omit --resume to start a new handover.`,
|
|
760
|
-
operationId: options.resumeOperationId,
|
|
761
|
-
};
|
|
762
|
-
}
|
|
763
|
-
const binding = collectHostWorkspaceClaimsFor(context.workspaceDir, context.homeDir, options.env);
|
|
764
|
-
if (binding.bindingUnverifiable !== null) {
|
|
765
|
-
return {
|
|
766
|
-
ok: false,
|
|
767
|
-
outcome: 'blocked',
|
|
768
|
-
reason: `foreign_owner_unverifiable:${binding.bindingUnverifiable}`,
|
|
769
|
-
nextAction: 'A host binding file could not be read or parsed, so cross-host ownership cannot be verified; repair the binding file(s) and retry (fail-closed per §9.1.8).',
|
|
770
|
-
};
|
|
771
|
-
}
|
|
772
|
-
if (!binding.openclawClaimed) {
|
|
773
|
-
return {
|
|
774
|
-
ok: false,
|
|
775
|
-
outcome: 'blocked',
|
|
776
|
-
reason: 'no_openclaw_host_binding',
|
|
777
|
-
nextAction: 'Bind the workspace to OpenClaw first (host declaration or validated mcp-binding claim); the handover never guesses host ownership.',
|
|
778
|
-
};
|
|
779
|
-
}
|
|
780
|
-
if (binding.foreignOwner !== null) {
|
|
781
|
-
return {
|
|
782
|
-
ok: false,
|
|
783
|
-
outcome: 'blocked',
|
|
784
|
-
reason: `foreign_workspace_owner:${binding.foreignOwner}`,
|
|
785
|
-
nextAction: 'Another host claims this workspace; resolve the cross-host ownership conflict before handing over to the Service Host.',
|
|
786
|
-
};
|
|
787
|
-
}
|
|
788
|
-
record('binding_verified', 'openclaw_claim_present');
|
|
789
|
-
// ── 2. begin_handover (idempotent; registers the workspace atomically). ──
|
|
790
|
-
const resumeOp = markerOp;
|
|
791
|
-
// ── 1.5. Scheduler gate (PRI-1282 review): handing ownership to the
|
|
792
|
-
// Service Host while no enabled OS trigger exists would leave the
|
|
793
|
-
// workspace consumed by NOBODY. Verified BEFORE the ownership-changing
|
|
794
|
-
// transition so a refusal keeps the workspace cleanly legacy-owned (and
|
|
795
|
-
// never blocks a recovery --abort); the command never enables the trigger
|
|
796
|
-
// on the operator's behalf. ──
|
|
797
|
-
const schedulerStatus = options.probes?.schedulerStatus !== undefined
|
|
798
|
-
? await options.probes.schedulerStatus()
|
|
799
|
-
: await probeSchedulerEnabled(context, options.env);
|
|
800
|
-
if (!schedulerStatus.ok) {
|
|
801
|
-
return {
|
|
802
|
-
ok: false,
|
|
803
|
-
outcome: 'blocked',
|
|
804
|
-
reason: `service_host_scheduler_status_unavailable:${schedulerStatus.reason}`,
|
|
805
|
-
nextAction: 'The Service Host scheduler status could not be determined; resolve that first (the workspace stays legacy-owned and untouched).',
|
|
806
|
-
};
|
|
807
|
-
}
|
|
808
|
-
if (schedulerStatus.registered !== true || schedulerStatus.enabled !== true) {
|
|
809
|
-
return {
|
|
810
|
-
ok: false,
|
|
811
|
-
outcome: 'blocked',
|
|
812
|
-
reason: 'service_host_scheduler_not_enabled',
|
|
813
|
-
nextAction: 'Install and enable the Service Host scheduler for this install first (`pd service install`, `pd service enable`); without an enabled trigger a handed-over workspace is consumed by nobody, so the workspace stays legacy-owned.',
|
|
814
|
-
};
|
|
815
|
-
}
|
|
816
|
-
record('scheduler_trigger', 'registered_and_enabled');
|
|
817
|
-
// operationId comes from the in-flight marker alone now — an explicit
|
|
818
|
-
// --resume was already proven equal to it above, and a fresh operation
|
|
819
|
-
// mints a fresh id. A marker name is never silently replaced.
|
|
820
|
-
const operationId = resumeOp ?? options.probes?.mintOperationId?.('handover') ?? `handover-${crypto.randomUUID()}`;
|
|
821
|
-
if (!isSafeOperationId(operationId)) {
|
|
822
|
-
return { ok: false, outcome: 'blocked', reason: 'operation_id_invalid', nextAction: 'operationId may only contain letters, digits, dots, underscores and hyphens (1-128 chars).', operationId };
|
|
823
|
-
}
|
|
824
|
-
const begin = transitionWorkspaceBackgroundExecution({
|
|
825
|
-
manifestPath: context.manifestPath, workspaceDir: context.workspaceDir, kind: 'begin_handover', operationId, registerWorkspace: true,
|
|
826
|
-
});
|
|
827
|
-
if (!begin.ok) {
|
|
828
|
-
return { ok: false, outcome: 'blocked', reason: `begin_handover_failed:${begin.reason}`, nextAction: begin.nextAction ?? 'Re-read the ownership record and retry.', operationId, detail: begin.message };
|
|
829
|
-
}
|
|
830
|
-
record('begin_handover', begin.changed ? 'handover_preparing' : 'idempotent_replay', `generation=${begin.record.generation}`);
|
|
831
|
-
const preparingGeneration = begin.record.generation;
|
|
832
|
-
// ── 3. No-consume readiness through the ACTIVE-RELEASE worker. ──
|
|
833
|
-
const readiness = await runActiveReleaseWorkerProbe({ homeDir: context.homeDir, workspaceDir: context.workspaceDir, mode: 'readiness', timeoutMs: stepTimeoutMs, ...(options.signal !== undefined ? { signal: options.signal } : {}) });
|
|
834
|
-
if (!readiness.ok) {
|
|
835
|
-
const rollback = transitionWorkspaceBackgroundExecution({ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir, kind: 'abort_handover', operationId, expectedGeneration: preparingGeneration });
|
|
836
|
-
record('readiness', 'unavailable', readiness.reason);
|
|
837
|
-
if (!rollback.ok) {
|
|
838
|
-
return { ok: false, outcome: 'failed', reason: `readiness_failed_and_abort_failed:${readiness.reason}|${rollback.reason}`, nextAction: 'The workspace is STUCK in handover_preparing — resolve manually (pd service handover --abort).', operationId, detail: readiness.nextAction };
|
|
839
|
-
}
|
|
840
|
-
return { ok: false, outcome: 'blocked', reason: `readiness_not_met:${readiness.reason}`, nextAction: `${readiness.nextAction} The workspace was restored to legacy ownership.`, operationId };
|
|
841
|
-
}
|
|
842
|
-
const readinessJson = parseWorkerJson(readiness.result.stdout);
|
|
843
|
-
const readinessMode = typeof readinessJson?.mode === 'string' ? readinessJson.mode : 'unknown';
|
|
844
|
-
// PRI-1282 review P2-1: 'ready' must be corroborated by a clean process
|
|
845
|
-
// outcome — a timed-out/cancelled/failed child that managed to print
|
|
846
|
-
// mode:'ready' before dying is not evidence of readiness.
|
|
847
|
-
const readinessProcessFailed = readiness.result.exitCode !== 0
|
|
848
|
-
|| readiness.result.timedOut === true
|
|
849
|
-
|| readiness.result.cancelled === true
|
|
850
|
-
|| readiness.result.spawnError !== undefined
|
|
851
|
-
|| readiness.result.stdoutTruncated === true
|
|
852
|
-
// close-observed is required: a worker whose stdout was captured but
|
|
853
|
-
// whose process never provably terminated cannot attest readiness
|
|
854
|
-
// (PRI-1282 r4 §10).
|
|
855
|
-
|| readiness.result.terminationConfirmed !== true;
|
|
856
|
-
// The readiness document must attest THIS workspace — an out-of-band or
|
|
857
|
-
// stale 'ready' printed for another dir is not this workspace's proof.
|
|
858
|
-
const readinessWorkspaceMismatch = typeof readinessJson?.workspaceDir === 'string'
|
|
859
|
-
&& path.resolve(readinessJson.workspaceDir) !== context.workspaceDir;
|
|
860
|
-
if (readinessMode !== 'ready' || readinessProcessFailed || readinessWorkspaceMismatch) {
|
|
861
|
-
const processDetail = readinessProcessFailed
|
|
862
|
-
? `exitCode=${readiness.result.exitCode} timedOut=${readiness.result.timedOut} cancelled=${readiness.result.cancelled} stdoutTruncated=${readiness.result.stdoutTruncated} terminationConfirmed=${readiness.result.terminationConfirmed ?? false}${readiness.result.spawnError !== undefined ? ` spawnError=${readiness.result.spawnError}` : ''}`
|
|
863
|
-
: '';
|
|
864
|
-
const rollback = transitionWorkspaceBackgroundExecution({ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir, kind: 'abort_handover', operationId, expectedGeneration: preparingGeneration });
|
|
865
|
-
record('readiness', readinessProcessFailed ? `process_failed(${processDetail})` : readinessMode, readiness.result.stdout.slice(0, 400));
|
|
866
|
-
if (!rollback.ok) {
|
|
867
|
-
return { ok: false, outcome: 'failed', reason: `readiness_not_ready_and_abort_failed:${readinessMode}|${rollback.reason}`, nextAction: 'The workspace is STUCK in handover_preparing — resolve manually (pd service handover --abort).', operationId };
|
|
868
|
-
}
|
|
869
|
-
return {
|
|
870
|
-
ok: false,
|
|
871
|
-
outcome: 'blocked',
|
|
872
|
-
reason: readinessWorkspaceMismatch
|
|
873
|
-
? 'openclaw_worker_readiness_workspace_mismatch'
|
|
874
|
-
: readinessProcessFailed ? `openclaw_worker_readiness_process:${readinessMode}` : `openclaw_worker_readiness:${readinessMode}`,
|
|
875
|
-
nextAction: 'Fix the failing readiness checks (declaration / evidence port / credentials) and retry; the workspace was restored to legacy ownership.',
|
|
876
|
-
operationId,
|
|
877
|
-
detail: readinessJson ?? { exitCode: readiness.result.exitCode, timedOut: readiness.result.timedOut, cancelled: readiness.result.cancelled },
|
|
878
|
-
};
|
|
879
|
-
}
|
|
880
|
-
record('readiness', 'ready');
|
|
881
|
-
// ── 4. Wait for the Gateway quiesce ack (persisted, operation-bound). ──
|
|
882
|
-
const ackPlugin = await import('principles-disciple/openclaw-worker');
|
|
883
|
-
const ackDeadline = Date.now() + (options.ackWaitMs ?? ackWaitMs);
|
|
884
|
-
let ack = null;
|
|
885
|
-
while (Date.now() < ackDeadline) {
|
|
886
|
-
if (aborted())
|
|
887
|
-
break;
|
|
888
|
-
ack = ackPlugin.readGatewayQuiesceAck(context.workspaceDir);
|
|
889
|
-
// PRI-1282 review P2-2: the ack must bind THIS operation's state and
|
|
890
|
-
// THIS workspace too — an ack written for handover_preparing of another
|
|
891
|
-
// workspace (or a stale-marker state) is not this operation's evidence.
|
|
892
|
-
if (ack !== null
|
|
893
|
-
&& ack.operationId === operationId
|
|
894
|
-
&& ack.generation === preparingGeneration
|
|
895
|
-
&& ack.state === 'handover_preparing'
|
|
896
|
-
// PRI-1282 r4 §11: compare REAL directory identity, not lexical
|
|
897
|
-
// spelling — an ack persisted under a symlinked alias spelling must
|
|
898
|
-
// still bind this workspace (and a foreign spelling must not).
|
|
899
|
-
&& ackWorkspaceMatches(ack.workspaceDir, context.workspaceDir)
|
|
900
|
-
&& ack.outcome === 'quiesced'
|
|
901
|
-
&& ack.inFlightCycles === 0)
|
|
902
|
-
break;
|
|
903
|
-
await wait(2_000);
|
|
904
|
-
}
|
|
905
|
-
const ackDefect = ack === null
|
|
906
|
-
? 'gateway_quiesce_ack_absent'
|
|
907
|
-
: ack.operationId !== operationId
|
|
908
|
-
? 'gateway_quiesce_ack_operation_mismatch'
|
|
909
|
-
: ack.generation !== preparingGeneration
|
|
910
|
-
? 'gateway_quiesce_ack_generation_mismatch'
|
|
911
|
-
: ack.state !== 'handover_preparing'
|
|
912
|
-
? `gateway_quiesce_ack_state_mismatch:${ack.state}`
|
|
913
|
-
: !ackWorkspaceMatches(ack.workspaceDir, context.workspaceDir)
|
|
914
|
-
? 'gateway_quiesce_ack_workspace_mismatch'
|
|
915
|
-
: ack.outcome !== 'quiesced'
|
|
916
|
-
? `gateway_quiesce_ack_not_quiesced:${ack.outcome}`
|
|
917
|
-
: null;
|
|
918
|
-
if (ackDefect !== null) {
|
|
919
|
-
const rollback = transitionWorkspaceBackgroundExecution({ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir, kind: 'abort_handover', operationId, expectedGeneration: preparingGeneration });
|
|
920
|
-
record('quiesce_ack', 'missing_or_mismatched', ack === null ? 'no_ack_file' : `${ack.state}/${ack.operationId}/${ack.outcome}`);
|
|
921
|
-
if (!rollback.ok) {
|
|
922
|
-
return { ok: false, outcome: 'failed', reason: `quiesce_unproven_and_abort_failed:${ackDefect}|${rollback.reason}`, nextAction: 'The workspace is STUCK in handover_preparing — resolve manually (pd service handover --abort).', operationId };
|
|
923
|
-
}
|
|
924
|
-
return {
|
|
925
|
-
ok: false,
|
|
926
|
-
outcome: 'blocked',
|
|
927
|
-
reason: ackDefect,
|
|
928
|
-
nextAction: ackDefect === 'gateway_quiesce_ack_not_quiesced:in_flight_timeout'
|
|
929
|
-
? 'The Gateway reported an in-flight cycle it could not bound; retry the handover after the cycle settles.'
|
|
930
|
-
: ackDefect === 'gateway_quiesce_ack_operation_mismatch'
|
|
931
|
-
? 'The persisted ack belongs to a DIFFERENT handover operation; let this operation reach the Gateway (it may still be mid-tick) and retry, or restart the Gateway so its gates re-acknowledge.'
|
|
932
|
-
: 'Start or restart the OpenClaw Gateway so it can acknowledge the handover (its start gate writes the ack), then retry.',
|
|
933
|
-
operationId,
|
|
934
|
-
detail: ack ?? undefined,
|
|
935
|
-
};
|
|
936
|
-
}
|
|
937
|
-
if (ack === null) {
|
|
938
|
-
// Unreachable (a null ack always yields a defect above) — kept total for
|
|
939
|
-
// the type system; fail loudly rather than trust a silent pass-through.
|
|
940
|
-
return { ok: false, outcome: 'failed', reason: 'internal_ack_unexpected_null', nextAction: 'Retry the handover.', operationId };
|
|
941
|
-
}
|
|
942
|
-
record('quiesce_ack', 'quiesced', `startedVia=${ack.writer.startedVia}`);
|
|
943
|
-
// ── 5-7. Commit section — under the SAME install-level run mutex the
|
|
944
|
-
// scheduler and rollback serialize on (PRI-1282 review): holding it from
|
|
945
|
-
// before the flip until the first worker child exits means a rollback can
|
|
946
|
-
// never flip ownership back while this cycle is still consuming, and a
|
|
947
|
-
// managed run-once sees `already_running` instead of overlapping us. A
|
|
948
|
-
// bare `pd openclaw worker --once` stays lock-free BY DESIGN — it is the
|
|
949
|
-
// leaf consumer the orchestrators drive; serializing it too would
|
|
950
|
-
// self-deadlock every launch below. ──
|
|
951
|
-
const runLock = acquireServiceRunLock(context.pdHome);
|
|
952
|
-
if (!runLock.ok) {
|
|
953
|
-
return {
|
|
954
|
-
ok: false,
|
|
955
|
-
outcome: 'blocked',
|
|
956
|
-
reason: `service_run_in_progress:${runLock.kind}`,
|
|
957
|
-
nextAction: 'A managed run-once or rollback is currently executing; wait for it to finish and rerun the handover — the workspace stays handover_preparing and this operationId resumes.',
|
|
958
|
-
operationId,
|
|
959
|
-
};
|
|
960
|
-
}
|
|
961
|
-
try {
|
|
962
|
-
// The workspace mutex still held means a Worker child outlived its
|
|
963
|
-
// coordinator — refuse before flipping rather than overlap it.
|
|
964
|
-
const stillRunning = refuseWhileWorkerRunning(context, operationId);
|
|
965
|
-
if (stillRunning !== null)
|
|
966
|
-
return stillRunning;
|
|
967
|
-
// Persist the commit intent BEFORE the flip: the steady-state marker
|
|
968
|
-
// clears operationId, so a crash between flip and evidence write would
|
|
969
|
-
// leave the commit unattributable without it (PRI-1282 review).
|
|
970
|
-
const intentWritten = writeHandoverIntent({
|
|
971
|
-
schemaVersion: HANDOVER_INTENT_SCHEMA,
|
|
972
|
-
kind: 'handover',
|
|
973
|
-
operationId,
|
|
974
|
-
workspaceDir: context.workspaceDir,
|
|
975
|
-
preparingGeneration,
|
|
976
|
-
committedGeneration: preparingGeneration + 1,
|
|
977
|
-
writtenAt: nowIso(),
|
|
978
|
-
}, context.pdHome);
|
|
979
|
-
if (!intentWritten.ok) {
|
|
980
|
-
return { ok: false, outcome: 'failed', reason: `handover_intent_write_failed:${intentWritten.reason ?? 'io'}`, nextAction: 'The commit intent could not be persisted; the workspace stays handover_preparing — fix the write failure and rerun (the operation resumes).', operationId };
|
|
981
|
-
}
|
|
982
|
-
// ── 4b. Scheduler re-check (PRI-1282 r4 §9): the §1.5 gate proved the
|
|
983
|
-
// trigger was enabled at command start, but `pd service disable` may
|
|
984
|
-
// have landed between then and now (it serializes on the SAME install
|
|
985
|
-
// lock, so an in-flight handover never overlaps a live disable — a
|
|
986
|
-
// disable that completed before our lock acquisition is what this
|
|
987
|
-
// catches). Re-verify immediately before the irreversible flip.
|
|
988
|
-
const schedulerRecheck = options.probes?.schedulerStatus !== undefined
|
|
989
|
-
? await options.probes.schedulerStatus()
|
|
990
|
-
: await probeSchedulerEnabled(context, options.env);
|
|
991
|
-
if (!schedulerRecheck.ok || schedulerRecheck.registered !== true || schedulerRecheck.enabled !== true) {
|
|
992
|
-
const reason = !schedulerRecheck.ok
|
|
993
|
-
? `service_host_scheduler_status_unavailable:${schedulerRecheck.reason}`
|
|
994
|
-
: 'service_host_scheduler_not_enabled';
|
|
995
|
-
const rollback = transitionWorkspaceBackgroundExecution({
|
|
996
|
-
manifestPath: context.manifestPath, workspaceDir: context.workspaceDir, kind: 'abort_handover', operationId, expectedGeneration: preparingGeneration,
|
|
997
|
-
});
|
|
998
|
-
record('cas_flip', 'aborted', `scheduler_recheck:${reason}${rollback.ok ? '' : ` (abort_handover failed: ${rollback.ok === false ? rollback.reason : '?'})`}`);
|
|
999
|
-
return {
|
|
1000
|
-
ok: false,
|
|
1001
|
-
outcome: 'blocked',
|
|
1002
|
-
reason,
|
|
1003
|
-
nextAction: 'The Service Host scheduler was disabled or became unreadable during the handover; the preparing state was rolled back — enable it (`pd service enable`) and rerun `pd service handover`.',
|
|
1004
|
-
operationId,
|
|
1005
|
-
};
|
|
1006
|
-
}
|
|
1007
|
-
// ── 5. The single CAS flip. ──
|
|
1008
|
-
const flip = transitionWorkspaceBackgroundExecution({
|
|
1009
|
-
manifestPath: context.manifestPath, workspaceDir: context.workspaceDir, kind: 'complete_handover', operationId, expectedGeneration: preparingGeneration,
|
|
1010
|
-
});
|
|
1011
|
-
if (!flip.ok) {
|
|
1012
|
-
// unexpected_state on service_host_owned can mean a prior crashed run
|
|
1013
|
-
// already flipped: distinguish via the marker, never by guessing.
|
|
1014
|
-
const after = readWorkspaceBackgroundOwnership({ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir });
|
|
1015
|
-
if (after.status === 'service_host_owned') {
|
|
1016
|
-
record('cas_flip', 'already_service_host_owned', flip.reason);
|
|
1017
|
-
}
|
|
1018
|
-
else {
|
|
1019
|
-
return { ok: false, outcome: 'failed', reason: `complete_handover_failed:${flip.reason}`, nextAction: flip.nextAction ?? 'Re-read the ownership record and retry; the workspace is still handover_preparing.', operationId, detail: flip.message };
|
|
1020
|
-
}
|
|
1021
|
-
}
|
|
1022
|
-
else {
|
|
1023
|
-
record('cas_flip', 'service_host_owned', `generation=${flip.record.generation}`);
|
|
1024
|
-
}
|
|
1025
|
-
// ── 6. One real worker cycle through the SAME managed adapter the
|
|
1026
|
-
// scheduler drives — its contract already validates spawn, exit code,
|
|
1027
|
-
// workspace match and worker mode, so a failed/garbage first cycle is
|
|
1028
|
-
// never recorded as success (PRI-1282 review). ──
|
|
1029
|
-
const cycle = await runManagedOpenClawCycle({ homeDir: context.homeDir, workspaceDir: context.workspaceDir, invocationId: operationId, timeoutMs: Math.max(stepTimeoutMs, 10 * 60_000), ...(options.signal !== undefined ? { signal: options.signal } : {}) });
|
|
1030
|
-
record('worker_cycle', cycle.ok ? `${cycle.result.cycleOutcome}${cycle.result.workerMode !== undefined ? `(${cycle.result.workerMode})` : ''}` : cycle.reason);
|
|
1031
|
-
if (!cycle.ok || !verifiedCycleOutcome(cycle.result)) {
|
|
1032
|
-
// Ownership is committed but the FIRST cycle is not verified —
|
|
1033
|
-
// reported as a resumable failure, NEVER as a completed handover.
|
|
1034
|
-
return {
|
|
1035
|
-
ok: false,
|
|
1036
|
-
outcome: 'failed',
|
|
1037
|
-
reason: `first_cycle_unverified:${cycle.ok ? cycle.result.cycleOutcome : cycle.reason}`,
|
|
1038
|
-
nextAction: 'Ownership already flipped to the Service Host but the first managed cycle did not verify; fix the worker problem and rerun `pd service handover --resume <operationId>` to re-verify, or `pd service rollback` to return the workspace to the Gateway.',
|
|
1039
|
-
operationId,
|
|
1040
|
-
detail: cycle.ok ? (cycle.result.reason ?? cycle.result.worker.stderrTail ?? undefined) : cycle.nextAction,
|
|
1041
|
-
};
|
|
1042
|
-
}
|
|
1043
|
-
// ── 6b. Final ownership re-verification (PRI-1282 r4 §7): the worker
|
|
1044
|
-
// cycle verified, but 'completed' ALSO requires the authoritative
|
|
1045
|
-
// marker to still prove THIS operation's commit — status
|
|
1046
|
-
// service_host_owned at exactly the committed generation, backed by the
|
|
1047
|
-
// persisted commit intent bound to this operationId. A flipped-away or
|
|
1048
|
-
// re-generated marker means something else owns the workspace now —
|
|
1049
|
-
// report a resumable verification failure, never a completed handover.
|
|
1050
|
-
const finalOwnership = readWorkspaceBackgroundOwnership({ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir });
|
|
1051
|
-
const persistedIntent = readHandoverIntent(context.pdHome, context.workspaceDir, operationId);
|
|
1052
|
-
const verificationDefect = finalOwnership.status !== 'service_host_owned'
|
|
1053
|
-
? `final_ownership_status:${finalOwnership.status}`
|
|
1054
|
-
: finalOwnership.generation !== preparingGeneration + 1
|
|
1055
|
-
? `final_ownership_generation:${finalOwnership.generation}!=${preparingGeneration + 1}`
|
|
1056
|
-
: persistedIntent === null
|
|
1057
|
-
? 'commit_intent_absent'
|
|
1058
|
-
: persistedIntent.operationId !== operationId || persistedIntent.committedGeneration !== finalOwnership.generation
|
|
1059
|
-
? 'commit_intent_mismatch'
|
|
1060
|
-
: null;
|
|
1061
|
-
if (verificationDefect !== null) {
|
|
1062
|
-
return {
|
|
1063
|
-
ok: false,
|
|
1064
|
-
outcome: 'failed',
|
|
1065
|
-
reason: `final_ownership_verification_failed:${verificationDefect}`,
|
|
1066
|
-
nextAction: 'The first managed cycle verified but the final ownership state cannot be proven to be THIS operation\'s commit; rerun `pd service handover --resume` with this operationId to re-verify, or `pd service rollback` to return the workspace to the Gateway.',
|
|
1067
|
-
operationId,
|
|
1068
|
-
};
|
|
1069
|
-
}
|
|
1070
|
-
record('final_ownership_verification', 'verified', `generation=${preparingGeneration + 1}`);
|
|
1071
|
-
// ── 7. Completion evidence (write-once, operationId keyed). The
|
|
1072
|
-
// handover only reports completion when BOTH the verified cycle and
|
|
1073
|
-
// this write landed. ──
|
|
1074
|
-
const evidence = {
|
|
1075
|
-
schemaVersion: HANDOVER_EVIDENCE_SCHEMA,
|
|
1076
|
-
kind: 'handover',
|
|
1077
|
-
operationId,
|
|
1078
|
-
workspaceDir: context.workspaceDir,
|
|
1079
|
-
startedAt,
|
|
1080
|
-
completedAt: nowIso(),
|
|
1081
|
-
outcome: 'completed',
|
|
1082
|
-
steps,
|
|
1083
|
-
finalOwnership,
|
|
1084
|
-
};
|
|
1085
|
-
const written = writeHandoverEvidence(evidence, context.pdHome);
|
|
1086
|
-
if (!written.ok) {
|
|
1087
|
-
return { ok: false, outcome: 'failed', reason: `handover_evidence_write_failed:${written.reason ?? 'io'}`, nextAction: 'The first managed cycle verified but the completion evidence could not be persisted; fix the write failure and rerun `pd service handover --resume <operationId>`.', operationId };
|
|
1088
|
-
}
|
|
1089
|
-
return {
|
|
1090
|
-
ok: true,
|
|
1091
|
-
outcome: 'completed',
|
|
1092
|
-
operationId,
|
|
1093
|
-
workspaceDir: context.workspaceDir,
|
|
1094
|
-
generation: finalOwnership.status === 'service_host_owned' ? finalOwnership.generation : (flip.ok ? flip.record.generation : preparingGeneration),
|
|
1095
|
-
readiness: 'ready',
|
|
1096
|
-
quiesceAck: { operationId: ack.operationId ?? operationId, generation: ack.generation, outcome: ack.outcome, startedVia: ack.writer.startedVia },
|
|
1097
|
-
workerCycle: { mode: cycle.result.workerMode ?? cycle.result.cycleOutcome, exitCode: cycle.result.worker.exitCode, evidencePath: written.path },
|
|
1098
|
-
evidencePath: written.path,
|
|
1099
|
-
};
|
|
1100
|
-
}
|
|
1101
|
-
finally {
|
|
1102
|
-
releaseServiceRunLock(runLock.handle);
|
|
1103
|
-
}
|
|
1104
|
-
}
|
|
1105
|
-
export async function runWorkspaceRollback(workspaceDir, options) {
|
|
1106
|
-
const context = establishHandoverContext(workspaceDir, options);
|
|
1107
|
-
if (!context.ok)
|
|
1108
|
-
return { ok: false, outcome: 'blocked', reason: context.reason, nextAction: context.nextAction };
|
|
1109
|
-
if (options.resumeOperationId !== undefined && !isSafeOperationId(options.resumeOperationId)) {
|
|
1110
|
-
return { ok: false, outcome: 'blocked', reason: 'operation_id_invalid', nextAction: 'operationId may only contain letters, digits, dots, underscores and hyphens (1-128 chars).' };
|
|
1111
|
-
}
|
|
1112
|
-
const startedAt = nowIso();
|
|
1113
|
-
const steps = [];
|
|
1114
|
-
const record = (step, outcome, detail) => {
|
|
1115
|
-
steps.push({ step, at: nowIso(), outcome, ...(detail !== undefined ? { detail } : {}) });
|
|
1116
|
-
};
|
|
1117
|
-
// ── 1-3. Stop Service Host cycles: a held run-once lock means a managed
|
|
1118
|
-
// run is ACTIVE — the rollback refuses rather than race it. ──
|
|
1119
|
-
const runLock = acquireServiceRunLock(context.pdHome);
|
|
1120
|
-
if (!runLock.ok) {
|
|
1121
|
-
return {
|
|
1122
|
-
ok: false,
|
|
1123
|
-
outcome: 'blocked',
|
|
1124
|
-
reason: `service_run_in_progress:${runLock.kind}`,
|
|
1125
|
-
nextAction: 'A managed run-once is currently executing; wait for it to finish (workers are bounded) and retry the rollback.',
|
|
1126
|
-
};
|
|
1127
|
-
}
|
|
1128
|
-
try {
|
|
1129
|
-
const initial = readWorkspaceBackgroundOwnership({ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir });
|
|
1130
|
-
if (initial.status === 'manifest_unreadable') {
|
|
1131
|
-
return { ok: false, outcome: 'blocked', reason: `ownership_unreadable:${initial.reason}`, nextAction: initial.nextAction };
|
|
1132
|
-
}
|
|
1133
|
-
const resumeOp = initial.status === 'rollback_pending' ? initial.record.operationId : undefined;
|
|
1134
|
-
// ── --resume arbitration (PRI-1282 r4 §5/§8): an explicit resume may
|
|
1135
|
-
// only continue a REAL in-flight or already-committed operation.
|
|
1136
|
-
if (options.resumeOperationId !== undefined && resumeOp !== undefined && options.resumeOperationId !== resumeOp) {
|
|
1137
|
-
return {
|
|
1138
|
-
ok: false,
|
|
1139
|
-
outcome: 'blocked',
|
|
1140
|
-
reason: 'operation_id_mismatch',
|
|
1141
|
-
nextAction: `The in-flight rollback is ${resumeOp}; --resume must name that exact operation (or omit --resume to adopt it).`,
|
|
1142
|
-
operationId: resumeOp ?? undefined,
|
|
1143
|
-
};
|
|
1144
|
-
}
|
|
1145
|
-
if (options.resumeOperationId !== undefined && resumeOp === undefined) {
|
|
1146
|
-
const resumeIntent = readRollbackIntent(context.pdHome, context.workspaceDir, options.resumeOperationId);
|
|
1147
|
-
const canCompleteEvidence = initial.status === 'legacy_owned'
|
|
1148
|
-
&& resumeIntent !== null
|
|
1149
|
-
&& resumeIntent.workspaceDir === context.workspaceDir
|
|
1150
|
-
&& resumeIntent.committedGeneration === initial.generation;
|
|
1151
|
-
if (!canCompleteEvidence) {
|
|
1152
|
-
return {
|
|
1153
|
-
ok: false,
|
|
1154
|
-
outcome: 'blocked',
|
|
1155
|
-
reason: 'no_resumable_operation',
|
|
1156
|
-
nextAction: `No in-flight or committed-but-unevidenced rollback exists for this workspace to resume as '${options.resumeOperationId}'.`,
|
|
1157
|
-
operationId: options.resumeOperationId,
|
|
1158
|
-
};
|
|
1159
|
-
}
|
|
1160
|
-
// PRI-1282 r5 F6 — resume of an ALREADY-EVIDENCED operation returns
|
|
1161
|
-
// the ORIGINAL recorded conclusion, never a fabricated re-verification:
|
|
1162
|
-
// if the first run persisted evidence (including its real
|
|
1163
|
-
// gateway_resumption observation) and then crashed, the stored
|
|
1164
|
-
// document is the answer.
|
|
1165
|
-
const existingEvidence = readHandoverEvidence(context.pdHome, context.workspaceDir, options.resumeOperationId);
|
|
1166
|
-
if (existingEvidence !== null && existingEvidence.kind === 'rollback') {
|
|
1167
|
-
if (existingEvidence.outcome !== 'completed') {
|
|
1168
|
-
return {
|
|
1169
|
-
ok: false,
|
|
1170
|
-
outcome: 'failed',
|
|
1171
|
-
reason: `prior_operation_outcome:${existingEvidence.outcome}`,
|
|
1172
|
-
nextAction: 'The persisted evidence records this operation did not complete; inspect the evidence document, then run a NEW rollback.',
|
|
1173
|
-
operationId: options.resumeOperationId,
|
|
1174
|
-
};
|
|
1175
|
-
}
|
|
1176
|
-
const observedStep = existingEvidence.steps.find((entry) => entry.step === 'gateway_resumption');
|
|
1177
|
-
return {
|
|
1178
|
-
ok: true,
|
|
1179
|
-
outcome: 'completed',
|
|
1180
|
-
operationId: options.resumeOperationId,
|
|
1181
|
-
workspaceDir: context.workspaceDir,
|
|
1182
|
-
generation: initial.generation,
|
|
1183
|
-
gatewayResumption: observedStep?.outcome === 'observed' ? 'observed' : 'not_verified_gateway_not_running',
|
|
1184
|
-
evidencePath: handoverEvidencePath(context.pdHome, context.workspaceDir, options.resumeOperationId),
|
|
1185
|
-
};
|
|
1186
|
-
}
|
|
1187
|
-
// Evidence-only continuation: ownership already returned to the
|
|
1188
|
-
// Gateway at exactly the intent's committed generation — rewrite ONLY
|
|
1189
|
-
// the missing evidence, never re-run the transition (§8.6).
|
|
1190
|
-
record('resume', 'evidence_only_continuation', `generation=${initial.generation}`);
|
|
1191
|
-
const evidence = {
|
|
1192
|
-
schemaVersion: HANDOVER_EVIDENCE_SCHEMA,
|
|
1193
|
-
kind: 'rollback',
|
|
1194
|
-
operationId: options.resumeOperationId,
|
|
1195
|
-
workspaceDir: context.workspaceDir,
|
|
1196
|
-
startedAt,
|
|
1197
|
-
completedAt: nowIso(),
|
|
1198
|
-
outcome: 'completed',
|
|
1199
|
-
steps,
|
|
1200
|
-
finalOwnership: initial,
|
|
1201
|
-
};
|
|
1202
|
-
const written = writeHandoverEvidence(evidence, context.pdHome);
|
|
1203
|
-
if (!written.ok) {
|
|
1204
|
-
return {
|
|
1205
|
-
ok: false,
|
|
1206
|
-
outcome: 'failed',
|
|
1207
|
-
reason: `rollback_evidence_write_failed:${written.reason ?? 'io'}`,
|
|
1208
|
-
nextAction: 'Ownership already returned to the Gateway but the rollback evidence still cannot be persisted; fix the write failure and rerun `pd service rollback --resume` with this operationId.',
|
|
1209
|
-
operationId: options.resumeOperationId,
|
|
1210
|
-
};
|
|
1211
|
-
}
|
|
1212
|
-
return {
|
|
1213
|
-
ok: true,
|
|
1214
|
-
outcome: 'completed',
|
|
1215
|
-
operationId: options.resumeOperationId,
|
|
1216
|
-
workspaceDir: context.workspaceDir,
|
|
1217
|
-
generation: initial.generation,
|
|
1218
|
-
gatewayResumption: 'not_verified_gateway_not_running',
|
|
1219
|
-
evidencePath: written.path,
|
|
1220
|
-
};
|
|
1221
|
-
}
|
|
1222
|
-
const operationId = resumeOp ?? options.probes?.mintOperationId?.('rollback') ?? `rollback-${crypto.randomUUID()}`;
|
|
1223
|
-
// ── 4-6. begin_rollback FIRST, then drain, then complete_rollback
|
|
1224
|
-
// (PRI-1282 review P1-1 — ordering, not a new lock): flipping the marker
|
|
1225
|
-
// to rollback_pending closes the worker gate (`service_host_owned` is
|
|
1226
|
-
// the only consumable state) BEFORE we wait, so a worker that starts
|
|
1227
|
-
// after this CAS can never begin consuming. Probing the workspace mutex
|
|
1228
|
-
// first left a TOCTOU window: a worker launched between the probe and
|
|
1229
|
-
// the CAS passed the gate and kept consuming past complete_rollback →
|
|
1230
|
-
// two consumers on one workspace.
|
|
1231
|
-
const begin = transitionWorkspaceBackgroundExecution({
|
|
1232
|
-
manifestPath: context.manifestPath, workspaceDir: context.workspaceDir, kind: 'begin_rollback', operationId,
|
|
1233
|
-
});
|
|
1234
|
-
if (!begin.ok) {
|
|
1235
|
-
return { ok: false, outcome: 'blocked', reason: `begin_rollback_failed:${begin.reason}`, nextAction: begin.nextAction ?? 'Only a service_host_owned workspace can roll back.', operationId };
|
|
1236
|
-
}
|
|
1237
|
-
record('begin_rollback', begin.changed ? 'rollback_pending' : 'idempotent_replay', `generation=${begin.record.generation}`);
|
|
1238
|
-
const rollbackGeneration = begin.record.generation;
|
|
1239
|
-
// Now that new cycles are gated out, wait for the LAST in-flight cycle
|
|
1240
|
-
// to finish — the workspace run mutex is held by the worker child for
|
|
1241
|
-
// its whole cycle, so 'free' is the honest drain proof (bounded; a
|
|
1242
|
-
// timeout keeps the workspace safely rollback_pending and resumable).
|
|
1243
|
-
const workspaceRunLockPath = workspaceServiceRunLockPath(context.pdHome, context.workspaceDir);
|
|
1244
|
-
const drainDeadline = Date.now() + (options.stepTimeoutMs ?? DEFAULT_ROLLBACK_DRAIN_WAIT_MS);
|
|
1245
|
-
for (;;) {
|
|
1246
|
-
const probe = probeServiceRunLockState(workspaceRunLockPath);
|
|
1247
|
-
if (probe.state === 'free')
|
|
1248
|
-
break;
|
|
1249
|
-
if (probe.state !== 'held') {
|
|
1250
|
-
return {
|
|
1251
|
-
ok: false,
|
|
1252
|
-
outcome: 'blocked',
|
|
1253
|
-
reason: `service_host_worker_lock_unverifiable:${probe.detail ?? 'unknown'}`,
|
|
1254
|
-
nextAction: 'The workspace run mutex could not be verified; the workspace stays rollback_pending (fail-closed) — repair the stale lock under <pdHome>/service/workspace-runs/ and rerun the rollback.',
|
|
1255
|
-
operationId,
|
|
1256
|
-
};
|
|
1257
|
-
}
|
|
1258
|
-
if (Date.now() >= drainDeadline || options.signal?.aborted === true) {
|
|
1259
|
-
return {
|
|
1260
|
-
ok: false,
|
|
1261
|
-
outcome: 'blocked',
|
|
1262
|
-
reason: 'service_host_worker_drain_timeout',
|
|
1263
|
-
nextAction: 'A worker cycle still holds the workspace run mutex past the drain deadline; the workspace stays rollback_pending — wait for the bounded cycle to finish and rerun the rollback.',
|
|
1264
|
-
operationId,
|
|
1265
|
-
};
|
|
1266
|
-
}
|
|
1267
|
-
await wait(2_000);
|
|
1268
|
-
}
|
|
1269
|
-
record('worker_drain', 'workspace_run_mutex_free');
|
|
1270
|
-
// Persist the rollback intent BEFORE the CAS (PRI-1282 r4 §8): a run
|
|
1271
|
-
// killed between complete_rollback and the evidence write would
|
|
1272
|
-
// otherwise leave the flip unattributable — --resume verifies against
|
|
1273
|
-
// this intent and only rewrites the missing evidence.
|
|
1274
|
-
const intentWritten = writeRollbackIntent({
|
|
1275
|
-
schemaVersion: ROLLBACK_INTENT_SCHEMA,
|
|
1276
|
-
kind: 'rollback',
|
|
1277
|
-
operationId,
|
|
1278
|
-
workspaceDir: context.workspaceDir,
|
|
1279
|
-
pendingGeneration: rollbackGeneration,
|
|
1280
|
-
committedGeneration: rollbackGeneration + 1,
|
|
1281
|
-
writtenAt: nowIso(),
|
|
1282
|
-
}, context.pdHome);
|
|
1283
|
-
if (!intentWritten.ok) {
|
|
1284
|
-
return { ok: false, outcome: 'failed', reason: `rollback_intent_write_failed:${intentWritten.reason ?? 'io'}`, nextAction: 'The rollback intent could not be persisted; the workspace stays rollback_pending — fix the write failure and rerun `pd service rollback --resume` with this operationId.', operationId };
|
|
1285
|
-
}
|
|
1286
|
-
const finish = transitionWorkspaceBackgroundExecution({
|
|
1287
|
-
manifestPath: context.manifestPath, workspaceDir: context.workspaceDir, kind: 'complete_rollback', operationId, expectedGeneration: rollbackGeneration,
|
|
1288
|
-
});
|
|
1289
|
-
if (!finish.ok) {
|
|
1290
|
-
return { ok: false, outcome: 'failed', reason: `complete_rollback_failed:${finish.reason}`, nextAction: 'The workspace is rollback_pending — rerun the rollback command to complete it (fail-closed, never auto-cleared).', operationId };
|
|
1291
|
-
}
|
|
1292
|
-
record('complete_rollback', 'legacy_owned', `generation=${finish.record.generation}`);
|
|
1293
|
-
// ── 6b. Final ownership re-verification (PRI-1282 r4 §7): 'completed'
|
|
1294
|
-
// requires the authoritative marker to prove THIS rollback's commit —
|
|
1295
|
-
// legacy_owned at exactly the intent's committed generation.
|
|
1296
|
-
const verifyOwnership = readWorkspaceBackgroundOwnership({ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir });
|
|
1297
|
-
const verificationDefect = verifyOwnership.status !== 'legacy_owned'
|
|
1298
|
-
? `final_ownership_status:${verifyOwnership.status}`
|
|
1299
|
-
: verifyOwnership.generation !== rollbackGeneration + 1
|
|
1300
|
-
? `final_ownership_generation:${verifyOwnership.generation}!=${rollbackGeneration + 1}`
|
|
1301
|
-
: null;
|
|
1302
|
-
if (verificationDefect !== null) {
|
|
1303
|
-
return {
|
|
1304
|
-
ok: false,
|
|
1305
|
-
outcome: 'failed',
|
|
1306
|
-
reason: `final_ownership_verification_failed:${verificationDefect}`,
|
|
1307
|
-
nextAction: 'The rollback CAS committed but the final ownership state cannot be proven to be THIS operation\'s commit; rerun `pd service rollback --resume` with this operationId to re-verify.',
|
|
1308
|
-
operationId,
|
|
1309
|
-
};
|
|
1310
|
-
}
|
|
1311
|
-
record('final_ownership_verification', 'verified', `generation=${rollbackGeneration + 1}`);
|
|
1312
|
-
// ── 7-9. Observe the Gateway's resumption (bounded; honest NOT_VERIFIED
|
|
1313
|
-
// when the Gateway is not running — the start gate guarantees resumption
|
|
1314
|
-
// on its next launch, verified separately by the gate tests). ──
|
|
1315
|
-
let gatewayResumption = 'not_verified_gateway_not_running';
|
|
1316
|
-
const resumeDeadline = Date.now() + (options.ackWaitMs ?? DEFAULT_ROLLBACK_RESUME_WAIT_MS);
|
|
1317
|
-
const startedAtMs = Date.parse(startedAt);
|
|
1318
|
-
while (Date.now() < resumeDeadline) {
|
|
1319
|
-
if (options.signal?.aborted === true)
|
|
1320
|
-
break;
|
|
1321
|
-
const logsDir = path.join(context.workspaceDir, 'memory', 'logs');
|
|
1322
|
-
try {
|
|
1323
|
-
const logs = fs.readdirSync(logsDir).filter((name) => name.startsWith('SYSTEM_')).sort();
|
|
1324
|
-
for (const logName of logs.slice(-3)) {
|
|
1325
|
-
const text = fs.readFileSync(path.join(logsDir, logName), 'utf8');
|
|
1326
|
-
// PRI-1282 review P2-3: a resumption event only counts when its
|
|
1327
|
-
// SystemLogger timestamp is AT/AFTER this rollback started — a
|
|
1328
|
-
// substring hit on an older log line fabricated 'observed' from a
|
|
1329
|
-
// resumption that predates this rollback.
|
|
1330
|
-
for (const line of text.split('\n')) {
|
|
1331
|
-
const stamp = /^\[([^\]]+)\]\s*\[([A-Z_]+)\]/.exec(line);
|
|
1332
|
-
if (stamp === null || stamp[1] === undefined || stamp[2] === undefined)
|
|
1333
|
-
continue;
|
|
1334
|
-
const eventMs = Date.parse(stamp[1]);
|
|
1335
|
-
if (!Number.isFinite(eventMs) || eventMs < startedAtMs)
|
|
1336
|
-
continue;
|
|
1337
|
-
if (stamp[2] === 'INTERNALIZATION_CONSUMER_RESUMED' || stamp[2] === 'INTERNALIZATION_CONSUMER_STARTED') {
|
|
1338
|
-
gatewayResumption = 'observed';
|
|
1339
|
-
break;
|
|
1340
|
-
}
|
|
1341
|
-
}
|
|
1342
|
-
if (gatewayResumption === 'observed')
|
|
1343
|
-
break;
|
|
1344
|
-
}
|
|
1345
|
-
}
|
|
1346
|
-
catch {
|
|
1347
|
-
// No SystemLogger stream at all → Gateway has never run here in this
|
|
1348
|
-
// window; stays not_verified.
|
|
1349
|
-
}
|
|
1350
|
-
if (gatewayResumption === 'observed')
|
|
1351
|
-
break;
|
|
1352
|
-
await wait(3_000);
|
|
1353
|
-
}
|
|
1354
|
-
record('gateway_resumption', gatewayResumption);
|
|
1355
|
-
const evidence = {
|
|
1356
|
-
schemaVersion: HANDOVER_EVIDENCE_SCHEMA,
|
|
1357
|
-
kind: 'rollback',
|
|
1358
|
-
operationId,
|
|
1359
|
-
workspaceDir: context.workspaceDir,
|
|
1360
|
-
startedAt,
|
|
1361
|
-
completedAt: nowIso(),
|
|
1362
|
-
outcome: 'completed',
|
|
1363
|
-
steps,
|
|
1364
|
-
finalOwnership: verifyOwnership,
|
|
1365
|
-
};
|
|
1366
|
-
const written = writeHandoverEvidence(evidence, context.pdHome);
|
|
1367
|
-
// PRI-1282 review P2-3: the rollback did not complete if its audit
|
|
1368
|
-
// record could not be persisted — the ownership flip already happened,
|
|
1369
|
-
// so this reports a resumable failure, never silent success.
|
|
1370
|
-
if (!written.ok) {
|
|
1371
|
-
return {
|
|
1372
|
-
ok: false,
|
|
1373
|
-
outcome: 'failed',
|
|
1374
|
-
reason: `rollback_evidence_write_failed:${written.reason ?? 'io'}`,
|
|
1375
|
-
nextAction: 'Ownership already returned to the Gateway but the rollback evidence could not be persisted; fix the write failure and rerun `pd service rollback` to record it (the operation is idempotent).',
|
|
1376
|
-
operationId,
|
|
1377
|
-
};
|
|
1378
|
-
}
|
|
1379
|
-
return {
|
|
1380
|
-
ok: true,
|
|
1381
|
-
outcome: 'completed',
|
|
1382
|
-
operationId,
|
|
1383
|
-
workspaceDir: context.workspaceDir,
|
|
1384
|
-
generation: finish.record.generation,
|
|
1385
|
-
gatewayResumption,
|
|
1386
|
-
evidencePath: written.path,
|
|
1387
|
-
};
|
|
1388
|
-
}
|
|
1389
|
-
finally {
|
|
1390
|
-
releaseServiceRunLock(runLock.handle);
|
|
1391
|
-
}
|
|
1392
|
-
}
|
|
1393
|
-
//# sourceMappingURL=workspace-handover.js.map
|