create-principles-disciple 1.156.2 → 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.
Files changed (242) hide show
  1. package/_release/product-identity.json +2 -2
  2. package/codex-adapter/dist/worker/workspace-worker.d.ts +11 -3
  3. package/codex-adapter/dist/worker/workspace-worker.js +30 -16
  4. package/codex-adapter/package.json +1 -1
  5. package/console/dist/server/models/OwnerDecisionConsoleModel.js +33 -1
  6. package/console/dist/web/assets/app.js +3 -3
  7. package/core/dist/runtime/adversarial-loop.d.ts +8 -0
  8. package/core/dist/runtime/adversarial-loop.d.ts.map +1 -1
  9. package/core/dist/runtime/adversarial-loop.js +420 -45
  10. package/core/dist/runtime/adversarial-loop.js.map +1 -1
  11. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +3 -3
  12. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
  13. package/core/dist/runtime/feature-flags/plugin-surface-registry.d.ts.map +1 -1
  14. package/core/dist/runtime/feature-flags/plugin-surface-registry.js +0 -16
  15. package/core/dist/runtime/feature-flags/plugin-surface-registry.js.map +1 -1
  16. package/core/dist/runtime/index.d.ts +4 -0
  17. package/core/dist/runtime/index.d.ts.map +1 -1
  18. package/core/dist/runtime/index.js +10 -0
  19. package/core/dist/runtime/index.js.map +1 -1
  20. package/core/dist/runtime/internalization/artificer-runner.d.ts +9 -0
  21. package/core/dist/runtime/internalization/artificer-runner.d.ts.map +1 -1
  22. package/core/dist/runtime/internalization/artificer-runner.js +52 -0
  23. package/core/dist/runtime/internalization/artificer-runner.js.map +1 -1
  24. package/core/dist/runtime/internalization/correlation-lineage.d.ts +16 -3
  25. package/core/dist/runtime/internalization/correlation-lineage.d.ts.map +1 -1
  26. package/core/dist/runtime/internalization/correlation-lineage.js +4 -4
  27. package/core/dist/runtime/internalization/correlation-lineage.js.map +1 -1
  28. package/core/dist/runtime/internalization/evaluator-runner.d.ts +35 -0
  29. package/core/dist/runtime/internalization/evaluator-runner.d.ts.map +1 -1
  30. package/core/dist/runtime/internalization/evaluator-runner.js +390 -91
  31. package/core/dist/runtime/internalization/evaluator-runner.js.map +1 -1
  32. package/core/dist/runtime/internalization/internalization-orchestrator.d.ts +40 -13
  33. package/core/dist/runtime/internalization/internalization-orchestrator.d.ts.map +1 -1
  34. package/core/dist/runtime/internalization/internalization-orchestrator.js +520 -199
  35. package/core/dist/runtime/internalization/internalization-orchestrator.js.map +1 -1
  36. package/core/dist/runtime/internalization/internalization-transition-decision.js +1 -1
  37. package/core/dist/runtime/internalization/internalization-transition-decision.js.map +1 -1
  38. package/core/dist/runtime/internalization/owner-resolution-service.d.ts.map +1 -1
  39. package/core/dist/runtime/internalization/owner-resolution-service.js +10 -8
  40. package/core/dist/runtime/internalization/owner-resolution-service.js.map +1 -1
  41. package/core/dist/runtime/internalization/owner-review.d.ts +2 -0
  42. package/core/dist/runtime/internalization/owner-review.d.ts.map +1 -1
  43. package/core/dist/runtime/internalization/owner-review.js +17 -11
  44. package/core/dist/runtime/internalization/owner-review.js.map +1 -1
  45. package/core/dist/runtime/internalization/peer-runner-contracts.d.ts +2 -0
  46. package/core/dist/runtime/internalization/peer-runner-contracts.d.ts.map +1 -1
  47. package/core/dist/runtime/internalization/peer-runner-contracts.js.map +1 -1
  48. package/core/dist/runtime/internalization/pitask-metadata.d.ts +36 -1
  49. package/core/dist/runtime/internalization/pitask-metadata.d.ts.map +1 -1
  50. package/core/dist/runtime/internalization/pitask-metadata.js +23 -2
  51. package/core/dist/runtime/internalization/pitask-metadata.js.map +1 -1
  52. package/core/dist/runtime/internalization/repair-create.d.ts +73 -0
  53. package/core/dist/runtime/internalization/repair-create.d.ts.map +1 -0
  54. package/core/dist/runtime/internalization/repair-create.js +200 -0
  55. package/core/dist/runtime/internalization/repair-create.js.map +1 -0
  56. package/core/dist/runtime/internalization/repair-lineage-backfill.d.ts +94 -0
  57. package/core/dist/runtime/internalization/repair-lineage-backfill.d.ts.map +1 -0
  58. package/core/dist/runtime/internalization/repair-lineage-backfill.js +123 -0
  59. package/core/dist/runtime/internalization/repair-lineage-backfill.js.map +1 -0
  60. package/core/dist/runtime/internalization/repair-task-identity.d.ts +99 -4
  61. package/core/dist/runtime/internalization/repair-task-identity.d.ts.map +1 -1
  62. package/core/dist/runtime/internalization/repair-task-identity.js +225 -7
  63. package/core/dist/runtime/internalization/repair-task-identity.js.map +1 -1
  64. package/core/dist/runtime/internalization/revision-reopen.d.ts +56 -1
  65. package/core/dist/runtime/internalization/revision-reopen.d.ts.map +1 -1
  66. package/core/dist/runtime/internalization/revision-reopen.js +82 -39
  67. package/core/dist/runtime/internalization/revision-reopen.js.map +1 -1
  68. package/core/dist/runtime/internalization/rollout-reviewer-runner.d.ts +0 -7
  69. package/core/dist/runtime/internalization/rollout-reviewer-runner.d.ts.map +1 -1
  70. package/core/dist/runtime/internalization/rollout-reviewer-runner.js +13 -68
  71. package/core/dist/runtime/internalization/rollout-reviewer-runner.js.map +1 -1
  72. package/core/dist/runtime/internalization/successor-create.d.ts +69 -0
  73. package/core/dist/runtime/internalization/successor-create.d.ts.map +1 -0
  74. package/core/dist/runtime/internalization/successor-create.js +173 -0
  75. package/core/dist/runtime/internalization/successor-create.js.map +1 -0
  76. package/core/dist/runtime/internalization/successor-lookup.d.ts +50 -0
  77. package/core/dist/runtime/internalization/successor-lookup.d.ts.map +1 -0
  78. package/core/dist/runtime/internalization/successor-lookup.js +213 -0
  79. package/core/dist/runtime/internalization/successor-lookup.js.map +1 -0
  80. package/core/dist/runtime/runner/succeeded-result-recovery.d.ts +58 -0
  81. package/core/dist/runtime/runner/succeeded-result-recovery.d.ts.map +1 -0
  82. package/core/dist/runtime/runner/succeeded-result-recovery.js +117 -0
  83. package/core/dist/runtime/runner/succeeded-result-recovery.js.map +1 -0
  84. package/core/dist/runtime/store/runtime-state-manager.d.ts +1 -0
  85. package/core/dist/runtime/store/runtime-state-manager.d.ts.map +1 -1
  86. package/core/dist/runtime/store/runtime-state-manager.js +4 -0
  87. package/core/dist/runtime/store/runtime-state-manager.js.map +1 -1
  88. package/core/dist/runtime/store/task/memory-task-store.d.ts +3 -3
  89. package/core/dist/runtime/store/task/memory-task-store.d.ts.map +1 -1
  90. package/core/dist/runtime/store/task/memory-task-store.js +52 -0
  91. package/core/dist/runtime/store/task/memory-task-store.js.map +1 -1
  92. package/core/dist/runtime/store/task/sqlite-task-store.d.ts +3 -0
  93. package/core/dist/runtime/store/task/sqlite-task-store.d.ts.map +1 -1
  94. package/core/dist/runtime/store/task/sqlite-task-store.js +204 -135
  95. package/core/dist/runtime/store/task/sqlite-task-store.js.map +1 -1
  96. package/core/dist/runtime/store/task/task-store.d.ts +17 -0
  97. package/core/dist/runtime/store/task/task-store.d.ts.map +1 -1
  98. package/core/dist/telemetry-event.d.ts +2 -2
  99. package/core/dist/telemetry-event.d.ts.map +1 -1
  100. package/core/dist/telemetry-event.js +4 -0
  101. package/core/dist/telemetry-event.js.map +1 -1
  102. package/core/package.json +1 -1
  103. package/dist/index.js +1 -1
  104. package/dist/index.js.map +1 -1
  105. package/dist/installer.d.ts +69 -11
  106. package/dist/installer.d.ts.map +1 -1
  107. package/dist/installer.js +432 -120
  108. package/dist/installer.js.map +1 -1
  109. package/dist/service-host-bridge.d.ts +0 -5
  110. package/dist/service-host-bridge.d.ts.map +1 -1
  111. package/dist/service-host-bridge.js.map +1 -1
  112. package/dist/service-host-provisioning.d.ts +123 -18
  113. package/dist/service-host-provisioning.d.ts.map +1 -1
  114. package/dist/service-host-provisioning.js +645 -77
  115. package/dist/service-host-provisioning.js.map +1 -1
  116. package/dist/utils/env.d.ts +9 -0
  117. package/dist/utils/env.d.ts.map +1 -1
  118. package/dist/utils/env.js +269 -49
  119. package/dist/utils/env.js.map +1 -1
  120. package/host-runtime/dist/codex-worker-status.d.ts +6 -4
  121. package/host-runtime/dist/codex-worker-status.js +7 -5
  122. package/host-runtime/dist/diagnostician-auto-run.js +2 -2
  123. package/host-runtime/dist/governance-signal-admission.d.ts +2 -1
  124. package/host-runtime/dist/governance-signal-admission.js +2 -1
  125. package/host-runtime/dist/index.d.ts +4 -2
  126. package/host-runtime/dist/index.js +6 -2
  127. package/host-runtime/dist/internalization-consumer-cycle.d.ts +13 -106
  128. package/host-runtime/dist/internalization-consumer-cycle.js +21 -99
  129. package/host-runtime/dist/internalization-consumer-governance.d.ts +3 -3
  130. package/host-runtime/dist/internalization-consumer-governance.js +17 -96
  131. package/host-runtime/dist/internalization-task-executor.d.ts +127 -0
  132. package/host-runtime/dist/internalization-task-executor.js +121 -0
  133. package/host-runtime/dist/workbuddy-worker-status.d.ts +6 -3
  134. package/host-runtime/dist/workbuddy-worker-status.js +7 -4
  135. package/host-runtime/dist/workspace-telemetry-emitter.js +1 -1
  136. package/host-runtime/package.json +1 -1
  137. package/install-layout/dist/background-execution-transition.d.ts +25 -29
  138. package/install-layout/dist/background-execution-transition.js +90 -138
  139. package/install-layout/dist/index.d.ts +45 -33
  140. package/install-layout/dist/index.js +24 -18
  141. package/install-layout/package.json +1 -1
  142. package/package.json +5 -4
  143. package/pd-cli/dist/commands/codex-worker.d.ts +7 -3
  144. package/pd-cli/dist/commands/codex-worker.d.ts.map +1 -1
  145. package/pd-cli/dist/commands/codex-worker.js +125 -101
  146. package/pd-cli/dist/commands/codex-worker.js.map +1 -1
  147. package/pd-cli/dist/commands/runtime-internalization-enqueue-successors.d.ts.map +1 -1
  148. package/pd-cli/dist/commands/runtime-internalization-enqueue-successors.js +148 -130
  149. package/pd-cli/dist/commands/runtime-internalization-enqueue-successors.js.map +1 -1
  150. package/pd-cli/dist/commands/runtime-internalization-run-once.d.ts.map +1 -1
  151. package/pd-cli/dist/commands/runtime-internalization-run-once.js +4 -0
  152. package/pd-cli/dist/commands/runtime-internalization-run-once.js.map +1 -1
  153. package/pd-cli/dist/commands/runtime-internalization-run-rulehost.js +1 -1
  154. package/pd-cli/dist/commands/runtime-internalization-run-rulehost.js.map +1 -1
  155. package/pd-cli/dist/commands/service-run-once.d.ts +12 -27
  156. package/pd-cli/dist/commands/service-run-once.d.ts.map +1 -1
  157. package/pd-cli/dist/commands/service-run-once.js +15 -206
  158. package/pd-cli/dist/commands/service-run-once.js.map +1 -1
  159. package/pd-cli/dist/commands/workbuddy-worker.d.ts +7 -2
  160. package/pd-cli/dist/commands/workbuddy-worker.d.ts.map +1 -1
  161. package/pd-cli/dist/commands/workbuddy-worker.js +133 -99
  162. package/pd-cli/dist/commands/workbuddy-worker.js.map +1 -1
  163. package/pd-cli/dist/commands/worker-service-host-gate.d.ts +38 -0
  164. package/pd-cli/dist/commands/worker-service-host-gate.d.ts.map +1 -0
  165. package/pd-cli/dist/commands/worker-service-host-gate.js +110 -0
  166. package/pd-cli/dist/commands/worker-service-host-gate.js.map +1 -0
  167. package/pd-cli/dist/program.d.ts.map +1 -1
  168. package/pd-cli/dist/program.js +20 -84
  169. package/pd-cli/dist/program.js.map +1 -1
  170. package/pd-cli/dist/services/rulehost-pipeline-runner.d.ts.map +1 -1
  171. package/pd-cli/dist/services/rulehost-pipeline-runner.js +198 -142
  172. package/pd-cli/dist/services/rulehost-pipeline-runner.js.map +1 -1
  173. package/pd-cli/dist/services/service-host/coordinator-common.d.ts.map +1 -1
  174. package/pd-cli/dist/services/service-host/coordinator-common.js +4 -5
  175. package/pd-cli/dist/services/service-host/coordinator-common.js.map +1 -1
  176. package/pd-cli/dist/services/service-host/index.d.ts +7 -10
  177. package/pd-cli/dist/services/service-host/index.d.ts.map +1 -1
  178. package/pd-cli/dist/services/service-host/index.js +8 -11
  179. package/pd-cli/dist/services/service-host/index.js.map +1 -1
  180. package/pd-cli/dist/services/service-host/install-identity.d.ts +5 -5
  181. package/pd-cli/dist/services/service-host/managed-run.d.ts.map +1 -1
  182. package/pd-cli/dist/services/service-host/managed-run.js +19 -22
  183. package/pd-cli/dist/services/service-host/managed-run.js.map +1 -1
  184. package/pd-cli/dist/services/service-host/scheduler/linux.d.ts.map +1 -1
  185. package/pd-cli/dist/services/service-host/scheduler/linux.js +21 -2
  186. package/pd-cli/dist/services/service-host/scheduler/linux.js.map +1 -1
  187. package/pd-cli/dist/services/service-host/scheduler/service-status.d.ts +1 -1
  188. package/pd-cli/dist/services/service-host/scheduler/service-status.d.ts.map +1 -1
  189. package/pd-cli/dist/services/service-host/scheduler/service-status.js +0 -2
  190. package/pd-cli/dist/services/service-host/scheduler/service-status.js.map +1 -1
  191. package/pd-cli/dist/services/service-host/status/service-run-status.d.ts +7 -51
  192. package/pd-cli/dist/services/service-host/status/service-run-status.d.ts.map +1 -1
  193. package/pd-cli/dist/services/service-host/status/service-run-status.js.map +1 -1
  194. package/pd-cli/dist/services/service-host/worker-adapter-openclaw.js +3 -3
  195. package/pd-cli/dist/services/service-host/worker-adapter.d.ts +0 -10
  196. package/pd-cli/dist/services/service-host/worker-adapter.d.ts.map +1 -1
  197. package/pd-cli/dist/services/service-host/worker-adapter.js +4 -12
  198. package/pd-cli/dist/services/service-host/worker-adapter.js.map +1 -1
  199. package/pd-cli/dist/services/service-host/worker-env.d.ts +1 -1
  200. package/pd-cli/dist/services/service-host/workspace-dispatch.d.ts +5 -7
  201. package/pd-cli/dist/services/service-host/workspace-dispatch.d.ts.map +1 -1
  202. package/pd-cli/dist/services/service-host/workspace-dispatch.js +1 -3
  203. package/pd-cli/dist/services/service-host/workspace-dispatch.js.map +1 -1
  204. package/pd-cli/package.json +1 -1
  205. package/plugin/dist/bundle.js +616 -1319
  206. package/plugin/dist/core/openclaw-tool-declaration.d.ts +13 -0
  207. package/plugin/dist/index.d.ts +0 -9
  208. package/plugin/dist/openclaw-worker.d.ts +21 -8
  209. package/plugin/dist/openclaw-worker.js +267 -267
  210. package/plugin/dist/openclaw.plugin.json +1 -1
  211. package/plugin/openclaw.plugin.json +1 -1
  212. package/plugin/package.json +1 -1
  213. package/release-manager/dist/installer.js +432 -120
  214. package/release-manager/dist/service-host-provisioning.js +645 -77
  215. package/release-manager/dist/utils/env.js +269 -49
  216. package/release-manager/package.json +3 -2
  217. package/workbuddy-adapter/dist/worker/workspace-worker.d.ts +9 -1
  218. package/workbuddy-adapter/dist/worker/workspace-worker.js +21 -9
  219. package/workbuddy-adapter/package.json +1 -1
  220. package/pd-cli/dist/commands/service-handover.d.ts +0 -12
  221. package/pd-cli/dist/commands/service-handover.d.ts.map +0 -1
  222. package/pd-cli/dist/commands/service-handover.js +0 -117
  223. package/pd-cli/dist/commands/service-handover.js.map +0 -1
  224. package/pd-cli/dist/commands/worker-drain.d.ts +0 -7
  225. package/pd-cli/dist/commands/worker-drain.d.ts.map +0 -1
  226. package/pd-cli/dist/commands/worker-drain.js +0 -51
  227. package/pd-cli/dist/commands/worker-drain.js.map +0 -1
  228. package/pd-cli/dist/services/service-host/handover-claims.d.ts +0 -14
  229. package/pd-cli/dist/services/service-host/handover-claims.d.ts.map +0 -1
  230. package/pd-cli/dist/services/service-host/handover-claims.js +0 -50
  231. package/pd-cli/dist/services/service-host/handover-claims.js.map +0 -1
  232. package/pd-cli/dist/services/service-host/shadow-run.d.ts +0 -87
  233. package/pd-cli/dist/services/service-host/shadow-run.d.ts.map +0 -1
  234. package/pd-cli/dist/services/service-host/shadow-run.js +0 -549
  235. package/pd-cli/dist/services/service-host/shadow-run.js.map +0 -1
  236. package/pd-cli/dist/services/service-host/workspace-handover.d.ts +0 -190
  237. package/pd-cli/dist/services/service-host/workspace-handover.d.ts.map +0 -1
  238. package/pd-cli/dist/services/service-host/workspace-handover.js +0 -1393
  239. package/pd-cli/dist/services/service-host/workspace-handover.js.map +0 -1
  240. package/plugin/dist/service/gateway-consumer-lease.d.ts +0 -142
  241. package/plugin/dist/service/gateway-quiesce-ack.d.ts +0 -40
  242. package/plugin/dist/service/internalization-auto-consumer-service.d.ts +0 -100
