@edgehero/pi-dispatch 4.3.1 → 5.1.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 (260) hide show
  1. package/.env.example +84 -3
  2. package/README.md +21 -7
  3. package/deploy/console.service +52 -0
  4. package/deploy/docker-compose.yml +3 -1
  5. package/deploy/pi-dispatch-valkey.container +4 -2
  6. package/deploy/sandbox-gateway.service +23 -0
  7. package/deploy/worker-env-wrapper.cmd +6 -0
  8. package/deploy/worker-env-wrapper.sh +10 -1
  9. package/package.json +118 -19
  10. package/src/agent-snapshot.mjs +49 -0
  11. package/src/answerer-runtime.mjs +194 -0
  12. package/src/answerer.mjs +178 -0
  13. package/src/approval-policy.mjs +76 -0
  14. package/src/approval-runtime.mjs +188 -0
  15. package/src/approval-session.mjs +137 -0
  16. package/src/approval-state.mjs +170 -0
  17. package/src/auth-cli.mjs +86 -0
  18. package/src/auth-connections.mjs +145 -0
  19. package/src/auth-policy.mjs +32 -0
  20. package/src/auth-store.mjs +97 -0
  21. package/src/azure-host.mjs +66 -4
  22. package/src/azure-prompt.mjs +5 -4
  23. package/src/backend-conformance.mjs +34 -2
  24. package/src/backend-local.mjs +103 -34
  25. package/src/backend-openshell.mjs +1540 -0
  26. package/src/backend-podman.mjs +63 -2
  27. package/src/backend-registry.mjs +61 -4
  28. package/src/backends.mjs +395 -6
  29. package/src/bullmq-internals.mjs +208 -0
  30. package/src/canary-cli.mjs +28 -0
  31. package/src/canary-lock.mjs +41 -0
  32. package/src/canary-runtime.mjs +237 -0
  33. package/src/canary.mjs +53 -0
  34. package/src/cancel-cli.mjs +47 -34
  35. package/src/cancel-state.mjs +213 -15
  36. package/src/capabilities.mjs +36 -1
  37. package/src/capacity-cli.mjs +28 -8
  38. package/src/capacity-records.mjs +75 -16
  39. package/src/capacity.mjs +65 -0
  40. package/src/chat-cli.mjs +288 -0
  41. package/src/chat-fork.mjs +547 -0
  42. package/src/chat-mode.mjs +156 -0
  43. package/src/chat-view.mjs +720 -0
  44. package/src/checkpoint-paths.mjs +113 -0
  45. package/src/cli.mjs +136 -41
  46. package/src/comment-tables.mjs +322 -0
  47. package/src/community-auth-adapters.mjs +87 -0
  48. package/src/community-auth-helper.mjs +76 -0
  49. package/src/community-auth-metadata.mjs +6 -0
  50. package/src/community-auth-output-pins.mjs +38 -0
  51. package/src/community-auth-patches.mjs +168 -0
  52. package/src/community-auth-pins.mjs +38 -0
  53. package/src/config.mjs +190 -29
  54. package/src/connection.mjs +83 -7
  55. package/src/console-answer.mjs +113 -0
  56. package/src/console-audit.mjs +604 -0
  57. package/src/console-bootstrap.mjs +325 -0
  58. package/src/console-client.mjs +848 -0
  59. package/src/console-devices.mjs +372 -0
  60. package/src/console-install.mjs +239 -0
  61. package/src/console-open.mjs +99 -0
  62. package/src/console-probe.mjs +106 -0
  63. package/src/console-tokens.mjs +459 -0
  64. package/src/container-names.mjs +51 -0
  65. package/src/container-spec.mjs +20 -1
  66. package/src/cpu-reserve.mjs +4 -1
  67. package/src/defer-reasons.mjs +200 -0
  68. package/src/defer-write.mjs +208 -0
  69. package/src/deployment-venue.mjs +23 -6
  70. package/src/docker-run.mjs +11 -0
  71. package/src/doctor-bundles.mjs +130 -0
  72. package/src/doctor-model-proposals.mjs +109 -0
  73. package/src/doctor-openshell.mjs +238 -0
  74. package/src/doctor-results.mjs +602 -0
  75. package/src/doctor-spawner.mjs +215 -0
  76. package/src/doctor.mjs +1657 -196
  77. package/src/dollar-budget.mjs +212 -3
  78. package/src/endpoint-status.mjs +100 -0
  79. package/src/env-allowlist.mjs +96 -6
  80. package/src/env-file.mjs +6 -4
  81. package/src/envelope.mjs +5 -3
  82. package/src/file-expect.mjs +47 -0
  83. package/src/forgejo-host.mjs +42 -5
  84. package/src/forgejo-prompt.mjs +5 -4
  85. package/src/forges.mjs +33 -3
  86. package/src/fork-job.mjs +58 -0
  87. package/src/fork-policy.mjs +23 -0
  88. package/src/fork-store.mjs +338 -0
  89. package/src/get-token.mjs +1 -1
  90. package/src/git-dirty.mjs +119 -14
  91. package/src/git-hardening.mjs +85 -0
  92. package/src/github-host.mjs +31 -6
  93. package/src/github-prompt.mjs +7 -16
  94. package/src/gitlab-host.mjs +42 -3
  95. package/src/gitlab-prompt.mjs +5 -4
  96. package/src/held-document.mjs +23 -0
  97. package/src/held-replies.mjs +325 -0
  98. package/src/held-settle.mjs +266 -0
  99. package/src/hook-runs.mjs +188 -0
  100. package/src/host-budget.mjs +8 -5
  101. package/src/host-clone.mjs +72 -0
  102. package/src/host-loads.mjs +557 -0
  103. package/src/host-registry.mjs +66 -6
  104. package/src/host-telemetry.mjs +92 -0
  105. package/src/http-body.mjs +78 -0
  106. package/src/image-preflight.mjs +156 -13
  107. package/src/import-pi.mjs +60 -172
  108. package/src/inbox-relay.mjs +482 -0
  109. package/src/inbox-settle.mjs +196 -0
  110. package/src/index.mjs +734 -129
  111. package/src/init.mjs +35 -5
  112. package/src/job-data-version.mjs +75 -0
  113. package/src/job-id.mjs +30 -15
  114. package/src/job-layout.mjs +22 -0
  115. package/src/job-size.mjs +16 -0
  116. package/src/live-jobs.mjs +14 -6
  117. package/src/live-probes.mjs +6 -2
  118. package/src/live-transcript.mjs +872 -0
  119. package/src/loaded-record.mjs +609 -0
  120. package/src/mcp-config.mjs +4 -2
  121. package/src/mcp-preflight.mjs +36 -5
  122. package/src/model-attempts.mjs +84 -0
  123. package/src/model-catalog.mjs +83 -0
  124. package/src/model-cooldowns.mjs +22 -0
  125. package/src/model-failover-protocol.mjs +11 -0
  126. package/src/model-failover.mjs +134 -0
  127. package/src/model-observation.mjs +50 -0
  128. package/src/model-proposal-protocol.mjs +21 -0
  129. package/src/model-proposals.mjs +75 -0
  130. package/src/model-ref.mjs +67 -10
  131. package/src/model-roles-file.mjs +24 -0
  132. package/src/model-roles.mjs +73 -0
  133. package/src/model-status.mjs +34 -0
  134. package/src/models-json.mjs +12 -2
  135. package/src/money.mjs +1 -1
  136. package/src/oauth-openai.mjs +121 -0
  137. package/src/older-state.mjs +249 -0
  138. package/src/on-failure.mjs +17 -13
  139. package/src/open-browser.mjs +31 -2
  140. package/src/opener-cli.mjs +135 -0
  141. package/src/opener-protocol.mjs +27 -0
  142. package/src/opener-terminal.mjs +128 -0
  143. package/src/openshell-cli.mjs +155 -0
  144. package/src/openshell-policy.mjs +163 -0
  145. package/src/outbox.mjs +14 -0
  146. package/src/output-cap.mjs +1 -0
  147. package/src/package-canary-record.mjs +26 -0
  148. package/src/package-canary.mjs +135 -0
  149. package/src/package-names.mjs +9 -0
  150. package/src/package-stage.mjs +418 -0
  151. package/src/packages.mjs +24 -16
  152. package/src/parked.mjs +2 -1
  153. package/src/pause-windows.mjs +136 -17
  154. package/src/podman-stack.mjs +40 -14
  155. package/src/portfolio-snapshot.mjs +26 -7
  156. package/src/prepare-github.mjs +41 -77
  157. package/src/prepare-local.mjs +32 -2
  158. package/src/prepare.mjs +45 -11
  159. package/src/private-store-boundary.mjs +70 -0
  160. package/src/processor.mjs +1550 -173
  161. package/src/projects.mjs +23 -0
  162. package/src/prompt-fence.mjs +18 -0
  163. package/src/provider-key.mjs +7 -0
  164. package/src/provider-steering.mjs +1 -0
  165. package/src/question-context.mjs +35 -0
  166. package/src/question-group-runtime.mjs +91 -0
  167. package/src/question-groups.mjs +171 -0
  168. package/src/queue.mjs +264 -55
  169. package/src/reason-catalog.mjs +448 -0
  170. package/src/receiver-status.mjs +230 -0
  171. package/src/record-reason.mjs +37 -0
  172. package/src/recovery-queue.mjs +566 -0
  173. package/src/redact-secrets.mjs +219 -0
  174. package/src/reserve-estimate.mjs +101 -0
  175. package/src/reserved-env.mjs +36 -1
  176. package/src/retention.mjs +67 -0
  177. package/src/run-budget-ledger.mjs +283 -0
  178. package/src/run-checkpoint.mjs +627 -0
  179. package/src/run-container.mjs +749 -33
  180. package/src/run-history.mjs +791 -45
  181. package/src/run-mirror.mjs +75 -7
  182. package/src/run-progress.mjs +751 -0
  183. package/src/runtime-observations.mjs +3 -1
  184. package/src/runtime-settings.mjs +272 -37
  185. package/src/sandbox-cli.mjs +78 -2
  186. package/src/sandbox-deployment.mjs +51 -0
  187. package/src/sandbox-gateway-protocol.mjs +378 -0
  188. package/src/sandbox-hosts.mjs +100 -0
  189. package/src/sandbox-inventory.mjs +83 -0
  190. package/src/sandbox-policy.mjs +225 -0
  191. package/src/sandbox-prepare-requests.mjs +145 -0
  192. package/src/sandbox-prepare.mjs +285 -0
  193. package/src/sandbox-refs.mjs +70 -0
  194. package/src/sandbox-session-monitor.mjs +4 -0
  195. package/src/sandbox-session-watch.mjs +124 -0
  196. package/src/sandbox-sessions.mjs +161 -0
  197. package/src/sandbox-store.mjs +63 -6
  198. package/src/sandbox-workspace-guard.mjs +39 -0
  199. package/src/sandbox.mjs +27 -200
  200. package/src/scheduler-stall-guard.mjs +14 -8
  201. package/src/schedules.mjs +19 -6
  202. package/src/secret-bundles.mjs +245 -0
  203. package/src/secret-profiles.mjs +103 -3
  204. package/src/secrets.mjs +19 -9
  205. package/src/service-env.mjs +38 -5
  206. package/src/service.mjs +638 -106
  207. package/src/session-key.mjs +60 -0
  208. package/src/session-store.mjs +168 -10
  209. package/src/setup-contract.mjs +40 -0
  210. package/src/setup-egress.mjs +113 -0
  211. package/src/setup-host-entry.mjs +36 -0
  212. package/src/setup-host.mjs +242 -0
  213. package/src/setup-lock.mjs +41 -0
  214. package/src/size-records.mjs +15 -3
  215. package/src/start.mjs +1353 -135
  216. package/src/status-comment.mjs +415 -0
  217. package/src/stderr-transcript.mjs +318 -0
  218. package/src/steer-ack.mjs +122 -0
  219. package/src/steer-cli.mjs +213 -0
  220. package/src/steer-framing.mjs +185 -0
  221. package/src/steer-inbox.mjs +693 -0
  222. package/src/store-version.mjs +139 -0
  223. package/src/subscription-config.mjs +56 -0
  224. package/src/subscription-limits.mjs +3 -0
  225. package/src/subscription-quota.mjs +259 -0
  226. package/src/subscription-runtime.mjs +123 -0
  227. package/src/subscription-status.mjs +42 -0
  228. package/src/subscription-wait.mjs +11 -0
  229. package/src/subscriptions.mjs +7 -1
  230. package/src/thinking-level.mjs +19 -0
  231. package/src/touch-outbox.mjs +61 -0
  232. package/src/touch-state.mjs +133 -0
  233. package/src/triggers-file.mjs +299 -39
  234. package/src/triggers.mjs +780 -38
  235. package/src/trust-paths.mjs +171 -0
  236. package/src/up.mjs +402 -53
  237. package/src/updates-cli.mjs +61 -0
  238. package/src/updates-look.mjs +127 -0
  239. package/src/updates-reconcile.mjs +182 -0
  240. package/src/updates-subscription-adapters.mjs +8 -0
  241. package/src/updates.mjs +252 -0
  242. package/src/valkey-auth.mjs +32 -9
  243. package/src/valkey-endpoint.mjs +14 -4
  244. package/src/wait-for.mjs +1 -1
  245. package/src/wait-state.mjs +62 -3
  246. package/src/watch-board.mjs +38 -0
  247. package/src/watch-closer.mjs +1 -1
  248. package/src/watch-contract.mjs +102 -0
  249. package/src/watch-decision.mjs +78 -0
  250. package/src/watch-drainer.mjs +14 -0
  251. package/src/watch-issue-adapter.mjs +44 -0
  252. package/src/watch-issue.mjs +111 -0
  253. package/src/watch-record.mjs +10 -0
  254. package/src/watch-runtime.mjs +167 -0
  255. package/src/watch-store.mjs +183 -0
  256. package/src/watch-trace.mjs +34 -0
  257. package/src/workspace-checkpoint.mjs +1750 -0
  258. package/src/zero-touch-fixes.mjs +99 -0
  259. package/src/zero-touch.mjs +225 -0
  260. package/src/repeat-slot.mjs +0 -13
package/src/doctor.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  /**
2
3
  * `pi-dispatch doctor` — preflight the host before the first job. Prints a ✓/⚠/✗ line per prerequisite
3
4
  * with a one-line fix, and exits non-zero if any hard check fails, so it is usable in a setup script.
@@ -52,30 +53,33 @@
52
53
  import { accessSync, chmodSync, closeSync, constants as fsConstants, existsSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, realpathSync, rmSync, statSync } from "node:fs";
53
54
  import { lookup as dnsLookup } from "node:dns/promises";
54
55
  import { homedir, networkInterfaces, release as osRelease, tmpdir, userInfo } from "node:os";
56
+ import { BlockList, isIPv4, isIPv6 } from "node:net";
57
+ import * as nodeFs from "node:fs";
55
58
  import { NETNS_KEEPER, NETNS_KEEPER_FORMAT, NETNS_KEEPER_START, STACK_KEYS, STARTED_AT_FORMAT, VALKEY_SHARED_KEY, judgeNetnsKeeper, judgeValkeyListeners, netnsKeeperRemedy, pinnedValkeyUrl, podmanNeedsNetnsKeeper, probeTcpAddress, proxyConfCopyPath, readSubuidRanges, proxyRestartAdvice, readLinger, readValkeyKeys, valkeySharedOn, valkeyTarget } from "./podman-stack.mjs";
56
- import { basename, dirname, isAbsolute, join, delimiter, posix, resolve, win32 } from "node:path";
59
+ import { basename, dirname, isAbsolute, join, posix, resolve, win32 } from "node:path";
57
60
  import { fileURLToPath } from "node:url";
58
61
  import { spawn as nodeSpawn } from "node:child_process";
59
62
  import { randomBytes } from "node:crypto";
60
- import { DEFAULT_MODEL, DEFAULT_PROVIDER, DEFAULT_VALKEY_URL, accountTempRoot, allowedModelsFrom, defaultLogsDir, defaultSandboxDir, defaultSettingsFile, defaultWorkerName, globalExtensionsEnabled, jobsDirOwnerFix, jobsDirPath, sandboxDirOwnerFix, legacyTempStateDir, logsDirPath, modelEndpointsFilePath, delimitedList, envelopeFilePath, pauseWindowsFilePath, projectsFilePath, safeHomeDir, scopedLimitsFilePath, settingsFilePath, underOsTempDir } from "./config.mjs";
63
+ import { DEFAULT_MODEL, DEFAULT_PROVIDER, DEFAULT_VALKEY_URL, accountTempRoot, checkpointStoreCollision, checkpointsDirPath, allowedModelsFrom, modelFrom, providerFrom, defaultLogsDir, defaultSandboxDir, defaultSettingsFile, defaultWorkerName, globalExtensionsEnabled, jobsDirOwnerFix, jobsDirPath, sandboxDirOwnerFix, legacyTempStateDir, logsDirPath, modelEndpointsFilePath, delimitedList, envelopeFilePath, pauseWindowsFilePath, projectsFilePath, safeHomeDir, scopedLimitsFilePath, settingsFilePath, underOsTempDir, workerName as workerNameFrom } from "./config.mjs";
61
64
  import { SYSTEMD_HAZARD_SHAPES, decodeEnvFile, envFileHazard, envValueShown, quotedRegions, readEnvAssignments, renderEnvValue, envFileWrapperInternal, wrapperInternalSentence } from "./env-file.mjs";
62
65
  import { canonicalScope, danglingProjectRows, dollarRowsBelowJobCap, dollarRowsWithoutCap, isModelScope, isProjectScope, loadScopedLimits, parseScopedLimits, scopedLimitsVersionFor } from "./scoped-limits.mjs";
63
- import { EMPTY_PROJECTS_FINGERPRINT, loadProjects, projectsFingerprint } from "./projects.mjs";
66
+ import { EMPTY_PROJECTS_FINGERPRINT, escapeControls, loadProjects, projectOf, projectsFingerprint } from "./projects.mjs";
64
67
  import { parseModelsJson, stripBom, stripJsonComments } from "./models-json.mjs";
65
- import { isTransientOverlayRead, overlayProviderProblem } from "./model-catalog.mjs";
68
+ import { FIRST_CALL_MIN_CONTEXT_BYTES, FIRST_CALL_OVERHEAD_TOKENS, boundModelOf, firstCallFloorMicros, isTransientOverlayRead, overlayProviderProblem, serviceTierMultiplier } from "./model-catalog.mjs";
66
69
  import { EMPTY_USD_FINGERPRINT, usdFingerprint } from "./dollar-fingerprint.mjs";
67
70
  import { splitModelEntry } from "./model-ref.mjs";
71
+ import { resolveConfiguredModelRuns as resolveDoctorModelRuns, cooldownModelRefs, RADIUS_COST_CAP_LABEL, RADIUS_COST_CAP_FIX } from "./model-observation.mjs";
68
72
  import { ignoredOutputCapModels, outputCapView, outputUnboundable } from "./output-cap.mjs";
69
73
  import { KEYLESS_API_KEY, KEYLESS_HOW, MODEL_ENDPOINTS_FILE_NAME, MODEL_ENDPOINTS_INCLUDE_NAME, MODEL_ENDPOINT_ID_RE, OVERLAY_LINK_FIX, OVERLAY_NOT_A_FILE_FIX, RENAMED_PROVIDERS, baseUrlTarget, endpointsAt, keylessVerdict, loadModelEndpoints, providerRenameHint, readOverlayModels, renderEndpointsInclude, unreportedUsageModels } from "./model-endpoints.mjs";
70
74
  import { declaredEndpointsIn, endpointsDeclaredIn, reloadCommand, rulesFileIncludes, rulesPredateEndpointsLine } from "./egress-cli.mjs";
71
- import { loadPauseWindows, parseScopeString } from "./pause-windows.mjs";
75
+ import { loadPauseWindows, parsePauseWindows, parseScopeString, pauseWindowsVersionFor } from "./pause-windows.mjs";
72
76
  import { WAIT_AFTER_MAX_DEFAULT_MS, afterInstantMs, parseWaitProfiles } from "./wait-for.mjs";
73
77
  import { isForgeKind } from "./forges.mjs";
74
78
  import { findLiteralSecret, ADMIN_RE } from "./import-pi.mjs";
75
79
  import { mcpServerWhere, readOverlayMcp } from "./mcp-config.mjs";
76
80
  import { allowlistEntryFor, egressRefusalFor, packageRunnerHosts, parseAllowlist } from "./egress-allowlist.mjs";
77
81
  import { agentDirFrom, readHostPi } from "./host-pi.mjs";
78
- import { PACKAGES_SUBDIR, readStagedSkills, readStageManifest } from "./packages.mjs";
82
+ import { PACKAGES_SUBDIR, readStagedSkills, readStageManifest, STAGE_MANIFEST } from "./packages.mjs";
79
83
  import { copySkillTree } from "./copy-tree.mjs";
80
84
  import { SKILL_NAME_RE } from "./flow-gate.mjs";
81
85
  import { GIT_READ_FLAGS } from "./git-hardening.mjs";
@@ -84,21 +88,21 @@ import { deploymentVenueEnv, sharedShellIgnored } from "./deployment-venue.mjs";
84
88
  import { readDeploymentEnv, resolveServiceEnv, serviceEnvFileOf, serviceEnvLoader } from "./service-env.mjs";
85
89
  import { imageRefProblem, jobImageFix, pullOffered } from "./image-ref.mjs";
86
90
  import { PROXY_STATE_FORMAT, parseProxyState, rulesIncludeEndpoints, shippedProxyDrift } from "./egress-proxy-state.mjs";
87
- import { PACKAGED_EGRESS_PROXY_CONF, judgeProxyConfCopy, packageCopyName, readPackagedProxyConf } from "./egress-conf-copy.mjs";
88
- import { ABSENT, ASSERTED, DAEMON_APPLIES_BOUNDS, DEFAULT_BACKEND, DOCKER_ENDPOINT_LOCAL, OBSERVATION_FIX, OBSERVATIONS, PODMAN_ADDS_NO_MOUNTS, PODMAN_BACKEND, PODMAN_BOUNDS_DELEGATED, PODMAN_ROOTFUL_WIDENING_KEYS, PODMAN_SERVICE_LOCAL, PROPERTY_NAMES, RUNTIME_ADDS_NO_MOUNTS, HOST_ROUTE_LAN, HOST_ROUTE_REFUTED, HOST_ROUTE_WORKS, declarationOf, floorShortfall, hostRouteFor, isProxyLocalHost, parseBackendFloor, parseBackendList, unarmedFloor, unobservedFloor, venuesOf } from "./backends.mjs";
89
- import { PODMAN_BOOT_REFUSING_CAUSES, PODMAN_FIRST_START_TIMEOUT_MS, PODMAN_INFO_TIMEOUT_MS, PODMAN_JOB_USER_FIX, decidePodmanJobUser, makePodmanInfoReader, observePodman, observeRootlessNetns, podmanConfFix, podmanConfWidening, resolvePodmanImageUser } from "./backend-podman.mjs";
90
- import { PODMAN_PINNED_FLAGS, buildPodmanRunArgs, containerSpec, podmanArgsFromSpec } from "./docker-run.mjs";
91
+ import { PACKAGED_EGRESS_PROXY_CONF, PACKAGE_VERSION, judgeProxyConfCopy, packageCopyName, readPackagedProxyConf } from "./egress-conf-copy.mjs";
92
+ import { ABSENT, ASSERTED, BACKENDS, DAEMON_APPLIES_BOUNDS, DEFAULT_BACKEND, DOCKER_ENDPOINT_LOCAL, OBSERVATION_FIX, OBSERVATIONS, PODMAN_ADDS_NO_MOUNTS, PODMAN_BACKEND, PODMAN_BOUNDS_DELEGATED, PODMAN_ROOTFUL_WIDENING_KEYS, PODMAN_SERVICE_LOCAL, PROPERTY_NAMES, RUNTIME_ADDS_NO_MOUNTS, HOST_ROUTE_LAN, HOST_ROUTE_REFUTED, HOST_ROUTE_WORKS, backendRefusals, declarationOf, floorShortfall, hostRouteFor, isProxyLocalHost, openshellSetupOf, parseBackendFloor, parseBackendList, unarmedFloor, unobservedFloor, venuesOf } from "./backends.mjs";
93
+ import { PODMAN_BOOT_REFUSING_CAUSES, PODMAN_FIRST_START_TIMEOUT_MS, PODMAN_INFO_TIMEOUT_MS, PODMAN_JOB_USER_FIX, decidePodmanJobUser, makePodmanInfoReader, podmanPausable, observePodman, observeRootlessNetns, podmanConfFix, podmanConfWidening, resolvePodmanImageUser } from "./backend-podman.mjs";
94
+ import { PODMAN_PINNED_FLAGS, buildDockerRunArgs, buildPodmanRunArgs, containerSpec, podmanArgsFromSpec } from "./docker-run.mjs";
91
95
  import { PODMAN_SERVICE_TIMEOUT_MS, PODMAN_SERVICE_UNIT, makePodmanServiceReader, observeHost, observeRootfulConf, readRootfulService, rootfulConfFix, rootfulConfRetries, rootfulConfResidual, rootfulUnreadList } from "./runtime-observations.mjs";
92
96
  import { JOB_NAME_PREFIX, endpointShown, makeDockerEndpointResolver, quotedShown } from "./backend-local.mjs";
93
97
  import { DEFAULT_EGRESS_PROXY, STOPPED_PROXY_STATES, EGRESS_CANARY_NET_PREFIX, EGRESS_CANARY_PROBE_PREFIX, EGRESS_ENDPOINT_PROBE_PREFIX, egressArmed, egressCanaryNetwork, egressCanaryProbe, egressEndpointProbe, egressEnv, egressProxyName, egressProxyUrl, networkEndpoints, removeNetworkOrSay } from "./egress.mjs";
94
98
  import { detachBlockedSentence, makeDetachGate, runtimeFromFacts } from "./netns-keeper.mjs";
95
99
  import { runLiveProbes } from "./live-probes.mjs";
96
- import { VALKEY_PASSWORD_KEY, VALKEY_PASSWORD_HOWTO, VALKEY_PORT_KEY, isLoopbackHost, valkeyPasswordProblem, valkeyPortConflict } from "./valkey-auth.mjs";
100
+ import { COMPOSE_VALKEY_OVERRIDE, VALKEY_PASSWORD_KEY, VALKEY_PASSWORD_HOWTO, VALKEY_PORT_KEY, isLoopbackHost, valkeyContainerOwner, valkeyPasswordProblem, valkeyPortConflict } from "./valkey-auth.mjs";
97
101
  import { urlShown, valkeyContextFromResolution, valkeyPasswordFor, valkeyUrlProblem } from "./valkey-endpoint.mjs";
98
102
  import { SANDBOX_TOMBSTONE_STUCK_MS, isSandboxTombstone, sandboxTombstoneAge } from "./sandbox-store.mjs";
99
- import { installedUnitPaths, readUnitSeam, readUnitUser } from "./service.mjs";
103
+ import { installedConsoleUnitPath, installedUnitPaths, readUnitSeam, readUnitUser } from "./service.mjs";
100
104
  import { CONTAINER_HOME, SHIPPED_IMAGE_UID, SIZE_LABEL_CPU, SIZE_LABEL_MEM } from "./container-spec.mjs";
101
- import { DEFAULT_JOB_SIZE, cpuCeilingCenti, formatCpus, formatMemory, jobSizeDefaults, resolveJobSize } from "./job-size.mjs";
105
+ import { DEFAULT_JOB_SIZE, codemodeWorkersOf, cpuCeilingCenti, formatCpus, formatMemory, jobSizeDefaults, resolveJobSize } from "./job-size.mjs";
102
106
  import { SUGGEST_WINDOW_DAYS, cpusText, hostCap, refusalWords, sizeRefusal, suggestSize, suggestionCall, suggestionEvidence } from "./size-suggest.mjs";
103
107
  import { SIZING_RECORD_MAX_BYTES, readSizingRecords } from "./size-records.mjs";
104
108
  import { CAPACITY_WINDOWS, computeCapacity } from "./capacity.mjs";
@@ -107,19 +111,39 @@ import { CGROUP_PARENT, cgroupParentFor, operatorQuotaCommand, readQuota, reserv
107
111
  import { HOST_BUDGET_KEYS, computeHostBudget, hostBudgetSettings, largestFit, neverFits, projectBudgetRow, publishedBudget, readUserServiceLimits } from "./host-budget.mjs";
108
112
  import { makeImagePreflight, normalizeImageId } from "./image-preflight.mjs";
109
113
  import { BOOT_REFUSING_JOB_USER_CAUSES, DAEMON_FACTS_TIMEOUT_MS, JOB_USER_FIX, makeDaemonFactsReader, makeJobUserResolver, relabelsPrivateMounts, resolveImageUser } from "./job-user.mjs";
110
- import { parseSecretProfiles } from "./secret-profiles.mjs";
114
+ import { mergeSecretProfiles, parseSecretProfiles, servableSecretProfiles } from "./secret-profiles.mjs";
111
115
  // The OAuth-suffix rule and the variable it selects live in their own import-free module so the worker
112
116
  // can share them: doctor NAMES a variable and env-allowlist WRITES one, and they must never differ.
113
117
  import { apiKeyVariable, nonApiKeyKind } from "./provider-key.mjs";
114
- import { parseTriggers } from "./triggers.mjs";
115
- import { readOverlay, resolveSettings } from "./runtime-settings.mjs";
116
- import { DOLLAR_KEY_PREFIX } from "./dollar-budget.mjs";
118
+ import { WORKER_NAME_RE } from "./worker-name.mjs";
119
+ import { parseTriggersDocument, triggersFileVersionFor } from "./triggers.mjs";
120
+ import { jobDataVersionFor } from "./job-data-version.mjs";
121
+ import { secretBundleChecks } from "./doctor-bundles.mjs";
122
+ import { doctorModelProposalChecks } from "./doctor-model-proposals.mjs";
123
+
124
+ /**
125
+ * How long `doctor --secrets` waits for one bundle resolver (issue #704): doctor's own 30 s capture bound, not the
126
+ * job path's tighter PI_SECRET_RESOLVE_TIMEOUT_MS. A job's read sits in front of a paid container and holds a slot;
127
+ * doctor's is an operator at a prompt asking whether the wiring works, and a slow manager is an answer, not a fault.
128
+ */
129
+ const BUNDLE_DOCTOR_TIMEOUT_MS = 30_000;
130
+ import { readOverlay, readOverlayDocument, resolveSettings, settingsVersionFor } from "./runtime-settings.mjs";
131
+ import { DEPLOYMENT_WINDOWS, DOLLAR_KEY_PREFIX, deploymentWindowsAt, dollarWindowCaps, dollarWindowFloors, valkeyEndpointTag } from "./dollar-budget.mjs";
117
132
  import { dayKey, monthKey, weekKey } from "./budget.mjs";
118
133
  import { DOLLAR_ENV_NAMES, DOLLAR_SETTING_KEYS, checkDollarInvariant, effectiveCostCapMicros, formatMicros, optionalUsdMicros, parseUsdMicros } from "./money.mjs";
119
134
  import { cronPlacement, envelopeJobPaths } from "./schedules.mjs";
120
- import { envelopeDigest, loadEnvelopeChecked } from "./envelope.mjs";
135
+ import { envelopeDigest, envelopeInsideJobPaths, loadEnvelopeChecked } from "./envelope.mjs";
136
+ import { keptTokens, operatorCount, readTokensFile, tokensFilePath } from "./console-tokens.mjs";
137
+ import { consoleDevicesDir, devicesState } from "./console-devices.mjs";
138
+ import { RUN_MIRROR_MAX_RUNS_DEFAULT, RUN_MIRROR_MAX_RUNS_MAX, RUN_MIRROR_MAX_RUNS_MIN, runMirrorMaxRunsOf } from "./retention.mjs";
139
+ import { verifyConsoleAudit } from "./console-audit.mjs";
121
140
  import { OTHER } from "./priorities.mjs";
122
141
  import { ALLOC_PLAN_KEY, NO_ENVELOPE_FINGERPRINT } from "./allocation.mjs";
142
+ import { assignCheckIds, buildDoctorRecord, doctorIntervalHours, publishRedactor, secretValuesIn } from "./doctor-results.mjs";
143
+ import { olderStateFindings as olderStateFindingsReal, VALKEY_CONTAINER } from "./older-state.mjs";
144
+ import { DOCTOR_PUBLISH_SKIPPED_PREFIX } from "./doctor-spawner.mjs";
145
+ import { extensionsNotHere } from "./loaded-record.mjs";
146
+ import { buildHostLoads, flowProbes, flowTierOf, mcpRowsOf, pathIsThere, readOverlayExtensionRows, readOverlaySkillNames } from "./host-loads.mjs";
123
147
 
124
148
  const NODE_FLOOR = [22, 19]; // pi's engine floor (22.19.0)
125
149
 
