@principles/pd-cli 1.152.12 → 1.152.13

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 (296) hide show
  1. package/package.json +13 -7
  2. package/CHANGELOG.md +0 -23
  3. package/dist/commands/__tests__/intent-flag-wiring.test.d.ts +0 -9
  4. package/dist/commands/__tests__/intent-flag-wiring.test.d.ts.map +0 -1
  5. package/dist/commands/__tests__/intent-flag-wiring.test.js +0 -237
  6. package/dist/commands/__tests__/intent-flag-wiring.test.js.map +0 -1
  7. package/dist/commands/__tests__/legacy-cleanup.test.d.ts +0 -18
  8. package/dist/commands/__tests__/legacy-cleanup.test.d.ts.map +0 -1
  9. package/dist/commands/__tests__/legacy-cleanup.test.js +0 -467
  10. package/dist/commands/__tests__/legacy-cleanup.test.js.map +0 -1
  11. package/dist/commands/__tests__/mvp-smoke.test.d.ts +0 -15
  12. package/dist/commands/__tests__/mvp-smoke.test.d.ts.map +0 -1
  13. package/dist/commands/__tests__/mvp-smoke.test.js +0 -262
  14. package/dist/commands/__tests__/mvp-smoke.test.js.map +0 -1
  15. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts +0 -2
  16. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts.map +0 -1
  17. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js +0 -60
  18. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js.map +0 -1
  19. package/dist/commands/__tests__/rulecode-flag-wiring.test.d.ts +0 -21
  20. package/dist/commands/__tests__/rulecode-flag-wiring.test.d.ts.map +0 -1
  21. package/dist/commands/__tests__/rulecode-flag-wiring.test.js +0 -186
  22. package/dist/commands/__tests__/rulecode-flag-wiring.test.js.map +0 -1
  23. package/dist/commands/__tests__/rulecode-handler.test.d.ts +0 -16
  24. package/dist/commands/__tests__/rulecode-handler.test.d.ts.map +0 -1
  25. package/dist/commands/__tests__/rulecode-handler.test.js +0 -285
  26. package/dist/commands/__tests__/rulecode-handler.test.js.map +0 -1
  27. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.d.ts +0 -24
  28. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.d.ts.map +0 -1
  29. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js +0 -232
  30. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js.map +0 -1
  31. package/dist/commands/__tests__/runtime-activation-nextaction.test.d.ts +0 -15
  32. package/dist/commands/__tests__/runtime-activation-nextaction.test.d.ts.map +0 -1
  33. package/dist/commands/__tests__/runtime-activation-nextaction.test.js +0 -73
  34. package/dist/commands/__tests__/runtime-activation-nextaction.test.js.map +0 -1
  35. package/dist/commands/__tests__/runtime-probe-config.test.d.ts +0 -20
  36. package/dist/commands/__tests__/runtime-probe-config.test.d.ts.map +0 -1
  37. package/dist/commands/__tests__/runtime-probe-config.test.js +0 -389
  38. package/dist/commands/__tests__/runtime-probe-config.test.js.map +0 -1
  39. package/dist/commands/__tests__/telemetry-flag-wiring.test.d.ts +0 -9
  40. package/dist/commands/__tests__/telemetry-flag-wiring.test.d.ts.map +0 -1
  41. package/dist/commands/__tests__/telemetry-flag-wiring.test.js +0 -76
  42. package/dist/commands/__tests__/telemetry-flag-wiring.test.js.map +0 -1
  43. package/dist/commands/__tests__/version.test.d.ts +0 -2
  44. package/dist/commands/__tests__/version.test.d.ts.map +0 -1
  45. package/dist/commands/__tests__/version.test.js +0 -238
  46. package/dist/commands/__tests__/version.test.js.map +0 -1
  47. package/dist/commands/runtime-uat.guard.test.d.ts +0 -2
  48. package/dist/commands/runtime-uat.guard.test.d.ts.map +0 -1
  49. package/dist/commands/runtime-uat.guard.test.js +0 -153
  50. package/dist/commands/runtime-uat.guard.test.js.map +0 -1
  51. package/dist/services/__tests__/cli-output.test.d.ts +0 -18
  52. package/dist/services/__tests__/cli-output.test.d.ts.map +0 -1
  53. package/dist/services/__tests__/cli-output.test.js +0 -103
  54. package/dist/services/__tests__/cli-output.test.js.map +0 -1
  55. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts +0 -2
  56. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts.map +0 -1
  57. package/dist/services/__tests__/evaluator-runner-deps.test.js +0 -343
  58. package/dist/services/__tests__/evaluator-runner-deps.test.js.map +0 -1
  59. package/dist/services/__tests__/rulehost-readiness.test.d.ts +0 -2
  60. package/dist/services/__tests__/rulehost-readiness.test.d.ts.map +0 -1
  61. package/dist/services/__tests__/rulehost-readiness.test.js +0 -311
  62. package/dist/services/__tests__/rulehost-readiness.test.js.map +0 -1
  63. package/dist/services/__tests__/runtime-adapter-resolver.test.d.ts +0 -18
  64. package/dist/services/__tests__/runtime-adapter-resolver.test.d.ts.map +0 -1
  65. package/dist/services/__tests__/runtime-adapter-resolver.test.js +0 -673
  66. package/dist/services/__tests__/runtime-adapter-resolver.test.js.map +0 -1
  67. package/dist/utils/production-workspace-guard.test.d.ts +0 -2
  68. package/dist/utils/production-workspace-guard.test.d.ts.map +0 -1
  69. package/dist/utils/production-workspace-guard.test.js +0 -137
  70. package/dist/utils/production-workspace-guard.test.js.map +0 -1
  71. package/scripts/llm-dogfood.ts +0 -456
  72. package/scripts/migrate-illegal-expected-decision.ts +0 -252
  73. package/src/commands/__tests__/intent-flag-wiring.test.ts +0 -282
  74. package/src/commands/__tests__/legacy-cleanup.test.ts +0 -602
  75. package/src/commands/__tests__/mvp-smoke.test.ts +0 -300
  76. package/src/commands/__tests__/pain-retry-maxTokens-flag.test.ts +0 -73
  77. package/src/commands/__tests__/rulecode-flag-wiring.test.ts +0 -237
  78. package/src/commands/__tests__/rulecode-handler.test.ts +0 -369
  79. package/src/commands/__tests__/run-rulehost-flag-wiring.test.ts +0 -292
  80. package/src/commands/__tests__/runtime-activation-nextaction.test.ts +0 -81
  81. package/src/commands/__tests__/runtime-probe-config.test.ts +0 -432
  82. package/src/commands/__tests__/telemetry-flag-wiring.test.ts +0 -84
  83. package/src/commands/__tests__/version.test.ts +0 -251
  84. package/src/commands/admission-gate.ts +0 -30
  85. package/src/commands/artifact.ts +0 -82
  86. package/src/commands/build-trajectory-evidence.ts +0 -298
  87. package/src/commands/candidate.ts +0 -1250
  88. package/src/commands/codex-ingest-catchup.ts +0 -114
  89. package/src/commands/codex-ingest-quarantine.ts +0 -127
  90. package/src/commands/codex-reconcile.ts +0 -84
  91. package/src/commands/codex-setup.ts +0 -476
  92. package/src/commands/codex-worker.ts +0 -185
  93. package/src/commands/command-helpers.ts +0 -24
  94. package/src/commands/config-doctor.ts +0 -193
  95. package/src/commands/console.ts +0 -797
  96. package/src/commands/context.ts +0 -72
  97. package/src/commands/demo-story-a.ts +0 -241
  98. package/src/commands/diagnose.ts +0 -756
  99. package/src/commands/errors-list.ts +0 -441
  100. package/src/commands/evolution-tasks-list.ts +0 -48
  101. package/src/commands/evolution-tasks-show.ts +0 -62
  102. package/src/commands/flow.ts +0 -60
  103. package/src/commands/health-codex.ts +0 -576
  104. package/src/commands/health.ts +0 -315
  105. package/src/commands/history.ts +0 -63
  106. package/src/commands/intent.ts +0 -457
  107. package/src/commands/legacy-cleanup.ts +0 -531
  108. package/src/commands/legacy-import.ts +0 -104
  109. package/src/commands/mvp-smoke.ts +0 -160
  110. package/src/commands/pain-evidence.ts +0 -226
  111. package/src/commands/pain-list.ts +0 -239
  112. package/src/commands/pain-record.ts +0 -612
  113. package/src/commands/pain-retry.ts +0 -916
  114. package/src/commands/principles-stats.ts +0 -700
  115. package/src/commands/proven-channel-baseline.ts +0 -115
  116. package/src/commands/quality-scorecard.ts +0 -272
  117. package/src/commands/remediation-output.ts +0 -66
  118. package/src/commands/rulecode.ts +0 -465
  119. package/src/commands/run.ts +0 -89
  120. package/src/commands/runtime-activation.ts +0 -1629
  121. package/src/commands/runtime-artifact-repair.ts +0 -524
  122. package/src/commands/runtime-canary.ts +0 -395
  123. package/src/commands/runtime-compatibility-scan.ts +0 -105
  124. package/src/commands/runtime-diagnostics-export.ts +0 -229
  125. package/src/commands/runtime-features.ts +0 -153
  126. package/src/commands/runtime-gfi-snapshot.ts +0 -135
  127. package/src/commands/runtime-health-snapshot.ts +0 -108
  128. package/src/commands/runtime-init.ts +0 -429
  129. package/src/commands/runtime-internalization-enqueue-successors.ts +0 -530
  130. package/src/commands/runtime-internalization-integrity-repair.ts +0 -79
  131. package/src/commands/runtime-internalization-integrity.ts +0 -107
  132. package/src/commands/runtime-internalization-queue.ts +0 -135
  133. package/src/commands/runtime-internalization-retry.ts +0 -191
  134. package/src/commands/runtime-internalization-run-once.ts +0 -791
  135. package/src/commands/runtime-internalization-run-rulehost.ts +0 -749
  136. package/src/commands/runtime-internalization-wake-once.ts +0 -87
  137. package/src/commands/runtime-pain-flood-simulation.ts +0 -121
  138. package/src/commands/runtime-pruning.ts +0 -438
  139. package/src/commands/runtime-recovery-failed-tasks.ts +0 -258
  140. package/src/commands/runtime-recovery.ts +0 -109
  141. package/src/commands/runtime-synthetic-baseline.ts +0 -70
  142. package/src/commands/runtime-uat.guard.test.ts +0 -175
  143. package/src/commands/runtime-uat.ts +0 -380
  144. package/src/commands/runtime.ts +0 -473
  145. package/src/commands/samples-list.ts +0 -39
  146. package/src/commands/samples-review.ts +0 -36
  147. package/src/commands/task.ts +0 -271
  148. package/src/commands/telemetry.ts +0 -349
  149. package/src/commands/trace.ts +0 -174
  150. package/src/commands/trajectory-db-unavailable.ts +0 -19
  151. package/src/commands/trajectory.ts +0 -64
  152. package/src/commands/version.ts +0 -49
  153. package/src/config-reader.ts +0 -122
  154. package/src/index.ts +0 -1276
  155. package/src/legacy/legacy-import.ts +0 -179
  156. package/src/legacy/session-history-import.ts +0 -203
  157. package/src/resolve-workspace.ts +0 -106
  158. package/src/services/__tests__/cli-output.test.ts +0 -130
  159. package/src/services/__tests__/evaluator-runner-deps.test.ts +0 -382
  160. package/src/services/__tests__/rulehost-readiness.test.ts +0 -363
  161. package/src/services/__tests__/runtime-adapter-resolver.test.ts +0 -793
  162. package/src/services/cli-output.ts +0 -95
  163. package/src/services/config-doctor.ts +0 -697
  164. package/src/services/console-launcher.ts +0 -537
  165. package/src/services/demo-rule-compiler.ts +0 -40
  166. package/src/services/demo-story-a-runner.ts +0 -471
  167. package/src/services/mainline-snapshot-assembler.ts +0 -579
  168. package/src/services/pain-flood-simulation-runner.ts +0 -462
  169. package/src/services/pd-config-loader.ts +0 -433
  170. package/src/services/proven-channel-baseline-runner.ts +0 -157
  171. package/src/services/quality-scorecard/data-extractor.ts +0 -150
  172. package/src/services/quality-scorecard/local-evaluator.ts +0 -142
  173. package/src/services/quality-scorecard/strong-model-gate.ts +0 -202
  174. package/src/services/resolve-runtime-from-pd-config.ts +0 -230
  175. package/src/services/rulehost-pipeline-runner.ts +0 -1214
  176. package/src/services/rulehost-readiness.ts +0 -326
  177. package/src/services/runtime-adapter-resolver.ts +0 -364
  178. package/src/services/synthetic-baseline-runner.ts +0 -400
  179. package/src/services/version-report.ts +0 -253
  180. package/src/services/workspace-tool-semantics.ts +0 -26
  181. package/src/utils/path-security.ts +0 -96
  182. package/src/utils/production-workspace-guard.test.ts +0 -157
  183. package/src/utils/production-workspace-guard.ts +0 -210
  184. package/tests/bdd/cli-contract.steps.ts +0 -346
  185. package/tests/bdd/principles-stats.steps.ts +0 -211
  186. package/tests/bdd/support/gherkin-loader.ts +0 -147
  187. package/tests/bdd/support/repo-root.ts +0 -62
  188. package/tests/bdd/support/vitest-bdd.ts +0 -179
  189. package/tests/commands/admission-gate-coverage.test.ts +0 -79
  190. package/tests/commands/build-trajectory-evidence.test.ts +0 -508
  191. package/tests/commands/candidate-audit-repair.test.ts +0 -421
  192. package/tests/commands/candidate-intake.test.ts +0 -732
  193. package/tests/commands/candidate-internalization-backfill.test.ts +0 -548
  194. package/tests/commands/candidate-internalize-lineage.test.ts +0 -628
  195. package/tests/commands/candidate-internalize.test.ts +0 -299
  196. package/tests/commands/candidate-route.test.ts +0 -329
  197. package/tests/commands/candidate-show.test.ts +0 -95
  198. package/tests/commands/cli-command-tree.test.ts +0 -144
  199. package/tests/commands/cli-help-snapshot.test.ts +0 -155
  200. package/tests/commands/cli-skill-contract.test.ts +0 -121
  201. package/tests/commands/codex-consent-reversibility.steps.test.ts +0 -299
  202. package/tests/commands/codex-ingest-quarantine.test.ts +0 -136
  203. package/tests/commands/codex-setup.test.ts +0 -297
  204. package/tests/commands/codex-worker-daemon.test.ts +0 -95
  205. package/tests/commands/codex-worker-registration.test.ts +0 -207
  206. package/tests/commands/config-doctor.test.ts +0 -336
  207. package/tests/commands/console-launcher-edge-cases.test.ts +0 -388
  208. package/tests/commands/console-open.test.ts +0 -1381
  209. package/tests/commands/context.test.ts +0 -114
  210. package/tests/commands/demo-story-a.test.ts +0 -318
  211. package/tests/commands/diagnose.test.ts +0 -1803
  212. package/tests/commands/errors-list.test.ts +0 -679
  213. package/tests/commands/evolution-tasks-list.test.ts +0 -41
  214. package/tests/commands/evolution-tasks-show.test.ts +0 -46
  215. package/tests/commands/health-codex.test.ts +0 -349
  216. package/tests/commands/health-host-wiring.test.ts +0 -76
  217. package/tests/commands/health-reliability.test.ts +0 -99
  218. package/tests/commands/health.test.ts +0 -413
  219. package/tests/commands/intent.test.ts +0 -321
  220. package/tests/commands/legacy-cleanup.test.ts +0 -148
  221. package/tests/commands/pain-evidence.test.ts +0 -518
  222. package/tests/commands/pain-list.test.ts +0 -219
  223. package/tests/commands/pain-record-async.test.ts +0 -335
  224. package/tests/commands/pain-record-session-parser.test.ts +0 -228
  225. package/tests/commands/pain-record.test.ts +0 -851
  226. package/tests/commands/pain-retry.test.ts +0 -1121
  227. package/tests/commands/plugin-config-resolution-cutover.test.ts +0 -229
  228. package/tests/commands/pri-393-runtime-config-unification.test.ts +0 -443
  229. package/tests/commands/principles-stats-wiring.test.ts +0 -135
  230. package/tests/commands/principles-stats.test.ts +0 -274
  231. package/tests/commands/product-path-regression.test.ts +0 -86
  232. package/tests/commands/proven-channel-baseline.test.ts +0 -441
  233. package/tests/commands/rulecode.test.ts +0 -177
  234. package/tests/commands/run-rulehost-handler.test.ts +0 -908
  235. package/tests/commands/runtime-activation-approve-flag-wiring.test.ts +0 -227
  236. package/tests/commands/runtime-activation-deactivate-flag-wiring.test.ts +0 -167
  237. package/tests/commands/runtime-activation-dispatch-flag-wiring.test.ts +0 -262
  238. package/tests/commands/runtime-activation-governance-audit.test.ts +0 -95
  239. package/tests/commands/runtime-activation-list-flag-wiring.test.ts +0 -193
  240. package/tests/commands/runtime-activation-promote-flag-wiring.test.ts +0 -248
  241. package/tests/commands/runtime-activation-shadow-telemetry.test.ts +0 -130
  242. package/tests/commands/runtime-activation.test.ts +0 -2052
  243. package/tests/commands/runtime-artifact-repair-registration.test.ts +0 -74
  244. package/tests/commands/runtime-artifact-repair.test.ts +0 -404
  245. package/tests/commands/runtime-canary.test.ts +0 -430
  246. package/tests/commands/runtime-compatibility-scan.test.ts +0 -146
  247. package/tests/commands/runtime-diagnostics-export.test.ts +0 -175
  248. package/tests/commands/runtime-features.test.ts +0 -249
  249. package/tests/commands/runtime-health-snapshot.test.ts +0 -358
  250. package/tests/commands/runtime-init-empty-workspace.test.ts +0 -252
  251. package/tests/commands/runtime-init.test.ts +0 -420
  252. package/tests/commands/runtime-internalization-enqueue-successors.test.ts +0 -782
  253. package/tests/commands/runtime-internalization-integrity-repair.test.ts +0 -239
  254. package/tests/commands/runtime-internalization-integrity.test.ts +0 -140
  255. package/tests/commands/runtime-internalization-queue.test.ts +0 -380
  256. package/tests/commands/runtime-internalization-retry-owner-authority.test.ts +0 -431
  257. package/tests/commands/runtime-internalization-run-once-evaluator-parity.test.ts +0 -269
  258. package/tests/commands/runtime-internalization-run-once-language.test.ts +0 -303
  259. package/tests/commands/runtime-internalization-run-once-real-config.test.ts +0 -237
  260. package/tests/commands/runtime-internalization-run-once-rollout-parity.test.ts +0 -706
  261. package/tests/commands/runtime-internalization-run-once.test.ts +0 -1791
  262. package/tests/commands/runtime-internalization-wake-once.test.ts +0 -171
  263. package/tests/commands/runtime-internalization.test.ts +0 -53
  264. package/tests/commands/runtime-pain-flood-simulation.test.ts +0 -418
  265. package/tests/commands/runtime-pruning.test.ts +0 -694
  266. package/tests/commands/runtime-recovery-failed-tasks.test.ts +0 -328
  267. package/tests/commands/runtime-recovery.test.ts +0 -120
  268. package/tests/commands/runtime-synthetic-baseline.test.ts +0 -249
  269. package/tests/commands/runtime-uat.test.ts +0 -397
  270. package/tests/commands/runtime.test.ts +0 -392
  271. package/tests/commands/samples-list.test.ts +0 -43
  272. package/tests/commands/samples-review.test.ts +0 -41
  273. package/tests/commands/task.test.ts +0 -153
  274. package/tests/commands/telemetry.test.ts +0 -190
  275. package/tests/commands/trace.test.ts +0 -316
  276. package/tests/config-reader.test.ts +0 -143
  277. package/tests/e2e/candidate-intake-e2e.test.ts +0 -338
  278. package/tests/e2e/cli-full-flow.test.ts +0 -233
  279. package/tests/e2e/cross-package-acceptance.test.ts +0 -635
  280. package/tests/helpers/pd-cli-path.ts +0 -5
  281. package/tests/pd-cli-smoke.test.ts +0 -13
  282. package/tests/resolve-workspace.test.ts +0 -196
  283. package/tests/services/config-doctor-signal-health.test.ts +0 -109
  284. package/tests/services/console-launcher.test.ts +0 -114
  285. package/tests/services/demo-rule-compiler.test.ts +0 -242
  286. package/tests/services/mainline-snapshot-assembler.test.ts +0 -572
  287. package/tests/services/pd-config-loader.test.ts +0 -505
  288. package/tests/services/proven-channel-baseline-runner.test.ts +0 -30
  289. package/tests/services/quality-scorecard/strong-model-gate.test.ts +0 -133
  290. package/tests/services/resolve-runtime-from-pd-config.test.ts +0 -485
  291. package/tests/services/rulehost-pipeline-e2e.test.ts +0 -538
  292. package/tests/services/rulehost-pipeline-runner.test.ts +0 -1242
  293. package/tests/services/workspace-tool-semantics.test.ts +0 -76
  294. package/tests/utils/path-security.test.ts +0 -180
  295. package/tsconfig.json +0 -26
  296. package/vitest.config.ts +0 -10
