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,65 @@
1
+ import { resolveCodexHome } from './codex-home.js';
2
+ import { validateCodexTranscriptPath } from './transcript-path.js';
3
+ import { classifyCodexVersion, CODEX_VERSION_NEXT_ACTION } from './codex-version.js';
4
+ import { decodeTranscriptWindow } from './transcript-decoder.js';
5
+ export function createCodexTranscriptSource(context) {
6
+ return {
7
+ hostKind: 'codex',
8
+ locate(_session, hints) {
9
+ const home = resolveCodexHome(context.env);
10
+ if (!home.ok)
11
+ return { status: 'degraded', reason: home.reason, nextAction: home.nextAction };
12
+ if (typeof hints.transcriptPath !== 'string' || hints.transcriptPath.length === 0) {
13
+ // SPEC §9: never scan for another file; keep a neutral degraded result.
14
+ return { status: 'degraded', reason: 'transcript_unavailable', nextAction: 'Codex supplied no transcript for this event; nothing is read or fabricated.' };
15
+ }
16
+ const validated = validateCodexTranscriptPath(hints.transcriptPath, home.home);
17
+ if (!validated.ok)
18
+ return { status: 'degraded', reason: validated.reason, nextAction: validated.nextAction };
19
+ return {
20
+ status: 'ok',
21
+ filePath: validated.canonicalPath,
22
+ expectedIdentity: validated.identity,
23
+ sessionIdentity: validated.rolloutIdentity,
24
+ };
25
+ },
26
+ decodeWindow(locator, window, checkpoint) {
27
+ const decoded = decodeTranscriptWindow({
28
+ bytes: window.bytes,
29
+ fileOffset: window.fileOffset,
30
+ byteBoundReached: window.byteBoundReached,
31
+ rolloutIdentity: locator.sessionIdentity,
32
+ fallbackRootSessionId: checkpoint !== null ? checkpoint.rootSessionId : context.fallbackRootSessionId,
33
+ nowIso: context.now.toISOString(),
34
+ });
35
+ // Supported-version guard (SPEC §9): the version signal lives in the
36
+ // transcript session_meta (or the committed checkpoint after the first
37
+ // batch). Anything below the verified floor or above the verified
38
+ // ceiling refuses the delta — never guess record fields of an unknown
39
+ // contract.
40
+ const cliVersion = decoded.rolloutMeta.cliVersion ?? checkpoint?.cliVersion ?? null;
41
+ const version = classifyCodexVersion(cliVersion);
42
+ const guard = version.status === 'supported'
43
+ ? null
44
+ : { reason: `${version.reason}:${cliVersion ?? 'unknown'}`, nextAction: CODEX_VERSION_NEXT_ACTION };
45
+ return {
46
+ observations: decoded.observations,
47
+ rollout: {
48
+ rootSessionId: decoded.rolloutMeta.rootSessionId ?? checkpoint?.rootSessionId ?? context.fallbackRootSessionId,
49
+ ...(cliVersion !== null ? { cliVersion } : {}),
50
+ ...(decoded.rolloutMeta.parentRolloutIdentity !== null ? { parentRolloutIdentity: decoded.rolloutMeta.parentRolloutIdentity } : {}),
51
+ ...(decoded.rolloutMeta.agentIdentity !== null ? { agentIdentity: decoded.rolloutMeta.agentIdentity } : {}),
52
+ ...(decoded.rolloutMeta.agentDepth !== null ? { agentDepth: decoded.rolloutMeta.agentDepth } : {}),
53
+ },
54
+ guard,
55
+ compactionTimestamp: decoded.compactionTimestamp,
56
+ rollbackTurns: decoded.rollbackTurns,
57
+ stop: decoded.stop,
58
+ nextByteOffset: decoded.nextByteOffset,
59
+ lastOrdinal: decoded.lastOrdinal,
60
+ warnings: decoded.warnings,
61
+ fileSize: window.fileSize,
62
+ };
63
+ },
64
+ };
65
+ }
@@ -11,5 +11,31 @@ 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
+ * PRI-1181: remaining-budget floor for the pre-selection skip gate. Defaults
36
+ * to the measured minimum; 0 keeps a cancellation scenario sending.
37
+ */
38
+ readonly minRemainingBudgetMs?: number;
39
+ }
40
+ export declare function processHookInvocation(rawStdin: string, _env?: EnvMap, cwd?: string, deps?: PdHookDeps): Promise<PdHookResult>;
15
41
  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,25 @@ 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