@@ -1,16 +1,19 @@
1
1
  /**
2
- * Fresh-install Service Host provisioning (PRI-1278 Phase 5).
2
+ * Service Host ownership provisioning (PRI-1278 consolidation).
3
3
  *
4
- * A brand-new PD install hands its NEW workspace to the PD-owned Service Host
5
- * in the same installer run:
4
+ * The PD Service Host is the ONLY background runtime: the Companion worker
5
+ * runtime and the Gateway auto-consumer are deleted repo-wide, so there is
6
+ * no legacy consumer left to quiesce. Provisioning hands a workspace to the
7
+ * Service Host in one atomic write from ANY prior ownership state — a
8
+ * pre-consolidation record (including interrupted handover/rollback residue)
9
+ * cannot prove a live consumer anymore:
6
10
  *
7
11
  * 1. the workspace is already registered in the canonical manifest;
8
12
  * 2. a no-consume Worker readiness probe runs through the ACTIVE RELEASE
9
13
  * (`pd <host> worker --readiness` / `--status`), never through the
10
14
  * installer's own code;
11
- * 3. the §8.4 CAS provision transition writes `service_host_owned`
12
- * atomically (generation 1) — there is no legacy consumer to quiesce,
13
- * and the marker itself blocks every legacy consumer from starting;
15
+ * 3. the provision CAS transition writes `service_host_owned` atomically
16
+ * (the only surviving transition kind; flips any residue state);
14
17
  * 4. one bounded REAL managed cycle runs (`pd service run-once`);
15
18
  * 5. an auditable provisioning record is written under `<pdHome>/service/`.
16
19
  *
@@ -18,18 +21,20 @@
18
21
  * - this module NEVER owns scheduler lifecycle or ownership semantics — both
19
22
  * are delegated to their existing single implementations (`pd service …`
20
23
  * and `@principles/install-layout`);
21
- * - it only runs for a FRESH install whose scheduler was verified ENABLED;
22
- * a failed/absent scheduler never flips ownership (no silent migration);
23
- * - an upgrade never calls it — existing workspaces migrate through
24
- * `pd service handover`;
24
+ * - ownership is handed over ONLY when the scheduler is verified enabled —
25
+ * a failed/absent scheduler leaves a fail-closed pending record instead
26
+ * (there is no companion fallback);
27
+ * - on an upgrade install the caller proves first that no legacy continuous
28
+ * worker process still consumes the workspace (the one-time switch
29
+ * evidence gate); a positive or unverifiable scan stays pending;
25
30
  * - no credential, token or environment snapshot is written to argv, the
26
31
  * evidence file or logs.
27
32
  */
