create-principles-disciple 1.153.3 → 1.154.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (298) hide show
  1. package/_release/product-identity.json +1 -1
  2. package/codex-adapter/dist/ingestion/codex-home.d.ts +1 -0
  3. package/codex-adapter/dist/ingestion/codex-home.js +19 -7
  4. package/codex-adapter/dist/ingestion/ingestion.js +34 -7
  5. package/codex-adapter/dist/pd-hook.js +14 -6
  6. package/codex-adapter/dist/worker/workspace-worker.js +31 -1
  7. package/codex-adapter/package.json +1 -1
  8. package/console/dist/server/index.js +5 -16
  9. package/console/dist/server/utils/installed-layout.js +6 -4
  10. package/console/dist/server/utils/pd-backups.d.ts +1 -14
  11. package/console/dist/server/utils/pd-backups.js +12 -64
  12. package/console/dist/web/assets/app.css +153 -9
  13. package/console/dist/web/assets/app.js +41 -37
  14. package/console/dist/web/assets/intent-reflection.webp +3 -0
  15. package/console/dist/web/assets/providers/anthropic.png +0 -0
  16. package/console/dist/web/assets/providers/deepseek.png +0 -0
  17. package/console/dist/web/assets/providers/google.png +0 -0
  18. package/console/dist/web/assets/providers/groq.svg +1 -0
  19. package/console/dist/web/assets/providers/kimi.png +0 -0
  20. package/console/dist/web/assets/providers/minimax.png +0 -0
  21. package/console/dist/web/assets/providers/mistral.svg +28 -0
  22. package/console/dist/web/assets/providers/nvidia.png +0 -0
  23. package/console/dist/web/assets/providers/openai.svg +1 -0
  24. package/console/dist/web/assets/providers/openrouter.svg +3 -0
  25. package/console/dist/web/assets/providers/qwen.png +0 -0
  26. package/console/dist/web/assets/providers/together.svg +21 -0
  27. package/console/dist/web/assets/providers/xai.svg +1 -0
  28. package/console/dist/web/assets/providers/xiaomi.png +0 -0
  29. package/console/dist/web/assets/providers/zai.svg +219 -0
  30. package/core/dist/index.d.ts +1 -2
  31. package/core/dist/index.d.ts.map +1 -1
  32. package/core/dist/index.js +4 -2
  33. package/core/dist/index.js.map +1 -1
  34. package/core/dist/prompt-builder/focus-compression.d.ts +8 -60
  35. package/core/dist/prompt-builder/focus-compression.d.ts.map +1 -1
  36. package/core/dist/prompt-builder/focus-compression.js +8 -434
  37. package/core/dist/prompt-builder/focus-compression.js.map +1 -1
  38. package/core/dist/prompt-builder/index.d.ts +1 -2
  39. package/core/dist/prompt-builder/index.d.ts.map +1 -1
  40. package/core/dist/prompt-builder/index.js +3 -2
  41. package/core/dist/prompt-builder/index.js.map +1 -1
  42. package/core/dist/runtime/activation/production-gate-deps.d.ts +7 -3
  43. package/core/dist/runtime/activation/production-gate-deps.d.ts.map +1 -1
  44. package/core/dist/runtime/activation/production-gate-deps.js +15 -6
  45. package/core/dist/runtime/activation/production-gate-deps.js.map +1 -1
  46. package/core/dist/runtime/adapter/principle-tree-ledger-adapter.d.ts +2 -0
  47. package/core/dist/runtime/adapter/principle-tree-ledger-adapter.d.ts.map +1 -1
  48. package/core/dist/runtime/adapter/principle-tree-ledger-adapter.js +9 -1
  49. package/core/dist/runtime/adapter/principle-tree-ledger-adapter.js.map +1 -1
  50. package/core/dist/runtime/config/pd-config-types.d.ts +20 -1
  51. package/core/dist/runtime/config/pd-config-types.d.ts.map +1 -1
  52. package/core/dist/runtime/config/pd-config-types.js.map +1 -1
  53. package/core/dist/runtime/config/pd-config-validate.d.ts.map +1 -1
  54. package/core/dist/runtime/config/pd-config-validate.js +12 -1
  55. package/core/dist/runtime/config/pd-config-validate.js.map +1 -1
  56. package/core/dist/runtime/internalization/bash-risk.d.ts.map +1 -1
  57. package/core/dist/runtime/internalization/bash-risk.js +6 -3
  58. package/core/dist/runtime/internalization/bash-risk.js.map +1 -1
  59. package/core/dist/runtime/internalization/internalization-orchestrator.d.ts +28 -1
  60. package/core/dist/runtime/internalization/internalization-orchestrator.d.ts.map +1 -1
  61. package/core/dist/runtime/internalization/internalization-orchestrator.js +109 -13
  62. package/core/dist/runtime/internalization/internalization-orchestrator.js.map +1 -1
  63. package/core/dist/runtime/internalization/split-diagnostician-runner.d.ts +10 -0
  64. package/core/dist/runtime/internalization/split-diagnostician-runner.d.ts.map +1 -1
  65. package/core/dist/runtime/internalization/split-diagnostician-runner.js +6 -1
  66. package/core/dist/runtime/internalization/split-diagnostician-runner.js.map +1 -1
  67. package/core/dist/runtime/pain-chain-read-model.d.ts +14 -0
  68. package/core/dist/runtime/pain-chain-read-model.d.ts.map +1 -1
  69. package/core/dist/runtime/pain-chain-read-model.js +91 -3
  70. package/core/dist/runtime/pain-chain-read-model.js.map +1 -1
  71. package/core/dist/runtime/pain-ingress-payload.d.ts +15 -0
  72. package/core/dist/runtime/pain-ingress-payload.d.ts.map +1 -1
  73. package/core/dist/runtime/pain-ingress-payload.js +32 -3
  74. package/core/dist/runtime/pain-ingress-payload.js.map +1 -1
  75. package/core/dist/runtime/pain-signal-bridge.d.ts +8 -0
  76. package/core/dist/runtime/pain-signal-bridge.d.ts.map +1 -1
  77. package/core/dist/runtime/pain-signal-bridge.js +11 -0
  78. package/core/dist/runtime/pain-signal-bridge.js.map +1 -1
  79. package/core/dist/runtime/pain-signal-runtime-factory.d.ts.map +1 -1
  80. package/core/dist/runtime/pain-signal-runtime-factory.js +3 -0
  81. package/core/dist/runtime/pain-signal-runtime-factory.js.map +1 -1
  82. package/core/dist/runtime/pain-submit-capability.d.ts +54 -0
  83. package/core/dist/runtime/pain-submit-capability.d.ts.map +1 -1
  84. package/core/dist/runtime/pain-submit-capability.js +49 -1
  85. package/core/dist/runtime/pain-submit-capability.js.map +1 -1
  86. package/core/dist/runtime/storage-paths.d.ts +9 -10
  87. package/core/dist/runtime/storage-paths.d.ts.map +1 -1
  88. package/core/dist/runtime/storage-paths.js +9 -10
  89. package/core/dist/runtime/storage-paths.js.map +1 -1
  90. package/core/dist/runtime/store/context/sqlite-context-assembler.d.ts.map +1 -1
  91. package/core/dist/runtime/store/context/sqlite-context-assembler.js +10 -2
  92. package/core/dist/runtime/store/context/sqlite-context-assembler.js.map +1 -1
  93. package/core/dist/runtime/store/storage-paths.d.ts +65 -12
  94. package/core/dist/runtime/store/storage-paths.d.ts.map +1 -1
  95. package/core/dist/runtime/store/storage-paths.js +92 -39
  96. package/core/dist/runtime/store/storage-paths.js.map +1 -1
  97. package/core/package.json +1 -1
  98. package/dist/index.d.ts.map +1 -1
  99. package/dist/index.js +6 -0
  100. package/dist/index.js.map +1 -1
  101. package/dist/installer.d.ts +137 -9
  102. package/dist/installer.d.ts.map +1 -1
  103. package/dist/installer.js +627 -100
  104. package/dist/installer.js.map +1 -1
  105. package/dist/installers/codex-host-installer.d.ts +23 -3
  106. package/dist/installers/codex-host-installer.d.ts.map +1 -1
  107. package/dist/installers/codex-host-installer.js +36 -20
  108. package/dist/installers/codex-host-installer.js.map +1 -1
  109. package/dist/installers/index.d.ts.map +1 -1
  110. package/dist/installers/index.js +24 -3
  111. package/dist/installers/index.js.map +1 -1
  112. package/dist/installers/mcp-registration-conflict.d.ts.map +1 -1
  113. package/dist/installers/mcp-registration-conflict.js +23 -16
  114. package/dist/installers/mcp-registration-conflict.js.map +1 -1
  115. package/dist/installers/openclaw-host-installer.d.ts.map +1 -1
  116. package/dist/installers/openclaw-host-installer.js +1 -8
  117. package/dist/installers/openclaw-host-installer.js.map +1 -1
  118. package/dist/installers/workbuddy-host-installer.d.ts.map +1 -1
  119. package/dist/installers/workbuddy-host-installer.js +51 -15
  120. package/dist/installers/workbuddy-host-installer.js.map +1 -1
  121. package/dist/mvp-config.d.ts +30 -5
  122. package/dist/mvp-config.d.ts.map +1 -1
  123. package/dist/mvp-config.js +49 -16
  124. package/dist/mvp-config.js.map +1 -1
  125. package/dist/prompts.js +1 -1
  126. package/dist/prompts.js.map +1 -1
  127. package/dist/uninstaller.d.ts.map +1 -1
  128. package/dist/uninstaller.js +142 -5
  129. package/dist/uninstaller.js.map +1 -1
  130. package/dist/update/release-manager.d.ts.map +1 -1
  131. package/dist/update/release-manager.js +5 -2
  132. package/dist/update/release-manager.js.map +1 -1
  133. package/dist/utils/env.d.ts +5 -10
  134. package/dist/utils/env.d.ts.map +1 -1
  135. package/dist/utils/env.js +91 -34
  136. package/dist/utils/env.js.map +1 -1
  137. package/dist/utils/host-workspace-ownership.d.ts +25 -0
  138. package/dist/utils/host-workspace-ownership.d.ts.map +1 -1
  139. package/dist/utils/host-workspace-ownership.js +153 -2
  140. package/dist/utils/host-workspace-ownership.js.map +1 -1
  141. package/host-runtime/dist/adaptive-background-append.d.ts +6 -0
  142. package/host-runtime/dist/adaptive-background-append.js +4 -1
  143. package/host-runtime/dist/adaptive-decision-protocol.d.ts +18 -2
  144. package/host-runtime/dist/adaptive-decision-protocol.js +39 -9
  145. package/host-runtime/dist/adaptive-principle-context-reader.d.ts +79 -0
  146. package/host-runtime/dist/adaptive-principle-context-reader.js +303 -0
  147. package/host-runtime/dist/adaptive-priority-provider.d.ts +33 -0
  148. package/host-runtime/dist/adaptive-priority-provider.js +68 -2
  149. package/host-runtime/dist/adaptive-selection.d.ts +16 -0
  150. package/host-runtime/dist/adaptive-selection.js +23 -1
  151. package/host-runtime/dist/codex-legacy-registration.js +10 -2
  152. package/host-runtime/dist/conversation-ingestion/pipeline.d.ts +8 -0
  153. package/host-runtime/dist/conversation-ingestion/pipeline.js +179 -7
  154. package/host-runtime/dist/degraded-enforcement-marker.js +16 -2
  155. package/host-runtime/dist/diagnostician-auto-run.js +4 -0
  156. package/host-runtime/dist/governance-observation-store.d.ts +44 -0
  157. package/host-runtime/dist/governance-observation-store.js +84 -1
  158. package/host-runtime/dist/governance-trajectory-turn-reader.d.ts +30 -0
  159. package/host-runtime/dist/governance-trajectory-turn-reader.js +47 -0
  160. package/host-runtime/dist/index.d.ts +2 -0
  161. package/host-runtime/dist/index.js +6 -0
  162. package/host-runtime/dist/product-telemetry/service.js +86 -20
  163. package/host-runtime/package.json +1 -1
  164. package/install-layout/dist/index.d.ts +23 -9
  165. package/install-layout/dist/index.js +49 -24
  166. package/install-layout/dist/mcp-binding-contract.d.ts +62 -0
  167. package/install-layout/dist/mcp-binding-contract.js +175 -3
  168. package/install-layout/dist/pd-home.d.ts +35 -5
  169. package/install-layout/dist/pd-home.js +138 -23
  170. package/install-layout/package.json +1 -1
  171. package/package.json +4 -4
  172. package/pd-cli/dist/commands/candidate.d.ts.map +1 -1
  173. package/pd-cli/dist/commands/candidate.js +134 -8
  174. package/pd-cli/dist/commands/candidate.js.map +1 -1
  175. package/pd-cli/dist/commands/codex-worker.d.ts.map +1 -1
  176. package/pd-cli/dist/commands/codex-worker.js +36 -2
  177. package/pd-cli/dist/commands/codex-worker.js.map +1 -1
  178. package/pd-cli/dist/commands/diagnose.d.ts.map +1 -1
  179. package/pd-cli/dist/commands/diagnose.js +34 -8
  180. package/pd-cli/dist/commands/diagnose.js.map +1 -1
  181. package/pd-cli/dist/commands/health-codex-install.d.ts +1 -3
  182. package/pd-cli/dist/commands/health-codex-install.d.ts.map +1 -1
  183. package/pd-cli/dist/commands/health-codex-install.js +19 -6
  184. package/pd-cli/dist/commands/health-codex-install.js.map +1 -1
  185. package/pd-cli/dist/commands/health-codex.d.ts.map +1 -1
  186. package/pd-cli/dist/commands/health-codex.js +27 -9
  187. package/pd-cli/dist/commands/health-codex.js.map +1 -1
  188. package/pd-cli/dist/commands/health-console.d.ts +2 -1
  189. package/pd-cli/dist/commands/health-console.d.ts.map +1 -1
  190. package/pd-cli/dist/commands/health-console.js +12 -3
  191. package/pd-cli/dist/commands/health-console.js.map +1 -1
  192. package/pd-cli/dist/commands/health-ingestion.d.ts +10 -2
  193. package/pd-cli/dist/commands/health-ingestion.d.ts.map +1 -1
  194. package/pd-cli/dist/commands/health-ingestion.js +56 -14
  195. package/pd-cli/dist/commands/health-ingestion.js.map +1 -1
  196. package/pd-cli/dist/commands/health-mcp.d.ts +19 -7
  197. package/pd-cli/dist/commands/health-mcp.d.ts.map +1 -1
  198. package/pd-cli/dist/commands/health-mcp.js +131 -45
  199. package/pd-cli/dist/commands/health-mcp.js.map +1 -1
  200. package/pd-cli/dist/commands/health-workbuddy.d.ts +2 -1
  201. package/pd-cli/dist/commands/health-workbuddy.d.ts.map +1 -1
  202. package/pd-cli/dist/commands/health-workbuddy.js +17 -8
  203. package/pd-cli/dist/commands/health-workbuddy.js.map +1 -1
  204. package/pd-cli/dist/commands/health.d.ts.map +1 -1
  205. package/pd-cli/dist/commands/health.js +12 -5
  206. package/pd-cli/dist/commands/health.js.map +1 -1
  207. package/pd-cli/dist/commands/mcp-probe.d.ts +6 -0
  208. package/pd-cli/dist/commands/mcp-probe.d.ts.map +1 -1
  209. package/pd-cli/dist/commands/mcp-probe.js +35 -7
  210. package/pd-cli/dist/commands/mcp-probe.js.map +1 -1
  211. package/pd-cli/dist/commands/pain-retry.d.ts.map +1 -1
  212. package/pd-cli/dist/commands/pain-retry.js +10 -2
  213. package/pd-cli/dist/commands/pain-retry.js.map +1 -1
  214. package/pd-cli/dist/commands/trace.d.ts.map +1 -1
  215. package/pd-cli/dist/commands/trace.js +8 -0
  216. package/pd-cli/dist/commands/trace.js.map +1 -1
  217. package/pd-cli/dist/commands/workbuddy-setup.d.ts.map +1 -1
  218. package/pd-cli/dist/commands/workbuddy-setup.js +7 -3
  219. package/pd-cli/dist/commands/workbuddy-setup.js.map +1 -1
  220. package/pd-cli/dist/commands/workbuddy-worker.d.ts.map +1 -1
  221. package/pd-cli/dist/commands/workbuddy-worker.js +21 -6
  222. package/pd-cli/dist/commands/workbuddy-worker.js.map +1 -1
  223. package/pd-cli/dist/services/admission-write-gate.d.ts +10 -1
  224. package/pd-cli/dist/services/admission-write-gate.d.ts.map +1 -1
  225. package/pd-cli/dist/services/admission-write-gate.js +12 -2
  226. package/pd-cli/dist/services/admission-write-gate.js.map +1 -1
  227. package/pd-cli/dist/services/codex-plugin-install.d.ts +1 -3
  228. package/pd-cli/dist/services/codex-plugin-install.d.ts.map +1 -1
  229. package/pd-cli/dist/services/codex-plugin-install.js +10 -3
  230. package/pd-cli/dist/services/codex-plugin-install.js.map +1 -1
  231. package/pd-cli/dist/services/pain-flood-simulation-runner.d.ts.map +1 -1
  232. package/pd-cli/dist/services/pain-flood-simulation-runner.js +2 -0
  233. package/pd-cli/dist/services/pain-flood-simulation-runner.js.map +1 -1
  234. package/pd-cli/dist/services/pd-config-loader.d.ts +2 -2
  235. package/pd-cli/dist/services/pd-config-loader.d.ts.map +1 -1
  236. package/pd-cli/dist/services/pd-config-loader.js +28 -20
  237. package/pd-cli/dist/services/pd-config-loader.js.map +1 -1
  238. package/pd-cli/dist/services/synthetic-baseline-runner.d.ts.map +1 -1
  239. package/pd-cli/dist/services/synthetic-baseline-runner.js +2 -0
  240. package/pd-cli/dist/services/synthetic-baseline-runner.js.map +1 -1
  241. package/pd-cli/package.json +1 -1
  242. package/pd-mcp-server/dist/log-file.js +9 -2
  243. package/pd-mcp-server/dist/server.d.ts +52 -2
  244. package/pd-mcp-server/dist/server.js +40 -4
  245. package/pd-mcp-server/dist/submit-assembly.js +85 -12
  246. package/pd-mcp-server/dist/version.d.ts +1 -1
  247. package/pd-mcp-server/dist/version.js +1 -1
  248. package/pd-mcp-server/package.json +1 -1
  249. package/plugin/dist/bundle.js +761 -722
  250. package/plugin/dist/commands/focus.d.ts +10 -7
  251. package/plugin/dist/commands/strategy.d.ts +10 -0
  252. package/plugin/dist/core/focus-history.d.ts +9 -49
  253. package/plugin/dist/core/paths.d.ts +6 -53
  254. package/plugin/dist/governance-audit.js +2 -2
  255. package/plugin/dist/hooks/prompt-helpers.d.ts +6 -5
  256. package/plugin/dist/hooks/prompt-types.d.ts +6 -6
  257. package/plugin/dist/openclaw.plugin.json +1 -1
  258. package/plugin/dist/rulehost-evidence.js +29 -29
  259. package/plugin/dist/templates/workspace/okr/RECOVERY_PROTOCOL.md +8 -7
  260. package/plugin/dist/utils/io.d.ts +1 -1
  261. package/plugin/dist/utils/workspace-resolver.d.ts +0 -20
  262. package/plugin/mcp/launcher.cjs +159 -35
  263. package/plugin/openclaw.plugin.json +1 -1
  264. package/plugin/package.json +1 -1
  265. package/plugin/templates/workspace/okr/RECOVERY_PROTOCOL.md +8 -7
  266. package/release-manager/dist/installer.js +627 -100
  267. package/release-manager/dist/installers/codex-host-installer.js +36 -20
  268. package/release-manager/dist/installers/index.js +24 -3
  269. package/release-manager/dist/installers/mcp-registration-conflict.js +23 -16
  270. package/release-manager/dist/installers/openclaw-host-installer.js +1 -8
  271. package/release-manager/dist/installers/workbuddy-host-installer.js +51 -15
  272. package/release-manager/dist/mvp-config.js +49 -16
  273. package/release-manager/dist/update/release-manager.js +5 -2
  274. package/release-manager/dist/utils/env.js +91 -34
  275. package/release-manager/dist/utils/host-workspace-ownership.js +153 -2
  276. package/release-manager/package.json +2 -2
  277. package/workbuddy-adapter/dist/index.d.ts +1 -1
  278. package/workbuddy-adapter/dist/index.js +1 -1
  279. package/workbuddy-adapter/dist/ingestion/catch-up.js +15 -3
  280. package/workbuddy-adapter/dist/ingestion/index.d.ts +1 -1
  281. package/workbuddy-adapter/dist/ingestion/index.js +1 -1
  282. package/workbuddy-adapter/dist/ingestion/ingestion.d.ts +18 -0
  283. package/workbuddy-adapter/dist/ingestion/ingestion.js +20 -2
  284. package/workbuddy-adapter/dist/ingestion/transcript-path.d.ts +13 -4
  285. package/workbuddy-adapter/dist/ingestion/transcript-path.js +102 -4
  286. package/workbuddy-adapter/dist/ingestion/transcript-source.js +76 -58
  287. package/workbuddy-adapter/dist/pd-hook.js +10 -3
  288. package/workbuddy-adapter/dist/worker/workspace-worker.js +4 -1
  289. package/workbuddy-adapter/dist/workspace-resolution.d.ts +9 -2
  290. package/workbuddy-adapter/dist/workspace-resolution.js +19 -3
  291. package/workbuddy-adapter/package.json +1 -1
  292. package/workbuddy-adapter/plugin/mcp/launcher.cjs +159 -35
  293. package/plugin/dist/templates/workspace/okr/CURRENT_FOCUS.md +0 -56
  294. package/plugin/dist/templates/workspace/okr/TASK_CHANGES.jsonl +0 -6
  295. package/plugin/dist/templates/workspace/okr/WEEK_TASKS.json +0 -6
  296. package/plugin/templates/workspace/okr/CURRENT_FOCUS.md +0 -56
  297. package/plugin/templates/workspace/okr/TASK_CHANGES.jsonl +0 -6
  298. package/plugin/templates/workspace/okr/WEEK_TASKS.json +0 -6