+ // PRI-1181: a deterministic pre-selection skip is normal behaviour (zero
34
+ // reads, zero sends) — it must not be reported as a degraded selection.
35
+ const status = line.status === 'selected'
36
+ ? 'adaptive'
37
+ : line.status === 'skipped'
38
+ ? 'skipped'
39
+ : 'degraded';
40
+ const failures = line.failures.length > 0 ? line.failures.join('|') : 'none';
41
+ 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}`
42
+ .replace(/\s+/g, ' ')
43
+ .trim()
44
+ .slice(0, MAX_DIAGNOSTIC * 2);
45
+ }
27
46
  function redactStringFields(data) {
28
47
  // rc-8: telemetry is redacted string-field by string field (same policy as
29
48
  // the OpenClaw EventLog redactEventData) — shared by every emitter here.
@@ -191,7 +210,25 @@ async function runConversationIngestion(args) {
191
210
  }
192
211
  return diagnostics;
193
212
  }
194
- export async function processHookInvocation(rawStdin, _env = process.env, cwd = process.cwd()) {
213
+ /**
214
+ * The host hook window is declared by the plugin manifest
215
+ * (`plugins/principles-disciple/hooks/hooks.json`, `UserPromptSubmit.timeout`,
216
+ * in seconds). Codex owns that timer and terminates the hook process when it
217
+ * fires; PD gets no in-band notification, so Adaptive must end BEFORE the
218
+ * window and leave the remainder to emit the Native body.
219
+ * `pd-hook-adaptive.test.ts` guards this constant against the manifest.
220
+ */
221
+ export const CODEX_HOOK_TIMEOUT_MS = 5_000;
222
+ /** Reserved for Native packing, encoding and stdout after Adaptive is cut off. */
223
+ export const CODEX_NATIVE_RESERVE_MS = 800;
224
+ export const CODEX_ADAPTIVE_BUDGET_MS = CODEX_HOOK_TIMEOUT_MS - CODEX_NATIVE_RESERVE_MS;
225
+ // stdin, env and cwd are the host CLI contract; `deps` is the optional transport
226
+ // seam that lets integration tests drive the real entry point without a network.
227
+ // eslint-disable-next-line @typescript-eslint/max-params
228
+ export async function processHookInvocation(rawStdin, _env = process.env, cwd = process.cwd(), deps = {}) {
229
+ // The host owns this window and kills the process when it expires; anchor at
230
+ // entry so decode/ingestion time counts against the same budget.
231
+ const adaptiveDeadlineAt = Date.now() + (deps.hookBudgetMs ?? CODEX_ADAPTIVE_BUDGET_MS);
195
232
  let parsed;
196
233
  try {
197
234
  parsed = JSON.parse(rawStdin);
@@ -385,17 +422,56 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
385
422
  // event-JSONL writer (same events_*.jsonl format as the OpenClaw EventLog;
386
423
  // the Codex adapter stays independent of the OpenClaw plugin). The line
387
424
  // writer appends synchronously — no flush/dispose needed for the subprocess.
425
+ // PRI-1170: Adaptive Activation is an INDEPENDENT, default-off switch on
426
+ // top of the PD hook. `host.codex.enabled` remains the whole-hook gate.
427
+ const adaptiveDiagnostics = [];
428
+ let adaptivePriorityProvider;
429
+ if (event.kind === 'before_prompt_build' && flags['host.codex.adaptive_activation']?.enabled === true) {
430
+ const adaptive = createAdaptivePriorityProviderForConfig(config.effective.config, resolution.workspaceDir, {
431
+ env: _env,
432
+ ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),
433
+ ...(deps.now ? { now: deps.now } : {}),
434
+ ...(deps.firstByteTimeoutMs !== undefined ? { firstByteTimeoutMs: deps.firstByteTimeoutMs } : {}),
435
+ ...(deps.generationTimeoutMs !== undefined ? { generationTimeoutMs: deps.generationTimeoutMs } : {}),
436
+ ...(deps.minRemainingBudgetMs !== undefined ? { minRemainingBudgetMs: deps.minRemainingBudgetMs } : {}),
437
+ outerDeadlineAt: adaptiveDeadlineAt,
438
+ onDiagnostic: (line) => { adaptiveDiagnostics.push(adaptiveSelectionDiagnostic(line)); },
439
+ });
440
+ if (adaptive.ok) {
441
+ adaptivePriorityProvider = adaptive.provider;
442
+ }
443
+ else {
444
+ // rc-9: an enabled-but-unusable switch is observable, never silent.
445
+ adaptiveDiagnostics.push(diagnostic(`adaptive_activation_${adaptive.readiness}:${adaptive.reason}`, adaptive.nextAction));
446
+ }
447
+ }
448
+ // B3: resolve tool semantics from the workspace declarations — the SAME
449
+ // source replay / evidence / Console read — with the compiled-in Codex
450
+ // declaration as the fallback. A malformed declaration degrades
451
+ // observably on stderr instead of blocking the tool call (rc-9).
452
+ const toolSemanticsResolution = resolveHostToolSemanticsForHook({
453
+ workspaceDir: resolution.workspaceDir,
454
+ hostKind: 'codex',
455
+ staticMappings: CODEX_TOOL_SEMANTIC_MAPPINGS,
456
+ });
457
+ const toolSemantics = toolSemanticsResolution.ok
458
+ ? toolSemanticsResolution.registry
459
+ : CODEX_TOOL_SEMANTICS;
460
+ const toolSemanticsDiagnostics = toolSemanticsResolution.ok
461
+ ? []
462
+ : [diagnostic(toolSemanticsResolution.reason, toolSemanticsResolution.nextAction)];
388
463
  const result = await createProductionHostRuntime({
389
464
  projectDir: requestedCwd,
390
465
  hostKind: 'codex',
391
- toolSemantics: CODEX_TOOL_SEMANTICS,
466
+ toolSemantics,
467
+ ...(adaptivePriorityProvider ? { adaptivePriorityProvider } : {}),
392
468
  ruleContextProvider: createCodexRuleContextProvider({
393
469
  workspaceDir: resolution.workspaceDir,
394
470
  projectDir: requestedCwd,
395
471
  enabled: flags.rulecode_context_v2?.enabled === true && ingestionEnabled,
396
472
  cutoffAt: hookEpoch,
397
473
  currentToolUseId: event.context.toolCallId ?? '',
398
- toolSemantics: CODEX_TOOL_SEMANTICS,
474
+ toolSemantics,
399
475
  }),
400
476
  events: codexEventEmitter(path.join(resolution.workspaceDir, '.state'), evidenceContext),
401
477
  }).dispatch(event);
@@ -463,7 +539,7 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
463
539
  evidenceDiagnostics.push(diagnostic(`codex_evidence_deny_failed:${errorMessage(error)}`, 'The deny decision was already encoded; evidence replay from the durable source is safe.'));
464
540
  }
465
541
  }
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];
542
+ 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
543
  return { stdout: encoded, exitCode: 0, stderr };
468
544
  }
469
545
  catch (error) {
@@ -545,7 +621,12 @@ async function main() {
545
621
  }
546
622
  let result;
547
623
  try {
548
- result = await processHookInvocation(raw);
624
+ // The host's 5 s window starts at process spawn, not at this call: node
625
+ // boot and module loading already consumed part of it. Anchor the deadline
626
+ // at process start so the measured reserve really reaches Native.
627
+ const elapsedSinceProcessStartMs = Math.round(process.uptime() * 1000);
628
+ const remainingBudgetMs = Math.max(1, CODEX_ADAPTIVE_BUDGET_MS - elapsedSinceProcessStartMs);
629
+ result = await processHookInvocation(raw, process.env, process.cwd(), { hookBudgetMs: remainingBudgetMs });
549
630
  }
550
631
  catch (error) {
551
632
  // 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.8",
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';
@@ -253,12 +254,17 @@ export async function initServices(workspaceDir, authConfig) {
253
254
  // Governance Experience Snapshot v1.5.1 (PRI-584~587): default off; flag-off
254
255
  // keeps the legacy Focus experience and 403s the endpoint before any DB access.
255
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;
256
261
  const feedbackFlags = {
257
262
  feedback_channel: { enabled: feedbackChannelEnabled },
258
263
  failed_tasks_observability: { enabled: failedTasksObservabilityEnabled },
259
264
  principle_governance_projection_v2: { enabled: governanceProjectionEnabled },
260
265
  failed_task_recovery_console: { enabled: failedTaskRecoveryEnabled },
261
266
  governance_experience_v1: { enabled: governanceExperienceEnabled },
267
+ openclaw_diagnostician_consumer: { enabled: openclawDiagnosticianConsumerEnabled },
262
268
  };
263
269
  if (!configResult.ok) {
264
270
  console.warn('[pd-console] PD config loading failed (using defaults for feedback channel):', configResult.errors.map(e => e.reason).join('; '));
@@ -362,6 +368,14 @@ export function handleRequest(services) {
362
368
  asyncHandler(() => handleFeedbackReportsRoute(req, res, { workspaceDir: services.workspaceDir, subPath, featureFlags: services.feedbackFlags, maintainerEmail: services.maintainerEmail, channelConfig: services.feedbackChannelConfig }))(req, res);
363
369
  return;
364
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
+ }
365
379
  // Task 9: GET /api/failed-tasks, /api/failed-tasks/:id
366
380
  if (routePath === '/api/failed-tasks' || routePath.startsWith('/api/failed-tasks/')) {
367
381
  const subPath = routePath.slice('/api/failed-tasks'.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,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>;