33
+ import { execFileSync } from 'node:child_process';
28
34
  import * as fs from 'node:fs';
29
35
  import * as path from 'node:path';
30
36
  import { readWorkspaceBackgroundOwnership, transitionWorkspaceBackgroundExecution, } from '@principles/install-layout';
31
37
  import { runInstalledCliJson, } from './service-host-bridge.js';
32
- import { checkOpenClawGateway } from './utils/env.js';
33
38
  const DEFAULT_FIRST_CYCLE_TIMEOUT_MS = 180_000;
34
39
  const EVIDENCE_SCHEMA = 'pd.service-install-provisioning.v1';
35
40
  const PENDING_SCHEMA = 'pd.service-pending-provisioning.v1';
@@ -53,6 +58,478 @@ function canonicalIdentity(value) {
53
58
  const form = stableWorkspacePath(value);
54
59
  return process.platform === 'win32' ? form.toLowerCase() : form;
55
60
  }
61
+ /**
62
+ * The legacy continuous-worker shape: `<host> worker --workspace <dir>`
63
+ * WITHOUT `--once`. Post-consolidation workers are always bounded `--once`
64
+ * cycles the Service Host spawns; a worker process without `--once` can only
65
+ * be a pre-upgrade continuous child the deleted Companion runtime spawned.
66
+ * Returns the `--workspace` value when the command line matches.
67
+ */
68
+ export function matchLegacyWorkerCommandLine(commandLine) {
69
+ if (/(^|\\s)--once(?=\s|$)/.test(commandLine))
70
+ return null;
71
+ if (!/(^|\s)worker(?=\s|$)/.test(commandLine))
72
+ return null;
73
+ const workspace = /(?:^|\s)--workspace(?:\s+|=)(?:"([^"]+)"|'([^']+)'|(\S+))/.exec(commandLine);
74
+ return workspace?.[1] ?? workspace?.[2] ?? workspace?.[3] ?? null;
75
+ }
76
+ const LEGACY_WORKER_HOSTS = new Set(['codex', 'workbuddy']);
77
+ /**
78
+ * argv-token matcher for platforms that expose exact process arguments.
79
+ * Unlike command-line scraping, a workspace containing spaces is one token
80
+ * here and can never be truncated. The host token must immediately precede
81
+ * `worker`, which keeps unrelated Node processes out of the match set.
82
+ */
83
+ export function matchLegacyWorkerArgv(argv) {
84
+ // Inspect every exact `<host> worker` pair. Mode flags are interpreted only
85
+ // in the argument stream after that subcommand; a workspace VALUE such as
86
+ // `--once` is consumed as a value and must not suppress detection.
87
+ for (let workerIndex = 1; workerIndex < argv.length; workerIndex += 1) {
88
+ if (argv[workerIndex] !== 'worker' || !LEGACY_WORKER_HOSTS.has(argv[workerIndex - 1] ?? ''))
89
+ continue;
90
+ let continuous = true;
91
+ let workspaceDir = null;
92
+ for (let index = workerIndex + 1; index < argv.length; index += 1) {
93
+ const token = argv[index];
94
+ if (token === '--workspace') {
95
+ const value = argv[index + 1];
96
+ if (typeof value === 'string' && value.length > 0) {
97
+ workspaceDir = value;
98
+ index += 1;
99
+ }
100
+ continue;
101
+ }
102
+ if (token?.startsWith('--workspace=') === true) {
103
+ const value = token.slice('--workspace='.length);
104
+ if (value.length > 0)
105
+ workspaceDir = value;
106
+ continue;
107
+ }
108
+ // `--once` is the new bounded mode. `--status`/`--readiness` are
109
+ // no-consume probes, not continuous consumers.
110
+ if (token === '--once' || token === '--status' || token === '--readiness')
111
+ continuous = false;
112
+ }
113
+ if (continuous && workspaceDir !== null)
114
+ return workspaceDir;
115
+ }
116
+ return null;
117
+ }
118
+ /**
119
+ * Windows process entries are a single CommandLine string, not an argv array.
120
+ * Parse the MSVC/CommandLineToArgvW quoting rules closely enough for the
121
+ * installer-produced worker shape; malformed whitespace/token structure is a
122
+ * scan failure rather than a false clean result.
123
+ */
124
+ export function parseWindowsCommandLineArgv(commandLine) {
125
+ const argv = [];
126
+ let current = '';
127
+ let inQuotes = false;
128
+ let tokenActive = false;
129
+ let backslashes = 0;
130
+ for (const char of commandLine) {
131
+ if (char === '\\') {
132
+ backslashes += 1;
133
+ continue;
134
+ }
135
+ if (char === '"') {
136
+ current += '\\'.repeat(Math.floor(backslashes / 2));
137
+ if (backslashes % 2 === 0) {
138
+ // A quote preceded by an even number of backslashes toggles quoting;
139
+ // inside quotes a doubled quote is represented by the sequence rules
140
+ // closely enough for paths produced by Node/Windows installers.
141
+ inQuotes = !inQuotes;
142
+ tokenActive = true;
143
+ }
144
+ else {
145
+ current += '"';
146
+ tokenActive = true;
147
+ }
148
+ backslashes = 0;
149
+ continue;
150
+ }
151
+ current += '\\'.repeat(backslashes);
152
+ backslashes = 0;
153
+ if ((char === ' ' || char === '\t') && !inQuotes) {
154
+ if (tokenActive || current.length > 0)
155
+ argv.push(current);
156
+ current = '';
157
+ tokenActive = false;
158
+ continue;
159
+ }
160
+ current += char;
161
+ tokenActive = true;
162
+ }
163
+ current += '\\'.repeat(backslashes);
164
+ if (tokenActive || current.length > 0 || argv.length === 0)
165
+ argv.push(current);
166
+ return argv.length > 0 && argv.every((token) => typeof token === 'string') ? argv : null;
167
+ }
168
+ /**
169
+ * Parse the Darwin `KERN_PROCARGS2` payload. Layout: int32 argc, exec path,
170
+ * NUL padding, then exactly argc NUL-terminated argv entries followed by envp.
171
+ * Returning null is parse failure, never "no argv".
172
+ */
173
+ export function parseDarwinProcArgs2(raw) {
174
+ if (raw.length < 4)
175
+ return null;
176
+ const argc = raw.readInt32LE(0);
177
+ if (!Number.isInteger(argc) || argc < 1 || argc > 4096)
178
+ return null;
179
+ const execEnd = raw.indexOf(0, 4);
180
+ if (execEnd < 4 || execEnd === raw.length - 1)
181
+ return null;
182
+ // Apple pads the executable path with NUL bytes before argv. Empty leading
183
+ // argv entries are inherently ambiguous with that padding in this kernel
184
+ // format; for normal host-launched workers argv[0] is non-empty. Parse the
185
+ // selected entries byte-wise and require every one to be NUL-terminated so
186
+ // truncation can never masquerade as a complete argument.
187
+ let cursor = execEnd + 1;
188
+ while (cursor < raw.length && raw[cursor] === 0)
189
+ cursor += 1;
190
+ if (cursor >= raw.length)
191
+ return null;
192
+ const argv = [];
193
+ for (let index = 0; index < argc; index += 1) {
194
+ const end = raw.indexOf(0, cursor);
195
+ if (end < 0)
196
+ return null;
197
+ argv.push(raw.subarray(cursor, end).toString('utf8'));
198
+ cursor = end + 1;
199
+ if (cursor > raw.length && index < argc - 1)
200
+ return null;
201
+ }
202
+ return argv;
203
+ }
204
+ /** One-shot Darwin argv reader. Ruby/Fiddle is a transient interpreter use, not a service. */
205
+ const DARWIN_ARGV_READER = String.raw `
206
+ require 'fiddle'
207
+ require 'fiddle/import'
208
+ module PdSysctl
209
+ extend Fiddle::Importer
210
+ dlload '/usr/lib/libSystem.B.dylib'
211
+ extern 'int sysctl(void*, unsigned int, void*, void*, void*, unsigned long)'
212
+ end
213
+ pid_state = lambda do |pid|
214
+ begin
215
+ Process.kill(0, pid)
216
+ rescue Errno::ESRCH
217
+ next 'exited'
218
+ rescue Errno::EPERM
219
+ next 'live'
220
+ end
221
+ # kill(pid, 0) still succeeds for an unreaped zombie. KERN_PROCARGS2 then
222
+ # fails with EINVAL even though no consumer threads remain, so classify the
223
+ # current process-table state at the moment the read fails/succeeds.
224
+ stat_io = IO.popen(['/bin/ps', '-o', 'stat=', '-p', pid.to_s], err: File::NULL)
225
+ stat = stat_io.read.strip
226
+ stat_io.close
227
+ ps_ok = !$?.nil? && $?.success?
228
+ if stat.empty? && ps_ok
229
+ 'exited'
230
+ elsif stat.empty?
231
+ # ps itself failing is not evidence of exit. Re-check liveness; a process
232
+ # still present but whose state cannot be inspected remains fail-closed.
233
+ begin
234
+ Process.kill(0, pid)
235
+ 'live'
236
+ rescue Errno::ESRCH
237
+ 'exited'
238
+ end
239
+ elsif stat.start_with?('Z')
240
+ 'zombie'
241
+ else
242
+ 'live'
243
+ end
244
+ end
245
+ emit_failure = lambda do |pid, reason|
246
+ # A process that disappeared or became zombie residue after enumeration no
247
+ # longer consumes anything; a live process whose argv cannot be inspected is
248
+ # unverifiable and must stay fail-closed.
249
+ if pid_state.call(pid) == 'live'
250
+ puts "#{pid}\tERROR:#{reason}"
251
+ else
252
+ puts "#{pid}\tEXITED"
253
+ end
254
+ end
255
+ ARGV.each do |pid_text|
256
+ pid = pid_text.to_i
257
+ next if pid <= 1
258
+ begin
259
+ unless pid_state.call(pid) != 'exited'
260
+ puts "#{pid}\tEXITED"
261
+ next
262
+ end
263
+ mib = [1, 49, pid].pack('l<3')
264
+ size = [0].pack('Q<')
265
+ if PdSysctl.sysctl(mib, 3, nil, size, nil, 0) != 0
266
+ emit_failure.call(pid, 'sysctl_size')
267
+ next
268
+ end
269
+ len = size.unpack1('Q<')
270
+ if len < 4 || len > 8 * 1024 * 1024
271
+ emit_failure.call(pid, 'invalid_size')
272
+ next
273
+ end
274
+ if len > 8 * 1024 * 1024
275
+ emit_failure.call(pid, 'oversized')
276
+ next
277
+ end
278
+ raw = nil
279
+ attempts = 0
280
+ while attempts < 3 && raw.nil?
281
+ attempts += 1
282
+ buf = Fiddle::Pointer.malloc(len)
283
+ size = Fiddle::Pointer.malloc(8)
284
+ size[0, 8] = [len].pack('Q<')
285
+ if PdSysctl.sysctl(mib, 3, buf, size, nil, 0) != 0
286
+ errno = Fiddle.last_error
287
+ if errno == Errno::ENOMEM::Errno && attempts < 3
288
+ # The argument area can grow while a process execs; re-query instead
289
+ # of accepting a truncation-prone fixed ceiling.
290
+ size_probe = Fiddle::Pointer.malloc(8)
291
+ size_probe[0, 8] = [0].pack('Q<')
292
+ if PdSysctl.sysctl(mib, 3, nil, size_probe, nil, 0) == 0
293
+ new_len = size_probe.to_str(8).unpack1('Q<')
294
+ if new_len >= 4 && new_len <= 8 * 1024 * 1024
295
+ len = new_len
296
+ next
297
+ end
298
+ end
299
+ end
300
+ emit_failure.call(pid, "sysctl_read:#{errno || 'unknown'}")
301
+ break
302
+ end
303
+ out_len = size.to_str(8).unpack1('Q<')
304
+ if out_len < 4 || out_len > len
305
+ emit_failure.call(pid, 'invalid_read_size')
306
+ break
307
+ end
308
+ raw = buf.to_str(out_len)
309
+ end
310
+ next if raw.nil?
311
+ puts "#{pid}\t#{raw.unpack1('H*')}"
312
+ rescue Errno::ESRCH
313
+ puts "#{pid}\tEXITED"
314
+ rescue SystemCallError => e
315
+ emit_failure.call(pid, "#{e.class.name}:#{e.respond_to?(:errno) ? e.errno : 'unknown'}")
316
+ rescue => e
317
+ emit_failure.call(pid, e.class.name)
318
+ end
319
+ end
320
+ `;
321
+ /**
322
+ * Decode the one-shot Darwin reader protocol. `EXITED` rows are safe scan
323
+ * residue; every malformed or `ERROR` row is fail-closed scan evidence rather
324
+ * than proof that no legacy worker exists. Exported for focused regression tests.
325
+ */
326
+ export function parseDarwinArgvReaderOutput(output) {
327
+ const rows = [];
328
+ const failures = [];
329
+ for (const line of output.split('\n')) {
330
+ const trimmed = line.trimEnd();
331
+ if (trimmed.length === 0)
332
+ continue;
333
+ const tab = trimmed.indexOf('\t');
334
+ const pid = Number.parseInt(trimmed.slice(0, tab), 10);
335
+ if (!(tab > 0 && Number.isInteger(pid) && pid > 1)) {
336
+ failures.push(`unparseable row ${trimmed.slice(0, 80)}`);
337
+ continue;
338
+ }
339
+ const payload = trimmed.slice(tab + 1);
340
+ if (payload === 'EXITED')
341
+ continue;
342
+ if (payload.startsWith('ERROR:')) {
343
+ failures.push(`pid ${pid}: ${payload.slice('ERROR:'.length)}`);
344
+ continue;
345
+ }
346
+ if (!/^(?:[0-9a-fA-F]{2})+$/.test(payload)) {
347
+ failures.push(`pid ${pid}: malformed hex payload`);
348
+ continue;
349
+ }
350
+ const raw = Buffer.from(payload, 'hex');
351
+ const argv = parseDarwinProcArgs2(raw);
352
+ if (argv === null) {
353
+ failures.push(`pid ${pid}: malformed KERN_PROCARGS2 payload`);
354
+ continue;
355
+ }
356
+ rows.push({ pid, commandLine: argv.join(' '), argv });
357
+ }
358
+ if (failures.length > 0) {
359
+ throw new Error(`darwin argv reader evidence unverifiable (${failures.slice(0, 5).join('; ')}${failures.length > 5 ? '; …' : ''})`);
360
+ }
361
+ return rows;
362
+ }
363
+ function listDarwinProcessRows(afterEnumeration) {
364
+ // `-x` is NOT a same-user filter on Darwin: it also exposes unrelated
365
+ // daemons, and KERN_PROCARGS2 can return EINVAL for another account's
366
+ // process. Legacy installer-spawned workers belong to the install user, so
367
+ // filter ownership before reading argv. A same-user process that still
368
+ // cannot be inspected remains fail-closed in the Ruby reader.
369
+ const currentUser = execFileSync('/usr/bin/id', ['-un'], { encoding: 'utf8', timeout: 10_000, windowsHide: true }).trim();
370
+ if (currentUser.length === 0)
371
+ throw new Error('darwin scan could not resolve the current user');
372
+ const pidOutput = execFileSync('/bin/ps', ['-xo', 'pid=,user=,stat=,comm='], { encoding: 'utf8', timeout: 10_000, windowsHide: true });
373
+ const pids = [];
374
+ for (const line of pidOutput.split('\n')) {
375
+ const trimmed = line.trim();
376
+ if (trimmed.length === 0)
377
+ continue;
378
+ const [pidText, user, stat, commandText] = trimmed.split(/\s+/);
379
+ const pid = Number.parseInt(pidText ?? '', 10);
380
+ if (!(Number.isInteger(pid) && pid > 1) || typeof user !== 'string' || user.length === 0 || typeof stat !== 'string' || stat.length === 0 || typeof commandText !== 'string' || commandText.length === 0) {
381
+ throw new Error(`darwin ps returned an unparseable process row: ${trimmed.slice(0, 80)}`);
382
+ }
383
+ // Legacy workers are Node processes. Restricting the expensive
384
+ // KERN_PROCARGS2 pass to Node keeps the scan bounded on a real macOS host
385
+ // while preserving exact argv evidence for every process that can match.
386
+ if (user !== currentUser || stat.startsWith('Z') || path.basename(commandText) !== 'node')
387
+ continue;
388
+ pids.push(pid);
389
+ }
390
+ if (pids.length === 0)
391
+ return [];
392
+ afterEnumeration?.();
393
+ const output = execFileSync('/usr/bin/ruby', ['-e', DARWIN_ARGV_READER, ...pids.map(String)], {
394
+ encoding: 'utf8',
395
+ timeout: 30_000,
396
+ windowsHide: true,
397
+ maxBuffer: 32 * 1024 * 1024,
398
+ });
399
+ return parseDarwinArgvReaderOutput(output);
400
+ }
401
+ /**
402
+ * Parse the Windows owner-scoped process table emitted by the PowerShell
403
+ * enumerator. Ownership filtering is deliberate migration evidence, so it is
404
+ * a pure TypeScript contract rather than hidden script text: a process whose
405
+ * owner resolves to another account is not installer evidence at all, while a
406
+ * same-user or owner-unresolved process with an unreadable command line stays
407
+ * fail-closed.
408
+ */
409
+ export function parseWindowsProcessRows(output) {
410
+ const rows = [];
411
+ let currentUser;
412
+ for (const rawLine of output.split('\n')) {
413
+ const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
414
+ if (line.length === 0)
415
+ continue;
416
+ if (line.startsWith('CURRENT\t')) {
417
+ currentUser = line.slice('CURRENT\t'.length);
418
+ continue;
419
+ }
420
+ const [pidText, ownerState, owner, encodedCommandLine, extra] = line.split('\t');
421
+ const pid = Number.parseInt(pidText ?? '', 10);
422
+ if (!Number.isInteger(pid) || pid <= 0 || typeof ownerState !== 'string' || typeof encodedCommandLine !== 'string' || extra !== undefined) {
423
+ throw new Error(`Windows process row unparseable: ${line.slice(0, 80)}`);
424
+ }
425
+ if (ownerState === 'resolved' && typeof currentUser === 'string' && currentUser.length > 0
426
+ && typeof owner === 'string' && owner.toLowerCase() !== currentUser.toLowerCase()) {
427
+ continue;
428
+ }
429
+ const commandLine = Buffer.from(encodedCommandLine, 'base64').toString('utf16le');
430
+ if (commandLine.length === 0) {
431
+ throw new Error(`Windows process command line unreadable for pid ${pid}`);
432
+ }
433
+ const argv = parseWindowsCommandLineArgv(commandLine);
434
+ if (argv === null)
435
+ throw new Error(`Windows process command line unparseable for pid ${pid}`);
436
+ rows.push({ pid, commandLine, argv });
437
+ }
438
+ if (typeof currentUser !== 'string' || currentUser.length === 0) {
439
+ throw new Error('Windows process scan did not identify the current user');
440
+ }
441
+ return rows;
442
+ }
443
+ /** Platform process table as (pid, commandLine/argv) rows — bounded, read-only. */
444
+ function listProcessRows(platform, afterDarwinEnumeration) {
445
+ if (platform === 'win32') {
446
+ // powershell.exe is the project-allowlisted process-query host (wmic is
447
+ // gone since Windows 11 24H2). EncodedCommand because Node→PowerShell
448
+ // argv quoting corrupts embedded quotes in -Command strings. PowerShell
449
+ // only ENUMERATES pid/owner/command-line evidence here; ownership policy
450
+ // and fail-closed parsing stay in parseWindowsProcessRows where adversarial
451
+ // owner/unreadable combinations are directly testable.
452
+ const script = `[Console]::OutputEncoding=[System.Text.Encoding]::UTF8; $ProgressPreference = 'SilentlyContinue'; "CURRENT\`t$([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)"; Get-CimInstance Win32_Process -Filter "Name='node.exe'" | ForEach-Object { $ownerState = 'unresolved'; $owner = ''; try { $ownerResult = Invoke-CimMethod -InputObject $_ -MethodName GetOwner; if ($ownerResult.ReturnValue -eq 0) { $ownerState = 'resolved'; $owner = "$($ownerResult.Domain)\\$($ownerResult.User)" } } catch { $ownerState = 'query_failed' }; $cmd = $_.CommandLine; if ($null -eq $cmd) { $cmd = '' }; $encodedCmd = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($cmd)); "$($_.ProcessId)\`t$ownerState\`t$owner\`t$encodedCmd" }`;
453
+ const encoded = Buffer.from(script, 'utf16le').toString('base64');
454
+ const output = execFileSync('powershell.exe', ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], { encoding: 'utf8', timeout: 15_000, windowsHide: true });
455
+ return parseWindowsProcessRows(output);
456
+ }
457
+ const rows = [];
458
+ if (platform === 'linux') {
459
+ // `/proc/<pid>/cmdline` preserves exact argv boundaries with NUL separators.
460
+ // Flattening Linux argv through `ps ... args` is ownership-unsafe because a
461
+ // workspace such as `/tmp/pd legacy worker/workspace` is indistinguishable
462
+ // from multiple independent arguments.
463
+ const procEntries = fs.readdirSync('/proc', { withFileTypes: true });
464
+ const unreadable = [];
465
+ for (const entry of procEntries) {
466
+ if (!entry.isDirectory() || !/^\d+$/.test(entry.name))
467
+ continue;
468
+ const pid = Number.parseInt(entry.name, 10);
469
+ const cmdlinePath = path.join('/proc', entry.name, 'cmdline');
470
+ let raw;
471
+ try {
472
+ raw = fs.readFileSync(cmdlinePath);
473
+ }
474
+ catch (error) {
475
+ const { code } = error;
476
+ // ENOENT/ESRCH means the process exited between directory enumeration
477
+ // and the read; an exited process cannot still consume the workspace.
478
+ if (code !== 'ENOENT' && code !== 'ESRCH')
479
+ unreadable.push(`${entry.name}:${code ?? 'read_failed'}`);
480
+ continue;
481
+ }
482
+ const argv = raw.toString('utf8').split('\0');
483
+ if (argv[argv.length - 1] === '')
484
+ argv.pop();
485
+ if (argv.length === 0)
486
+ continue; // kernel threads and zombies carry no argv
487
+ rows.push({ pid, commandLine: argv.join(' '), argv });
488
+ }
489
+ if (unreadable.length > 0) {
490
+ throw new Error(`/proc cmdline unreadable for pid(s) ${unreadable.slice(0, 5).join(',')}${unreadable.length > 5 ? '…' : ''}`);
491
+ }
492
+ return rows;
493
+ }
494
+ if (platform === 'darwin')
495
+ return listDarwinProcessRows(afterDarwinEnumeration);
496
+ // Other POSIX process APIs do not expose a portable argv-boundary-safe table.
497
+ // Returning a flat `ps args` parse would fabricate confidence; quiesce is
498
+ // unverifiable instead (the caller's fail-closed gate stays pending).
499
+ throw new Error(`legacy worker scan unsupported on platform ${platform}: argv boundaries cannot be verified`);
500
+ }
501
+ /**
502
+ * One bounded scan of the process table for legacy continuous workers.
503
+ *
504
+ * Rationale (one-time switch, PRI-1278 consolidation): the upgrade replaced
505
+ * the binaries and the Companion restart kills its continuous worker
506
+ * children — but "the binary is new" is not evidence that no old child
507
+ * survived, and a surviving child becomes a second consumer the moment
508
+ * ownership flips. This probe is the evidence gate: it runs once per upgrade
509
+ * install before the first provision write — no retry machinery, no daemon.
510
+ * A positive or unverifiable scan keeps the workspace pending (fail-closed);
511
+ * the next install re-verifies.
512
+ */
513
+ export function scanRunningLegacyWorkerProcesses(options = {}) {
514
+ let rows;
515
+ try {
516
+ rows = options.rows !== undefined ? options.rows() : listProcessRows(options.platform ?? process.platform, options.afterDarwinEnumeration);
517
+ }
518
+ catch (error) {
519
+ return { ok: false, workers: [], detail: `process scan failed: ${error instanceof Error ? error.message : String(error)}` };
520
+ }
521
+ const workers = [];
522
+ for (const row of rows) {
523
+ if (row.pid === process.pid)
524
+ continue;
525
+ const workspaceDir = row.argv !== undefined
526
+ ? matchLegacyWorkerArgv(row.argv)
527
+ : matchLegacyWorkerCommandLine(row.commandLine);
528
+ if (workspaceDir !== null)
529
+ workers.push({ pid: row.pid, workspaceDir });
530
+ }
531
+ return { ok: true, workers };
532
+ }
56
533
  function readinessProbeArgs(host, workspaceDir) {
57
534
  // OpenClaw has a dedicated no-consume readiness mode; Codex / WorkBuddy
58
535
  // answer the same question through their `--status` mode (no cycle runs).
@@ -137,31 +614,49 @@ function countExecutions(doc, workspaceDir) {
137
614
  return { executed, progressed, waitingForBinding };
138
615
  }
139
616
  async function runFirstCycle(input) {
140
- const result = await runInstalledCliJson(input.pdHome, ['service', 'run-once', '--trigger', 'installer', '--json'], {
141
- probes: input.probes ?? {},
142
- timeoutMs: input.firstCycleTimeoutMs ?? DEFAULT_FIRST_CYCLE_TIMEOUT_MS,
143
- });
144
- if (!result.ok || !isRecord(result.doc)) {
145
- return { ...notAttempted(result.detail), attempted: true };
146
- }
147
- const { doc } = result;
148
- const outcome = typeof doc.outcome === 'string' ? doc.outcome : 'unknown';
149
- if (outcome === 'already_running') {
150
- // Overlapping OS trigger won the install-level lock: honest deferral, not
151
- // a failed install, and not a fabricated success either.
152
- return { ...notAttempted('service_run_lock_held'), attempted: true, outcome };
617
+ const budgetMs = input.firstCycleTimeoutMs ?? DEFAULT_FIRST_CYCLE_TIMEOUT_MS;
618
+ const deadline = performance.now() + budgetMs;
619
+ for (;;) {
620
+ const remainingMs = deadline - performance.now();
621
+ if (remainingMs <= 0)
622
+ return { ...notAttempted('first_cycle_timeout'), attempted: true };
623
+ const result = await runInstalledCliJson(input.pdHome, ['service', 'run-once', '--trigger', 'installer', '--json'], {
624
+ probes: input.probes ?? {},
625
+ timeoutMs: remainingMs,
626
+ });
627
+ if (!isRecord(result.doc)) {
628
+ return { ...notAttempted(result.detail), attempted: true };
629
+ }
630
+ const { doc } = result;
631
+ const outcome = typeof doc.outcome === 'string' ? doc.outcome : 'unknown';
632
+ if (outcome === 'already_running') {
633
+ // Enabling a systemd timer on a machine whose uptime already exceeds
634
+ // OnBootSec can start the OS-triggered run immediately. Overlap is
635
+ // healthy, but the installer still owes first-cycle evidence for THIS
636
+ // ownership write: wait inside the existing bounded budget for the
637
+ // holder to finish, then run the installer-triggered cycle once.
638
+ if (deadline - performance.now() > 1_100) {
639
+ await new Promise((resolve) => setTimeout(resolve, 1_000));
640
+ continue;
641
+ }
642
+ return { ...notAttempted('service_run_lock_held'), attempted: true, outcome };
643
+ }
644
+ const { executed, progressed, waitingForBinding } = countExecutions(doc, input.workspaceDir);
645
+ return {
646
+ attempted: true,
647
+ ok: result.code === 0 && (doc.ok === true || outcome === 'completed'),
648
+ ...(outcome !== 'unknown' ? { outcome } : {}),
649
+ ...(typeof doc.runId === 'string' ? { runId: doc.runId } : {}),
650
+ executed,
651
+ progressed,
652
+ waitingForBinding,
653
+ ...(typeof doc.reason === 'string'
654
+ ? { reason: doc.reason }
655
+ : result.code !== 0
656
+ ? { reason: result.detail }
657
+ : {}),
658
+ };
153
659
  }
154
- const { executed, progressed, waitingForBinding } = countExecutions(doc, input.workspaceDir);
155
- return {
156
- attempted: true,
157
- ok: result.code === 0 && (doc.ok === true || outcome === 'completed'),
158
- ...(outcome !== 'unknown' ? { outcome } : {}),
159
- ...(typeof doc.runId === 'string' ? { runId: doc.runId } : {}),
160
- executed,
161
- progressed,
162
- waitingForBinding,
163
- ...(typeof doc.reason === 'string' ? { reason: doc.reason } : {}),
164
- };
165
660
  }
166
661
  function writeEvidence(pdHome, evidence) {
167
662
  const dir = path.join(pdHome, 'service');
@@ -293,6 +788,11 @@ function clearPending(pdHome, workspaceDir, warn) {
293
788
  warn(`Pending provisioning record could not be updated (${error instanceof Error ? error.message : String(error)}).`);
294
789
  }
295
790
  }
791
+ function findPendingEntry(pdHome, workspaceDir) {
792
+ const { entries } = readPendingRegistry(pdHome);
793
+ const identity = canonicalIdentity(workspaceDir);
794
+ return entries.find((entry) => canonicalIdentity(entry.workspaceDir) === identity);
795
+ }
296
796
  function limitationsFor(host, readiness) {
297
797
  const limitations = [];
298
798
  if (host === 'none') {
@@ -304,7 +804,8 @@ function limitationsFor(host, readiness) {
304
804
  return limitations;
305
805
  }
306
806
  /**
307
- * Provision ONE fresh-install workspace into Service Host ownership.
807
+ * Provision ONE workspace into Service Host ownership — a fresh install's
808
+ * new workspace or a deferred/upgrade resume converging residue state.
308
809
  * Returns a structured outcome; never throws for expected refusals (rc-9).
309
810
  */
310
811
  export async function provisionFreshInstallWorkspace(input) {
@@ -328,8 +829,8 @@ export async function provisionFreshInstallWorkspace(input) {
328
829
  };
329
830
  }
330
831
  if (before.status === 'service_host_owned') {
331
- // The workspace reached ownership another way (e.g. `pd service handover`);
332
- // its pending hint is stale and must not be resumed again.
832
+ // The workspace already converged (an earlier provisioning run or a
833
+ // replay); its pending hint is stale and must not be resumed again.
333
834
  clearPending(input.pdHome, input.workspaceDir, warn);
334
835
  return {
335
836
  ownership: 'already_owned',
@@ -342,22 +843,10 @@ export async function provisionFreshInstallWorkspace(input) {
342
843
  warnings,
343
844
  };
344
845
  }
345
- if (before.status !== 'legacy_owned' || before.source !== 'no_record') {
346
- // Any recorded history (including legacy_owned) is an UPGRADE: it must go
347
- // through the quiescing handover, never through fresh provisioning.
348
- clearPending(input.pdHome, input.workspaceDir, warn);
349
- return {
350
- ownership: 'not_provisioned',
351
- ownershipBefore: before.status,
352
- ownershipAfter: before.status,
353
- generation: before.generation,
354
- readiness: 'skipped',
355
- firstCycle: notAttempted('ownership_history_present'),
356
- pendingProvisioning: false,
357
- nextAction: 'This workspace already has an ownership record, so the installer did not change it. Move it explicitly with `pd service handover --workspace <dir>` (legacy consumer quiesce + readiness) or keep the legacy lifecycle.',
358
- warnings,
359
- };
360
- }
846
+ // Every other persisted state — no record, an explicit legacy_owned record,
847
+ // or interrupted handover/rollback residue — is flippable residue in the
848
+ // Service-Host-only model: the legacy consumer implementation is deleted
849
+ // repo-wide, so no recorded history can prove a live consumer anymore.
361
850
  const recordPending = (reason, args) => {
362
851
  const recordedAt = (input.now?.() ?? new Date()).toISOString();
363
852
  // Per-workspace hint: `--host all` produces multiple targets, and the
@@ -419,28 +908,44 @@ export async function provisionFreshInstallWorkspace(input) {
419
908
  }
420
909
  // Guard: ownership is only handed over when the scheduler is VERIFIED
421
910
  // enabled. A registration that failed or stayed disabled must never flip
422
- // the marker (no silent legacy retirement) — it records a PENDING
423
- // provisioning fact instead so a later explicit install can resume.
911
+ // the marker — there is no companion fallback — so it records a PENDING
912
+ // provisioning fact instead, and a later explicit install can resume.
424
913
  if (input.scheduler.state !== 'enabled' || input.scheduler.enabled !== true) {
425
914
  return recordPending(`scheduler_${input.scheduler.state}`, {
426
915
  readiness: 'skipped',
427
916
  firstCycle: notAttempted(`scheduler_${input.scheduler.state}`),
428
- nextAction: `${input.scheduler.nextAction} Workspace ownership was NOT handed over because the scheduler is not verified enabled. This new workspace is recorded as pending; after arming the scheduler, re-run: npx create-principles-disciple install --enable-service-host --workspace "${input.workspaceDir}"`,
917
+ nextAction: `${input.scheduler.nextAction} Workspace ownership was NOT handed over because the scheduler is not verified enabled. This workspace is recorded as pending; after arming the scheduler, re-run: npx create-principles-disciple install --enable-service-host --workspace "${input.workspaceDir}"`,
429
918
  });
430
919
  }
431
- // A DEFERRED resume proves only that the first install did not hand over —
432
- // not that no legacy consumer started afterwards. With a running OpenClaw
433
- // Gateway, flipping ownership here would create a second consumer; the
434
- // controlled handover (Gateway quiesce ack) is the only safe path.
435
- if (input.resume === true && (input.host === 'openclaw' || input.host === 'all')) {
436
- const gatewayRunning = input.probes?.gatewayRunning !== undefined
437
- ? await input.probes.gatewayRunning()
438
- : (await checkOpenClawGateway()).isRunning;
439
- if (gatewayRunning) {
440
- return recordPending('legacy_consumer_running', {
920
+ // Static caller-supplied scan evidence is a pre-readiness gate. When a
921
+ // scan function is supplied, the same scan is refreshed again immediately
922
+ // before CAS below; positive/unverifiable evidence never reaches readiness.
923
+ if (input.legacyWorkerScan !== undefined) {
924
+ const scan = input.legacyWorkerScan;
925
+ const identity = canonicalIdentity(input.workspaceDir);
926
+ const matches = scan.workers.filter((worker) => canonicalIdentity(worker.workspaceDir) === identity);
927
+ if (!scan.ok || matches.length > 0) {
928
+ const detail = !scan.ok
929
+ ? `the legacy worker process scan could not verify quiesce (${scan.detail ?? 'scan failed'})`
930
+ : `legacy continuous worker process(es) still consume this workspace (pid ${matches.map((match) => match.pid).join(', ')})`;
931
+ return recordPending('legacy_worker_still_running', {
932
+ readiness: 'skipped',
933
+ firstCycle: notAttempted('legacy_worker_still_running'),
934
+ nextAction: `Ownership was NOT handed over: ${detail}. Restart the machine first — or let the Companion update finish retiring its old worker processes — then re-run: npx create-principles-disciple install --enable-service-host --workspace "${input.workspaceDir}"`,
935
+ });
936
+ }
937
+ }
938
+ // OpenClaw's legacy consumer was an in-process Gateway timer chain, so the
939
+ // continuous-worker argv scan cannot see it. An upgrade ownership transfer
940
+ // requires positive installer-scoped proof that the old Gateway is absent or
941
+ // the observed process exited; absence of evidence is fail-closed pending.
942
+ if (input.requireOpenClawGatewayQuiesce === true && (input.host === 'openclaw' || input.host === 'all')) {
943
+ const quiesce = input.openClawGatewayQuiesce;
944
+ if (quiesce?.ok !== true) {
945
+ return recordPending('openclaw_gateway_unproven', {
441
946
  readiness: 'skipped',
442
- firstCycle: notAttempted('legacy_consumer_running'),
443
- nextAction: `A running OpenClaw Gateway may still consume this workspace, so ownership was NOT handed over. Quiesce it through the controlled handover: pd service handover --workspace "${input.workspaceDir}" — or stop the Gateway (openclaw gateway stop) and re-run this install.`,
947
+ firstCycle: notAttempted('openclaw_gateway_unproven'),
948
+ nextAction: `Ownership was NOT handed over because the pre-upgrade OpenClaw Gateway process could not be proven quiescent (${quiesce?.reason ?? 'no quiesce evidence'}). Stop the OpenClaw Gateway and re-run: npx create-principles-disciple install --enable-service-host --workspace "${input.workspaceDir}"`,
444
949
  });
445
950
  }
446
951
  }
@@ -453,13 +958,78 @@ export async function provisionFreshInstallWorkspace(input) {
453
958
  nextAction: `The active-release Worker readiness probe failed (${readiness.detail ?? 'unknown'}), so workspace ownership was NOT handed over. Fix the host adapter/workspace readiness, then re-run: npx create-principles-disciple install --enable-service-host --workspace "${input.workspaceDir}"`,
454
959
  });
455
960
  }
961
+ // Re-verify at the CAS boundary. The first scan may have selected this
962
+ // target, but readiness probing is asynchronous; ownership evidence must be
963
+ // fresh enough that no legacy worker appeared during that window.
964
+ const casBoundaryScan = input.legacyWorkerScanFn?.() ?? input.legacyWorkerScan;
965
+ if (casBoundaryScan !== undefined) {
966
+ const identity = canonicalIdentity(input.workspaceDir);
967
+ const matches = casBoundaryScan.workers.filter((worker) => canonicalIdentity(worker.workspaceDir) === identity);
968
+ if (!casBoundaryScan.ok || matches.length > 0) {
969
+ const detail = !casBoundaryScan.ok
970
+ ? `the legacy worker process scan could not verify quiesce (${casBoundaryScan.detail ?? 'scan failed'})`
971
+ : `legacy continuous worker process(es) still consume this workspace (pid ${matches.map((match) => match.pid).join(', ')})`;
972
+ return recordPending('legacy_worker_still_running', {
973
+ readiness: readiness.readiness,
974
+ ...(readiness.detail !== undefined ? { readinessDetail: readiness.detail } : {}),
975
+ firstCycle: notAttempted('legacy_worker_still_running'),
976
+ nextAction: `Ownership was NOT handed over: ${detail}. Restart the machine first — or let the Companion update finish retiring its old worker processes — then re-run: npx create-principles-disciple install --enable-service-host --workspace "${input.workspaceDir}"`,
977
+ });
978
+ }
979
+ }
980
+ // Re-verify OpenClaw quiescence at the CAS boundary as well. The initial
981
+ // evidence was collected before a long install transaction and readiness
982
+ // probes; ownership must not flip if the Gateway returned in that window.
983
+ if (input.requireOpenClawGatewayQuiesce === true && (input.host === 'openclaw' || input.host === 'all')) {
984
+ let boundaryQuiesce = input.openClawGatewayQuiesce;
985
+ if (input.openClawGatewayQuiesceFn !== undefined) {
986
+ try {
987
+ boundaryQuiesce = await input.openClawGatewayQuiesceFn();
988
+ }
989
+ catch (error) {
990
+ boundaryQuiesce = { ok: false, reason: `Gateway quiescence re-verification failed: ${error instanceof Error ? error.message : String(error)}` };
991
+ }
992
+ }
993
+ if (boundaryQuiesce?.ok !== true) {
994
+ return recordPending('openclaw_gateway_unproven', {
995
+ readiness: readiness.readiness,
996
+ ...(readiness.detail !== undefined ? { readinessDetail: readiness.detail } : {}),
997
+ firstCycle: notAttempted('openclaw_gateway_unproven'),
998
+ nextAction: `Ownership was NOT handed over because OpenClaw Gateway quiescence could not be re-verified immediately before the ownership write (${boundaryQuiesce?.reason ?? 'no quiesce evidence'}). Stop the OpenClaw Gateway and re-run: npx create-principles-disciple install --enable-service-host --workspace "${input.workspaceDir}"`,
999
+ });
1000
+ }
1001
+ }
1002
+ // Host-binding evidence is likewise stale after asynchronous readiness work.
1003
+ // A binding that appeared, disappeared, or changed during that window means
1004
+ // the readiness/quiescence evidence was gathered for the wrong host set.
1005
+ if (input.hostBindingReverification !== undefined) {
1006
+ const reverified = input.hostBindingReverification();
1007
+ if (!reverified.ok) {
1008
+ return recordPending('binding_unverifiable', {
1009
+ readiness: readiness.readiness,
1010
+ ...(readiness.detail !== undefined ? { readinessDetail: readiness.detail } : {}),
1011
+ firstCycle: notAttempted('binding_unverifiable'),
1012
+ nextAction: `${reverified.nextAction} Ownership was NOT handed over because the workspace's host binding could not be re-verified immediately before the ownership write (${reverified.reason}).`,
1013
+ });
1014
+ }
1015
+ if (reverified.host !== input.host) {
1016
+ return recordPending('binding_changed', {
1017
+ readiness: readiness.readiness,
1018
+ ...(readiness.detail !== undefined ? { readinessDetail: readiness.detail } : {}),
1019
+ firstCycle: notAttempted('binding_changed'),
1020
+ nextAction: `Ownership was NOT handed over because the workspace host binding changed during provisioning (${input.host} -> ${reverified.host}). Re-run: npx create-principles-disciple install --enable-service-host --workspace "${input.workspaceDir}"`,
1021
+ });
1022
+ }
1023
+ }
456
1024
  const operationId = `install-provision-${input.now?.().getTime() ?? Date.now()}-${process.pid}`;
1025
+ // provision_fresh_install is the only surviving transition kind, redefined
1026
+ // as from-ANY-state → service_host_owned: residue records flip in the same
1027
+ // atomic write as a no-record workspace (generation fencing still applies).
457
1028
  const provisioned = transitionWorkspaceBackgroundExecution({
458
1029
  manifestPath,
459
1030
  workspaceDir: input.workspaceDir,
460
1031
  kind: 'provision_fresh_install',
461
1032
  operationId,
462
- freshInstall: true,
463
1033
  registerWorkspace: true,
464
1034
  expectedGeneration: before.generation,
465
1035
  });
@@ -555,9 +1125,9 @@ export async function provisionFreshInstallWorkspace(input) {
555
1125
  *
556
1126
  * A multi-host install (`--host all`) records one entry per ACTUAL workspace
557
1127
  * instead of overwriting a single document, so a later explicit enable can
558
- * resume all of them. This is a HINT, never an ownership authority: the caller
559
- * still requires explicit enable consent and an ownership record with no
560
- * history (`provision_fresh_install` enforces both).
1128
+ * resume all of them. This is a HINT, never an ownership authority: the
1129
+ * caller still requires explicit enable consent, and the provisioning CAS
1130
+ * itself converges any residue ownership state in one atomic write.
561
1131
  */
562
1132
  export function readAllPendingProvisioning(pdHome) {
563
1133
  const { entries, warning } = readPendingRegistry(pdHome);
@@ -576,12 +1146,10 @@ export function readAllPendingProvisioning(pdHome) {
576
1146
  * Read the pending hint for ONE workspace.
577
1147
  *
578
1148
  * Unreadable/foreign records are `null` (fail-closed, never a guess); the
579
- * caller then leaves the workspace in legacy ownership.
1149
+ * caller then leaves the workspace un-provisioned.
580
1150
  */
581
1151
  export function readPendingProvisioningEvidence(pdHome, workspaceDir) {
582
- const { entries } = readPendingRegistry(pdHome);
583
- const identity = canonicalIdentity(workspaceDir);
584
- const found = entries.find((entry) => canonicalIdentity(entry.workspaceDir) === identity);
1152
+ const found = findPendingEntry(pdHome, workspaceDir);
585
1153
  return found === undefined
586
1154
  ? null
587
1155
  : {