create-principles-disciple 1.155.2 → 1.156.0

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 (247) hide show
  1. package/_release/product-identity.json +2 -2
  2. package/codex-adapter/dist/ingestion/pain-receipt-fallback.d.ts +28 -1
  3. package/codex-adapter/dist/ingestion/pain-receipt-fallback.js +53 -17
  4. package/codex-adapter/dist/worker/workspace-worker.js +86 -66
  5. package/codex-adapter/package.json +1 -1
  6. package/console/dist/server/index.d.ts +11 -1
  7. package/console/dist/server/index.js +84 -19
  8. package/console/dist/server/release-handover.d.ts +256 -0
  9. package/console/dist/server/release-handover.js +402 -0
  10. package/console/dist/server/routes/onboarding.js +1 -0
  11. package/console/dist/server/routes/update-transaction.js +37 -3
  12. package/console/dist/server/routes/update.js +21 -1
  13. package/console/dist/server/successor.d.ts +46 -0
  14. package/console/dist/server/successor.js +128 -0
  15. package/console/dist/web/assets/app.css +18 -0
  16. package/console/dist/web/assets/app.js +32 -31
  17. package/console/package.json +2 -2
  18. package/core/dist/runtime/candidate-intake-service.d.ts +1 -1
  19. package/core/dist/runtime/candidate-intake-service.d.ts.map +1 -1
  20. package/core/dist/runtime/candidate-intake-service.js +89 -12
  21. package/core/dist/runtime/candidate-intake-service.js.map +1 -1
  22. package/core/dist/runtime/context-payload.d.ts +11 -0
  23. package/core/dist/runtime/context-payload.d.ts.map +1 -1
  24. package/core/dist/runtime/context-payload.js +27 -0
  25. package/core/dist/runtime/context-payload.js.map +1 -1
  26. package/core/dist/runtime/host-submission-context.d.ts +13 -6
  27. package/core/dist/runtime/host-submission-context.d.ts.map +1 -1
  28. package/core/dist/runtime/host-submission-context.js +77 -8
  29. package/core/dist/runtime/host-submission-context.js.map +1 -1
  30. package/core/dist/runtime/index.d.ts +2 -1
  31. package/core/dist/runtime/index.d.ts.map +1 -1
  32. package/core/dist/runtime/index.js +8 -0
  33. package/core/dist/runtime/index.js.map +1 -1
  34. package/core/dist/runtime/pain-ingress.d.ts +8 -0
  35. package/core/dist/runtime/pain-ingress.d.ts.map +1 -1
  36. package/core/dist/runtime/pain-ingress.js +8 -1
  37. package/core/dist/runtime/pain-ingress.js.map +1 -1
  38. package/core/dist/runtime/pain-recall-read-model.d.ts +72 -0
  39. package/core/dist/runtime/pain-recall-read-model.d.ts.map +1 -1
  40. package/core/dist/runtime/pain-recall-read-model.js +46 -21
  41. package/core/dist/runtime/pain-recall-read-model.js.map +1 -1
  42. package/core/dist/runtime/pain-receipt-recovery.d.ts +4 -1
  43. package/core/dist/runtime/pain-receipt-recovery.d.ts.map +1 -1
  44. package/core/dist/runtime/pain-receipt-recovery.js +28 -10
  45. package/core/dist/runtime/pain-receipt-recovery.js.map +1 -1
  46. package/core/dist/runtime/pain-signal-bridge.d.ts +38 -23
  47. package/core/dist/runtime/pain-signal-bridge.d.ts.map +1 -1
  48. package/core/dist/runtime/pain-signal-bridge.js +533 -182
  49. package/core/dist/runtime/pain-signal-bridge.js.map +1 -1
  50. package/core/dist/runtime/pain-signal-runtime-factory.d.ts +8 -1
  51. package/core/dist/runtime/pain-signal-runtime-factory.d.ts.map +1 -1
  52. package/core/dist/runtime/pain-signal-runtime-factory.js +196 -25
  53. package/core/dist/runtime/pain-signal-runtime-factory.js.map +1 -1
  54. package/core/dist/runtime/pain-target-evidence-reconcile.d.ts +78 -4
  55. package/core/dist/runtime/pain-target-evidence-reconcile.d.ts.map +1 -1
  56. package/core/dist/runtime/pain-target-evidence-reconcile.js +229 -18
  57. package/core/dist/runtime/pain-target-evidence-reconcile.js.map +1 -1
  58. package/core/dist/runtime/pain-to-principle-service.d.ts +26 -5
  59. package/core/dist/runtime/pain-to-principle-service.d.ts.map +1 -1
  60. package/core/dist/runtime/pain-to-principle-service.js +63 -52
  61. package/core/dist/runtime/pain-to-principle-service.js.map +1 -1
  62. package/core/dist/runtime/store/candidate/admission-document.d.ts +43 -0
  63. package/core/dist/runtime/store/candidate/admission-document.d.ts.map +1 -1
  64. package/core/dist/runtime/store/candidate/admission-document.js +130 -0
  65. package/core/dist/runtime/store/candidate/admission-document.js.map +1 -1
  66. package/core/dist/runtime/store/candidate/candidate-store.d.ts +3 -1
  67. package/core/dist/runtime/store/candidate/candidate-store.d.ts.map +1 -1
  68. package/core/dist/runtime/store/candidate/memory-candidate-store.d.ts +2 -1
  69. package/core/dist/runtime/store/candidate/memory-candidate-store.d.ts.map +1 -1
  70. package/core/dist/runtime/store/candidate/memory-candidate-store.js +27 -1
  71. package/core/dist/runtime/store/candidate/memory-candidate-store.js.map +1 -1
  72. package/core/dist/runtime/store/candidate/sqlite-candidate-store.d.ts +2 -1
  73. package/core/dist/runtime/store/candidate/sqlite-candidate-store.d.ts.map +1 -1
  74. package/core/dist/runtime/store/candidate/sqlite-candidate-store.js +59 -2
  75. package/core/dist/runtime/store/candidate/sqlite-candidate-store.js.map +1 -1
  76. package/core/dist/runtime/store/context/sqlite-context-assembler.d.ts.map +1 -1
  77. package/core/dist/runtime/store/context/sqlite-context-assembler.js +18 -3
  78. package/core/dist/runtime/store/context/sqlite-context-assembler.js.map +1 -1
  79. package/core/dist/runtime/store/runtime-state-manager.d.ts +2 -1
  80. package/core/dist/runtime/store/runtime-state-manager.d.ts.map +1 -1
  81. package/core/dist/runtime/store/runtime-state-manager.js +4 -0
  82. package/core/dist/runtime/store/runtime-state-manager.js.map +1 -1
  83. package/core/dist/telemetry-event.d.ts +2 -2
  84. package/core/dist/telemetry-event.d.ts.map +1 -1
  85. package/core/dist/telemetry-event.js +5 -0
  86. package/core/dist/telemetry-event.js.map +1 -1
  87. package/core/package.json +1 -1
  88. package/dist/i18n.d.ts.map +1 -1
  89. package/dist/i18n.js +72 -0
  90. package/dist/i18n.js.map +1 -1
  91. package/dist/index.d.ts +15 -0
  92. package/dist/index.d.ts.map +1 -1
  93. package/dist/index.js +145 -35
  94. package/dist/index.js.map +1 -1
  95. package/dist/installer.d.ts +149 -9
  96. package/dist/installer.d.ts.map +1 -1
  97. package/dist/installer.js +562 -38
  98. package/dist/installer.js.map +1 -1
  99. package/dist/installers/codex-host-installer.js +1 -1
  100. package/dist/installers/codex-host-installer.js.map +1 -1
  101. package/dist/installers/index.d.ts +10 -0
  102. package/dist/installers/index.d.ts.map +1 -1
  103. package/dist/installers/index.js +4 -0
  104. package/dist/installers/index.js.map +1 -1
  105. package/dist/mvp-config.js +1 -1
  106. package/dist/mvp-config.js.map +1 -1
  107. package/dist/prompts.d.ts +36 -12
  108. package/dist/prompts.d.ts.map +1 -1
  109. package/dist/prompts.js +102 -30
  110. package/dist/prompts.js.map +1 -1
  111. package/dist/service-host-bridge.d.ts +71 -12
  112. package/dist/service-host-bridge.d.ts.map +1 -1
  113. package/dist/service-host-bridge.js +228 -48
  114. package/dist/service-host-bridge.js.map +1 -1
  115. package/dist/service-host-provisioning.d.ts +102 -0
  116. package/dist/service-host-provisioning.d.ts.map +1 -0
  117. package/dist/service-host-provisioning.js +595 -0
  118. package/dist/service-host-provisioning.js.map +1 -0
  119. package/dist/uninstaller.js +1 -1
  120. package/dist/uninstaller.js.map +1 -1
  121. package/dist/update/apply-payload.d.ts +9 -0
  122. package/dist/update/apply-payload.d.ts.map +1 -1
  123. package/dist/update/apply-payload.js +44 -2
  124. package/dist/update/apply-payload.js.map +1 -1
  125. package/dist/update/console-surface.d.ts +2 -1
  126. package/dist/update/console-surface.d.ts.map +1 -1
  127. package/dist/update/console-surface.js +6 -1
  128. package/dist/update/console-surface.js.map +1 -1
  129. package/dist/update/install-layout.d.ts +12 -0
  130. package/dist/update/install-layout.d.ts.map +1 -1
  131. package/dist/update/install-layout.js +49 -7
  132. package/dist/update/install-layout.js.map +1 -1
  133. package/dist/update/release-manager-authority.d.ts +16 -0
  134. package/dist/update/release-manager-authority.d.ts.map +1 -1
  135. package/dist/update/release-manager-authority.js +45 -3
  136. package/dist/update/release-manager-authority.js.map +1 -1
  137. package/dist/update/release-manager.d.ts +8 -3
  138. package/dist/update/release-manager.d.ts.map +1 -1
  139. package/dist/update/release-manager.js +29 -1
  140. package/dist/update/release-manager.js.map +1 -1
  141. package/dist/update/transaction-progress.d.ts +63 -0
  142. package/dist/update/transaction-progress.d.ts.map +1 -0
  143. package/dist/update/transaction-progress.js +207 -0
  144. package/dist/update/transaction-progress.js.map +1 -0
  145. package/dist/utils/env.d.ts +16 -1
  146. package/dist/utils/env.d.ts.map +1 -1
  147. package/dist/utils/env.js +55 -43
  148. package/dist/utils/env.js.map +1 -1
  149. package/host-runtime/dist/diagnostician-auto-run.js +37 -31
  150. package/host-runtime/dist/governance-observation-store.d.ts +38 -0
  151. package/host-runtime/dist/governance-observation-store.js +41 -0
  152. package/host-runtime/dist/governance-trajectory-turn-reader.js +26 -33
  153. package/host-runtime/package.json +1 -1
  154. package/install-layout/dist/background-execution-transition.d.ts +11 -1
  155. package/install-layout/dist/background-execution-transition.js +45 -1
  156. package/install-layout/dist/index.d.ts +3 -3
  157. package/install-layout/dist/index.js +10 -4
  158. package/install-layout/dist/pd-home.d.ts +12 -0
  159. package/install-layout/dist/pd-home.js +6 -1
  160. package/install-layout/package.json +1 -1
  161. package/package.json +10 -10
  162. package/pd-cli/dist/commands/candidate.d.ts +15 -0
  163. package/pd-cli/dist/commands/candidate.d.ts.map +1 -1
  164. package/pd-cli/dist/commands/candidate.js +449 -93
  165. package/pd-cli/dist/commands/candidate.js.map +1 -1
  166. package/pd-cli/dist/commands/console.d.ts.map +1 -1
  167. package/pd-cli/dist/commands/console.js +10 -0
  168. package/pd-cli/dist/commands/console.js.map +1 -1
  169. package/pd-cli/dist/commands/diagnose.d.ts.map +1 -1
  170. package/pd-cli/dist/commands/diagnose.js +254 -160
  171. package/pd-cli/dist/commands/diagnose.js.map +1 -1
  172. package/pd-cli/dist/commands/intake-outcome-guidance.d.ts +57 -0
  173. package/pd-cli/dist/commands/intake-outcome-guidance.d.ts.map +1 -0
  174. package/pd-cli/dist/commands/intake-outcome-guidance.js +206 -0
  175. package/pd-cli/dist/commands/intake-outcome-guidance.js.map +1 -0
  176. package/pd-cli/dist/commands/mcp-probe.d.ts.map +1 -1
  177. package/pd-cli/dist/commands/mcp-probe.js +1 -0
  178. package/pd-cli/dist/commands/mcp-probe.js.map +1 -1
  179. package/pd-cli/dist/commands/pain-record.d.ts.map +1 -1
  180. package/pd-cli/dist/commands/pain-record.js +18 -4
  181. package/pd-cli/dist/commands/pain-record.js.map +1 -1
  182. package/pd-cli/dist/commands/pain-retry.d.ts.map +1 -1
  183. package/pd-cli/dist/commands/pain-retry.js +91 -21
  184. package/pd-cli/dist/commands/pain-retry.js.map +1 -1
  185. package/pd-cli/dist/commands/runtime-uat.d.ts.map +1 -1
  186. package/pd-cli/dist/commands/runtime-uat.js +1 -0
  187. package/pd-cli/dist/commands/runtime-uat.js.map +1 -1
  188. package/pd-cli/dist/commands/service-lifecycle.js +1 -1
  189. package/pd-cli/dist/commands/service-lifecycle.js.map +1 -1
  190. package/pd-cli/dist/commands/service-run-once.d.ts +1 -1
  191. package/pd-cli/dist/commands/service-run-once.d.ts.map +1 -1
  192. package/pd-cli/dist/commands/service-run-once.js +9 -5
  193. package/pd-cli/dist/commands/service-run-once.js.map +1 -1
  194. package/pd-cli/dist/program.d.ts.map +1 -1
  195. package/pd-cli/dist/program.js +14 -3
  196. package/pd-cli/dist/program.js.map +1 -1
  197. package/pd-cli/dist/services/admission-write-gate.d.ts +4 -0
  198. package/pd-cli/dist/services/admission-write-gate.d.ts.map +1 -1
  199. package/pd-cli/dist/services/admission-write-gate.js +50 -48
  200. package/pd-cli/dist/services/admission-write-gate.js.map +1 -1
  201. package/pd-cli/dist/services/console-launcher.js +3 -3
  202. package/pd-cli/dist/services/console-launcher.js.map +1 -1
  203. package/pd-cli/dist/services/service-host/managed-run.d.ts.map +1 -1
  204. package/pd-cli/dist/services/service-host/managed-run.js +25 -8
  205. package/pd-cli/dist/services/service-host/managed-run.js.map +1 -1
  206. package/pd-cli/dist/services/service-host/scheduler/service-status.d.ts +12 -0
  207. package/pd-cli/dist/services/service-host/scheduler/service-status.d.ts.map +1 -1
  208. package/pd-cli/dist/services/service-host/scheduler/service-status.js +16 -7
  209. package/pd-cli/dist/services/service-host/scheduler/service-status.js.map +1 -1
  210. package/pd-cli/dist/services/service-host/status/service-run-status.d.ts +7 -5
  211. package/pd-cli/dist/services/service-host/status/service-run-status.d.ts.map +1 -1
  212. package/pd-cli/dist/services/service-host/status/service-run-status.js +1 -1
  213. package/pd-cli/dist/services/service-host/status/service-run-status.js.map +1 -1
  214. package/pd-cli/package.json +1 -1
  215. package/pd-mcp-server/dist/submit-assembly.js +61 -18
  216. package/pd-mcp-server/dist/version.d.ts +1 -1
  217. package/pd-mcp-server/dist/version.js +1 -1
  218. package/pd-mcp-server/package.json +1 -1
  219. package/plugin/dist/bundle.js +493 -493
  220. package/plugin/dist/openclaw-worker.js +263 -263
  221. package/plugin/dist/openclaw.plugin.json +1 -1
  222. package/plugin/openclaw.plugin.json +1 -1
  223. package/plugin/package.json +1 -1
  224. package/release-manager/dist/i18n.js +72 -0
  225. package/release-manager/dist/installer.js +562 -38
  226. package/release-manager/dist/installers/codex-host-installer.js +1 -1
  227. package/release-manager/dist/installers/index.js +4 -0
  228. package/release-manager/dist/mvp-config.js +1 -1
  229. package/release-manager/dist/service-host-bridge.js +228 -48
  230. package/release-manager/dist/service-host-provisioning.js +595 -0
  231. package/release-manager/dist/update/apply-payload.js +44 -2
  232. package/release-manager/dist/update/console-surface.js +6 -1
  233. package/release-manager/dist/update/install-layout.js +49 -7
  234. package/release-manager/dist/update/release-manager-authority.js +45 -3
  235. package/release-manager/dist/update/release-manager.js +29 -1
  236. package/release-manager/dist/update/transaction-progress.js +207 -0
  237. package/release-manager/dist/utils/env.js +55 -43
  238. package/release-manager/package.json +8 -8
  239. package/workbuddy-adapter/dist/codec/input-decoder.d.ts +21 -0
  240. package/workbuddy-adapter/dist/codec/input-decoder.js +50 -1
  241. package/workbuddy-adapter/dist/ingestion/pain-receipt-fallback.d.ts +68 -0
  242. package/workbuddy-adapter/dist/ingestion/pain-receipt-fallback.js +225 -0
  243. package/workbuddy-adapter/dist/pd-hook.js +60 -0
  244. package/workbuddy-adapter/dist/worker/workspace-worker.js +46 -44
  245. package/workbuddy-adapter/package.json +1 -1
  246. package/console/dist/server/utils/gateway.d.ts +0 -29
  247. package/console/dist/server/utils/gateway.js +0 -175
