create-principles-disciple 1.149.0 → 1.150.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (258) hide show
  1. package/_release/product-identity.json +1 -1
  2. package/codex-adapter/dist/ingestion/ingestion.d.ts +9 -7
  3. package/codex-adapter/dist/ingestion/ingestion.js +68 -144
  4. package/codex-adapter/dist/ingestion/transcript-decoder.d.ts +35 -44
  5. package/codex-adapter/dist/ingestion/transcript-decoder.js +23 -84
  6. package/codex-adapter/dist/ingestion/transcript-source.d.ts +29 -0
  7. package/codex-adapter/dist/ingestion/transcript-source.js +65 -0
  8. package/codex-adapter/dist/pd-hook.d.ts +27 -1
  9. package/codex-adapter/dist/pd-hook.js +88 -7
  10. package/codex-adapter/dist/worker/workspace-worker.d.ts +15 -0
  11. package/codex-adapter/dist/worker/workspace-worker.js +7 -36
  12. package/codex-adapter/package.json +1 -1
  13. package/console/dist/server/index.js +14 -0
  14. package/console/dist/server/models/ActivationsConsoleModel.d.ts +3 -17
  15. package/console/dist/server/models/ActivationsConsoleModel.js +5 -44
  16. package/console/dist/server/routes/diagnostician.d.ts +50 -0
  17. package/console/dist/server/routes/diagnostician.js +388 -0
  18. package/console/dist/server/routes/examiner-eligibility.d.ts +73 -0
  19. package/console/dist/server/routes/examiner-eligibility.js +326 -0
  20. package/console/dist/server/routes/examiner.js +66 -8
  21. package/console/dist/web/assets/app.css +40 -0
  22. package/console/dist/web/assets/app.js +30 -30
  23. package/core/dist/host/host-installer.d.ts +7 -0
  24. package/core/dist/host/host-installer.d.ts.map +1 -1
  25. package/core/dist/host/host-installer.js.map +1 -1
  26. package/core/dist/runtime/activation/index.d.ts +3 -3
  27. package/core/dist/runtime/activation/index.d.ts.map +1 -1
  28. package/core/dist/runtime/activation/index.js +1 -1
  29. package/core/dist/runtime/activation/index.js.map +1 -1
  30. package/core/dist/runtime/activation/promotion-readiness-evaluator.d.ts +25 -1
  31. package/core/dist/runtime/activation/promotion-readiness-evaluator.d.ts.map +1 -1
  32. package/core/dist/runtime/activation/promotion-readiness-evaluator.js +58 -1
  33. package/core/dist/runtime/activation/promotion-readiness-evaluator.js.map +1 -1
  34. package/core/dist/runtime/activation/promotion-readiness-reader.d.ts.map +1 -1
  35. package/core/dist/runtime/activation/promotion-readiness-reader.js +4 -2
  36. package/core/dist/runtime/activation/promotion-readiness-reader.js.map +1 -1
  37. package/core/dist/runtime/activation/rulecode-owner-decision-service.d.ts +28 -0
  38. package/core/dist/runtime/activation/rulecode-owner-decision-service.d.ts.map +1 -1
  39. package/core/dist/runtime/activation/rulecode-owner-decision-service.js +2 -0
  40. package/core/dist/runtime/activation/rulecode-owner-decision-service.js.map +1 -1
  41. package/core/dist/runtime/admission-gate.d.ts +8 -1
  42. package/core/dist/runtime/admission-gate.d.ts.map +1 -1
  43. package/core/dist/runtime/admission-gate.js +2 -1
  44. package/core/dist/runtime/admission-gate.js.map +1 -1
  45. package/core/dist/runtime/config/pd-config-defaults.d.ts.map +1 -1
  46. package/core/dist/runtime/config/pd-config-defaults.js +20 -2
  47. package/core/dist/runtime/config/pd-config-defaults.js.map +1 -1
  48. package/core/dist/runtime/config/pd-config-effective.d.ts.map +1 -1
  49. package/core/dist/runtime/config/pd-config-effective.js +5 -2
  50. package/core/dist/runtime/config/pd-config-effective.js.map +1 -1
  51. package/core/dist/runtime/config/pd-config-validate.d.ts.map +1 -1
  52. package/core/dist/runtime/config/pd-config-validate.js +18 -0
  53. package/core/dist/runtime/config/pd-config-validate.js.map +1 -1
  54. package/core/dist/runtime/context-payload.d.ts +48 -3
  55. package/core/dist/runtime/context-payload.d.ts.map +1 -1
  56. package/core/dist/runtime/context-payload.js +38 -0
  57. package/core/dist/runtime/context-payload.js.map +1 -1
  58. package/core/dist/runtime/diagnostician/rootcause-prompt-builder.d.ts +8 -2
  59. package/core/dist/runtime/diagnostician/rootcause-prompt-builder.d.ts.map +1 -1
  60. package/core/dist/runtime/diagnostician/rootcause-prompt-builder.js +28 -2
  61. package/core/dist/runtime/diagnostician/rootcause-prompt-builder.js.map +1 -1
  62. package/core/dist/runtime/diagnostician-candidate.d.ts +24 -0
  63. package/core/dist/runtime/diagnostician-candidate.d.ts.map +1 -0
  64. package/core/dist/runtime/diagnostician-candidate.js +55 -0
  65. package/core/dist/runtime/diagnostician-candidate.js.map +1 -0
  66. package/core/dist/runtime/evidence-guards.d.ts +10 -4
  67. package/core/dist/runtime/evidence-guards.d.ts.map +1 -1
  68. package/core/dist/runtime/evidence-guards.js +12 -5
  69. package/core/dist/runtime/evidence-guards.js.map +1 -1
  70. package/core/dist/runtime/evolution/evolution-types.d.ts +4 -4
  71. package/core/dist/runtime/evolution/evolution-types.d.ts.map +1 -1
  72. package/core/dist/runtime/evolution/evolution-types.js +1 -0
  73. package/core/dist/runtime/evolution/evolution-types.js.map +1 -1
  74. package/core/dist/runtime/feature-flags/feature-flag-contract.d.ts.map +1 -1
  75. package/core/dist/runtime/feature-flags/feature-flag-contract.js +14 -0
  76. package/core/dist/runtime/feature-flags/feature-flag-contract.js.map +1 -1
  77. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.d.ts.map +1 -1
  78. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +16 -0
  79. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
  80. package/core/dist/runtime/index.d.ts +5 -2
  81. package/core/dist/runtime/index.d.ts.map +1 -1
  82. package/core/dist/runtime/index.js +6 -1
  83. package/core/dist/runtime/index.js.map +1 -1
  84. package/core/dist/runtime/internalization/index.d.ts +1 -0
  85. package/core/dist/runtime/internalization/index.d.ts.map +1 -1
  86. package/core/dist/runtime/internalization/index.js +2 -0
  87. package/core/dist/runtime/internalization/index.js.map +1 -1
  88. package/core/dist/runtime/internalization/rule-host-contracts.d.ts +10 -0
  89. package/core/dist/runtime/internalization/rule-host-contracts.d.ts.map +1 -1
  90. package/core/dist/runtime/internalization/rule-host-evaluator.js +10 -10
  91. package/core/dist/runtime/internalization/rule-host-evaluator.js.map +1 -1
  92. package/core/dist/runtime/internalization/rule-host-input-builder.d.ts +7 -6
  93. package/core/dist/runtime/internalization/rule-host-input-builder.d.ts.map +1 -1
  94. package/core/dist/runtime/internalization/rule-host-input-builder.js +6 -2
  95. package/core/dist/runtime/internalization/rule-host-input-builder.js.map +1 -1
  96. package/core/dist/runtime/internalization/rule-host-result-normalizer.d.ts +33 -0
  97. package/core/dist/runtime/internalization/rule-host-result-normalizer.d.ts.map +1 -0
  98. package/core/dist/runtime/internalization/rule-host-result-normalizer.js +61 -0
  99. package/core/dist/runtime/internalization/rule-host-result-normalizer.js.map +1 -0
  100. package/core/dist/runtime/internalization/rule-host-validator.d.ts.map +1 -1
  101. package/core/dist/runtime/internalization/rule-host-validator.js +17 -0
  102. package/core/dist/runtime/internalization/rule-host-validator.js.map +1 -1
  103. package/core/dist/runtime/pain-ingress-payload.d.ts +27 -2
  104. package/core/dist/runtime/pain-ingress-payload.d.ts.map +1 -1
  105. package/core/dist/runtime/pain-ingress-payload.js +45 -3
  106. package/core/dist/runtime/pain-ingress-payload.js.map +1 -1
  107. package/core/dist/runtime/pain-ingress.d.ts +4 -2
  108. package/core/dist/runtime/pain-ingress.d.ts.map +1 -1
  109. package/core/dist/runtime/pain-ingress.js +23 -3
  110. package/core/dist/runtime/pain-ingress.js.map +1 -1
  111. package/core/dist/runtime/pain-severity.d.ts +14 -0
  112. package/core/dist/runtime/pain-severity.d.ts.map +1 -0
  113. package/core/dist/runtime/pain-severity.js +14 -0
  114. package/core/dist/runtime/pain-severity.js.map +1 -0
  115. package/core/dist/runtime/pain-signal-bridge.d.ts +17 -3
  116. package/core/dist/runtime/pain-signal-bridge.d.ts.map +1 -1
  117. package/core/dist/runtime/pain-signal-bridge.js +6 -0
  118. package/core/dist/runtime/pain-signal-bridge.js.map +1 -1
  119. package/core/dist/runtime/pain-signal-observability.d.ts.map +1 -1
  120. package/core/dist/runtime/pain-signal-observability.js +3 -2
  121. package/core/dist/runtime/pain-signal-observability.js.map +1 -1
  122. package/core/dist/runtime/pain-submit-capability.d.ts +164 -0
  123. package/core/dist/runtime/pain-submit-capability.d.ts.map +1 -0
  124. package/core/dist/runtime/pain-submit-capability.js +442 -0
  125. package/core/dist/runtime/pain-submit-capability.js.map +1 -0
  126. package/core/dist/runtime/pain-to-principle-service.d.ts +4 -0
  127. package/core/dist/runtime/pain-to-principle-service.d.ts.map +1 -1
  128. package/core/dist/runtime/pain-to-principle-service.js +2 -0
  129. package/core/dist/runtime/pain-to-principle-service.js.map +1 -1
  130. package/core/dist/runtime/stalled-diagnostician-task-read-model.d.ts +56 -10
  131. package/core/dist/runtime/stalled-diagnostician-task-read-model.d.ts.map +1 -1
  132. package/core/dist/runtime/stalled-diagnostician-task-read-model.js +80 -4
  133. package/core/dist/runtime/stalled-diagnostician-task-read-model.js.map +1 -1
  134. package/core/dist/runtime/store/context/sqlite-context-assembler.d.ts.map +1 -1
  135. package/core/dist/runtime/store/context/sqlite-context-assembler.js +11 -0
  136. package/core/dist/runtime/store/context/sqlite-context-assembler.js.map +1 -1
  137. package/core/dist/runtime/store/run/memory-run-store.d.ts +10 -0
  138. package/core/dist/runtime/store/run/memory-run-store.d.ts.map +1 -1
  139. package/core/dist/runtime/store/run/memory-run-store.js +21 -0
  140. package/core/dist/runtime/store/run/memory-run-store.js.map +1 -1
  141. package/core/dist/runtime/store/run/run-store.d.ts +12 -0
  142. package/core/dist/runtime/store/run/run-store.d.ts.map +1 -1
  143. package/core/dist/runtime/store/run/sqlite-run-store.d.ts +1 -0
  144. package/core/dist/runtime/store/run/sqlite-run-store.d.ts.map +1 -1
  145. package/core/dist/runtime/store/run/sqlite-run-store.js +14 -0
  146. package/core/dist/runtime/store/run/sqlite-run-store.js.map +1 -1
  147. package/core/dist/runtime/task-status.d.ts +9 -0
  148. package/core/dist/runtime/task-status.d.ts.map +1 -1
  149. package/core/dist/runtime/task-status.js +7 -1
  150. package/core/dist/runtime/task-status.js.map +1 -1
  151. package/core/dist/runtime/types/evidence-chain-contract.d.ts +18 -0
  152. package/core/dist/runtime/types/evidence-chain-contract.d.ts.map +1 -1
  153. package/core/dist/runtime/types/evidence-chain-contract.js +37 -7
  154. package/core/dist/runtime/types/evidence-chain-contract.js.map +1 -1
  155. package/core/package.json +5 -1
  156. package/dist/install-summary.d.ts +7 -0
  157. package/dist/install-summary.d.ts.map +1 -1
  158. package/dist/install-summary.js +4 -0
  159. package/dist/install-summary.js.map +1 -1
  160. package/dist/installer.d.ts +34 -1
  161. package/dist/installer.d.ts.map +1 -1
  162. package/dist/installer.js +84 -4
  163. package/dist/installer.js.map +1 -1
  164. package/dist/installers/codex-host-installer.d.ts +88 -1
  165. package/dist/installers/codex-host-installer.d.ts.map +1 -1
  166. package/dist/installers/codex-host-installer.js +370 -11
  167. package/dist/installers/codex-host-installer.js.map +1 -1
  168. package/dist/installers/index.d.ts +23 -0
  169. package/dist/installers/index.d.ts.map +1 -1
  170. package/dist/installers/index.js +38 -1
  171. package/dist/installers/index.js.map +1 -1
  172. package/dist/installers/legacy-workbuddy-skill.d.ts +59 -0
  173. package/dist/installers/legacy-workbuddy-skill.d.ts.map +1 -0
  174. package/dist/installers/legacy-workbuddy-skill.js +168 -0
  175. package/dist/installers/legacy-workbuddy-skill.js.map +1 -0
  176. package/dist/installers/workbuddy-host-installer.d.ts.map +1 -1
  177. package/dist/installers/workbuddy-host-installer.js +7 -0
  178. package/dist/installers/workbuddy-host-installer.js.map +1 -1
  179. package/host-runtime/dist/adaptive-priority-provider.d.ts +101 -0
  180. package/host-runtime/dist/adaptive-priority-provider.js +194 -0
  181. package/host-runtime/dist/adaptive-selection.d.ts +164 -0
  182. package/host-runtime/dist/adaptive-selection.js +506 -0
  183. package/host-runtime/dist/adaptive-skip-decision.d.ts +61 -0
  184. package/host-runtime/dist/adaptive-skip-decision.js +114 -0
  185. package/host-runtime/dist/codex-ingestion-consent.d.ts +32 -95
  186. package/host-runtime/dist/codex-ingestion-consent.js +33 -205
  187. package/host-runtime/dist/conversation-ingestion/consent.d.ts +124 -0
  188. package/host-runtime/dist/conversation-ingestion/consent.js +531 -0
  189. package/host-runtime/dist/conversation-ingestion/index.d.ts +12 -0
  190. package/host-runtime/dist/conversation-ingestion/index.js +12 -0
  191. package/host-runtime/dist/conversation-ingestion/pipeline.d.ts +101 -0
  192. package/host-runtime/dist/conversation-ingestion/pipeline.js +162 -0
  193. package/host-runtime/dist/conversation-ingestion/source.d.ts +172 -0
  194. package/host-runtime/dist/conversation-ingestion/source.js +111 -0
  195. package/host-runtime/dist/conversation-ingestion/text-policy.d.ts +51 -0
  196. package/host-runtime/dist/conversation-ingestion/text-policy.js +68 -0
  197. package/host-runtime/dist/diagnostician-auto-run.d.ts +28 -0
  198. package/host-runtime/dist/diagnostician-auto-run.js +100 -0
  199. package/host-runtime/dist/governance-observation-store.d.ts +9 -7
  200. package/host-runtime/dist/governance-observation-store.js +20 -4
  201. package/host-runtime/dist/host-tool-semantic-resolver.d.ts +42 -1
  202. package/host-runtime/dist/host-tool-semantic-resolver.js +80 -14
  203. package/host-runtime/dist/index.d.ts +5 -0
  204. package/host-runtime/dist/index.js +12 -0
  205. package/host-runtime/dist/production-rulehost-gate.js +17 -17
  206. package/host-runtime/dist/rulecode-event-collection.d.ts +31 -0
  207. package/host-runtime/dist/rulecode-event-collection.js +62 -0
  208. package/host-runtime/package.json +1 -1
  209. package/package.json +3 -3
  210. package/pd-cli/dist/commands/diagnose.d.ts +30 -0
  211. package/pd-cli/dist/commands/diagnose.d.ts.map +1 -1
  212. package/pd-cli/dist/commands/diagnose.js +75 -0
  213. package/pd-cli/dist/commands/diagnose.js.map +1 -1
  214. package/pd-cli/dist/commands/pain-record.d.ts.map +1 -1
  215. package/pd-cli/dist/commands/pain-record.js +5 -4
  216. package/pd-cli/dist/commands/pain-record.js.map +1 -1
  217. package/pd-cli/dist/commands/pain-retry.d.ts.map +1 -1
  218. package/pd-cli/dist/commands/pain-retry.js +2 -1
  219. package/pd-cli/dist/commands/pain-retry.js.map +1 -1
  220. package/pd-cli/dist/commands/runtime-activation.d.ts +6 -17
  221. package/pd-cli/dist/commands/runtime-activation.d.ts.map +1 -1
  222. package/pd-cli/dist/commands/runtime-activation.js +42 -48
  223. package/pd-cli/dist/commands/runtime-activation.js.map +1 -1
  224. package/pd-cli/dist/index.js +1 -0
  225. package/pd-cli/dist/index.js.map +1 -1
  226. package/pd-cli/dist/services/delivery-surfaces.js +1 -1
  227. package/pd-cli/dist/services/delivery-surfaces.js.map +1 -1
  228. package/pd-cli/package.json +1 -1
  229. package/pd-mcp-server/dist/budget.d.ts +1 -1
  230. package/pd-mcp-server/dist/budget.js +2 -2
  231. package/pd-mcp-server/dist/envelope.d.ts +15 -0
  232. package/pd-mcp-server/dist/envelope.js +49 -1
  233. package/pd-mcp-server/dist/index.d.ts +2 -0
  234. package/pd-mcp-server/dist/index.js +6 -0
  235. package/pd-mcp-server/dist/server.d.ts +83 -14
  236. package/pd-mcp-server/dist/server.js +251 -4
  237. package/pd-mcp-server/dist/version.d.ts +1 -1
  238. package/pd-mcp-server/dist/version.js +1 -1
  239. package/pd-mcp-server/dist/workspace.d.ts +4 -2
  240. package/pd-mcp-server/dist/workspace.js +5 -2
  241. package/pd-mcp-server/package.json +1 -1
  242. package/plugin/dist/bundle.js +449 -437
  243. package/plugin/dist/core/evolution-reducer.d.ts +2 -2
  244. package/plugin/dist/hooks/hook-tool-semantics.d.ts +25 -0
  245. package/plugin/dist/hooks/pain-ingress-adapter.d.ts +1 -1
  246. package/plugin/dist/openclaw.plugin.json +1 -1
  247. package/plugin/dist/rulehost-evidence.js +1 -1
  248. package/plugin/openclaw.plugin.json +1 -1
  249. package/plugin/package.json +1 -1
  250. package/release-manager/dist/installer.js +84 -4
  251. package/release-manager/dist/installers/codex-host-installer.js +370 -11
  252. package/release-manager/dist/installers/index.js +38 -1
  253. package/release-manager/dist/installers/legacy-workbuddy-skill.js +168 -0
  254. package/release-manager/dist/installers/workbuddy-host-installer.js +7 -0
  255. package/release-manager/package.json +1 -1
  256. package/workbuddy-adapter/dist/pd-hook.js +20 -4
  257. package/workbuddy-adapter/package.json +1 -1
  258. package/workbuddy-adapter/plugin/skills/pd-pain-signal/SKILL.md +123 -20