@@ -1,697 +0,0 @@
1
- /**
2
- * pd config doctor — Discover and explain PD / OpenClaw configuration state.
3
- *
4
- * PRI-305: Cutover to .pd/config.yaml.
5
- * - Feature flags and internal agent runtime bindings come from .pd/config.yaml
6
- * - .pd/feature-flags.yaml and .state/workflows.yaml are no longer production inputs
7
- * - Legacy files are detected and reported as warnings
8
- *
9
- * PRI-299 MVP UX: provides a single, read-only view of:
10
- * - PD workspace config paths (with existence checks)
11
- * - OpenClaw config paths (with existence checks)
12
- * - Effective feature flags from .pd/config.yaml
13
- * - Internal agent runtime binding readiness from .pd/config.yaml
14
- * - Provider/model/auth status (classified)
15
- *
16
- * Constraints:
17
- * - NEVER reads or returns API key values, env var values, or raw config bytes.
18
- * - All file reads are bounded; YAML/JSON is treated as `unknown` and validated.
19
- * - Missing/malformed config produces a structured warning, never a crash.
20
- * - Failures include `reason` and `nextAction` for operator guidance.
21
- */
22
-
23
- import * as fs from 'fs';
24
- import * as path from 'path';
25
- import Database from 'better-sqlite3';
26
- import type { Database as BetterSqliteDatabase } from 'better-sqlite3';
27
- import {
28
- loadPdConfig,
29
- computeFlagsFromLoadResult,
30
- redactLoadResult,
31
- getPdConfigPath,
32
- } from './pd-config-loader.js';
33
- import { MVP_CHANNEL_IDS } from '@principles/core/runtime-v2';
34
- import type {
35
- RedactedAgentSummary,
36
- RedactedRuntimeProfileSummary,
37
- } from '@principles/core/runtime-v2';
38
-
39
- // ─── Public types ────────────────────────────────────────────────────────────
40
-
41
- export type DoctorClassification =
42
- | 'healthy'
43
- | 'config_missing'
44
- | 'auth_missing'
45
- | 'needs_probe'
46
- | 'rate_limit'
47
- | 'unavailable'
48
- | 'parse_failure'
49
- | 'unknown';
50
-
51
- export type DoctorStatus = 'ok' | 'degraded' | 'failed';
52
-
53
- export interface ConfigPathEntry {
54
- path: string;
55
- exists: boolean;
56
- parseable?: boolean;
57
- }
58
-
59
- export interface ProviderHealthEntry {
60
- provider: string | null;
61
- model: string | null;
62
- apiKeyEnv: string | null;
63
- apiKeyPresent: boolean;
64
- classification: DoctorClassification;
65
- reason: string;
66
- nextAction: string;
67
- source: string;
68
- }
69
-
70
- export interface FeatureFlagSummary {
71
- source: string;
72
- configPath: string;
73
- enabledMvpChannels: string[];
74
- disabledFlags: string[];
75
- warnings: string[];
76
- }
77
-
78
- export interface InternalAgentDiagnostics {
79
- name: string;
80
- enabled: boolean;
81
- runtimeProfileId: string;
82
- runtimeProfileLabel: string;
83
- readiness: 'ready' | 'not_ready' | 'needs_setup' | 'disabled' | 'unknown';
84
- provider: string | null;
85
- model: string | null;
86
- apiKeyEnv: string | null;
87
- apiKeyPresent: boolean;
88
- reason: string;
89
- nextAction: string;
90
- }
91
-
92
- export interface DoctorOutput {
93
- status: DoctorStatus;
94
- workspaceDir: string;
95
- pdConfigPaths: {
96
- workspaceDir: ConfigPathEntry;
97
- pdDir: ConfigPathEntry;
98
- configYaml: ConfigPathEntry;
99
- stateDb: ConfigPathEntry;
100
- };
101
- openclawConfigPaths: {
102
- openclawHome: ConfigPathEntry;
103
- openclawConfig: ConfigPathEntry;
104
- };
105
- featureFlags: FeatureFlagSummary;
106
- internalAgents: InternalAgentDiagnostics[];
107
- providerHealth: ProviderHealthEntry[];
108
- warnings: string[];
109
- reason?: string;
110
- nextActions: string[];
111
- /** Legacy files detected (informational only, not used for resolution) */
112
- legacyFilesDetected: string[];
113
- /** PRI-404: Next actions for removing legacy files */
114
- legacyFileNextActions: string[];
115
- /** PRI-788 G4: 纠正信号检测健康(.state/signal-health.json,缺失=unknown) */
116
- signalHealth: SignalHealthEntry;
117
- }
118
-
119
- export interface SignalHealthEntry {
120
- status: DoctorStatus | 'unknown';
121
- counts: {
122
- stage1Strong: number;
123
- stage2Confirmed: number;
124
- stage2Queued: number;
125
- stage2Dropped: number;
126
- pendingCount: number;
127
- } | null;
128
- lastStage2SuccessAt: string | null;
129
- observerLastSuccessAt: string | null;
130
- observerConsecutiveFailures: number | null;
131
- updatedAt: string | null;
132
- reason: string;
133
- nextAction: string;
134
- }
135
-
136
- // ─── Helpers ────────────────────────────────────────────────────────────────
137
-
138
- export function getOpenClawHome(): string {
139
- const home = process.env.HOME
140
- || process.env.USERPROFILE
141
- || (process.env.HOMEDRIVE && process.env.HOMEPATH ? process.env.HOMEDRIVE + process.env.HOMEPATH : '');
142
- if (!home) return path.join(process.cwd(), '.openclaw');
143
- return path.join(home, '.openclaw');
144
- }
145
-
146
- export function getOpenClawConfigPath(): string {
147
- return path.join(getOpenClawHome(), 'openclaw.json');
148
- }
149
-
150
- function pathEntry(p: string): ConfigPathEntry {
151
- return { path: p, exists: fs.existsSync(p) };
152
- }
153
-
154
- const RATE_LIMIT_KEYWORDS = ['rate_limit', 'rate-limit', '429', 'too many requests', 'rpm exhausted'];
155
- const AUTH_MISSING_KEYWORDS = ['auth_missing', 'unauthorized', '401', 'api key', 'no api key', 'api_key missing'];
156
- const UNAVAILABLE_KEYWORDS = ['unavailable', 'model fallback', 'candidate_failed', 'embedded agent failed'];
157
-
158
- function classifyText(text: string): DoctorClassification | null {
159
- const lowered = text.toLowerCase();
160
- for (const kw of RATE_LIMIT_KEYWORDS) {
161
- if (lowered.includes(kw)) return 'rate_limit';
162
- }
163
- for (const kw of AUTH_MISSING_KEYWORDS) {
164
- if (lowered.includes(kw)) return 'auth_missing';
165
- }
166
- for (const kw of UNAVAILABLE_KEYWORDS) {
167
- if (lowered.includes(kw)) return 'unavailable';
168
- }
169
- return null;
170
- }
171
-
172
- // ─── State DB Inspection (unchanged from PRI-299) ────────────────────────────
173
-
174
- export interface InspectStateDbOptions {
175
- maxRows?: number;
176
- maxAgeMs?: number;
177
- }
178
-
179
- export interface RecentProviderSignal {
180
- classification: DoctorClassification;
181
- reason: string;
182
- observedAt: string | null;
183
- }
184
-
185
- export interface StateDbSignalResult {
186
- signal: RecentProviderSignal | null;
187
- dbReachable: boolean;
188
- warning?: string;
189
- }
190
-
191
- const DEFAULT_MAX_ROWS = 50;
192
- const DEFAULT_MAX_AGE_MS = 24 * 60 * 60 * 1000;
193
-
194
- export async function inspectStateDbForProviderSignal(
195
- stateDbPath: string,
196
- nowMs: number = Date.now(),
197
- opts: InspectStateDbOptions = {},
198
- ): Promise<StateDbSignalResult> {
199
- const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
200
- const maxAgeMs = opts.maxAgeMs ?? DEFAULT_MAX_AGE_MS;
201
-
202
- if (!fs.existsSync(stateDbPath)) {
203
- return { signal: null, dbReachable: false };
204
- }
205
-
206
- let db: BetterSqliteDatabase;
207
- try {
208
- db = new Database(stateDbPath, { readonly: true, fileMustExist: true });
209
- } catch (err) {
210
- return {
211
- signal: null,
212
- dbReachable: false,
213
- warning: `state.db present but readonly open failed: ${err instanceof Error ? err.message : String(err)}`,
214
- };
215
- }
216
-
217
- try {
218
- const tableInfo = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='tasks'").get() as { name: string } | undefined;
219
- if (!tableInfo) {
220
- return { signal: null, dbReachable: true, warning: 'state.db has no tasks table — pipeline not initialized yet' };
221
- }
222
-
223
- const taskCols = db.prepare("PRAGMA table_info(tasks)").all() as { name: string }[];
224
- const taskColNames = new Set(taskCols.map((c) => c.name));
225
- const hasErrorMessage = taskColNames.has('error_message');
226
- const hasLastErrorMessage = taskColNames.has('last_error_message');
227
- const hasFailureCategory = taskColNames.has('failure_category');
228
- const hasErrorCategory = taskColNames.has('error_category');
229
- const hasUpdatedAt = taskColNames.has('updated_at');
230
- const hasLastErrorAt = taskColNames.has('last_error_at');
231
- const hasCreatedAt = taskColNames.has('created_at');
232
-
233
- if (!hasErrorMessage && !hasLastErrorMessage) {
234
- return { signal: null, dbReachable: true, warning: 'state.db tasks table has no error_message column — provider signal unavailable' };
235
- }
236
-
237
- const errorCol = hasErrorMessage ? 'error_message' : 'last_error_message';
238
- const tsCol = hasUpdatedAt ? 'updated_at' : hasLastErrorAt ? 'last_error_at' : hasCreatedAt ? 'created_at' : null;
239
- const tsExpr = tsCol ? `, ${tsCol} AS ts` : '';
240
- const whereExpr = tsCol ? `WHERE ${tsCol} >= ?` : '';
241
- const params: unknown[] = tsCol ? [nowMs - maxAgeMs] : [];
242
-
243
- const rows = db.prepare(
244
- `SELECT ${errorCol} AS error${tsExpr} FROM tasks ${whereExpr} ORDER BY rowid DESC LIMIT ?`,
245
- ).all(...params, maxRows) as { error: unknown; ts?: unknown }[];
246
-
247
- let mostRecentObservedAt: number | null = null;
248
- let aggregate = '';
249
- for (const row of rows) {
250
- if (typeof row.error !== 'string') continue;
251
- aggregate += ` ${row.error}`;
252
- if (typeof row.ts === 'number' && (mostRecentObservedAt === null || row.ts > mostRecentObservedAt)) {
253
- mostRecentObservedAt = row.ts;
254
- }
255
- }
256
-
257
- if (hasErrorCategory || hasFailureCategory) {
258
- const catCol = hasErrorCategory ? 'error_category' : 'failure_category';
259
- const catRows = db.prepare(
260
- `SELECT ${catCol} AS cat${tsCol ? `, ${tsCol} AS ts` : ''} FROM tasks WHERE ${catCol} IS NOT NULL ${tsCol ? `AND ${tsCol} >= ?` : ''} ORDER BY rowid DESC LIMIT ?`,
261
- ).all(...(tsCol ? [nowMs - maxAgeMs] : []), maxRows) as { cat: unknown; ts?: unknown }[];
262
- for (const row of catRows) {
263
- if (typeof row.cat === 'string') {
264
- aggregate += ` ${row.cat}`;
265
- }
266
- }
267
- }
268
-
269
- const classification = classifyText(aggregate);
270
- if (classification === null) {
271
- return { signal: null, dbReachable: true };
272
- }
273
-
274
- return {
275
- signal: {
276
- classification,
277
- reason: `Recent task error matches '${classification}' signature (state.db scan)`,
278
- observedAt: mostRecentObservedAt ? new Date(mostRecentObservedAt).toISOString() : null,
279
- },
280
- dbReachable: true,
281
- };
282
- } catch (err) {
283
- return {
284
- signal: null,
285
- dbReachable: false,
286
- warning: `state.db scan failed: ${err instanceof Error ? err.message : String(err)}`,
287
- };
288
- } finally {
289
- try { db.close(); } catch { /* best effort */ }
290
- }
291
- }
292
-
293
- // ─── Internal Agent Diagnostics from .pd/config.yaml ─────────────────────────
294
-
295
- function diagnoseInternalAgent(
296
- agent: RedactedAgentSummary,
297
- profile: RedactedRuntimeProfileSummary | undefined,
298
- ): InternalAgentDiagnostics {
299
- if (!agent.enabled) {
300
- return {
301
- name: agent.name,
302
- enabled: false,
303
- runtimeProfileId: agent.runtimeProfileId,
304
- runtimeProfileLabel: agent.runtimeProfileLabel,
305
- readiness: 'disabled',
306
- provider: null,
307
- model: null,
308
- apiKeyEnv: null,
309
- apiKeyPresent: false,
310
- reason: `${agent.name} is disabled in .pd/config.yaml`,
311
- nextAction: `Set internalAgents.agents.${agent.name}.enabled=true in .pd/config.yaml to enable`,
312
- };
313
- }
314
-
315
- // Agent is enabled — check profile readiness
316
- if (!profile) {
317
- return {
318
- name: agent.name,
319
- enabled: true,
320
- runtimeProfileId: agent.runtimeProfileId,
321
- runtimeProfileLabel: agent.runtimeProfileLabel,
322
- readiness: 'needs_setup',
323
- provider: null,
324
- model: null,
325
- apiKeyEnv: null,
326
- apiKeyPresent: false,
327
- reason: `Runtime profile '${agent.runtimeProfileId}' not found in .pd/config.yaml`,
328
- nextAction: `Add runtime profile '${agent.runtimeProfileId}' to .pd/config.yaml runtimeProfiles, or change the agent's runtimeProfile reference`,
329
- };
330
- }
331
-
332
- // Check apiKeyEnv for pi-ai profiles
333
- if (profile.type === 'pi-ai') {
334
- const apiKeyEnv = profile.apiKeyEnv ?? null;
335
- const apiKeyPresent = !!apiKeyEnv && Object.prototype.hasOwnProperty.call(process.env, apiKeyEnv) && !!process.env[apiKeyEnv];
336
-
337
- if (!apiKeyEnv) {
338
- return {
339
- name: agent.name,
340
- enabled: true,
341
- runtimeProfileId: agent.runtimeProfileId,
342
- runtimeProfileLabel: agent.runtimeProfileLabel,
343
- readiness: 'needs_setup',
344
- provider: profile.provider ?? null,
345
- model: profile.model ?? null,
346
- apiKeyEnv: null,
347
- apiKeyPresent: false,
348
- reason: `pi-ai profile '${profile.id}' missing apiKeyEnv`,
349
- nextAction: `Add apiKeyEnv to runtime profile '${profile.id}' in .pd/config.yaml`,
350
- };
351
- }
352
-
353
- if (!apiKeyPresent) {
354
- return {
355
- name: agent.name,
356
- enabled: true,
357
- runtimeProfileId: agent.runtimeProfileId,
358
- runtimeProfileLabel: agent.runtimeProfileLabel,
359
- readiness: 'needs_setup',
360
- provider: profile.provider ?? null,
361
- model: profile.model ?? null,
362
- apiKeyEnv,
363
- apiKeyPresent: false,
364
- reason: `Environment variable '${apiKeyEnv}' is not set or empty`,
365
- nextAction: `Set the environment variable '${apiKeyEnv}' with a valid API key`,
366
- };
367
- }
368
-
369
- // pi-ai with key present — check state.db for signals
370
- return {
371
- name: agent.name,
372
- enabled: true,
373
- runtimeProfileId: agent.runtimeProfileId,
374
- runtimeProfileLabel: agent.runtimeProfileLabel,
375
- readiness: 'not_ready', // runtime availability unknown without actual probe
376
- provider: profile.provider ?? null,
377
- model: profile.model ?? null,
378
- apiKeyEnv,
379
- apiKeyPresent: true,
380
- reason: `pi-ai profile configured with apiKeyEnv='${apiKeyEnv}' (key present); runtime availability unknown`,
381
- nextAction: 'Run pd runtime probe to verify end-to-end connectivity',
382
- };
383
- }
384
-
385
- // OpenClaw profile
386
- if (profile.readiness === 'needs_setup') {
387
- return {
388
- name: agent.name,
389
- enabled: true,
390
- runtimeProfileId: agent.runtimeProfileId,
391
- runtimeProfileLabel: agent.runtimeProfileLabel,
392
- readiness: 'needs_setup',
393
- provider: null,
394
- model: null,
395
- apiKeyEnv: null,
396
- apiKeyPresent: false,
397
- reason: `OpenClaw profile '${profile.id}' needs setup (missing provider/model)`,
398
- nextAction: `Configure provider and model in runtime profile '${profile.id}' in .pd/config.yaml`,
399
- };
400
- }
401
-
402
- return {
403
- name: agent.name,
404
- enabled: true,
405
- runtimeProfileId: agent.runtimeProfileId,
406
- runtimeProfileLabel: agent.runtimeProfileLabel,
407
- readiness: 'ready',
408
- provider: null,
409
- model: null,
410
- apiKeyEnv: null,
411
- apiKeyPresent: false,
412
- reason: `OpenClaw profile '${profile.id}' is configured and ready`,
413
- nextAction: 'No action required',
414
- };
415
- }
416
-
417
- // ─── Signal detection health (PRI-788 G4) ───────────────────────────────────
418
-
419
- // PRI-788 G4 契约:健康产物 >24h 未更新即视为 degraded(PR 描述与下方 reason 文案
420
- // 均写 >24h;此前常量为 25h,会让 24–25h 之间错误地显示健康)。
421
- const SIGNAL_HEALTH_STALE_MS = 24 * 60 * 60 * 1000;
422
- /** observer 连续失败超过该次数(≈1 小时无成功轮)→ degraded */
423
- const OBSERVER_FAILURE_DEGRADED_THRESHOLD = 4;
424
-
425
- function isStringRecord(v: unknown): v is Record<string, unknown> {
426
- return typeof v === 'object' && v !== null;
427
- }
428
-
429
- function numberOr(v: unknown, fallback: number): number {
430
- return typeof v === 'number' && Number.isFinite(v) ? v : fallback;
431
- }
432
-
433
- function stringOrNull(v: unknown): string | null {
434
- return typeof v === 'string' ? v : null;
435
- }
436
-
437
- /**
438
- * Read + classify `.state/signal-health.json` (written by the OpenClaw plugin).
439
- * rc-1/rc-2: file content parsed as unknown; malformed/missing → status
440
- * 'unknown' with a next action, never a throw.
441
- */
442
- export function buildSignalHealthEntry(stateDir: string): SignalHealthEntry {
443
- const unknownEntry: SignalHealthEntry = {
444
- status: 'unknown',
445
- counts: null,
446
- lastStage2SuccessAt: null,
447
- observerLastSuccessAt: null,
448
- observerConsecutiveFailures: null,
449
- updatedAt: null,
450
- reason: 'signal-health.json missing or unreadable (plugin not running, or pre-G4 runtime)',
451
- nextAction: 'If correction detection should be active, verify the OpenClaw gateway is running and the signal_collector / correction_observer flags are enabled',
452
- };
453
- let parsed: unknown;
454
- try {
455
- parsed = JSON.parse(fs.readFileSync(path.join(stateDir, 'signal-health.json'), 'utf-8'));
456
- } catch {
457
- return unknownEntry;
458
- }
459
- if (!isStringRecord(parsed)) return unknownEntry;
460
-
461
- const failures = numberOr(parsed.observerConsecutiveFailures, 0);
462
- const updatedAt = stringOrNull(parsed.updatedAt);
463
- const entry: SignalHealthEntry = {
464
- status: 'ok',
465
- counts: {
466
- stage1Strong: numberOr(parsed.stage1Strong, 0),
467
- stage2Confirmed: numberOr(parsed.stage2Confirmed, 0),
468
- stage2Queued: numberOr(parsed.stage2Queued, 0),
469
- stage2Dropped: numberOr(parsed.stage2Dropped, 0),
470
- pendingCount: numberOr(parsed.pendingCount, 0),
471
- },
472
- lastStage2SuccessAt: stringOrNull(parsed.lastStage2SuccessAt),
473
- observerLastSuccessAt: stringOrNull(parsed.observerLastSuccessAt),
474
- observerConsecutiveFailures: failures,
475
- updatedAt,
476
- reason: 'Signal detection healthy',
477
- nextAction: '',
478
- };
479
-
480
- if (failures > OBSERVER_FAILURE_DEGRADED_THRESHOLD) {
481
- entry.status = 'degraded';
482
- entry.reason = `Correction observer failing ${failures} cycles in a row — keyword learning and batch confirmation are paused`;
483
- entry.nextAction = "Check the observer runtime profile (quota/provider), then run 'pd runtime probe --runtime pi-ai' to verify connectivity";
484
- return entry;
485
- }
486
-
487
- const parsedTime = updatedAt === null ? Number.NaN : Date.parse(updatedAt);
488
- if (updatedAt === null || Number.isNaN(parsedTime) || (Date.now() - parsedTime) > SIGNAL_HEALTH_STALE_MS) {
489
- entry.status = 'degraded';
490
- entry.reason = updatedAt === null
491
- ? 'Health file carries no timestamp'
492
- : `Signal health not updated for >24h (last: ${updatedAt})`;
493
- entry.nextAction = 'Verify the OpenClaw plugin is running and the signal_collector / correction_observer flags are enabled';
494
- }
495
- return entry;
496
- }
497
-
498
- // ─── Main entry: buildDoctorOutput ───────────────────────────────────────────
499
-
500
- export interface BuildDoctorInput {
501
- workspaceDir: string;
502
- }
503
-
504
- export async function buildDoctorOutput(input: BuildDoctorInput): Promise<DoctorOutput> {
505
- const workspaceDir = path.resolve(input.workspaceDir);
506
- const pdDir = path.join(workspaceDir, '.pd');
507
- const configYamlPath = getPdConfigPath(workspaceDir);
508
- const stateDbPath = path.join(pdDir, 'state.db');
509
-
510
- // 1) Load PD config from .pd/config.yaml
511
- const loadResult = loadPdConfig(workspaceDir);
512
- const flags = computeFlagsFromLoadResult(loadResult);
513
- const redacted = redactLoadResult(loadResult);
514
-
515
- // 2) Feature flag summary
516
- const enabledMvpChannels: string[] = [];
517
- const disabledFlags: string[] = [];
518
- for (const flag of Object.values(flags.flags)) {
519
- if (flag.enabled && MVP_CHANNEL_IDS.includes(flag.id as typeof MVP_CHANNEL_IDS[number])) {
520
- enabledMvpChannels.push(flag.id);
521
- } else if (!flag.enabled) {
522
- disabledFlags.push(flag.id);
523
- }
524
- }
525
-
526
- const featureFlags: FeatureFlagSummary = {
527
- source: loadResult.ok ? loadResult.source : 'malformed',
528
- configPath: loadResult.configPath,
529
- enabledMvpChannels,
530
- disabledFlags,
531
- warnings: flags.warnings,
532
- };
533
-
534
- // 3) Internal agent diagnostics from .pd/config.yaml
535
- const profileMap = new Map<string, RedactedRuntimeProfileSummary>();
536
- for (const p of redacted.runtimeProfiles) {
537
- profileMap.set(p.id, p);
538
- }
539
-
540
- const internalAgents: InternalAgentDiagnostics[] = [];
541
- for (const agent of redacted.agents) {
542
- const profile = profileMap.get(agent.runtimeProfileId);
543
- internalAgents.push(diagnoseInternalAgent(agent, profile));
544
- }
545
-
546
- // 4) Provider health — derived from internal agents that are enabled
547
- const providerHealth: ProviderHealthEntry[] = [];
548
- const warnings: string[] = [];
549
- const nextActions: string[] = [];
550
-
551
- // Add config-level warnings
552
- warnings.push(...loadResult.warnings);
553
- warnings.push(...flags.warnings);
554
-
555
- // PRI-404: Add legacy file nextActions (separate field, not mixed into general nextActions)
556
- const { legacyFileNextActions } = loadResult;
557
-
558
- if (!loadResult.ok) {
559
- for (const err of loadResult.errors) {
560
- warnings.push(`Config error at ${err.path}: ${err.reason}`);
561
- }
562
- nextActions.push(loadResult.errors[0]?.nextAction ?? 'Fix .pd/config.yaml and retry');
563
- }
564
-
565
- // Check for enabled agents that need setup
566
- const needsSetupAgents = internalAgents.filter(a => a.enabled && (a.readiness === 'needs_setup' || a.readiness === 'not_ready'));
567
- for (const agent of needsSetupAgents) {
568
- // not_ready = key present but not probed → needs_probe (degraded), NOT auth_missing (failed)
569
- const classification: DoctorClassification = agent.readiness === 'needs_setup'
570
- ? 'config_missing'
571
- : 'needs_probe';
572
- providerHealth.push({
573
- provider: agent.provider,
574
- model: agent.model,
575
- apiKeyEnv: agent.apiKeyEnv,
576
- apiKeyPresent: agent.apiKeyPresent,
577
- classification,
578
- reason: agent.reason,
579
- nextAction: agent.nextAction,
580
- source: 'config.yaml',
581
- });
582
- }
583
-
584
- // Check state.db for rate-limit / unavailable signals for enabled agents
585
- const readyAgents = internalAgents.filter(a => a.enabled && a.readiness === 'ready');
586
- if (readyAgents.length > 0) {
587
- const signalResult = await inspectStateDbForProviderSignal(stateDbPath);
588
- if (signalResult.warning) {
589
- warnings.push(signalResult.warning);
590
- }
591
- if (signalResult.signal) {
592
- const { classification: cls, reason: rsn } = signalResult.signal;
593
- providerHealth.push({
594
- provider: null,
595
- model: null,
596
- apiKeyEnv: null,
597
- apiKeyPresent: false,
598
- classification: cls,
599
- reason: rsn,
600
- nextAction: cls === 'rate_limit'
601
- ? "Wait for the provider's rate limit to reset, or reduce request rate"
602
- : 'Provider/model temporarily unavailable. Try a different model or retry later.',
603
- source: 'state.db',
604
- });
605
- } else {
606
- providerHealth.push({
607
- provider: null,
608
- model: null,
609
- apiKeyEnv: null,
610
- apiKeyPresent: false,
611
- classification: 'healthy',
612
- reason: 'Config is valid; no recent error signals in state.db',
613
- nextAction: 'Run pd runtime probe to verify end-to-end connectivity',
614
- source: 'config.yaml',
615
- });
616
- }
617
- }
618
-
619
- // 5) Compute overall status
620
- // Classification → status mapping:
621
- // - config_missing (profile exists but fields empty/placeholder) → degraded
622
- // This is the expected initial state for the default `pd.default` profile
623
- // that ships with empty provider/model/apiKeyEnv. Users fill via console.
624
- // - auth_missing (apiKeyEnv set but env var not in environment) → failed
625
- // User configured the profile but the secret is missing at runtime.
626
- // - needs_probe / rate_limit / unavailable → degraded
627
- let status: DoctorStatus = 'ok';
628
- const classifications = providerHealth.map((p) => p.classification);
629
- if (classifications.includes('rate_limit') || classifications.includes('unavailable') || classifications.includes('needs_probe') || classifications.includes('config_missing')) {
630
- status = 'degraded';
631
- }
632
- if (classifications.includes('auth_missing')) {
633
- status = 'failed';
634
- }
635
- if (!loadResult.ok) {
636
- status = 'failed';
637
- }
638
- if ((warnings.length > 0) && status === 'ok') {
639
- status = 'degraded';
640
- }
641
-
642
- // 6) Reason
643
- let reason: string | undefined;
644
- if (status === 'failed') {
645
- if (!loadResult.ok) {
646
- reason = `Config validation failed: ${loadResult.errors.map(e => e.reason).join('; ')}`;
647
- } else {
648
- const failed = providerHealth.filter((p) => p.classification === 'auth_missing' || p.classification === 'config_missing');
649
- reason = failed.length > 0
650
- ? `Provider auth/config missing: ${failed.map((p) => p.classification).join(', ')}`
651
- : 'Configuration is missing required fields';
652
- }
653
- } else if (status === 'degraded') {
654
- const degraded = providerHealth.filter((p) => p.classification === 'rate_limit' || p.classification === 'unavailable' || p.classification === 'needs_probe');
655
- if (degraded.length > 0) {
656
- reason = `Provider connectivity degraded: ${degraded.map((p) => p.classification).join(', ')}`;
657
- } else if (warnings.length > 0) {
658
- reason = `Config warnings present: ${warnings.length} item(s)`;
659
- }
660
- }
661
-
662
- // 7) Signal detection health (PRI-788 G4)
663
- const signalHealth = buildSignalHealthEntry(path.join(workspaceDir, '.state'));
664
- if (signalHealth.status === 'degraded') {
665
- const { reason: shReason, nextAction: shNextAction } = signalHealth;
666
- if (status === 'ok') status = 'degraded';
667
- if (!reason) reason = shReason;
668
- if (shNextAction) nextActions.push(shNextAction);
669
- }
670
-
671
- // 8) Build output
672
- const out: DoctorOutput = {
673
- status,
674
- workspaceDir,
675
- pdConfigPaths: {
676
- workspaceDir: pathEntry(workspaceDir),
677
- pdDir: pathEntry(pdDir),
678
- configYaml: { ...pathEntry(configYamlPath), parseable: loadResult.ok || !fs.existsSync(configYamlPath) ? true : false },
679
- stateDb: pathEntry(stateDbPath),
680
- },
681
- openclawConfigPaths: {
682
- openclawHome: pathEntry(getOpenClawHome()),
683
- openclawConfig: pathEntry(getOpenClawConfigPath()),
684
- },
685
- featureFlags,
686
- internalAgents,
687
- providerHealth,
688
- warnings,
689
- nextActions: nextActions.length > 0 ? nextActions : ['All checks passed — configuration is valid'],
690
- legacyFilesDetected: loadResult.legacyFilesDetected,
691
- legacyFileNextActions,
692
- signalHealth,
693
- };
694
-
695
- if (reason) out.reason = reason;
696
- return out;
697
- }