package/dist/installer.js CHANGED
@@ -24,6 +24,7 @@ import * as installLayoutModule from '@principles/install-layout';
24
24
  import { resolveMcpServerDir } from './mcp-server-layout-compat.js';
25
25
  import { detectOpenClawMainWorkspaceDivergence } from './utils/workspace-divergence.js';
26
26
  import { reconcileServiceHostScheduler } from './service-host-bridge.js';
27
+ import { provisionFreshInstallWorkspace, readAllPendingProvisioning, readPendingProvisioningEvidence } from './service-host-provisioning.js';
27
28
  import { applySkillLanguageSelection } from './skill-language.js';
28
29
  import { parseReleaseAssetIdentity, parseReleaseAssetManifest, ReleaseAssetManifestError, verifyReleaseAssetManifestAsync, verifyReleaseAssetTarget, } from './update/release-asset-manifest.js';
29
30
  import { parseEmbeddedProductIdentity, ProductIdentityError } from './update/product-identity.js';
@@ -138,6 +139,10 @@ const ALLOWED_NATIVE_MODULES = ['better-sqlite3'];
138
139
  // Shared components use ~/.pd/runtime. The plugin package is host-neutral for
139
140
  // Codex-only installs; OpenClaw/all still receive their adapter copy under
140
141
  // ~/.openclaw/extensions for host discovery.
