create-principles-disciple 1.148.11 → 1.150.1

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 (250) hide show
  1. package/_release/product-identity.json +1 -1
  2. package/codex-adapter/dist/pd-hook.d.ts +22 -1
  3. package/codex-adapter/dist/pd-hook.js +81 -7
  4. package/codex-adapter/dist/worker/workspace-worker.d.ts +15 -0
  5. package/codex-adapter/dist/worker/workspace-worker.js +7 -36
  6. package/codex-adapter/package.json +1 -1
  7. package/console/dist/server/index.js +21 -0
  8. package/console/dist/server/models/ActivationsConsoleModel.d.ts +3 -17
  9. package/console/dist/server/models/ActivationsConsoleModel.js +5 -44
  10. package/console/dist/server/routes/compatibility-scan.d.ts +18 -0
  11. package/console/dist/server/routes/compatibility-scan.js +33 -0
  12. package/console/dist/server/routes/diagnostician.d.ts +50 -0
  13. package/console/dist/server/routes/diagnostician.js +388 -0
  14. package/console/dist/shared/compatibility-scan-contract.d.ts +26 -0
  15. package/console/dist/shared/compatibility-scan-contract.js +1 -0
  16. package/console/dist/web/assets/app.js +31 -31
  17. package/core/dist/host/host-installer.d.ts +7 -0
  18. package/core/dist/host/host-installer.d.ts.map +1 -1
  19. package/core/dist/host/host-installer.js.map +1 -1
  20. package/core/dist/runtime/activation/index.d.ts +3 -3
  21. package/core/dist/runtime/activation/index.d.ts.map +1 -1
  22. package/core/dist/runtime/activation/index.js +1 -1
  23. package/core/dist/runtime/activation/index.js.map +1 -1
  24. package/core/dist/runtime/activation/promotion-readiness-evaluator.d.ts +25 -1
  25. package/core/dist/runtime/activation/promotion-readiness-evaluator.d.ts.map +1 -1
  26. package/core/dist/runtime/activation/promotion-readiness-evaluator.js +58 -1
  27. package/core/dist/runtime/activation/promotion-readiness-evaluator.js.map +1 -1
  28. package/core/dist/runtime/activation/promotion-readiness-reader.d.ts.map +1 -1
  29. package/core/dist/runtime/activation/promotion-readiness-reader.js +4 -2
  30. package/core/dist/runtime/activation/promotion-readiness-reader.js.map +1 -1
  31. package/core/dist/runtime/activation/rulecode-owner-decision-service.d.ts +28 -0
  32. package/core/dist/runtime/activation/rulecode-owner-decision-service.d.ts.map +1 -1
  33. package/core/dist/runtime/activation/rulecode-owner-decision-service.js +2 -0
  34. package/core/dist/runtime/activation/rulecode-owner-decision-service.js.map +1 -1
  35. package/core/dist/runtime/activation-compatibility-read-model.d.ts +20 -5
  36. package/core/dist/runtime/activation-compatibility-read-model.d.ts.map +1 -1
  37. package/core/dist/runtime/activation-compatibility-read-model.js +15 -3
  38. package/core/dist/runtime/activation-compatibility-read-model.js.map +1 -1
  39. package/core/dist/runtime/admission-gate.d.ts +8 -1
  40. package/core/dist/runtime/admission-gate.d.ts.map +1 -1
  41. package/core/dist/runtime/admission-gate.js +2 -1
  42. package/core/dist/runtime/admission-gate.js.map +1 -1
  43. package/core/dist/runtime/config/pd-config-defaults.d.ts.map +1 -1
  44. package/core/dist/runtime/config/pd-config-defaults.js +20 -2
  45. package/core/dist/runtime/config/pd-config-defaults.js.map +1 -1
  46. package/core/dist/runtime/config/pd-config-validate.d.ts.map +1 -1
  47. package/core/dist/runtime/config/pd-config-validate.js +18 -0
  48. package/core/dist/runtime/config/pd-config-validate.js.map +1 -1
  49. package/core/dist/runtime/context-payload.d.ts +48 -3
  50. package/core/dist/runtime/context-payload.d.ts.map +1 -1
  51. package/core/dist/runtime/context-payload.js +38 -0
  52. package/core/dist/runtime/context-payload.js.map +1 -1
  53. package/core/dist/runtime/diagnostician/rootcause-prompt-builder.d.ts +8 -2
  54. package/core/dist/runtime/diagnostician/rootcause-prompt-builder.d.ts.map +1 -1
  55. package/core/dist/runtime/diagnostician/rootcause-prompt-builder.js +28 -2
  56. package/core/dist/runtime/diagnostician/rootcause-prompt-builder.js.map +1 -1
  57. package/core/dist/runtime/diagnostician-candidate.d.ts +24 -0
  58. package/core/dist/runtime/diagnostician-candidate.d.ts.map +1 -0
  59. package/core/dist/runtime/diagnostician-candidate.js +55 -0
  60. package/core/dist/runtime/diagnostician-candidate.js.map +1 -0
  61. package/core/dist/runtime/evidence-guards.d.ts +10 -4
  62. package/core/dist/runtime/evidence-guards.d.ts.map +1 -1
  63. package/core/dist/runtime/evidence-guards.js +12 -5
  64. package/core/dist/runtime/evidence-guards.js.map +1 -1
  65. package/core/dist/runtime/evolution/evolution-types.d.ts +4 -4
  66. package/core/dist/runtime/evolution/evolution-types.d.ts.map +1 -1
  67. package/core/dist/runtime/evolution/evolution-types.js +1 -0
  68. package/core/dist/runtime/evolution/evolution-types.js.map +1 -1
  69. package/core/dist/runtime/feature-flags/feature-flag-contract.d.ts.map +1 -1
  70. package/core/dist/runtime/feature-flags/feature-flag-contract.js +14 -0
  71. package/core/dist/runtime/feature-flags/feature-flag-contract.js.map +1 -1
  72. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.d.ts.map +1 -1
  73. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +16 -0
  74. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
  75. package/core/dist/runtime/index.d.ts +5 -2
  76. package/core/dist/runtime/index.d.ts.map +1 -1
  77. package/core/dist/runtime/index.js +6 -1
  78. package/core/dist/runtime/index.js.map +1 -1
  79. package/core/dist/runtime/internalization/index.d.ts +1 -0
  80. package/core/dist/runtime/internalization/index.d.ts.map +1 -1
  81. package/core/dist/runtime/internalization/index.js +2 -0
  82. package/core/dist/runtime/internalization/index.js.map +1 -1
  83. package/core/dist/runtime/internalization/rule-host-contracts.d.ts +10 -0
  84. package/core/dist/runtime/internalization/rule-host-contracts.d.ts.map +1 -1
  85. package/core/dist/runtime/internalization/rule-host-evaluator.js +10 -10
  86. package/core/dist/runtime/internalization/rule-host-evaluator.js.map +1 -1
  87. package/core/dist/runtime/internalization/rule-host-input-builder.d.ts +7 -6
  88. package/core/dist/runtime/internalization/rule-host-input-builder.d.ts.map +1 -1
  89. package/core/dist/runtime/internalization/rule-host-input-builder.js +6 -2
  90. package/core/dist/runtime/internalization/rule-host-input-builder.js.map +1 -1
  91. package/core/dist/runtime/internalization/rule-host-result-normalizer.d.ts +33 -0
  92. package/core/dist/runtime/internalization/rule-host-result-normalizer.d.ts.map +1 -0
  93. package/core/dist/runtime/internalization/rule-host-result-normalizer.js +61 -0
  94. package/core/dist/runtime/internalization/rule-host-result-normalizer.js.map +1 -0
  95. package/core/dist/runtime/internalization/rule-host-validator.d.ts.map +1 -1
  96. package/core/dist/runtime/internalization/rule-host-validator.js +17 -0
  97. package/core/dist/runtime/internalization/rule-host-validator.js.map +1 -1
  98. package/core/dist/runtime/pain-ingress-payload.d.ts +27 -2
  99. package/core/dist/runtime/pain-ingress-payload.d.ts.map +1 -1
  100. package/core/dist/runtime/pain-ingress-payload.js +45 -3
  101. package/core/dist/runtime/pain-ingress-payload.js.map +1 -1
  102. package/core/dist/runtime/pain-ingress.d.ts +4 -2
  103. package/core/dist/runtime/pain-ingress.d.ts.map +1 -1
  104. package/core/dist/runtime/pain-ingress.js +23 -3
  105. package/core/dist/runtime/pain-ingress.js.map +1 -1
  106. package/core/dist/runtime/pain-severity.d.ts +14 -0
  107. package/core/dist/runtime/pain-severity.d.ts.map +1 -0
  108. package/core/dist/runtime/pain-severity.js +14 -0
  109. package/core/dist/runtime/pain-severity.js.map +1 -0
  110. package/core/dist/runtime/pain-signal-bridge.d.ts +17 -3
  111. package/core/dist/runtime/pain-signal-bridge.d.ts.map +1 -1
  112. package/core/dist/runtime/pain-signal-bridge.js +6 -0
  113. package/core/dist/runtime/pain-signal-bridge.js.map +1 -1
  114. package/core/dist/runtime/pain-signal-observability.d.ts.map +1 -1
  115. package/core/dist/runtime/pain-signal-observability.js +3 -2
  116. package/core/dist/runtime/pain-signal-observability.js.map +1 -1
  117. package/core/dist/runtime/pain-submit-capability.d.ts +164 -0
  118. package/core/dist/runtime/pain-submit-capability.d.ts.map +1 -0
  119. package/core/dist/runtime/pain-submit-capability.js +442 -0
  120. package/core/dist/runtime/pain-submit-capability.js.map +1 -0
  121. package/core/dist/runtime/pain-to-principle-service.d.ts +4 -0
  122. package/core/dist/runtime/pain-to-principle-service.d.ts.map +1 -1
  123. package/core/dist/runtime/pain-to-principle-service.js +2 -0
  124. package/core/dist/runtime/pain-to-principle-service.js.map +1 -1
  125. package/core/dist/runtime/stalled-diagnostician-task-read-model.d.ts +56 -10
  126. package/core/dist/runtime/stalled-diagnostician-task-read-model.d.ts.map +1 -1
  127. package/core/dist/runtime/stalled-diagnostician-task-read-model.js +80 -4
  128. package/core/dist/runtime/stalled-diagnostician-task-read-model.js.map +1 -1
  129. package/core/dist/runtime/store/context/sqlite-context-assembler.d.ts.map +1 -1
  130. package/core/dist/runtime/store/context/sqlite-context-assembler.js +11 -0
  131. package/core/dist/runtime/store/context/sqlite-context-assembler.js.map +1 -1
  132. package/core/dist/runtime/store/run/memory-run-store.d.ts +10 -0
  133. package/core/dist/runtime/store/run/memory-run-store.d.ts.map +1 -1
  134. package/core/dist/runtime/store/run/memory-run-store.js +21 -0
  135. package/core/dist/runtime/store/run/memory-run-store.js.map +1 -1
  136. package/core/dist/runtime/store/run/run-store.d.ts +12 -0
  137. package/core/dist/runtime/store/run/run-store.d.ts.map +1 -1
  138. package/core/dist/runtime/store/run/sqlite-run-store.d.ts +1 -0
  139. package/core/dist/runtime/store/run/sqlite-run-store.d.ts.map +1 -1
  140. package/core/dist/runtime/store/run/sqlite-run-store.js +14 -0
  141. package/core/dist/runtime/store/run/sqlite-run-store.js.map +1 -1
  142. package/core/dist/runtime/task-status.d.ts +9 -0
  143. package/core/dist/runtime/task-status.d.ts.map +1 -1
  144. package/core/dist/runtime/task-status.js +7 -1
  145. package/core/dist/runtime/task-status.js.map +1 -1
  146. package/core/dist/runtime/types/evidence-chain-contract.d.ts +18 -0
  147. package/core/dist/runtime/types/evidence-chain-contract.d.ts.map +1 -1
  148. package/core/dist/runtime/types/evidence-chain-contract.js +37 -7
  149. package/core/dist/runtime/types/evidence-chain-contract.js.map +1 -1
  150. package/core/package.json +5 -1
  151. package/dist/install-summary.d.ts +7 -0
  152. package/dist/install-summary.d.ts.map +1 -1
  153. package/dist/install-summary.js +4 -0
  154. package/dist/install-summary.js.map +1 -1
  155. package/dist/installer.d.ts +92 -8
  156. package/dist/installer.d.ts.map +1 -1
  157. package/dist/installer.js +215 -10
  158. package/dist/installer.js.map +1 -1
  159. package/dist/installers/codex-host-installer.d.ts +88 -1
  160. package/dist/installers/codex-host-installer.d.ts.map +1 -1
  161. package/dist/installers/codex-host-installer.js +350 -11
  162. package/dist/installers/codex-host-installer.js.map +1 -1
  163. package/dist/installers/index.d.ts +23 -0
  164. package/dist/installers/index.d.ts.map +1 -1
  165. package/dist/installers/index.js +38 -1
  166. package/dist/installers/index.js.map +1 -1
  167. package/dist/installers/legacy-workbuddy-skill.d.ts +59 -0
  168. package/dist/installers/legacy-workbuddy-skill.d.ts.map +1 -0
  169. package/dist/installers/legacy-workbuddy-skill.js +168 -0
  170. package/dist/installers/legacy-workbuddy-skill.js.map +1 -0
  171. package/dist/installers/workbuddy-host-installer.d.ts.map +1 -1
  172. package/dist/installers/workbuddy-host-installer.js +7 -0
  173. package/dist/installers/workbuddy-host-installer.js.map +1 -1
  174. package/host-runtime/dist/adaptive-priority-provider.d.ts +94 -0
  175. package/host-runtime/dist/adaptive-priority-provider.js +162 -0
  176. package/host-runtime/dist/adaptive-selection.d.ts +164 -0
  177. package/host-runtime/dist/adaptive-selection.js +506 -0
  178. package/host-runtime/dist/diagnostician-auto-run.d.ts +28 -0
  179. package/host-runtime/dist/diagnostician-auto-run.js +100 -0
  180. package/host-runtime/dist/host-tool-semantic-resolver.d.ts +42 -1
  181. package/host-runtime/dist/host-tool-semantic-resolver.js +80 -14
  182. package/host-runtime/dist/index.d.ts +4 -0
  183. package/host-runtime/dist/index.js +6 -0
  184. package/host-runtime/dist/production-rulehost-gate.js +17 -17
  185. package/host-runtime/dist/rulecode-event-collection.d.ts +31 -0
  186. package/host-runtime/dist/rulecode-event-collection.js +62 -0
  187. package/host-runtime/package.json +1 -1
  188. package/install-layout/dist/index.d.ts +1 -1
  189. package/install-layout/dist/index.js +1 -1
  190. package/install-layout/dist/pd-home.d.ts +9 -2
  191. package/install-layout/dist/pd-home.js +77 -14
  192. package/install-layout/package.json +1 -1
  193. package/package.json +4 -4
  194. package/pd-cli/dist/commands/diagnose.d.ts +30 -0
  195. package/pd-cli/dist/commands/diagnose.d.ts.map +1 -1
  196. package/pd-cli/dist/commands/diagnose.js +75 -0
  197. package/pd-cli/dist/commands/diagnose.js.map +1 -1
  198. package/pd-cli/dist/commands/pain-record.d.ts.map +1 -1
  199. package/pd-cli/dist/commands/pain-record.js +5 -4
  200. package/pd-cli/dist/commands/pain-record.js.map +1 -1
  201. package/pd-cli/dist/commands/pain-retry.d.ts.map +1 -1
  202. package/pd-cli/dist/commands/pain-retry.js +2 -1
  203. package/pd-cli/dist/commands/pain-retry.js.map +1 -1
  204. package/pd-cli/dist/commands/runtime-activation.d.ts +6 -17
  205. package/pd-cli/dist/commands/runtime-activation.d.ts.map +1 -1
  206. package/pd-cli/dist/commands/runtime-activation.js +42 -48
  207. package/pd-cli/dist/commands/runtime-activation.js.map +1 -1
  208. package/pd-cli/dist/commands/runtime-compatibility-scan.d.ts +5 -2
  209. package/pd-cli/dist/commands/runtime-compatibility-scan.d.ts.map +1 -1
  210. package/pd-cli/dist/commands/runtime-compatibility-scan.js +22 -2
  211. package/pd-cli/dist/commands/runtime-compatibility-scan.js.map +1 -1
  212. package/pd-cli/dist/index.js +1 -0
  213. package/pd-cli/dist/index.js.map +1 -1
  214. package/pd-cli/dist/services/config-doctor.d.ts +9 -0
  215. package/pd-cli/dist/services/config-doctor.d.ts.map +1 -1
  216. package/pd-cli/dist/services/config-doctor.js +15 -0
  217. package/pd-cli/dist/services/config-doctor.js.map +1 -1
  218. package/pd-cli/dist/services/delivery-surfaces.js +1 -1
  219. package/pd-cli/dist/services/delivery-surfaces.js.map +1 -1
  220. package/pd-cli/package.json +1 -1
  221. package/pd-mcp-server/dist/budget.d.ts +1 -1
  222. package/pd-mcp-server/dist/budget.js +2 -2
  223. package/pd-mcp-server/dist/envelope.d.ts +15 -0
  224. package/pd-mcp-server/dist/envelope.js +49 -1
  225. package/pd-mcp-server/dist/index.d.ts +2 -0
  226. package/pd-mcp-server/dist/index.js +6 -0
  227. package/pd-mcp-server/dist/server.d.ts +83 -14
  228. package/pd-mcp-server/dist/server.js +251 -4
  229. package/pd-mcp-server/dist/version.d.ts +1 -1
  230. package/pd-mcp-server/dist/version.js +1 -1
  231. package/pd-mcp-server/dist/workspace.d.ts +4 -2
  232. package/pd-mcp-server/dist/workspace.js +5 -2
  233. package/pd-mcp-server/package.json +1 -1
  234. package/plugin/dist/bundle.js +443 -431
  235. package/plugin/dist/core/evolution-reducer.d.ts +2 -2
  236. package/plugin/dist/hooks/hook-tool-semantics.d.ts +25 -0
  237. package/plugin/dist/hooks/pain-ingress-adapter.d.ts +1 -1
  238. package/plugin/dist/openclaw.plugin.json +1 -1
  239. package/plugin/dist/rulehost-evidence.js +1 -1
  240. package/plugin/openclaw.plugin.json +1 -1
  241. package/plugin/package.json +1 -1
  242. package/release-manager/dist/installer.js +215 -10
  243. package/release-manager/dist/installers/codex-host-installer.js +350 -11
  244. package/release-manager/dist/installers/index.js +38 -1
  245. package/release-manager/dist/installers/legacy-workbuddy-skill.js +168 -0
  246. package/release-manager/dist/installers/workbuddy-host-installer.js +7 -0
  247. package/release-manager/package.json +1 -1
  248. package/workbuddy-adapter/dist/pd-hook.js +20 -4
  249. package/workbuddy-adapter/package.json +1 -1
  250. package/workbuddy-adapter/plugin/skills/pd-pain-signal/SKILL.md +123 -20
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "productVersion": "2.8.6",
4
- "sourceCommit": "14077529ae736f07922c62010a266569ce034294"
4
+ "sourceCommit": "8851a3be8c3bcacb732609143bfe3d2ac4ba4ea5"
5
5
  }