@@ -2,6 +2,7 @@ import { pdProviderCredentials } from '@principles/core/runtime';
2
2
  import { loadPdConfigForPlugin } from './pd-config.js';
3
3
  import { ADAPTIVE_SELECTION_LIMITS, runAdaptiveSelection, } from './adaptive-selection.js';
4
4
  import { decideAdaptiveSkip } from './adaptive-skip-decision.js';
5
+ import { readPrincipleContext } from './adaptive-principle-context-reader.js';
5
6
  /** Independent switch. `features.host.codex.enabled` remains the whole-hook gate. */
6
7
  export const ADAPTIVE_ACTIVATION_FLAG = 'host.codex.adaptive_activation';
7
8
  /**
@@ -102,6 +103,7 @@ export function createAdaptivePriorityProvider(options) {
102
103
  providerObserved: null,
103
104
  targetActivationId: null,
104
105
  decision: null,
106
+ contextDropped: null,
105
107
  failures: [],
106
108
  });
107
109
  return undefined;
@@ -109,18 +111,70 @@ export function createAdaptivePriorityProvider(options) {
109
111
  // The gate already proved identity and a non-blank prompt (rc-3); the
110
112
  // selector only needs the prompt body from here on.
111
113
  const prompt = promptContent ?? '';
114
+ const turnWorkspaceDir = workspaceDir || options.workspaceDir;
115
+ // Principle Context (SPEC v1.1 §5.1/§5.4.1): the authorization gate runs
116
+ // AFTER the skip gate. S1 (not `=== true`) performs zero stat/read by
117
+ // construction — the Reader is never called. Only an authorized turn
118
+ // performs ONE bounded read; any Reader failure degrades to a no-context
119
+ // turn (S2), never an error into the host prompt path.
120
+ // The abort signal is created BEFORE the context read so the Reader's
121
+ // stage gates can honor the same cooperative abort the selection uses.
112
122
  const signal = hostDeadlineAt === undefined ? undefined : AbortSignal.timeout(Math.max(1, hostDeadlineAt - now()));
123
+ let principleContext;
124
+ let contextFailure;
125
+ if (options.sendPrincipleContext === true) {
126
+ try {
127
+ // The Reader shares the host's remaining Adaptive window: its stage
128
+ // gates consume the same absolute deadline the selection runs under
129
+ // (minus the output reserve), so slow I/O cannot eat the turn's
130
+ // budget before the model request starts (SPEC §5.8).
131
+ const read = await (options.readPrincipleContextImpl ?? readPrincipleContext)(turnWorkspaceDir, {
132
+ ...(hostDeadlineAt !== undefined ? { deadlineAt: hostDeadlineAt } : {}),
133
+ ...(signal ? { signal } : {}),
134
+ ...(options.now ? { now: options.now } : {}),
135
+ });
136
+ if (read.status === 'available') {
137
+ principleContext = read.text;
138
+ }
139
+ else {
140
+ // Bounded enum-only diagnostic (status + reason), never context text.
141
+ contextFailure = `principle_context:${read.status}:${read.reason}`;
142
+ }
143
+ }
144
+ catch {
145
+ // Belt-and-braces: the Reader contract is "never throws", but a
146
+ // failure here may only cost the context, never the selection.
147
+ contextFailure = 'principle_context:unreadable:read_failed';
148
+ }
149
+ }
113
150
  const outcome = await runAdaptiveSelection({
114
- workspaceDir: workspaceDir || options.workspaceDir,
151
+ workspaceDir: turnWorkspaceDir,
115
152
  currentPrompt: prompt,
116
153
  candidates,
117
154
  replacementByActivationId,
118
155
  model: options.model,
119
156
  requestTimeoutMs,
157
+ ...(principleContext !== undefined ? { principleContext } : {}),
120
158
  ...(hostDeadlineAt !== undefined ? { outerDeadlineAt: hostDeadlineAt, signal } : {}),
121
159
  ...(options.now ? { now: options.now } : {}),
122
160
  ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),
123
161
  });
162
+ // S-state (SPEC v1.1 §5.4.1): a single bounded enum the four host
163
+ // diagnostic surfaces project verbatim, so an Owner can always tell
164
+ // whether the context actually participated in this decision. Computed
165
+ // AFTER the selection so the budget-drop marker is already final.
166
+ // `sent` is evidence-backed, never inferred from `principleContext` alone:
167
+ // it requires the authorization, a successful read, no budget drop, AND a
168
+ // real dispatch of a request that carried the field (`sends > 0`). A
169
+ // refused input or an expired deadline before the send leaves `sends` at
170
+ // 0 — the context did NOT participate, so no `sent` is fabricated.
171
+ const principleContextState = options.sendPrincipleContext !== true
172
+ ? 'unauthorized'
173
+ : contextFailure !== undefined
174
+ ? 'unavailable'
175
+ : outcome.diagnostics.contextDropped !== null
176
+ ? 'dropped_budget'
177
+ : principleContext !== undefined && outcome.sends > 0 ? 'sent' : undefined;
124
178
  options.onDiagnostic?.({
125
179
  status: outcome.status,
126
180
  reason: outcome.reason,
@@ -137,7 +191,9 @@ export function createAdaptivePriorityProvider(options) {
137
191
  providerObserved: outcome.diagnostics.providerObserved,
138
192
  targetActivationId: outcome.status === 'selected' && outcome.target ? outcome.target.activationId : null,
139
193
  decision: outcome.diagnostics.decision,
140
- failures: [...outcome.diagnostics.failures],
194
+ contextDropped: outcome.diagnostics.contextDropped,
195
+ ...(principleContextState !== undefined ? { principleContext: principleContextState } : {}),
196
+ failures: [...outcome.diagnostics.failures, ...(contextFailure ? [contextFailure] : [])],
141
197
  });
142
198
  if (outcome.status !== 'selected' || !outcome.target)
143
199
  return undefined;
@@ -163,15 +219,25 @@ export function createAdaptivePriorityProviderForConfig(config, workspaceDir, op
163
219
  nextAction: resolved.nextAction,
164
220
  };
165
221
  }
222
+ // Principle Context authorization (SPEC v1.1 §5.1/§6.2): evaluated EXACTLY
223
+ // ONCE here, from the already-loaded-and-validated config, and injected as a
224
+ // boolean the provider closure holds. No per-turn config re-read. Strict
225
+ // `=== true` means: absent config, absent section, absent key, an explicit
226
+ // false, and any invalid value rejected by the validator are ALL
227
+ // unauthorized — fail-closed for every construction path (direct
228
+ // construction and tests never pass the field, so they stay unauthorized).
229
+ const sendPrincipleContext = config.adaptiveActivation?.sendPrincipleContext === true;
166
230
  const provider = createAdaptivePriorityProvider({
167
231
  workspaceDir,
168
232
  model: resolved.model,
233
+ sendPrincipleContext,
169
234
  ...(options.requestTimeoutMs !== undefined ? { requestTimeoutMs: options.requestTimeoutMs } : {}),
170
235
  ...(options.outerDeadlineAt !== undefined ? { outerDeadlineAt: options.outerDeadlineAt } : {}),
171
236
  ...(options.outputReserveMs !== undefined ? { outputReserveMs: options.outputReserveMs } : {}),
172
237
  ...(options.minExecutableBudgetMs !== undefined ? { minExecutableBudgetMs: options.minExecutableBudgetMs } : {}),
173
238
  ...(options.now ? { now: options.now } : {}),
174
239
  ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),
240
+ ...(options.readPrincipleContextImpl ? { readPrincipleContextImpl: options.readPrincipleContextImpl } : {}),
175
241
  ...(options.onDiagnostic ? { onDiagnostic: options.onDiagnostic } : {}),
176
242
  });
177
243
  return {
@@ -49,6 +49,8 @@ export interface BoundedSelectionInput {
49
49
  readonly digest: string;
50
50
  readonly replaces?: string;
51
51
  }[];
52
+ /** Principle Context (SPEC v1.1 §5.2): normalized, already authorized, optional. */
53
+ readonly principleContext?: string;
52
54
  };