142
+ // Library-level legacy default for helpers called OUTSIDE an install run
143
+ // (tests, diagnostics, backup helpers). install() overwrites it from the
144
+ // operator's explicit host selection before any deployment step — the CLI
145
+ // itself never defaults to OpenClaw anymore (PRI-1278 Phase 5).
141
146
  let activeHostTarget = 'openclaw';
142
147
  function installsOpenClaw(host) {
143
148
  return host === 'openclaw' || host === 'all';
@@ -145,6 +150,81 @@ function installsOpenClaw(host) {
145
150
  function installsWorkbuddy(host) {
146
151
  return host === 'workbuddy' || host === 'all';
147
152
  }
153
+ /**
154
+ * PRI-1278 Phase 5 review: when may THIS run (re)initialize ownership?
155
+ *
156
+ * - a fresh install always records the attempt (a pending marker on failure);
157
+ * - an existing install resumes ONLY with explicit enable consent AND a
158
+ * matching pending marker from a previous fresh install. Historical
159
+ * workspaces never wrote that marker → they can never be flipped here.
160
+ */
161
+ export function shouldProvisionOnInstall(input) {
162
+ if (input.freshInstall)
163
+ return true;
164
+ return input.consentIntent === 'enable'
165
+ && input.consentSource === 'explicit_flag'
166
+ && input.schedulerState === 'enabled'
167
+ && input.hasPendingMarker;
168
+ }
169
+ /** Stable identity for a workspace directory (real path, case-insensitive on Windows). */
170
+ function workspaceKey(workspaceDir) {
171
+ const resolved = path.resolve(workspaceDir);
172
+ let real;
173
+ try {
174
+ const candidate = realpathSync.native(resolved);
175
+ real = typeof candidate === 'string' && candidate.length > 0 ? candidate : resolved;
176
+ }
177
+ catch {
178
+ real = resolved;
179
+ }
180
+ return process.platform === 'win32' ? real.toLowerCase() : real;
181
+ }
182
+ /**
183
+ * The ACTUAL workspaces this install bound — not the requested host list.
184
+ * WorkBuddy binds its own governance directory, and Codex may be redirected
185
+ * by materialization. Provisioning the requested project dir alone left the
186
+ * real host workspace in legacy ownership.
187
+ */
188
+ export function resolveProvisioningTargets(options) {
189
+ const targets = [];
190
+ if (options.host === 'none' || options.host === 'openclaw' || options.host === 'all') {
191
+ targets.push({ host: options.host === 'none' ? 'none' : 'openclaw', workspaceDir: options.workspaceDir });
192
+ }
193
+ if (options.host === 'codex' || options.host === 'all') {
194
+ targets.push({ host: 'codex', workspaceDir: options.codexWorkspaceDir ?? options.workspaceDir });
195
+ }
196
+ if (options.host === 'workbuddy') {
197
+ targets.push({
198
+ host: 'workbuddy',
199
+ workspaceDir: getWorkbuddyWorkspaceDir(getHomeDir(), process.env.WORKBUDDY_CONFIG_DIR),
200
+ });
201
+ }
202
+ const seen = new Set();
203
+ return targets.filter((target) => {
204
+ const key = workspaceKey(target.workspaceDir);
205
+ if (seen.has(key))
206
+ return false;
207
+ seen.add(key);
208
+ return true;
209
+ });
210
+ }
211
+ /**
212
+ * Merge THIS run's targets with the per-workspace pending records a previous
213
+ * fresh install left behind. A plain `install --enable-service-host` (no
214
+ * `--host`) must resume every deferred workspace, not only the neutral one.
215
+ */
216
+ export function mergePendingProvisioningTargets(targets, pending) {
217
+ const merged = [...targets];
218
+ const seen = new Set(targets.map((target) => workspaceKey(target.workspaceDir)));
219
+ for (const entry of pending) {
220
+ const key = workspaceKey(entry.workspaceDir);
221
+ if (seen.has(key))
222
+ continue;
223
+ seen.add(key);
224
+ merged.push({ host: entry.host === 'all' ? 'none' : entry.host, workspaceDir: entry.workspaceDir });
225
+ }
226
+ return merged;
227
+ }
148
228
  /**
149
229
  * Whether this run actually serves Codex — as the requested install target or
150
230
  * as a persisted sibling host being refreshed. The Codex workspace is
@@ -219,7 +299,7 @@ function readPersistedInstallHosts() {
219
299
  * that ALREADY records it must be refreshed like any other served host.
220
300
  */
221
301
  export function resolveHostRefreshTargets(persistedHosts, host) {
222
- const covered = new Set(host === 'all' ? ['openclaw', 'codex'] : [host]);
302
+ const covered = new Set(host === 'all' ? ['openclaw', 'codex'] : host === 'none' ? [] : [host]);
223
303
  const targets = [];
224
304
  for (const persisted of persistedHosts) {
225
305
  if (persisted !== 'openclaw' && persisted !== 'codex' && persisted !== 'workbuddy')
@@ -426,7 +506,18 @@ function resolvePackageDir(name, fromDir) {
426
506
  function copyExecutorDependencyClosure(sourcePackageDir, stagingDir) {
427
507
  const stagedModulesDir = path.join(stagingDir, 'node_modules');
428
508
  const manifest = JSON.parse(readFileSync(path.join(sourcePackageDir, 'package.json'), 'utf8'));
429
- const seen = new Set();
509
+ // Two separate dedup keys, because they guard different things:
510
+ // - `copied` dedups the FLAT staged name (first resolution wins, mirroring
511
+ // the npm hoisted winner at top level).
512
+ // - `expanded` dedups by RESOLVED package root, so every distinct version
513
+ // still gets its dependency list walked. Name-only dedup here dropped
514
+ // transitive deps of version-conflicted packages: minimatch resolved to
515
+ // the hoisted copy first, so the tuf-js-nested minimatch's own deps
516
+ // (@isaacs/nonrecursive-glob-match) were never staged, while the
517
+ // wholesale cpSync still carried that nested copy into tuf-js — where
518
+ // its require then failed (PR #2767 CI).
519
+ const copied = new Set();
520
+ const expanded = new Set();
430
521
  // Each queued dependency resolves from the package that DECLARES it —
431
522
  // nested/deduped layouts mean chownr resolves from tar, not from the
432
523
  // installer package root. The directory walk mirrors Node's own
@@ -434,15 +525,17 @@ function copyExecutorDependencyClosure(sourcePackageDir, stagingDir) {
434
525
  const queue = Object.keys(manifest.dependencies ?? {}).map((name) => ({ name, fromDir: sourcePackageDir }));
435
526
  while (queue.length > 0) {
436
527
  const item = queue.shift();
437
- if (seen.has(item.name))
438
- continue;
439
- seen.add(item.name);
440
528
  const packageRoot = resolvePackageDir(item.name, item.fromDir);
441
- cpSync(packageRoot, path.join(stagedModulesDir, item.name), { recursive: true, dereference: true });
529
+ if (expanded.has(packageRoot))
530
+ continue;
531
+ expanded.add(packageRoot);
532
+ if (!copied.has(item.name)) {
533
+ copied.add(item.name);
534
+ cpSync(packageRoot, path.join(stagedModulesDir, item.name), { recursive: true, dereference: true });
535
+ }
442
536
  const dependencyManifest = JSON.parse(readFileSync(path.join(packageRoot, 'package.json'), 'utf8'));
443
537
  for (const dependencyName of Object.keys(dependencyManifest.dependencies ?? {})) {
444
- if (!seen.has(dependencyName))
445
- queue.push({ name: dependencyName, fromDir: packageRoot });
538
+ queue.push({ name: dependencyName, fromDir: packageRoot });
446
539
  }
447
540
  }
448
541
  }
@@ -768,6 +861,7 @@ function execNpm(args, cwd, timeoutOverride) {
768
861
  encoding: 'utf-8',
769
862
  stdio: 'pipe',
770
863
  env: process.env,
864
+ windowsHide: true,
771
865
  timeout: timeoutOverride ?? INSTALL_TIMEOUT_MS,
772
866
  })).trim();
773
867
  }
@@ -804,7 +898,7 @@ export function verifyNativeModules(cwd, componentName) {
804
898
  if (!existsSync(nativeModPath))
805
899
  continue;
806
900
  try {
807
- execFileSync(process.execPath, ['-e', `require('${nativeMod}')`], { cwd, stdio: 'pipe' });
901
+ execFileSync(process.execPath, ['-e', `require('${nativeMod}')`], { cwd, stdio: 'pipe', windowsHide: true });
808
902
  }
809
903
  catch {
810
904
  throw new Error(`${componentName} native module ${nativeMod} failed its require probe: the prebuilt binary for this Node.js ABI is missing or incompatible (no rebuild step exists by design). Install the platform release asset matching this OS, architecture, and ABI.`);
@@ -1079,16 +1173,39 @@ const INSTALL_STEPS = [
1079
1173
  { name: 'Updating host config', weight: 3 },
1080
1174
  ];
1081
1175
  const TOTAL_WEIGHT = INSTALL_STEPS.reduce((sum, step) => sum + step.weight, 0);
1176
+ /** The installer's weighted completion at a step; null outside the step table. */
1177
+ function installPercent(currentStep) {
1178
+ if (currentStep < 0 || currentStep >= INSTALL_STEPS.length)
1179
+ return null;
1180
+ const completedWeight = INSTALL_STEPS.slice(0, currentStep + 1).reduce((sum, step) => sum + step.weight, 0);
1181
+ return Math.round((completedWeight / TOTAL_WEIGHT) * 100);
1182
+ }
1183
+ function terminalProgressSurface(spinner) {
1184
+ return {
1185
+ report: (message, percent) => { spinner.text = percent === null ? message : `${message} (${percent}%)`; },
1186
+ succeed: (message) => { spinner.succeed(message); },
1187
+ warn: (message) => { spinner.warn(message); },
1188
+ fail: (message) => { spinner.fail(message); },
1189
+ };
1190
+ }
1191
+ /**
1192
+ * Status line for a run nobody is watching in a terminal: every step is
1193
+ * handed to the caller exactly as the spinner would have shown it. The three
1194
+ * terminal markers print nothing — the result of the run travels in its
1195
+ * return value.
1196
+ */
1197
+ function narratedProgress(onStep) {
1198
+ return {
1199
+ report: (message, percent) => { onStep({ message, percent }); },
1200
+ succeed: () => { },
1201
+ warn: () => { },
1202
+ fail: () => { },
1203
+ };
1204
+ }
1082
1205
  function updateProgress(spinner, currentStep, message) {
1083
1206
  if (!spinner)
1084
1207
  return;
1085
- if (currentStep < 0 || currentStep >= INSTALL_STEPS.length) {
1086
- spinner.text = message;
1087
- return;
1088
- }
1089
- const completedWeight = INSTALL_STEPS.slice(0, currentStep + 1).reduce((sum, s) => sum + s.weight, 0);
1090
- const percent = Math.round((completedWeight / TOTAL_WEIGHT) * 100);
1091
- spinner.text = `${message} (${percent}%)`;
1208
+ spinner.report(message, installPercent(currentStep));
1092
1209
  }
1093
1210
  /**
1094
1211
  * §8.4: why a symlink entry must NOT be renamed into the canonical backups
@@ -2013,7 +2130,7 @@ async function defaultLegacyRulePreflightRunner(pdCliEntry, workspaceDir) {
2013
2130
  const { promisify } = await import('node:util');
2014
2131
  const execFileAsync = promisify(execFile);
2015
2132
  try {
2016
- const result = await execFileAsync(process.execPath, [pdCliEntry, 'runtime', 'compatibility-scan', '--json', '--workspace', workspaceDir], { timeout: 60_000, env: { ...process.env, PD_INVOCATION_SOURCE: 'installer' } });
2133
+ const result = await execFileAsync(process.execPath, [pdCliEntry, 'runtime', 'compatibility-scan', '--json', '--workspace', workspaceDir], { timeout: 60_000, env: { ...process.env, PD_INVOCATION_SOURCE: 'installer' }, windowsHide: true });
2017
2134
  return parseCompatibilityScanStdout(result.stdout);
2018
2135
  }
2019
2136
  catch (err) {
@@ -2599,6 +2716,7 @@ export function tryUpgradePdCliFromNpm(installedPdCliDir) {
2599
2716
  encoding: 'utf-8',
2600
2717
  timeout: 30_000,
2601
2718
  stdio: ['pipe', 'pipe', 'pipe'],
2719
+ windowsHide: true,
2602
2720
  });
2603
2721
  }
2604
2722
  else {
@@ -2606,6 +2724,7 @@ export function tryUpgradePdCliFromNpm(installedPdCliDir) {
2606
2724
  encoding: 'utf-8',
2607
2725
  timeout: 30_000,
2608
2726
  stdio: ['pipe', 'pipe', 'pipe'],
2727
+ windowsHide: true,
2609
2728
  });
2610
2729
  }
2611
2730
  const tgzFiles = readdirSync(tmpDir).filter(f => f.endsWith('.tgz'));
@@ -2620,6 +2739,7 @@ export function tryUpgradePdCliFromNpm(installedPdCliDir) {
2620
2739
  encoding: 'utf-8',
2621
2740
  timeout: 15_000,
2622
2741
  stdio: ['pipe', 'pipe', 'pipe'],
2742
+ windowsHide: true,
2623
2743
  });
2624
2744
  const packageDir = path.join(extractDir, 'package');
2625
2745
  if (!existsSync(path.join(packageDir, 'dist', 'index.js'))) {
@@ -2719,7 +2839,7 @@ function verifyPdCliShim() {
2719
2839
  let localError;
2720
2840
  try {
2721
2841
  const installedEntry = path.join(getInstalledPdCliDir(), 'dist', 'index.js');
2722
- execFileSync(process.execPath, [installedEntry, '--version'], { stdio: 'pipe', timeout: PD_CLI_VERIFICATION_TIMEOUT_MS, env: { ...process.env, PD_INVOCATION_SOURCE: 'installer' } });
2842
+ execFileSync(process.execPath, [installedEntry, '--version'], { stdio: 'pipe', timeout: PD_CLI_VERIFICATION_TIMEOUT_MS, windowsHide: true, env: { ...process.env, PD_INVOCATION_SOURCE: 'installer' } });
2723
2843
  localOk = true;
2724
2844
  }
2725
2845
  catch (e) {
@@ -2761,7 +2881,7 @@ function verifyPdCliShim() {
2761
2881
  execFileSync('cmd.exe', ['/c', 'pd', '--version'], { stdio: 'pipe', timeout: PD_CLI_VERIFICATION_TIMEOUT_MS, windowsHide: true, env: { ...process.env, PD_INVOCATION_SOURCE: 'installer' } });
2762
2882
  }
2763
2883
  else {
2764
- execFileSync('pd', ['--version'], { stdio: 'pipe', timeout: PD_CLI_VERIFICATION_TIMEOUT_MS, env: { ...process.env, PD_INVOCATION_SOURCE: 'installer' } });
2884
+ execFileSync('pd', ['--version'], { stdio: 'pipe', timeout: PD_CLI_VERIFICATION_TIMEOUT_MS, windowsHide: true, env: { ...process.env, PD_INVOCATION_SOURCE: 'installer' } });
2765
2885
  }
2766
2886
  return true;
2767
2887
  }
@@ -3731,6 +3851,10 @@ export async function verifyConsole(workspaceDir, probePolicy = {}) {
3731
3851
  stdio: 'pipe',
3732
3852
  env: { ...process.env },
3733
3853
  detached: false,
3854
+ // The installer may run with no console at all (the detached update
3855
+ // executor, the Companion); an unhidden probe console would pop a
3856
+ // visible terminal window on every attempt.
3857
+ windowsHide: true,
3734
3858
  });
3735
3859
  let childExited = false;
3736
3860
  let childExitCode = null;
@@ -3899,6 +4023,7 @@ async function autoLaunchConsole(workspaceDir) {
3899
4023
  detached: true,
3900
4024
  stdio: 'ignore',
3901
4025
  shell: false,
4026
+ windowsHide: true,
3902
4027
  env: { ...process.env, PD_INVOCATION_SOURCE: 'installer' },
3903
4028
  });
3904
4029
  child.unref();
@@ -4097,12 +4222,19 @@ const OPENCLAW_PD_CONFIG_FILENAME = 'principles-disciple.json';
4097
4222
  function describeError(error) {
4098
4223
  return error instanceof Error ? error.message : String(error);
4099
4224
  }
4100
- /** Same-directory identity for a workspace pointer (Windows is case-insensitive). */
4225
+ /** Same-directory identity for a workspace pointer (real path; Windows is case-insensitive). */
4101
4226
  function sameWorkspaceTarget(left, right) {
4102
4227
  const normalize = (value) => {
4103
4228
  const resolved = path.resolve(value);
4104
- const trimmed = resolved.length > 1 ? resolved.replace(/[\\/]+$/, '') : resolved;
4105
- return process.platform === 'win32' ? trimmed.toLowerCase() : trimmed;
4229
+ let real;
4230
+ try {
4231
+ const candidate = realpathSync.native(resolved);
4232
+ real = typeof candidate === 'string' && candidate.length > 0 ? candidate : resolved;
4233
+ }
4234
+ catch {
4235
+ real = resolved;
4236
+ }
4237
+ return process.platform === 'win32' ? real.toLowerCase() : real;
4106
4238
  };
4107
4239
  return normalize(left) === normalize(right);
4108
4240
  }
@@ -4262,6 +4394,216 @@ function readSecondaryOpenClawDeclaration(homeDir) {
4262
4394
  }
4263
4395
  return { ok: true, workspace: declaredRaw.trim() };
4264
4396
  }
4397
+ /**
4398
+ * Read ONE binding file in the layout the Codex launcher actually writes
4399
+ * (PRI-1248): `mcp-binding.json` beside the plugin data root, and as a legacy
4400
+ * mirror in the versioned payload. The old implementation scanned
4401
+ * `PLUGIN_DATA/runtime/<version>/`, a directory that only holds the runtime
4402
+ * dependencies — so a normally bound Codex was reported as "no binding" and a
4403
+ * plain `--yes` upgrade skipped its refresh entirely.
4404
+ */
4405
+ function readCodexBindingFile(bindingPath) {
4406
+ if (!existsSync(bindingPath))
4407
+ return { state: 'absent' };
4408
+ let raw;
4409
+ try {
4410
+ raw = readFileSync(bindingPath, 'utf-8');
4411
+ }
4412
+ catch (error) {
4413
+ return { state: 'invalid', reason: `binding unreadable at ${bindingPath} (${describeError(error)})` };
4414
+ }
4415
+ let parsed;
4416
+ try {
4417
+ parsed = JSON.parse(raw);
4418
+ }
4419
+ catch (error) {
4420
+ return { state: 'invalid', reason: `binding is not valid JSON at ${bindingPath} (${describeError(error)})` };
4421
+ }
4422
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
4423
+ return { state: 'invalid', reason: `binding at ${bindingPath} has no JSON-object root` };
4424
+ }
4425
+ if (Reflect.get(parsed, 'host') !== 'codex') {
4426
+ return { state: 'invalid', reason: `binding at ${bindingPath} does not declare host=codex` };
4427
+ }
4428
+ const workspace = Reflect.get(parsed, 'workspaceDir');
4429
+ if (typeof workspace !== 'string' || !isUsableWorkspacePointer(workspace.trim())) {
4430
+ return { state: 'invalid', reason: `binding at ${bindingPath} has no usable absolute "workspaceDir"` };
4431
+ }
4432
+ const resolved = path.resolve(workspace.trim());
4433
+ if (!existsSync(resolved)) {
4434
+ return { state: 'invalid', reason: `binding at ${bindingPath} names a workspace that does not exist (${resolved})` };
4435
+ }
4436
+ return { state: 'bound', workspaceDir: resolved };
4437
+ }
4438
+ /** Legacy payload-local mirror: `<codexHome>/plugins/cache/<marketplace>/principles-disciple/<version>`. */
4439
+ function readCodexBindingFromPayloadCache() {
4440
+ const cacheRoot = path.join(getCodexHomeDir(), 'plugins', 'cache');
4441
+ let marketplaceDirs;
4442
+ try {
4443
+ marketplaceDirs = readdirSync(cacheRoot);
4444
+ }
4445
+ catch (error) {
4446
+ if (errnoCode(error) === 'ENOENT')
4447
+ return { state: 'absent' };
4448
+ return { state: 'invalid', reason: `Codex plugin cache is unreadable at ${cacheRoot} (${describeError(error)})` };
4449
+ }
4450
+ const candidates = [];
4451
+ for (const marketplace of marketplaceDirs) {
4452
+ const pluginRoot = path.join(cacheRoot, marketplace, 'principles-disciple');
4453
+ let versions;
4454
+ try {
4455
+ versions = readdirSync(pluginRoot);
4456
+ }
4457
+ catch {
4458
+ continue;
4459
+ }
4460
+ for (const version of versions) {
4461
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
4462
+ if (match === null)
4463
+ continue;
4464
+ const parts = [Number(match[1]), Number(match[2]), Number(match[3])];
4465
+ if (!parts.every((n) => Number.isFinite(n)))
4466
+ continue;
4467
+ candidates.push({ versionDir: path.join(pluginRoot, version), parts });
4468
+ }
4469
+ }
4470
+ candidates.sort((a, b) => (b.parts[0] - a.parts[0]) || (b.parts[1] - a.parts[1]) || (b.parts[2] - a.parts[2]));
4471
+ let sawBinding = false;
4472
+ let firstInvalid;
4473
+ for (const candidate of candidates) {
4474
+ const state = readCodexBindingFile(path.join(candidate.versionDir, 'mcp-binding.json'));
4475
+ if (state.state === 'absent')
4476
+ continue;
4477
+ sawBinding = true;
4478
+ if (state.state === 'bound')
4479
+ return state;
4480
+ firstInvalid ??= state.reason;
4481
+ }
4482
+ return sawBinding
4483
+ ? { state: 'invalid', reason: firstInvalid ?? 'no readable Codex mcp-binding.json under the plugin cache' }
4484
+ : { state: 'absent' };
4485
+ }
4486
+ /** The workspace a host is ACTUALLY bound to, read from that host's own record. */
4487
+ export function readHostWorkspaceBinding(host) {
4488
+ if (host === 'workbuddy') {
4489
+ return {
4490
+ state: 'bound',
4491
+ workspaceDir: getWorkbuddyWorkspaceDir(getHomeDir(), process.env.WORKBUDDY_CONFIG_DIR),
4492
+ source: 'workbuddy_governance_dir',
4493
+ };
4494
+ }
4495
+ if (host === 'openclaw') {
4496
+ const configPath = path.join(getOpenClawDir(), OPENCLAW_PD_CONFIG_FILENAME);
4497
+ if (!existsSync(configPath)) {
4498
+ return { state: 'unbound', reason: `openclaw declaration absent at ${configPath}` };
4499
+ }
4500
+ let raw;
4501
+ try {
4502
+ raw = readFileSync(configPath, 'utf-8');
4503
+ }
4504
+ catch (error) {
4505
+ return { state: 'unverifiable', reason: `openclaw declaration unreadable at ${configPath} (${describeError(error)})` };
4506
+ }
4507
+ let parsed;
4508
+ try {
4509
+ parsed = JSON.parse(raw);
4510
+ }
4511
+ catch (error) {
4512
+ return { state: 'unverifiable', reason: `openclaw declaration is not valid JSON (${describeError(error)})` };
4513
+ }
4514
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
4515
+ return { state: 'unverifiable', reason: `openclaw declaration at ${configPath} has no JSON-object root` };
4516
+ }
4517
+ const declared = Object.hasOwn(parsed, 'workspace') ? Reflect.get(parsed, 'workspace') : undefined;
4518
+ if (typeof declared !== 'string' || !isUsableWorkspacePointer(declared.trim())) {
4519
+ return { state: 'unbound', reason: `openclaw declaration at ${configPath} has no usable absolute "workspace"` };
4520
+ }
4521
+ return { state: 'bound', workspaceDir: path.resolve(declared.trim()), source: 'openclaw_declaration' };
4522
+ }
4523
+ // Codex: durable binding first, payload-local legacy second — the same
4524
+ // authority order the launcher and `pd health` use.
4525
+ const pluginDataRoot = resolvePluginDataRoot(getCodexHomeDir(), 'principles');
4526
+ const persistentPath = pluginDataRoot === undefined ? undefined : path.join(pluginDataRoot, 'mcp-binding.json');
4527
+ const persistent = persistentPath === undefined ? { state: 'absent' } : readCodexBindingFile(persistentPath);
4528
+ if (persistent.state === 'bound') {
4529
+ return { state: 'bound', workspaceDir: persistent.workspaceDir, source: 'codex_mcp_binding' };
4530
+ }
4531
+ if (persistent.state === 'invalid')
4532
+ return { state: 'unverifiable', reason: persistent.reason };
4533
+ const payload = readCodexBindingFromPayloadCache();
4534
+ if (payload.state === 'bound')
4535
+ return { state: 'bound', workspaceDir: payload.workspaceDir, source: 'codex_mcp_binding' };
4536
+ if (payload.state === 'invalid')
4537
+ return { state: 'unverifiable', reason: payload.reason };
4538
+ return { state: 'unbound', reason: 'no Codex mcp-binding.json records an existing workspace' };
4539
+ }
4540
+ /**
4541
+ * PRI-1278 Phase 5 review: a host that is REFRESHED (not explicitly selected)
4542
+ * must keep the workspace it is already bound to. Passing this run's target
4543
+ * workspace to a Codex plugin rebuild / OpenClaw declaration rewrite silently
4544
+ * moved the host to `~/pd-workspace` after a plain `npx create-principles-disciple
4545
+ * --yes` upgrade. The recorded binding is the authority; when it cannot be
4546
+ * read/validated the refresh is SKIPPED with an actionable warning instead of
4547
+ * guessing.
4548
+ */
4549
+ export function resolveExistingHostWorkspaceForRefresh(host) {
4550
+ const binding = readHostWorkspaceBinding(host);
4551
+ if (binding.state === 'bound') {
4552
+ return { ok: true, workspaceDir: binding.workspaceDir, source: binding.source };
4553
+ }
4554
+ const nextAction = host === 'codex'
4555
+ ? 'Re-run the installer explicitly for Codex with its real workspace: npx create-principles-disciple install --host codex --workspace "<existing workspace>"'
4556
+ : host === 'openclaw'
4557
+ ? 'Re-run the installer explicitly for OpenClaw with the real workspace: npx create-principles-disciple install --host openclaw --workspace "<existing workspace>"'
4558
+ : 'Re-run the installer explicitly for WorkBuddy so it can restore its governance workspace.';
4559
+ return { ok: false, reason: binding.reason, nextAction };
4560
+ }
4561
+ /**
4562
+ * Verify a DEFERRED provisioning target against the host bindings that exist
4563
+ * NOW (not the `--host` this resume run happened to omit).
4564
+ *
4565
+ * - no binding at all → `none` (a truthful waiting state);
4566
+ * - one/more verified bindings → probe the verified host(s) before the flip;
4567
+ * - an unreadable binding with
4568
+ * nothing else verifiable → refuse (never flip from an unverified state).
4569
+ */
4570
+ export function resolveResumeProvisioningHost(markerHost, workspaceDir) {
4571
+ const candidates = ['openclaw', 'codex', 'workbuddy'];
4572
+ const bound = [];
4573
+ const unverifiable = [];
4574
+ for (const host of candidates) {
4575
+ let binding;
4576
+ try {
4577
+ binding = readHostWorkspaceBinding(host);
4578
+ }
4579
+ catch (error) {
4580
+ // A host root that cannot even be resolved is unverifiable, not absent.
4581
+ unverifiable.push(`${host}: ${describeError(error)}`);
4582
+ continue;
4583
+ }
4584
+ if (binding.state === 'unverifiable') {
4585
+ unverifiable.push(`${host}: ${binding.reason}`);
4586
+ }
4587
+ else if (binding.state === 'bound' && sameWorkspaceTarget(binding.workspaceDir, workspaceDir)) {
4588
+ bound.push(host);
4589
+ }
4590
+ }
4591
+ if (bound.length === 0 && unverifiable.length > 0) {
4592
+ return {
4593
+ ok: false,
4594
+ reason: unverifiable.join('; '),
4595
+ nextAction: 'Repair the host binding file(s) so the workspace ownership can be verified, then re-run this install.',
4596
+ };
4597
+ }
4598
+ if (bound.length === 0)
4599
+ return { ok: true, host: 'none' };
4600
+ if (bound.includes('openclaw') && bound.includes('codex'))
4601
+ return { ok: true, host: 'all' };
4602
+ if (markerHost !== 'none' && markerHost !== 'all' && bound.includes(markerHost)) {
4603
+ return { ok: true, host: markerHost };
4604
+ }
4605
+ return { ok: true, host: bound[0] ?? 'none' };
4606
+ }
4265
4607
  export function resolveUpdateWorkspaceDir(workspaceDir, host, options = {}) {
4266
4608
  if (!installsOpenClaw(host))
4267
4609
  return { kind: 'resolved', workspaceDir, source: 'caller' };
@@ -4531,6 +4873,10 @@ export async function materializeCodexWorkspace(options, io) {
4531
4873
  return { codexWorkspaceDir, redirected };
4532
4874
  }
4533
4875
  export async function runHostInstallers(host, ctx, overrides = {}) {
4876
+ // Service-Host-only install: no host adapter exists, so no host installer
4877
+ // runs. This is a first-class mode, not an error — never fabricate one.
4878
+ if (host === 'none')
4879
+ return [];
4534
4880
  const installers = getHostInstallers(host);
4535
4881
  const results = [];
4536
4882
  for (const installer of installers) {
@@ -4698,6 +5044,11 @@ transaction) {
4698
5044
  // time the config writer runs, and the rollback path does not undo workspace
4699
5045
  // files. Validated here, the failure costs nothing.
4700
5046
  assertUsableWorkspaceDir(options.workspaceDir);
5047
+ // PRI-1278 Phase 5: a FIRST install is proven by the absence of the PD
5048
+ // install manifest BEFORE this run mutates anything. Only a first install
5049
+ // may adopt the new background default (scheduler enable + ownership
5050
+ // provisioning); every existing installation keeps its recorded lifecycle.
5051
+ const freshInstallRun = !existsSync(getInstallManifestPath());
4701
5052
  // Decide the payload shape once: self-contained (release asset) or
4702
5053
  // npm-distributed (registry-resolved dependencies). A present `_release`
4703
5054
  // asset keeps the hard preflight; the npm-distributed shape must pass
@@ -4866,7 +5217,12 @@ transaction) {
4866
5217
  logger.warn(t('gateway_proceed_warn'));
4867
5218
  }
4868
5219
  }
4869
- const spinner = quiet ? null : ora('Installing...').start();
5220
+ // A terminal gets the spinner. A quiet run that asked to be narrated gets
5221
+ // the relay instead of `null`, so every `if (spinner)` step report still
5222
+ // flows somewhere; a quiet run that did not stays silent as before.
5223
+ const spinner = quiet
5224
+ ? (mode.onProgress === undefined ? null : narratedProgress(mode.onProgress))
5225
+ : terminalProgressSurface(ora('Installing...').start());
4870
5226
  let backupDir = null;
4871
5227
  let runtimeBackupDir = null;
4872
5228
  // ADR-0024 D-2: non-null once the transaction is planned (first mutation is imminent).
@@ -5013,8 +5369,11 @@ transaction) {
5013
5369
  // carries PD and include it in BOTH the manifest record and the refresh
5014
5370
  // set, so one upgrade brings all hosts forward without uninstall/reinstall.
5015
5371
  const detectedHostsBeforeRun = detectInstalledHosts();
5016
- const hostPlan = planUpgradeHosts(options.host, persistedHostsBeforeRun, detectedHostsBeforeRun);
5017
- installManifestHosts = withDetectedHosts(resolveInstallManifestHosts(options.host), detectedHostsBeforeRun);
5372
+ // PRI-1278 Phase 5: a FIRST install never inherits a host from machine
5373
+ // leftovers or a sibling detection — the operator chose the host adapter
5374
+ // (or chose none). Only an EXISTING install widens its coverage.
5375
+ const hostPlan = planUpgradeHosts(options.host, freshInstallRun ? [] : persistedHostsBeforeRun, freshInstallRun ? [] : detectedHostsBeforeRun);
5376
+ installManifestHosts = withDetectedHosts(resolveInstallManifestHosts(options.host), freshInstallRun ? [] : detectedHostsBeforeRun);
5018
5377
  for (const detectedHost of hostPlan.newlyCovered) {
5019
5378
  logger.info(`Detected installed host "${detectedHost.hostId}" (${detectedHost.evidence}) — included in this upgrade.`);
5020
5379
  }
@@ -5256,6 +5615,7 @@ transaction) {
5256
5615
  const pdCliEntry = path.join(getInstalledPdCliDir(), 'dist', 'index.js');
5257
5616
  execFileSync(process.execPath, [pdCliEntry, 'runtime', 'init', '--confirm', '--workspace', options.workspaceDir], {
5258
5617
  stdio: ['ignore', 'ignore', 'pipe'],
5618
+ windowsHide: true,
5259
5619
  timeout: 30000,
5260
5620
  env: { ...process.env, PD_INVOCATION_SOURCE: 'installer' },
5261
5621
  });
@@ -5290,6 +5650,7 @@ transaction) {
5290
5650
  const { promisify } = await import('node:util');
5291
5651
  const execFileAsync = promisify(execFile);
5292
5652
  await execFileAsync(process.execPath, [pdCliEntry, 'demo', 'story-a', '--json'], {
5653
+ windowsHide: true,
5293
5654
  timeout: STORY_A_VERIFICATION_TIMEOUT_MS,
5294
5655
  env: { ...process.env, PD_INVOCATION_SOURCE: 'installer' },
5295
5656
  });
@@ -5332,7 +5693,13 @@ transaction) {
5332
5693
  // isolation intact.
5333
5694
  let codexWorkspaceDir;
5334
5695
  let codexWorkspaceError;
5335
- if (installRunServesCodex(options.host, hostPlan.refreshTargets)) {
5696
+ // PRI-1278 Phase 5 review: materialize a Codex workspace ONLY when Codex
5697
+ // is the REQUESTED target. A refresh-only Codex (a plain `--yes` upgrade
5698
+ // with no --host) must reuse its recorded binding via
5699
+ // resolveExistingHostWorkspaceForRefresh — never create/rebind to this
5700
+ // run's neutral workspace.
5701
+ const requestsCodex = options.host === 'codex' || options.host === 'all';
5702
+ if (requestsCodex) {
5336
5703
  try {
5337
5704
  const materialized = await materializeCodexWorkspace(options, {
5338
5705
  resolve: (target, notes) => resolveCodexHostWorkspace(options, notes),
@@ -5393,6 +5760,37 @@ transaction) {
5393
5760
  for (const refreshTarget of refreshTargets) {
5394
5761
  if (spinner)
5395
5762
  updateProgress(spinner, stepIndex, `Refreshing ${refreshTarget} host binding...`);
5763
+ // PRI-1278 Phase 5 review: a refresh must re-use the host's RECORDED
5764
+ // workspace. Passing this run's target (a neutral `~/pd-workspace` when
5765
+ // --host was omitted) silently moved Codex/OpenClaw to a new directory.
5766
+ if (refreshTarget === 'codex' || refreshTarget === 'openclaw' || refreshTarget === 'workbuddy') {
5767
+ const existing = resolveExistingHostWorkspaceForRefresh(refreshTarget);
5768
+ if (!existing.ok) {
5769
+ logger.warn(`Host "${refreshTarget}" refresh skipped: ${existing.reason}. The existing host binding was KEPT unchanged. Next: ${existing.nextAction}`);
5770
+ refreshedResults.push({
5771
+ success: false,
5772
+ hostId: refreshTarget,
5773
+ configAction: 'skipped',
5774
+ reason: `existing binding could not be read: ${existing.reason}`,
5775
+ nextAction: existing.nextAction,
5776
+ });
5777
+ continue;
5778
+ }
5779
+ const refreshCtx = { ...hostInstallCtx, workspaceDir: existing.workspaceDir };
5780
+ const refreshResults = await runHostInstallers(refreshTarget, refreshCtx, { codexWorkspaceDir: existing.workspaceDir, codexWorkspaceError });
5781
+ refreshedResults.push(...refreshResults);
5782
+ for (const hr of refreshResults) {
5783
+ if (hr.success) {
5784
+ logger.info(`Host "${hr.hostId}" refresh: ${hr.configAction === 'updated' ? 'updated' : 'no change needed'}${hr.reason ? ` — ${hr.reason}` : ''} (workspace ${existing.workspaceDir} from ${existing.source}).`);
5785
+ for (const warning of hr.warnings ?? [])
5786
+ logger.warn(`Host "${hr.hostId}": ${warning}`);
5787
+ }
5788
+ else {
5789
+ logger.warn(`Host "${hr.hostId}" refresh failed: ${hr.reason ?? 'unknown failure'}. Next: ${hr.nextAction ?? `npx create-principles-disciple install --host ${hr.hostId}`}`);
5790
+ }
5791
+ }
5792
+ continue;
5793
+ }
5396
5794
  const refreshResults = await runHostInstallers(refreshTarget, hostInstallCtx, { codexWorkspaceDir, codexWorkspaceError });
5397
5795
  refreshedResults.push(...refreshResults);
5398
5796
  for (const hr of refreshResults) {
@@ -5532,23 +5930,141 @@ transaction) {
5532
5930
  logger.warn(`Could not record recovery resolution for ${pendingId} (alarm stays): ${resolutionError instanceof Error ? resolutionError.message : String(resolutionError)}`);
5533
5931
  }
5534
5932
  }
5535
- // PRI-1281 Phase 3 (task §6): user-level OS scheduler reconciliation.
5933
+ // PRI-1281 Phase 3 / PRI-1278 Phase 5: user-level OS scheduler
5934
+ // reconciliation + fresh-install ownership provisioning.
5536
5935
  // POST-COMMIT by design — the runtime transaction is already confirmed,
5537
5936
  // so every bridge failure is a WARNING, never a reported install failure
5538
- // (ERR-197). Consent-gated registration; upgrades only refresh an
5539
- // EXISTING registration (enabled state preserved) and never create one
5540
- // silently. Identity comes from the installer's own authoritative pdHome.
5937
+ // (ERR-197). The consent intent is resolved by the caller; the installer
5938
+ // enforces the two hard rules itself:
5939
+ // 1. an upgrade NEVER enables implicitly (only an explicit flag may);
5940
+ // 2. ownership is handed over ONLY on a fresh install whose scheduler is
5941
+ // verified enabled.
5942
+ let serviceHostOutcome;
5541
5943
  try {
5542
- await reconcileServiceHostScheduler({
5944
+ const freshInstall = freshInstallRun;
5945
+ const requestedConsent = options.serviceHost ?? {
5946
+ // Defensive default for callers that predate the consent contract:
5947
+ // explicit flags only, never an implicit fresh-install enable.
5948
+ intent: options.enableServiceHost === true
5949
+ ? 'enable'
5950
+ : options.registerServiceHost === true
5951
+ ? 'register_only'
5952
+ : 'refresh_if_registered',
5953
+ source: 'explicit_flag',
5954
+ };
5955
+ const consent = requestedConsent.intent === 'enable'
5956
+ && requestedConsent.source !== 'explicit_flag'
5957
+ && !freshInstall
5958
+ ? {
5959
+ intent: 'refresh_if_registered',
5960
+ source: 'policy',
5961
+ }
5962
+ : requestedConsent;
5963
+ if (consent !== requestedConsent) {
5964
+ logger.warn('Service Host scheduler enable was requested implicitly on an EXISTING installation — downgraded to refresh-if-registered. Run `pd service enable` explicitly to arm automatic runs.');
5965
+ }
5966
+ const scheduler = await reconcileServiceHostScheduler({
5543
5967
  pdHome: getPdDir(),
5544
- registerServiceHost: options.enableServiceHost === true || options.registerServiceHost === true,
5545
- enableServiceHost: options.enableServiceHost === true,
5968
+ intent: consent.intent,
5969
+ source: consent.source,
5970
+ freshInstall,
5546
5971
  warn: (message) => logger.warn(message),
5547
5972
  info: (message) => logger.info(message),
5548
5973
  });
5974
+ // Fresh installs ALWAYS run the provisioning step: even when ownership
5975
+ // cannot be handed over yet it records a durable PER-WORKSPACE pending
5976
+ // entry, which is what a later explicit `--enable-service-host` install
5977
+ // resumes. A multi-host install records every real target independently
5978
+ // (`--host all` → OpenClaw + Codex), instead of the last one overwriting
5979
+ // the others.
5980
+ //
5981
+ // An existing installation is resumed ONLY with explicit consent AND a
5982
+ // matching pending marker from a previous fresh install. Historical
5983
+ // workspaces never wrote that marker, so they can never be flipped
5984
+ // implicitly — they still require the quiescing handover.
5985
+ const runTargets = resolveProvisioningTargets({
5986
+ host: options.host,
5987
+ workspaceDir: options.workspaceDir,
5988
+ ...(codexWorkspaceDir !== undefined ? { codexWorkspaceDir } : {}),
5989
+ });
5990
+ const pending = freshInstall
5991
+ ? { entries: [] }
5992
+ : readAllPendingProvisioning(getPdDir());
5993
+ if (pending.warning !== undefined)
5994
+ logger.warn(pending.warning);
5995
+ const targets = mergePendingProvisioningTargets(runTargets, pending.entries);
5996
+ const perTarget = [];
5997
+ for (const target of targets) {
5998
+ if (!existsSync(target.workspaceDir)) {
5999
+ logger.warn(`Service Host provisioning skipped for ${target.workspaceDir}: the directory does not exist.`);
6000
+ continue;
6001
+ }
6002
+ const marker = freshInstall ? null : readPendingProvisioningEvidence(getPdDir(), target.workspaceDir);
6003
+ const resume = shouldProvisionOnInstall({
6004
+ freshInstall,
6005
+ consentIntent: consent.intent,
6006
+ consentSource: consent.source,
6007
+ schedulerState: scheduler.state,
6008
+ hasPendingMarker: marker !== null,
6009
+ });
6010
+ if (!resume)
6011
+ continue;
6012
+ // A deferred resume must use the host binding that exists NOW: this
6013
+ // run may have omitted --host, and the original pending record only
6014
+ // named the host the first install intended.
6015
+ let host = target.host;
6016
+ let bindingVerification;
6017
+ if (marker !== null) {
6018
+ const resolution = resolveResumeProvisioningHost(marker.host, target.workspaceDir);
6019
+ if (resolution.ok) {
6020
+ ({ host } = resolution);
6021
+ }
6022
+ else {
6023
+ bindingVerification = { ok: false, reason: resolution.reason, nextAction: resolution.nextAction };
6024
+ }
6025
+ }
6026
+ const outcome = await provisionFreshInstallWorkspace({
6027
+ pdHome: getPdDir(),
6028
+ workspaceDir: target.workspaceDir,
6029
+ host,
6030
+ scheduler,
6031
+ resume: marker !== null,
6032
+ ...(bindingVerification !== undefined ? { bindingVerification } : {}),
6033
+ warn: (message) => logger.warn(message),
6034
+ info: (message) => logger.info(message),
6035
+ });
6036
+ perTarget.push({ host, workspaceDir: target.workspaceDir, outcome });
6037
+ }
6038
+ const provisioning = perTarget.length > 0
6039
+ ? {
6040
+ targets: perTarget,
6041
+ pending: perTarget.some((entry) => entry.outcome.pendingProvisioning === true),
6042
+ nextAction: perTarget.map((entry) => entry.outcome.nextAction).join(' | '),
6043
+ }
6044
+ : null;
6045
+ serviceHostOutcome = {
6046
+ freshInstall,
6047
+ scheduler,
6048
+ provisioning,
6049
+ nextAction: provisioning?.nextAction ?? scheduler.nextAction,
6050
+ };
5549
6051
  }
5550
6052
  catch (bridgeError) {
5551
- logger.warn(`Service Host scheduler reconciliation threw (${bridgeError instanceof Error ? bridgeError.message : String(bridgeError)}) — the install itself is unaffected; run pd service status manually.`);
6053
+ const detail = bridgeError instanceof Error ? bridgeError.message : String(bridgeError);
6054
+ logger.warn(`Service Host reconciliation threw (${detail}) — the install itself is unaffected; run pd service status manually.`);
6055
+ serviceHostOutcome = {
6056
+ freshInstall: freshInstallRun,
6057
+ scheduler: {
6058
+ state: 'failed',
6059
+ registered: null,
6060
+ enabled: null,
6061
+ detail: `reconciliation_threw:${detail}`,
6062
+ nextAction: 'Run `pd service status --json` and repair the Service Host manually; no ownership change was attempted.',
6063
+ warnings: [detail],
6064
+ },
6065
+ provisioning: null,
6066
+ nextAction: 'Run `pd service status --json` and repair the Service Host manually; no ownership change was attempted.',
6067
+ };
5552
6068
  }
5553
6069
  if (spinner) {
5554
6070
  // rc-9: the runtime transaction IS committed here, but a pending host
@@ -5574,12 +6090,17 @@ transaction) {
5574
6090
  // must not leak past the install either).
5575
6091
  await killConsoleChild();
5576
6092
  // Task 8: auto-launch console via `pd console open` (reuses PRI-300
5577
- // handleConsoleOpen — no new launcher subsystem). Opens the browser to
5578
- // /welcome for onboarding. Detached so the console survives installer exit.
6093
+ // handleConsoleOpen — no new launcher subsystem). A fresh install opens
6094
+ // the browser on /welcome for onboarding. An update launches nothing: the
6095
+ // console the update was started from hands itself over to the new
6096
+ // release, and `pd console open` beside it would only add a second one.
6097
+ // Detached so the console survives installer exit.
5579
6098
  // WorkBuddy remediation: the console manages the GOVERNANCE workspace for
5580
6099
  // this host — the directory hook/worker read — never the project dir.
5581
6100
  const consoleWorkspaceDir = resolveConsoleWorkspaceDir(activeHostTarget, options.workspaceDir, getHomeDir());
5582
- const launchResult = await autoLaunchConsole(consoleWorkspaceDir);
6101
+ const launchResult = mode.launchConsole === false
6102
+ ? { manualOpenCommand: `pd console open --workspace "${consoleWorkspaceDir}"`, consoleUrl: undefined, fallbackAction: undefined }
6103
+ : await autoLaunchConsole(consoleWorkspaceDir);
5583
6104
  // PRI-645: report the ACTUAL effective channels (registry default +
5584
6105
  // sparse override). Never mask an explicit Owner disable with the
5585
6106
  // requested channels — that would re-create ERR-042 (reporting the
@@ -5614,7 +6135,8 @@ transaction) {
5614
6135
  nextActions.push(`Console ready at ${launchResult.consoleUrl} (browser opened automatically)`);
5615
6136
  }
5616
6137
  else {
5617
- // EP-03: auto-launch did not succeed — keep manual start instruction.
6138
+ // EP-03: auto-launch did not succeed (or, for an update, was not asked
6139
+ // for) — keep the manual start instruction.
5618
6140
  nextActions.push(`${launchResult.manualOpenCommand} (listens on 127.0.0.1 only)`);
5619
6141
  }
5620
6142
  }
@@ -5641,6 +6163,8 @@ transaction) {
5641
6163
  ...(legacyBackupMigrationFailures !== undefined ? { legacyBackupMigrationFailures } : {}),
5642
6164
  ...(manualActionReason !== undefined ? { reason: manualActionReason, manualActions: hostManualActions } : {}),
5643
6165
  journal: installerJournalRecord(journal),
6166
+ serviceHost: serviceHostOutcome,
6167
+ hostAdapter: options.host,
5644
6168
  };
5645
6169
  return pendingResult;
5646
6170
  }