@@ -11,5 +11,26 @@ export interface CodexEvidenceContext {
11
11
  evidenceEnabled: boolean;
12
12
  warn: (diagnosticLine: string) => void;
13
13
  }
14
- export declare function processHookInvocation(rawStdin: string, _env?: EnvMap, cwd?: string): Promise<PdHookResult>;
14
+ /**
15
+ * The host hook window is declared by the plugin manifest
16
+ * (`plugins/principles-disciple/hooks/hooks.json`, `UserPromptSubmit.timeout`,
17
+ * in seconds). Codex owns that timer and terminates the hook process when it
18
+ * fires; PD gets no in-band notification, so Adaptive must end BEFORE the
19
+ * window and leave the remainder to emit the Native body.
20
+ * `pd-hook-adaptive.test.ts` guards this constant against the manifest.
21
+ */
22
+ export declare const CODEX_HOOK_TIMEOUT_MS = 5000;
23
+ /** Reserved for Native packing, encoding and stdout after Adaptive is cut off. */
24
+ export declare const CODEX_NATIVE_RESERVE_MS = 800;
25
+ export declare const CODEX_ADAPTIVE_BUDGET_MS: number;
26
+ export interface PdHookDeps {
27
+ /** Test seam: replace the outbound transport without bypassing the hook entry. */
28
+ readonly fetchImpl?: typeof fetch;
29
+ readonly now?: () => number;
30
+ readonly firstByteTimeoutMs?: number;
31
+ readonly generationTimeoutMs?: number;
32
+ /** Test seam: effective adaptive budget inside the host hook window. */
33
+ readonly hookBudgetMs?: number;
34
+ }
35
+ export declare function processHookInvocation(rawStdin: string, _env?: EnvMap, cwd?: string, deps?: PdHookDeps): Promise<PdHookResult>;
15
36
  export {};