53
55
  readonly entries: readonly AdaptiveCandidate[];
54
56
  readonly priorDropped: number;
@@ -105,6 +107,12 @@ export interface AdaptiveSelectionDiagnostics {
105
107
  scores: Readonly<Record<string, number>>;
106
108
  } | null;
107
109
  failures: AdaptiveFailureCode[];
110
+ /**
111
+ * S3 marker (SPEC v1.1 sect 5.3): the context was read and normalized but the
112
+ * 20,000-code-unit budget rejected the first build, so the field was
113
+ * removed and the request rebuilt. Bounded code - never context text.
114
+ */
115
+ contextDropped: 'principle_context_dropped:budget' | null;
108
116
  }
109
117
  export declare function hash(value: string): string;
110
118
  export declare function buildBoundedSelectionInput(input: {
@@ -115,6 +123,7 @@ export declare function buildBoundedSelectionInput(input: {
115
123
  }[];
116
124
  readonly candidates: readonly AdaptiveCandidateSource[];
117
125
  readonly replacementByActivationId?: ReadonlyMap<string, ActivatedPrinciple> | undefined;
126
+ readonly principleContext?: string;
118
127
  }): BuildBoundedInputResult;
119
128
  export interface DecisionSelectorOptions {
120
129
  readonly fetchImpl?: typeof fetch;
@@ -149,6 +158,13 @@ export interface RunAdaptiveSelectionOptions {
149
158
  readonly currentPrompt: string;
150
159
  readonly candidates: readonly ActivatedPrinciple[];
151
160
  readonly replacementByActivationId?: ReadonlyMap<string, ActivatedPrinciple> | undefined;
161
+ /**
162
+ * Principle Context (SPEC v1.1 §5.2/§5.3): normalized text from the shared
163
+ * Reader, present ONLY on an authorized turn whose read returned available.
164
+ * Passes into the Decisions state JSON; dropped whole (never truncated)
165
+ * before instruction/candidates when the 20K budget overflows.
166
+ */
167
+ readonly principleContext?: string;
152
168
  readonly model: AdaptiveSelectionModel;
153
169
  readonly requestTimeoutMs?: number;
154
170
  readonly signal?: AbortSignal;
@@ -91,6 +91,9 @@ export function buildBoundedSelectionInput(input) {
91
91
  currentInstruction,
92
92
  priorMessages: boundedPrior,
93
93
  candidates: entries.map(({ ref, text, digest, replaces }) => ({ ref, text, digest, ...(replaces !== undefined ? { replaces } : {}) })),
94
+ ...(input.principleContext !== undefined && input.principleContext.length > 0
95
+ ? { principleContext: input.principleContext }
96
+ : {}),
94
97
  },
95
98
  entries,
96
99
  priorDropped: Math.max(0, priorMessages.length - selectedPrior.length),
@@ -134,6 +137,7 @@ function emptyDiagnostics() {
134
137
  usage: null,
135
138
  decision: null,
136
139
  failures: [],
140
+ contextDropped: null,
137
141
  };
138
142
  }
139
143
  function projectUsage(value) {
@@ -339,17 +343,31 @@ export async function runAdaptiveSelection(options) {
339
343
  currentInput: options.currentPrompt,
340
344
  candidates: options.candidates,
341
345
  replacementByActivationId: options.replacementByActivationId,
346
+ ...(options.principleContext !== undefined ? { principleContext: options.principleContext } : {}),
342
347
  });
343
348
  if (!built.ok)
344
349
  return unavailable(built.reason, 'idle');
345
- const request = buildDecisionRequest({
350
+ const buildRequest = (withPrincipleContext) => buildDecisionRequest({
346
351
  model: options.model.model,
347
352
  ...(options.model.provider !== undefined ? { provider: options.model.provider } : {}),
348
353
  currentInstruction: built.input.payload.currentInstruction,
349
354
  priorMessages: built.input.payload.priorMessages,
350
355
  candidates: built.input.payload.candidates,
356
+ ...(withPrincipleContext && built.input.payload.principleContext !== undefined
357
+ ? { principleContext: built.input.payload.principleContext }
358
+ : {}),
351
359
  maxPayloadChars: ADAPTIVE_SELECTION_LIMITS.maxPayloadChars,
352
360
  });
361
+ let request = buildRequest(true);
362
+ // Principle Context budget rule (SPEC v1.1 sect 5.3): build WITH the
363
+ // context first; on overflow remove the WHOLE field and rebuild. Never
364
+ // truncate the instruction and never drop candidates to keep the context.
365
+ // Still overflowing without the context => the existing INPUT_REFUSED.
366
+ let contextDropped = false;
367
+ if (!request.ok && request.reason === 'INPUT_REFUSED' && built.input.payload.principleContext !== undefined) {
368
+ contextDropped = true;
369
+ request = buildRequest(false);
370
+ }
353
371
  if (!request.ok)
354
372
  return unavailable(request.reason, 'idle');
355
373
  const selector = createDecisionSelector({
@@ -360,6 +378,10 @@ export async function runAdaptiveSelection(options) {
360
378
  ...(options.now ? { now: options.now } : {}),
361
379
  ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),
362
380
  });
381
+ if (contextDropped) {
382
+ // S3 marker on the diagnostics the report will carry (bounded code only).
383
+ selector.report().diagnostics.contextDropped = 'principle_context_dropped:budget';
384
+ }
363
385
  let decision;
364
386
  try {
365
387
  decision = await selector.select({
@@ -9,11 +9,19 @@
9
9
  * the same core parser at its own edge.
10
10
  */
11
11
  import fs from 'node:fs';
12
- import os from 'node:os';
13
12
  import * as path from 'node:path';
14
13
  import { parseLegacyCodexHooksRegistration } from '@principles/core/host';
14
+ import { resolvePdHome } from '@principles/install-layout';
15
15
  function getCodexHooksJsonPath() {
16
- return path.join(os.homedir(), '.codex', 'hooks.json');
16
+ // The Codex home follows the shared PD Home authority (CODEX_HOME override,
17
+ // PD_EXPERIMENT_ROOT isolation). A refused resolution fails loud — reading a
18
+ // production hooks.json from inside a misconfigured lab would silently
19
+ // report foreign governance state.
20
+ const home = resolvePdHome();
21
+ if (!home.ok) {
22
+ throw new Error(`PD home resolution refused (${home.reason}): ${home.message} Next action: ${home.nextAction}`);
23
+ }
24
+ return path.join(home.codexHome, 'hooks.json');
17
25
  }
18
26
  /**
19
27
  * Detect a PD-owned legacy global hook registration in ~/.codex/hooks.json.
@@ -77,4 +77,12 @@ export type ConversationIngestionOutcome = {
77
77
  nextAction: string;
78
78
  warnings: readonly string[];
79
79
  };
80
+ /**
81
+ * PRI-1261: how far the oversized-record scan-ahead may read past the bounded
82
+ * window while looking for the record's terminating newline. Bounded memory is
83
+ * preserved — chunks are discarded as soon as they are scanned. Beyond the cap
84
+ * the record's completeness cannot be confirmed and the checkpoint HOLDS (the
85
+ * same safe posture as an incomplete tail) instead of guessing.
86
+ */
87
+ export declare const OVERSIZED_RECORD_SCAN_AHEAD_CAP_BYTES: number;
80
88
  export declare function runConversationIngestion(args: RunIngestionArgs): ConversationIngestionOutcome;
@@ -32,6 +32,100 @@ import { appendEventLogLine } from '@principles/core/runtime';
32
32
  import { ingestGovernanceObservations, readGovernanceCheckpoint, } from '../governance-observation-store.js';
33
33
  import { CONVERSATION_INGESTION_MAX_BATCH_BYTES, TranscriptReplacedError, createNodeTranscriptPort, } from './source.js';
34
34
  import { TEXT_POLICY_BOUNDED_MAX_CHARS } from './text-policy.js';
35
+ /**
36
+ * PRI-1261: how far the oversized-record scan-ahead may read past the bounded
37
+ * window while looking for the record's terminating newline. Bounded memory is
38
+ * preserved — chunks are discarded as soon as they are scanned. Beyond the cap
39
+ * the record's completeness cannot be confirmed and the checkpoint HOLDS (the
40
+ * same safe posture as an incomplete tail) instead of guessing.
41
+ */
42
+ export const OVERSIZED_RECORD_SCAN_AHEAD_CAP_BYTES = 64 * 1024 * 1024;
43
+ /**
44
+ * Review-round hardening (2026-11-18): the bounded slice of an oversized
45
+ * record retained ONLY to detect a control envelope (`type:"compacted"`).
46
+ * Envelope keys sit at the head of the JSON line, so a few KiB suffice and no
47
+ * payload body is ever retained.
48
+ */
49
+ const OVERSIZED_RECORD_HEAD_PROBE_BYTES = 8 * 1024;
50
+ /**
51
+ * PRI-1261: scan PAST the bounded window for the oversized record's
52
+ * terminating newline, discarding bytes as they are scanned (bounded memory).
53
+ * The scan starts after the window — the decoder only reports
54
+ * `oversized_record` when the window contains NO newline at all.
55
+ */
56
+ function scanAheadForRecordNewline(args) {
57
+ const { port, locator, maxChunkBytes } = args;
58
+ let cursor = args.fromOffset;
59
+ let scanned = 0;
60
+ for (;;) {
61
+ if (scanned >= OVERSIZED_RECORD_SCAN_AHEAD_CAP_BYTES) {
62
+ return { found: false, newlineOffset: -1, scannedBytes: scanned, stopReason: 'cap' };
63
+ }
64
+ let bytes;
65
+ try {
66
+ const window = port.read({
67
+ canonicalPath: locator.filePath,
68
+ offset: cursor,
69
+ maxBytes: Math.min(maxChunkBytes, OVERSIZED_RECORD_SCAN_AHEAD_CAP_BYTES - scanned),
70
+ expectedIdentity: locator.expectedIdentity,
71
+ });
72
+ ({ bytes } = window);
73
+ }
74
+ catch {
75
+ return { found: false, newlineOffset: -1, scannedBytes: scanned, stopReason: 'read_failed' };
76
+ }
77
+ if (bytes.length === 0) {
78
+ return { found: false, newlineOffset: -1, scannedBytes: scanned, stopReason: 'eof' };
79
+ }
80
+ const index = bytes.indexOf(0x0a);
81
+ if (index !== -1) {
82
+ return { found: true, newlineOffset: cursor + index, scannedBytes: scanned + bytes.length, stopReason: 'newline' };
83
+ }
84
+ cursor += bytes.length;
85
+ scanned += bytes.length;
86
+ }
87
+ }
88
+ /**
89
+ * PRI-1261 review fix: bounded read of the OVERSIZED RECORD'S OWN HEAD (the
90
+ * record starts at `recordStart`, which is BEFORE the scan-ahead origin — the
91
+ * decoder's window already sits inside the record). Envelope keys live in the
92
+ * first bytes of the JSON line, so 8 KiB suffice and no payload body is ever
93
+ * retained. Returns null when the head cannot be read (the marker is then
94
+ * simply undetectable — never guessed).
95
+ */
96
+ function readOversizedRecordHead(args) {
97
+ try {
98
+ const window = args.port.read({
99
+ canonicalPath: args.locator.filePath,
100
+ offset: args.recordStart,
101
+ maxBytes: OVERSIZED_RECORD_HEAD_PROBE_BYTES,
102
+ expectedIdentity: args.locator.expectedIdentity,
103
+ });
104
+ return window.bytes.length > 0 ? window.bytes : null;
105
+ }
106
+ catch {
107
+ return null;
108
+ }
109
+ }
110
+ /**
111
+ * PRI-1261 review fix: a SKIPPED oversized record must not silently drop a
112
+ * `compacted` CONTROL record — the compaction marker is what tombstones the
113
+ * rollout's pre-compaction history; skipping it would leave stale turns
114
+ * attributed to the live conversation forever. The probe reads only the
115
+ * record head (envelope keys live there), never the payload body.
116
+ * Returns the marker's timestamp, 'unparseable' when a marker exists but its
117
+ * timestamp cannot be trusted, or null when the head carries no marker.
118
+ */
119
+ function detectOversizedCompactionMarker(head) {
120
+ const headText = head.toString('utf8');
121
+ if (!/"type"\s*:\s*"compacted"/.test(headText))
122
+ return null;
123
+ const timestampMatch = /"timestamp"\s*:\s*"([^"]+)"/.exec(headText);
124
+ const timestamp = timestampMatch?.[1] ?? '';
125
+ if (timestamp.length === 0 || !Number.isFinite(Date.parse(timestamp)))
126
+ return 'unparseable';
127
+ return { timestamp };
128
+ }
35
129
  export function runConversationIngestion(args) {
36
130
  const texts = {
37
131
  readFailedNextAction: 'verify the transcript file still exists and is a regular file inside the host sessions root.',
@@ -131,11 +225,64 @@ export function runConversationIngestion(args) {
131
225
  }
132
226
  // 8. Stop-classified store degradations (recorded on the checkpoint row).
133
227
  const degradations = [];
228
+ // PRI-1261: an oversized_record whose terminating newline exists in the file
229
+ // is a COMPLETE record that policy cannot retain — the checkpoint SKIPS past
230
+ // it (tracked disposition below) so subsequent turns stay reachable instead
231
+ // of the checkpoint stalling on the same offset forever. No newline until
232
+ // EOF (or the scan cap) is indistinguishable from a record still being
233
+ // written: the checkpoint HOLDS exactly like an incomplete tail.
234
+ let checkpointByteOffset = delta.nextByteOffset;
235
+ let oversizedSkip = null;
236
+ let oversizedHeldIncomplete = false;
237
+ /** Review fix: a skipped record that WAS the compaction marker applies it before the checkpoint advances. */
238
+ let oversizedCompactionTimestamp = null;
134
239
  if (delta.stop.kind === 'malformed') {
135
240
  degradations.push({ reason: 'transcript_record_malformed', ...(delta.stop.ordinal !== null ? { ordinal: delta.stop.ordinal } : {}), nextAction: texts.malformedNextAction });
136
241
  }
137
242
  else if (delta.stop.kind === 'oversized_record') {
138
- degradations.push({ reason: 'transcript_record_too_large', nextAction: texts.oversizedNextAction });
243
+ const scan = scanAheadForRecordNewline({
244
+ port,
245
+ locator,
246
+ fromOffset: offset + windowBytes.length,
247
+ maxChunkBytes: args.maxBatchBytes ?? CONVERSATION_INGESTION_MAX_BATCH_BYTES,
248
+ });
249
+ const head = scan.found ? readOversizedRecordHead({ port, locator, recordStart: offset }) : null;
250
+ const marker = head !== null ? detectOversizedCompactionMarker(head) : null;
251
+ const markerBlocked = marker === 'unparseable';
252
+ if (scan.found && markerBlocked) {
253
+ // A control record we cannot safely interpret must NOT be crossed:
254
+ // applying the wrong (or no) compaction silently corrupts history
255
+ // attribution. Hold the checkpoint on the record instead (rc-3).
256
+ oversizedHeldIncomplete = true;
257
+ degradations.push({
258
+ reason: 'transcript_record_too_large',
259
+ nextAction: `an oversized control record (compaction marker) at offset ${offset} could not be interpreted within the bounded head probe; the checkpoint holds on it. Inspect the transcript file.`,
260
+ });
261
+ }
262
+ else if (scan.found && !markerBlocked) {
263
+ checkpointByteOffset = scan.newlineOffset + 1;
264
+ oversizedSkip = { start: offset, bytes: checkpointByteOffset - offset };
265
+ if (marker !== null) {
266
+ oversizedCompactionTimestamp = marker.timestamp;
267
+ }
268
+ degradations.push({
269
+ reason: 'transcript_record_too_large',
270
+ nextAction: marker !== null
271
+ ? `a complete oversized compaction marker (${oversizedSkip.bytes} bytes at offset ${oversizedSkip.start}) was SKIPPED but its compaction WAS applied (history before ${marker.timestamp} is tombstoned); later records continue from offset ${checkpointByteOffset}.`
272
+ : `a complete record of ${oversizedSkip.bytes} bytes at offset ${oversizedSkip.start} exceeded the retention window and was SKIPPED (not retained); later records continue from offset ${checkpointByteOffset}.`,
273
+ });
274
+ }
275
+ else {
276
+ oversizedHeldIncomplete = scan.stopReason !== 'read_failed';
277
+ degradations.push({
278
+ reason: 'transcript_record_too_large',
279
+ nextAction: scan.stopReason === 'eof'
280
+ ? 'the oversized record has no terminating newline yet (likely still being written); the checkpoint holds and retries after the record completes.'
281
+ : scan.stopReason === 'cap'
282
+ ? `the record exceeded the ${OVERSIZED_RECORD_SCAN_AHEAD_CAP_BYTES}-byte scan-ahead cap, so its completeness cannot be confirmed; the checkpoint holds. Inspect the transcript file.`
283
+ : texts.oversizedNextAction,
284
+ });
285
+ }
139
286
  }
140
287
  const rootSessionId = delta.rollout.rootSessionId ?? existing?.rootSessionId ?? args.session.sessionId;
141
288
  // 9. Pre-ingest host side-writes — failure holds the checkpoint (retry-safe).
@@ -164,14 +311,28 @@ export function runConversationIngestion(args) {
164
311
  checkpoint: {
165
312
  hostKind: args.source.hostKind,
166
313
  rolloutIdentity: locator.sessionIdentity,
167
- byteOffset: delta.nextByteOffset,
314
+ byteOffset: checkpointByteOffset,
168
315
  lastOrdinal: delta.lastOrdinal >= 0 ? delta.lastOrdinal : existing?.lastOrdinal ?? 0,
169
316
  ...(delta.rollout.cliVersion !== undefined ? { cliVersion: delta.rollout.cliVersion } : {}),
170
317
  rootSessionId,
171
- incompleteTail: delta.stop.kind === 'incomplete_tail',
318
+ incompleteTail: delta.stop.kind === 'incomplete_tail' || oversizedHeldIncomplete,
172
319
  },
173
320
  ...(degradations.length > 0 ? { degradations } : {}),
174
- ...(delta.compactionTimestamp !== null ? { compactionTimestamp: delta.compactionTimestamp } : {}),
321
+ ...((() => {
322
+ // Two markers in one window (decoded + skipped-oversized): the LATER
323
+ // timestamp tombstones the union of both ranges, so applying it covers
324
+ // the earlier marker too.
325
+ if (delta.compactionTimestamp === null) {
326
+ return oversizedCompactionTimestamp !== null ? { compactionTimestamp: oversizedCompactionTimestamp } : {};
327
+ }
328
+ if (oversizedCompactionTimestamp === null)
329
+ return { compactionTimestamp: delta.compactionTimestamp };
330
+ return {
331
+ compactionTimestamp: Date.parse(oversizedCompactionTimestamp) > Date.parse(delta.compactionTimestamp)
332
+ ? oversizedCompactionTimestamp
333
+ : delta.compactionTimestamp,
334
+ };
335
+ })()),
175
336
  ...(delta.rollbackTurns.length > 0 ? { rollbackTurns: delta.rollbackTurns } : {}),
176
337
  now,
177
338
  });
@@ -188,7 +349,18 @@ export function runConversationIngestion(args) {
188
349
  return degraded('transcript_record_malformed', texts.malformedNextAction, warnings);
189
350
  }
190
351
  if (delta.stop.kind === 'oversized_record') {
191
- return degraded('transcript_record_too_large', texts.oversizedNextAction, warnings);
352
+ // PRI-1261: the tracked disposition rides the warnings so the skip (or the
353
+ // hold) is queryable without re-deriving it from the checkpoint row.
354
+ if (oversizedSkip !== null) {
355
+ warnings.push(`transcript_record_skipped_oversized:${oversizedSkip.bytes}b@${oversizedSkip.start}->${checkpointByteOffset}`);
356
+ if (oversizedCompactionTimestamp !== null) {
357
+ warnings.push(`transcript_record_skipped_oversized_compaction_applied:${oversizedCompactionTimestamp}`);
358
+ }
359
+ }
360
+ else if (oversizedHeldIncomplete) {
361
+ warnings.push('transcript_record_oversized_incomplete_tail');
362
+ }
363
+ return degraded('transcript_record_too_large', degradations.find((entry) => entry.reason === 'transcript_record_too_large')?.nextAction ?? texts.oversizedNextAction, warnings);
192
364
  }
193
365
  return {
194
366
  status: 'ok',
@@ -196,9 +368,9 @@ export function runConversationIngestion(args) {
196
368
  enriched: result.enriched,
197
369
  duplicates: result.duplicates,
198
370
  warnings,
199
- lagBytes: Math.max(0, fileSize - delta.nextByteOffset),
371
+ lagBytes: Math.max(0, fileSize - checkpointByteOffset),
200
372
  observations: delta.observations,
201
373
  sessionIdentity: locator.sessionIdentity,
202
- checkpointByteOffset: delta.nextByteOffset,
374
+ checkpointByteOffset,
203
375
  };
204
376
  }
@@ -16,8 +16,8 @@
16
16
  */
17
17
  import { createHash } from 'node:crypto';
18
18
  import * as fs from 'node:fs';
19
- import * as os from 'node:os';
20
19
  import * as path from 'node:path';
20
+ import { resolvePdHome } from '@principles/install-layout';
21
21
  const UNREADABLE_MARKER_NEXT_ACTION = 'Inspect the marker file and the workspace governance store. Enforcement ran fail-open when this was recorded; the recorder never clears the marker automatically — after investigating, an Owner may delete the marker file to reset this signal.';
22
22
  function isRecord(value) {
23
23
  return typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -47,7 +47,11 @@ function unknownReading(markerPath, unreadableReason) {
47
47
  return { state: 'unknown', markerPath, unreadableReason, nextAction: UNREADABLE_MARKER_NEXT_ACTION };
48
48
  }
49
49
  function markerDir() {
50
- return path.join(path.resolve(os.homedir()), '.pd', 'enforcement-health');
50
+ const home = resolvePdHome();
51
+ if (!home.ok) {
52
+ throw new Error(`PD home resolution refused (${home.reason}): ${home.message} Next action: ${home.nextAction}`);
53
+ }
54
+ return path.join(home.pdHome, 'enforcement-health');
51
55
  }
52
56
  /** Stable per-workspace marker path (keyed by resolved workspace dir). */
53
57
  export function markerPathFor(workspaceDir) {
@@ -104,6 +108,16 @@ export function recordDegradedEnforcement(workspaceDir, reason, now = new Date()
104
108
  * of the governance store. Read-only by contract.
105
109
  */
106
110
  export function readDegradedEnforcement(workspaceDir) {
111
+ // An unusable PD Home configuration is a STRUCTURED unknown, not a throw
112
+ // (Devin review #2699-0007): `pd health --json` reads markers BEFORE it
113
+ // reaches its own PD Home handling, so a throw here would break the
114
+ // single-parseable-JSON contract (cli-1/cli-6). The marker stays unread and
115
+ // the refusal is reported in unreadableReason — same contract as a malformed
116
+ // marker file.
117
+ const homeResolution = resolvePdHome();
118
+ if (!homeResolution.ok) {
119
+ return unknownReading(path.join('<pd-home-unresolved>', 'enforcement-health', `degraded-${createHash('sha256').update(path.resolve(workspaceDir), 'utf8').digest('hex').slice(0, 16)}.json`), `pd_home_unresolved: ${homeResolution.reason} — ${homeResolution.message}`.slice(0, 300));
120
+ }
107
121
  const markerPath = markerPathFor(workspaceDir);
108
122
  let raw;
109
123
  try {
@@ -21,6 +21,7 @@ import * as path from 'node:path';
21
21
  import { PrincipleTreeLedgerAdapter, createPainSignalBridge, createRuntimeStateHandle, pickDiagnosticianCandidate, resolveDiagnosticianCapability, } from '@principles/core/runtime';
22
22
  import { loadFeatureFlagFromConfig, loadPdConfigForPlugin } from './pd-config.js';
23
23
  import { createHostIntentDocReader } from './intent-doc-reader.js';
24
+ import { createGovernanceTrajectoryTurnReader } from './governance-trajectory-turn-reader.js';
24
25
  /** Quiet flag that owns the L3 half of the ladder. */
25
26
  export const DIAGNOSTICIAN_AUTO_RUN_FLAG = 'openclaw_diagnostician_consumer';
26
27
  /** Owner string used for the diagnostics this module starts. */
@@ -75,6 +76,9 @@ export async function runPendingDiagnosticianOnce(options) {
75
76
  // neutral host reader must ride along or admission would never capture
76
77
  // a snapshot on this path. Flag-off keeps zero filesystem access.
77
78
  intentDocReader: createHostIntentDocReader({ workspaceDir: options.workspaceDir, effectiveConfig: config.effective }),
79
+ // PRI-1265: the auto-run path sees the bound session's ORIGINAL turns
80
+ // like every other diagnosis entry.
81
+ trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir: options.workspaceDir }),
78
82
  });
79
83
  const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
80
84
  if (executed.status === 'failed') {
@@ -258,10 +258,54 @@ export declare function listGovernanceUncheckpointedSessions(args: ListGovernanc
258
258
  export interface ListGovernanceObservationsInput {
259
259
  readonly workspaceDir: string;
260
260
  readonly rolloutIdentity?: string;
261
+ readonly hostKind?: GovernanceObservationInput['hostKind'];
262
+ readonly hostTurnId?: string;
261
263
  readonly retentionClass?: GovernanceRetentionClass;
262
264
  readonly limit?: number;
263
265
  readonly databaseFactory?: ObservationDatabaseFactory;
264
266
  }
267
+ /** A retained turn text row (visible_text NOT NULL — expired rows are out). */
268
+ export interface GovernanceTurnTextRow {
269
+ readonly id: number;
270
+ readonly sourceOrdinal: number;
271
+ readonly visibleText: string;
272
+ readonly observedAt: string;
273
+ }
274
+ export interface ListGovernanceTurnTextsInput {
275
+ readonly workspaceDir: string;
276
+ readonly kind: 'user_turn' | 'assistant_turn';
277
+ /**
278
+ * Matches the session's OWN rollout rows first; rows that merely carry the
279
+ * id as `root_session_id` (parent-of-subagent lineage, historical alias)
280
+ * are consulted only when no exact rollout row exists.
281
+ */
282
+ readonly sessionId: string;
283
+ /** Restrict to ONE host's observations — session ids are only unique per `(host_kind, rollout_identity)`. */
284
+ readonly hostKind?: 'codex' | 'openclaw' | 'workbuddy';
285
+ readonly limit?: number;
286
+ readonly databaseFactory?: ObservationDatabaseFactory;
287
+ }
288
+ export type ListGovernanceTurnTextsResult = {
289
+ ok: true;
290
+ turns: readonly GovernanceTurnTextRow[];
291
+ } | Degradation;
292
+ /**
293
+ * PRI-1265: retained turn texts for ONE session, oldest-first — the read side
294
+ * behind the shared TrajectoryTurnReader adapter (CLI diagnose/pain retry,
295
+ * Codex/WorkBuddy workers, host-runtime auto-run). Review-round hardening
296
+ * (2026-11-18):
297
+ * - ONLY `retention_class IN ('operational','promoted')` rows are served —
298
+ * a replay can refill an expired row's body through the enrichment path,
299
+ * so `visible_text IS NOT NULL` alone is not a retention verdict;
300
+ * - the NEWEST `limit` turns are returned (the reported/last turn must not
301
+ * fall off a long session's window just because it is recent);
302
+ * - exact `rollout_identity` rows win over `root_session_id` rows, so a
303
+ * subagent rollout (whose root_session_id points at its parent thread)
304
+ * is never mixed into the parent's own conversation;
305
+ * - an optional `hostKind` keeps verification per-host (session ids are
306
+ * unique per `(host_kind, rollout_identity)`, not globally).
307
+ */
308
+ export declare function listGovernanceTurnTexts(input: ListGovernanceTurnTextsInput): ListGovernanceTurnTextsResult;
265
309
  export type ListGovernanceObservationsResult = {
266
310
  ok: true;
267
311
  observations: readonly GovernanceObservationRecord[];