@@ -0,0 +1,388 @@
1
+ /**
2
+ * SPEC v0.8 §9.2 (L2) and §9.4 (L2b) — Console execution + backlog visibility.
3
+ *
4
+ * Two routes, one owner module:
5
+ *
6
+ * POST /api/diagnostician/:taskId/run spawn `pd diagnose run` (L2)
7
+ * GET /api/diagnostician/backlog backlog snapshot (L2b)
8
+ *
9
+ * Boundaries this module must not cross:
10
+ * - L2 does not execute the diagnosis in-process. It must not copy runtime
11
+ * resolution (the single production entry lives in pd-cli, P4), so check 7
12
+ * spawns `pd diagnose run --preflight` and only spawns the real run when
13
+ * that verdict is ok.
14
+ * - A 202 means "a child process was started", never "the diagnosis
15
+ * succeeded". The CLI re-checks everything and owns the lease.
16
+ * - L2b reports observed activity (`runs.started_at`) only. It never claims
17
+ * the executor is alive.
18
+ */
19
+ import { spawn } from 'child_process';
20
+ import * as fs from 'fs';
21
+ import * as path from 'path';
22
+ import { fileURLToPath } from 'url';
23
+ import { RuntimeStateManager, StalledDiagnosticianTaskReadModel, isRetryWaitBackoffElapsed, resolveAgentRuntimeBinding, resolveDiagnosticianCapability, } from '@principles/core/runtime';
24
+ import { loadPdConfig } from '../config/pd-config-store.js';
25
+ import { resolveUpdateLayout } from '../utils/installed-layout.js';
26
+ import { errorMessage, sendError, sendJson, sendMethodNotAllowed, sendNotFound } from '../utils/response.js';
27
+ /** Contract limits (TD §8.2.4). */
28
+ const PREFLIGHT_TIMEOUT_MS = 3_000;
29
+ const SPAWN_CONFIRM_TIMEOUT_MS = 2_000;
30
+ /**
31
+ * Resolve the pd-cli entry from the installed layout (`pdCliDir`), falling back
32
+ * to the monorepo sibling only when no installation can be resolved.
33
+ */
34
+ export function resolvePdCliInvocation() {
35
+ const layout = resolveUpdateLayout();
36
+ if (layout !== undefined) {
37
+ const rootDir = path.resolve(layout.pdCliDir);
38
+ return { rootDir, entryPath: path.join(rootDir, 'dist', 'index.js') };
39
+ }
40
+ const entryPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../../pd-cli/dist/index.js');
41
+ return { rootDir: path.dirname(path.dirname(entryPath)), entryPath };
42
+ }
43
+ function collectChild(limit) {
44
+ let buffer = '';
45
+ return {
46
+ append(chunk) {
47
+ if (buffer.length >= limit)
48
+ return;
49
+ const text = typeof chunk === 'string' ? chunk : Buffer.isBuffer(chunk) ? chunk.toString('utf8') : '';
50
+ buffer += text.slice(0, limit - buffer.length);
51
+ },
52
+ text: () => buffer,
53
+ };
54
+ }
55
+ function parsePreflightStdout(stdout) {
56
+ let parsed;
57
+ try {
58
+ parsed = JSON.parse(stdout);
59
+ }
60
+ catch {
61
+ return null;
62
+ }
63
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
64
+ return null;
65
+ const field = (key) => (Object.hasOwn(parsed, key) ? Reflect.get(parsed, key) : undefined);
66
+ const ok = field('ok');
67
+ if (ok === true)
68
+ return { ok: true };
69
+ if (ok !== false)
70
+ return null;
71
+ const reason = field('reason');
72
+ const message = field('message');
73
+ const nextAction = field('nextAction');
74
+ return {
75
+ ok: false,
76
+ reason: typeof reason === 'string' ? reason : undefined,
77
+ message: typeof message === 'string' ? message : undefined,
78
+ nextAction: typeof nextAction === 'string' ? nextAction : undefined,
79
+ };
80
+ }
81
+ export function createDiagnosticianRuntime(opts = {}) {
82
+ const preflightTimeoutMs = opts.preflightTimeoutMs ?? PREFLIGHT_TIMEOUT_MS;
83
+ const spawnConfirmTimeoutMs = opts.spawnConfirmTimeoutMs ?? SPAWN_CONFIRM_TIMEOUT_MS;
84
+ const invocation = opts.pdCliEntry === undefined
85
+ ? resolvePdCliInvocation()
86
+ : { entryPath: path.resolve(opts.pdCliEntry), rootDir: path.dirname(path.dirname(path.resolve(opts.pdCliEntry))) };
87
+ const entryInsideRoot = invocation.entryPath.startsWith(invocation.rootDir + path.sep);
88
+ return {
89
+ preflight({ taskId, workspaceDir }) {
90
+ if (!entryInsideRoot) {
91
+ return Promise.resolve({
92
+ ok: false,
93
+ reason: 'preflight_failed',
94
+ message: `pd CLI entry ${invocation.entryPath} is outside the pd-cli component dir ${invocation.rootDir}`,
95
+ nextAction: 'Reinstall PD so the console and pd-cli come from the same component set.',
96
+ });
97
+ }
98
+ return new Promise((resolve) => {
99
+ let settled = false;
100
+ const stdout = collectChild(64 * 1024);
101
+ const stderr = collectChild(8 * 1024);
102
+ const child = spawn(process.execPath, [
103
+ invocation.entryPath,
104
+ 'diagnose',
105
+ 'run',
106
+ '--task-id',
107
+ taskId,
108
+ '--workspace',
109
+ workspaceDir,
110
+ '--preflight',
111
+ '--json',
112
+ ], { shell: false, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
113
+ const timer = setTimeout(() => {
114
+ if (settled)
115
+ return;
116
+ settled = true;
117
+ child.kill();
118
+ resolve('timeout');
119
+ }, preflightTimeoutMs);
120
+ child.stdout?.on('data', (chunk) => stdout.append(chunk));
121
+ child.stderr?.on('data', (chunk) => stderr.append(chunk));
122
+ child.on('error', (error) => {
123
+ if (settled)
124
+ return;
125
+ settled = true;
126
+ clearTimeout(timer);
127
+ resolve({
128
+ ok: false,
129
+ reason: 'preflight_failed',
130
+ message: error.message,
131
+ nextAction: 'Run `pd diagnose run --task-id <id> --workspace <ws> --preflight --json` manually.',
132
+ });
133
+ });
134
+ child.on('close', (code) => {
135
+ if (settled)
136
+ return;
137
+ settled = true;
138
+ clearTimeout(timer);
139
+ const verdict = parsePreflightStdout(stdout.text());
140
+ if (verdict !== null) {
141
+ resolve(verdict);
142
+ return;
143
+ }
144
+ const detail = stderr.text().trim();
145
+ resolve({
146
+ ok: false,
147
+ reason: 'preflight_failed',
148
+ message: detail.length > 0 ? detail.slice(0, 400) : `pd diagnose --preflight exited with code ${code ?? 'unknown'}`,
149
+ nextAction: 'Run `pd diagnose run --task-id <id> --workspace <ws> --preflight --json` manually.',
150
+ });
151
+ });
152
+ });
153
+ },
154
+ spawnRun({ taskId, workspaceDir }) {
155
+ if (!entryInsideRoot) {
156
+ return Promise.resolve({
157
+ outcome: 'failed',
158
+ message: `pd CLI entry ${invocation.entryPath} is outside the pd-cli component dir ${invocation.rootDir}`,
159
+ });
160
+ }
161
+ return new Promise((resolve) => {
162
+ let settled = false;
163
+ const child = spawn(process.execPath, [invocation.entryPath, 'diagnose', 'run', '--task-id', taskId, '--workspace', workspaceDir, '--json'], { detached: true, stdio: 'ignore', shell: false, windowsHide: true });
164
+ const timer = setTimeout(() => {
165
+ if (settled)
166
+ return;
167
+ settled = true;
168
+ resolve({ outcome: 'unconfirmed' });
169
+ }, spawnConfirmTimeoutMs);
170
+ child.on('error', (error) => {
171
+ if (settled)
172
+ return;
173
+ settled = true;
174
+ clearTimeout(timer);
175
+ resolve({ outcome: 'failed', message: error.message });
176
+ });
177
+ child.on('spawn', () => {
178
+ if (settled)
179
+ return;
180
+ settled = true;
181
+ clearTimeout(timer);
182
+ child.unref();
183
+ resolve({ outcome: 'spawned' });
184
+ });
185
+ });
186
+ },
187
+ };
188
+ }
189
+ function isSameOriginRequest(req) {
190
+ const { host, origin } = req.headers;
191
+ if (typeof origin === 'string' && origin.length > 0) {
192
+ if (typeof host !== 'string' || host.length === 0)
193
+ return false;
194
+ try {
195
+ return new URL(origin).host === host;
196
+ }
197
+ catch {
198
+ return false;
199
+ }
200
+ }
201
+ const site = req.headers['sec-fetch-site'];
202
+ if (typeof site === 'string' && site.length > 0) {
203
+ return site === 'same-origin' || site === 'none';
204
+ }
205
+ // No browser provenance headers: a CLI/script client (TD §8.2.3).
206
+ return true;
207
+ }
208
+ function isJsonContentType(value) {
209
+ const raw = Array.isArray(value) ? value[0] : value;
210
+ if (typeof raw !== 'string')
211
+ return false;
212
+ const [mediaType] = raw.split(';');
213
+ return mediaType?.trim().toLowerCase() === 'application/json';
214
+ }
215
+ function stateDbPath(workspaceDir) {
216
+ return path.join(workspaceDir, '.pd', 'state.db');
217
+ }
218
+ function resolveConfiguration(deps) {
219
+ const loadResult = loadPdConfig(deps.workspaceDir);
220
+ const effective = loadResult.ok ? loadResult.effective : loadResult.defaults;
221
+ return {
222
+ l3FlagEnabled: deps.featureFlags?.openclaw_diagnostician_consumer?.enabled ?? true,
223
+ capabilityAvailable: resolveDiagnosticianCapability(effective).available,
224
+ runtimeBound: resolveAgentRuntimeBinding(effective, 'diagnostician').ok,
225
+ };
226
+ }
227
+ async function handleBacklog(res, deps) {
228
+ if (!fs.existsSync(stateDbPath(deps.workspaceDir))) {
229
+ sendError(res, 404, 'workspace_state_missing', `Workspace state.db not found at ${stateDbPath(deps.workspaceDir)}`, {
230
+ nextAction: 'Run any PD command in this workspace once to create .pd/state.db.',
231
+ });
232
+ return;
233
+ }
234
+ const manager = new RuntimeStateManager({
235
+ workspaceDir: deps.workspaceDir,
236
+ readonly: true,
237
+ bootstrapIfMissing: false,
238
+ });
239
+ try {
240
+ await manager.initialize();
241
+ const readModel = new StalledDiagnosticianTaskReadModel({ stateManager: manager });
242
+ const snapshot = await readModel.getBacklog({
243
+ configuration: resolveConfiguration(deps),
244
+ now: deps.now?.() ?? new Date(),
245
+ });
246
+ sendJson(res, 200, { success: true, data: snapshot });
247
+ }
248
+ catch (error) {
249
+ // rc-9: degraded reads stay observable, never a silent empty backlog.
250
+ sendError(res, 500, 'backlog_unavailable', errorMessage(error), {
251
+ nextAction: 'Check .pd/state.db integrity, then retry GET /api/diagnostician/backlog.',
252
+ });
253
+ }
254
+ finally {
255
+ await manager.close().catch(() => undefined);
256
+ }
257
+ }
258
+ async function handleRun(req, res, input) {
259
+ const { deps, taskId } = input;
260
+ req.resume(); // body is `{}` / empty; drain so the socket is not reset.
261
+ // 1. Same-origin (TD §8.2.3). Bearer/loopback auth already ran upstream.
262
+ if (!isSameOriginRequest(req)) {
263
+ sendError(res, 403, 'cross_origin_rejected', 'Cross-origin request rejected');
264
+ return;
265
+ }
266
+ // 2. JSON content type — a cross-site form cannot forge it without preflight.
267
+ if (!isJsonContentType(req.headers['content-type'])) {
268
+ sendError(res, 415, 'unsupported_media_type', 'Content-Type must be application/json');
269
+ return;
270
+ }
271
+ // 3. state.db must exist — never bootstrap from a read route.
272
+ if (!fs.existsSync(stateDbPath(deps.workspaceDir))) {
273
+ sendError(res, 404, 'workspace_state_missing', `Workspace state.db not found at ${stateDbPath(deps.workspaceDir)}`, {
274
+ nextAction: 'Run any PD command in this workspace once to create .pd/state.db.',
275
+ });
276
+ return;
277
+ }
278
+ const nowMs = (deps.now?.() ?? new Date()).getTime();
279
+ const manager = new RuntimeStateManager({
280
+ workspaceDir: deps.workspaceDir,
281
+ readonly: true,
282
+ bootstrapIfMissing: false,
283
+ });
284
+ try {
285
+ await manager.initialize();
286
+ // 4. Task exists and is a diagnostician task.
287
+ const task = await manager.getTask(taskId);
288
+ if (task === null || task.taskKind !== 'diagnostician') {
289
+ sendError(res, 404, 'task_not_found', `No diagnostician task '${taskId}' in this workspace`, {
290
+ nextAction: 'Check GET /api/diagnostician/backlog for the current task ids.',
291
+ });
292
+ return;
293
+ }
294
+ // 6. A valid lease wins over the runnable check: a leased task presents as
295
+ // status='leased', so evaluating "not_runnable" first would make
296
+ // `already_leased` unreachable.
297
+ const leaseExpiresMs = typeof task.leaseExpiresAt === 'string' ? new Date(task.leaseExpiresAt).getTime() : Number.NaN;
298
+ if (task.status === 'leased' && Number.isFinite(leaseExpiresMs) && leaseExpiresMs > nowMs) {
299
+ sendError(res, 409, 'already_leased', `Task '${taskId}' already holds a lease until ${task.leaseExpiresAt}`, {
300
+ taskId,
301
+ status: task.status,
302
+ nextAction: 'Wait for the current run to finish; the lease decides who executes.',
303
+ });
304
+ return;
305
+ }
306
+ // 5. Runnable: pending, or retry_wait whose backoff elapsed.
307
+ const runnable = task.status === 'pending' ||
308
+ (task.status === 'retry_wait' && isRetryWaitBackoffElapsed(task.status, task.leaseExpiresAt, nowMs));
309
+ if (!runnable) {
310
+ sendError(res, 409, 'not_runnable', `Task '${taskId}' is ${task.status}`, {
311
+ taskId,
312
+ status: task.status,
313
+ nextAction: task.status === 'leased'
314
+ ? 'The lease has expired; wait for lease recovery to return the task to pending.'
315
+ : 'Only pending, or retry_wait with elapsed backoff, can start now.',
316
+ });
317
+ return;
318
+ }
319
+ }
320
+ finally {
321
+ await manager.close().catch(() => undefined);
322
+ }
323
+ // 7. Preflight through the CLI — the only production runtime-resolution entry.
324
+ const runtime = deps.runtime ?? createDiagnosticianRuntime();
325
+ const preflight = await runtime.preflight({ taskId, workspaceDir: deps.workspaceDir });
326
+ if (preflight === 'timeout') {
327
+ // 8. Timed-out preflight never spawns.
328
+ sendError(res, 504, 'preflight_timeout', `pd diagnose --preflight did not exit within ${PREFLIGHT_TIMEOUT_MS}ms`, {
329
+ taskId,
330
+ nextAction: 'Retry, or run `pd diagnose run --task-id <id> --workspace <ws> --preflight --json` manually.',
331
+ });
332
+ return;
333
+ }
334
+ if (!preflight.ok) {
335
+ sendError(res, 409, preflight.reason ?? 'preflight_failed', preflight.message ?? 'Diagnostician cannot run', {
336
+ taskId,
337
+ nextAction: preflight.nextAction,
338
+ });
339
+ return;
340
+ }
341
+ // 8. Spawn the real run only after the preflight verdict is ok.
342
+ const spawned = await runtime.spawnRun({ taskId, workspaceDir: deps.workspaceDir });
343
+ if (spawned.outcome === 'failed') {
344
+ sendError(res, 500, 'spawn_failed', spawned.message ?? 'Failed to spawn pd diagnose run', {
345
+ taskId,
346
+ nextAction: 'Check the console logs, then run `pd diagnose run --task-id <id> --workspace <ws> --json` manually.',
347
+ });
348
+ return;
349
+ }
350
+ if (spawned.outcome === 'unconfirmed') {
351
+ sendError(res, 500, 'spawn_unconfirmed', 'The child process neither started nor failed within 2s', {
352
+ taskId,
353
+ nextAction: 'Do not retry blindly; check GET /api/diagnostician/backlog for a new run before retrying.',
354
+ });
355
+ return;
356
+ }
357
+ // 202 = a child process started. It is NOT the diagnosis result.
358
+ sendJson(res, 202, {
359
+ success: true,
360
+ data: {
361
+ state: 'diagnosis_accepted',
362
+ taskId,
363
+ workspaceDir: deps.workspaceDir,
364
+ nextAction: '执行已启动;用 GET /api/diagnostician/backlog 观察 runs 记录。',
365
+ },
366
+ });
367
+ }
368
+ export async function handleDiagnosticianRoute(req, res, deps) {
369
+ const method = req.method ?? 'GET';
370
+ if (deps.subPath === '/backlog') {
371
+ if (method !== 'GET') {
372
+ sendMethodNotAllowed(res);
373
+ return;
374
+ }
375
+ await handleBacklog(res, deps);
376
+ return;
377
+ }
378
+ const runMatch = /^\/([^/]+)\/run$/.exec(deps.subPath);
379
+ if (runMatch?.[1] !== undefined) {
380
+ if (method !== 'POST') {
381
+ sendMethodNotAllowed(res);
382
+ return;
383
+ }
384
+ await handleRun(req, res, { deps, taskId: decodeURIComponent(runMatch[1]) });
385
+ return;
386
+ }
387
+ sendNotFound(res, 'Unknown diagnostician route');
388
+ }
@@ -0,0 +1,73 @@
1
+ import type { LabModules, StudyRoots } from './examiner-executor.js';
2
+ import { type ProductionSnapshot, type StudyRuleCodeFacts } from './examiner-study-inputs.js';
3
+ /**
4
+ * Phase C: Study eligibility pre-check.
5
+ *
6
+ * The verdict is computed from the SAME authorities the creation path uses:
7
+ * - the workspace ledger (target presence / status);
8
+ * - `buildHostEffectivePrincipleSet` (the lab's status eligibility rule);
9
+ * - `gatherProductionSnapshot` + `deriveStudyRuleCodeFacts` +
10
+ * `buildRuleCodePolicy` (the lab's RuleCode / identifiability rule);
11
+ * - `suiteCaseDefs` (the lab's suite compiler).
12
+ *
13
+ * Creation calls this same function BEFORE materializing, so a study that the
14
+ * pre-check calls BLOCKED is never created, and a study that is created was
15
+ * ELIGIBLE or DEGRADED under exactly these rules.
16
+ *
17
+ * Read-only by contract: no study directory, no state mutation.
18
+ */
19
+ export type EligibilityCheckId = 'experiment_mode' | 'principle_exists' | 'principle_status' | 'production_snapshot' | 'activation_evidence' | 'rulecode_identifiability' | 'experiment_configuration' | 'suite_available' | 'study_root_writable';
20
+ export type EligibilityCheckStatus = 'PASS' | 'WARNING' | 'BLOCKED';
21
+ export interface EligibilityCheck {
22
+ id: EligibilityCheckId;
23
+ status: EligibilityCheckStatus;
24
+ /** Stable machine code the UI can translate. */
25
+ reasonCode: string;
26
+ /** Technical detail (English); null when there is nothing to add. */
27
+ detail: string | null;
28
+ /** Supporting evidence (ids, markers, counts). */
29
+ evidence: string[];
30
+ /** Owner-facing next step (English); the UI maps reasonCode to localized copy. */
31
+ nextAction: string | null;
32
+ }
33
+ export type EligibilityStatus = 'ELIGIBLE' | 'DEGRADED' | 'BLOCKED';
34
+ export interface StudyEligibilityVerdict {
35
+ status: EligibilityStatus;
36
+ principleId: string;
37
+ /** Owner-facing one-liner; the UI prefers its own localized copy. */
38
+ summary: string;
39
+ /** Stable machine code of the first blocking reason (null when not blocked). */
40
+ reasonCode: string | null;
41
+ /** Alias kept for callers that read "blockingReasonCode". */
42
+ blockingReasonCode: string | null;
43
+ /** First actionable next step, or null when the study is creatable. */
44
+ nextAction: string | null;
45
+ checks: EligibilityCheck[];
46
+ }
47
+ export interface StudyEligibilityInputs {
48
+ snapshot: ProductionSnapshot;
49
+ ruleCodeFacts: StudyRuleCodeFacts;
50
+ }
51
+ export interface StudyEligibilityResult {
52
+ verdict: StudyEligibilityVerdict;
53
+ /** Reusable creation inputs — present whenever the snapshot was gathered. */
54
+ inputs: StudyEligibilityInputs | null;
55
+ }
56
+ declare const EXPERIMENT_MODES: readonly ['isolated_principle', 'full_library_incremental'];
57
+ export type ExperimentMode = (typeof EXPERIMENT_MODES)[number];
58
+ /**
59
+ * Project a verdict into its operator-facing shape. Every HTTP response must
60
+ * use this; the raw verdict stays internal because it also carries the
61
+ * creation inputs (`snapshot` / `ruleCodeFacts`).
62
+ */
63
+ export declare function toOperatorVerdict(result: StudyEligibilityResult): StudyEligibilityVerdict;
64
+ export declare function evaluateStudyEligibility(args: {
65
+ workspaceDir: string;
66
+ labRoot: string;
67
+ labModules: LabModules;
68
+ roots: StudyRoots;
69
+ principleId: string;
70
+ experimentMode: string;
71
+ suiteKey?: string;
72
+ }): Promise<StudyEligibilityResult>;
73
+ export {};