@@ -181,7 +205,8 @@ const ghProbeArgs = (image, bin) => ["run", "--rm", "-i", "--pull=never", ...(bi
181
205
  export async function runDoctor(shellVars = process.env, deps = {}) {
182
206
  const {
183
207
  cwd = process.cwd(),
184
- out = (s) => process.stdout.write(s),
208
+ out: output = (s) => process.stdout.write(s),
209
+ json = false,
185
210
  spawn = nodeSpawn,
186
211
  // The bounds every `runCmd` goes through (issue #397). A seam so a test can drive the timeout path
187
212
  // in milliseconds; nothing else passes it.
@@ -217,20 +242,55 @@ export async function runDoctor(shellVars = process.env, deps = {}) {
217
242
  // without uninstalling a dependency. Threaded like every other seam: a seam collectChecks honours
218
243
  // and runDoctor silently drops is a seam that cannot pin an EXIT CODE, only a check object.
219
244
  providerOracle = defaultProviderOracle,
245
+ subscriptionFactory,
220
246
  // Issues #501 and #502: the worker's model catalog and pi's own model loader, both imported lazily. Seams, so a test
221
247
  // can drive the not-installed arm and a disagreement without editing pi. Undefined means the defaults.
222
248
  modelCatalog,
223
249
  piModelLoader,
250
+ modelProposals,
224
251
  dollarKeysExist,
225
252
  // Issue #504 part B: the applied split's envelope digest (`alloc:plan`), read once. Undefined means the default.
226
253
  readAppliedSplit,
227
254
  // Issue #599, phase 2: the capacity line's read of the run history (the run mirror and the logs directory).
228
255
  // Undefined means the default, which reads the deployment's real Valkey and files.
229
256
  readCapacity,
257
+ // Issue #761: the dollar window check's two reads, this host's records and then the counters (`doctorDollarWindows`),
258
+ // and the stores an older release left behind (`olderStateFindings`, older-state.mjs). Undefined means the defaults,
259
+ // which read the deployment's real files, Valkey and Docker.
260
+ readDollarRecords,
261
+ readDollarCounters,
262
+ olderStateFindings,
263
+ // Issue #708: whether the operator console answers (`probeConsole`, console-probe.mjs). Undefined means the default,
264
+ // which sends one GET /healthz to a loopback address or the socket, so a test passes its own.
265
+ consoleProbe,
230
266
  // --live (issue #278, INT-LIVE-PROBE-CONTRACT): read the backend declarations back off short-lived real containers.
231
267
  // STRICTLY `=== true`, so only the CLI's own flag arms it: a truthy string from a caller that forwarded an
232
268
  // option bag runs nothing. The fs, PID-liveness and nonce are seams so the sequence is driven without Docker.
233
269
  live = false,
270
+ // The granted browser action publishes observations without starting/sweeping probe containers (#774).
271
+ setupReadOnly = false,
272
+ // Issue #683: `--openshell`, the openshell venue's lines (doctor-openshell.mjs), strictly `=== true` as `live`.
273
+ // `openshellRun` is their spawn seam, for the tests.
274
+ openshell = false,
275
+ // Issue #704: `--secrets`, resolve each project secret bundle on this host and print its variable names and count,
276
+ // never a value (doctor-bundles.mjs). Strictly `=== true`, as `live`: it spawns every bundle resolver, which reads
277
+ // the operator's manager. `bundleSpawn` is its spawn seam, for the tests.
278
+ secrets = false,
279
+ bundleSpawn,
280
+ // Issue #712: publish this run's results to Valkey for the console and the panel (`doctor-results.mjs`). Strictly
281
+ // `=== true`, as `live`: the CLI passes it unless `--no-publish`, and a caller that hands runDoctor an option bag
282
+ // (every test) publishes nothing unless it says so. `publishDoctor(url, name, record, loads)` is the write, a seam so a
283
+ // test drives it against a fake Valkey; `writeErr` takes the one line said when it could not publish; `publishNow`
284
+ // stamps the record.
285
+ publish = false,
286
+ // `{ worker: true, every }` when the worker's own spawn ran this (`--by-worker=<hours>`): the record then carries the
287
+ // interval the worker actually runs at, not this resolution's reading of it.
288
+ publishBy = null,
289
+ publishDoctor = defaultPublishDoctor,
290
+ hostLoadsOf = doctorHostLoads,
291
+ writeErr = (s) => process.stderr.write(s),
292
+ publishNow = Date.now,
293
+ openshellRun,
234
294
  liveFs = { chmodSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync },
235
295
  // Issue #341: who a job on this host would run as, decided from the same facts the worker reads. Seams because
236
296
  // the answer is this process's own ids and a daemon, neither of which belongs in a unit test. `stat` reads the
@@ -247,6 +307,8 @@ export async function runDoctor(shellVars = process.env, deps = {}) {
247
307
  readEnvFile = (path) => readFileSync(path),
248
308
  // Issue #345: the host files the runtime-mounts observation reads (Podman's mounts.conf and containers.conf).
249
309
  observationFs = { statSync, readFileSync, readdirSync },
310
+ // Issue #800: what the flow tiers read, so a test can stand in for a folder at mode 000, which root reads straight through.
311
+ flowFs = { statSync, readFileSync, readdirSync },
250
312
  // Issue #464: the jobs dir check's reads (its owner, whether this account may write it, the old shared default's
251
313
  // retained workspaces). Never a write: doctor says what the worker will meet, and the worker creates the dir.
252
314
  jobsDirFs = { accessSync, lstatSync, readdirSync, statSync },
@@ -315,6 +377,8 @@ export async function runDoctor(shellVars = process.env, deps = {}) {
315
377
  // against), and the text handed to the first `.env` read the checks below make, so a run still reads the file once.
316
378
  // A file that is there and cannot be read is said, as `up` says it (gate round 2): the venue then comes from this
317
379
  // shell alone. An absent one (ENOENT) is simply absent.
380
+ // JSON owns stdout; the same diagnostics and fixes remain visible on stderr.
381
+ const out = json === true ? writeErr : output;
318
382
  const envPath = join(cwd, ".env");
319
383
  // BYTES (issue #447): what systemd refuses to load is judged before decoding. Through ONE descriptor since gate round
320
384
  // 2 (`readDeploymentEnv`, the panel's reader too): judged by `stat` and read by path, a folder another account could
@@ -390,7 +454,7 @@ export async function runDoctor(shellVars = process.env, deps = {}) {
390
454
  return { ...(await valkeyAuthState(url, { context, withoutPassword })), passwordSet: Boolean(sent.password), from: sent.from };
391
455
  }
392
456
  : null;
393
- const seams = { cwd, out, spawn, probeValkey, valkeyAuth: valkeyAuthSeam, readHosts, ...(modelCatalog ? { modelCatalog } : {}), ...(piModelLoader ? { piModelLoader } : {}), ...(dollarKeysExist ? { dollarKeysExist } : {}), ...(readAppliedSplit ? { readAppliedSplit } : {}), ...(readCapacity ? { readCapacity } : {}), fileExists, nodeVersion, mkdir, chmod, rm, agentDir, platform, home, providerOracle, facts, jobUserIdentity, stat, passwd, readUnit, readEnvFile: readEnvFileShared, observationFs, jobsDirFs, jobsDirUid, valkeyOwner: valkeyOwnerSeam, isAlive, pid, runTimeouts, live: live === true, wallClock, ...(readRunRecords ? { readRunRecords } : {}), venueChecks, userName, proxyFilesExist, proxyFileIsDirectory, ...(includeNeeds ? { includeNeeds } : {}), ...(declaredEndpoints ? { declaredEndpoints } : {}), ...(readOverlayFile ? { readOverlayFile } : {}), ...(lstatOverlayFile ? { lstatOverlayFile } : {}), ...(hostAddresses ? { hostAddresses } : {}), ...(readProxyConf ? { readProxyConf } : {}), ...(readPackagedConf ? { readPackagedProxyConf: readPackagedConf } : {}), ...(readPodmanService ? { readPodmanService } : {}), serviceEnvFile: envValues === null ? null : serviceEnvFileOf(envValues, envPath, serviceEnvLoader(platform)) };
457
+ const seams = { setupReadOnly: setupReadOnly === true, ...(subscriptionFactory ? { subscriptionFactory } : {}), ...(modelProposals ? { modelProposals } : {}), secrets: secrets === true, ...(bundleSpawn ? { bundleSpawn } : {}), openshell: openshell === true, ...(openshellRun ? { openshellRun } : {}), cwd, out, spawn, probeValkey, valkeyAuth: valkeyAuthSeam, readHosts, ...(modelCatalog ? { modelCatalog } : {}), ...(piModelLoader ? { piModelLoader } : {}), ...(dollarKeysExist ? { dollarKeysExist } : {}), ...(readAppliedSplit ? { readAppliedSplit } : {}), ...(readCapacity ? { readCapacity } : {}), ...(readDollarRecords ? { readDollarRecords } : {}), ...(readDollarCounters ? { readDollarCounters } : {}), ...(olderStateFindings ? { olderStateFindings } : {}), ...(consoleProbe ? { consoleProbe } : {}), fileExists, nodeVersion, mkdir, chmod, rm, agentDir, platform, home, providerOracle, facts, jobUserIdentity, stat, passwd, readUnit, readEnvFile: readEnvFileShared, observationFs, flowFs, jobsDirFs, jobsDirUid, valkeyOwner: valkeyOwnerSeam, isAlive, pid, runTimeouts, live: live === true, wallClock, ...(readRunRecords ? { readRunRecords } : {}), venueChecks, userName, proxyFilesExist, proxyFileIsDirectory, ...(includeNeeds ? { includeNeeds } : {}), ...(declaredEndpoints ? { declaredEndpoints } : {}), ...(readOverlayFile ? { readOverlayFile } : {}), ...(lstatOverlayFile ? { lstatOverlayFile } : {}), ...(hostAddresses ? { hostAddresses } : {}), ...(readProxyConf ? { readProxyConf } : {}), ...(readPackagedConf ? { readPackagedProxyConf: readPackagedConf } : {}), ...(readPodmanService ? { readPodmanService } : {}), serviceEnvFile: envValues === null ? null : serviceEnvFileOf(envValues, envPath, serviceEnvLoader(platform)) };
394
458
  // Issue #471: every other service key, resolved ONCE for the whole run (the fix pass's re-collect and `--live` judge the
395
459
  // same resolution). THE RULE (PR #474's round cap, after three rounds of trust patches): no program doctor starts is
396
460
  // handed anything from `.env`. Every child gets this shell's own environment, the one it had before #471; a `.env`
@@ -425,6 +489,8 @@ export async function runDoctor(shellVars = process.env, deps = {}) {
425
489
  }
426
490
  }
427
491
 
492
+ // The --live read-backs, kept for the published record (issue #712).
493
+ const liveRendered = [];
428
494
  // ONCE, and after --fix: the probes read the host as the fix pass left it, so a fix that pulled the job image is
429
495
  // read back rather than reported absent. Rendered like every other check and judged by the same rule.
430
496
  if (live === true) {
@@ -433,8 +499,26 @@ export async function runDoctor(shellVars = process.env, deps = {}) {
433
499
  // Each venue's results are rendered BEFORE the next venue announces its containers, so what podman is about to
434
500
  // start never lands between local's announcement and local's verdicts.
435
501
  const liveSeams = { ...seams, liveFs, isAlive, pid, nonce, ...(now ? { now } : {}), ...(delay ? { delay } : {}) };
436
- if (facts.localUsed !== false && render(await liveChecks(env, liveSeams, facts), out)) failed = true;
437
- if (facts.podman && render(await podmanLiveChecks(env, liveSeams, facts), out)) failed = true;
502
+ if (facts.localUsed !== false) {
503
+ const read = await liveChecks(env, liveSeams, facts);
504
+ liveRendered.push(...read);
505
+ if (render(read, out)) failed = true;
506
+ }
507
+ if (facts.podman) {
508
+ const read = await podmanLiveChecks(env, liveSeams, facts);
509
+ liveRendered.push(...read);
510
+ if (render(read, out)) failed = true;
511
+ }
512
+ }
513
+
514
+ // Issue #712: what was judged, published for the console and the panel, after every check is in (the `--fix`
515
+ // re-collect and the `--live` read-backs included) and before the closing line. Best effort BY CONTRACT: whatever
516
+ // happens here leaves `failed`, and so the exit code, as it was, and a fault is one line on stderr, never on stdout,
517
+ // where a script reads doctor's verdict.
518
+ const record = doctorResultsRecord({ checks: [...checks, ...liveRendered], liveRendered, seams, env, at: publishNow(), by: publishBy });
519
+ if (json === true) output(`${JSON.stringify(record)}\n`);
520
+ if (publish === true) {
521
+ await publishResults({ seams, publishDoctor, hostLoadsOf, writeErr, record, env });
438
522
  }
439
523
 
440
524
  // Issue #477: whether anything doctor judged came from the deployment's `.env`, which a hand-started worker never reads.
@@ -449,6 +533,117 @@ export async function runDoctor(shellVars = process.env, deps = {}) {
449
533
  return failed ? 1 : 0;
450
534
  }
451
535
 
536
+ /**
537
+ * Issue #712: publish one run's results (`INT-DOCTOR-RESULTS-KEY`). Never throws and never decides anything: a Valkey
538
+ * this run may not talk to, or one that does not answer, is ONE line on stderr whose wording starts with
539
+ * `DOCTOR_PUBLISH_SKIPPED_PREFIX` (the worker's spawner reads that prefix and nothing else), and no URL, path or value
540
+ * is in it. A record that landed without its `doctor:loads` beside it (issue #800) is one line in other words, for the same
541
+ * reader: it was published, and saying it was not would be false.
542
+ * The secrets the record must not carry are every secret-named value of the resolution (`env`, which holds
543
+ * this shell's whole environment with the service's `.env` values over it), plus the `.env` values the resolution did
544
+ * not take (a provider key resolved later, a value this shell disagrees with), so a value the file holds is as absent
545
+ * as one this shell exports.
546
+ */
547
+ export function doctorResultsRecord({ checks, liveRendered = [], seams, env, at, by = null }) {
548
+ const live = new Set(liveRendered);
549
+ const ids = assignCheckIds(checks, (c) => (live.has(c) ? "live" : (seams.checkSection?.(c) ?? "env")));
550
+ const service = seams.serviceEnv ?? {};
551
+ const fileSide = Object.fromEntries((service.disagreements ?? []).map((d) => [d.key, d.file]));
552
+ const secrets = secretValuesIn(env, service.fromFile, service.extraFromFile, fileSide);
553
+ const worker = by?.worker === true;
554
+ const every = worker && Number.isSafeInteger(by.every) ? by.every : seams.publishTo?.every;
555
+ return buildDoctorRecord({ checks, ids, at, version: PACKAGE_VERSION, openshell: seams.openshellJudged === true, every, secrets, by: { uid: process.geteuid?.() ?? null, worker } });
556
+ }
557
+
558
+ /**
559
+ * Issue #800: what this host's jobs can load, for `doctor:loads:<name>` (`host-loads.mjs`), read when it is published and
560
+ * through the readers a job's worker uses, so a run by `--no-publish` reads nothing more. A part that cannot be read is
561
+ * named in `unread`, which a reader takes as unknown, and an empty list would read as none. Only ABSENT_CODES are absence
562
+ * (`pathIsThere`): an overlay this uid cannot enter is not an overlay with nothing in it. A throw that gets past that is
563
+ * the caller's to say: the doctor record goes out either way.
564
+ */
565
+ export function doctorHostLoads({ seams, env, record, fs = { readFileSync, readdirSync, statSync } }) {
566
+ const overlay = typeof env.PI_GLOBAL_PI_DIR === "string" ? env.PI_GLOBAL_PI_DIR : "";
567
+ const unread = [];
568
+ const read = (part, fn, fallback) => {
569
+ try {
570
+ const value = fn();
571
+ if (value !== null) return value;
572
+ } catch {
573
+ // named below, by part alone: what failed is the doctor line's to say
574
+ }
575
+ unread.push(part);
576
+ return fallback;
577
+ };
578
+ const service = seams.serviceEnv ?? {};
579
+ const fileSide = Object.fromEntries((service.disagreements ?? []).map((d) => [d.key, d.file]));
580
+ const redact = publishRedactor(secretValuesIn(env, service.fromFile, service.extraFromFile, fileSide));
581
+ const extensions = read("extensions", () => readOverlayExtensionRows(overlay, { fs }), []);
582
+ const skills = read("skills", () => readOverlaySkillNames(overlay, { fs }), []);
583
+ const mcp = read("mcp", () => mcpRowsOf(readOverlayMcp(overlay, { readFileSync: seams.readOverlayFile ?? ((p, enc) => readFileSync(p, enc)), ...(seams.lstatOverlayFile ? { lstatSync: seams.lstatOverlayFile } : {}) })?.servers, { redact }), []);
584
+ // A manifest that is there and does not read is not "nothing staged": the job's own reader degrades, this one says so.
585
+ const packages = read("packages", () => {
586
+ if (overlay === "" || !pathIsThere(join(overlay, PACKAGES_SUBDIR, STAGE_MANIFEST), fs)) return [];
587
+ return readStageManifest({ globalPiDir: overlay, readFile: (p) => fs.readFileSync(p, "utf8"), fileExists: () => true })?.packages ?? null;
588
+ }, []);
589
+ // `none` says every tier was checked, and a tier in `unread` was not. Doctor's line stays as it is, since "visible here" is
590
+ // still true of it. What is published is what can be said: not that the flow is nowhere, only that it was not found.
591
+ const blind = unread.includes("skills") || unread.includes("packages");
592
+ const flows = (seams.flowRows ?? []).map((row) => (blind && row.tier === "none" && row.flow !== null ? { ...row, tier: "unknown" } : row));
593
+ return buildHostLoads({ at: record.at, every: record.every, by: record.by, overlayExtensionsAllowed: env.PI_GLOBAL_ALLOW_EXTENSIONS !== "0", extensions, skills, mcp, packages, flows, unread });
594
+ }
595
+
596
+ async function publishResults({ seams, publishDoctor, hostLoadsOf, writeErr, record, env }) {
597
+ const line = (text) => {
598
+ try {
599
+ writeErr(`${text}\n`);
600
+ } catch {
601
+ // A closed stderr cannot change the verdict either.
602
+ }
603
+ };
604
+ const say = (why) => line(`${DOCTOR_PUBLISH_SKIPPED_PREFIX} (${why}); the console and the panel keep the last published results`);
605
+ // Not that prefix, on purpose: the doctor record DID land, and the worker's spawner reads the prefix as "it did not". And not
606
+ // "readers say unknown", which is false: the last list stays for its seven days and reads as current until it is old.
607
+ const sayLoads = (why) => line(`doctor: results published, but not what this host's jobs can load (${why}); the console keeps the last list it had`);
608
+ const target = seams.publishTo;
609
+ if (!target) return say("doctor talked to no Valkey on this run");
610
+ if (target.refused) return say(target.refused);
611
+ let loads = null;
612
+ let loadsThrew = false;
613
+ try {
614
+ loads = hostLoadsOf({ seams, env, record });
615
+ } catch {
616
+ // Each part's own read fails into `unread`, so this is the build of it failing. The doctor record is the older promise
617
+ // and goes out on its own.
618
+ loadsThrew = true;
619
+ }
620
+ try {
621
+ await publishDoctor(target.url, target.name, record, loads);
622
+ } catch (error) {
623
+ return error?.doctorRecordLanded === true ? sayLoads("Valkey did not take them") : say("Valkey did not take them");
624
+ }
625
+ if (loadsThrew) sayLoads("this run could not read them");
626
+ }
627
+
628
+ /**
629
+ * The real write: doctor's own fail-fast client, bounded, always dropped (`withDoctorClient`). A fault on the second write says
630
+ * the first landed (`doctorRecordLanded`), since "nothing was published" would then be false of a record readers can see.
631
+ */
632
+ export async function defaultPublishDoctor(url, name, record, loads = null, { makeClient } = {}) {
633
+ const { publishDoctorRecord } = await import("./doctor-results.mjs");
634
+ const { publishHostLoads } = await import("./host-loads.mjs");
635
+ await withDoctorClient(url, async (client) => {
636
+ await publishDoctorRecord(client, name, record);
637
+ if (loads === null) return;
638
+ // After the doctor record, whose write puts this host under the index both share.
639
+ try {
640
+ await publishHostLoads(client, name, loads);
641
+ } catch (cause) {
642
+ throw Object.assign(new Error("the doctor record landed and the loads did not", { cause }), { doctorRecordLanded: true });
643
+ }
644
+ }, { makeClient });
645
+ }
646
+
452
647
  /**
453
648
  * Issue #477: how to start a worker that runs with what doctor judged. `pi-dispatch worker` started by hand reads this
454
649
  * shell's environment and no `.env` (docs/secrets.md: the worker parses no `.env` file), so where doctor took any value
@@ -601,8 +796,10 @@ export const ENV_FILE_READABLE_KEYS = Object.freeze(["PI_PAUSE_WINDOWS_FILE", "P
601
796
  * the key's path, neither a secret); the inline key is only ever sniffed for its first bytes. */
602
797
  export const GITHUB_SERVICE_KEYS = Object.freeze(["GITHUB_AUTH_SOURCE", "GITHUB_APP_ID", "GITHUB_APP_INSTALLATION_ID", "GITHUB_APP_PRIVATE_KEY_PATH", "GITHUB_APP_PRIVATE_KEY"]);
603
798
  /** Issue #471: the worker's settings doctor judges, which it read from this shell alone while the service read them from
604
- * `.env`. TEMP is TMPDIR's twin in the worker's temp root; PI_CODING_AGENT_DIR is where the worker reads auth.json. */
605
- export const WORKER_SERVICE_KEYS = Object.freeze(["PI_JOB_IMAGE", "PI_JOB_MEMORY", "PI_JOB_CPUS", "PI_CONCURRENCY", ...Object.values(HOST_BUDGET_KEYS), "PI_TRIGGERS_FILE", "PI_LOGS_DIR", "PI_LOG_RETENTION_DAYS", "PI_SETTINGS_FILE", "PI_SESSIONS_DIR", "PI_SESSIONS_TTL_DAYS", "PI_SESSION_MAX_AGE_DAYS", "PI_SESSION_MAX_CONTEXT_PCT", "PI_SESSION_MAX_RESUME_CHAIN", "PI_GLOBAL_PI_DIR", "PI_GLOBAL_ALLOW_EXTENSIONS", "PI_FORWARD_ENV", "PI_AUTH_FROM_PI", "PI_CODING_AGENT_DIR", "PI_BACKEND_FLOOR", "PI_SECRET_PROFILES", "PI_SECRET_RESOLVER_ROOTS", "PI_WAIT_PROFILES", "PI_WAIT_AFTER_MAX_MS", "PI_SANDBOX_RETENTION_HOURS", "PI_ALLOWED_MODELS", "PI_DISPATCH_RUN_ROOTS", "GITHUB_PAT_VAR", "TEMP", ...Object.values(DOLLAR_ENV_NAMES)]);
799
+ * `.env`. TEMP is TMPDIR's twin in the worker's temp root; PI_CODING_AGENT_DIR is where the worker reads auth.json.
800
+ * Issue #761: PI_CONSOLE_AUDIT_RETENTION_DAYS is here and not in `CONSOLE_ENV_KEYS` although it is named for the
801
+ * console: the worker reads it (it runs the audit reaper), and a console key set alone makes doctor judge a console. */
802
+ export const WORKER_SERVICE_KEYS = Object.freeze(["PI_JOB_IMAGE", "PI_JOB_MEMORY", "PI_JOB_CPUS", "PI_CONCURRENCY", ...Object.values(HOST_BUDGET_KEYS), "PI_TRIGGERS_FILE", "PI_LOGS_DIR", "PI_LOG_RETENTION_DAYS", "PI_CONSOLE_AUDIT_RETENTION_DAYS", "PI_RUN_MIRROR_MAX_RUNS", "PI_SETTINGS_FILE", "PI_SESSIONS_DIR", "PI_CHECKPOINTS_DIR", "PI_SESSIONS_TTL_DAYS", "PI_SESSION_MAX_AGE_DAYS", "PI_SESSION_MAX_CONTEXT_PCT", "PI_SESSION_MAX_RESUME_CHAIN", "PI_GLOBAL_PI_DIR", "PI_GLOBAL_ALLOW_EXTENSIONS", "PI_FORWARD_ENV", "PI_AUTH_FROM_PI", "PI_AUTH_CONNECTIONS_FILE", "PI_AUTH_STORE_DIR", "PI_CODING_AGENT_DIR", "PI_BACKEND_FLOOR", "PI_OPENSHELL_ENGINE", "PI_OPENSHELL_GATEWAY", "PI_SECRET_PROFILES", "PI_SECRET_BUNDLES", "PI_SECRET_RESOLVER_ROOTS", "PI_SECRET_RESOLVE_TIMEOUT_MS", "PI_WAIT_PROFILES", "PI_WAIT_AFTER_MAX_MS", "PI_SANDBOX_RETENTION_HOURS", "PI_DOCTOR_INTERVAL_HOURS", "PI_ALLOWED_MODELS", "PI_DISPATCH_RUN_ROOTS", "GITHUB_PAT_VAR", "TEMP", ...Object.values(DOLLAR_ENV_NAMES)]);
606
803
  /** Issue #471: the receiver's keys doctor judges its boot by (the receiver's unit reads the same `.env`). */
607
804
  export const RECEIVER_SERVICE_KEYS = Object.freeze(["WEBHOOK_SECRET", "RECEIVER_PORT", "GITLAB_TOKEN", "GITLAB_URL", "GITLAB_WEBHOOK_MODE", "GITLAB_WEBHOOK_SECRET", "FORGEJO_URL", "FORGEJO_TOKEN", "FORGEJO_PERMISSION_TOKEN", "FORGEJO_WEBHOOK_SECRET", "AZURE_ORG_URL", "AZURE_TOKEN", "AZURE_WEBHOOK_MODE", "AZURE_WEBHOOK_SECRET", "AZURE_WEBHOOK_HEADER"]);
608
805
  /**
@@ -624,9 +821,17 @@ export const CLI_SERVICE_KEYS = Object.freeze({
624
821
  podman: Object.freeze(["CONTAINERS_CONF", "CONTAINERS_CONF_OVERRIDE", "CONTAINERS_STORAGE_CONF", "CONTAINERS_REGISTRIES_CONF", "CONTAINER_HOST", "CONTAINER_CONNECTION", "XDG_CONFIG_HOME", "XDG_RUNTIME_DIR", "HOME"]),
625
822
  docker: Object.freeze(["DOCKER_HOST", "DOCKER_CONTEXT", "DOCKER_CONFIG", "HOME"]),
626
823
  gh: Object.freeze(["GH_TOKEN", "GITHUB_TOKEN", "GH_CONFIG_DIR", "GH_HOST", "XDG_CONFIG_HOME", "HOME"]),
824
+ // Issue #707: the openshell CLI keeps its gateway registrations (and so which gateway is the active one) under this
825
+ // account's config dir, XDG_CONFIG_HOME or else HOME/.config (measured on 0.1.4: `gateway add` writes there), so a
826
+ // `.env` that moves either points the SERVICE's CLI at another registration than doctor's. PATH is not listed: every
827
+ // shell sets one, which would make the line fire on every run, and where the CLI is found is `service install`'s to
828
+ // put in the unit (the plist's PATH carries its directory on macOS).
829
+ openshell: Object.freeze(["XDG_CONFIG_HOME", "HOME"]),
627
830
  });
628
831
  const CLI_KEY_NAMES = [...new Set(Object.values(CLI_SERVICE_KEYS).flat())];
629
- export const SERVICE_ENV_KEYS = Object.freeze([...STACK_KEYS, "VALKEY_URL", VALKEY_SHARED_KEY, VALKEY_PASSWORD_KEY, VALKEY_PORT_KEY, "PI_PROVIDER", "PI_MODEL", ...GITHUB_SERVICE_KEYS, "PI_JOBS_DIR", "PI_SANDBOX_DIR", "TMPDIR", "PI_WORKER_NAME", ...WORKER_SERVICE_KEYS, ...RECEIVER_SERVICE_KEYS, ...CLI_KEY_NAMES]);
832
+ // A Set, since issue #707 made two of the worker's keys (PI_OPENSHELL_ENGINE, PI_OPENSHELL_GATEWAY) venue keys too: each
833
+ // key once, in the order it is first named.
834
+ export const SERVICE_ENV_KEYS = Object.freeze([...new Set([...STACK_KEYS, "VALKEY_URL", VALKEY_SHARED_KEY, VALKEY_PASSWORD_KEY, VALKEY_PORT_KEY, "PI_PROVIDER", "PI_MODEL", ...GITHUB_SERVICE_KEYS, "PI_JOBS_DIR", "PI_SANDBOX_DIR", "TMPDIR", "PI_WORKER_NAME", ...WORKER_SERVICE_KEYS, ...RECEIVER_SERVICE_KEYS, ...CLI_KEY_NAMES])]);
630
835
 
631
836
  /** Issue #471 (gate round 1): what a service manager gives every service itself, so a `.env` need not carry it. */
632
837
  const AMBIENT_SERVICE_KEYS = Object.freeze(["TMPDIR", "TEMP", "XDG_RUNTIME_DIR", "HOME"]);
@@ -651,6 +856,33 @@ function installedWorkerUnit(seams, cwd) {
651
856
  return null;
652
857
  }
653
858
 
859
+ /**
860
+ * Issue #707: whether the worker unit installed for this folder pulls in the OpenShell gateway's own user unit
861
+ * (`Wants=openshell-gateway.service`, which the 0.1.4 deb ships), as `service install` writes it for an openshell venue,
862
+ * and is NOT ordered after it: that unit is `After=default.target`, so an `After=` from a worker that is WantedBy
863
+ * default.target is an ordering cycle, and systemd deletes the worker's start job to break it (review round 1 of #715,
864
+ * measured). Read only on Linux, from the unit file itself (`installedWorkerUnit`); no unit for this folder says nothing,
865
+ * since the worker may run by hand. A ⚠, not a ✗: a missing `Wants=` costs a gateway the worker's boot only logs as
866
+ * down, and `service install --force` rewrites the unit.
867
+ */
868
+ export function openshellUnitOrderChecks(seams, cwd) {
869
+ if (seams.platform !== "linux" || typeof seams.fileExists !== "function") return [];
870
+ const unit = installedWorkerUnit(seams, cwd);
871
+ if (!unit) return [];
872
+ if (unit.scope === "system") {
873
+ return [{ ok: true, warn: true, label: `openshell: the worker's unit (${unit.path}) is a system unit, which cannot pull in the gateway's user unit (openshell-gateway.service)`, fix: "install the worker in user scope (`pi-dispatch service install`, without --system), in the account whose user manager runs the gateway and whose home holds the CLI's gateway registration" }];
874
+ }
875
+ let text;
876
+ try {
877
+ text = String((seams.readUnit ?? ((path) => readFileSync(path, "utf8")))(unit.path));
878
+ } catch {
879
+ return [{ ok: true, warn: true, label: `openshell: whether the worker's unit (${unit.path}) pulls in the gateway could not be read`, fix: "make the unit file readable by this account, then re-run doctor" }];
880
+ }
881
+ const names = (key) => new RegExp(`^${key}=(?:.*\\s)?openshell-gateway\\.service(?:\\s|$)`, "m").test(text);
882
+ if (names("After")) return [{ ok: true, warn: true, label: `openshell: the worker's unit (${unit.path}) is After=openshell-gateway.service, an ordering cycle (the gateway's unit is After=default.target), which systemd breaks by deleting the worker's start job at boot`, fix: "`pi-dispatch service install --force` in the deployment folder rewrites the unit with Wants=openshell-gateway.service and no After= on it" }];
883
+ return [names("Wants") ? { ok: true, label: "openshell: the worker's unit pulls in the gateway's (Wants=openshell-gateway.service)" } : { ok: true, warn: true, label: `openshell: the worker's unit (${unit.path}) does not pull in the gateway's (openshell-gateway.service), so at boot the gateway starts only if something else starts it`, fix: "`pi-dispatch service install --force` in the deployment folder rewrites the unit with Wants=openshell-gateway.service" }];
884
+ }
885
+
654
886
  /** The CLI variables that name a path, whose value a ⚠ may show; the rest (endpoints, names, tokens) it never shows. */
655
887
  const CLI_PATH_KEYS = Object.freeze(["CONTAINERS_CONF", "CONTAINERS_CONF_OVERRIDE", "CONTAINERS_STORAGE_CONF", "CONTAINERS_REGISTRIES_CONF", "XDG_CONFIG_HOME", "XDG_RUNTIME_DIR", "DOCKER_CONFIG", "GH_CONFIG_DIR", "HOME"]);
656
888
  /** The ones the worker's containers.conf chain check reads, which doctor runs in-process on the resolved values. */
@@ -662,11 +894,13 @@ const PODMAN_CHAIN_KEYS = Object.freeze(["CONTAINERS_CONF", "CONTAINERS_CONF_OVE
662
894
  * context name, or a token. Says that doctor's probes through that CLI describe this shell's view, and, for the keys
663
895
  * the containers.conf chain check reads, that the check itself judged the file's value, in-process, as the worker does.
664
896
  */
665
- export function cliNotHandedLines(service, envPath) {
897
+ export function cliNotHandedLines(service, envPath, { openshellUsed = false } = {}) {
666
898
  const listed = (items) => (items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`);
667
899
  // Issue #481: an empty value is left out only where the tool's own source reads it as unset (`fileConfigures`).
668
900
  return CLI_KEY_NAMES.filter((k) => Object.hasOwn(service.fromFile, k) && fileConfigures(k, service.fromFile[k])).map((k) => {
669
- const names = Object.entries(CLI_SERVICE_KEYS).filter(([, ks]) => ks.includes(k)).map(([cli]) => cli);
901
+ // The openshell CLI is named only where an openshell venue is blessed (review round 1 of #715): elsewhere no probe
902
+ // of it runs, and the service never starts it.
903
+ const names = Object.entries(CLI_SERVICE_KEYS).filter(([cli, ks]) => ks.includes(k) && (cli !== "openshell" || openshellUsed)).map(([cli]) => cli);
670
904
  const clis = listed(names);
671
905
  // Grammar by count (round-cap re-review, D2): "podman, docker and gh use it", "podman uses it".
672
906
  const verb = names.length > 1 ? "use" : "uses";
@@ -691,6 +925,7 @@ export const STEERING_SERVICE_KEYS = Object.freeze({
691
925
  PI_BACKENDS: "which runtime doctor spawns: judged by the worker's own list parser, a shell/.env disagreement a ✗ (deploymentVenueEnv)",
692
926
  PI_EGRESS: "whether the egress canary runs: the worker's own reading, a disagreement a ✗ (deploymentVenueEnv)",
693
927
  PI_EGRESS_PROXY: "which proxy container doctor inspects: the worker's own name resolution, a disagreement a ✗ (deploymentVenueEnv)",
928
+ PI_OPENSHELL_ENGINE: "which engine the openshell lines spawn (its version, the job image in its store): docker or podman only, anything else named and nothing spawned (doctor-openshell.mjs), a disagreement a ✗ (deploymentVenueEnv, issue #707)",
694
929
  VALKEY_URL: "which Valkey doctor connects to: the owner rule the worker applies at boot, and a line doctor cannot read makes it contact none",
695
930
  PI_JOB_IMAGE: "the image doctor inspects and runs (the canary, the gh probe, --live): the worker's `||` default and the one image rule its boot applies (image-ref.mjs: blank, padded, a leading dash, a control character), a refused value named and not used",
696
931
  GITHUB_AUTH_SOURCE: "whether doctor runs gh on this host: the worker's own three values",
@@ -708,6 +943,13 @@ export const STEERING_SERVICE_KEYS = Object.freeze({
708
943
  GH_CONFIG_DIR: "which gh login the SERVICE's gh reads: never handed to doctor's gh, named in a ⚠",
709
944
  });
710
945
 
946
+ /**
947
+ * The operator console's environment (issue #640): the keys `pi-dispatch-console` reads, resolved by the console's own
948
+ * rule (this shell's value where it sets one, else the deployment `.env`'s, as `panelEnv` does for the panel). Not
949
+ * service keys: no service reads them, so they are kept out of SERVICE_ENV_KEYS and its "set in this shell only" line.
950
+ */
951
+ export const CONSOLE_ENV_KEYS = Object.freeze(["PI_CONSOLE_LISTEN", "PI_CONSOLE_TOKENS_FILE", "PI_CONSOLE_ALLOWED_HOSTS", "PI_CONSOLE_READ_ONLY", "PI_CONSOLE_BIND_PUBLIC", "PI_CONSOLE_IDLE_MINUTES", "PI_CONSOLE_MAX_HOURS", "PI_CONSOLE_MAX_STREAMS"]);
952
+
711
953
  /**
712
954
  * Issue #471: the variables doctor reads from THIS shell on purpose, each with why, so the bolt test can tell a read
713
955
  * that went back to the shell from one that was always meant to be there. A name read as `env.NAME` in doctor.mjs is in
@@ -723,6 +965,7 @@ export const DOCTOR_SHELL_KEYS = Object.freeze({
723
965
  PI_MODEL_ENDPOINTS_FILE: "read from .env by its own two-subject rule (ENV_FILE_READABLE_KEYS), #503",
724
966
  PI_ENVELOPE_FILE: "read from .env by its own two-subject rule (ENV_FILE_READABLE_KEYS), #504",
725
967
  [VALKEY_SHARED_KEY]: "read from .env ONLY (#464); a value in this shell is named as ignored",
968
+ ...Object.fromEntries(CONSOLE_ENV_KEYS.map((k) => [k, "the operator console's, not a service's: resolved by the console's own rule (this shell, else the deployment .env) apart from the service record, #640"])),
726
969
  });
727
970
 
728
971
  /** Issue #471: the service keys whose values a disagreement line never prints (set or unset only); URLs print as
@@ -1021,7 +1264,7 @@ export function envFileKeys(path, keys, { fileExists, readEnvFile, statFile = st
1021
1264
  * loaders throw a `configError` on a path that does not exist and on content that does not parse, which is
1022
1265
  * exactly the boot this check is predicting.
1023
1266
  */
1024
- const BOOT_FILES = Object.freeze([
1267
+ export const BOOT_FILES = Object.freeze([
1025
1268
  Object.freeze({
1026
1269
  key: "PI_PAUSE_WINDOWS_FILE",
1027
1270
  noun: "scoped pauses",
@@ -1120,6 +1363,15 @@ const BOOT_FILES = Object.freeze([
1120
1363
  }),
1121
1364
  ]);
1122
1365
 
1366
+ /**
1367
+ * A boot file's published check id (issue #712, `NAMED_CHECK_IDS`): `<scaffold name>.file` for the SERVICE's verdict on
1368
+ * the file it reads, `<scaffold name>.file-shell` for this shell's. Derived from the scaffold name so a sixth boot file
1369
+ * names itself, and the test holding `NAMED_CHECK_IDS` to the source fails until it is listed.
1370
+ */
1371
+ export function bootFileId(spec, subject = "service") {
1372
+ return `${spec.scaffold.replace(/\.json$/, "")}.file${subject === "shell" ? "-shell" : ""}`;
1373
+ }
1374
+
1123
1375
  /** A key's value when it is a non-empty string, else null: the boot reads an unset key as off. */
1124
1376
  function nonEmpty(value) {
1125
1377
  return typeof value === "string" && value.trim() !== "" ? value : null;
@@ -1226,10 +1478,161 @@ function loadVerdict(spec, rawPath, cwd, io, platform = process.platform) {
1226
1478
  spec.load(path, io.loaderIo, io.env);
1227
1479
  return { ok: true };
1228
1480
  } catch (err) {
1229
- return { ok: false, reason: envValueShown(err?.message ?? String(err)) };
1481
+ // Issue #761: the loader's own flag says a newer pi-dispatch wrote the file (never the message's wording), so the
1482
+ // fix can say to upgrade rather than to edit what that release wrote.
1483
+ return { ok: false, reason: envValueShown(err?.message ?? String(err)), ...(err?.newer === true ? { newer: true } : {}) };
1230
1484
  }
1231
1485
  }
1232
1486
 
1487
+ /**
1488
+ * The fix for a file a newer pi-dispatch wrote (issue #761), whichever store: upgrade `who` and every writer of the file,
1489
+ * never edit or delete it, which would lose what that release wrote. The one exception is a `version` an operator
1490
+ * wrote by hand (earlier releases ignored the key): no release wrote that file, so removing the key is the fix. One
1491
+ * sentence for the settings overlay, the pause windows file and the triggers file, so the three cannot drift apart.
1492
+ */
1493
+ export function newerFileFix(who) {
1494
+ return `upgrade ${who}, and every panel and console that writes this file, to the release that wrote it; do not edit or delete the file, which would lose what that release wrote, unless you added \`version\` to it yourself: then remove that key`;
1495
+ }
1496
+
1497
+ /** The oldest git the checkpoint store accepts (issue #645), as `[major, minor]`. */
1498
+ export const CHECKPOINT_GIT_MIN = Object.freeze([2, 32]);
1499
+
1500
+ /** `[major, minor]` out of `git --version`'s answer (`git version 2.43.0`, `git version 2.39.3 (Apple Git-146)`), or null. */
1501
+ export function parseGitVersion(text) {
1502
+ const m = /\bgit version (\d{1,4})\.(\d{1,4})/.exec(String(text ?? ""));
1503
+ return m ? [Number(m[1]), Number(m[2])] : null;
1504
+ }
1505
+
1506
+ /**
1507
+ * The checkpoint store's group (issue #645): where it is, whether it is a private directory of this account's, whether it
1508
+ * sits under the OS temp dir, whether git is new enough, and whether each venue that runs jobs here can freeze one while
1509
+ * its workspace is read. Pure over its reads, so every arm is driven without a host.
1510
+ *
1511
+ * WARN AT MOST, with ONE exception, and that is deliberate rather than lenient: the store is written only by jobs whose
1512
+ * trigger arms `run.recover` (the worker's run checkpointer, issue #645), so a red doctor here would fail every deployment
1513
+ * that configured the store and armed nothing, and a problem with it costs a durable run its recovery (the run falls back
1514
+ * to today's retry), never a job its run. The exception is a store that
1515
+ * COLLIDES with the session store (`checkpointStoreCollision`), which is ✗ because the worker itself refuses to load
1516
+ * that configuration: doctor's verdict follows the worker's.
1517
+ *
1518
+ * 0700 AND THIS ACCOUNT'S, for the transcript store's reason: a checkpoint is a job's whole workspace, so as PII-bearing
1519
+ * as a transcript, and an owner other than the worker could swap what a restore reads. A symbolic link is refused for the
1520
+ * same reason (the store's contents would live wherever it points). Under the OS temp dir it is swept by the OS, which
1521
+ * turns a durable run's resume into a silent cold start.
1522
+ *
1523
+ * GIT 2.32 because that is the first release that reads `GIT_CONFIG_GLOBAL`, which the store's git environment
1524
+ * (`git-hardening.mjs`, `storeGitEnv`) points at /dev/null so no global config (a hook path, a filter, an fsmonitor)
1525
+ * runs inside the store. An older git ignores the variable; the empty HOME beside it still hides `~/.gitconfig`, so the
1526
+ * line warns rather than refuses, but the store then rests on one guard where it was built with two.
1527
+ *
1528
+ * PAUSABLE IS A FACT LINE (`ok: true`) either way, because nothing the operator does short of changing hosts clears it.
1529
+ * What it costs is said in the line: a venue that cannot freeze a running job gets EXIT checkpoints only, taken once the
1530
+ * container is gone, so a job there is not recovered from a worker that crashed mid-run. A checkpoint is never read
1531
+ * from a workspace the job is still writing.
1532
+ */
1533
+ export function checkpointStoreChecks({ dir, explicit = false, sessionsDir = null, fs = { lstatSync, statSync, accessSync }, uid, underTemp = () => false, gitVersion = null, venues = [DEFAULT_BACKEND], podmanRead = null }) {
1534
+ const checks = [];
1535
+ const shown = envValueShown(dir);
1536
+ const where = explicit ? "PI_CHECKPOINTS_DIR" : "the default inside PI_SESSIONS_DIR";
1537
+ const collision = checkpointStoreCollision(sessionsDir, dir);
1538
+ if (collision) {
1539
+ checks.push({
1540
+ ok: false,
1541
+ label: `checkpoint store ${shown} and the session store ${envValueShown(resolve(sessionsDir))} collide: ${collision}, so the session reaper and the checkpoint sweep would delete each other's folders, and the worker refuses to start with this configuration`,
1542
+ fix: "unset PI_CHECKPOINTS_DIR (the default is <PI_SESSIONS_DIR>/.checkpoints) or point it at a directory outside PI_SESSIONS_DIR",
1543
+ });
1544
+ }
1545
+ let st = null;
1546
+ let missing = false;
1547
+ try {
1548
+ st = fs.lstatSync(dir);
1549
+ } catch (err) {
1550
+ if (err?.code === "ENOENT") missing = true;
1551
+ else checks.push({ ok: false, warn: true, label: `checkpoint store ${shown} (${where}) could not be read (${err?.code ?? "error"})`, fix: "make it a directory this account can read, or point PI_CHECKPOINTS_DIR at one" });
1552
+ }
1553
+ if (missing) {
1554
+ // The nearest ancestor that exists decides whether the checkpointer can create it, as `mkdir -p` would. One that
1555
+ // exists and is NOT a directory (a file where a parent should be) is its own answer: `mkdir -p` fails on it.
1556
+ let parent = dirname(dir);
1557
+ let ancestor = null;
1558
+ let blockedBy = null;
1559
+ for (let i = 0; i < 64 && ancestor === null && blockedBy === null; i++) {
1560
+ let pst = null;
1561
+ try {
1562
+ pst = fs.statSync(parent);
1563
+ } catch {
1564
+ pst = null;
1565
+ }
1566
+ if (pst?.isDirectory()) ancestor = parent;
1567
+ else if (pst) blockedBy = parent;
1568
+ else {
1569
+ const up = dirname(parent);
1570
+ if (up === parent) break;
1571
+ parent = up;
1572
+ }
1573
+ }
1574
+ let writable = false;
1575
+ if (ancestor) {
1576
+ try {
1577
+ fs.accessSync(ancestor, fsConstants.W_OK | fsConstants.X_OK);
1578
+ writable = true;
1579
+ } catch {
1580
+ writable = false;
1581
+ }
1582
+ }
1583
+ checks.push(
1584
+ writable
1585
+ ? { ok: true, label: `checkpoint store ${shown} (${where}) does not exist yet: it is created with mode 0700 inside ${envValueShown(ancestor)} when a durable run first writes one` }
1586
+ : { ok: false, warn: true, label: `checkpoint store ${shown} (${where}) does not exist and cannot be created: ${ancestor ? `${envValueShown(ancestor)} is not writable by this account` : blockedBy ? `${envValueShown(blockedBy)} above it is not a directory` : "no directory above it exists"}`, fix: `create it as the worker's account: mkdir -p ${shown} && chmod 700 ${shown}` },
1587
+ );
1588
+ } else if (st) {
1589
+ if (st.isSymbolicLink()) {
1590
+ checks.push({ ok: false, warn: true, label: `checkpoint store ${shown} (${where}) is a symbolic link, so what a restore reads lives wherever it points`, fix: `replace it with a real directory: rm ${shown} && mkdir -p ${shown} && chmod 700 ${shown}` });
1591
+ } else if (!st.isDirectory()) {
1592
+ checks.push({ ok: false, warn: true, label: `checkpoint store ${shown} (${where}) is not a directory`, fix: `move it aside and create a directory there: mkdir -p ${shown} && chmod 700 ${shown}` });
1593
+ } else {
1594
+ // No uid (Windows): ownership and the mode bits mean nothing there, so neither is judged.
1595
+ const problems = [];
1596
+ if (Number.isInteger(uid) && st.uid !== uid) problems.push(`owned by uid ${st.uid}, not this account (uid ${uid})`);
1597
+ if (Number.isInteger(uid) && (st.mode & 0o777) !== 0o700) problems.push(`mode ${(st.mode & 0o777).toString(8).padStart(4, "0")}, not 0700`);
1598
+ checks.push(
1599
+ problems.length === 0
1600
+ ? { ok: true, label: `checkpoint store ${shown} (${where}) is a private directory of this account's` }
1601
+ : { ok: false, warn: true, label: `checkpoint store ${shown} (${where}) is ${problems.join(" and ")}: a checkpoint holds a job's whole workspace, as private as a transcript`, fix: `as the worker's account: chown "$(id -u)" ${shown} && chmod 700 ${shown}` },
1602
+ );
1603
+ }
1604
+ }
1605
+ if (underTemp(dir)) {
1606
+ checks.push({ ok: false, warn: true, label: `checkpoint store ${shown} is under the OS temp dir, which the OS sweeps: a durable run would resume from nothing after a reboot or a cleaner pass`, fix: "point PI_CHECKPOINTS_DIR (or PI_SESSIONS_DIR) at a durable private directory" });
1607
+ }
1608
+ const version = parseGitVersion(gitVersion);
1609
+ const [minMajor, minMinor] = CHECKPOINT_GIT_MIN;
1610
+ if (version === null) {
1611
+ checks.push({ ok: false, warn: true, label: "checkpoint store: `git --version` did not answer, so whether git is 2.32 or newer is not known", fix: "install git 2.32 or newer on the worker's PATH" });
1612
+ } else if (version[0] < minMajor || (version[0] === minMajor && version[1] < minMinor)) {
1613
+ checks.push({ ok: false, warn: true, label: `checkpoint store: git ${version.join(".")} is older than 2.32, which ignores GIT_CONFIG_GLOBAL, so the store's git keeps one of its two guards against this host's own config`, fix: "install git 2.32 or newer on the worker's PATH" });
1614
+ } else {
1615
+ checks.push({ ok: true, label: `checkpoint store: git ${version.join(".")} (2.32 or newer)` });
1616
+ }
1617
+ for (const venue of venues) {
1618
+ const word = BACKENDS[venue]?.declares?.pausable ?? ABSENT;
1619
+ let label;
1620
+ const exitOnly = "so its jobs get exit checkpoints only, taken once the container is gone, and are not recovered from a worker crash mid-run";
1621
+ if (word === ABSENT) label = `checkpoint store: ${venue} declares no freeze, ${exitOnly}`;
1622
+ else if (venue === PODMAN_BACKEND) {
1623
+ const can = podmanPausable(podmanRead);
1624
+ label =
1625
+ can.pausable === true
1626
+ ? `checkpoint store: ${venue} can freeze a job while its workspace is read (podman pause, cgroup v2)`
1627
+ : can.pausable === false
1628
+ ? `checkpoint store: ${venue} cannot freeze a job here (rootless Podman on cgroup v1), ${exitOnly}`
1629
+ : `checkpoint store: whether ${venue} can freeze a job is not known (podman info did not answer: ${can.reason}); on cgroup v1 it cannot, ${exitOnly}`;
1630
+ } else label = `checkpoint store: ${venue} can freeze a job while its workspace is read (docker pause, the cgroup freezer)`;
1631
+ checks.push({ ok: true, label });
1632
+ }
1633
+ return checks;
1634
+ }
1635
+
1233
1636
  /**
1234
1637
  * Run every probe and return the check list without rendering -- runDoctor renders it, and under --fix
1235
1638
  * collects it a second time for the converge re-check. Exported for the never-tier doctrine pin in the
@@ -1277,6 +1680,22 @@ export async function collectChecks(shellVars, seams) {
1277
1680
  // ioredis's SELECT. It is a ✗ of its own, the worker's refusal (exit 2), and nothing below contacts a Valkey.
1278
1681
  const valkeyDbProblem = unreadValkey ? null : valkeyUrlProblem(valkeyUrl);
1279
1682
  const provider = env.PI_PROVIDER ?? "anthropic";
1683
+ // Issue #673: is the service's PI_MODEL or PI_PROVIDER outside the one id shape (`modelFrom`, `providerFrom`)? Judged
1684
+ // once, here, because the answer decides more than its own row (review round 1): the older rows that judge the same
1685
+ // value (the provider-key row, the trigger-secret clash row and the deployment default's catalog row) are skipped for
1686
+ // a malformed one. They print the value, so a control byte would reach the terminal, and their fix ("set PI_PROVIDER to
1687
+ // a provider pi has") is not the one the boot refusal asks for; one root cause prints one row. A well-shaped value is
1688
+ // judged by them unchanged. Null when the setting is unset or well-shaped, else the worker's own refusal message.
1689
+ const envShapeProblem = {};
1690
+ for (const [name, judge] of [["PI_MODEL", modelFrom], ["PI_PROVIDER", providerFrom]]) {
1691
+ envShapeProblem[name] = null;
1692
+ if (typeof env[name] !== "string") continue;
1693
+ try {
1694
+ judge(env);
1695
+ } catch (err) {
1696
+ envShapeProblem[name] = err?.message ?? "invalid";
1697
+ }
1698
+ }
1280
1699
  // Issue #464 (gate round 1): this host's declared worker name, resolved with every other service key. Every reader
1281
1700
  // below (the fleet line and its routing warning, the per-host backend wording, which cron triggers are scheduled
1282
1701
  // here) uses this value: read from the shell alone, a deployment whose `.env` names its worker was told host routing
@@ -1291,8 +1710,25 @@ export async function collectChecks(shellVars, seams) {
1291
1710
  let patFromFile = null;
1292
1711
 
1293
1712
  const checks = [];
1713
+ // Issue #712: the section each check was added in, for its published id (`assignCheckIds`, doctor-results.mjs). Each
1714
+ // `section(name)` call hands every check added since the last one to the section that was current, then opens `name`.
1715
+ // A WeakMap rather than a field on the check: a check may be a shared or frozen object, and a write to a frozen one
1716
+ // throws in this strict module. Read back through `seams.checkSection`, set again on every collection (`--fix`
1717
+ // re-collects).
1718
+ const sectionOf = new WeakMap();
1719
+ let currentSection = "node";
1720
+ const tagSection = (list, name) => {
1721
+ for (const c of list) if (c !== null && typeof c === "object" && !sectionOf.has(c)) sectionOf.set(c, name);
1722
+ };
1723
+ const section = (name) => {
1724
+ tagSection(checks, currentSection);
1725
+ currentSection = name;
1726
+ };
1727
+ seams.checkSection = (c) => sectionOf.get(c) ?? null;
1728
+ section("node");
1294
1729
  checks.push(nodeCheck(nodeVersion));
1295
1730
 
1731
+ section("env");
1296
1732
  checks.push({
1297
1733
  ok: fileExists(join(cwd, ".env")),
1298
1734
  warn: true, // advisory: env may be supplied by a service manager instead of a file
@@ -1391,10 +1827,11 @@ export async function collectChecks(shellVars, seams) {
1391
1827
  // disagreement is said once at the end rather than lost.
1392
1828
  const envPathShown = serviceEnvFile?.path ?? join(cwd, ".env");
1393
1829
  // PR #474's round cap: each CLI variable the file sets, which no program doctor starts is handed.
1394
- checks.push(...cliNotHandedLines(service, envPathShown));
1830
+ checks.push(...cliNotHandedLines(service, envPathShown, { openshellUsed: venuesOf(env).openshellUsed }));
1395
1831
  const saidAtTop = { disagreements: service.disagreements.length, unread: service.unread.length };
1396
1832
  // A CLI variable is not listed as read: no program doctor starts used it, and its own ⚠ says so.
1397
1833
  checks.push(...serviceEnvLines(service, envPathShown, { said: ["VALKEY_URL", "PI_PROVIDER", ...GITHUB_SERVICE_KEYS, "PI_JOBS_DIR", "PI_SANDBOX_DIR", "TMPDIR", ...CLI_KEY_NAMES] }));
1834
+ section("image");
1398
1835
  if (jobImageRefused) {
1399
1836
  checks.push({
1400
1837
  ok: false,
@@ -1406,6 +1843,12 @@ export async function collectChecks(shellVars, seams) {
1406
1843
  // Issue #354: which venues run jobs here. An unparseable PI_BACKENDS reads as the unset default, so every docker line
1407
1844
  // below is exactly what it always was, and the backend section is what fails on it (the worker refuses to boot).
1408
1845
  const { localUsed, podmanUsed, podmanDefault } = venuesOf(env);
1846
+ // Issue #707: where an openshell-only deployment's Valkey runs (`openshellSetupOf`, the rule `up` and `service install`
1847
+ // follow): on the gateway's engine, docker by default. The Valkey lines' fixes name THAT engine's way to start it, as
1848
+ // they name docker's where `local` is blessed and the Quadlet unit's where `podman` is.
1849
+ const openshellSetup = openshellSetupOf(venuesOf(env), env);
1850
+ const valkeyVenues = { localUsed: localUsed || openshellSetup.valkeyEngine === "docker", podmanUsed: podmanUsed || openshellSetup.valkeyEngine === "podman" };
1851
+ section("docker");
1409
1852
  // THE FIRST DOCKER CALL OF THE RUN, which is why it was the one that hung (issue #397): a daemon that
1410
1853
  // accepts the connection and never answers held doctor here, before it had printed anything. Bounded
1411
1854
  // now, and the three outcomes are three different sentences, because telling someone whose daemon is
@@ -1447,9 +1890,17 @@ export async function collectChecks(shellVars, seams) {
1447
1890
  // image checks just below, and `optingOut`/`requiring` colour the staged-packages lines further down.
1448
1891
  // `optingOut` counts the only value that withholds the staged set; `requiring` counts an explicit
1449
1892
  // run.packages: true, which arms nothing any more but is still an operator statement of intent.
1450
- const { requiring, waiting, listing, waitProfiles, waitAfters, optingOut, resuming, replicating, instructing, commands, secreting, onceArmed, onceSpent, secretProfiles, localSecretFolders, secretNames, folders, images, imageRoutes, namedBackends, skillsDirs, forges, repositories, flows, costCaps, modelRuns, parseError, path: triggersFilePath } = readTriggerFacts(env, fileExists, cwd, declaredWorkerName);
1893
+ // Issue #761: the version tables, and the versions this build reads, that the store-version needs are judged by,
1894
+ // per store: `{ settings: { supported, table, valueTable }, pauseWindows: { supported, table }, triggers: { supported,
1895
+ // runTable, blockTable }, jobData: { table } }`, each part the store module's own when absent. This seam is how a test
1896
+ // drives a need above 1 through the real collection, for a store whose table has no row of its own and at a version no row holds yet.
1897
+ const versionTables = seams.versionTables ?? {};
1898
+ const { watchSources: triggerWatchSources, watchRules: triggerWatchRules, modelRoles: triggerModelRoles, secretBundles: triggerBundles, requiring, waiting, listing, waitProfiles, waitAfters, optingOut, resuming, recovering, replicating, instructing, commands, secreting, onceArmed, onceSpent, secretProfiles, localSecretFolders, secretNames, folders, images, imageRoutes, namedBackends, skillsDirs, forges, repositories, flows, excludedNames, costCaps, modelRuns, triggersVersionNeed, jobDataVersionNeed, parseError, parseNewer: triggersFileIsNewer, path: triggersFilePath } = readTriggerFacts(env, fileExists, cwd, declaredWorkerName, versionTables);
1899
+ const modelRoleProjects = readProjectFacts(env, fileExists).projects;
1451
1900
  const scopedLimitFacts = readScopedLimitFacts(env, fileExists);
1452
- const pauseWindowFacts = readPauseWindowFacts(env, fileExists);
1901
+ const pauseWindowFacts = readPauseWindowFacts(env, fileExists, versionTables.pauseWindows);
1902
+ section("triggers");
1903
+ checks.push(...watchDoctorChecks({ sources: triggerWatchSources, rules: triggerWatchRules, env }));
1453
1904
  // FIRST, and fail rather than warn: every check below this line reads counts that a parse failure
1454
1905
  // zeroed, so a green run here would be reporting on a file nobody could read. The receiver loads this
1455
1906
  // file unconditionally and refuses to start without it, which is the consequence worth naming.
@@ -1462,6 +1913,7 @@ export async function collectChecks(shellVars, seams) {
1462
1913
  if (triggersSet !== undefined && !fileExists(triggersPath(env, cwd))) {
1463
1914
  const note = fromFileNote(fileSays("PI_TRIGGERS_FILE"));
1464
1915
  checks.push({
1916
+ id: "triggers.file-missing",
1465
1917
  ok: false,
1466
1918
  label: triggersSet === ""
1467
1919
  ? `PI_TRIGGERS_FILE is set to an empty value, which neither process reads as unset: the worker and the receiver refuse to start on it (exit 2)${note}`
@@ -1471,17 +1923,24 @@ export async function collectChecks(shellVars, seams) {
1471
1923
  }
1472
1924
  if (parseError) {
1473
1925
  checks.push({
1926
+ // Named (issue #712): the console quotes it beside "the triggers file does not load".
1927
+ id: "triggers.file",
1474
1928
  ok: false,
1475
1929
  // "is refused at load" rather than "does not parse", because since issue #313 it is no longer
1476
1930
  // only a syntax error: a duplicate key parses perfectly and is refused anyway. The loader's own
1477
1931
  // message says which, and the old wording sent an operator hunting for a syntax error that was
1478
1932
  // not there. It still covers the JSON case, whose message begins "is not valid JSON".
1479
1933
  label: `triggers file is refused at load -- the receiver will refuse to start: ${parseError}`,
1480
- fix: `fix ${triggersFilePath} so it loads (the message above names the entry and the reason), then re-run doctor -- every trigger-derived check below is skipped until it loads`,
1934
+ // Issue #761: a file a newer pi-dispatch wrote is no broken file, and editing it would lose what that release wrote.
1935
+ fix: triggersFileIsNewer
1936
+ ? `${newerFileFix("this host's worker and receiver")} -- every trigger-derived check below is skipped until this host reads it`
1937
+ : `fix ${triggersFilePath} so it loads (the message above names the entry and the reason), then re-run doctor -- every trigger-derived check below is skipped until it loads`,
1481
1938
  });
1482
1939
  }
1940
+ section("dollars");
1483
1941
  checks.push(...dollarChecks(env, costCaps, triggersSet !== undefined));
1484
1942
 
1943
+ section("image");
1485
1944
  // Only meaningful if docker itself responds; otherwise the image check is noise on top of a down daemon. Issue #433:
1486
1945
  // and never without `local`, where the podman section's line (the image in THIS ACCOUNT'S store) is the image check.
1487
1946
  const imageRun = dockerRun === null ? null : dockerCode === 0 ? await runCmd(spawn, "docker", ["image", "inspect", jobImage], runTimeouts.cmd) : { code: null, ended: "error" };
@@ -1527,6 +1986,7 @@ export async function collectChecks(shellVars, seams) {
1527
1986
  : {}),
1528
1987
  });
1529
1988
 
1989
+ section("triggers");
1530
1990
  // REQ-PER-TRIGGER-SKILLS (issue #60). Every distinct `run.skillsDir`, checked BEFORE anything fires,
1531
1991
  // because the worker's own gate for these refuses at job time -- correct, but at 03:00 in a log nobody
1532
1992
  // is reading. A deployment naming none adds no lines at all, so its output is byte-identical.
@@ -1585,14 +2045,20 @@ export async function collectChecks(shellVars, seams) {
1585
2045
  // (DES-FLOW-RESOLUTION-TWO-ADVISORY-LAYERS): these probes read dir names, and a frontmatter
1586
2046
  // `name:` rename is invisible to them, so a ⚠ here can be wrong in only the loud direction.
1587
2047
  // A deployment with no triggers adds no lines at all, so its output is byte-identical.
2048
+ // Issue #800: the same answer per trigger, for the record of what this host's jobs can load (`publishResults`). Set afresh
2049
+ // on every collection, so a `--fix` re-collect replaces it, as `seams.checkSection` is.
2050
+ seams.flowRows = [];
1588
2051
  if (flows.length > 0) {
1589
2052
  // One stage read for the whole run; each tuple's staged probe is a lookup on its result.
1590
- const staged = readStagedSkills({ globalPiDir: env.PI_GLOBAL_PI_DIR, readFile: (p) => readFileSync(p, "utf8"), fileExists });
2053
+ const flowFs = seams.flowFs ?? { statSync, readFileSync, readdirSync };
2054
+ const stagedProbes = flowProbes({ fileExists, fs: flowFs });
2055
+ const staged = readStagedSkills({ globalPiDir: env.PI_GLOBAL_PI_DIR, readFile: stagedProbes.readFile, fileExists: stagedProbes.fileExists, readDir: stagedProbes.readDir });
1591
2056
  const groups = new Map();
1592
2057
  for (const f of flows) {
1593
- const key = JSON.stringify([f.flow, f.folder, f.skillsDir, f.packages]);
1594
- if (!groups.has(key)) groups.set(key, { ...f, labels: [] });
2058
+ const key = JSON.stringify([f.flow, f.folder, f.skillsDir, f.packages, f.excludeExtensions]);
2059
+ if (!groups.has(key)) groups.set(key, { ...f, labels: [], triggers: [] });
1595
2060
  groups.get(key).labels.push(f.label);
2061
+ groups.get(key).triggers.push(f.index);
1596
2062
  }
1597
2063
  for (const g of groups.values()) {
1598
2064
  const at = g.labels.join(", ");
@@ -1606,37 +2072,18 @@ export async function collectChecks(shellVars, seams) {
1606
2072
  label: `Trigger flow ${JSON.stringify(g.flow)} fails the skill name charset (${at})`,
1607
2073
  fix: "a flow name must match the skill charset (lowercase alphanumerics, - and _, 64 max), or no tier can ever hold it -- fix run.flow",
1608
2074
  });
2075
+ // No tier can hold it, and a name that fails the charset is not published.
2076
+ for (const trigger of g.triggers) seams.flowRows.push({ trigger, flow: null, tier: "none", package: null, repo: "unknown" });
1609
2077
  continue;
1610
2078
  }
1611
- let resolved = null;
1612
- const checked = [];
1613
- const unknown = [];
1614
- if (g.folder) {
1615
- const state = await repoFlowAtHead(spawn, g.folder, g.flow);
1616
- if (state === "present") resolved = `repo .pi/skills at HEAD of ${g.folder}`;
1617
- else if (state === "absent") checked.push("repo .pi/skills at HEAD");
1618
- else unknown.push(`repo (${g.folder} is not readable as a git repo here)`);
1619
- } else {
1620
- unknown.push("repo (a forge clone, not on this host)");
1621
- }
1622
- if (!resolved && g.skillsDir) {
1623
- if (fileExists(join(g.skillsDir, g.flow, "SKILL.md"))) resolved = `injected run.skillsDir ${g.skillsDir}`;
1624
- else checked.push("injected run.skillsDir");
1625
- }
1626
- if (!resolved && env.PI_GLOBAL_PI_DIR) {
1627
- if (fileExists(join(env.PI_GLOBAL_PI_DIR, "skills", g.flow, "SKILL.md"))) resolved = "the overlay skills/";
1628
- else checked.push("overlay skills/");
1629
- }
1630
- if (!resolved) {
1631
- if (!g.packages) {
1632
- checked.push("staged packages (withheld: run.packages false)");
1633
- } else {
1634
- const hit = staged.skills.find((s) => s.name === g.flow);
1635
- if (hit) resolved = `staged package ${hit.package}`;
1636
- else if (staged.unenumerable.length > 0) unknown.push(`staged package(s) ${staged.unenumerable.join(", ")} (manifest patterns, not enumerable here)`);
1637
- else checked.push("staged packages");
1638
- }
1639
- }
2079
+ const probes = flowProbes({ fileExists, fs: flowFs });
2080
+ const found = await flowTierOf(g, { repoFlowAtHead: (folder, flow) => repoFlowAtHead(spawn, folder, flow), fileExists: probes.fileExists, overlay: env.PI_GLOBAL_PI_DIR, staged });
2081
+ const { resolved, checked, unknown } = found;
2082
+ // `none` says every tier was checked. Per question, and the stage's read only where this one looks in the stage: a
2083
+ // trigger that withholds the packages did not, and another trigger's unreadable folder says nothing of this one's.
2084
+ const blind = probes.blind() || (g.packages !== false && stagedProbes.blind());
2085
+ const tier = found.tier === "none" && blind ? "unknown" : found.tier;
2086
+ for (const trigger of g.triggers) seams.flowRows.push({ trigger, flow: g.flow, tier, package: found.package, repo: found.repo });
1640
2087
  if (resolved) {
1641
2088
  checks.push({ ok: true, label: `Trigger flow "${g.flow}" resolves (${at}: ${resolved})` });
1642
2089
  } else {
@@ -1644,7 +2091,38 @@ export async function collectChecks(shellVars, seams) {
1644
2091
  ok: false,
1645
2092
  warn: true,
1646
2093
  label: `Trigger flow "${g.flow}" resolves in NO tier visible here (${at})`,
1647
- fix: `checked: ${checked.join(", ") || "nothing checkable"}${unknown.length > 0 ? `; not checkable here: ${unknown.join(", ")}` : ""} -- commit .pi/skills/${g.flow}/SKILL.md, add the skill to run.skillsDir or the overlay skills/, or stage a package shipping it; a job of this trigger runs without the flow it names (the runner logs flow_not_loaded) and still exits 0`,
2094
+ fix: `checked: ${checked.join(", ") || "nothing checkable"}${unknown.length > 0 ? `; not checkable here: ${unknown.join(", ")}` : ""} -- commit .pi/skills/${g.flow}/SKILL.md, add the skill to run.skillsDir or the overlay skills/, or stage a package shipping it (one already staged must be off this trigger's run.excludeExtensions, and run.packages must not be false); a job of this trigger runs without the flow it names (the runner logs flow_not_loaded) and still exits 0`,
2095
+ });
2096
+ }
2097
+ }
2098
+ }
2099
+
2100
+ // Issue #800: a name in run.excludeExtensions that this host holds neither way. No job refuses over it and nothing loads for it, since a host's overlay
2101
+ // and stage are its own and the file is shared, but a typo in a list that keeps code out of a job reads as kept out. ⚠ and never ✗. Only against what
2102
+ // was read: an overlay or manifest that cannot be read says nothing of a name, and has its own line. A trigger that withholds the packages is passed
2103
+ // over: its name may be a package's, which that trigger never looks for.
2104
+ {
2105
+ const overlayDir = env.PI_GLOBAL_PI_DIR;
2106
+ let held = null;
2107
+ try {
2108
+ const entries = readOverlayExtensionRows(overlayDir, { fs: seams.flowFs ?? { readFileSync, readdirSync, statSync } });
2109
+ const manifest = overlayDir && fileExists(join(overlayDir, PACKAGES_SUBDIR, STAGE_MANIFEST)) ? readStageManifest({ globalPiDir: overlayDir, readFile: (p) => readFileSync(p, "utf8"), fileExists }) : { packages: [] };
2110
+ if (entries !== null && manifest !== null) held = { overlay: entries.map((row) => row.name), packages: manifest.packages };
2111
+ } catch {
2112
+ held = null;
2113
+ }
2114
+ if (held !== null) {
2115
+ const lines = new Map();
2116
+ for (const { label, names, packages } of excludedNames) {
2117
+ if (!packages) continue;
2118
+ for (const name of extensionsNotHere(names, held)) lines.set(name, [...(lines.get(name) ?? []), label]);
2119
+ }
2120
+ for (const [name, labels] of lines) {
2121
+ checks.push({
2122
+ ok: false,
2123
+ warn: true,
2124
+ label: `run.excludeExtensions names ${JSON.stringify(name)}, and this host has no staged package or overlay extension of that name (${labels.join(", ")})`,
2125
+ fix: "nothing loads for it here, so a job is not refused: fix the name if it is a typo, since a misspelled name keeps nothing out on a host that has the real one",
1648
2126
  });
1649
2127
  }
1650
2128
  }
@@ -1661,6 +2139,7 @@ export async function collectChecks(shellVars, seams) {
1661
2139
  checks.push({ ok: true, label: `${commands} command trigger(s): a command is only verifiable in-container -- the runner refuses an unregistered one before the prompt is sent (command-unregistered)` });
1662
2140
  }
1663
2141
 
2142
+ section("venues");
1664
2143
  // Issue #41: every DISTINCT image a trigger names in run.image, minus the deployment default already
1665
2144
  // checked above. Two silent-failure modes, and both used to be impossible because there was one image.
1666
2145
  // 1. the image was never built -- a job that refuses pre-spend at 03:00 in a log nobody is reading, and
@@ -1723,6 +2202,7 @@ export async function collectChecks(shellVars, seams) {
1723
2202
  // of the default image is what gates their podman half; its lines are still printed after the backend section, where
1724
2203
  // they always were, so moving the read changed the order of spawns and not a byte of output.
1725
2204
  const podman = podmanUsed ? await podmanChecks(env, seams, { jobImage, jobImageNote }) : null;
2205
+ section("images");
1726
2206
  for (const img of images.filter((i) => i !== jobImage)) {
1727
2207
  if (dockerRun !== null && dockerCode === 0 && dockerRouted.has(img)) {
1728
2208
  const run = await runCmd(spawn, "docker", ["image", "inspect", img], runTimeouts.cmd);
@@ -1760,6 +2240,7 @@ export async function collectChecks(shellVars, seams) {
1760
2240
  }
1761
2241
  }
1762
2242
 
2243
+ section("egress");
1763
2244
  // REQ-EGRESS-ALLOWLIST (issue #202). [] when PI_EGRESS=0, so a deployment that declined it gets
1764
2245
  // byte-identical output. Gated on docker and the image, because two of these checks run a container and
1765
2246
  // the rest are noise on top of a down daemon.
@@ -1842,7 +2323,9 @@ export async function collectChecks(shellVars, seams) {
1842
2323
  : dockerCode === null
1843
2324
  ? { answered: false, reason: "docker-not-found", transient: true }
1844
2325
  : null);
2326
+ section("backends");
1845
2327
  checks.push(...backendChecks(env, { endpoint, daemon, fs: seams.observationFs, unit: jobUser.unit, ...(podman ? { podman: podman.observed } : {}) }));
2328
+ section("sizing");
1846
2329
  // Issue #596: the default job size, and what this host's runtime says about the bounds a size becomes.
1847
2330
  // Each venue this deployment runs, from that venue's own read: `undefined` leaves a venue out, null is "not read".
1848
2331
  // Issue #596, phase 2: the host budget a worker started now would compute, from the same two reads, and what it means
@@ -1875,6 +2358,8 @@ export async function collectChecks(shellVars, seams) {
1875
2358
  const total = { memMiB: least(f.memTotalMiB, f.userMemMiB), cpuCenti: least(Number.isSafeInteger(f.hostCpus) ? f.hostCpus * 100 : null, f.userCpuCenti) };
1876
2359
  checks.push(...sizeSuggestionChecks({ projects: sizingProjects, limits: budgetChecksArgs.limits, env, records: read.records, budget: { memMiB: budgetView.memMiB, cpuCenti: budgetView.cpuCenti }, total, nowMs }));
1877
2360
  if (read.skipped > 0) checks.push({ ok: true, label: `size suggestions: ${read.skipped} run record${read.skipped === 1 ? "" : "s"} over ${SIZING_RECORD_MAX_BYTES / 1024} KiB skipped, not read` });
2361
+ // Issue #761: a record a newer pi-dispatch wrote is not folded into a suggestion (`readSizingRecords`), said so.
2362
+ if (read.newerSkipped > 0) checks.push({ ok: true, label: `size suggestions: ${read.newerSkipped} run record${read.newerSkipped === 1 ? "" : "s"} from a newer pi-dispatch not read` });
1878
2363
  }
1879
2364
  }
1880
2365
  // Issue #596, phase 2: the aggregate CPU reserve per venue, read (never written) the way the worker reads it.
@@ -1890,8 +2375,29 @@ export async function collectChecks(shellVars, seams) {
1890
2375
  });
1891
2376
  checks.push(...cpuReserveChecks(reserveReads, budgetView.cpuCenti));
1892
2377
  }
2378
+ section("job-user");
1893
2379
  checks.push(...jobUser.checks);
2380
+ section("podman");
1894
2381
  if (podman) checks.push(...podman.checks);
2382
+ section("openshell");
2383
+ // Issue #683: the openshell venue's lines, asked by `--openshell` (before a deployment blesses it), or on every run
2384
+ // once PI_BACKENDS does (blessable since #684).
2385
+ // Issue #686 part 3: either OpenShell venue runs the section; copy mode's image line where `openshell` is blessed (or
2386
+ // asked for with neither blessed), bind mode's lines where `openshell-bind` is.
2387
+ const openshellVenues = venuesOf(env);
2388
+ // Issue #712: whether this run judged the openshell venue, for the published record.
2389
+ seams.openshellJudged = seams.openshell === true || Boolean(openshellVenues.openshellUsed);
2390
+ if (seams.openshell === true || openshellVenues.openshellUsed) {
2391
+ const { openshellChecks } = await import("./doctor-openshell.mjs");
2392
+ const modes = { copy: openshellVenues.openshellCopyUsed || !openshellVenues.openshellUsed, bind: openshellVenues.openshellBindUsed };
2393
+ // Bind mode's job-user line reads the same identity doctor's local and podman lines read.
2394
+ const ids = seams.jobUserIdentity ? { ids: { euid: seams.jobUserIdentity.euid ?? null, egid: seams.jobUserIdentity.egid ?? null } } : {};
2395
+ const osPlatform = seams.jobUserIdentity?.platform ?? seams.platform;
2396
+ // The probe's source under the jobs dir the service will use (review round 2 of #714).
2397
+ const probeJobsDir = Number.isInteger(seams.jobsDirUid) ? jobsDirPath(env, seams.jobsDirUid) : null;
2398
+ checks.push(...(await openshellChecks(env, { image: jobImage, modes, ...ids, jobsDir: probeJobsDir || null, ...(osPlatform ? { platform: osPlatform } : {}), ...(seams.openshellRun ? { run: seams.openshellRun } : {}), ...(seams.openshellMkdtemp ? { mkdtemp: seams.openshellMkdtemp, rmdir: () => {} } : {}) })));
2399
+ if (openshellVenues.openshellUsed) checks.push(...openshellUnitOrderChecks(seams, cwd));
2400
+ }
1895
2401
  if (facts) facts.jobUser = jobUser.forLive;
1896
2402
  // Issue #596, phase 2: the CPU budget the parent's quota is read back against by `--live`.
1897
2403
  if (facts) facts.cpuBudgetCenti = budgetView.cpuCenti ?? null;
@@ -1899,6 +2405,7 @@ export async function collectChecks(shellVars, seams) {
1899
2405
  if (facts) facts.daemon = jobUser.daemon;
1900
2406
  // Issue #354: which read-backs `--live` runs, and the podman venue's facts for its own.
1901
2407
  if (facts) Object.assign(facts, { localUsed, podman: podman?.forLive ?? null });
2408
+ section("selinux");
1902
2409
  // Issue #355: on a Podman host that confines containers with SELinux, the directories a job mounts that the worker
1903
2410
  // did NOT make, which it therefore never relabels. Read from the same facts and endpoint as the line above. Issue #354:
1904
2411
  // the podman venue relabels on the same rule (its own directories only), so the same lines, ONCE when both venues do.
@@ -1906,6 +2413,7 @@ export async function collectChecks(shellVars, seams) {
1906
2413
  checks.push(...(await selinuxLabelChecks({ folders, overlay: env.PI_GLOBAL_PI_DIR || null, spawn: seams.spawn })));
1907
2414
  }
1908
2415
 
2416
+ section("forges");
1909
2417
  // The receiver itself, when the triggers file names ANY forge (issue #80). Only forge deliveries need
1910
2418
  // the receiver at all, so a cron/local-only deployment gets no receiver noise here. WARNS rather than
1911
2419
  // fails, same doctrine as the gitlab block below: a deployment can legitimately be mid-setup (or run
@@ -2083,6 +2591,7 @@ export async function collectChecks(shellVars, seams) {
2083
2591
  }
2084
2592
  }
2085
2593
 
2594
+ section("github");
2086
2595
  // The default source `gh` mints job tokens from the operator's gh login, so the FULL-scope login token
2087
2596
  // reaches every token-carrying job container — the opposite of the App path's per-repo short-lived
2088
2597
  // tokens (CONST-TOKEN-SCOPED-PER-JOB). Both checks below warn, never fail: a local-only deployment with
@@ -2291,7 +2800,7 @@ export async function collectChecks(shellVars, seams) {
2291
2800
  // is podman's answer to the question docker's endpoint read answers below: the token must not ride to another
2292
2801
  // machine. A deployment with `local` probes on docker exactly as before, and only there: one hand-off of the token per
2293
2802
  // doctor run, not one per venue, and that deployment's output unchanged.
2294
- const ghProbeBin = localUsed
2803
+ const ghProbeBin = seams.setupReadOnly ? null : localUsed
2295
2804
  ? dockerCode === 0 && imageCode === 0
2296
2805
  ? "docker"
2297
2806
  : null
@@ -2380,6 +2889,7 @@ export async function collectChecks(shellVars, seams) {
2380
2889
  }
2381
2890
  }
2382
2891
 
2892
+ section("valkey");
2383
2893
  // Issue #464 (gate rounds 1 and 2): WHOSE Valkey that is, on the podman venue, by the one rule the worker applies at
2384
2894
  // boot and `service install` and `up` apply (`judgeValkeyListeners`). Reachable is not enough: on a shared host a
2385
2895
  // VALKEY_URL that reaches another account's Valkey (its port, its ::1 for a `localhost` URL, or 0.0.0.0) passed here,
@@ -2397,7 +2907,7 @@ export async function collectChecks(shellVars, seams) {
2397
2907
  })();
2398
2908
  if (!unreadValkey && !valkeyDbProblem && seams.valkeyOwner) {
2399
2909
  if (typeof env[VALKEY_SHARED_KEY] === "string") checks.push({ ok: false, warn: true, label: sharedShellIgnored(env[VALKEY_SHARED_KEY], join(cwd, ".env")), fix: "put PI_VALKEY_SHARED=1 in the deployment's .env if that Valkey is shared on purpose, and unset it in this shell" });
2400
- ownerVerdict = await seams.valkeyOwner(valkeyUrl, { shared: valkeySharedOn(sharedInFile), user: userNameOf(seams), envPath: join(cwd, ".env"), rootOk: !(podmanUsed && !localUsed) });
2910
+ ownerVerdict = await seams.valkeyOwner(valkeyUrl, { shared: valkeySharedOn(sharedInFile), user: userNameOf(seams), envPath: join(cwd, ".env"), rootOk: !((podmanUsed && !localUsed) || openshellSetup.valkeyEngine === "podman") });
2401
2911
  }
2402
2912
  // A name that does not resolve here cannot be judged (gate round 3): said, and talked to no more than a refused one.
2403
2913
  const valkeyUnresolved = ownerVerdict?.unresolved ? `VALKEY_URL's host ${ownerVerdict.unresolved} did not resolve here (${ownerVerdict.why}), so whose Valkey it reaches cannot be judged; the worker waits for it and retries` : null;
@@ -2431,7 +2941,7 @@ export async function collectChecks(shellVars, seams) {
2431
2941
  } else if (valkeyAuthVerdict && (valkeyAuthVerdict.state === "noauth" || valkeyAuthVerdict.state === "wrongpass")) {
2432
2942
  // Issue #468: a Valkey that refuses this deployment's credential answers, so "not reachable" would be the wrong
2433
2943
  // sentence: it is the password, named by its key and where it came from, never its value.
2434
- checks.push({ ok: false, label: `Valkey (${urlShown(valkeyUrl)}) answers, and ${valkeyAuthVerdict.state === "noauth" ? "requires a password this deployment does not send" : `refuses the ${VALKEY_PASSWORD_KEY} this deployment sends`}: the worker refuses to start on it (exit 2)`, fix: valkeyAuthFix(valkeyAuthVerdict.state, { localUsed, podmanUsed, envPath: join(cwd, ".env") }) });
2944
+ checks.push({ ok: false, label: `Valkey (${urlShown(valkeyUrl)}) answers, and ${valkeyAuthVerdict.state === "noauth" ? "requires a password this deployment does not send" : `refuses the ${VALKEY_PASSWORD_KEY} this deployment sends`}: the worker refuses to start on it (exit 2)`, fix: valkeyAuthFix(valkeyAuthVerdict.state, { ...valkeyVenues, envPath: join(cwd, ".env") }) });
2435
2945
  } else checks.push({
2436
2946
  ok: await probeValkey(valkeyTalkUrl),
2437
2947
  label: `Valkey reachable (${urlShown(valkeyUrl)})${fromFileNote(fileSays("VALKEY_URL"))}`,
@@ -2440,9 +2950,11 @@ export async function collectChecks(shellVars, seams) {
2440
2950
  // the deployment's VALKEY_PASSWORD in the docker CLI's environment, and doctor hands no program anything from
2441
2951
  // `.env`). It names the step: `pi-dispatch up`, which starts it with the password, labels its container and volume
2442
2952
  // with this folder, and asks before it uses a volume it cannot attribute. The words hold on both venues.
2443
- fix: localUsed
2953
+ fix: valkeyVenues.localUsed
2444
2954
  ? "run `pi-dispatch up` in the deployment folder: it starts Valkey with the deployment's VALKEY_PASSWORD (or, in a folder /dispatch setup handed to compose, compose's own: `docker compose -p <folder name> --env-file .env -f deploy/docker-compose.yml -f deploy/docker-compose.valkey.yml up -d valkey`)"
2445
- : "run `pi-dispatch up` (or `pi-dispatch service install`) as this account: on the podman venue both start Valkey as a Quadlet unit under its Podman (docs/podman.md, setup step 6); a Valkey you run yourself, a distribution package say, works too",
2955
+ : openshellSetup.valkeyEngine !== "podman"
2956
+ ? "run `pi-dispatch up` (or `pi-dispatch service install`) as this account: on the podman venue both start Valkey as a Quadlet unit under its Podman (docs/podman.md, setup step 6); a Valkey you run yourself, a distribution package say, works too"
2957
+ : "run `pi-dispatch up` (or `pi-dispatch service install`) as this account: with PI_OPENSHELL_ENGINE=podman both start Valkey as a Quadlet unit under its Podman (the openshell venue's engine; no egress proxy is started for it); a Valkey you run yourself, a distribution package say, works too",
2446
2958
  });
2447
2959
 
2448
2960
  // Round 3 of PR #475's review: PI_VALKEY_PORT is the port compose publishes its Valkey on, and VALKEY_URL's is the one
@@ -2465,11 +2977,12 @@ export async function collectChecks(shellVars, seams) {
2465
2977
  if (ownerVerdict?.heldBy) {
2466
2978
  checks.push({ ok: true, label: `Valkey (${urlShown(valkeyUrl)}) answers from a listener of ${ownerVerdict.heldBy}${ownerVerdict.chosen ? `; the worker connects to ${ownerVerdict.chosen} only` : ""}` });
2467
2979
  }
2468
- checks.push(...(await valkeyPasswordChecks({ verdict: valkeyAuthVerdict, context: valkeyContext, seams, valkeyUrl, valkeyTalkUrl, localUsed, podmanUsed, platform, statSeam, fileValue })));
2980
+ checks.push(...(await valkeyPasswordChecks({ verdict: valkeyAuthVerdict, context: valkeyContext, seams, valkeyUrl, valkeyTalkUrl, ...valkeyVenues, platform, statSeam, fileValue })));
2469
2981
  for (const other of ownerVerdict?.elsewhere ?? []) {
2470
2982
  checks.push({ ok: false, warn: true, label: `another account also listens on an address VALKEY_URL's host resolves to: ${other}. The worker connects only to the address judged this account's, so it never reaches that one`, fix: "nothing to change for this deployment; a client that resolves the name itself (`pi-dispatch run` from a shell) may still reach it, so prefer VALKEY_URL=redis://127.0.0.1:<port>" });
2471
2983
  }
2472
2984
 
2985
+ section("fleet");
2473
2986
  // --- the fleet (issue #57) -------------------------------------------------------------------------
2474
2987
  //
2475
2988
  // Every line here is gated on a peer actually existing, so a single-host deployment's output is
@@ -2485,7 +2998,12 @@ export async function collectChecks(shellVars, seams) {
2485
2998
  // Valkey doctor reads, a host row is another party's text, and a control byte in a name or zone must not reach the
2486
2999
  // terminal. The registry's own charset already refuses them at the source; this is the reader not relying on it.
2487
3000
  const peers = (fleet.hosts ?? []).map((h) => ({ ...h, name: printable(h.name), tz: h.tz ? printable(h.tz) : h.tz })).filter((h) => h.name !== workerNameOf(declaredWorkerName));
2488
- if (!env.PI_WORKER_NAME && peers.length > 0) checks.splice(budgetChecksAt, budgetChecksHere.length, ...hostBudgetChecks(budgetView, { ...budgetChecksArgs, peers: true }));
3001
+ if (!env.PI_WORKER_NAME && peers.length > 0) {
3002
+ // The budget lines are re-said for a fleet IN PLACE, so they keep the section they were first said in (issue #712).
3003
+ const again = hostBudgetChecks(budgetView, { ...budgetChecksArgs, peers: true });
3004
+ tagSection(again, "sizing");
3005
+ checks.splice(budgetChecksAt, budgetChecksHere.length, ...again);
3006
+ }
2489
3007
  // Issue #596, phase 2: this host's own row, when its worker runs and publishes one. Its host budget ledger is held
2490
3008
  // against the size labels of the job containers each venue's runtime lists, read only when the row carries the ledger.
2491
3009
  const selfRow = (fleet.hosts ?? []).find((h) => printable(h.name) === workerNameOf(declaredWorkerName)) ?? null;
@@ -2516,6 +3034,17 @@ export async function collectChecks(shellVars, seams) {
2516
3034
  // no envelope that refuses every job is told why. `{ digest }`, `{ undecodable: true }` for a key that exists and does
2517
3035
  // not decode (the worker's EXISTS still counts it as governed), or null (no split, or no answer: nothing is said).
2518
3036
  const valkeyUsable = !(unreadValkey || valkeyRefused || valkeyDbProblem || valkeyAuthVerdict?.state === "dbrange");
3037
+ // Issue #712: where this run's results are published, by the rule every read above obeys: the Valkey doctor may talk
3038
+ // to, at the address the worker pins, or none. Named for this host as the worker names it, so a record and its
3039
+ // registry row share a name.
3040
+ // A declared name the worker refuses at boot (review round 1) is never a key: the worker's own rule, not a copy.
3041
+ let publishName = null;
3042
+ try {
3043
+ publishName = workerNameFrom({ PI_WORKER_NAME: declaredWorkerName });
3044
+ } catch {
3045
+ publishName = null;
3046
+ }
3047
+ seams.publishTo = !valkeyUsable ? null : publishName === null ? { refused: "PI_WORKER_NAME is a name the worker refuses at boot" } : { url: valkeyTalkUrl, name: publishName, every: doctorIntervalHours(env) };
2519
3048
  const appliedSplit = valkeyUsable ? await (seams.readAppliedSplit ?? defaultReadAppliedSplit)(valkeyTalkUrl) : null;
2520
3049
  // Read only when there is a peer to compare against. Every line below is gated on a peer existing, and
2521
3050
  // the SUBPROCESS has to be too: otherwise every `doctor` run on every single-host deployment spawns an
@@ -2537,6 +3066,17 @@ export async function collectChecks(shellVars, seams) {
2537
3066
  // The one thing that is silently WRONG rather than merely undeclared. Without a declared name this
2538
3067
  // host enqueues its own folder work to the SHARED queue, where a peer that has no such folder can
2539
3068
  // pop it -- so the routing that makes a fleet safe is simply off, and nothing else says so.
3069
+ // Issue #645: a durable run's checkpoint lives on ONE host, and its recovery is routed there through that host's own
3070
+ // queue. Without a declared name the recovery goes to the SHARED queue, where a peer that holds no checkpoint can pop
3071
+ // it and refuse it (`recovery-checkpoint-absent`), so every crash on this host ends the run instead of continuing it.
3072
+ if (!declaredWorkerName && recovering > 0) {
3073
+ checks.push({
3074
+ ok: false,
3075
+ warn: true,
3076
+ label: `${recovering} trigger(s) arm run.recover, but this worker has peers and no PI_WORKER_NAME, so a crashed run's recovery is queued where a host without its checkpoint can take it`,
3077
+ fix: "set PI_WORKER_NAME in this host's .env and restart: a recovery is routed to the host holding the run's checkpoint through that host's own queue, which only a named worker drains",
3078
+ });
3079
+ }
2540
3080
  if (!declaredWorkerName) {
2541
3081
  checks.push({
2542
3082
  ok: false,
@@ -2611,6 +3151,10 @@ export async function collectChecks(shellVars, seams) {
2611
3151
  // no edit to the file applies on it. Judged on the DECLARED version, or the derived one if that is higher (gate
2612
3152
  // round 2). SKIPPED when this host's file does not load.
2613
3153
  if (scopedLimitFacts.parseError === null) checks.push(...fleetSizeChecks(Math.max(Number(scopedLimitFacts.declaredVersion) || 0, scopedLimitsVersionFor(scopedLimitFacts.limits)), peers));
3154
+ // Issue #761: the version each of this host's own stores needs (the higher of what the file declares and what its
3155
+ // content needs, the size check's rule), by registry field, against what every peer publishes. A store whose file
3156
+ // does not load here is left out: its own line already fails, and comparing would name the wrong hosts.
3157
+ checks.push(...fleetStoreVersionChecks(storeVersionNeeds({ settingsFile: settingsFilePath(env, home), fileExists, pauseWindowFacts, triggersVersionNeed, jobDataVersionNeed, triggersParsed: parseError === null, settingsVersions: versionTables.settings }), peers));
2614
3158
  // Issue #596, phase 2: each host's budget and use, and which hosts each project's size fits on, from every row that
2615
3159
  // publishes a budget (this host's own included). SKIPPED when this host's scoped-limits file does not load.
2616
3160
  if (scopedLimitFacts.parseError === null) checks.push(...fleetBudgetChecks((fleet.hosts ?? []).map((h) => ({ ...h, name: printable(h.name) })), { limits: scopedLimitFacts.limits, env }));
@@ -2623,6 +3167,16 @@ export async function collectChecks(shellVars, seams) {
2623
3167
  // Said, rather than silently absent: "no peers" and "could not ask" are different facts.
2624
3168
  checks.push({ ok: true, label: `Fleet: could not read the host registry (${printable(fleet.unreachable)})` });
2625
3169
  }
3170
+ // Issue #761: the pi-dispatch versions the live workers report, and this doctor's own against this host's running
3171
+ // worker, after the peers block so the second is said on a single host too. Workers only: a receiver's status row is
3172
+ // never a doctor input (INT-RECEIVER-STATUS-KEY).
3173
+ checks.push(...fleetVersionChecks({ installed: PACKAGE_VERSION, self: selfRow, selfName: workerNameOf(declaredWorkerName), peers }));
3174
+ // Issue #761: a dollar window counter below what this host's own records settled into it (`doctorDollarWindows`).
3175
+ // Re-opened here, where whether this command may talk to the Valkey is known, from the same Valkey at the address the
3176
+ // worker pins.
3177
+ section("dollars");
3178
+ checks.push(...(await doctorDollarWindows({ seams, env, home, url: valkeyUsable ? valkeyTalkUrl : null, localHost: workerNameOf(declaredWorkerName), fileExists })));
3179
+ section("capacity");
2626
3180
  // Issue #599, phase 2: how busy each host was over the last 7 days, one fact line per host, never a warning (nothing
2627
3181
  // decides on it). On every deployment, a single host too: its own files are read when the run mirror is not. Read from
2628
3182
  // the same Valkey the fleet was, with the registry rows just read (their running jobs count up to now), every Valkey
@@ -2636,6 +3190,8 @@ export async function collectChecks(shellVars, seams) {
2636
3190
  if (envelopeHere.parseError === null) checks.push(...appliedSplitChecks(appliedSplit, envelopeHere.envelope ? envelopeDigest(envelopeHere.envelope) : NO_ENVELOPE_FINGERPRINT, workerNameOf(declaredWorkerName), peers));
2637
3191
  }
2638
3192
 
3193
+ section("provider");
3194
+ const subscriptionCredentials = await doctorSubscriptionCredentials(env, { cwd, home, now: seams.wallClock ?? Date.now, configure: seams.subscriptionFactory });
2639
3195
  // Which variable holds a provider's key is PI'S fact, asked of pi rather than copied (issue #286).
2640
3196
  // The copy this replaced had anthropic's two variables in the WRONG precedence order, invented
2641
3197
  // GOOGLE_API_KEY, and invented a `gemini` provider pi has never had -- three ways for doctor to bless
@@ -2689,7 +3245,8 @@ export async function collectChecks(shellVars, seams) {
2689
3245
  hintUnread = true;
2690
3246
  }
2691
3247
  }
2692
- const keyCheck = providerKeyCheck({ provider, env: { ...env, ...keyFromFile }, agentDir: keyAgentDir, oracle, nodeOk: checks[0]?.ok, keyless: { endpoints: keylessEndpoints, models: keylessModels, unreadable: keylessUnreadable, hintModels, hintUnread } });
3248
+ const subscriptionDefault = await subscriptionCredentials.check(provider);
3249
+ const keyCheck = subscriptionDefault.managed ? subscriptionCredentialCheck(provider, subscriptionDefault) : providerKeyCheck({ provider, env: { ...env, ...keyFromFile }, agentDir: keyAgentDir, oracle, nodeOk: checks[0]?.ok, keyless: { endpoints: keylessEndpoints, models: keylessModels, unreadable: keylessUnreadable, hintModels, hintUnread } });
2693
3250
  const keyNamed = Object.keys(keyFromFile).filter((name) => keyCheck.label?.includes(`: ${name})`));
2694
3251
  // Issue #481 (PR #485 review round 2): a key found nowhere doctor can look is one an env-setup script may export, which
2695
3252
  // is the documented home for a provider key fetched from a secrets manager (docs/secrets.md).
@@ -2700,9 +3257,12 @@ export async function collectChecks(shellVars, seams) {
2700
3257
  : setupSupplies(["worker"])
2701
3258
  ? credentialAbsent({ subject: `Provider key (${provider}: ${keyAbsent.join(" or ")}) not set`, names: keyNames, readers: ["worker"], refusal: "jobs cannot authenticate to the provider", fix: keyShown.fix })
2702
3259
  : { ...keyShown, fix: `${keyShown.fix}${notSupplied(keyNames, ["worker"])}` };
2703
- checks.push({ ...keyLine, label: `${keyLine.label}${fromFileNote([...fileSays("PI_PROVIDER"), ...keyNamed, ...(keyAgentDir !== agentDir ? ["PI_CODING_AGENT_DIR"] : [])])}` });
3260
+ // Not for a malformed PI_PROVIDER: its shape row below is the one line (issue #673, review round 1).
3261
+ // Issue #737: the console reads whether the key is found by this id (`NAMED_CHECK_IDS`).
3262
+ if (envShapeProblem.PI_PROVIDER === null) checks.push({ ...keyLine, id: "provider.key", label: `${keyLine.label}${fromFileNote([...fileSays("PI_PROVIDER"), ...keyNamed, ...(keyAgentDir !== agentDir ? ["PI_CODING_AGENT_DIR"] : [])])}` });
2704
3263
 
2705
3264
 
3265
+ section("overlay");
2706
3266
  // REQ-GLOBAL-PI-OVERLAY: read the extensions opt-out through the WORKER's own parser, so doctor reports
2707
3267
  // the exact posture the worker will boot with and refuses the exact values it refuses. Checked with or
2708
3268
  // without an overlay configured, because a malformed knob stops boot either way -- and a `false` an
@@ -2915,7 +3475,7 @@ export async function collectChecks(shellVars, seams) {
2915
3475
  // A model a capped job may use is named by the cost-cap line below (`costCapFitChecks`), which runs on the
2916
3476
  // same catalog seam, so this line names only the rest: one line per model.
2917
3477
  const capEndpoints = (seams.declaredEndpoints ?? ((a) => declaredEndpointsIn({ ...a, fs: keylessIo })))({ env, cwd: seams.cwd, platform: seams.platform ?? process.platform, valkeyUrl: keylessValkey });
2918
- const capped = usageCatalog ? cappedModelNames(env, { runs: parseError ? [] : modelRuns, deployment: deploymentSettingsOf(env, settingsFilePath(env, home), fileExists) }) : new Set();
3478
+ const capped = usageCatalog ? cappedModelNames(env, { runs: parseError ? [] : modelRuns, deployment: deploymentSettingsOf(env, settingsFilePath(env, home), fileExists), modelRoles: triggerModelRoles, projects: modelRoleProjects }) : new Set();
2919
3479
  const uncapped = ignoredOutputCapModels({ models: overlayModels, endpoints: capEndpoints, builtinModel: usageCatalog?.builtinModel, builtinChatModels: usageCatalog?.builtinChatModels }).filter((m) => !capped.has(`${m.provider}/${m.modelId}`));
2920
3480
  if (uncapped.length > 0) {
2921
3481
  const SHOWN = 5;
@@ -2949,7 +3509,7 @@ export async function collectChecks(shellVars, seams) {
2949
3509
  }
2950
3510
 
2951
3511
  // Staged pi packages (REQ-GLOBAL-PI-OVERLAY): pinned third-party code the operator staged with
2952
- // `import-pi --with-packages`, loaded by every job whose trigger did not set `run.packages: false`.
3512
+ // `import-pi --with-packages`, loaded by every job whose trigger did not set `run.packages: false` or name it in `run.excludeExtensions`.
2953
3513
  // Keyed on the dir the same way the extensions pair above is, so a deployment that stages none
2954
3514
  // prints nothing here.
2955
3515
  const packagesDir = join(overlay, PACKAGES_SUBDIR);
@@ -3005,7 +3565,7 @@ export async function collectChecks(shellVars, seams) {
3005
3565
  });
3006
3566
  }
3007
3567
  // There is no dormant state left to report: a staged, manifested package loads into every
3008
- // job whose trigger did not opt out -- INCLUDING jobs no trigger file describes at all
3568
+ // job whose trigger did not opt out or leave it out by name -- INCLUDING jobs no trigger file describes at all
3009
3569
  // (a matched webhook, `dispatch_run`, the CLI). So "staged" IS "loading", and the honest
3010
3570
  // line says so and names how much of the trigger file withholds it. Warn, never fail: this
3011
3571
  // is the intended posture, and it is stated so a forgotten stage cannot read as inert.
@@ -3014,8 +3574,9 @@ export async function collectChecks(shellVars, seams) {
3014
3574
  checks.push({
3015
3575
  ok: false,
3016
3576
  warn: true,
3017
- label: `Staged packages LOAD in every job (${optingOut} trigger(s) opt out with run.packages: false)`,
3018
- fix: "they run third-party code against adversarial input with open egress -- vet each, keep every version exactly pinned, and set run.packages: false on any trigger that must not load them",
3577
+ // Counted against this host's manifest: a name in the list may be an overlay extension, which withholds no package, and a trigger with packages off is counted above.
3578
+ label: `Staged packages LOAD in every job (${optingOut} trigger(s) opt out with run.packages: false, ${(excludedNames ?? []).filter((listed) => listed.packages && listed.names.some((name) => manifest.packages.some((staged) => staged.name === name))).length} leave one or more out with run.excludeExtensions)`,
3579
+ fix: "they run third-party code against adversarial input with open egress -- vet each, keep every version exactly pinned, and on a trigger that must not load them set run.packages: false, or name one in run.excludeExtensions",
3019
3580
  });
3020
3581
 
3021
3582
  // A staged package whose --ignore-scripts build never ran (issue #102, comment 1). The
@@ -3118,6 +3679,7 @@ export async function collectChecks(shellVars, seams) {
3118
3679
  });
3119
3680
  }
3120
3681
 
3682
+ section("waits");
3121
3683
  // Issue #230, `run.waitFor`. The PARSE is asked unconditionally, and the rest only when something waits.
3122
3684
  // That split is not the usual "only report what this deployment uses": `loadConfig` calls
3123
3685
  // `parseWaitProfiles` on every boot whether or not a trigger holds anything, so a garbled variable is a
@@ -3189,6 +3751,18 @@ export async function collectChecks(shellVars, seams) {
3189
3751
  });
3190
3752
  }
3191
3753
 
3754
+ section("models");
3755
+ // Issue #673: PI_MODEL and PI_PROVIDER are held to the one model-id and provider-id shape a trigger's run.model and
3756
+ // run.provider are (`modelFrom`, `providerFrom`), and a value outside it is a worker that will not boot. Judged by the
3757
+ // worker's own functions (`envShapeProblem`, above), the PI_ALLOWED_MODELS row's rule below, on the SERVICE's value.
3758
+ // Only a failing row: a good value is judged further by the provider-key and model-catalog lines, which a malformed one
3759
+ // skips. The value is never echoed, as the worker's own refusal never echoes it; the setting's name is all an
3760
+ // operator needs to find the line.
3761
+ for (const name of ["PI_MODEL", "PI_PROVIDER"]) {
3762
+ if (envShapeProblem[name] === null) continue;
3763
+ checks.push({ ok: false, label: `${name} is not a valid ${name === "PI_MODEL" ? "model" : "provider"} id`, fix: `${envShapeProblem[name]} -- the worker refuses to boot until this is fixed` });
3764
+ }
3765
+
3192
3766
  // Issue #502, allowed-model lists. The deployment list is judged unconditionally, `PI_WAIT_PROFILES`' rule: a
3193
3767
  // malformed or spaced value is a worker that will not boot. Its grammar is the worker's own (`allowedModelsFrom`).
3194
3768
  // The value doctor reads is the SERVICE's (`WORKER_SERVICE_KEYS`), so a spaced value in a `.env` a shell sources is
@@ -3230,6 +3804,10 @@ export async function collectChecks(shellVars, seams) {
3230
3804
  // pi-ai does not load: the provider key line below already fails on that. A triggers file that did not load
3231
3805
  // contributes no trigger (its own line says so), and the deployment's default is still judged for its cap.
3232
3806
  {
3807
+ let roleEnvList = null;
3808
+ try { roleEnvList = allowedModelsFrom(env); } catch {}
3809
+ // Role refusals are determinate without pi; a missing catalog must not hide invalid reviewed policy.
3810
+ checks.push(...resolveDoctorModelRuns({ runs: parseError ? [] : modelRuns, deployment: deploymentSettingsOf(env, settingsFilePath(env, home), fileExists), envList: roleEnvList, modelRoles: triggerModelRoles, projects: modelRoleProjects }).checks);
3233
3811
  const catalog = await (seams.modelCatalog ?? defaultModelCatalog)();
3234
3812
  if (catalog) {
3235
3813
  const overlayDir = typeof env.PI_GLOBAL_PI_DIR === "string" && env.PI_GLOBAL_PI_DIR !== "" ? resolve(cwd, env.PI_GLOBAL_PI_DIR) : null;
@@ -3246,37 +3824,110 @@ export async function collectChecks(shellVars, seams) {
3246
3824
  } catch {
3247
3825
  // A malformed PI_ALLOWED_MODELS is its own line above (the worker refuses to boot on it).
3248
3826
  }
3249
- const subjects = modelSubjects({ runs: parseError ? [] : modelRuns, deployment: deploymentSettingsOf(env, settingsFilePath(env, home), fileExists), envList });
3250
- checks.push(...unknownModelChecks(subjects, catalog.checkModelsKnown, readOverlayDoc));
3251
- checks.push(...costCapFitChecks(subjects, (ref) => boundModelOf(ref, { builtinModel: catalog.builtinModel, overlay: overlayDoc }), { unboundable: (ref) => outputUnboundable(outputCapView({ models: overlayDoc, provider: ref.provider, modelId: ref.id, builtinModel: catalog.builtinModel, builtinChatModels: catalog.builtinChatModels })) }));
3827
+ const subjects = modelSubjects({ runs: parseError ? [] : modelRuns, deployment: deploymentSettingsOf(env, settingsFilePath(env, home), fileExists), envList, modelRoles: triggerModelRoles, projects: modelRoleProjects });
3828
+ const subscriptionChecks = new Map();
3829
+ for (const subjectProvider of new Set(subjects.flatMap((subject) => [subject.main.provider, ...subject.list.map((ref) => ref.provider)]))) {
3830
+ const result = await subscriptionCredentials.check(subjectProvider);
3831
+ subscriptionChecks.set(subjectProvider, result);
3832
+ if (subjectProvider !== provider && result.managed) checks.push(subscriptionCredentialCheck(subjectProvider, result));
3833
+ }
3834
+
3835
+ // The deployment default's catalog row prints PI_PROVIDER/PI_MODEL: not for a malformed one, whose shape row is
3836
+ // the one line (issue #673, review round 1).
3837
+ const envShapeBad = envShapeProblem.PI_MODEL !== null || envShapeProblem.PI_PROVIDER !== null;
3838
+ checks.push(...unknownModelChecks(envShapeBad ? subjects.filter((s) => s.deployment !== true) : subjects, catalog.checkModelsKnown, readOverlayDoc));
3839
+ checks.push(...costCapFitChecks(subjects, (ref) => boundModelOf(ref, { builtinModel: catalog.builtinModel, overlay: overlayDoc }), { unboundable: (ref) => outputUnboundable(outputCapView({ models: overlayDoc, provider: ref.provider, modelId: ref.id, builtinModel: catalog.builtinModel, builtinChatModels: catalog.builtinChatModels })), apiOf: (ref) => outputCapView({ models: overlayDoc, provider: ref.provider, modelId: ref.id, builtinModel: catalog.builtinModel, builtinChatModels: catalog.builtinChatModels })?.api }));
3252
3840
  checks.push(
3253
3841
  ...listedProviderCredentialChecks(subjects, {
3254
3842
  candidatesOf: (name) => (typeof oracle?.providerKeyCandidates === "function" ? oracle.providerKeyCandidates(name) : []),
3255
3843
  forwarded: (env.PI_FORWARD_ENV ?? "").split(",").map((name) => name.trim()).filter((name) => name !== ""),
3256
3844
  env,
3257
3845
  overlay: overlayDoc,
3846
+ subscriptionChecks,
3258
3847
  }),
3259
3848
  );
3260
3849
  }
3261
3850
  }
3262
3851
 
3852
+ // Read only configured model identities. A keyspace scan would expose retired configuration and make a
3853
+ // doctor run's cost depend on everything else sharing this Valkey.
3854
+ {
3855
+ let envList = null;
3856
+ try { envList = allowedModelsFrom(env); } catch {}
3857
+ const refs = cooldownModelRefs(parseError ? [] : modelRuns, deploymentSettingsOf(env, settingsFilePath(env, home), fileExists), { modelRoles: triggerModelRoles, projects: modelRoleProjects, envList });
3858
+ if (refs.length > 0) {
3859
+ const state = valkeyUsable ? await (seams.readModelCooldowns ?? defaultReadModelCooldowns)(valkeyTalkUrl, refs, { now: seams.wallClock ?? Date.now }) : null;
3860
+ checks.push(...modelCooldownChecks(state));
3861
+ }
3862
+ }
3863
+
3864
+ checks.push(...await doctorModelProposalChecks(env, { cwd, credentials: service.extra(["ANTHROPIC_API_KEY", "OPENAI_API_KEY"]).env, now: seams.wallClock ?? Date.now, ...(seams.modelProposals ?? {}) }));
3865
+ section("secrets");
3263
3866
  // REQ-TRIGGER-SECRETS. Only reported when a trigger actually binds one, on the run.resume block's
3264
3867
  // reasoning below: a deployment that uses no secrets should not be told about a variable it has no
3265
3868
  // reason to set.
3266
3869
  if (secreting > 0) {
3267
- const { profiles: declared, error: parseFailure } = parseSecretProfilesSafe(env.PI_SECRET_PROFILES);
3268
- const names = Object.keys(declared).sort();
3870
+ const { profiles: envDeclared, error: parseFailure } = parseSecretProfilesSafe(env.PI_SECRET_PROFILES);
3871
+ const roots = delimitedList(env.PI_SECRET_RESOLVER_ROOTS);
3269
3872
  if (parseFailure) {
3270
3873
  checks.push({ ok: false, label: "PI_SECRET_PROFILES does not parse", fix: `${parseFailure} -- the worker refuses to boot until this is fixed, rather than dropping the entry and leaving you a profile you believe is wired` });
3271
3874
  } else {
3875
+ // Issue #704: the worker resolves a profile from PI_SECRET_PROFILES AND the settings overlay's
3876
+ // `secretProfiles`, so a profile declared in the panel is declared, and reading env alone told an
3877
+ // operator it was missing. The worker's rules, reused rather than restated: a name in both sources is
3878
+ // ambiguous (`mergeSecretProfiles`, and the worker then refuses every secrets job), and an overlay
3879
+ // profile counts only when its resolver is an executable file whose realpath sits inside
3880
+ // PI_SECRET_RESOLVER_ROOTS (`servableSecretProfiles`, the lookup the resolver makes). An invalid
3881
+ // overlay contributes nothing here; its own check below already fails doctor.
3882
+ //
3883
+ // The probe is the resolver's own (`secrets.mjs -> realExecutable`), through a dynamic import for the
3884
+ // reason `providerOracle` gives: that module loads pi through `env-allowlist.mjs`, and a static import
3885
+ // would make doctor itself fail to start when pi does not load. Without it only the usability probe is
3886
+ // skipped: the ambiguity check needs no pi and still runs on the raw overlay, and an overlay profile then
3887
+ // counts as declared as written (the pi failure is already its own failing line).
3888
+ //
3889
+ // OWN properties only, in every lookup below: the profile charset admits `toString` and `constructor`.
3890
+ const settingsRead = fileExists(settingsFilePath(env, home)) ? readOverlay(settingsFilePath(env, home)) : { overlay: {} };
3891
+ let realExecutablePath = null;
3892
+ try {
3893
+ ({ realExecutable: realExecutablePath } = await import("./secrets.mjs"));
3894
+ } catch {
3895
+ realExecutablePath = null;
3896
+ }
3897
+ const overlayDeclared = settingsRead.invalid ? {} : (settingsRead.overlay?.secretProfiles ?? {});
3898
+ const ambiguousNames = Object.keys(overlayDeclared).filter((name) => Object.hasOwn(envDeclared, name)).sort();
3899
+ const unambiguous = Object.fromEntries(Object.entries(overlayDeclared).filter(([name]) => !Object.hasOwn(envDeclared, name)));
3900
+ const overlayUsable = realExecutablePath === null ? unambiguous : servableSecretProfiles({ envProfiles: {}, overlayProfiles: unambiguous, roots, realExecutablePath }).profiles;
3901
+ const declared = { ...envDeclared, ...overlayUsable };
3902
+ const names = Object.keys(declared).sort();
3903
+ if (mergeSecretProfiles(envDeclared, overlayDeclared).ambiguous) {
3904
+ checks.push({
3905
+ ok: false,
3906
+ label: `${ambiguousNames.length} secret profile name(s) are declared in both PI_SECRET_PROFILES and the settings overlay: ${ambiguousNames.join(", ")}`,
3907
+ fix: "remove each name from one of the two (neither source wins a collision) -- until then the worker refuses every job that binds secrets as secret-profile-ambiguous, whatever profile it names",
3908
+ });
3909
+ }
3910
+ // Named by a trigger, declared in the overlay, and not usable: said apart from "not declared",
3911
+ // because the fix is the resolver or the roots, not a new declaration.
3912
+ const unusable = secretProfiles.filter((name) => Object.hasOwn(unambiguous, name) && !Object.hasOwn(overlayUsable, name));
3913
+ if (unusable.length > 0) {
3914
+ checks.push({
3915
+ ok: false,
3916
+ label: `${unusable.length} named secret profile(s) are declared in the settings overlay but not usable: ${unusable.join(", ")}`,
3917
+ fix:
3918
+ roots.length === 0
3919
+ ? "PI_SECRET_RESOLVER_ROOTS is unset, so the worker uses no overlay-declared resolver: set it to the directory the resolver lives in, or declare the profile in PI_SECRET_PROFILES -- these jobs refuse pre-spend as secret-profile-unknown until you do"
3920
+ : "the resolver must be an executable file whose real path sits inside PI_SECRET_RESOLVER_ROOTS -- these jobs refuse pre-spend as secret-profile-unknown until it is",
3921
+ });
3922
+ }
3272
3923
  // A HARD FAIL, not a warning, and worded like the run.resume/PI_SESSIONS_DIR check below for the
3273
3924
  // same reason: these jobs refuse pre-spend until it is set, deliberately, rather than running
3274
3925
  // without their secrets and looking like they worked.
3275
- const missing = secretProfiles.filter((name) => !(name in declared));
3926
+ const missing = secretProfiles.filter((name) => !Object.hasOwn(declared, name) && !unusable.includes(name) && !ambiguousNames.includes(name));
3276
3927
  checks.push({
3277
3928
  ok: missing.length === 0,
3278
3929
  label: missing.length === 0 ? `${secreting} trigger(s) bind secrets, and every profile they name is declared` : `${secreting} trigger(s) bind secrets, but ${missing.length} named profile(s) are not declared: ${missing.join(", ")}`,
3279
- fix: `declare them in PI_SECRET_PROFILES as name:/absolute/path pairs (a resolver is one line, e.g. \`exec op read --no-newline "$1"\`) -- these jobs refuse pre-spend until you do`,
3930
+ fix: `declare them in PI_SECRET_PROFILES as name:/absolute/path pairs (a resolver is one line, e.g. \`exec op read --no-newline "$1"\`), or through the panel with PI_SECRET_RESOLVER_ROOTS set -- these jobs refuse pre-spend until you do`,
3280
3931
  });
3281
3932
  // The declared table, so an operator sees what is wired without reading .env. NAMES and paths only:
3282
3933
  // this is doctor's own stdout on the operator's host, not a public issue comment.
@@ -3287,7 +3938,6 @@ export async function collectChecks(shellVars, seams) {
3287
3938
  // when closed and a disclosure when open. Issue #462: the disclosure is a FACT LINE too, since the operator opened
3288
3939
  // it on purpose and nothing but closing it again clears it, so its advice lives in the label (an `ok: true` check
3289
3940
  // never prints a fix line).
3290
- const roots = (env.PI_SECRET_RESOLVER_ROOTS ?? "").split(delimiter).map((r) => r.trim()).filter(Boolean);
3291
3941
  checks.push({
3292
3942
  ok: true,
3293
3943
  ...(roots.length === 0
@@ -3312,7 +3962,7 @@ export async function collectChecks(shellVars, seams) {
3312
3962
  // one would be permanently false and this check would silently never run. It is skipped rather than
3313
3963
  // failed when pi did not load, because providerKeyCheck above has already reported that as its own ✗
3314
3964
  // and one root cause should print one line.
3315
- if (secretNames.length > 0 && oracle?.providerKeyCandidates) {
3965
+ if (secretNames.length > 0 && oracle?.providerKeyCandidates && envShapeProblem.PI_PROVIDER === null) {
3316
3966
  const candidates = oracle.providerKeyCandidates(provider);
3317
3967
  const clashing = secretNames.filter((n) => candidates.includes(n));
3318
3968
  checks.push({
@@ -3334,6 +3984,60 @@ export async function collectChecks(shellVars, seams) {
3334
3984
  }
3335
3985
  }
3336
3986
 
3987
+ // Issue #704: the project secret bundles (doctor-bundles.mjs says what each line is for). Silent on a deployment that
3988
+ // binds no bundle and declares no bundle profile. The overlay and the probe are read the way the run.secrets block
3989
+ // above reads them, and `--secrets` (seams.secrets) resolves each bundle here, names only.
3990
+ {
3991
+ const bundleSettingsPath = settingsFilePath(env, home);
3992
+ const bundleSettings = fileExists(bundleSettingsPath) ? readOverlay(bundleSettingsPath) : { overlay: {} };
3993
+ const overlayBundles = bundleSettings.invalid ? {} : (bundleSettings.overlay?.secretBundles ?? {});
3994
+ const anyBundle = Object.keys(triggerBundles ?? {}).length > 0 || (env.PI_SECRET_BUNDLES ?? "").trim() !== "" || Object.keys(overlayBundles).length > 0;
3995
+ // Review round 2: the named residual. A worker that declares no bundle profile and has no triggers file reads "no
3996
+ // bundles", so on a fleet a project another host's file binds would run here without its environment, with no
3997
+ // skip reason. Doctor cannot see another host's file, so it warns where the shape allows it: a multi-host worker
3998
+ // (PI_WORKER_NAME) with projects and no triggers file of its own.
3999
+ if (!anyBundle && typeof env.PI_WORKER_NAME === "string" && env.PI_WORKER_NAME.trim() !== "" && !fileExists(triggersPath(env, cwd))) {
4000
+ const fleetProjects = readProjectFacts(env, fileExists);
4001
+ if (fleetProjects.parseError === null && fleetProjects.projects.length > 0) {
4002
+ checks.push({ ok: true, warn: true, label: "this fleet worker has projects but no triggers file, so it applies no project secret bundle: a project another host's triggers.json binds would run here without its environment", fix: "keep the same triggers.json on every host (PI_TRIGGERS_FILE), or declare the bundle profiles here, which makes a missing file a retry instead" });
4003
+ }
4004
+ }
4005
+ if (anyBundle) {
4006
+ let realExecutablePath = null;
4007
+ try {
4008
+ ({ realExecutable: realExecutablePath } = await import("./secrets.mjs"));
4009
+ } catch {
4010
+ realExecutablePath = null;
4011
+ }
4012
+ const projectFacts = readProjectFacts(env, fileExists);
4013
+ let resolveBundle = null;
4014
+ if (seams.secrets === true) {
4015
+ try {
4016
+ const { makeBundleResolver } = await import("./secret-bundles.mjs");
4017
+ const { parseSecretBundleProfilesSafe } = await import("./doctor-bundles.mjs");
4018
+ const resolver = makeBundleResolver({ envBundles: parseSecretBundleProfilesSafe(env.PI_SECRET_BUNDLES).bundles, roots: delimitedList(env.PI_SECRET_RESOLVER_ROOTS), forwardEnv: (env.PI_FORWARD_ENV ?? "").split(",").map((n) => n.trim()).filter((n) => n !== ""), hostEnv: spawnEnv, timeoutMs: Math.max(BUNDLE_DOCTOR_TIMEOUT_MS, Number(env.PI_SECRET_RESOLVE_TIMEOUT_MS) || 0), ...(seams.bundleSpawn ? { spawnFn: seams.bundleSpawn } : {}) });
4019
+ resolveBundle = (binding) => resolver.resolve({ provider }, binding, { overlayBundles });
4020
+ } catch {
4021
+ checks.push({ ok: false, label: "--secrets could not load the bundle resolver (pi did not load; its own line above says why)" });
4022
+ }
4023
+ }
4024
+ checks.push(
4025
+ ...(await secretBundleChecks({
4026
+ bundles: triggerBundles ?? {},
4027
+ triggersPresent: fileExists(triggersPath(env, cwd)),
4028
+ projects: projectFacts.projects,
4029
+ projectsError: projectFacts.parseError,
4030
+ envRaw: env.PI_SECRET_BUNDLES,
4031
+ overlayBundles,
4032
+ roots: delimitedList(env.PI_SECRET_RESOLVER_ROOTS),
4033
+ realExecutablePath,
4034
+ resolveBundle,
4035
+ })),
4036
+ );
4037
+ }
4038
+ }
4039
+
4040
+ section("sessions");
3337
4041
  // REQ-RESUMABLE-SESSION. Only reported when a trigger actually asked for it: a deployment that does
3338
4042
  // not use resume should not be told about a directory it has no reason to create.
3339
4043
  if (resuming > 0) {
@@ -3411,6 +4115,30 @@ export async function collectChecks(shellVars, seams) {
3411
4115
  }
3412
4116
  }
3413
4117
 
4118
+ // Issue #645: the checkpoint store, only where one is configured (PI_CHECKPOINTS_DIR, or the default inside
4119
+ // PI_SESSIONS_DIR). Never a ✗: only a job that arms run.recover writes it, a fault costs that run its recovery and never
4120
+ // the job, and a deployment without durable runs must not fail doctor over a store it does not use. One `git --version`, bounded like every other spawn here.
4121
+ const checkpointsDir = checkpointsDirPath(env);
4122
+ if (checkpointsDir) {
4123
+ // The hardening flags lead even here, where no repository is read, because the bolt that pins every host-side git
4124
+ // argv to them (`prepare-local.test.mjs`) is worth more unbroken than one `--version` is without them.
4125
+ const gitRead = await runCmdCapture(spawn, "git", [...GIT_READ_FLAGS, "--version"], { timeoutMs: runTimeouts.cmd, stdoutOnly: true });
4126
+ checks.push(
4127
+ ...checkpointStoreChecks({
4128
+ dir: checkpointsDir,
4129
+ explicit: Boolean(env.PI_CHECKPOINTS_DIR),
4130
+ sessionsDir: env.PI_SESSIONS_DIR || null,
4131
+ fs: seams.checkpointFs,
4132
+ uid: Object.hasOwn(seams, "checkpointUid") ? seams.checkpointUid : process.geteuid?.(),
4133
+ underTemp: (path) => underTemp(path, env),
4134
+ gitVersion: gitRead.code === 0 ? gitRead.output : null,
4135
+ venues: blessedList ?? [DEFAULT_BACKEND],
4136
+ podmanRead: podman?.observed?.read ?? null,
4137
+ }),
4138
+ );
4139
+ }
4140
+
4141
+ section("triggers");
3414
4142
  // REQ-PER-TRIGGER-INSTRUCTION. A plain fact line, not a warning: standing text is an ordinary operator
3415
4143
  // choice. It is reported at all because it changes what EVERY job of that trigger is told, and unlike a
3416
4144
  // flow (which lives in the repo, reviewed by a merge) it lives only in triggers.json, so nothing else
@@ -3465,6 +4193,7 @@ export async function collectChecks(shellVars, seams) {
3465
4193
  });
3466
4194
  }
3467
4195
 
4196
+ section("files");
3468
4197
  // REQ-SCOPED-PAUSE-WINDOWS, the panel-writes-what-the-worker-ignores trap (issue #99). Three defaults
3469
4198
  // that are individually defensible and together silent:
3470
4199
  //
@@ -3661,12 +4390,19 @@ export async function collectChecks(shellVars, seams) {
3661
4390
  const verdict = loadVerdict(spec, fileRaw, cwd, seamsForLoad, platform);
3662
4391
  checks.push(
3663
4392
  verdict.ok
3664
- ? { ok: true, label: `${spec.key} is set in ${join(cwd, ".env")} (${envValueShown(fileRaw)})${alsoExported === undefined ? "" : ", for this platform's loader,"} and loads: the service reads that file, this shell does not` }
4393
+ ? { id: bootFileId(spec), ok: true, label: `${spec.key} is set in ${join(cwd, ".env")} (${envValueShown(fileRaw)})${alsoExported === undefined ? "" : ", for this platform's loader,"} and loads: the service reads that file, this shell does not` }
3665
4394
  : {
4395
+ id: bootFileId(spec),
3666
4396
  ok: false,
3667
4397
  warn: envSetup !== null,
3668
4398
  label: `${spec.key} is set in ${join(cwd, ".env")} (${envValueShown(fileRaw)}) to a file the worker cannot load, so a service started from it ${spec.fails}: ${verdict.reason}`,
3669
- fix: envSetup !== null ? `${envSetup} runs after that file and may replace it; if it does not, fix ${envValueShown(fileRaw)} or point the key at a file that loads` : `fix ${envValueShown(fileRaw)}, or point ${spec.key} at a file that loads`,
4399
+ fix: verdict.newer
4400
+ ? envSetup !== null
4401
+ ? `${envSetup} runs after that file and may replace it; if it does not, ${newerFileFix("this host's worker")}`
4402
+ : newerFileFix("this host's worker")
4403
+ : envSetup !== null
4404
+ ? `${envSetup} runs after that file and may replace it; if it does not, fix ${envValueShown(fileRaw)} or point the key at a file that loads`
4405
+ : `fix ${envValueShown(fileRaw)}, or point ${spec.key} at a file that loads`,
3670
4406
  },
3671
4407
  );
3672
4408
  }
@@ -3682,9 +4418,10 @@ export async function collectChecks(shellVars, seams) {
3682
4418
  const verdict = loadVerdict(spec, shellRaw, cwd, seamsForLoad, platform);
3683
4419
  if (!verdict.ok) {
3684
4420
  checks.push({
4421
+ id: bootFileId(spec, "shell"),
3685
4422
  ok: false,
3686
4423
  label: `${spec.key} is set in this shell to a file the worker cannot load, so it ${spec.fails}: ${verdict.reason}`,
3687
- fix: `fix ${envValueShown(shellRaw)}, or point ${spec.key} at a file that loads`,
4424
+ fix: verdict.newer ? newerFileFix("this host's worker") : `fix ${envValueShown(shellRaw)}, or point ${spec.key} at a file that loads`,
3688
4425
  });
3689
4426
  }
3690
4427
  } else if (spec.defaultsToScaffold) {
@@ -3698,6 +4435,7 @@ export async function collectChecks(shellVars, seams) {
3698
4435
  const verdict = loadVerdict(spec, scaffolded, cwd, seamsForLoad, platform);
3699
4436
  if (!verdict.ok) {
3700
4437
  checks.push({
4438
+ id: bootFileId(spec),
3701
4439
  ok: false,
3702
4440
  label: `${spec.key} is unset, so ${spec.unsetMeans}, and it does not load: the worker ${spec.fails}: ${verdict.reason}`,
3703
4441
  fix: `fix ${envValueShown(scaffolded)}, or empty its "endpoints" list`,
@@ -3733,6 +4471,7 @@ export async function collectChecks(shellVars, seams) {
3733
4471
  // dead folder by one line and a bare repo by the other.
3734
4472
  const folderOnly = (s) => scopeFormOf(s) !== "qualified" && (s.startsWith("/") || s.startsWith("./") || s.startsWith("../") || s.includes("\\") || !s.includes("/") || /^[A-Za-z]:/.test(s));
3735
4473
 
4474
+ section("limits");
3736
4475
  // The dead-scope advisory (issue #242), honest about what doctor can actually judge. A forge repo
3737
4476
  // always contains "/" and never begins "/", "./" or "../" or carries a backslash, so a scope in any
3738
4477
  // of THOSE shapes can only ever be a folder -- and a folder row that matches no trigger's canonical
@@ -3767,11 +4506,26 @@ export async function collectChecks(shellVars, seams) {
3767
4506
  if (projectFacts.parseError === null) checks.push(...projectRowChecks(scopedLimitFacts.limits, projectFacts.projects, scopedLimitFacts.path));
3768
4507
  }
3769
4508
 
4509
+ section("envelope");
3770
4510
  // Issue #504 part B: the envelope's advisories, on the file the service names, when it loads (a file that does not is
3771
4511
  // the BOOT_FILES line's). Warnings only: the worker boots on both.
3772
4512
  const envelopeFactsHere = readEnvelopeFacts(env);
3773
4513
  if (envelopeFactsHere.envelope) checks.push(...envelopeChecks(envelopeFactsHere.envelope, envelopeFactsHere.projects, envelopeFactsHere.maxCostMicros));
3774
4514
 
4515
+ section("console");
4516
+ // Issue #640: the operator console, judged with its keys resolved by the console's own rule (this shell's value, else
4517
+ // the deployment `.env`'s; DOCTOR_SHELL_KEYS). This shell's values are the ones `env` already carries (the resolution
4518
+ // starts from a copy of this shell), so nothing here reads the shell a second way; and the resolution is apart from the
4519
+ // service record, so a console key is never reported as a service's.
4520
+ const consoleShell = Object.fromEntries(CONSOLE_ENV_KEYS.filter((k) => Object.hasOwn(env, k)).map((k) => [k, env[k]]));
4521
+ const consoleEnv = { ...env, ...resolveServiceEnv({ env: consoleShell, file: serviceEnvFile, keys: CONSOLE_ENV_KEYS }).env };
4522
+ const consoleLines = consoleChecks(consoleEnv, { cwd, home, platform, folders, skillsDirs });
4523
+ checks.push(...consoleLines);
4524
+ // Issue #708: whether a service keeps the console running, and whether it answers. Only for a deployment that has a
4525
+ // console at all (the lines above), so a deployment that never set one up meets no probe.
4526
+ if (consoleLines.length > 0) checks.push(...(await consoleServiceChecks(consoleEnv, { ...seams, cwd, home, platform })));
4527
+
4528
+ section("limits");
3775
4529
  // Issue #498: a BARE repo scope (`acme/web`) matches that repo on every forge, so with triggers on more than one forge
3776
4530
  // kind a bare row is one cap (one lease, one count) shared by GitHub's acme/web and Forgejo's, and a bare pause window
3777
4531
  // pauses both. That may be meant, so this is a WARNING naming the qualified spellings, never a failure: refusing bare
@@ -3791,6 +4545,7 @@ export async function collectChecks(shellVars, seams) {
3791
4545
  }
3792
4546
  }
3793
4547
 
4548
+ section("dirs");
3794
4549
  // Issue #464: the jobs dir is this account's to write. PI_JOBS_DIR, PI_SANDBOX_DIR and TMPDIR as the service reads them
3795
4550
  // (TMPDIR in .env is a documented way out of a squatted default root, so doctor judges the root the service will use).
3796
4551
  let dirRefused = false;
@@ -3827,14 +4582,18 @@ export async function collectChecks(shellVars, seams) {
3827
4582
  checks.push(...sandboxTombstoneChecks(sandboxDir, kept));
3828
4583
  }
3829
4584
 
4585
+ section("state");
4586
+ // Issue #761: how long the console audit trail is kept and how many runs the shared run index holds, each a ✗ where
4587
+ // the worker refuses to boot on its value (`WORKER_INT_SETTINGS`).
4588
+ checks.push(...workerIntSettingChecks(env, (key) => fromFileNote(fileSays(key))));
3830
4589
  // issue #290. The two DURABLE stores -- the run history everything folds over, and the overlay holding
3831
4590
  // every cap the operator tuned from the panel -- used to default under the OS temp dir, which macOS
3832
4591
  // sweeps on its own schedule and which is tmpfs (RAM) on several Linux distros. They now default under
3833
4592
  // ~/.pi-dispatch, so this block is normally one green line; it warns only when a path RESOLVES under a
3834
4593
  // temp dir, which after the move means an operator put it there.
3835
4594
  //
3836
- // Deliberately NOT checked HERE: PI_JOBS_DIR, PI_SANDBOX_DIR and PI_GRAPH_DIR. Those are per-run,
3837
- // retention-bounded and regenerable respectively, and they stay under temp on purpose. Warning about a
4595
+ // Deliberately NOT checked HERE: PI_JOBS_DIR and PI_SANDBOX_DIR. Those are per-run and
4596
+ // retention-bounded respectively, and they stay under temp on purpose. Warning about a
3838
4597
  // directory that is SUPPOSED to be swept is how an operator learns to skim this section, which costs
3839
4598
  // more than it buys. Whose the jobs dir is, is checked above (`jobsDirChecks`, issue #464): that is a
3840
4599
  // different question, and the one that failed every job of a second account on a shared host.
@@ -3914,22 +4673,51 @@ export async function collectChecks(shellVars, seams) {
3914
4673
  // become invalid on upgrade: a duplicate key, which used to take the last value, is now refused. The reason names
3915
4674
  // keys only, never values. Absent is the normal empty overlay and says nothing.
3916
4675
  if (fileExists(settingsFile)) {
3917
- const overlay = readOverlay(settingsFile);
4676
+ // The writer's read (issue #761), so the keys this build does not know are named below; its verdict is the
4677
+ // worker's own (`readOverlay` is this read without the carry).
4678
+ const overlay = readOverlayDocument(settingsFile);
3918
4679
  if (overlay.invalid) {
4680
+ // Issue #761: a file written by a newer pi-dispatch is no broken file. The worker DEFERS every job
4681
+ // (newer-release) rather than refusing it, and the fix is an upgrade, never an edit or a delete, which would
4682
+ // lose what the newer release wrote. The one exception is a `version` an operator wrote by hand (earlier
4683
+ // releases ignored the key): no release wrote that file, so removing the key is the fix.
4684
+ const newer = overlay.newer === true;
3919
4685
  checks.push({
4686
+ // Named (issue #712): the console quotes it beside "the settings overlay does not load".
4687
+ id: "settings.overlay",
3920
4688
  ok: false,
3921
- label: `settings overlay ${settingsFile} is invalid (${overlay.invalid}) -- the worker refuses every job as settings-overlay-invalid until it is fixed, and the panel refuses to write over it`,
4689
+ label: newer
4690
+ ? `settings overlay ${settingsFile} cannot be read here (${overlay.invalid}) -- the worker defers every job (newer-release) until it is upgraded, and the panel refuses to write over it`
4691
+ : `settings overlay ${settingsFile} is invalid (${overlay.invalid}) -- the worker refuses every job as settings-overlay-invalid until it is fixed, and the panel refuses to write over it`,
3922
4692
  // The fix follows the reason: only a duplicate key gets the upgrade note, since only it loaded before #501.
3923
- fix: /duplicate key/.test(overlay.invalid)
3924
- ? "remove the repeated key from that file, keeping the value you mean (a duplicate key is refused since issue #501; it used to take the last value), or delete the file to start from an empty overlay"
3925
- : "fix what the reason names in that file, or delete the file to start from an empty overlay",
4693
+ fix: newer
4694
+ ? newerFileFix("this worker")
4695
+ : /duplicate key/.test(overlay.invalid)
4696
+ ? "remove the repeated key from that file, keeping the value you mean (a duplicate key is refused since issue #501; it used to take the last value), or delete the file to start from an empty overlay"
4697
+ : "fix what the reason names in that file, or delete the file to start from an empty overlay",
3926
4698
  });
3927
4699
  } else {
4700
+ // Issue #761: the keys this build does not know, which the worker ignores and every writer from issue #761's
4701
+ // release on keeps. An earlier panel or console (4.3.1 included) drops every key it does not know when it writes
4702
+ // the file (`secretBundles` included, which it predates), so the fix says to upgrade those first. NAMES only,
4703
+ // sorted and capped, never a value.
4704
+ const unknown = [...(overlay.carry?.unknownKeys ?? [])].map((key) => printable(key).slice(0, UNKNOWN_KEY_NAME_MAX)).sort();
4705
+ if (unknown.length > 0) {
4706
+ const shown = unknown.slice(0, UNKNOWN_KEYS_SHOWN);
4707
+ const more = unknown.length - shown.length;
4708
+ checks.push({
4709
+ id: "settings.unknown-keys",
4710
+ ok: false,
4711
+ warn: true,
4712
+ label: `settings overlay ${settingsFile} holds ${unknown.length === 1 ? "a key" : `${unknown.length} keys`} this build does not know (${shown.join(", ")}${more > 0 ? `, and ${more} more` : ""}): the worker ignores ${unknown.length === 1 ? "it" : "them"}`,
4713
+ fix: "a key from a newer release is ignored here and kept by every panel and console from 5.0.0 on, but an earlier one (4.3.1 included) drops every key it does not know when it writes this file, secretBundles included, so upgrade every panel and console first; a misspelt key is kept too, so remove it if it is a typo",
4714
+ });
4715
+ }
3928
4716
  // Issue #501 (PR #542's review): a VALID overlay can still break the dollar invariant once merged over env
3929
4717
  // (a window in one, no maxCostUsd in either), which the worker checks per job and answers by refusing every
3930
4718
  // job. The env-only half is `dollarChecks`; this is the merged half, said only when env alone is fine.
3931
4719
  const merged = overlayDollarProblem(overlay.overlay, env);
3932
- if (merged) checks.push({ ok: false, label: `settings overlay ${settingsFile}: ${merged} -- the worker refuses every job as settings-overlay-invalid`, fix: "set maxCostUsd in the overlay (or PI_MAX_COST_USD in .env), or remove the dollar window" });
4720
+ if (merged) checks.push({ id: "settings.overlay-dollars", ok: false, label: `settings overlay ${settingsFile}: ${merged} -- the worker refuses every job as settings-overlay-invalid`, fix: "set maxCostUsd in the overlay (or PI_MAX_COST_USD in .env), or remove the dollar window" });
3933
4721
  }
3934
4722
  }
3935
4723
  // PR #549's review: the scoped-limits dollar rows against the deployment's per-job cap, env and overlay merged
@@ -3992,7 +4780,29 @@ export async function collectChecks(shellVars, seams) {
3992
4780
  });
3993
4781
  }
3994
4782
  }
3995
-
4783
+ // Issue #761: a store an older release left in a shape this build no longer writes (older-state.mjs), one warning per
4784
+ // finding, each published under this one id (a second is `state.older-2`, `assignCheckIds`). The id is set here, never
4785
+ // in that module, so it is written at one site. The three older-location hints above keep their own words and places.
4786
+ // The container is judged as `up` judges it (`upValkeyContainerImage`): this deployment's, in a folder not handed to
4787
+ // compose, and only where VALKEY_URL names this host, the one place `up` runs a Valkey. The hand-over is read as `up`
4788
+ // reads it, by the override's presence; null where it cannot be, which names no container.
4789
+ // Only where the `.env` reads cleanly through the reader `up` judges its Valkey by (`readValkeyKeys`, under
4790
+ // `deploymentValkeyEnv`), from the file's bytes, and its VALKEY_URL, where it sets one, is the URL judged here. Not
4791
+ // when that reader errors, this shell's VALKEY_URL set or not: under systemd, a NUL or invalid UTF-8 anywhere in the
4792
+ // file (it loads none of it), or, in a file that spells one of its three Valkey keys, a line the service's loader reads
4793
+ // differently or one of those keys on a line it cannot read. `up` refuses each of those on Linux, and elsewhere judges
4794
+ // this shell's value or the default in the file's place. Nor when the file's VALKEY_URL is not `valkeyUrl` (this
4795
+ // shell sets another, which `up` refuses everywhere). Either way the port judged may not be the one the service
4796
+ // dials, and the fix's `pi-dispatch up` would start no Valkey, so the container is not asked about at all.
4797
+ const upValkeyRead = serviceEnvFile ? readValkeyKeys(serviceEnvFile.raw ?? serviceEnvFile.text, { loader: serviceEnvFile.loader, path: serviceEnvFile.path }) : { keys: {} };
4798
+ const valkeyUrlRead = !upValkeyRead.error && (!Object.hasOwn(upValkeyRead.keys, "VALKEY_URL") || upValkeyRead.keys.VALKEY_URL === valkeyUrl);
4799
+ const valkeyContainer = valkeyContainerReader({ spawn, runTimeouts, asked: localUsed && dockerCode === 0 && valkeyUrlRead, cwd, valkeyUrl });
4800
+ const handedOver = typeof fileExists === "function" && typeof cwd === "string" && cwd !== "" ? Boolean(fileExists(join(cwd, COMPOSE_VALKEY_OVERRIDE))) : null;
4801
+ for (const f of await olderStateOf(seams, { cwd, home, valkeyContainer, handedOver })) {
4802
+ checks.push({ id: "state.older", ok: false, warn: true, label: f.label, fix: f.fix });
4803
+ }
4804
+
4805
+ section("env");
3996
4806
  // Issue #471: what a key resolved above this point (the provider's variables, the PAT) added to the record.
3997
4807
  checks.push(...serviceEnvLines({ fromFile: {}, disagreements: service.disagreements.slice(saidAtTop.disagreements), unread: service.unread.slice(saidAtTop.unread) }, envPathShown));
3998
4808
  // Issue #471 (gate round 1): a key only this shell sets was taken in silence. Where a service for this folder is
@@ -4017,6 +4827,7 @@ export async function collectChecks(shellVars, seams) {
4017
4827
  const { hazard } = serviceEnvFile;
4018
4828
  checks.push({ ok: false, label: `${serviceEnvFile.path} line ${hazard.line} ${hazard.what}, so doctor read none of ${service.hazardSkipped.join(", ")} from it and judged this shell's values (or the defaults) instead: the service's own are unknown`, fix: hazard.fix });
4019
4829
  }
4830
+ tagSection(checks, currentSection);
4020
4831
  return checks;
4021
4832
  }
4022
4833
 
@@ -4436,7 +5247,8 @@ function nodeCheck(version) {
4436
5247
  * that every image a trigger names is actually on this host -- with `--pull=never` nothing will fetch one at
4437
5248
  * job time, so this is the only warning that arrives BEFORE the trigger fires at 03:00.
4438
5249
  *
4439
- * `optingOut` counts `run.packages: false` -- the only thing that now withholds the staged set from a job.
5250
+ * `optingOut` counts `run.packages: false` -- the only thing that withholds the whole staged set from a job. `run.excludeExtensions`
5251
+ * withholds one package at a time, and `excludedNames` holds those names.
4440
5252
  * `requiring` counts explicit `run.packages: true`, which arms nothing any more but is still an operator
4441
5253
  * asserting "this flow needs those packages"; that assertion is what makes an empty stage a hard failure.
4442
5254
  *
@@ -4638,6 +5450,245 @@ function readProjectFacts(env, fileExists) {
4638
5450
  }
4639
5451
  }
4640
5452
 
5453
+ // `sun_path` sizes, NUL terminator included, as the console's own `parseListen` (admin/src/console/listen.mjs) holds
5454
+ // them; doctor-console.test.mjs compares the two parsers' verdicts, since the worker cannot import the admin.
5455
+ const CONSOLE_SUN_PATH = { darwin: 104, freebsd: 104, openbsd: 104, netbsd: 104, linux: 108 };
5456
+ const CONSOLE_LOOPBACK = new BlockList();
5457
+ CONSOLE_LOOPBACK.addSubnet("127.0.0.0", 8, "ipv4");
5458
+ CONSOLE_LOOPBACK.addAddress("::1", "ipv6");
5459
+
5460
+ /**
5461
+ * PI_CONSOLE_LISTEN as the console parses it: `{ shown, loopback }` or `{ refusal }`. IP literals only (`ip:port`,
5462
+ * `[ipv6]:port`) or `unix:/abs/path` within the platform's socket path size; loopback is 127.0.0.0/8 and ::1. Unset or
5463
+ * empty is the default, 127.0.0.1:4790. The non-loopback refusal is the caller's (it depends on PI_CONSOLE_BIND_PUBLIC).
5464
+ */
5465
+ export function consoleListenOf(value, platform = process.platform) {
5466
+ const text = typeof value === "string" ? value.trim() : "";
5467
+ if (text === "") return { shown: "127.0.0.1:4790 (the default)", loopback: true };
5468
+ if (text.startsWith("unix:")) {
5469
+ const path = text.slice("unix:".length);
5470
+ if (!isAbsolute(path)) return { refusal: "a unix socket path must be absolute: write unix:/abs/path" };
5471
+ const limit = CONSOLE_SUN_PATH[platform] ?? 108;
5472
+ if (Buffer.byteLength(path) >= limit) return { refusal: `the unix socket path is ${Buffer.byteLength(path)} bytes, and this platform allows at most ${limit - 1}: choose a shorter path` };
5473
+ return { shown: text, loopback: true };
5474
+ }
5475
+ const m = /^(?:\[([^\]]*)\]|([^:[\]]*)):([0-9]{1,5})$/.exec(text);
5476
+ if (!m || Number(m[3]) > 65535) return { refusal: "it is not ip:port, [ipv6]:port or unix:/abs/path (the port a number from 0 to 65535)" };
5477
+ const host = m[1] ?? m[2];
5478
+ if (m[1] !== undefined ? !isIPv6(host) : !isIPv4(host)) return { refusal: `${host} is not an IP literal; a hostname can resolve anywhere, so write 127.0.0.1 or [::1]` };
5479
+ const loopback = CONSOLE_LOOPBACK.check(host, m[1] !== undefined ? "ipv6" : "ipv4");
5480
+ return { shown: text, loopback };
5481
+ }
5482
+
5483
+ /**
5484
+ * Issue #761: the worker settings read with `config.mjs`'s `nonNegativeInt` or `boundedInt` whose bad value doctor
5485
+ * names, by that same rule (unset or empty is the default; any other value must be exactly the integer, spaces around
5486
+ * it allowed, inside the bounds): a value the worker refuses to boot on (exit 2, a configuration error naming the key)
5487
+ * fails here too, and nothing else does. `want` is the loader's own phrase for the rule.
5488
+ */
5489
+ export const WORKER_INT_SETTINGS = Object.freeze({
5490
+ PI_CONSOLE_AUDIT_RETENTION_DAYS: Object.freeze({ min: 0, max: undefined, want: "a non-negative integer", fix: "set it to a whole number of days (0 keeps the console audit trail forever), or delete the line so the trail is kept as long as PI_LOG_RETENTION_DAYS keeps run history" }),
5491
+ PI_RUN_MIRROR_MAX_RUNS: Object.freeze({ min: RUN_MIRROR_MAX_RUNS_MIN, max: RUN_MIRROR_MAX_RUNS_MAX, want: `an integer ${RUN_MIRROR_MAX_RUNS_MIN}-${RUN_MIRROR_MAX_RUNS_MAX}`, fix: `set it to a whole number from ${RUN_MIRROR_MAX_RUNS_MIN} to ${RUN_MIRROR_MAX_RUNS_MAX}, or delete the line for the default (${RUN_MIRROR_MAX_RUNS_DEFAULT})` }),
5492
+ });
5493
+
5494
+ /** Whether `raw` is a value `config.mjs`'s `boundedInt` takes for `rule` (see `WORKER_INT_SETTINGS`). */
5495
+ function workerIntAccepted(raw, { min, max }) {
5496
+ if (raw === undefined || raw === "") return true;
5497
+ const n = Number.parseInt(raw, 10);
5498
+ return Number.isInteger(n) && n >= min && (max === undefined || n <= max) && String(n) === String(raw).trim();
5499
+ }
5500
+
5501
+ /**
5502
+ * A ✗ for each `WORKER_INT_SETTINGS` key `env` sets to a value the worker refuses to boot on; `note(key)` says where it
5503
+ * came from. The keys are the table's own, so a setting added there is judged here with nothing else to change.
5504
+ */
5505
+ export function workerIntSettingChecks(env, note = () => "") {
5506
+ return Object.entries(WORKER_INT_SETTINGS)
5507
+ .filter(([key, rule]) => !workerIntAccepted(env[key], rule))
5508
+ .map(([key, rule]) => ({ ok: false, label: `${key} is ${quotedShown(env[key])}, which is not ${rule.want}: the worker refuses to boot on it (exit 2)${note(key)}`, fix: rule.fix }));
5509
+ }
5510
+
5511
+ /**
5512
+ * The console's lines (issue #640, REQ-CONSOLE-SECURITY). NONE for a deployment that never set the console up: no
5513
+ * tokens file at the resolved path (nothing at all there, by lstat) and no PI_CONSOLE_* key set. Otherwise:
5514
+ * - the tokens file as the console reads it (`readTokensFile`: owner-only regular file, valid), ✗ with its own fix;
5515
+ * - at least one operator token, ✗ (with none, nobody can change anything from the console);
5516
+ * - the tokens file outside every path a job container can see, ✗: a local trigger's run.folder is bind-mounted
5517
+ * read-write, so a job there could read the file or add a token of its own. Judged by `envelopeInsideJobPaths`, the
5518
+ * envelope's identity-based containment check (a firmlink or bind alias of a folder is caught), on the file's real
5519
+ * path, with the local folders, skills dirs, absolute run roots and the overlay;
5520
+ * - entries kept for a role this release does not know (issue #761, `keptTokens`), ⚠: a newer release writes such
5521
+ * entries, and a console of this release signs them in nowhere;
5522
+ * - PI_CONSOLE_LISTEN parseable (✗, the console refuses to start) and PI_CONSOLE_BIND_PUBLIC=1 (⚠, plain HTTP);
5523
+ * - the audit chain (`verifyConsoleAudit`), ⚠ when broken, nothing while the log holds no row; an intact chain with
5524
+ * rows whose shaped action or outcome this release does not know (issue #761, `unknown`; a newer console writes
5525
+ * such rows) is still ok, and its line counts them.
5526
+ * `env` must already carry the console keys resolved (`collectChecks` does it). Seams: `cwd` (the deployment folder),
5527
+ * `fs`, `uid`, `home`, `platform`, `folders` (canonical local run.folders), `skillsDirs`, `realpath`.
5528
+ */
5529
+ export function consoleChecks(env, { cwd = process.cwd(), fs = nodeFs, uid = process.geteuid?.(), home, platform = process.platform, folders = [], skillsDirs = [], realpath = realpathSync.native } = {}) {
5530
+ const path = tokensFilePath({ PI_CONSOLE_TOKENS_FILE: env.PI_CONSOLE_TOKENS_FILE }, cwd);
5531
+ let present = true;
5532
+ try {
5533
+ fs.lstatSync(path);
5534
+ } catch {
5535
+ present = false;
5536
+ }
5537
+ const keysSet = CONSOLE_ENV_KEYS.filter((k) => typeof env[k] === "string" && env[k] !== "");
5538
+ if (!present && keysSet.length === 0) return [];
5539
+ const checks = [];
5540
+ const shownPath = quotedShown(path);
5541
+ const read = readTokensFile({ path, fs, uid });
5542
+ if (read.refusal) {
5543
+ checks.push({ ok: false, label: `console: the tokens file ${shownPath} cannot be used, so \`pi-dispatch-console serve\` refuses to start`, fix: escapeControls(read.refusal) });
5544
+ } else {
5545
+ const operators = operatorCount(read.file);
5546
+ const viewers = read.file.tokens.length - operators;
5547
+ if (operators === 0) {
5548
+ checks.push({ ok: false, label: `console: the tokens file ${shownPath} holds no operator token, so nobody can make a change from the console`, fix: "run `pi-dispatch-console token add --name <you> --role operator`" });
5549
+ }
5550
+ const inside = consoleTokensInsideJobPaths(path, env, { cwd, fs, folders, skillsDirs, realpath });
5551
+ if (inside.problem) {
5552
+ checks.push({ ok: false, label: `console: the tokens file ${shownPath} ${inside.problem}`, fix: inside.fix });
5553
+ } else if (operators > 0) {
5554
+ checks.push({ ok: true, label: `console: tokens file ${shownPath} is owner-only and outside every job folder (${operators} operator${operators === 1 ? "" : "s"}, ${viewers} viewer${viewers === 1 ? "" : "s"})` });
5555
+ }
5556
+ // Issue #849: the remembered devices, which sit beside the tokens file and are as sensitive as it is about who may sign in.
5557
+ const devicesDir = consoleDevicesDir(path);
5558
+ const devices = devicesState({ dir: devicesDir, fs, uid, platform });
5559
+ if (devices.problem) {
5560
+ checks.push({ ok: false, label: "console: the remembered-device folder cannot be used, so a remembered browser must sign in again", fix: escapeControls(devices.problem) });
5561
+ } else if (!devices.absent) {
5562
+ const devicesInside = consoleTokensInsideJobPaths(devicesDir, env, { cwd, fs, folders, skillsDirs, realpath, directory: true });
5563
+ if (devicesInside.problem) checks.push({ ok: false, label: `console: the remembered-device folder ${quotedShown(devicesDir)} ${devicesInside.problem}`, fix: devicesInside.fix });
5564
+ if (devices.unreadable > 0) checks.push({ ok: false, label: `console: ${devices.unreadable} remembered-device record${devices.unreadable === 1 ? "" : "s"} in ${quotedShown(devicesDir)} cannot be read, and those browsers must sign in again`, fix: `if a newer pi-dispatch wrote ${devices.unreadable === 1 ? "it" : "them"}, upgrade this host; otherwise remove the file${devices.unreadable === 1 ? "" : "s"} whose name${devices.unreadable === 1 ? " starts" : "s start"} with ${devices.unreadableIds.slice(0, 5).join(", ")} from that folder` });
5565
+ }
5566
+ const kept = keptTokens(read.file).length;
5567
+ if (kept > 0) {
5568
+ const said = kept === 1 ? "1 token carries a role this pi-dispatch does not know, so a console of this release signs it in nowhere" : `${kept} tokens carry a role this pi-dispatch does not know, so a console of this release signs them in nowhere`;
5569
+ checks.push({ ok: false, warn: true, label: `console: ${said}`, fix: "upgrade pi-dispatch and the console" });
5570
+ }
5571
+ }
5572
+ const listen = consoleListenOf(env.PI_CONSOLE_LISTEN, platform);
5573
+ const bindPublic = env.PI_CONSOLE_BIND_PUBLIC === "1";
5574
+ if (listen.refusal) {
5575
+ checks.push({ ok: false, label: `console: PI_CONSOLE_LISTEN ${quotedShown(env.PI_CONSOLE_LISTEN)} cannot be used, so \`pi-dispatch-console serve\` refuses to start: ${listen.refusal}`, fix: "write 127.0.0.1:4790, [::1]:4790 or unix:/abs/path, or unset PI_CONSOLE_LISTEN for the default" });
5576
+ } else if (!listen.loopback && !bindPublic) {
5577
+ checks.push({ ok: false, label: `console: PI_CONSOLE_LISTEN ${quotedShown(env.PI_CONSOLE_LISTEN)} is not a loopback address, so \`pi-dispatch-console serve\` refuses to start`, fix: "listen on 127.0.0.1, [::1] or a unix: socket and reach it with ssh -L; or, to accept plain HTTP on a network, set PI_CONSOLE_BIND_PUBLIC=1" });
5578
+ } else {
5579
+ checks.push({ ok: true, label: `console: listens on ${escapeControls(listen.shown)}` });
5580
+ }
5581
+ // Only on an address that really is not loopback: PI_CONSOLE_BIND_PUBLIC=1 alone changes nothing about where a loopback console's cookies travel.
5582
+ if (bindPublic && !listen.refusal && !listen.loopback) {
5583
+ const devices = devicesState({ dir: consoleDevicesDir(path), fs, uid, platform });
5584
+ if (devices.live > 0) checks.push({ ok: false, warn: true, label: `console: ${devices.live} remembered device${devices.live === 1 ? "" : "s"} on a console that listens on a non-loopback address, where cookies cross the network in plain HTTP`, fix: "listen on a loopback address and reach the console through a tunnel, or put it behind a proxy that terminates TLS" });
5585
+ }
5586
+ if (bindPublic) {
5587
+ checks.push({ ok: false, warn: true, label: "console: PI_CONSOLE_BIND_PUBLIC=1 lets the console listen on a non-loopback address, where tokens and session cookies cross the network in plain HTTP", fix: "keep it only behind a TLS proxy on a network you trust; otherwise unset PI_CONSOLE_BIND_PUBLIC, listen on 127.0.0.1, [::1] or a unix: socket, and reach it with ssh -L" });
5588
+ }
5589
+ const logsDir = logsDirPath(env, home);
5590
+ const audit = verifyConsoleAudit({ logsDir, fs });
5591
+ if (!audit.ok) {
5592
+ const where = audit.broken.file === null ? "" : ` at ${audit.broken.file} line ${audit.broken.line}`;
5593
+ checks.push({ ok: false, warn: true, label: `console: the audit log chain is broken${where}: ${escapeControls(audit.broken.reason)}`, fix: `a row was changed, removed or moved after it was written, or the file was damaged. Keep a copy of ${join(logsDir, "console-audit")} for review; \`pi-dispatch-console audit verify\` names the same link, and a damaged LAST line makes the console refuse every write until that file is moved aside` });
5594
+ } else if (audit.rows > 0) {
5595
+ const start = audit.startsAt ? `, starting at seq ${audit.startsAt.seq} in ${audit.startsAt.file} (older rows reaped)` : "";
5596
+ // Issue #761: what the check knows of such rows, that their words are unknown here and shaped, never who wrote them.
5597
+ // Last, since its colon would otherwise run into the start's clause.
5598
+ const unknown = audit.unknown > 0 ? `, ${audit.unknown} not known to this pi-dispatch: a newer console writes such rows` : "";
5599
+ checks.push({ ok: true, label: `console: audit log chain intact (${audit.rows} row${audit.rows === 1 ? "" : "s"}${start}${unknown})` });
5600
+ }
5601
+ return checks;
5602
+ }
5603
+
5604
+ /** The console's service name on Windows, where nssm keeps one machine-scoped service per name (service.mjs). */
5605
+ const CONSOLE_NSSM_SERVICE = "pi-dispatch-console";
5606
+
5607
+ /**
5608
+ * The console service unit installed for the deployment in `cwd` (issue #708): `{ path }` (the unit file, or the nssm
5609
+ * service's name on win32), else null. Read as the worker's unit is (`installedWorkerUnit`): a unit FILE whose
5610
+ * WorkingDirectory is this folder (`readUnitSeam`), in either scope; on win32 the nssm service by name, since nssm
5611
+ * keeps the folder apart (AppDirectory) and there is one such service per machine.
5612
+ */
5613
+ async function installedConsoleUnit({ platform, home, cwd, fileExists, readUnit = (path) => readFileSync(path, "utf8"), spawn }) {
5614
+ if (platform === "win32") {
5615
+ if (typeof spawn !== "function") return null;
5616
+ const got = await runCmdCapture(spawn, "nssm", ["status", CONSOLE_NSSM_SERVICE]);
5617
+ return got.code === 0 ? { path: CONSOLE_NSSM_SERVICE } : null;
5618
+ }
5619
+ const path = installedConsoleUnitPath({ platform, home, cwd, fileExists, readUnit });
5620
+ return path === null ? null : { path };
5621
+ }
5622
+
5623
+ /**
5624
+ * The console's service lines (issue #708): whether a service unit keeps the console of this deployment running, and
5625
+ * whether the console answers (`probeConsole`: one GET /healthz to the loopback address or the socket it binds, 1 s).
5626
+ * - a unit installed and the console answering: ✓;
5627
+ * - a unit installed and nothing answering: ✗, since the service exists to keep it answering (`serve` exits 2 on a
5628
+ * refusal and the unit then stays stopped, so the unit's log says which);
5629
+ * - no unit and nothing answering: ⚠, with the install command;
5630
+ * - no unit and the console answering: ✓, saying it was started by hand and stops with its terminal;
5631
+ * - an address the probe may not or cannot ask (port 0, a non-loopback bind): the unit line alone, and why the
5632
+ * answer is not known.
5633
+ * NOTHING when the console could not start on its listen address at all: `consoleChecks` already fails that line, and a
5634
+ * second line saying it does not answer would be the same fact twice. `env` carries the console keys resolved as
5635
+ * `collectChecks` resolves them; no other key is read. Seams: `consoleProbe(env)`, `fileExists`, `readUnit`, `spawn`.
5636
+ */
5637
+ export async function consoleServiceChecks(env, seams = {}) {
5638
+ const { platform = process.platform, cwd = process.cwd() } = seams;
5639
+ const listen = consoleListenOf(env.PI_CONSOLE_LISTEN, platform);
5640
+ if (listen.refusal || (!listen.loopback && env.PI_CONSOLE_BIND_PUBLIC !== "1")) return [];
5641
+ const unit = await installedConsoleUnit({ ...seams, platform, cwd, fileExists: seams.fileExists ?? existsSync });
5642
+ const probe = seams.consoleProbe ?? (async (e) => (await import("./console-probe.mjs")).probeConsole(e));
5643
+ let answer;
5644
+ try {
5645
+ answer = await probe(env);
5646
+ } catch (err) {
5647
+ answer = { state: "unknown", reason: `the probe failed (${escapeControls(err?.message ?? String(err))})` };
5648
+ }
5649
+ const at = answer.target ? ` on ${escapeControls(answer.target)}` : "";
5650
+ const why = answer.reason ? ` (${escapeControls(answer.reason)})` : "";
5651
+ const unitShown = unit ? quotedShown(unit.path) : null;
5652
+ const logs = platform === "linux" ? "`journalctl --user -u pi-dispatch-console` (or without --user for a system unit)" : platform === "darwin" ? `${join(cwd, "logs", "console.err.log")}` : `${join(cwd, "logs", "console.err.log")} and \`nssm status ${CONSOLE_NSSM_SERVICE}\``;
5653
+ if (answer.state === "unknown") {
5654
+ return [{ ok: true, label: `console: ${unit ? `the service ${unitShown} serves this deployment; ` : "no service unit keeps it running; "}whether it answers is not checked${why}` }];
5655
+ }
5656
+ if (unit && answer.state === "running") return [{ ok: true, label: `console: the service ${unitShown} keeps it running, and it answers${at}` }];
5657
+ if (unit) {
5658
+ const lock = join(logsDirPath(env, seams.home), "console-audit", ".console.lock");
5659
+ return [{ ok: false, label: `console: the service ${unitShown} is installed for this deployment, but nothing answers${at}${why}`, fix: `\`pi-dispatch service status --console\` says whether it runs, and ${logs} says why it stopped: \`pi-dispatch-console serve\` exits 2 on a refusal (no operator token, the lock held by another console, an address in use), and the unit then stays stopped until it is started again (\`pi-dispatch service start --console\`). After a crash the lock ${escapeControls(lock)} can name a pid another process has since taken, which keeps every start refusing: when that pid is not a console, remove the lock, then start the unit` }];
5660
+ }
5661
+ if (answer.state === "running") return [{ ok: true, label: `console: answers${at}, started by hand (no service unit for this deployment, so it stops with the terminal that runs it)` }];
5662
+ return [{ ok: false, warn: true, label: `console: not running${at}${why}, and no service unit keeps it running`, fix: "`pi-dispatch service install --console` keeps it running (it needs an operator token); or start it in a terminal with `pi-dispatch-console serve`" }];
5663
+ }
5664
+
5665
+ /**
5666
+ * Whether a job container can see the console tokens file: `{}` or `{ problem, fix }`. The file's REAL path is judged
5667
+ * (the containment check requires a canonical path, and the console reads whatever the configured one resolves to). A
5668
+ * second hard link is refused as the envelope's is: another name of the file could sit in a job folder unseen. A
5669
+ * relative run root is skipped here (the envelope refuses one; the console has no such rule to borrow), and a path
5670
+ * that cannot be judged is said, not passed.
5671
+ */
5672
+ function consoleTokensInsideJobPaths(path, env, { cwd, fs, folders, skillsDirs, realpath, directory = false }) {
5673
+ const fix = "move the tokens file out of every local trigger's run.folder and run.skillsDir, every PI_DISPATCH_RUN_ROOTS root and PI_GLOBAL_PI_DIR, and point PI_CONSOLE_TOKENS_FILE at its new path";
5674
+ try {
5675
+ const st = fs.statSync(path);
5676
+ // A folder always has more than one link (its own name, `.`, and each child's `..`), so the count says nothing about one.
5677
+ if (!directory && st.nlink > 1) return { problem: `has ${st.nlink} hard links: another name of the file could sit inside a folder a job can see, so keep exactly one`, fix: `remove the other names (\`find / -samefile ${path}\` lists them)` };
5678
+ const real = realpath(path);
5679
+ const runRoots = delimitedList(env.PI_DISPATCH_RUN_ROOTS).filter((r) => isAbsolute(r));
5680
+ const globalPiDir = typeof env.PI_GLOBAL_PI_DIR === "string" && env.PI_GLOBAL_PI_DIR !== "" ? env.PI_GLOBAL_PI_DIR : null;
5681
+ // PWD comes from the process environment inside the check, as on doctor's envelope load (`loadEnvelopeChecked`).
5682
+ const inside = envelopeInsideJobPaths(real, { cronFolders: folders, runRoots, skillsDirs, globalPiDir }, { cwd, directory });
5683
+ if (inside === null) return {};
5684
+ if (directory) return { problem: `lies inside a folder a job container can see (${quotedShown(inside.path)}): a job there could plant a remembered device`, fix: "move the tokens file and this folder out of every folder a job can see, point PI_CONSOLE_TOKENS_FILE at the new path, and remove the old folder" };
5685
+ const what = { "cron-folder": "a local trigger's run.folder", "run-root": "a PI_DISPATCH_RUN_ROOTS root", "skills-dir": "a trigger's run.skillsDir", "global-pi-dir": "PI_GLOBAL_PI_DIR" }[inside.kind] ?? inside.kind;
5686
+ return { problem: `lies inside ${what} (${quotedShown(inside.path)}), which a job container can see: a job there could read the token hashes or add a token of its own`, fix };
5687
+ } catch (err) {
5688
+ return { problem: `could not be judged against the folders a job can see (${escapeControls(err?.code ?? "the path could not be resolved")})`, fix: `make ${path} and the trigger folders readable here, then run doctor again` };
5689
+ }
5690
+ }
5691
+
4641
5692
  /**
4642
5693
  * The envelope facts (issue #504 part B): the envelope as the worker would load it, the projects and the per-job cap it
4643
5694
  * was judged against, or a parse error when `PI_ENVELOPE_FILE` is set and does not load (the BOOT_FILES line's).
@@ -4787,6 +5838,30 @@ export async function defaultReadAppliedSplit(url) {
4787
5838
  }
4788
5839
  }
4789
5840
 
5841
+ export { cooldownModelRefs } from "./model-observation.mjs";
5842
+
5843
+ /** A failed bounded read is visible, never reported as "no cooldown". */
5844
+ export async function defaultReadModelCooldowns(url, refs, options) {
5845
+ try {
5846
+ // Kept lazy like the other model checks: doctor must start even when pi cannot be imported.
5847
+ const { readModelCooldowns } = await import("./model-failover.mjs");
5848
+ return await withDoctorClient(url, (client) => boundedOp(readModelCooldowns(client, refs, options), DOCTOR_VALKEY_OP_TIMEOUT_MS));
5849
+ } catch {
5850
+ return null;
5851
+ }
5852
+ }
5853
+
5854
+ /** Warn lines are also published to the console's existing Doctor panel, with the observation's age. */
5855
+ export function modelCooldownChecks(rows) {
5856
+ if (!Array.isArray(rows)) return [{ ok: false, warn: true, label: "Model cooldowns could not be read", fix: "check Valkey and re-run doctor; failover jobs retry infrastructure failures before they spend" }];
5857
+ return rows.filter((row) => splitModelEntry(row?.ref) && ["rate-limited", "quota-exhausted", "overloaded"].includes(row.kind) && Number.isSafeInteger(row.until) && row.until >= 0 && row.until <= 253402300799999).map((row) => ({
5858
+ ok: false,
5859
+ warn: true,
5860
+ label: `Model ${row.ref} is cooling down until ${new Date(row.until).toISOString()} (${row.kind})`,
5861
+ fix: "new failover jobs skip this model until then and use only the reviewed fallback list; recovery keeps its checkpoint model",
5862
+ }));
5863
+ }
5864
+
4790
5865
  /**
4791
5866
  * A FAILURE per scoped-limits file that holds a `project:<id>` row whose id is not a project in `projects` (issue #499
4792
5867
  * part B): the worker refuses to start on it, and a live reload that would create one is kept out. Rows are named by
@@ -4807,15 +5882,24 @@ export function projectRowChecks(limits, projects, path) {
4807
5882
  /**
4808
5883
  * The pause-windows facts (issue #498): the parsed windows when PI_PAUSE_WINDOWS_FILE is set, else none. A file that
4809
5884
  * does not load is the BOOT_FILES check's line, so here it only silences the advisories that read the windows.
5885
+ * `versionNeed` (issue #761) is the version the file needs, the higher of what it declares and what its RAW windows'
5886
+ * fields need, for the fleet line that names a peer that cannot read it; 1 without a file. `versions` is the
5887
+ * `{ supported, table, valueTable }` the file is read and its need judged by (collectChecks' `versionTables`), the
5888
+ * module's own by default.
4810
5889
  */
4811
- function readPauseWindowFacts(env, fileExists) {
5890
+ function readPauseWindowFacts(env, fileExists, versions = {}) {
4812
5891
  const path = env.PI_PAUSE_WINDOWS_FILE;
4813
- if (typeof path !== "string" || path.trim() === "") return { windows: [], parseError: null };
5892
+ if (typeof path !== "string" || path.trim() === "") return { windows: [], versionNeed: 1, parseError: null };
4814
5893
  try {
4815
- if (!fileExists(path) || !statSync(path).isFile()) return { windows: [], parseError: "unreadable" };
4816
- return { windows: loadPauseWindows({ pauseWindowsFile: path }, { readFileSync, existsSync: fileExists }), parseError: null };
5894
+ if (!fileExists(path) || !statSync(path).isFile()) return { windows: [], versionNeed: 1, parseError: "unreadable" };
5895
+ // The loader's own parse (`loadPauseWindows` is this read after the existence check above), handed the versions.
5896
+ const text = readFileSync(path, "utf8");
5897
+ const windows = parsePauseWindows(text, path, versions);
5898
+ // The parse just accepted this text, so it parses, and a declared version is an integer.
5899
+ const doc = JSON.parse(text);
5900
+ return { windows, versionNeed: Math.max(Number.isSafeInteger(doc?.version) ? doc.version : 1, pauseWindowsVersionFor(doc?.windows, versions)), parseError: null };
4817
5901
  } catch (e) {
4818
- return { windows: [], parseError: e?.message ?? String(e) };
5902
+ return { windows: [], versionNeed: 1, parseError: e?.message ?? String(e) };
4819
5903
  }
4820
5904
  }
4821
5905
 
@@ -5007,6 +6091,76 @@ export function fleetSizeChecks(fileVersion, peers) {
5007
6091
  }];
5008
6092
  }
5009
6093
 
6094
+ /** The overlay keys `settings.unknown-keys` names at most (issue #761), and how much of each name it shows. */
6095
+ export const UNKNOWN_KEYS_SHOWN = 8;
6096
+ const UNKNOWN_KEY_NAME_MAX = 64;
6097
+
6098
+ /**
6099
+ * The stores a host publishes a version for (issue #761, `DES-STORE-VERSION-WHEN-NEEDED`), by registry field: what the
6100
+ * store is, what a peer does with this host's file when it publishes a LOWER version (this release's rule: it defers
6101
+ * the job, `newer-release`) and when it publishes NONE (a worker from before issue #761: it reads the file without its
6102
+ * version and drops what it does not know), and who else writes it, for the fix. A test holds the fields to the ones
6103
+ * start.mjs publishes.
6104
+ *
6105
+ * A lower peer that watches the pause windows or the triggers file defers every job from its next reload of it, not
6106
+ * only the jobs that read the file: its worker-wide newer state is read by the triggers gate at the processor's head,
6107
+ * and by the pickup's pause gate and the watch branch's (a job ended before those, by the draft-source or sandbox
6108
+ * check, a runtime's own result, a lost lock's replay or a grouping job's deleted project, spends nothing). Job data
6109
+ * is written by the receivers, the console and the workers' own builders, and a receiver publishes no registry row,
6110
+ * so its fix names the receivers as a set doctor cannot see.
6111
+ */
6112
+ export const STORE_FLEET_LINES = Object.freeze({
6113
+ settingsVersion: Object.freeze({ store: "the settings overlay", older: "defers every job (newer-release) while it reads this file", silent: "drops the overlay keys it does not know, so a cap they set does not apply on it", writers: "every panel and console that writes the settings overlay (one from before issue #761 drops a key it does not know when it writes)" }),
6114
+ pauseWindowsVersion: Object.freeze({ store: "the pause windows file", older: "defers every job (newer-release) from its next reload of this file, and refuses the file at its next start", silent: "drops the window fields it does not know, so a window pauses at the wrong time on it", writers: "every panel and console that writes the pause windows file (one from before issue #761 drops a key it does not know when it writes)" }),
6115
+ triggersVersion: Object.freeze({ store: "the triggers file", older: "defers every job (newer-release) from its next reload of this file, keeps its last good schedules, and refuses the file at its next start", silent: "drops the run keys it does not know, so a trigger's jobs run wider on it than the file says", writers: "every panel and console that writes the triggers file (one from before issue #761 drops a key it does not know when it writes)" }),
6116
+ jobDataVersion: Object.freeze({ store: "the jobs this host's triggers queue", older: "defers each such job (newer-release) until it is upgraded", silent: "drops the job fields it does not know, so such a job runs wider on it than its trigger says", writers: "every receiver and every console that queues these jobs (a receiver publishes no registry row, so doctor cannot see which receivers are older)" }),
6117
+ });
6118
+
6119
+ /**
6120
+ * The version each of this host's stores needs, by registry field (issue #761): the settings overlay (read by the
6121
+ * worker's own reader), the pause windows file and the triggers file (from the facts doctor already read), and the job
6122
+ * data their triggers queue. A store whose file does not load is left out. `settingsVersions` is the overlay's
6123
+ * `{ supported, table, valueTable }` (collectChecks' `versionTables`), the module's own by default.
6124
+ */
6125
+ export function storeVersionNeeds({ settingsFile, fileExists, pauseWindowFacts, triggersVersionNeed, jobDataVersionNeed, triggersParsed, settingsVersions = {} }) {
6126
+ const needs = {};
6127
+ const settings = fileExists(settingsFile) ? readOverlayDocument(settingsFile, settingsVersions) : { overlay: {}, carry: null };
6128
+ if (!settings.invalid) {
6129
+ const declared = settings.carry?.doc?.version;
6130
+ needs.settingsVersion = Math.max(Number.isSafeInteger(declared) ? declared : 1, settingsVersionFor(settings.overlay, settingsVersions));
6131
+ }
6132
+ if (pauseWindowFacts.parseError === null) needs.pauseWindowsVersion = pauseWindowFacts.versionNeed;
6133
+ if (triggersParsed) {
6134
+ needs.triggersVersion = triggersVersionNeed;
6135
+ needs.jobDataVersion = jobDataVersionNeed;
6136
+ }
6137
+ return needs;
6138
+ }
6139
+
6140
+ /**
6141
+ * The fleet's store versions (issue #761): for each store whose need (`needs`, registry field -> the version this host's
6142
+ * own file needs) is above 1, a WARNING naming the peers that publish that field below the need (they defer what the
6143
+ * file touches until they are upgraded) and one naming the peers that publish no such field at all (workers from before
6144
+ * the field: they read the file without its version and drop what they do not know, which can widen a job). Nothing
6145
+ * at all while every need is 1, which is a deployment whose files use nothing a table has a row for. Hosts are named,
6146
+ * never a file's content. `fleetSizeChecks` keeps its own line: a peer without `limitsVersion` still reads version 2.
6147
+ */
6148
+ export function fleetStoreVersionChecks(needs, peers) {
6149
+ const checks = [];
6150
+ const warn = (label, fix) => checks.push({ id: "fleet.store-versions", ok: false, warn: true, label, fix });
6151
+ const fix = (line, need) => `upgrade and restart the workers named, and ${line.writers}, to a release that reads version ${need}`;
6152
+ for (const [field, line] of Object.entries(STORE_FLEET_LINES)) {
6153
+ const need = needs?.[field];
6154
+ if (!Number.isSafeInteger(need) || need <= 1) continue;
6155
+ const silent = peers.filter((h) => h[field] === undefined || h[field] === null || h[field] === "");
6156
+ const older = peers.filter((h) => !silent.includes(h) && !(Number.isSafeInteger(Number(h[field])) && Number(h[field]) >= need));
6157
+ const names = (hosts) => hosts.map((h) => h.name).join(", ");
6158
+ if (older.length > 0) warn(`${names(older)} ${older.length === 1 ? "reads" : "read"} ${line.store} only below version ${need}, the version this host's file needs: ${older.length === 1 ? "it" : "each"} ${line.older}`, fix(line, need));
6159
+ if (silent.length > 0) warn(`${names(silent)} ${silent.length === 1 ? "publishes" : "publish"} no version for ${line.store} (a worker from before issue #761), while this host's file needs version ${need}: ${silent.length === 1 ? "it" : "each"} ${line.silent}`, fix(line, need));
6160
+ }
6161
+ return checks;
6162
+ }
6163
+
5010
6164
  export function fleetProjectsChecks(mine, peers) {
5011
6165
  const checks = [];
5012
6166
  const opinions = peers.filter((h) => typeof h.fpProjects === "string" && h.fpProjects !== "");
@@ -5032,72 +6186,11 @@ export function fleetProjectsChecks(mine, peers) {
5032
6186
  return checks;
5033
6187
  }
5034
6188
 
5035
- /**
5036
- * The runner's own input overhead (`BOUND_OVERHEAD_TOKENS`, image/runner/src/usage-meter.mjs), which its bound adds to
5037
- * every call. Copied, because the worker package does not ship the runner; `doctor.test.mjs` holds the two equal.
5038
- */
5039
- export const FIRST_CALL_OVERHEAD_TOKENS = 8192;
5040
- /**
5041
- * The least a job's FIRST call carries before its task, in bytes: pi 0.99.1's default system prompt (1,753 bytes) and
5042
- * the schemas of its four default tools (2,712 bytes) serialise to 4,465 bytes, and PR #542's lab measured 10,667 for
5043
- * a short task. 4,096 is below both, so the bound below stays a lower bound for a job that adds nothing.
5044
- */
5045
- export const FIRST_CALL_MIN_CONTEXT_BYTES = 4096;
6189
+ // The first-call bound moved to model-catalog.mjs (issue #800), where the console's preview can read it without loading this
6190
+ // module. Re-exported so every caller and test of doctor's own lines reads the one rule as before.
6191
+ export { FIRST_CALL_MIN_CONTEXT_BYTES, FIRST_CALL_OVERHEAD_TOKENS, boundModelOf, firstCallFloorMicros, serviceTierMultiplier };
5046
6192
 
5047
- /**
5048
- * A LOWER BOUND, in integer micro-dollars, on what the runner's cost guard (`callCostBound`) reserves for a job's
5049
- * first call on `model`, or null when this cannot say. The guard refuses a call when its bound would pass the cap, so
5050
- * a per-job cap below this number can never admit a call on the model: with the main model, the job makes no call at
5051
- * all (PR #542's lab: the default model's first call was bounded at $1.03 under a $1 cap).
5052
- *
5053
- * The guard's bound is (request bytes + 8,192) x the dearest input rate + the output limit x the dearest output rate,
5054
- * times a service-tier multiplier, over the model's table, its tiers and its fallbacks. This takes the parts of that
5055
- * which cannot be smaller: the model's own table (not its tiers or fallbacks, which only raise the bound), the output
5056
- * limit `model.maxTokens` (pi sends none of its own, so the guard uses the model's), an input of the overhead plus
5057
- * `FIRST_CALL_MIN_CONTEXT_BYTES`, and the runner's own service-tier multiplier (`serviceTierMultiplier`). The input
5058
- * rate is the guard's: the highest of input, cache read and cache write (not the 1h write, which needs long
5059
- * retention). Null for a table or limit it cannot read.
5060
- */
5061
- export function firstCallFloorMicros(model) {
5062
- const cost = model?.cost;
5063
- const usable = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
5064
- if (!cost || !["input", "output", "cacheRead", "cacheWrite"].every((field) => usable(cost[field]))) return null;
5065
- const maxTokens = model.maxTokens;
5066
- if (!(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0)) return null;
5067
- const inputRate = Math.max(cost.input, cost.cacheRead, cost.cacheWrite);
5068
- return Math.ceil(((FIRST_CALL_OVERHEAD_TOKENS + FIRST_CALL_MIN_CONTEXT_BYTES) * inputRate + maxTokens * cost.output) * serviceTierMultiplier(model));
5069
- }
5070
-
5071
- /**
5072
- * The runner's service-tier multiplier (`callCostBound` step 7, image/runner/src/usage-meter.mjs), copied like the
5073
- * overhead above: pi multiplies a settled cost by the tier the RESPONSE reports on these two apis, which can be the
5074
- * account's default rather than the request's, so the runner always bounds at the dearest tier. Leaving it out
5075
- * (PR #551's review) let doctor stay silent on a cap the runner refuses every call under: openai/gpt-5.5 under $5.
5076
- * `fleet-dollars.test.mjs` derives the runner's multiplier from its own bound for every priced api and holds this
5077
- * equal to it.
5078
- */
5079
- export function serviceTierMultiplier(model) {
5080
- if (model?.api !== "openai-responses" && model?.api !== "openai-codex-responses") return 1;
5081
- return model.id === "gpt-5.5" ? 2.5 : 2;
5082
- }
5083
-
5084
- /**
5085
- * The model object the floor above is computed from: the builtin catalog's (`builtinModel`, model-catalog.mjs), or a
5086
- * CUSTOM model the overlay `models.json` defines (its own `cost` and `maxTokens`). Null, so the model is not judged,
5087
- * when the overlay redefines or overrides a builtin model: pi composes the two, and this does not copy that rule.
5088
- */
5089
- export function boundModelOf({ provider, id }, { builtinModel, overlay = null }) {
5090
- const providers = overlay?.providers;
5091
- const entry = providers !== null && typeof providers === "object" && !Array.isArray(providers) && Object.hasOwn(providers, provider) ? providers[provider] : null;
5092
- const builtin = builtinModel(provider, id);
5093
- if (entry !== null && typeof entry === "object") {
5094
- const overrides = entry.modelOverrides;
5095
- if (overrides !== null && typeof overrides === "object" && Object.hasOwn(overrides, id)) return null;
5096
- const definition = Array.isArray(entry.models) ? entry.models.find((m) => m !== null && typeof m === "object" && m.id === id) : undefined;
5097
- if (definition !== undefined) return builtin ? null : definition;
5098
- }
5099
- return builtin;
5100
- }
6193
+ export { resolveConfiguredModelRuns as resolveDoctorModelRuns } from "./model-observation.mjs";
5101
6194
 
5102
6195
  /**
5103
6196
  * Who runs on which models under which cap (issues #501 and #502), as the worker resolves a job: the deployment's own
@@ -5108,7 +6201,7 @@ export function boundModelOf({ provider, id }, { builtinModel, overlay = null })
5108
6201
  * trigger's and the deployment's, `effectiveCostCapMicros`) or null, and `named` says the trigger names a provider, a
5109
6202
  * model or a list of its own.
5110
6203
  */
5111
- export function modelSubjects({ runs = [], deployment, envList = null }) {
6204
+ export function modelSubjects({ runs = [], deployment, envList = null, modelRoles = {}, projects = [] }) {
5112
6205
  const listOf = (list) => (Array.isArray(list) ? list.map(splitModelEntry).filter((ref) => ref !== null).map((ref) => ({ provider: ref.provider, id: ref.model })) : []);
5113
6206
  const capOf = (triggerValue) => {
5114
6207
  try {
@@ -5118,7 +6211,7 @@ export function modelSubjects({ runs = [], deployment, envList = null }) {
5118
6211
  }
5119
6212
  };
5120
6213
  const subjects = [{ label: "the deployment default", main: { provider: deployment.provider, id: deployment.model }, list: listOf(envList), cap: capOf(undefined), secretNames: [], named: false, deployment: true }];
5121
- for (const run of runs) {
6214
+ for (const run of resolveDoctorModelRuns({ runs, deployment, envList, modelRoles, projects }).runs) {
5122
6215
  subjects.push({
5123
6216
  label: run.label,
5124
6217
  main: { provider: run.provider ?? deployment.provider, id: run.model ?? deployment.model },
@@ -5136,7 +6229,7 @@ export function modelSubjects({ runs = [], deployment, envList = null }) {
5136
6229
  * `modelSubjects` resolves them), for the overlay's output-cap line to leave to `costCapFitChecks` (issue #507). Empty
5137
6230
  * when the settings cannot be read.
5138
6231
  */
5139
- export function cappedModelNames(env, { runs, deployment }) {
6232
+ export function cappedModelNames(env, { runs, deployment, modelRoles = {}, projects = [] }) {
5140
6233
  let envList = null;
5141
6234
  try {
5142
6235
  envList = allowedModelsFrom(env);
@@ -5144,7 +6237,7 @@ export function cappedModelNames(env, { runs, deployment }) {
5144
6237
  // A malformed PI_ALLOWED_MODELS is its own line.
5145
6238
  }
5146
6239
  const names = new Set();
5147
- for (const s of modelSubjects({ runs, deployment, envList })) {
6240
+ for (const s of modelSubjects({ runs, deployment, envList, modelRoles, projects })) {
5148
6241
  if (s.cap === null || s.cap === undefined) continue;
5149
6242
  for (const ref of [s.main, ...s.list]) names.add(`${ref.provider}/${ref.id}`);
5150
6243
  }
@@ -5159,10 +6252,13 @@ export function cappedModelNames(env, { runs, deployment }) {
5159
6252
  * Issue #507: `unboundable(ref)` says the runner cannot bound the model's output at all (`outputUnboundable`,
5160
6253
  * output-cap.mjs: openai-completions to a server off the trusted hosts without `compat.maxTokensField: "max_tokens"`),
5161
6254
  * so every call to it is refused under any cap. Such a model gets a line of its own, grouped by model, and no floor.
6255
+ * Radius and every composed pi-messages model have a separate diagnosis: their server-reported billing and input
6256
+ * rewrites are not bounded by the catalog, including rows whose listed rates are zero (issue #693).
5162
6257
  */
5163
- export function costCapFitChecks(subjects, modelOf, { unboundable = () => false } = {}) {
6258
+ export function costCapFitChecks(subjects, modelOf, { unboundable = () => false, apiOf = (ref) => modelOf(ref)?.api } = {}) {
5164
6259
  const groups = new Map();
5165
6260
  const unbounded = new Map();
6261
+ const radius = new Map();
5166
6262
  for (const s of subjects) {
5167
6263
  if (s.cap === null || s.cap === undefined) continue;
5168
6264
  const seen = new Set();
@@ -5170,6 +6266,15 @@ export function costCapFitChecks(subjects, modelOf, { unboundable = () => false
5170
6266
  const name = `${ref.provider}/${ref.id}`;
5171
6267
  if (seen.has(name)) continue;
5172
6268
  seen.add(name);
6269
+ // The gateway reports its own prices and may rewrite input, so even a zero-rate catalog row is no bound.
6270
+ const api = apiOf(ref);
6271
+ if (api === "pi-messages" || (api === undefined && ref.provider === "radius")) {
6272
+ if (!radius.has(name)) radius.set(name, { main: false, labels: [] });
6273
+ const r = radius.get(name);
6274
+ r.main ||= ref === s.main;
6275
+ r.labels.push(s.label);
6276
+ continue;
6277
+ }
5173
6278
  if (unboundable(ref)) {
5174
6279
  if (!unbounded.has(name)) unbounded.set(name, { main: false, labels: [] });
5175
6280
  const u = unbounded.get(name);
@@ -5186,6 +6291,15 @@ export function costCapFitChecks(subjects, modelOf, { unboundable = () => false
5186
6291
  }
5187
6292
  }
5188
6293
  const out = [];
6294
+ if (radius.size > 0) {
6295
+ const items = [...radius].map(([name, r]) => `${printable(name)}${r.main ? " (the main model, so such a job makes no call at all)" : ""} (${r.labels.join(", ")})`);
6296
+ out.push({
6297
+ ok: false,
6298
+ warn: true,
6299
+ label: `${RADIUS_COST_CAP_LABEL}: ${items.join("; ")}`,
6300
+ fix: RADIUS_COST_CAP_FIX,
6301
+ });
6302
+ }
5189
6303
  if (unbounded.size > 0) {
5190
6304
  const items = [...unbounded].map(([name, u]) => `${printable(name)}${u.main ? " (the main model, so such a job makes no call at all)" : ""} (${u.labels.join(", ")})`);
5191
6305
  out.push({
@@ -5270,7 +6384,7 @@ export function unknownModelChecks(subjects, checkModelsKnown, readOverlay) {
5270
6384
  * Said nothing about a provider it cannot judge: no names at all (Bedrock reads the AWS chain), the keyless marker
5271
6385
  * (#503), or an `apiKey` that is not a variable reference.
5272
6386
  */
5273
- export function listedProviderCredentialChecks(subjects, { candidatesOf, forwarded = [], env = {}, overlay = null }) {
6387
+ export function listedProviderCredentialChecks(subjects, { candidatesOf, forwarded = [], env = {}, overlay = null, subscriptionChecks = new Map() }) {
5274
6388
  const providers = overlay?.providers;
5275
6389
  const namesFor = (provider) => {
5276
6390
  const entry = providers !== null && typeof providers === "object" && !Array.isArray(providers) && Object.hasOwn(providers, provider) ? providers[provider] : null;
@@ -5286,6 +6400,7 @@ export function listedProviderCredentialChecks(subjects, { candidatesOf, forward
5286
6400
  for (const s of subjects) {
5287
6401
  for (const provider of new Set(s.list.map((ref) => ref.provider))) {
5288
6402
  if (provider === s.main.provider) continue;
6403
+ if (subscriptionChecks.get(provider)?.managed) continue;
5289
6404
  const names = namesFor(provider);
5290
6405
  if (names.length === 0) continue;
5291
6406
  if (names.some((n) => s.secretNames.includes(n) || (forwarded.includes(n) && typeof env[n] === "string" && env[n] !== ""))) continue;
@@ -5328,6 +6443,43 @@ export function deploymentSettingsOf(env, settingsFile, fileExists) {
5328
6443
  return Object.fromEntries(Object.keys(fromEnv).map((key) => [key, resolved[key] ?? null]));
5329
6444
  }
5330
6445
 
6446
+ /** Subscription diagnostics use only local credential metadata, independently of forge validity or Valkey. */
6447
+ export async function doctorSubscriptionCredentials(env, { cwd = process.cwd(), home = safeHomeDir(), now = Date.now, configure } = {}) {
6448
+ if (!env.PI_AUTH_CONNECTIONS_FILE) return { check: async () => ({ ok: true, managed: false }) };
6449
+ let auth;
6450
+ try {
6451
+ configure ??= (await import("./subscription-config.mjs")).configuredSubscriptions;
6452
+ const config = { authConnectionsFile: resolve(cwd, env.PI_AUTH_CONNECTIONS_FILE), authStoreDir: env.PI_AUTH_STORE_DIR ? resolve(cwd, env.PI_AUTH_STORE_DIR) : null, settingsFile: settingsFilePath(env, home), workerName: workerNameFrom(env), globalPiDir: env.PI_GLOBAL_PI_DIR || null, jobsDir: jobsDirPath(env), sandboxDir: env.PI_SANDBOX_DIR || defaultSandboxDir(env) };
6453
+ auth = configure({ config, redis: null, now })?.auth;
6454
+ if (typeof auth?.check !== "function") throw new Error();
6455
+ } catch { return { check: async () => ({ ok: false, managed: true, reason: "auth-policy-invalid" }) }; }
6456
+ const cache = new Map();
6457
+ return { check(provider) {
6458
+ if (!cache.has(provider)) cache.set(provider, Promise.resolve().then(() => auth.check(provider, { readOnly: true })).catch(() => ({ ok: false, managed: true, reason: "auth-state-unavailable" })));
6459
+ return cache.get(provider);
6460
+ } };
6461
+ }
6462
+
6463
+ export function subscriptionCredentialCheck(provider, row) {
6464
+ const name = printable(provider);
6465
+ const owner = typeof row.ownerHost === "string" && WORKER_NAME_RE.test(row.ownerHost) ? ` on owner ${row.ownerHost}` : "";
6466
+ const id = typeof (row.connectionId ?? row.id) === "string" && WORKER_NAME_RE.test(row.connectionId ?? row.id) ? ` ${row.connectionId ?? row.id}` : " CONNECTION";
6467
+ if (row.ok === true) return { ok: true, label: `Subscription credential selected (${name})${owner}; the host renews access before admitted jobs` };
6468
+ const words = {
6469
+ "auth-owner-host": "belongs to another owner host; this worker defers its subscription jobs",
6470
+ "auth-reauth-required": "requires sign-in on its owner host",
6471
+ "auth-refresh-uncertain": "requires reconnect after an uncertain token refresh",
6472
+ "auth-adapter-unpinned": "requires reviewed adapter staging",
6473
+ "auth-adapter-source-mismatch": "requires reviewed adapter staging",
6474
+ "auth-adapter-version-mismatch": "has an incompatible adapter version",
6475
+ "auth-adapter-unavailable": "has no usable staged adapter",
6476
+ "auth-store-permissions": "has unsafe private credential-store permissions",
6477
+ "auth-credential-invalid": "has an invalid stored subscription credential",
6478
+ "auth-policy-invalid": "has an unavailable or invalid connection policy",
6479
+ };
6480
+ return { ok: false, ...(row.reason === "auth-owner-host" ? { warn: true } : {}), label: `Subscription credential selected (${name}) ${words[row.reason] ?? "has unavailable credential metadata"}`, fix: row.reason === "auth-reauth-required" || row.reason === "auth-refresh-uncertain" ? `run \`pi-dispatch auth login${id}\` on the connection owner host` : "run `pi-dispatch auth status` on the connection owner host and correct its reviewed policy, adapter or private store" };
6481
+ }
6482
+
5331
6483
  /** The worker's model catalog (model-catalog.mjs), imported lazily for `defaultProviderOracle`'s reason, or null. */
5332
6484
  async function defaultModelCatalog() {
5333
6485
  try {
@@ -5427,8 +6579,8 @@ function triggerLabel(t, index) {
5427
6579
  return t.on.type === "cron" ? `cron "${t.on.id}"` : `${t.on.type} trigger #${index}`;
5428
6580
  }
5429
6581
 
5430
- function readTriggerFacts(env, fileExists, cwd, declaredWorkerName) {
5431
- const none = { requiring: 0, waiting: 0, listing: 0, waitProfiles: [], waitAfters: [], optingOut: 0, resuming: 0, replicating: 0, instructing: 0, commands: 0, secreting: 0, onceArmed: 0, onceSpent: 0, secretProfiles: [], localSecretFolders: [], secretNames: [], folders: [], images: [], imageRoutes: [], namedBackends: [], skillsDirs: [], forges: [], repositories: [], flows: [], costCaps: [], modelRuns: [], parseError: null, path: null };
6582
+ function readTriggerFacts(env, fileExists, cwd, declaredWorkerName, versionTables = {}) {
6583
+ const none = { watchSources: {}, watchRules: 0, modelRoles: {}, secretBundles: {}, requiring: 0, waiting: 0, listing: 0, waitProfiles: [], waitAfters: [], optingOut: 0, resuming: 0, recovering: 0, replicating: 0, instructing: 0, commands: 0, secreting: 0, onceArmed: 0, onceSpent: 0, secretProfiles: [], localSecretFolders: [], secretNames: [], folders: [], images: [], imageRoutes: [], namedBackends: [], skillsDirs: [], forges: [], repositories: [], flows: [], excludedNames: [], costCaps: [], modelRuns: [], triggersVersionNeed: 1, jobDataVersionNeed: 1, parseError: null, parseNewer: false, path: null };
5432
6584
  try {
5433
6585
  // Unset falls back to ./triggers.json in cwd, MIRRORING the receiver's own default
5434
6586
  // (receiver/src/config.mjs) -- the two must read the same file, or doctor preflights a deployment
@@ -5439,14 +6591,16 @@ function readTriggerFacts(env, fileExists, cwd, declaredWorkerName) {
5439
6591
  // naming a FIFO hangs the command with no output and no timeout that can reach it.
5440
6592
  if (!statSync(path).isFile()) return { ...none, parseError: `triggers file is not a regular file: ${path}`, path };
5441
6593
  const text = readFileSync(path, "utf8");
5442
- const triggers = parseTriggers(text, path);
6594
+ // The document parser, so the file's `secretBundles` (issue #704) is judged by the loaders' one rule too.
6595
+ const { triggers, secretBundles, modelRoles, watchSources } = parseTriggersDocument(text, path, versionTables.triggers);
5443
6596
  // The one-shot facts are counted from the RAW entries, not the parsed records, because the
5444
6597
  // validator collapses a disarmed entry to a sentinel that carries neither `once` nor
5445
6598
  // `disarmed` -- exactly so nothing can match it -- which also erases it from every parsed
5446
6599
  // count above. Doctor is the surface that must still SEE the spent entry: "why did nothing
5447
6600
  // fire" is answered by a spent row, and only the raw file still holds it. Safe unguarded:
5448
6601
  // parseTriggers just accepted this same text, so JSON.parse cannot throw here.
5449
- const rawEntries = JSON.parse(text)?.triggers ?? [];
6602
+ const rawDocument = JSON.parse(text);
6603
+ const rawEntries = rawDocument?.triggers ?? [];
5450
6604
  // Issue #433 review rounds 2 and 3: whether THIS HOST'S WORKER schedules a cron trigger, for the unblessed-venue
5451
6605
  // line, by the worker's two conditions and nothing else. (a) The worker schedules cron only from a PI_TRIGGERS_FILE
5452
6606
  // it was given (`config.triggersFile` is null without one, and `loadSchedules` then returns []), while doctor
@@ -5460,10 +6614,25 @@ function readTriggerFacts(env, fileExists, cwd, declaredWorkerName) {
5460
6614
  const fleet = Boolean(declaredWorkerName);
5461
6615
  const cronScheduledHere = (t) => env.PI_TRIGGERS_FILE !== undefined && cronPlacement(t.run, { existsSync: fileExists, fleet }) !== "elsewhere";
5462
6616
  return {
6617
+ // Issue #761: the version this file needs (the higher of what it declares and what its keys need), and the version
6618
+ // the jobs its triggers queue need (`jobDataVersionFor`): for the fleet line that names a peer that cannot read
6619
+ // either. The loader just accepted this text, so a declared version is an integer. The FILE's need is the raw
6620
+ // keys', since an older loader reads the raw file; the JOBS' need is what the loader KEPT, each parsed entry's
6621
+ // `run`, which is what the builders copy into job data (schedules.mjs, the receiver). A raw run key the loader
6622
+ // drops (a hand-written `run.packageCanary`, which only the Updates page's canary job carries) reaches no job,
6623
+ // so it needs no version, and a line claiming one would send an operator to upgrade for nothing.
6624
+ triggersVersionNeed: Math.max(Number.isSafeInteger(rawDocument?.version) ? rawDocument.version : 1, triggersFileVersionFor(rawDocument, versionTables.triggers)),
6625
+ jobDataVersionNeed: triggers.reduce((need, t) => Math.max(need, jobDataVersionFor(t?.run, versionTables.jobData)), 1),
6626
+ watchSources,
6627
+ watchRules: triggers.filter(t => t.on.type === "watch").length,
6628
+ secretBundles,
6629
+ modelRoles,
5463
6630
  onceArmed: rawEntries.filter((t) => t?.on?.once === true && t.on.disarmed === undefined).length,
5464
6631
  onceSpent: rawEntries.filter((t) => t?.on?.disarmed !== undefined).length,
5465
6632
  requiring: triggers.filter((t) => t.run.packages === true).length,
5466
6633
  resuming: triggers.filter((t) => t.run.resume === true).length,
6634
+ // Issue #645: durable runs. Counted for the fleet line: a recovery is routed to the host holding its checkpoint.
6635
+ recovering: triggers.filter((t) => t.run.recover === true).length,
5467
6636
  // REQ-PER-TRIGGER-INSTRUCTION. Counted beside `resuming` for the same reason: it is a per-trigger
5468
6637
  // choice that changes what every job of it is told, and an operator should see it before it fires.
5469
6638
  instructing: triggers.filter((t) => typeof t.run.instructions === "string").length,
@@ -5541,14 +6710,18 @@ function readTriggerFacts(env, fileExists, cwd, declaredWorkerName) {
5541
6710
  // entries by raw file position (the admin's trigger:<index> identity).
5542
6711
  flows: triggers
5543
6712
  .map((t, index) => ({
6713
+ index,
5544
6714
  label: triggerLabel(t, index),
5545
6715
  flow: t.run.flow,
5546
6716
  kind: t.run.kind,
5547
6717
  folder: typeof t.run.folder === "string" ? t.run.folder : null,
5548
6718
  skillsDir: typeof t.run.skillsDir === "string" ? t.run.skillsDir : null,
5549
6719
  packages: t.run.packages !== false,
6720
+ excludeExtensions: Array.isArray(t.run.excludeExtensions) ? t.run.excludeExtensions : [],
5550
6721
  }))
5551
6722
  .filter((f) => typeof f.flow === "string"),
6723
+ // Issue #800: each trigger's run.excludeExtensions, for the line that says a name is on neither side of this host.
6724
+ excludedNames: triggers.flatMap((t, index) => (Array.isArray(t.run.excludeExtensions) ? [{ label: triggerLabel(t, index), names: t.run.excludeExtensions, packages: t.run.packages !== false }] : [])),
5552
6725
  // Issue #501: every trigger that sets run.maxCostUsd, with the label the cap check names it by. The value
5553
6726
  // already parsed (the loader validated it), so the check below only compares.
5554
6727
  costCaps: triggers.map((t, index) => ({ label: triggerLabel(t, index), maxCostUsd: t.run.maxCostUsd })).filter((r) => r.maxCostUsd !== undefined && r.maxCostUsd !== null),
@@ -5557,9 +6730,13 @@ function readTriggerFacts(env, fileExists, cwd, declaredWorkerName) {
5557
6730
  // a model the worker does not know is refused wherever the job runs.
5558
6731
  modelRuns: triggers.map((t, index) => ({
5559
6732
  label: triggerLabel(t, index),
6733
+ kind: t.run.kind,
6734
+ folder: t.run.folder,
6735
+ repository: t.run.repository,
5560
6736
  provider: typeof t.run.provider === "string" ? t.run.provider : undefined,
5561
6737
  model: typeof t.run.model === "string" ? t.run.model : undefined,
5562
6738
  models: Array.isArray(t.run.models) ? t.run.models : undefined,
6739
+ fallbackModels: Array.isArray(t.run.fallbackModels) ? t.run.fallbackModels : undefined,
5563
6740
  maxCostUsd: t.run.maxCostUsd ?? undefined,
5564
6741
  secretNames: t.run.secrets !== undefined && t.run.secrets !== null ? Object.keys(t.run.secrets) : [],
5565
6742
  })),
@@ -5584,7 +6761,9 @@ function readTriggerFacts(env, fileExists, cwd, declaredWorkerName) {
5584
6761
  // a directory), which is not a statement about the file's CONTENT and has no fix an operator can act
5585
6762
  // on from this line. Those keep the old silent zeroes.
5586
6763
  if (e?.piDispatchConfig !== true) return none;
5587
- return { ...none, parseError: e.message, path: triggersPath(env, cwd) };
6764
+ // Issue #761: `parseNewer` is the loader's own flag for a file a newer pi-dispatch wrote, so the fix below says to
6765
+ // upgrade rather than to edit it.
6766
+ return { ...none, parseError: e.message, parseNewer: e.newer === true, path: triggersPath(env, cwd) };
5588
6767
  }
5589
6768
  }
5590
6769
 
@@ -6211,7 +7390,7 @@ async function egressChecks(env, seams, { dockerCode, imageCode, jobImage, endpo
6211
7390
  // ONE detach gate for this doctor run (issue #452, gate round 3), shared by the sweep and the canary: `local` can be a
6212
7391
  // rootless Podman 4.x reached as `docker`, where both of them detach the running proxy.
6213
7392
  const gate = makeDetachGate(canaryDocker, { bin: "docker", ...(seams.readFactsOnce ? { readRuntime: async () => runtimeFromFacts(await seams.readFactsOnce()) } : {}) });
6214
- checks.push(...(await sweepStaleCanaryNetworks({ run: canaryDocker, pid, isAlive, endpoint, gate })));
7393
+ if (!seams.setupReadOnly) checks.push(...(await sweepStaleCanaryNetworks({ run: canaryDocker, pid, isAlive, endpoint, gate })));
6215
7394
 
6216
7395
  // `docker inspect` on the container, not `ps`: it answers present-vs-absent and running-vs-stopped in
6217
7396
  // one call, and those are two different fixes. The FIELD_SEP habit is image-preflight.mjs's -- neither
@@ -6290,6 +7469,8 @@ async function egressChecks(env, seams, { dockerCode, imageCode, jobImage, endpo
6290
7469
  // `--live` reads, so the output never reads healthy right before saying the proxy is not this deployment's.
6291
7470
  const staleRunning = up && !custom && judged.drift.length > 0;
6292
7471
  const proxyCheck = {
7472
+ // Issue #737: the console reads whether the proxy runs by this id (`NAMED_CHECK_IDS`).
7473
+ id: "egress.proxy",
6293
7474
  ok: up,
6294
7475
  ...(retried ? { warn: true } : {}),
6295
7476
  label: up
@@ -6321,6 +7502,8 @@ async function egressChecks(env, seams, { dockerCode, imageCode, jobImage, endpo
6321
7502
  if (!custom) {
6322
7503
  if (judged.drift.length > 0) {
6323
7504
  checks.push({
7505
+ // This line stands in for the proxy's own (not pushed while `staleRunning`), so it carries that line's id.
7506
+ id: proxyCheck.id,
6324
7507
  ok: false,
6325
7508
  label: judged.outOfDate ? `Egress proxy is this deployment's proxy but out of date (${proxy}): ${judged.drift.join("; ")}` : `Egress proxy is running but is not this deployment's (${proxy}): ${judged.drift.join("; ")}`,
6326
7509
  fix: `${replaceFix}; until then every job's egress runs through a policy this deployment did not ship`,
@@ -6369,6 +7552,10 @@ async function egressChecks(env, seams, { dockerCode, imageCode, jobImage, endpo
6369
7552
  const mounted = readIncludeBindSource(parsed?.mounts);
6370
7553
  checks.push(endpointsIncludeCheck({ answer: inside, endpoints, bin: "docker", proxy, prefix: "", mounted, recreate: custom ? `recreate ${proxy} so it mounts the file anew` : `\`docker rm -f -v ${proxy}\`, then \`pi-dispatch up\` starts it on the file anew (a restart cuts running jobs' tunnels)` }));
6371
7554
  }
7555
+ if (seams.setupReadOnly) {
7556
+ checks.push({ ok: false, warn: true, label: "Egress canary: not run by browser setup", fix: "run pi-dispatch doctor in the deployment terminal for the container probe" });
7557
+ return checks;
7558
+ }
6372
7559
  if (imageCode !== 0) return checks;
6373
7560
  // Issue #431: the canary itself is `runEgressCanary`, shared with the podman venue's `--live` and the conformance
6374
7561
  // script. docker's probes keep `runCmdCapture` (its 30 s bound, stderr merged, SIGTERM at the bound) rather than the
@@ -7143,7 +8330,8 @@ export function allowlistHostAliases(text) {
7143
8330
  }
7144
8331
 
7145
8332
  /**
7146
- * The worker and receiver services installed for THIS folder, as `[{ which, source, setup }]` (`setup` null for a unit
8333
+ * The services installed for THIS folder (the worker, the receiver and, since issue #708, the console), as
8334
+ * `[{ which, source, setup }]` (`setup` null for a unit
7147
8335
  * rendered without `--env-setup`): an installed unit whose WorkingDirectory is this folder (systemd, launchd), or the
7148
8336
  * nssm service by name on win32, where nssm keeps the folder in a separate AppDirectory property and there is exactly
7149
8337
  * one machine-scoped service per name. Read ONCE (issue #481, PR #485's final review) and shared by the env-setup lines
@@ -7153,7 +8341,7 @@ async function installedServices(seams) {
7153
8341
  const { cwd, spawn, fileExists, platform, home } = seams;
7154
8342
  const found = [];
7155
8343
  if (platform === "win32") {
7156
- for (const which of ["worker", "receiver"]) {
8344
+ for (const which of ["worker", "receiver", "console"]) {
7157
8345
  const service = `pi-dispatch-${which}`;
7158
8346
  const got = await runCmdCapture(spawn, "nssm", ["get", service, "AppEnvironmentExtra"]);
7159
8347
  // Not installed, or nssm not on PATH: silence. Same doctrine as check-ignore below -- a check
@@ -7722,7 +8910,7 @@ export function jobSizeChecks(env, { daemon = undefined, podman = undefined, cpu
7722
8910
  return [{ ok: false, label: `job size does not parse: ${error.message}, so the worker REFUSES TO START`, fix: "set PI_JOB_MEMORY like 512m, 1536m or 4g and PI_JOB_CPUS like 0.5 or 2 (or unset them for 4g and 2), then re-run doctor" }];
7723
8911
  }
7724
8912
  const where = d.memSet || d.cpuSet ? "PI_JOB_MEMORY and PI_JOB_CPUS" : "the built-in default";
7725
- const checks = [{ ok: true, label: `Job size: ${formatMemory(d.memMiB)} of memory with no swap beyond it, and the CPU weight of ${formatCpus(d.cpuCenti)} CPUs, per job (${where}; a project row's memory and cpus override it, docs/scoped-limits.md)` }];
8913
+ const checks = [{ ok: true, label: `Job size: ${formatMemory(d.memMiB)} of memory with no swap beyond it, and the CPU weight of ${formatCpus(d.cpuCenti)} CPUs, per job (${where}; a project row's memory and cpus override it, docs/scoped-limits.md); codemode workers: ${codemodeWorkersOf(d.memMiB)} (PI_CODEMODE_MAX_WORKERS, half the memory reserved for pi, tools and worker overhead; a sizing heuristic, not an RSS guarantee)` }];
7726
8914
  const venues = [];
7727
8915
  // `reason` is the reader's own token (`timeout`, `unparseable`, ...), never the runtime's text.
7728
8916
  const reasonOf = (read) => (typeof read?.reason === "string" && /^[a-z0-9-]{1,40}$/.test(read.reason) ? read.reason : "not read");
@@ -7975,22 +9163,26 @@ export const CAPACITY_DOCTOR_TIMEOUT_MS = 5_000;
7975
9163
 
7976
9164
  /**
7977
9165
  * The capacity lines (issue #599, phase 2): the report over the last 7 days (`capacity.mjs`, the CLI's function), read
7978
- * by `seams.readCapacity` (default: `readCapacityRecords` through a fail-fast client, `prune`-free and writing nothing).
7979
- * Never throws and never warns: an unreadable history is one line saying so.
9166
+ * by `seams.readCapacity` (default: `readCapacityRecords` through a fail-fast client, `prune`-free and writing nothing;
9167
+ * `seams.readCapacityRecords` stands in for `readCapacityRecords` alone, see `defaultReadCapacity`). Never throws and
9168
+ * never warns: an unreadable history is one line saying so.
7980
9169
  */
7981
9170
  export async function doctorCapacity({ seams, env, home, url, hosts, localHost }) {
7982
9171
  try {
7983
9172
  const window = CAPACITY_WINDOWS["7d"];
7984
9173
  const nowMs = (typeof seams.wallClock === "function" ? seams.wallClock : Date.now)();
7985
9174
  const retention = typeof env.PI_LOG_RETENTION_DAYS === "string" && /^\d{1,6}$/.test(env.PI_LOG_RETENTION_DAYS) ? Number(env.PI_LOG_RETENTION_DAYS) : 30;
9175
+ // The mirror's cap (PI_RUN_MIRROR_MAX_RUNS, issue #761), so an index the workers may grow past the built-in cap is not
9176
+ // read as one a trim cut short. Lenient: a bad value is the worker's refusal, which `workerIntSettingChecks` names.
9177
+ const indexMax = runMirrorMaxRunsOf(env.PI_RUN_MIRROR_MAX_RUNS).value;
7986
9178
  // The read is told to stop when the bound passes (`signal`): giving up on it is not enough, since a client still
7987
9179
  // waiting on its connection would keep this process alive after doctor has printed everything.
7988
9180
  const stop = new AbortController();
7989
- const args = { url, logsDir: logsDirPath(env, home), sinceMs: nowMs - window.ms, nowMs, retentionDays: retention, localHost, signal: stop.signal };
9181
+ const args = { url, logsDir: logsDirPath(env, home), sinceMs: nowMs - window.ms, nowMs, retentionDays: retention, localHost, indexMax, signal: stop.signal };
7990
9182
  let timer;
7991
9183
  const read = await Promise.race([
7992
9184
  Promise.resolve()
7993
- .then(() => (seams.readCapacity ?? defaultReadCapacity)(args))
9185
+ .then(() => (seams.readCapacity ?? ((a) => defaultReadCapacity(a, seams.readCapacityRecords)))(args))
7994
9186
  .finally(() => clearTimeout(timer)),
7995
9187
  new Promise((resolve) => {
7996
9188
  timer = setTimeout(() => {
@@ -8025,11 +9217,14 @@ export const CAPACITY_CONNECT_TIMEOUT_MS = 2_000;
8025
9217
  /**
8026
9218
  * The default capacity read: a fail-fast client, its connection bounded (`connectWithin`: a server that accepts TCP and
8027
9219
  * never answers holds ioredis in its ready check forever) and DISCONNECTED when `signal` aborts, so a read doctor gave
8028
- * up on cannot keep the process alive.
9220
+ * up on cannot keep the process alive. `readRecords` (doctor's `seams.readCapacityRecords`, for a test) stands in for
9221
+ * `readCapacityRecords` and receives exactly what it would, the mirror's cap included. The forbidden-read guard still
9222
+ * runs first, whether or not it is given: it is a seam for a test process that never forbade the real read, and it
9223
+ * lifts the guard for no other test.
8029
9224
  */
8030
- async function defaultReadCapacity({ url, logsDir, sinceMs, nowMs, retentionDays, localHost, signal }) {
9225
+ async function defaultReadCapacity({ url, logsDir, sinceMs, nowMs, retentionDays, localHost, indexMax, signal }, readRecords = undefined) {
8031
9226
  if (defaultCapacityReadForbidden) throw Object.assign(new Error("doctor reached its real capacity read in a test: pass readCapacity"), { [FORBIDDEN_READ]: true });
8032
- const { readCapacityRecords } = await import("./capacity-records.mjs");
9227
+ const readCapacityRecords = readRecords ?? (await import("./capacity-records.mjs")).readCapacityRecords;
8033
9228
  let client = null;
8034
9229
  // Measured on ioredis 5.11: `disconnect()` ends the socket and arms a timer (`disconnectTimeout`, 2 s by default)
8035
9230
  // that destroys it unless the socket's `close` clears it first, and the client's own failed ready check disconnects
@@ -8058,7 +9253,7 @@ async function defaultReadCapacity({ url, logsDir, sinceMs, nowMs, retentionDays
8058
9253
  }
8059
9254
  }
8060
9255
  try {
8061
- return await readCapacityRecords({ redis: client, logsDir, sinceMs, nowMs, retentionDays, localHost, noMirrorReason: url ? "the Valkey did not answer: only this host's files were read" : "no Valkey to read: only this host's files were read" });
9256
+ return await readCapacityRecords({ redis: client, logsDir, sinceMs, nowMs, retentionDays, localHost, indexMax, noMirrorReason: url ? "the Valkey did not answer: only this host's files were read" : "no Valkey to read: only this host's files were read" });
8062
9257
  } finally {
8063
9258
  signal?.removeEventListener?.("abort", drop);
8064
9259
  drop();
@@ -8081,6 +9276,239 @@ export function connectWithin(client, ms, signal) {
8081
9276
  });
8082
9277
  }
8083
9278
 
9279
+ // ---- issue #761: what an upgrade leaves behind ----------------------------------------------------------------------
9280
+
9281
+ /** A version a registry row may carry: npm's characters, at most 32 of them. Anything else, `""` included, is unknown. */
9282
+ const ROW_VERSION_RE = /^[0-9A-Za-z.+-]{1,32}$/;
9283
+ const rowVersion = (v) => (typeof v === "string" && ROW_VERSION_RE.test(v) ? v : null);
9284
+
9285
+ /**
9286
+ * The fleet's versions (issue #761): one `fleet.versions` check, or none. PURE.
9287
+ * - `installed`: this doctor's own package version (`PACKAGE_VERSION`), null when it could not be read;
9288
+ * - `self`: this host's own registry row (its worker's), null when it publishes none; `selfName` its name;
9289
+ * - `peers`: every other live worker's row.
9290
+ * A WARNING when the live workers do not all report one version (an unreadable one, which a worker publishes as `""`
9291
+ * when it cannot read its own manifest, or a row's value outside the charset, is its own group, "unknown"), or when
9292
+ * this doctor's version is not the one this host's worker row reports. The second is worded as exactly that, two facts,
9293
+ * never "not restarted" and never "the running worker": doctor may run from another install (npx, another checkout),
9294
+ * and then it is that, not the service, which differs; and a row outlives a worker that died without deleting it for up
9295
+ * to its TTL (`HOST_TTL_MS`, 90 s), so what reports the version is the row, not a worker known to run. The headline says
9296
+ * "differ" only of versions it read: two readable ones among the workers, or this doctor's against this host's row.
9297
+ * Where the only other group is "unknown" it says the versions "cannot all be read", since an unread version may be the
9298
+ * same one. The fix is the order of docs/upgrading.md for each host: pause, wait for no active job, restart, resume.
9299
+ * Not `service restart --drain`, which covers this host's queues alone (the shared one and its own) and resumes them
9300
+ * after its own restart, so it is not the fleet's pause: a peer's own queue keeps running under it. An ok line when
9301
+ * peers exist and every one, this host's included, reports one known version, naming them as the workers with a live
9302
+ * row (this host's worker may publish none); nothing on a single host whose worker row reports this doctor's version,
9303
+ * or publishes none, so its output is unchanged. Workers only: the receiver's status row is never a doctor input
9304
+ * (INT-RECEIVER-STATUS-KEY).
9305
+ */
9306
+ export function fleetVersionChecks({ installed, self = null, selfName = null, peers = [] }) {
9307
+ const others = Array.isArray(peers) ? peers : [];
9308
+ const rows = [...(self ? [{ name: printable(String(selfName ?? self.name ?? "")), version: rowVersion(self.version) }] : []), ...others.map((p) => ({ name: printable(String(p?.name ?? "")), version: rowVersion(p?.version) }))];
9309
+ const groups = new Map();
9310
+ for (const r of rows) groups.set(r.version ?? "unknown", [...(groups.get(r.version ?? "unknown") ?? []), r.name]);
9311
+ const parts = [];
9312
+ if (groups.size > 1) parts.push(`the live workers report ${groups.size} versions: ${[...groups.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([v, names]) => `${v} (${names.sort().join(", ")})`).join(", ")}`);
9313
+ const mine = rowVersion(installed);
9314
+ const running = self ? rowVersion(self.version) : null;
9315
+ const apart = mine !== null && running !== null && mine !== running;
9316
+ if (apart) parts.push(`this doctor ${mine}, this host's worker row reports ${running}`);
9317
+ const warn = parts.length > 0;
9318
+ const differ = [...groups.keys()].filter((v) => v !== "unknown").length > 1 || apart;
9319
+ const agreed = !warn && others.length > 0 && groups.size === 1 && !groups.has("unknown");
9320
+ if (!warn && !agreed) return [];
9321
+ const fix = `finish the upgrade in one window (docs/upgrading.md): the same version on every host; on each host \`pi-dispatch pause\`, wait until \`pi-dispatch status\` shows no active job, restart the worker, then \`pi-dispatch resume\`${apart ? ". If this doctor is not the install the service runs (npx, another checkout), run that install's doctor instead" : ""}`;
9322
+ const one = rows.length === 1;
9323
+ const ok = `Fleet versions: the ${rows.length} ${one ? "worker with a live row reports" : "workers with a live row report"} ${[...groups.keys()][0]}`;
9324
+ return [{ id: "fleet.versions", ok: !warn, ...(warn ? { warn: true } : {}), label: warn ? `pi-dispatch versions ${differ ? "differ" : "cannot all be read"}: ${parts.join("; ")}` : ok, ...(warn ? { fix } : {}) }];
9325
+ }
9326
+
9327
+ /** The most the dollar window check may take, its records read and its counter read together. */
9328
+ export const DOLLAR_WINDOWS_DOCTOR_TIMEOUT_MS = 5_000;
9329
+
9330
+ const WINDOW_WORDS = Object.freeze({ day: { its: "today's", cap: "daily" }, week: { its: "this week's", cap: "weekly" }, month: { its: "this month's", cap: "monthly" } });
9331
+ /** A counter value as micro-dollars, sign kept: `-$2.00` for a counter a give-back took below 0. */
9332
+ const usdSigned = (micros) => (micros < 0 ? `-$${formatMicros(-micros)}` : `$${formatMicros(micros)}`);
9333
+ const utcMinute = (ms) => `${new Date(ms).toISOString().slice(0, 16).replace("T", " ")} UTC`;
9334
+
9335
+ /**
9336
+ * The dollar window reset check (issue #761, DES-DOLLAR-RESERVE-AND-SETTLE): whether a deployment dollar window's
9337
+ * counter holds less than this host's own run records settled into it, which only lost history explains (a flushed,
9338
+ * replaced or restored Valkey, an evicted key, a hand edit): the cap then counts from less than was spent and can let
9339
+ * at least the difference more be spent. One warning for every such window, or nothing.
9340
+ *
9341
+ * 1. The deployment's day, week and month caps, overlay over env (`deploymentSettingsOf`, `dollarWindowCaps`, which
9342
+ * throws on a value the worker refuses: that is its own line, and this check says nothing). None set, or no Valkey
9343
+ * this command may talk to (`url` null): nothing is read.
9344
+ * 2. This host's records FIRST (`seams.readDollarRecords`; default: `readLocalWindow` from the start of the earliest
9345
+ * active window, a file at a time until the bound passes), summed per window by `dollarWindowFloors` over this
9346
+ * host's name and the endpoint tag of `url` (`valkeyEndpointTag`, the worker's).
9347
+ * 3. THEN the counters of the windows whose sum is above 0 (`seams.readDollarCounters`; default: one MGET). In this
9348
+ * order every record read was settled before its counter was read, so a counter read after it cannot be
9349
+ * legitimately below it.
9350
+ * 4. A counter that is absent, or an integer below the sum (a negative one included), is a finding; one that is not
9351
+ * an integer is skipped.
9352
+ * Both default reads share one bound (`DOLLAR_WINDOWS_DOCTOR_TIMEOUT_MS`) and are refused in tests
9353
+ * (`forbidDefaultDollarWindowRead`). A read that fails or runs out of time says nothing: this check claims a reset only
9354
+ * where it sees one, and its silence is never a claim that nothing was lost. It sees this host's share only (another
9355
+ * host's records are not here) and only the deployment windows (a scoped, project or model key is a hash per ledger),
9356
+ * from the records written since issue #761 (`dollars.reservedIn`).
9357
+ */
9358
+ export async function doctorDollarWindows({ seams = {}, env = {}, home, url, localHost, fileExists = existsSync }) {
9359
+ // Resolved first, then judged: `deploymentSettingsOf` never throws and hands back values as written, which
9360
+ // `dollarWindowCaps` may refuse.
9361
+ const settings = deploymentSettingsOf(env, settingsFilePath(env, home), fileExists);
9362
+ let caps = null;
9363
+ try {
9364
+ caps = dollarWindowCaps(settings);
9365
+ } catch {
9366
+ return [];
9367
+ }
9368
+ const valkey = url ? valkeyEndpointTag(url) : null;
9369
+ if (caps === null || valkey === null) return [];
9370
+ try {
9371
+ const nowMs = (typeof seams.wallClock === "function" ? seams.wallClock : Date.now)();
9372
+ const at = deploymentWindowsAt(nowMs);
9373
+ const active = DEPLOYMENT_WINDOWS.filter((w) => caps[w] !== null && caps[w] !== undefined && at[w].bucket !== null).map((w) => ({ window: w, cap: caps[w], ...at[w] }));
9374
+ if (active.length === 0) return [];
9375
+ // The bound runs on the real clock, never the injected one a test fixes: it measures how long this read takes.
9376
+ const clock = typeof seams.dollarWindowsClock === "function" ? seams.dollarWindowsClock : Date.now;
9377
+ const deadlineAt = clock() + (seams.dollarWindowsTimeoutMs ?? DOLLAR_WINDOWS_DOCTOR_TIMEOUT_MS);
9378
+ const read = await (seams.readDollarRecords ?? defaultReadDollarRecords)({ logsDir: logsDirPath(env, home), sinceMs: Math.min(...active.map((w) => w.startMs)), deadlineAt, clock });
9379
+ const floors = dollarWindowFloors(read?.records, { host: localHost, valkey, buckets: Object.fromEntries(active.map((w) => [w.window, w.bucket])) });
9380
+ const due = active.filter((w) => floors[w.window] > 0);
9381
+ if (due.length === 0) return [];
9382
+ const counters = await (seams.readDollarCounters ?? defaultReadDollarCounters)({ url, keys: due.map((w) => w.key), deadlineAt, clock });
9383
+ if (!Array.isArray(counters) || counters.length !== due.length) return [];
9384
+ const found = [];
9385
+ due.forEach((w, i) => {
9386
+ const raw = counters[i];
9387
+ if (raw === null || raw === undefined) return void found.push({ ...w, floor: floors[w.window], counter: null });
9388
+ const text = typeof raw === "number" ? String(raw) : raw;
9389
+ if (typeof text !== "string" || !/^-?\d{1,16}$/.test(text) || !Number.isSafeInteger(Number(text))) return;
9390
+ if (Number(text) < floors[w.window]) found.push({ ...w, floor: floors[w.window], counter: Number(text) });
9391
+ });
9392
+ return dollarWindowResetChecks(found);
9393
+ } catch (err) {
9394
+ if (err?.[FORBIDDEN_READ]) throw err;
9395
+ return [];
9396
+ }
9397
+ }
9398
+
9399
+ /**
9400
+ * The one `dollars.window-reset` warning for `found` (`doctorDollarWindows`), each `{ window, key, cap, floor, counter,
9401
+ * ttlSeconds, endMs }` (`counter` null for an absent key), or none for an empty list. PURE. It says "at least" and
9402
+ * "this host's" wherever it gives an amount: the other hosts' records are not here, so the real shortfall can only be
9403
+ * larger. The fix puts the shortfall back (`INCRBY`, then `EXPIRE` with the window's own TTL, printed, and without
9404
+ * `NX`, which an operator's older Valkey may not take), lowers the cap, or pauses until the window ends. On a fleet
9405
+ * the amount is the sum of every host's settled share less what the counter holds, never the sum of each host's
9406
+ * shortfall: each shortfall subtracts the counter, so adding them subtracts it once per host and puts back too little.
9407
+ * The sum is in micro-dollars, as `INCRBY` takes it, while the label names dollars.
9408
+ */
9409
+ export function dollarWindowResetChecks(found) {
9410
+ if (!Array.isArray(found) || found.length === 0) return [];
9411
+ const parts = found.map((f) => {
9412
+ const short = f.floor - (f.counter ?? 0);
9413
+ const holds = f.counter === null ? "is missing" : `holds ${usdSigned(f.counter)}`;
9414
+ return `${WINDOW_WORDS[f.window].its} (${f.key}) ${holds} while this host's own run records settled $${formatMicros(f.floor)} into it, so the $${formatMicros(f.cap)} ${WINDOW_WORDS[f.window].cap} cap counts at least $${formatMicros(short)} too little`;
9415
+ });
9416
+ const put = found.map((f) => `\`valkey-cli INCRBY ${f.key} ${f.floor - (f.counter ?? 0)}\` then \`valkey-cli EXPIRE ${f.key} ${f.ttlSeconds}\``);
9417
+ const ends = found.map((f) => `${WINDOW_WORDS[f.window].its} at ${utcMinute(f.endMs)}`);
9418
+ const one = found.length === 1;
9419
+ return [
9420
+ {
9421
+ id: "dollars.window-reset",
9422
+ ok: false,
9423
+ warn: true,
9424
+ label: `${one ? "A dollar window counter is" : "Dollar window counters are"} below what this host's own runs settled into ${one ? "it" : "them"}, so ${one ? "its" : "their"} history was lost (a flushed, replaced or restored Valkey, an evicted key, or a hand edit) and the cap can let at least that much more be spent: ${parts.join("; ")}. Other hosts' runs are not counted here`,
9425
+ fix: `put back at least this host's share for the rest of the window: ${put.join("; ")} (on a fleet, run doctor on every host first, then \`INCRBY\` the sum, in micro-dollars, of what each says its records settled, less what the counter holds now), or lower the cap by what was already spent, or run \`pi-dispatch pause\` and resume once the window ends (${ends.join("; ")}). A counter lowered on purpose is named here until its window ends (docs/costs.md, "When a counter resets")`,
9426
+ },
9427
+ ];
9428
+ }
9429
+
9430
+ /**
9431
+ * Set by the test helper (test/helpers/doctor.mjs), as `forbidDefaultCapacityRead` is: from then on the dollar window
9432
+ * check's DEFAULT reads throw an error doctor does not swallow, so a test that reaches the developer's real logs
9433
+ * directory and Valkey fails loudly instead of judging whatever that machine holds.
9434
+ */
9435
+ let defaultDollarWindowReadForbidden = false;
9436
+ export function forbidDefaultDollarWindowRead() {
9437
+ defaultDollarWindowReadForbidden = true;
9438
+ }
9439
+ const forbiddenDollarRead = () => Object.assign(new Error("doctor reached its real dollar window read in a test: pass readDollarRecords and readDollarCounters"), { [FORBIDDEN_READ]: true });
9440
+
9441
+ /** The default records read: this host's files, a file at a time until `deadlineAt` (`readLocalWindow`). */
9442
+ async function defaultReadDollarRecords({ logsDir, sinceMs, deadlineAt, clock }) {
9443
+ if (defaultDollarWindowReadForbidden) throw forbiddenDollarRead();
9444
+ const { readLocalWindow } = await import("./capacity-records.mjs");
9445
+ return readLocalWindow(logsDir, { sinceMs, deadlineAt, clock });
9446
+ }
9447
+
9448
+ /**
9449
+ * The default counters read: one MGET through a fail-fast client, its connection and its command each bounded by what
9450
+ * is left before `deadlineAt`, so the whole check stays inside its bound. Null when it could not be read.
9451
+ */
9452
+ async function defaultReadDollarCounters({ url, keys, deadlineAt, clock }) {
9453
+ if (defaultDollarWindowReadForbidden) throw forbiddenDollarRead();
9454
+ const left = () => Math.max(0, deadlineAt - clock());
9455
+ if (left() === 0) return null;
9456
+ try {
9457
+ return await withDoctorClient(url, (client) => boundedOp(client.mget(...keys), left()), { connectTimeoutMs: left() });
9458
+ } catch {
9459
+ return null;
9460
+ }
9461
+ }
9462
+
9463
+ /**
9464
+ * The findings of older-state.mjs (`olderStateFindings({ cwd, home, readFile, valkeyContainer, handedOver })`, a promise
9465
+ * of `{ store, label, fix }` each), through `seams.olderStateFindings` when given. Never throws: an answer of another
9466
+ * shape is no finding, and every label and fix is made printable here, the printer not relying on it.
9467
+ */
9468
+ async function olderStateOf(seams, { cwd, home, valkeyContainer, handedOver }) {
9469
+ try {
9470
+ const find = typeof seams.olderStateFindings === "function" ? seams.olderStateFindings : olderStateFindingsReal;
9471
+ const found = await find({ cwd, home, readFile: (path) => readFileSync(path, "utf8"), valkeyContainer, handedOver });
9472
+ return (Array.isArray(found) ? found : []).filter((f) => typeof f?.label === "string" && typeof f?.fix === "string").map((f) => ({ label: printable(f.label), fix: printable(f.fix) }));
9473
+ } catch {
9474
+ return [];
9475
+ }
9476
+ }
9477
+
9478
+ /**
9479
+ * older-state.mjs's `valkeyContainer`: `valkeyContainerOwner`'s verdict on the container `up` starts the deployment's
9480
+ * Valkey as (`docker container inspect pi-dispatch-valkey`, judged by up's own rule with this folder, as given and as its
9481
+ * real path, and VALKEY_URL's port), or null; it never throws. A container docker cannot describe, or none, is a verdict
9482
+ * that is not `ours`, which names nothing. Null itself, so the container is not asked about at all, unless:
9483
+ * - `asked`: this deployment runs jobs on Docker and the daemon answered `docker info`, since doctor spawns no docker
9484
+ * anywhere else (issue #433), and VALKEY_URL was read as the service reads it (the caller's gate);
9485
+ * - and VALKEY_URL names this host by an IPv4 loopback address or `localhost`, where `up` runs a Valkey (it adds none
9486
+ * for another host's, and refuses an IPv6 literal). Elsewhere a `pi-dispatch-valkey` here is not the queue the
9487
+ * worker dials, whatever port it publishes, and the fix would remove it.
9488
+ */
9489
+ function valkeyContainerReader({ spawn, runTimeouts, asked, cwd, valkeyUrl }) {
9490
+ if (!asked || typeof cwd !== "string" || cwd === "") return null;
9491
+ const target = valkeyTarget(valkeyUrl);
9492
+ if (target.error || !isLoopbackHost(target.host) || target.host.includes(":")) return null;
9493
+ let deployment = cwd;
9494
+ try {
9495
+ deployment = realpathSync(cwd);
9496
+ } catch {
9497
+ // Unresolvable: the folder as given, as `up` does.
9498
+ }
9499
+ const query = async (cmd, args) => {
9500
+ const r = await runCmdCapture(spawn, cmd, args, { stdoutOnly: true, timeoutMs: runTimeouts?.cmd ?? RUN_TIMEOUTS.cmd });
9501
+ return { code: r.code, stdout: r.output, stderr: "" };
9502
+ };
9503
+ return async () => {
9504
+ try {
9505
+ return await valkeyContainerOwner(VALKEY_CONTAINER, { dirs: [deployment, cwd], port: target.port, query });
9506
+ } catch {
9507
+ return null;
9508
+ }
9509
+ };
9510
+ }
9511
+
8084
9512
  /**
8085
9513
  * One fact line per host of a capacity report (`INT-CAPACITY-REPORT`), `{ ok: true, label }` each, never a warning:
8086
9514
  * `Host a: last 7d busy 63% (avg 2.1 of 4 slots, full 12%), promised 48% memory / 40% CPU, used 18% CPU of 8, wait p50
@@ -8351,6 +9779,13 @@ export function backendChecks(env, { endpoint = null, daemon = null, fs = { stat
8351
9779
  // that could not start.
8352
9780
  checks.push({ ok: false, label: `PI_EGRESS does not parse, so what this deployment actually gets cannot be determined: ${error.message}`, fix: 'set PI_EGRESS to exactly "0" (off) or "1"/unset (on)' });
8353
9781
  }
9782
+ // Issue #684 (review): the worker's own boot rule for a layer venue with egress off, replayed from `backendRefusals`
9783
+ // so doctor and the worker say one sentence. Only that rule: the floor rules are this section's own lines below.
9784
+ if (switches.PI_EGRESS === false) {
9785
+ for (const refusal of backendRefusals({ backends, backendFloor: {}, egress: false }).filter((r) => r.startsWith("PI_EGRESS=0 cannot run"))) {
9786
+ checks.push({ ok: false, label: refusal, fix: "unset PI_EGRESS (armed is the default), or remove that backend from PI_BACKENDS: the worker refuses to boot otherwise" });
9787
+ }
9788
+ }
8354
9789
 
8355
9790
  // The dispatch landed in slice 4, so the "nothing selects yet" qualifier came off -- and it came off HERE
8356
9791
  // as well as in the code, because a stale caveat on the one surface that makes the table admissible is
@@ -8362,8 +9797,12 @@ export function backendChecks(env, { endpoint = null, daemon = null, fs = { stat
8362
9797
  const d = declarationOf(name, property);
8363
9798
  if (!d) continue;
8364
9799
  // FIRST, ahead of the gate: a control that does not exist is not a control that is unarmed.
9800
+ // A WARNING since issue #707, no longer a ✗: since the openshell venues, a blessed venue legitimately declares
9801
+ // properties absent (`localFolders`, `pausable`), and a ✗ here failed doctor, and so `up`, on every such
9802
+ // deployment. Whether the deployment NEEDS the property is the floor's to say, and that refusal is its own ✗
9803
+ // below (`PI_BACKEND_FLOOR is not met`), as the worker's boot refusal is unchanged.
8365
9804
  if (d.word === ABSENT) {
8366
- checks.push({ ok: false, label: `${name}: ${property} is ABSENT -- ${d.question}`, fix: `this backend does not provide ${property}; a deployment that needs it must not run jobs on ${name}` });
9805
+ checks.push({ ok: false, warn: true, label: `${name}: ${property} is ABSENT -- ${d.question}`, fix: `this backend does not provide ${property}: a PI_BACKEND_FLOOR naming ${property} refuses the boot while ${name} is blessed, so a deployment that needs it must not run jobs on ${name}` });
8367
9806
  continue;
8368
9807
  }
8369
9808
  if (d.armedBy && switches[d.armedBy] === undefined) {
@@ -8916,6 +10355,8 @@ export async function podmanChecks(env, seams, { jobImage, jobImageNote = "" })
8916
10355
  const crashLoop = status === "stopped" || status === "restarting";
8917
10356
  const retried = state.code === 0 && !proxyRunning && /^[a-z]{1,20}$/.test(status ?? "") && !STOPPED_PROXY_STATES.has(status) && !crashLoop;
8918
10357
  checks.push({
10358
+ // Issue #737: docker's proxy line's id, for this venue's proxy (`REPEATED_CHECK_IDS`).
10359
+ id: "egress.proxy",
8919
10360
  ok: proxyRunning,
8920
10361
  ...(retried ? { warn: true } : {}),
8921
10362
  label: proxyRunning ? `podman: egress proxy running under this account's Podman (${proxy})` : state.code === 0 ? `podman: egress proxy is ${/^[a-z]{1,20}$/.test(status ?? "") ? status : "in a state it did not report"} under this account's Podman (${proxy})` : `podman: egress proxy is not under this account's Podman (${proxy})`,
@@ -9266,6 +10707,9 @@ export async function liveChecks(env, seams, facts) {
9266
10707
  // endpoint the job-user line was decided from. The fixture's global directory is never relabelled, like a job's.
9267
10708
  const relabel = relabelsPrivateMounts(facts.daemon?.answered ? facts.daemon.facts : null, facts.endpoint, ids.platform ?? seams.platform);
9268
10709
  const result = await runLiveProbes({
10710
+ // Issue #681: the local venue's builder and CLI, named rather than defaulted.
10711
+ buildArgs: buildDockerRunArgs,
10712
+ bin: "docker",
9269
10713
  image: facts.jobImage ?? jobImageOf(env).image,
9270
10714
  // Issue #596: the deployment's default size, and the `--cpus` ceiling from the same `docker info` answer, so the
9271
10715
  // probe is built at the size a job gets and reads back memory, swap, weight and ceiling against it.
@@ -9860,3 +11304,20 @@ export function liveRunVia(spawn, { bin = "docker" } = {}) {
9860
11304
  child.on("close", (code) => finish(code, "close"));
9861
11305
  });
9862
11306
  }
11307
+
11308
+ /** Diagnose reviewed source bindings without resolving or printing credential values. */
11309
+ export function watchDoctorChecks({ sources = {}, rules = 0, env = {} } = {}) {
11310
+ const entries = Object.entries(sources);
11311
+ if (!entries.length) return [];
11312
+ const checks = [{ id: "watch.sources", ok: true, label: `${entries.length} watch source(s), ${rules} watch rule(s); daily caps are required at load` }];
11313
+ for (const [source, declaration] of entries) {
11314
+ const identity = createHash("sha256").update(source).digest("hex").slice(0, 16);
11315
+ const present = typeof env[declaration.secretEnv] === "string" && env[declaration.secretEnv].length > 0;
11316
+ checks.push({ id: `watch.secret-${identity}`, ok: present, ...(!present ? { warn: true } : {}), label: present ? `watch source ${source}: signing secret is available` : `watch source ${source}: signing secret ${declaration.secretEnv} is missing; push requests return 503`, ...(!present ? { fix: `Set ${declaration.secretEnv} on the receiver host, or use the configured pull source without serving push requests.` } : {}) });
11317
+ if (declaration.pull?.secretEnv) {
11318
+ const name = declaration.pull.secretEnv; const available = typeof env[name] === "string" && env[name].length > 0;
11319
+ checks.push({ id: `watch.pull-${identity}`, ok: available, ...(!available ? { warn: true } : {}), label: available ? `watch source ${source}: pull credential is available` : `watch source ${source}: pull credential ${name} is missing`, ...(!available ? { fix: `Set ${name} on the watch collector host.` } : {}) });
11320
+ }
11321
+ }
11322
+ return checks;
11323
+ }