@@ -5,8 +5,8 @@ import path from 'node:path';
5
5
  import process from 'node:process';
6
6
  import { pathToFileURL, fileURLToPath } from 'node:url';
7
7
  import { appendEventLogLine, redactTelemetryString, isRuleHostEvaluatedEventData } from '@principles/core/runtime';
8
- import { createCodexRuleContextProvider, createProductionHostRuntime, loadPdConfigForPlugin, resolveNearestPdWorkspace } from '@principles/host-runtime';
9
- import { CODEX_TOOL_SEMANTICS } from './tool-semantics.js';
8
+ import { createAdaptivePriorityProviderForConfig, createCodexRuleContextProvider, createProductionHostRuntime, loadPdConfigForPlugin, resolveHostToolSemanticsForHook, resolveNearestPdWorkspace } from '@principles/host-runtime';
9
+ import { CODEX_TOOL_SEMANTIC_MAPPINGS, CODEX_TOOL_SEMANTICS } from './tool-semantics.js';
10
10
  import { computeFeatureFlagsFromConfig } from '@principles/core/runtime';
11
11
  import { CodexHooksHostAdapter } from './host-adapter.js';
12
12
  import { CodexDecoderError, CodexEncoderError } from './codec/index.js';
@@ -24,6 +24,19 @@ function diagnostic(reason, nextAction) {
24
24
  function errorMessage(error) {
25
25
  return error instanceof Error ? error.message.slice(0, MAX_DIAGNOSTIC) : 'unknown_error';
26
26
  }
27
+ /**
28
+ * PRI-1170: one bounded line per Adaptive turn. Records the facts needed to
29
+ * tell first-byte expiry, generation expiry, transport failure and ref/digest
30
+ * rejection apart — never the prompt, the raw response, or credentials.
31
+ */
32
+ function adaptiveSelectionDiagnostic(line) {
33
+ const status = line.status === 'selected' ? 'adaptive' : 'degraded';
34
+ const failures = line.failures.length > 0 ? line.failures.join('|') : 'none';
35
+ return `[PD] status=${status} reason=adaptive_selection_${line.status}:${line.reason} stage=${line.stage} sends=${line.sends} firstByteAt=${line.firstByteAt ?? 'unknown'} generationEndedAt=${line.generationEndedAt ?? 'unknown'} cancelledAt=${line.cancelledAt ?? 'unknown'} httpStatus=${line.httpStatus ?? 'unknown'} finishReason=${line.finishReason} failures=${failures}`
36
+ .replace(/\s+/g, ' ')
37
+ .trim()
38
+ .slice(0, MAX_DIAGNOSTIC * 2);
39
+ }
27
40
  function redactStringFields(data) {
28
41
  // rc-8: telemetry is redacted string-field by string field (same policy as
29
42
  // the OpenClaw EventLog redactEventData) — shared by every emitter here.
@@ -191,7 +204,25 @@ async function runConversationIngestion(args) {
191
204
  }
192
205
  return diagnostics;
193
206
  }
194
- export async function processHookInvocation(rawStdin, _env = process.env, cwd = process.cwd()) {
207
+ /**
208
+ * The host hook window is declared by the plugin manifest
209
+ * (`plugins/principles-disciple/hooks/hooks.json`, `UserPromptSubmit.timeout`,
210
+ * in seconds). Codex owns that timer and terminates the hook process when it
211
+ * fires; PD gets no in-band notification, so Adaptive must end BEFORE the
212
+ * window and leave the remainder to emit the Native body.
213
+ * `pd-hook-adaptive.test.ts` guards this constant against the manifest.
214
+ */
215
+ export const CODEX_HOOK_TIMEOUT_MS = 5_000;
216
+ /** Reserved for Native packing, encoding and stdout after Adaptive is cut off. */
217
+ export const CODEX_NATIVE_RESERVE_MS = 800;
218
+ export const CODEX_ADAPTIVE_BUDGET_MS = CODEX_HOOK_TIMEOUT_MS - CODEX_NATIVE_RESERVE_MS;
219
+ // stdin, env and cwd are the host CLI contract; `deps` is the optional transport
220
+ // seam that lets integration tests drive the real entry point without a network.
221
+ // eslint-disable-next-line @typescript-eslint/max-params
222
+ export async function processHookInvocation(rawStdin, _env = process.env, cwd = process.cwd(), deps = {}) {
223
+ // The host owns this window and kills the process when it expires; anchor at
224
+ // entry so decode/ingestion time counts against the same budget.
225
+ const adaptiveDeadlineAt = Date.now() + (deps.hookBudgetMs ?? CODEX_ADAPTIVE_BUDGET_MS);
195
226
  let parsed;
196
227
  try {
197
228
  parsed = JSON.parse(rawStdin);
@@ -385,17 +416,55 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
385
416
  // event-JSONL writer (same events_*.jsonl format as the OpenClaw EventLog;
386
417
  // the Codex adapter stays independent of the OpenClaw plugin). The line
387
418
  // writer appends synchronously — no flush/dispose needed for the subprocess.
419
+ // PRI-1170: Adaptive Activation is an INDEPENDENT, default-off switch on
420
+ // top of the PD hook. `host.codex.enabled` remains the whole-hook gate.
421
+ const adaptiveDiagnostics = [];
422
+ let adaptivePriorityProvider;
423
+ if (event.kind === 'before_prompt_build' && flags['host.codex.adaptive_activation']?.enabled === true) {
424
+ const adaptive = createAdaptivePriorityProviderForConfig(config.effective.config, resolution.workspaceDir, {
425
+ env: _env,
426
+ ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),
427
+ ...(deps.now ? { now: deps.now } : {}),
428
+ ...(deps.firstByteTimeoutMs !== undefined ? { firstByteTimeoutMs: deps.firstByteTimeoutMs } : {}),
429
+ ...(deps.generationTimeoutMs !== undefined ? { generationTimeoutMs: deps.generationTimeoutMs } : {}),
430
+ outerDeadlineAt: adaptiveDeadlineAt,
431
+ onDiagnostic: (line) => { adaptiveDiagnostics.push(adaptiveSelectionDiagnostic(line)); },
432
+ });
433
+ if (adaptive.ok) {
434
+ adaptivePriorityProvider = adaptive.provider;
435
+ }
436
+ else {
437
+ // rc-9: an enabled-but-unusable switch is observable, never silent.
438
+ adaptiveDiagnostics.push(diagnostic(`adaptive_activation_${adaptive.readiness}:${adaptive.reason}`, adaptive.nextAction));
439
+ }
440
+ }
441
+ // B3: resolve tool semantics from the workspace declarations — the SAME
442
+ // source replay / evidence / Console read — with the compiled-in Codex
443
+ // declaration as the fallback. A malformed declaration degrades
444
+ // observably on stderr instead of blocking the tool call (rc-9).
445
+ const toolSemanticsResolution = resolveHostToolSemanticsForHook({
446
+ workspaceDir: resolution.workspaceDir,
447
+ hostKind: 'codex',
448
+ staticMappings: CODEX_TOOL_SEMANTIC_MAPPINGS,
449
+ });
450
+ const toolSemantics = toolSemanticsResolution.ok
451
+ ? toolSemanticsResolution.registry
452
+ : CODEX_TOOL_SEMANTICS;
453
+ const toolSemanticsDiagnostics = toolSemanticsResolution.ok
454
+ ? []
455
+ : [diagnostic(toolSemanticsResolution.reason, toolSemanticsResolution.nextAction)];
388
456
  const result = await createProductionHostRuntime({
389
457
  projectDir: requestedCwd,
390
458
  hostKind: 'codex',
391
- toolSemantics: CODEX_TOOL_SEMANTICS,
459
+ toolSemantics,
460
+ ...(adaptivePriorityProvider ? { adaptivePriorityProvider } : {}),
392
461
  ruleContextProvider: createCodexRuleContextProvider({
393
462
  workspaceDir: resolution.workspaceDir,
394
463
  projectDir: requestedCwd,
395
464
  enabled: flags.rulecode_context_v2?.enabled === true && ingestionEnabled,
396
465
  cutoffAt: hookEpoch,
397
466
  currentToolUseId: event.context.toolCallId ?? '',
398
- toolSemantics: CODEX_TOOL_SEMANTICS,
467
+ toolSemantics,
399
468
  }),
400
469
  events: codexEventEmitter(path.join(resolution.workspaceDir, '.state'), evidenceContext),
401
470
  }).dispatch(event);
@@ -463,7 +532,7 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
463
532
  evidenceDiagnostics.push(diagnostic(`codex_evidence_deny_failed:${errorMessage(error)}`, 'The deny decision was already encoded; evidence replay from the durable source is safe.'));
464
533
  }
465
534
  }
466
- const stderr = [...(result.warnings ?? []).slice(0, 16).map((warning) => diagnostic(warning, 'Inspect PD Workspace state and retry; the hook failed open.')), ...evaluationDiagnostics, ...evidenceDiagnostics, ...ingestionDiagnostics, ...explicitDiagnostics];
535
+ const stderr = [...(result.warnings ?? []).slice(0, 16).map((warning) => diagnostic(warning, 'Inspect PD Workspace state and retry; the hook failed open.')), ...evaluationDiagnostics, ...evidenceDiagnostics, ...ingestionDiagnostics, ...explicitDiagnostics, ...adaptiveDiagnostics, ...toolSemanticsDiagnostics];
467
536
  return { stdout: encoded, exitCode: 0, stderr };
468
537
  }
469
538
  catch (error) {
@@ -545,7 +614,12 @@ async function main() {
545
614
  }
546
615
  let result;
547
616
  try {
548
- result = await processHookInvocation(raw);
617
+ // The host's 5 s window starts at process spawn, not at this call: node
618
+ // boot and module loading already consumed part of it. Anchor the deadline
619
+ // at process start so the measured reserve really reaches Native.
620
+ const elapsedSinceProcessStartMs = Math.round(process.uptime() * 1000);
621
+ const remainingBudgetMs = Math.max(1, CODEX_ADAPTIVE_BUDGET_MS - elapsedSinceProcessStartMs);
622
+ result = await processHookInvocation(raw, process.env, process.cwd(), { hookBudgetMs: remainingBudgetMs });
549
623
  }
550
624
  catch (error) {
551
625
  // Fail-open belt for an unexpected pre-dispatch throw (e.g. a workspace
@@ -67,6 +67,21 @@ export interface CodexWorkerCycleOptions {
67
67
  readonly stage2AggregateBudgetMs?: number;
68
68
  }
69
69
  export declare function readCodexWorkerLiveness(workspaceDir: string): Record<string, unknown> | null;
70
+ /**
71
+ * SPEC §9.1 fair-share pick (review P1): pending and due-retry are both
72
+ * continuously-eligible classes; neither may starve the other while new
73
+ * pending signals keep arriving. A persistent round-robin cursor (stored in
74
+ * the existing reconciliation_cursor authority, so a worker restart does NOT
75
+ * reset it to pending-priority) alternates service between the two classes —
76
+ * each eligible class is served at least every other cycle, well inside the
77
+ * 3-full-cycle bound. Single-eligible work is always served.
78
+ *
79
+ * The implementation is shared with OpenClaw's L3 automatic run
80
+ * (`@principles/core/runtime` `pickDiagnosticianCandidate`); this file keeps no
81
+ * second copy. Oldest pending diagnostician first; retry_wait candidates are
82
+ * filtered to those whose backoff window has ELAPSED, so an old-but-still-
83
+ * waiting task cannot starve a younger eligible one (review P1).
84
+ */
70
85
  /**
71
86
  * Run ONE bounded worker cycle for a canonical workspace. Never throws:
72
87
  * every failure becomes a structured degraded result with a nextAction.
@@ -27,7 +27,7 @@
27
27
  */
28
28
  import fs from 'node:fs';
29
29
  import path from 'node:path';
30
- import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime';
30
+ import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, pickDiagnosticianCandidate, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime';
31
31
  import { createWorkspaceBehaviorEvidencePort, createCodexArtificerTrustedFactsPort, loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, saveHostToolDeclaration, } from '@principles/host-runtime';
32
32
  import { catchUpCodexIngestion } from '../ingestion/catch-up.js';
33
33
  import { CODEX_TOOL_SEMANTIC_MAPPINGS, CODEX_TOOL_SEMANTICS } from '../tool-semantics.js';
@@ -111,14 +111,6 @@ function writeLiveness(workspaceDir, patch) {
111
111
  // itself remains the observable degradation channel)
112
112
  }
113
113
  }
114
- /**
115
- * Oldest pending diagnostician first; retry_wait candidates are filtered to
116
- * those whose backoff window has ELAPSED, so an old-but-still-waiting task
117
- * cannot starve a younger eligible one (review P1). The candidate set stays
118
- * bounded (`limit`), and executePendingDiagnosis re-enforces the backoff
119
- * window on the chosen task — no double bookkeeping.
120
- */
121
- const DIAGNOSTICIAN_FAIR_SHARE_SCOPE = 'codex-worker-diagnostician-fair-share';
122
114
  /**
123
115
  * SPEC §9.1 fair-share pick (review P1): pending and due-retry are both
124
116
  * continuously-eligible classes; neither may starve the other while new
@@ -127,34 +119,13 @@ const DIAGNOSTICIAN_FAIR_SHARE_SCOPE = 'codex-worker-diagnostician-fair-share';
127
119
  * reset it to pending-priority) alternates service between the two classes —
128
120
  * each eligible class is served at least every other cycle, well inside the
129
121
  * 3-full-cycle bound. Single-eligible work is always served.
122
+ *
123
+ * The implementation is shared with OpenClaw's L3 automatic run
124
+ * (`@principles/core/runtime` `pickDiagnosticianCandidate`); this file keeps no
125
+ * second copy. Oldest pending diagnostician first; retry_wait candidates are
126
+ * filtered to those whose backoff window has ELAPSED, so an old-but-still-
127
+ * waiting task cannot starve a younger eligible one (review P1).
130
128
  */
131
- async function pickDiagnosticianCandidate(stateManager, limit, nowIso) {
132
- const pending = await stateManager.listTasks({ taskKind: 'diagnostician', status: 'pending', orderBy: 'updated_at_asc', limit });
133
- const [pendingTask] = pending;
134
- let retryTask = null;
135
- const retrying = await stateManager.listTasks({ taskKind: 'diagnostician', status: 'retry_wait', orderBy: 'updated_at_asc', limit });
136
- for (const candidate of retrying) {
137
- if (isRetryWaitBackoffElapsed(candidate.status, candidate.leaseExpiresAt)) {
138
- retryTask = candidate;
139
- break;
140
- }
141
- }
142
- if (pendingTask === undefined && retryTask === null)
143
- return null;
144
- if (retryTask === null) {
145
- await stateManager.setDiagnosticianServiceCursor(DIAGNOSTICIAN_FAIR_SHARE_SCOPE, { lastUpdatedAt: nowIso, lastTaskId: 'pending' });
146
- return pendingTask ?? null;
147
- }
148
- if (pendingTask === undefined) {
149
- await stateManager.setDiagnosticianServiceCursor(DIAGNOSTICIAN_FAIR_SHARE_SCOPE, { lastUpdatedAt: nowIso, lastTaskId: 'retry_wait' });
150
- return retryTask;
151
- }
152
- const cursor = await stateManager.getDiagnosticianServiceCursor(DIAGNOSTICIAN_FAIR_SHARE_SCOPE);
153
- const serveRetryFirst = cursor?.lastTaskId !== 'retry_wait';
154
- const servedClass = serveRetryFirst ? 'retry_wait' : 'pending';
155
- await stateManager.setDiagnosticianServiceCursor(DIAGNOSTICIAN_FAIR_SHARE_SCOPE, { lastUpdatedAt: nowIso, lastTaskId: servedClass });
156
- return serveRetryFirst ? retryTask : pendingTask;
157
- }
158
129
  /**
159
130
  * Run ONE bounded worker cycle for a canonical workspace. Never throws:
160
131
  * every failure becomes a structured degraded result with a nextAction.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/codex-adapter",
3
- "version": "0.8.7",
3
+ "version": "0.8.10",
4
4
  "description": "Codex CLI host adapter for Principles Disciple — implements HostAdapter interface for OpenAI Codex CLI's stdin/stdout JSON hook model (ADR-0020).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -14,6 +14,7 @@ import { EXPERIMENT_CONSOLE_PORT, defaultConsolePort } from './console-ports.js'
14
14
  import { WorkspaceService } from './models/WorkspaceService.js';
15
15
  import { handleFeedbackReportsRoute, handleFeedbackChannelsRoute, disposeFeedbackReportModels, } from './routes/feedback-reports.js';
16
16
  import { handleFailedTasksRoute, disposeFailedTasksModels } from './routes/failed-tasks.js';
17
+ import { handleDiagnosticianRoute } from './routes/diagnostician.js';
17
18
  import { handleApprovalsRoute, disposeApprovalsModels } from './routes/approvals.js';
18
19
  import { handleHealthRoute, disposeHealthModels } from './routes/health.js';
19
20
  import { handlePrinciplesRoute, handleCorePrinciplesRoute, disposePrinciplesModels } from './routes/principles.js';
@@ -21,6 +22,7 @@ import { handleLifecycleRoute, disposeLifecycleModels } from './routes/lifecycle
21
22
  import { handleExaminerRoute } from './routes/examiner.js';
22
23
  import { handleActivationsRoute, disposeActivationsModels } from './routes/activations.js';
23
24
  import { handleReceiptsRoute, disposeReceiptsModels } from './routes/receipts.js';
25
+ import { handleCompatibilityScanRoute } from './routes/compatibility-scan.js';
24
26
  import { handleApprovalsGroupedRoute, disposeApprovalsGroupedModels } from './routes/approvals-grouped.js';
25
27
  import { handleGovernanceRoute, handleGovernanceExperienceRoute, resolveOwnerConfigSnapshot, disposeGovernanceModels } from './routes/governance.js';
26
28
  import { handleOwnerDecisionsRoute } from './routes/owner-decisions.js';
@@ -252,12 +254,17 @@ export async function initServices(workspaceDir, authConfig) {
252
254
  // Governance Experience Snapshot v1.5.1 (PRI-584~587): default off; flag-off
253
255
  // keeps the legacy Focus experience and 403s the endpoint before any DB access.
254
256
  const governanceExperienceEnabled = pdFlags.flags.governance_experience_v1?.enabled ?? false;
257
+ // SPEC v0.8 §9.4 (L3): OpenClaw auto-execution flag, reported as a
258
+ // configuration fact on the backlog page. Default on; the console never
259
+ // executes it (L3 runs inside the OpenClaw service).
260
+ const openclawDiagnosticianConsumerEnabled = pdFlags.flags.openclaw_diagnostician_consumer?.enabled ?? true;
255
261
  const feedbackFlags = {
256
262
  feedback_channel: { enabled: feedbackChannelEnabled },
257
263
  failed_tasks_observability: { enabled: failedTasksObservabilityEnabled },
258
264
  principle_governance_projection_v2: { enabled: governanceProjectionEnabled },
259
265
  failed_task_recovery_console: { enabled: failedTaskRecoveryEnabled },
260
266
  governance_experience_v1: { enabled: governanceExperienceEnabled },
267
+ openclaw_diagnostician_consumer: { enabled: openclawDiagnosticianConsumerEnabled },
261
268
  };
262
269
  if (!configResult.ok) {
263
270
  console.warn('[pd-console] PD config loading failed (using defaults for feedback channel):', configResult.errors.map(e => e.reason).join('; '));
@@ -361,12 +368,26 @@ export function handleRequest(services) {
361
368
  asyncHandler(() => handleFeedbackReportsRoute(req, res, { workspaceDir: services.workspaceDir, subPath, featureFlags: services.feedbackFlags, maintainerEmail: services.maintainerEmail, channelConfig: services.feedbackChannelConfig }))(req, res);
362
369
  return;
363
370
  }
371
+ // SPEC v0.8 §9.2/§9.4: POST /api/diagnostician/:taskId/run (L2) and
372
+ // GET /api/diagnostician/backlog (L2b). The route never executes the
373
+ // diagnosis in-process; see routes/diagnostician.ts.
374
+ if (routePath === '/api/diagnostician' || routePath.startsWith('/api/diagnostician/')) {
375
+ const subPath = routePath.slice('/api/diagnostician'.length);
376
+ asyncHandler(() => handleDiagnosticianRoute(req, res, { workspaceDir: services.workspaceDir, subPath, featureFlags: services.feedbackFlags }))(req, res);
377
+ return;
378
+ }
364
379
  // Task 9: GET /api/failed-tasks, /api/failed-tasks/:id
365
380
  if (routePath === '/api/failed-tasks' || routePath.startsWith('/api/failed-tasks/')) {
366
381
  const subPath = routePath.slice('/api/failed-tasks'.length);
367
382
  asyncHandler(() => handleFailedTasksRoute(req, res, { workspaceDir: services.workspaceDir, subPath, featureFlags: services.feedbackFlags }))(req, res);
368
383
  return;
369
384
  }
385
+ // 5B-F: GET /api/runtime/compatibility-scan — read-only rule
386
+ // compatibility scan (reason-granular; never the per-row findings).
387
+ if (routePath === '/api/runtime/compatibility-scan') {
388
+ asyncHandler(() => handleCompatibilityScanRoute(req, res, services.workspaceDir))(req, res);
389
+ return;
390
+ }
370
391
  // PRI-533: GET /api/receipts/counts, /api/receipts/principles/:id
371
392
  if (routePath === '/api/receipts' || routePath.startsWith('/api/receipts/')) {
372
393
  const subPath = routePath.slice('/api/receipts'.length);
@@ -1,5 +1,5 @@
1
1
  import type { ActivationStatusRecord, PromotionReadinessResult, ActivationControlState, ActivationDecisionRecord, GlobalRuleCodePause, OwnerPromotionActor, OwnerPromotionResult } from '@principles/core/runtime';
2
- import { type PromptInjectionTargetHost } from '@principles/host-runtime';
2
+ import { collectRuleCodeEventEntries, type PromptInjectionTargetHost } from '@principles/host-runtime';
3
3
  import type { PromptActivationInjectionStatusWire, PromptInjectionRouteSummaryWire } from '../../shared/prompt-injection-contract.js';
4
4
  import { type GovernanceAuditWriter } from 'principles-disciple/governance-audit';
5
5
  import type { ApprovedRuleRevisionRequest } from '../../shared/approved-rule-revision-contract.js';
@@ -133,21 +133,8 @@ export interface OwnerMutationInput {
133
133
  * observation reader so the two readers can never drift).
134
134
  */
135
135
  export declare const RULECODE_EVENT_LOG_CANDIDATE_DIRS: readonly string[];
136
- export interface CollectedRuleCodeEventEntries {
137
- entries: unknown[];
138
- /** Number of candidate directories that actually exist on disk. */
139
- sourceDirsFound: number;
140
- }
141
- /**
142
- * Collect rulehost telemetry entries from all candidate log directories.
143
- * Malformed lines are excluded individually. A directory counts as a source
144
- * only after it can be enumerated, so an unreadable path cannot be mistaken
145
- * for a healthy channel with zero events (ERR-002).
146
- *
147
- * Exact lines copied between candidate directories are deduplicated by
148
- * priority. Different events in same-named daily files are retained.
149
- */
150
- export declare function collectRuleCodeEventEntries(workspaceDir: string): CollectedRuleCodeEventEntries;
136
+ export { collectRuleCodeEventEntries };
137
+ export type { CollectedRuleCodeEventEntries } from '@principles/host-runtime';
151
138
  export declare class ActivationsConsoleModel {
152
139
  private readonly workspaceDir;
153
140
  private readonly governanceAuditWriter;
@@ -205,4 +192,3 @@ export declare class ActivationsConsoleModel {
205
192
  }>;
206
193
  dispose(): void;
207
194
  }
208
- export {};
@@ -1,5 +1,5 @@
1
1
  import { SqliteConnection, SqliteActivationStateStore, SqlitePIArtifactStore, extractPrincipleId, extractEvidenceRefs, PromotionReadinessReader, RuleHostWriter, createProductionGateDeps, SqliteActivationSafetyStore, isFeatureEnabled, RuleCodeOwnerDecisionService, collectOpenClawPromotionChecks, summarizeRuleCodeShadowEvents, buildPromotionEvidenceSnapshot, createRuntimeStateHandle, PrincipleTreeLedgerAdapter, previewApprovedRuleRevision, reviseApprovedRuleOnce, } from '@principles/core/runtime';
2
- import { resolvePromotionHostLiveness, resolveWorkspaceHostToolSemantics, readPromptActivationInjectionStatuses, operatorDeclaredBudgetResolution, runtimeBudgetObservationToResolution, selectConsoleRuntimeBudgetFacts, productionRouteRotationState, RUNTIME_BUDGET_OBSERVATION_STALE_REASON, RUNTIME_EVENT_LOG_CANDIDATE_DIRS } from '@principles/host-runtime';
2
+ import { resolvePromotionHostLiveness, resolveWorkspaceHostToolSemantics, readPromptActivationInjectionStatuses, operatorDeclaredBudgetResolution, runtimeBudgetObservationToResolution, selectConsoleRuntimeBudgetFacts, productionRouteRotationState, RUNTIME_BUDGET_OBSERVATION_STALE_REASON, RUNTIME_EVENT_LOG_CANDIDATE_DIRS, collectRuleCodeEventEntries } from '@principles/host-runtime';
3
3
  import { PROMPT_BUDGET_HOST_KINDS } from '@principles/core/runtime';
4
4
  import { loadPdConfig, computeFlagsFromLoadResult } from '../config/pd-config-store.js';
5
5
  import { errorMessage } from '../utils/response.js';
@@ -70,49 +70,10 @@ function unavailableShadowSummary() {
70
70
  * observation reader so the two readers can never drift).
71
71
  */
72
72
  export const RULECODE_EVENT_LOG_CANDIDATE_DIRS = RUNTIME_EVENT_LOG_CANDIDATE_DIRS;
73
- /**
74
- * Collect rulehost telemetry entries from all candidate log directories.
75
- * Malformed lines are excluded individually. A directory counts as a source
76
- * only after it can be enumerated, so an unreadable path cannot be mistaken
77
- * for a healthy channel with zero events (ERR-002).
78
- *
79
- * Exact lines copied between candidate directories are deduplicated by
80
- * priority. Different events in same-named daily files are retained.
81
- */
82
- export function collectRuleCodeEventEntries(workspaceDir) {
83
- const entries = [];
84
- let sourceDirsFound = 0;
85
- const higherPriorityLines = new Set();
86
- for (const candidate of RULECODE_EVENT_LOG_CANDIDATE_DIRS) {
87
- const logsDir = path.join(workspaceDir, ...candidate.split('/'));
88
- if (!fs.existsSync(logsDir))
89
- continue;
90
- try {
91
- const files = fs.readdirSync(logsDir)
92
- .filter(name => /^events_.*\.jsonl$/.test(name))
93
- .sort()
94
- .slice(-7);
95
- sourceDirsFound += 1;
96
- const currentSourceLines = [];
97
- for (const file of files) {
98
- const lines = fs.readFileSync(path.join(logsDir, file), 'utf8').split('\n').filter(Boolean);
99
- for (const line of lines) {
100
- currentSourceLines.push(line);
101
- if (higherPriorityLines.has(line))
102
- continue;
103
- try {
104
- entries.push(JSON.parse(line));
105
- }
106
- catch { /* exclude malformed telemetry */ }
107
- }
108
- }
109
- for (const line of currentSourceLines)
110
- higherPriorityLines.add(line);
111
- }
112
- catch { /* unreadable directory contributes no entries */ }
113
- }
114
- return { entries, sourceDirsFound };
115
- }
73
+ // 5B: the scan itself lives in host-runtime so the Console Owner review and
74
+ // the CLI promotion path cannot drift. Kept as a re-export because existing
75
+ // tests import it from this module.
76
+ export { collectRuleCodeEventEntries };
116
77
  function readRuleCodeTelemetry(workspaceDir, activationId, options) {
117
78
  const { decisions } = options;
118
79
  const countCircuitTrips = (minimumTime) => decisions.filter(decision => decision.decision === 'safety_isolate' && Date.parse(decision.decidedAt) >= minimumTime).length;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * 5B-F — GET /api/runtime/compatibility-scan (read-only).
3
+ *
4
+ * Surfaces the SAME scan the installer preflight and `pd runtime
5
+ * compatibility-scan` use, reduced to reason-granular counts + samples (see
6
+ * `shared/compatibility-scan-contract.ts`). The scanner already holds the
7
+ * workspace DB connection semantics (`readonly`), so this route adds no
8
+ * runtime dependency — it reuses @principles/core/runtime in process.
9
+ *
10
+ * No mutation: the handler only constructs the read model and maps its result.
11
+ */
12
+ import type { IncomingMessage, ServerResponse } from 'node:http';
13
+ import type { ActivationCompatibilityScanResult } from '@principles/core/runtime';
14
+ import type { CompatibilityScanViewData } from '../../shared/compatibility-scan-contract.js';
15
+ /** Injectable seam so the route mapping is testable without seeding SQLite. */
16
+ export type CompatibilityScanner = (workspaceDir: string) => ActivationCompatibilityScanResult;
17
+ export declare function toCompatibilityScanView(result: ActivationCompatibilityScanResult): CompatibilityScanViewData;
18
+ export declare function handleCompatibilityScanRoute(req: IncomingMessage, res: ServerResponse, workspaceDir: string, scan?: CompatibilityScanner): Promise<void>;
@@ -0,0 +1,33 @@
1
+ import { ActivationCompatibilityReadModel } from '@principles/core/runtime';
2
+ import { sendSuccess, sendError, sendMethodNotAllowed, errorMessage } from '../utils/response.js';
3
+ const defaultScanner = workspaceDir => new ActivationCompatibilityReadModel({ workspaceDir }).scan();
4
+ export function toCompatibilityScanView(result) {
5
+ return {
6
+ status: result.status,
7
+ scannedActivations: result.scannedActivations,
8
+ unscannable: result.skipped.map(({ reason, count, sampleActivationIds }) => ({
9
+ reason,
10
+ count,
11
+ sampleActivationIds: [...sampleActivationIds],
12
+ })),
13
+ findingsTotal: result.findings.length,
14
+ ...(result.reason !== undefined ? { reason: result.reason } : {}),
15
+ ...(result.nextAction !== undefined ? { nextAction: result.nextAction } : {}),
16
+ };
17
+ }
18
+ /* eslint-disable @typescript-eslint/max-params */
19
+ export async function handleCompatibilityScanRoute(req, res, workspaceDir, scan = defaultScanner) {
20
+ if (req.method !== 'GET') {
21
+ sendMethodNotAllowed(res);
22
+ return;
23
+ }
24
+ try {
25
+ sendSuccess(res, toCompatibilityScanView(scan(workspaceDir)));
26
+ }
27
+ catch (error) {
28
+ // rc-9: a scan that throws is observable, not an empty list.
29
+ sendError(res, 500, 'compatibility_scan_failed', errorMessage(error), {
30
+ reason: 'compatibility_scan_failed',
31
+ });
32
+ }
33
+ }
@@ -0,0 +1,50 @@
1
+ import type { IncomingMessage, ServerResponse } from 'http';
2
+ export interface DiagnosticianPreflightVerdict {
3
+ ok: boolean;
4
+ reason?: string;
5
+ message?: string;
6
+ nextAction?: string;
7
+ }
8
+ export type DiagnosticianPreflightOutcome = DiagnosticianPreflightVerdict | 'timeout';
9
+ export interface DiagnosticianSpawnOutcome {
10
+ outcome: 'spawned' | 'failed' | 'unconfirmed';
11
+ message?: string;
12
+ }
13
+ /** The two external effects of L2, injectable so tests never launch Node. */
14
+ export interface DiagnosticianRuntime {
15
+ preflight(input: {
16
+ taskId: string;
17
+ workspaceDir: string;
18
+ }): Promise<DiagnosticianPreflightOutcome>;
19
+ spawnRun(input: {
20
+ taskId: string;
21
+ workspaceDir: string;
22
+ }): Promise<DiagnosticianSpawnOutcome>;
23
+ }
24
+ export interface DiagnosticianRuntimeOptions {
25
+ /** Absolute pd-cli dist/index.js entry. Defaults to installed-layout + dev fallback. */
26
+ pdCliEntry?: string;
27
+ preflightTimeoutMs?: number;
28
+ spawnConfirmTimeoutMs?: number;
29
+ }
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 declare function resolvePdCliInvocation(): {
35
+ rootDir: string;
36
+ entryPath: string;
37
+ };
38
+ export declare function createDiagnosticianRuntime(opts?: DiagnosticianRuntimeOptions): DiagnosticianRuntime;
39
+ export interface DiagnosticianRouteDeps {
40
+ workspaceDir: string;
41
+ subPath: string;
42
+ /** Console feature flags; `openclaw_diagnostician_consumer` defaults on. */
43
+ featureFlags?: Record<string, {
44
+ enabled: boolean;
45
+ }>;
46
+ /** Defaults to the real subprocess runtime. */
47
+ runtime?: DiagnosticianRuntime;
48
+ now?: () => Date;
49
+ }
50
+ export declare function handleDiagnosticianRoute(req: IncomingMessage, res: ServerResponse, deps: DiagnosticianRouteDeps): Promise<void>;