create-principles-disciple 1.150.2 → 1.150.4

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 (267) hide show
  1. package/_release/product-identity.json +1 -1
  2. package/codex-adapter/dist/ingestion/admission.js +2 -0
  3. package/codex-adapter/dist/pd-hook.d.ts +7 -5
  4. package/codex-adapter/dist/pd-hook.js +18 -7
  5. package/codex-adapter/dist/tool-semantics.js +5 -1
  6. package/codex-adapter/dist/worker/workspace-worker.js +4 -2
  7. package/codex-adapter/package.json +1 -1
  8. package/console/dist/lib/utils.js +16 -1
  9. package/console/dist/web/assets/app.css +147 -46
  10. package/console/dist/web/assets/app.js +35 -32
  11. package/console/package.json +2 -0
  12. package/core/dist/runtime/activation/adaptive-selection-output.d.ts +35 -0
  13. package/core/dist/runtime/activation/adaptive-selection-output.d.ts.map +1 -0
  14. package/core/dist/runtime/activation/adaptive-selection-output.js +38 -0
  15. package/core/dist/runtime/activation/adaptive-selection-output.js.map +1 -0
  16. package/core/dist/runtime/activation-compatibility-read-model.d.ts.map +1 -1
  17. package/core/dist/runtime/activation-compatibility-read-model.js +2 -1
  18. package/core/dist/runtime/activation-compatibility-read-model.js.map +1 -1
  19. package/core/dist/runtime/adapter/artificer-l2-adapter.d.ts.map +1 -1
  20. package/core/dist/runtime/adapter/artificer-l2-adapter.js +89 -27
  21. package/core/dist/runtime/adapter/artificer-l2-adapter.js.map +1 -1
  22. package/core/dist/runtime/adapter/context-budget.d.ts +49 -0
  23. package/core/dist/runtime/adapter/context-budget.d.ts.map +1 -0
  24. package/core/dist/runtime/adapter/context-budget.js +127 -0
  25. package/core/dist/runtime/adapter/context-budget.js.map +1 -0
  26. package/core/dist/runtime/adapter/output-schema-registry.d.ts.map +1 -1
  27. package/core/dist/runtime/adapter/output-schema-registry.js +7 -0
  28. package/core/dist/runtime/adapter/output-schema-registry.js.map +1 -1
  29. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.d.ts +30 -7
  30. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.d.ts.map +1 -1
  31. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.js +559 -211
  32. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.js.map +1 -1
  33. package/core/dist/runtime/candidate-audit.d.ts.map +1 -1
  34. package/core/dist/runtime/candidate-audit.js +2 -1
  35. package/core/dist/runtime/candidate-audit.js.map +1 -1
  36. package/core/dist/runtime/config/pd-config-effective.d.ts.map +1 -1
  37. package/core/dist/runtime/config/pd-config-effective.js +2 -0
  38. package/core/dist/runtime/config/pd-config-effective.js.map +1 -1
  39. package/core/dist/runtime/config/pd-config-types.d.ts +52 -0
  40. package/core/dist/runtime/config/pd-config-types.d.ts.map +1 -1
  41. package/core/dist/runtime/config/pd-config-types.js.map +1 -1
  42. package/core/dist/runtime/config/pd-config-validate.d.ts.map +1 -1
  43. package/core/dist/runtime/config/pd-config-validate.js +134 -0
  44. package/core/dist/runtime/config/pd-config-validate.js.map +1 -1
  45. package/core/dist/runtime/feature-flags/feature-flag-contract.d.ts.map +1 -1
  46. package/core/dist/runtime/feature-flags/feature-flag-contract.js +8 -0
  47. package/core/dist/runtime/feature-flags/feature-flag-contract.js.map +1 -1
  48. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.d.ts.map +1 -1
  49. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +24 -0
  50. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
  51. package/core/dist/runtime/index.d.ts +2 -0
  52. package/core/dist/runtime/index.d.ts.map +1 -1
  53. package/core/dist/runtime/index.js +2 -0
  54. package/core/dist/runtime/index.js.map +1 -1
  55. package/core/dist/runtime/internalization/rule-host-input-builder.d.ts +16 -0
  56. package/core/dist/runtime/internalization/rule-host-input-builder.d.ts.map +1 -1
  57. package/core/dist/runtime/internalization/rule-host-input-builder.js +18 -0
  58. package/core/dist/runtime/internalization/rule-host-input-builder.js.map +1 -1
  59. package/core/dist/runtime/internalization/split-diagnostician-runner.d.ts +8 -0
  60. package/core/dist/runtime/internalization/split-diagnostician-runner.d.ts.map +1 -1
  61. package/core/dist/runtime/internalization/split-diagnostician-runner.js +24 -2
  62. package/core/dist/runtime/internalization/split-diagnostician-runner.js.map +1 -1
  63. package/core/dist/runtime/internalization/tool-semantic-registry.d.ts +26 -0
  64. package/core/dist/runtime/internalization/tool-semantic-registry.d.ts.map +1 -1
  65. package/core/dist/runtime/internalization/tool-semantic-registry.js +55 -5
  66. package/core/dist/runtime/internalization/tool-semantic-registry.js.map +1 -1
  67. package/core/dist/runtime/internalization-chain-integrity-read-model.d.ts.map +1 -1
  68. package/core/dist/runtime/internalization-chain-integrity-read-model.js +2 -2
  69. package/core/dist/runtime/internalization-chain-integrity-read-model.js.map +1 -1
  70. package/core/dist/runtime/internalization-integrity-remediation.d.ts.map +1 -1
  71. package/core/dist/runtime/internalization-integrity-remediation.js +2 -2
  72. package/core/dist/runtime/internalization-integrity-remediation.js.map +1 -1
  73. package/core/dist/runtime/operator-health-read-model.d.ts.map +1 -1
  74. package/core/dist/runtime/operator-health-read-model.js +2 -2
  75. package/core/dist/runtime/operator-health-read-model.js.map +1 -1
  76. package/core/dist/runtime/pain-recall-read-model.d.ts.map +1 -1
  77. package/core/dist/runtime/pain-recall-read-model.js +4 -3
  78. package/core/dist/runtime/pain-recall-read-model.js.map +1 -1
  79. package/core/dist/runtime/pruning-read-model.d.ts.map +1 -1
  80. package/core/dist/runtime/pruning-read-model.js +3 -2
  81. package/core/dist/runtime/pruning-read-model.js.map +1 -1
  82. package/core/dist/runtime/risk/risk-calculator-policy.d.ts +12 -2
  83. package/core/dist/runtime/risk/risk-calculator-policy.d.ts.map +1 -1
  84. package/core/dist/runtime/risk/risk-calculator-policy.js +33 -22
  85. package/core/dist/runtime/risk/risk-calculator-policy.js.map +1 -1
  86. package/core/dist/runtime/schema-conformance-read-model.js +2 -2
  87. package/core/dist/runtime/schema-conformance-read-model.js.map +1 -1
  88. package/core/dist/runtime/store/sqlite-connection.d.ts +0 -5
  89. package/core/dist/runtime/store/sqlite-connection.d.ts.map +1 -1
  90. package/core/dist/runtime/store/sqlite-connection.js +4 -12
  91. package/core/dist/runtime/store/sqlite-connection.js.map +1 -1
  92. package/core/dist/runtime/store/storage-paths.d.ts +17 -0
  93. package/core/dist/runtime/store/storage-paths.d.ts.map +1 -0
  94. package/core/dist/runtime/store/storage-paths.js +52 -0
  95. package/core/dist/runtime/store/storage-paths.js.map +1 -0
  96. package/core/dist/runtime/trajectory-retention.d.ts +257 -0
  97. package/core/dist/runtime/trajectory-retention.d.ts.map +1 -0
  98. package/core/dist/runtime/trajectory-retention.js +598 -0
  99. package/core/dist/runtime/trajectory-retention.js.map +1 -0
  100. package/core/dist/telemetry-event.d.ts +2 -2
  101. package/core/dist/telemetry-event.d.ts.map +1 -1
  102. package/core/dist/telemetry-event.js +5 -0
  103. package/core/dist/telemetry-event.js.map +1 -1
  104. package/core/dist/trajectory-store.d.ts +9 -9
  105. package/core/dist/trajectory-store.d.ts.map +1 -1
  106. package/core/dist/trajectory-store.js +9 -12
  107. package/core/dist/trajectory-store.js.map +1 -1
  108. package/core/package.json +1 -1
  109. package/dist/installers/codex-host-installer.d.ts.map +1 -1
  110. package/dist/installers/codex-host-installer.js +92 -5
  111. package/dist/installers/codex-host-installer.js.map +1 -1
  112. package/dist/installers/mcp-binding-shape-mirror.d.ts +27 -0
  113. package/dist/installers/mcp-binding-shape-mirror.d.ts.map +1 -0
  114. package/dist/installers/mcp-binding-shape-mirror.js +105 -0
  115. package/dist/installers/mcp-binding-shape-mirror.js.map +1 -0
  116. package/dist/skill-catalog.d.ts +35 -0
  117. package/dist/skill-catalog.d.ts.map +1 -0
  118. package/dist/skill-catalog.js +85 -0
  119. package/dist/skill-catalog.js.map +1 -0
  120. package/dist/skill-delivery-parity.d.ts +22 -0
  121. package/dist/skill-delivery-parity.d.ts.map +1 -0
  122. package/dist/skill-delivery-parity.js +31 -0
  123. package/dist/skill-delivery-parity.js.map +1 -0
  124. package/host-runtime/dist/active-principle-prompt.d.ts +8 -0
  125. package/host-runtime/dist/active-principle-prompt.js +15 -5
  126. package/host-runtime/dist/adaptive-decision-protocol.d.ts +142 -0
  127. package/host-runtime/dist/adaptive-decision-protocol.js +190 -0
  128. package/host-runtime/dist/adaptive-priority-provider.d.ts +37 -13
  129. package/host-runtime/dist/adaptive-priority-provider.js +65 -62
  130. package/host-runtime/dist/adaptive-selection.d.ts +67 -62
  131. package/host-runtime/dist/adaptive-selection.js +218 -301
  132. package/host-runtime/dist/adaptive-skip-decision.d.ts +26 -14
  133. package/host-runtime/dist/adaptive-skip-decision.js +33 -29
  134. package/host-runtime/dist/codex-rule-context-provider.js +4 -1
  135. package/host-runtime/dist/governance-observation-store.d.ts +40 -1
  136. package/host-runtime/dist/governance-observation-store.js +188 -9
  137. package/host-runtime/dist/governance-signal-admission.d.ts +19 -3
  138. package/host-runtime/dist/governance-signal-admission.js +12 -4
  139. package/host-runtime/dist/host-tool-declaration.d.ts +18 -2
  140. package/host-runtime/dist/host-tool-declaration.js +67 -11
  141. package/host-runtime/dist/host-tool-semantic-resolver.d.ts +7 -0
  142. package/host-runtime/dist/host-tool-semantic-resolver.js +22 -2
  143. package/host-runtime/dist/index.d.ts +3 -0
  144. package/host-runtime/dist/index.js +14 -0
  145. package/host-runtime/dist/production-rulehost-gate.js +36 -4
  146. package/host-runtime/dist/trajectory-retention.d.ts +147 -0
  147. package/host-runtime/dist/trajectory-retention.js +907 -0
  148. package/host-runtime/package.json +1 -1
  149. package/install-layout/dist/index.d.ts +9 -2
  150. package/install-layout/dist/index.js +26 -9
  151. package/install-layout/dist/mcp-binding-contract.d.ts +91 -0
  152. package/install-layout/dist/mcp-binding-contract.js +230 -0
  153. package/install-layout/package.json +1 -1
  154. package/package.json +4 -4
  155. package/pd-cli/dist/commands/build-trajectory-evidence.d.ts.map +1 -1
  156. package/pd-cli/dist/commands/build-trajectory-evidence.js +17 -11
  157. package/pd-cli/dist/commands/build-trajectory-evidence.js.map +1 -1
  158. package/pd-cli/dist/commands/codex-reconcile.d.ts +7 -0
  159. package/pd-cli/dist/commands/codex-reconcile.d.ts.map +1 -1
  160. package/pd-cli/dist/commands/codex-reconcile.js +11 -2
  161. package/pd-cli/dist/commands/codex-reconcile.js.map +1 -1
  162. package/pd-cli/dist/commands/codex-worker.d.ts.map +1 -1
  163. package/pd-cli/dist/commands/codex-worker.js +35 -0
  164. package/pd-cli/dist/commands/codex-worker.js.map +1 -1
  165. package/pd-cli/dist/commands/command-helpers.d.ts +1 -1
  166. package/pd-cli/dist/commands/command-helpers.js +1 -1
  167. package/pd-cli/dist/commands/errors-list.d.ts +1 -1
  168. package/pd-cli/dist/commands/errors-list.js +1 -1
  169. package/pd-cli/dist/commands/health-mcp.d.ts +23 -1
  170. package/pd-cli/dist/commands/health-mcp.d.ts.map +1 -1
  171. package/pd-cli/dist/commands/health-mcp.js +81 -22
  172. package/pd-cli/dist/commands/health-mcp.js.map +1 -1
  173. package/pd-cli/dist/commands/health.d.ts +1 -1
  174. package/pd-cli/dist/commands/health.d.ts.map +1 -1
  175. package/pd-cli/dist/commands/health.js +12 -5
  176. package/pd-cli/dist/commands/health.js.map +1 -1
  177. package/pd-cli/dist/commands/principles-stats.d.ts +1 -1
  178. package/pd-cli/dist/commands/principles-stats.js +1 -1
  179. package/pd-cli/dist/commands/trajectory-retention.d.ts +23 -0
  180. package/pd-cli/dist/commands/trajectory-retention.d.ts.map +1 -0
  181. package/pd-cli/dist/commands/trajectory-retention.js +159 -0
  182. package/pd-cli/dist/commands/trajectory-retention.js.map +1 -0
  183. package/pd-cli/dist/commands/workbuddy-setup.d.ts +69 -0
  184. package/pd-cli/dist/commands/workbuddy-setup.d.ts.map +1 -0
  185. package/pd-cli/dist/commands/workbuddy-setup.js +379 -0
  186. package/pd-cli/dist/commands/workbuddy-setup.js.map +1 -0
  187. package/pd-cli/dist/commands/workbuddy-worker.d.ts.map +1 -1
  188. package/pd-cli/dist/commands/workbuddy-worker.js +42 -6
  189. package/pd-cli/dist/commands/workbuddy-worker.js.map +1 -1
  190. package/pd-cli/dist/index.d.ts +1 -7
  191. package/pd-cli/dist/index.d.ts.map +1 -1
  192. package/pd-cli/dist/index.js +15 -1201
  193. package/pd-cli/dist/index.js.map +1 -1
  194. package/pd-cli/dist/program.d.ts +17 -0
  195. package/pd-cli/dist/program.d.ts.map +1 -0
  196. package/pd-cli/dist/program.js +1263 -0
  197. package/pd-cli/dist/program.js.map +1 -0
  198. package/pd-cli/dist/services/delivery-surfaces.d.ts.map +1 -1
  199. package/pd-cli/dist/services/delivery-surfaces.js +7 -5
  200. package/pd-cli/dist/services/delivery-surfaces.js.map +1 -1
  201. package/pd-cli/dist/services/version-report.d.ts.map +1 -1
  202. package/pd-cli/dist/services/version-report.js +30 -4
  203. package/pd-cli/dist/services/version-report.js.map +1 -1
  204. package/pd-cli/package.json +1 -1
  205. package/pd-mcp-server/dist/version.d.ts +1 -1
  206. package/pd-mcp-server/dist/version.js +1 -1
  207. package/pd-mcp-server/package.json +3 -1
  208. package/plugin/dist/bundle.js +477 -471
  209. package/plugin/dist/constants/tools.d.ts +8 -1
  210. package/plugin/dist/core/trajectory-retention-trigger.d.ts +13 -0
  211. package/plugin/dist/core/trajectory.d.ts +14 -0
  212. package/plugin/dist/hooks/gate-block-helper.d.ts +17 -0
  213. package/plugin/dist/hooks/gate.d.ts +7 -2
  214. package/plugin/dist/host-runtime/openclaw-host-runtime.d.ts +1 -0
  215. package/plugin/dist/index.d.ts +5 -0
  216. package/plugin/dist/openclaw.plugin.json +1 -1
  217. package/plugin/dist/rulehost-evidence.js +29 -23
  218. package/plugin/dist/templates/langs/en/skills/pd-cli-operator/SKILL.md +16 -5
  219. package/plugin/dist/templates/langs/en/skills/pd-control/SKILL.md +7 -6
  220. package/plugin/dist/templates/langs/en/skills/pd-pain-signal/SKILL.md +141 -28
  221. package/plugin/dist/templates/langs/en/skills/pd-review/SKILL.md +15 -1
  222. package/plugin/dist/templates/langs/zh/skills/pd-cli-operator/SKILL.md +16 -5
  223. package/plugin/dist/templates/langs/zh/skills/pd-control/SKILL.md +7 -6
  224. package/plugin/dist/templates/langs/zh/skills/pd-pain-signal/SKILL.md +142 -29
  225. package/plugin/dist/templates/langs/zh/skills/pd-review/SKILL.md +15 -1
  226. package/plugin/openclaw.plugin.json +1 -1
  227. package/plugin/package.json +1 -1
  228. package/plugin/templates/langs/en/skills/pd-cli-operator/SKILL.md +16 -5
  229. package/plugin/templates/langs/en/skills/pd-control/SKILL.md +7 -6
  230. package/plugin/templates/langs/en/skills/pd-pain-signal/SKILL.md +141 -28
  231. package/plugin/templates/langs/en/skills/pd-review/SKILL.md +15 -1
  232. package/plugin/templates/langs/zh/skills/pd-cli-operator/SKILL.md +16 -5
  233. package/plugin/templates/langs/zh/skills/pd-control/SKILL.md +7 -6
  234. package/plugin/templates/langs/zh/skills/pd-pain-signal/SKILL.md +142 -29
  235. package/plugin/templates/langs/zh/skills/pd-review/SKILL.md +15 -1
  236. package/release-manager/dist/installers/codex-host-installer.js +92 -5
  237. package/release-manager/dist/installers/mcp-binding-shape-mirror.js +105 -0
  238. package/release-manager/package.json +1 -1
  239. package/workbuddy-adapter/dist/codec/input-decoder.d.ts +10 -0
  240. package/workbuddy-adapter/dist/codec/input-decoder.js +62 -5
  241. package/workbuddy-adapter/dist/host-adapter.js +1 -0
  242. package/workbuddy-adapter/dist/index.d.ts +1 -0
  243. package/workbuddy-adapter/dist/index.js +1 -0
  244. package/workbuddy-adapter/dist/ingestion/catch-up.d.ts +25 -0
  245. package/workbuddy-adapter/dist/ingestion/catch-up.js +161 -0
  246. package/workbuddy-adapter/dist/ingestion/encode-cwd.d.ts +6 -0
  247. package/workbuddy-adapter/dist/ingestion/encode-cwd.js +39 -0
  248. package/workbuddy-adapter/dist/ingestion/index.d.ts +13 -0
  249. package/workbuddy-adapter/dist/ingestion/index.js +13 -0
  250. package/workbuddy-adapter/dist/ingestion/ingestion.d.ts +46 -0
  251. package/workbuddy-adapter/dist/ingestion/ingestion.js +135 -0
  252. package/workbuddy-adapter/dist/ingestion/transcript-decoder.d.ts +70 -0
  253. package/workbuddy-adapter/dist/ingestion/transcript-decoder.js +554 -0
  254. package/workbuddy-adapter/dist/ingestion/transcript-path.d.ts +39 -0
  255. package/workbuddy-adapter/dist/ingestion/transcript-path.js +117 -0
  256. package/workbuddy-adapter/dist/ingestion/transcript-source.d.ts +15 -0
  257. package/workbuddy-adapter/dist/ingestion/transcript-source.js +152 -0
  258. package/workbuddy-adapter/dist/pd-hook.d.ts +8 -0
  259. package/workbuddy-adapter/dist/pd-hook.js +59 -2
  260. package/workbuddy-adapter/dist/worker/workspace-worker.d.ts +9 -0
  261. package/workbuddy-adapter/dist/worker/workspace-worker.js +46 -17
  262. package/workbuddy-adapter/package.json +1 -1
  263. package/workbuddy-adapter/plugin/hooks/hooks.json +11 -0
  264. package/workbuddy-adapter/plugin/skills/pd-cli-operator/SKILL.md +57 -19
  265. package/workbuddy-adapter/plugin/skills/pd-control/SKILL.md +21 -9
  266. package/workbuddy-adapter/plugin/skills/pd-pain-signal/SKILL.md +72 -61
  267. package/workbuddy-adapter/plugin/skills/pd-review/SKILL.md +27 -12
@@ -0,0 +1,117 @@
1
+ /**
2
+ * WorkBuddy transcript path authorization (PRI-1171 P2; SPEC v0.2 §4.4,
3
+ * tech design §5.1 — deterministic locate, never a directory scan).
4
+ *
5
+ * The ONLY accepted transcript sources are, in order:
6
+ * 1. a hook-payload path (`transcript_path` from
7
+ * UserPromptSubmit/SessionStart/SessionEnd; `agent_transcript_path`
8
+ * from Stop — capability-matrix Table A), empty strings skipped
9
+ * (InstructionsLoaded carries `""`, workbuddy-session-transcript-access
10
+ * §6.2);
11
+ * 2. the deterministic derivation
12
+ * `<home>/.workbuddy/projects/<encodeCwd(cwd)>/<sessionId>.jsonl`.
13
+ *
14
+ * Validation mirrors the Codex locator model: absolute path, `..` traversal
15
+ * rejection, native canonicalization (symlink/junction escape), containment
16
+ * under the projects root, the main-session file-name contract
17
+ * (`<uuid>.jsonl` DIRECTLY inside a project directory — subagent files
18
+ * under `<parent>/subagents/agent-*.jsonl` are P3 scope and rejected here),
19
+ * and a regular-file requirement with pre-open identity capture for the
20
+ * port's post-open TOCTOU revalidation.
21
+ */
22
+ import fs from 'node:fs';
23
+ import path from 'node:path';
24
+ import { encodeWorkbuddyCwd } from './encode-cwd.js';
25
+ const SESSION_FILE_NAME = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.jsonl$/;
26
+ /** Canonicalize to the final long form (native realpath first; 8.3-safe, mirrors the Codex locator). */
27
+ function canonicalizePath(target) {
28
+ try {
29
+ return fs.realpathSync.native(target);
30
+ }
31
+ catch {
32
+ return fs.realpathSync(target);
33
+ }
34
+ }
35
+ function hasParentTraversal(value) {
36
+ return value.split(/[\\/]+/).includes('..');
37
+ }
38
+ /** Projects root: `<home>/.workbuddy/projects` (engine-side join, forensics §2.2). */
39
+ export function workbuddyProjectsRoot(home) {
40
+ return path.join(home, '.workbuddy', 'projects');
41
+ }
42
+ /**
43
+ * Authorize one transcript path against the WorkBuddy projects root.
44
+ *
45
+ * Rejects non-absolute input, `..` segments, non-`<uuid>.jsonl` names, paths
46
+ * whose native canonical form escapes the root, non-regular files and
47
+ * subagent-nested files. On success returns the native canonical path, the
48
+ * parsed session identity and the pre-open file identity.
49
+ */
50
+ export function validateWorkbuddyTranscriptPath(transcriptPath, projectsRoot) {
51
+ if (!path.isAbsolute(transcriptPath) || hasParentTraversal(transcriptPath)) {
52
+ return { ok: false, reason: 'transcript_path_invalid', nextAction: 'WorkBuddy must supply an absolute transcript path without traversal segments.' };
53
+ }
54
+ if (!SESSION_FILE_NAME.test(path.basename(transcriptPath))) {
55
+ return { ok: false, reason: 'transcript_path_invalid', nextAction: 'the transcript file name does not match the WorkBuddy main-session contract (<sessionId>.jsonl).' };
56
+ }
57
+ let canonicalRoot;
58
+ let canonicalPath;
59
+ try {
60
+ canonicalRoot = canonicalizePath(projectsRoot);
61
+ canonicalPath = canonicalizePath(transcriptPath);
62
+ }
63
+ catch {
64
+ return { ok: false, reason: 'transcript_path_invalid', nextAction: 'the transcript path (or the WorkBuddy projects root) does not resolve to an existing location.' };
65
+ }
66
+ const relative = path.relative(canonicalRoot, canonicalPath);
67
+ if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) {
68
+ return { ok: false, reason: 'transcript_path_outside_projects_root', nextAction: 'the transcript is not inside the WorkBuddy projects root; refusing to read outside the host transcript store.' };
69
+ }
70
+ // Main sessions sit DIRECTLY inside a project directory; anything deeper
71
+ // (subagents/agent-*.jsonl, P3 scope) is not a P2 ingestion source.
72
+ if (relative.split(/[\\/]+/).length !== 2) {
73
+ return { ok: false, reason: 'transcript_path_not_main_session', nextAction: 'only main-session transcripts are ingested in P2; subagent transcripts are follow-up scope.' };
74
+ }
75
+ let stats;
76
+ try {
77
+ stats = fs.statSync(canonicalPath);
78
+ }
79
+ catch {
80
+ return { ok: false, reason: 'transcript_path_invalid', nextAction: 'the transcript file disappeared during validation.' };
81
+ }
82
+ if (!stats.isFile()) {
83
+ return { ok: false, reason: 'transcript_path_invalid', nextAction: 'the transcript path is not a regular file.' };
84
+ }
85
+ const sessionIdentity = path.basename(canonicalPath, '.jsonl').toLowerCase();
86
+ return {
87
+ ok: true,
88
+ canonicalPath,
89
+ sessionIdentity,
90
+ identity: { dev: stats.dev, ino: Number(stats.ino), size: stats.size, mtimeMs: stats.mtimeMs },
91
+ };
92
+ }
93
+ /** Encode a cwd into ONE safe path segment; null when the result is empty or NUL-bearing. */
94
+ function encodeCwdSafe(cwd) {
95
+ const encoded = encodeWorkbuddyCwd(cwd);
96
+ // An encoded cwd becomes ONE path segment; separators were collapsed, so
97
+ // only a NUL or an all-separator input could still threaten the join.
98
+ if (encoded.length === 0 || encoded.includes('\0'))
99
+ return null;
100
+ return encoded;
101
+ }
102
+ /**
103
+ * Deterministic derivation (fallback when no hook payload path exists):
104
+ * `<home>/.workbuddy/projects/<encodeCwd(cwd)>/<sessionId>.jsonl`. Returns
105
+ * null when the session identity or cwd cannot produce a contract-shaped
106
+ * path — the caller degrades, it never scans for a "latest" file.
107
+ */
108
+ export function deriveWorkbuddyTranscriptPath(input) {
109
+ if (input.sessionId.length === 0 || input.cwd.length === 0)
110
+ return null;
111
+ if (!SESSION_FILE_NAME.test(`${input.sessionId.toLowerCase()}.jsonl`))
112
+ return null;
113
+ const encoded = encodeCwdSafe(input.cwd);
114
+ if (encoded === null)
115
+ return null;
116
+ return path.join(workbuddyProjectsRoot(input.home), encoded, `${input.sessionId.toLowerCase()}.jsonl`);
117
+ }
@@ -0,0 +1,15 @@
1
+ import type { TranscriptSourceAdapter } from '@principles/host-runtime';
2
+ /** Single-session alert threshold (tech design §12). */
3
+ export declare const WORKBUDDY_SINGLE_SESSION_ALERT_BYTES: number;
4
+ export interface WorkbuddyTranscriptSourceContext {
5
+ /** `now` for fallback observedAt stamps (tests inject a fixed clock). */
6
+ readonly now: Date;
7
+ /** Home override for tests; production falls back to the OS home directory. */
8
+ readonly home?: string | undefined;
9
+ }
10
+ /**
11
+ * Build the WorkBuddy {@link TranscriptSourceAdapter} for the host-neutral
12
+ * conversation-ingestion seam. Locating is deterministic (hint first, then the
13
+ * encoded-cwd derivation); decoding is the flat-record projection below.
14
+ */
15
+ export declare function createWorkbuddyTranscriptSource(context: WorkbuddyTranscriptSourceContext): TranscriptSourceAdapter;
@@ -0,0 +1,152 @@
1
+ /**
2
+ * WorkBuddy transcript source adapter for the host-neutral
3
+ * conversation-ingestion seam (PRI-1171 P2; SPEC v0.2 §4.1/§4.4, tech
4
+ * design §5).
5
+ *
6
+ * Everything WorkBuddy-specific about LOCATING and DECODING a session
7
+ * transcript lives here (the seam stays format-agnostic):
8
+ * - locate: hook-payload paths first (empty strings skipped —
9
+ * InstructionsLoaded carries `""`, forensics §6.2), then the
10
+ * deterministic `<home>/.workbuddy/projects/<encodeCwd(cwd)>/
11
+ * <sessionId>.jsonl` derivation. No directory scan, no "latest" guess;
12
+ * - decodeWindow: the flat-record projection (transcript-decoder.ts) with
13
+ * synthesized ordinals seeded from the committed checkpoint;
14
+ * - no host contract guard (the WorkBuddy engine auto-updates and the
15
+ * record contract is tolerated, not version-pinned — new variants are
16
+ * visible as `wb_unknown_record_type` warnings, never guessed);
17
+ * - compactionTimestamp is ALWAYS null: WorkBuddy compaction only appends
18
+ * a summary record (history stays valid), and the store treats that
19
+ * parameter as an active tombstone (tech design §5.4);
20
+ * - single-session size alert: a transcript over 50MB reports
21
+ * `wb_transcript_oversized:<bytes>` (tech design §12) — batched
22
+ * catch-up keeps ingesting, the health surface shows the lag.
23
+ */
24
+ import fs from 'node:fs';
25
+ import os from 'node:os';
26
+ import { deriveWorkbuddyTranscriptPath, validateWorkbuddyTranscriptPath, workbuddyProjectsRoot } from './transcript-path.js';
27
+ import { decodeWorkbuddyTranscriptWindow } from './transcript-decoder.js';
28
+ /** Single-session alert threshold (tech design §12). */
29
+ export const WORKBUDDY_SINGLE_SESSION_ALERT_BYTES = 50 * 1024 * 1024;
30
+ /** Keep a hint only when it carries content (InstructionsLoaded sends `""`, forensics §6.2). */
31
+ function nonEmptyHint(value) {
32
+ return typeof value === 'string' && value.length > 0 ? value : null;
33
+ }
34
+ /** True only for an existing regular file; any stat failure is "absent", never a throw. */
35
+ function existsFile(target) {
36
+ try {
37
+ return fs.statSync(target).isFile();
38
+ }
39
+ catch {
40
+ return false;
41
+ }
42
+ }
43
+ /**
44
+ * Build the WorkBuddy {@link TranscriptSourceAdapter} for the host-neutral
45
+ * conversation-ingestion seam. Locating is deterministic (hint first, then the
46
+ * encoded-cwd derivation); decoding is the flat-record projection below.
47
+ */
48
+ export function createWorkbuddyTranscriptSource(context) {
49
+ return {
50
+ hostKind: 'workbuddy',
51
+ /**
52
+ * Resolve the session transcript, in priority order: a non-empty hook
53
+ * hint (validated AND identity-bound to this hook's session), then the
54
+ * deterministic `<projects>/<encodeCwd(cwd)>/<sessionId>.jsonl` path.
55
+ * Never scans directories; every refusal carries a reason + nextAction.
56
+ */
57
+ locate(session, hints, env) {
58
+ const home = env.home ?? context.home ?? os.homedir();
59
+ const projectsRoot = workbuddyProjectsRoot(home);
60
+ // 1. Hook-payload paths, empty strings skipped (forensics §6.2).
61
+ const hinted = nonEmptyHint(hints.transcriptPath) ?? nonEmptyHint(hints.agentTranscriptPath);
62
+ if (hinted !== null) {
63
+ const validated = validateWorkbuddyTranscriptPath(hinted, projectsRoot);
64
+ if (!validated.ok)
65
+ return { status: 'degraded', reason: validated.reason, nextAction: validated.nextAction };
66
+ // Session binding (P2 review): a contract-shaped path inside the
67
+ // projects root can still belong to ANOTHER session. Reading it would
68
+ // file that session's evidence under this hook's rollout identity, so
69
+ // the path's identity must equal the host session identity. The check
70
+ // compares the PARSED identity, never just the file name shape.
71
+ const hookSessionId = session.sessionId.trim().toLowerCase();
72
+ if (hookSessionId.length === 0) {
73
+ return {
74
+ status: 'degraded',
75
+ reason: 'transcript_session_unverified',
76
+ nextAction: 'the hook payload has no session_id, so the transcript path cannot be bound to this session; nothing is read.',
77
+ };
78
+ }
79
+ if (validated.sessionIdentity !== hookSessionId) {
80
+ return {
81
+ status: 'degraded',
82
+ reason: 'transcript_session_mismatch',
83
+ nextAction: `the hinted transcript belongs to session ${validated.sessionIdentity}, not ${hookSessionId}; PD refuses to read another session's evidence.`,
84
+ };
85
+ }
86
+ return { status: 'ok', filePath: validated.canonicalPath, expectedIdentity: validated.identity, sessionIdentity: validated.sessionIdentity };
87
+ }
88
+ // 2. Deterministic derivation from the session identity + cwd.
89
+ const derived = deriveWorkbuddyTranscriptPath({ home, cwd: session.cwd ?? '', sessionId: session.sessionId });
90
+ if (derived === null) {
91
+ return { status: 'degraded', reason: 'transcript_unavailable', nextAction: 'no hook transcript path and no derivable session transcript; nothing is read or fabricated.' };
92
+ }
93
+ const validated = validateWorkbuddyTranscriptPath(derived, projectsRoot);
94
+ if (!validated.ok && validated.reason === 'transcript_path_invalid' && !existsFile(derived)) {
95
+ // The derived session file simply does not exist yet — neutral
96
+ // unavailability, not an invalid payload.
97
+ return { status: 'degraded', reason: 'transcript_unavailable', nextAction: 'no WorkBuddy transcript exists yet for this session; nothing is read or fabricated.' };
98
+ }
99
+ if (!validated.ok)
100
+ return { status: 'degraded', reason: validated.reason, nextAction: validated.nextAction };
101
+ // Same session binding as the hinted branch (P2 review): the derived
102
+ // file name is shaped from the session id, but a symlinked
103
+ // <sessionId>.jsonl can resolve to ANOTHER session's transcript. Only the
104
+ // canonical identity is authoritative; never file another session's
105
+ // evidence under this session.
106
+ const derivedSessionId = session.sessionId.trim().toLowerCase();
107
+ if (derivedSessionId.length === 0 || validated.sessionIdentity !== derivedSessionId) {
108
+ return {
109
+ status: 'degraded',
110
+ reason: 'transcript_session_mismatch',
111
+ nextAction: `the derived transcript resolves to session ${validated.sessionIdentity}, not ${derivedSessionId}; PD refuses to read another session's evidence.`,
112
+ };
113
+ }
114
+ return { status: 'ok', filePath: validated.canonicalPath, expectedIdentity: validated.identity, sessionIdentity: validated.sessionIdentity };
115
+ },
116
+ /**
117
+ * Project one byte window into observations. No host contract guard
118
+ * (records are tolerated, not version-pinned), ordinals are seeded from
119
+ * the checkpoint, and `compactionTimestamp` is ALWAYS null (§5.4).
120
+ */
121
+ decodeWindow(locator, window, checkpoint) {
122
+ const decoded = decodeWorkbuddyTranscriptWindow({
123
+ bytes: window.bytes,
124
+ fileOffset: window.fileOffset,
125
+ byteBoundReached: window.byteBoundReached,
126
+ sessionIdentity: locator.sessionIdentity,
127
+ startOrdinal: checkpoint !== null ? checkpoint.lastOrdinal + 1 : 0,
128
+ nowIso: context.now.toISOString(),
129
+ });
130
+ const warnings = [...decoded.warnings];
131
+ if (window.fileSize > WORKBUDDY_SINGLE_SESSION_ALERT_BYTES) {
132
+ warnings.push(`wb_transcript_oversized:${window.fileSize}`);
133
+ }
134
+ return {
135
+ observations: decoded.observations,
136
+ rollout: {
137
+ rootSessionId: checkpoint?.rootSessionId ?? locator.sessionIdentity,
138
+ },
139
+ guard: null,
140
+ // §5.4 hard guardrail: NEVER pass a compaction tombstone for
141
+ // WorkBuddy — jsonl history stays valid after compaction.
142
+ compactionTimestamp: null,
143
+ rollbackTurns: [],
144
+ stop: decoded.stop,
145
+ nextByteOffset: decoded.nextByteOffset,
146
+ lastOrdinal: decoded.lastOrdinal,
147
+ warnings,
148
+ fileSize: window.fileSize,
149
+ };
150
+ },
151
+ };
152
+ }
@@ -13,5 +13,13 @@ export interface WorkbuddyEvidenceContext {
13
13
  warn: (diagnosticLine: string) => void;
14
14
  }
15
15
  export declare function annotateContextWarnings(warnings: readonly string[]): string[];
16
+ /**
17
+ * Handle one WorkBuddy hook invocation end-to-end: parse stdin, decode the
18
+ * host event, run the PD host adapter, and shape the channel-specific result.
19
+ *
20
+ * Pre-decode failures route through {@link channelFailure} so a blocking
21
+ * channel exits 2 while UserPromptSubmit never clears the user's prompt.
22
+ * A rejected Owner statement never grants authority or bypasses decoding.
23
+ */
16
24
  export declare function processWorkbuddyHookInvocation(rawStdin: string, channelEventName: string | undefined, _env?: EnvMap): Promise<WorkBuddyPdHookResult>;
17
25
  export {};
@@ -37,7 +37,7 @@ import path from 'node:path';
37
37
  import process from 'node:process';
38
38
  import { pathToFileURL, fileURLToPath } from 'node:url';
39
39
  import { appendEventLogLine, redactTelemetryString, isRuleHostEvaluatedEventData } from '@principles/core/runtime';
40
- import { createProductionHostRuntime, createWorkbuddyRuleContextProvider, loadPdConfigForPlugin, parseOwnerStatementPrefix, assessWorkbuddyCorrectionCandidate, resolveSharedCorrectionKeywordStoreForDetection, admitTrustedWorkbuddyLiveCorrection, ensureGovernanceDiagnosticianTask, resolveHostToolSemanticsForHook } from '@principles/host-runtime';
40
+ import { createAdaptivePriorityProviderForConfig, createProductionHostRuntime, createWorkbuddyRuleContextProvider, loadPdConfigForPlugin, parseOwnerStatementPrefix, assessWorkbuddyCorrectionCandidate, resolveSharedCorrectionKeywordStoreForDetection, admitTrustedWorkbuddyLiveCorrection, ensureGovernanceDiagnosticianTask, resolveHostToolSemanticsForHook } from '@principles/host-runtime';
41
41
  import { computeFeatureFlagsFromConfig } from '@principles/core/runtime';
42
42
  import { WorkBuddyHooksHostAdapter } from './host-adapter.js';
43
43
  import { WORKBUDDY_TOOL_SEMANTIC_MAPPINGS, WORKBUDDY_TOOL_SEMANTICS } from './tool-semantics.js';
@@ -45,6 +45,7 @@ import { resolveWorkbuddyWorkspace } from './workspace-resolution.js';
45
45
  import { WorkBuddyDecoderError, WorkBuddyEncoderError, isWorkBuddyHookOutput, WORKBUDDY_EVENT_PRE_TOOL_USE } from './codec/index.js';
46
46
  import { recordWorkbuddyOwnerStatement } from './explicit-owner-statement.js';
47
47
  import { recordWorkbuddyPromptDeliveryEvidence, recordWorkbuddyDenyEvidence } from './workbuddy-evidence-recorder.js';
48
+ import { ingestWorkbuddyConversation } from './ingestion/ingestion.js';
48
49
  const MAX_DIAGNOSTIC = 500;
49
50
  function bound(text) {
50
51
  return text.replace(/\s+/g, ' ').trim().slice(0, MAX_DIAGNOSTIC);
@@ -191,6 +192,14 @@ function channelFailure(channelEventName, reason, nextAction) {
191
192
  // PostToolUse/SessionStart: nothing blockable exists on those channels.
192
193
  return neutralWithDiagnostics([line]);
193
194
  }
195
+ /**
196
+ * Handle one WorkBuddy hook invocation end-to-end: parse stdin, decode the
197
+ * host event, run the PD host adapter, and shape the channel-specific result.
198
+ *
199
+ * Pre-decode failures route through {@link channelFailure} so a blocking
200
+ * channel exits 2 while UserPromptSubmit never clears the user's prompt.
201
+ * A rejected Owner statement never grants authority or bypasses decoding.
202
+ */
194
203
  export async function processWorkbuddyHookInvocation(rawStdin, channelEventName, _env = process.env) {
195
204
  let parsed;
196
205
  try {
@@ -372,6 +381,35 @@ export async function processWorkbuddyHookInvocation(rawStdin, channelEventName,
372
381
  return neutralWithDiagnostics([diagnostic('degraded', health.reason ?? 'runtime_unhealthy', health.nextAction ?? 'Inspect the governance workspace runtime.')]);
373
382
  return neutralWithDiagnostics([]);
374
383
  }
384
+ if (event.kind === 'turn_complete') {
385
+ // PRI-1171 P2 ticket ⑤: the authenticated Stop hook is the ingestion
386
+ // trigger. Neutral output is MANDATORY — WorkBuddy injects any stdout
387
+ // into model-visible context (P04). Flag-off stays completely silent so
388
+ // the pre-wiring behavior is unchanged; the consent gate and the
389
+ // transcript port are both inside ingestWorkbuddyConversation.
390
+ if (flags.workbuddy_conversation_ingestion?.enabled !== true) {
391
+ return neutralWithDiagnostics([]);
392
+ }
393
+ const ingestion = ingestWorkbuddyConversation({
394
+ workspaceDir: resolution.workspaceDir,
395
+ rawPayload: event.rawPayload,
396
+ sessionId: event.context.sessionId,
397
+ ...(projectDir !== undefined ? { cwd: projectDir } : {}),
398
+ ingestionEnabled: true,
399
+ now: hookEpoch,
400
+ });
401
+ if (ingestion.status === 'ingested') {
402
+ // A successful ingestion that skipped routine records is NOT degraded:
403
+ // `wb_skipped:*` is the decoder's normal "this record is not Owner
404
+ // evidence" channel. Only the remaining warnings describe something
405
+ // that needs investigation, so they keep the degraded status (rc-9:
406
+ // every skip stays observable, but the severity must be honest).
407
+ return neutralWithDiagnostics(ingestion.warnings.slice(0, 2).map((warning) => diagnostic(warning.startsWith('wb_skipped') ? 'skipped' : 'degraded', warning, 'Inspect the WorkBuddy transcript and the governance trajectory checkpoint; ingestion warnings are bounded and non-blocking.')));
408
+ }
409
+ if (ingestion.status === 'skipped')
410
+ return neutralWithDiagnostics([]);
411
+ return neutralWithDiagnostics([diagnostic('degraded', ingestion.reason, ingestion.nextAction)]);
412
+ }
375
413
  const evidenceDiagnostics = [];
376
414
  const evidenceContext = {
377
415
  workspaceDir: resolution.workspaceDir,
@@ -392,9 +430,28 @@ export async function processWorkbuddyHookInvocation(rawStdin, channelEventName,
392
430
  ? toolSemanticsResolution.registry
393
431
  : WORKBUDDY_TOOL_SEMANTICS;
394
432
  const toolSemanticsDiagnostics = toolSemanticsResolution.ok
395
- ? []
433
+ // ADR-0030: a legacy persisted declaration still loads (degraded to
434
+ // defaults) and must be visible on stderr (rc-9).
435
+ ? toolSemanticsResolution.warnings.map((warning) => diagnostic('degraded', warning, 're-run this host so it refreshes its persisted tool declaration'))
396
436
  : [diagnostic('degraded', toolSemanticsResolution.reason, toolSemanticsResolution.nextAction)];
437
+ const adaptive = event.kind === 'before_prompt_build' && flags['host.workbuddy.adaptive_activation']?.enabled === true
438
+ ? createAdaptivePriorityProviderForConfig(config.effective.config, resolution.workspaceDir, {
439
+ flag: 'host.workbuddy.adaptive_activation',
440
+ env: _env,
441
+ // The declared UserPromptSubmit timeout is 15 s. Bound the optional
442
+ // work well inside that budget, including this process's startup.
443
+ outerDeadlineAt: Date.now() + Math.max(0, 5000 - Math.round(process.uptime() * 1000)),
444
+ onDiagnostic: (line) => {
445
+ if (line.status !== 'selected')
446
+ evidenceDiagnostics.push(diagnostic(line.status === 'unavailable' ? 'degraded' : 'skipped', `adaptive_selection_${line.status}:${line.reason}`, 'Check Adaptive configuration or use Native assembly.'));
447
+ },
448
+ })
449
+ : undefined;
450
+ if (adaptive && !adaptive.ok) {
451
+ evidenceDiagnostics.push(diagnostic('degraded', `adaptive_activation_${adaptive.readiness}:${adaptive.reason}`, adaptive.nextAction));
452
+ }
397
453
  const result = await createProductionHostRuntime({
454
+ ...(adaptive?.ok ? { adaptiveGapProvider: adaptive.provider } : {}),
398
455
  ...(projectDir !== undefined ? { projectDir } : {}),
399
456
  hostKind: 'workbuddy',
400
457
  toolSemantics,
@@ -1,6 +1,9 @@
1
1
  import { type InternalizationConsumerCycleOutcome, type ConsumerCycleLogger, type ReconcileGovernanceContinuationResult, type SignalLlmClassifier, type Stage2CorrectionCycleReport } from '@principles/host-runtime';
2
+ import { type WorkbuddyCatchUpResult } from '../ingestion/catch-up.js';
2
3
  export type WorkbuddyWorkerMode = 'ready' | 'manual_action_required' | 'paused' | 'degraded';
3
4
  export interface WorkbuddyWorkerCycleStepReport {
5
+ /** PRI-1171 P2 ticket ⑤: bounded transcript catch-up, before reconciliation. */
6
+ readonly catchUp: WorkbuddyCatchUpResult;
4
7
  readonly reconcile: ReconcileGovernanceContinuationResult;
5
8
  /** At most ONE diagnostician execution per cycle (bounded work). */
6
9
  readonly diagnostician: {
@@ -19,6 +22,12 @@ export interface WorkbuddyWorkerCycleResult {
19
22
  readonly mode: WorkbuddyWorkerMode;
20
23
  readonly reason?: string;
21
24
  readonly nextAction?: string;
25
+ /**
26
+ * Degradations that did NOT decide the cycle mode. A `paused` cycle still
27
+ * runs catch-up, so its degradation must stay visible instead of being
28
+ * swallowed by the paused early return (P2 review).
29
+ */
30
+ readonly degradations?: readonly string[];
22
31
  readonly report?: WorkbuddyWorkerCycleStepReport;
23
32
  }
24
33
  export interface WorkbuddyWorkerCycleOptions {
@@ -2,10 +2,12 @@
2
2
  * WorkBuddy Workspace worker cycle (SPEC workbuddy-host-adapter §5 Part 5;
3
3
  * ADR-0020 §11.1 shape, third host instance).
4
4
  *
5
- * ONE Workspace-scoped worker cycle with exactly two background
6
- * responsibilities — the Codex catch-up step is DELIBERATELY ABSENT because
7
- * the WorkBuddy MVP excludes transcript ingestion (SPEC §1 Excluded; the
8
- * hook itself is the only evidence producer):
5
+ * ONE Workspace-scoped worker cycle with three bounded background
6
+ * responsibilities (PRI-1171 P2 tickets ⑤/⑥): transcript catch-up (gated by
7
+ * workbuddy_conversation_ingestion AND the v3 consent ledger), idempotent
8
+ * reconciliation, and one diagnostician/consumer pass. Catch-up runs BEFORE
9
+ * the paused early-return so hook lag keeps draining even while execution is
10
+ * off. Flag-off performs zero transcript I/O.
9
11
  *
10
12
  * 1. run the idempotent reconciliation pass (shared host-runtime authority)
11
13
  * 2. lease + run one Diagnostician execution, then ONE bounded downstream
@@ -30,8 +32,9 @@
30
32
  import fs from 'node:fs';
31
33
  import path from 'node:path';
32
34
  import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime';
33
- import { loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, saveHostToolDeclaration, } from '@principles/host-runtime';
35
+ import { loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
34
36
  import { WORKBUDDY_TOOL_SEMANTICS, WORKBUDDY_TOOL_SEMANTIC_MAPPINGS } from '../tool-semantics.js';
37
+ import { catchUpWorkbuddyIngestion } from '../ingestion/catch-up.js';
35
38
  const WORKER_OWNER = 'companion-worker';
36
39
  const DEFAULT_DIAG_CANDIDATE_LIMIT = 5;
37
40
  function workerLogger(logger) {
@@ -98,8 +101,27 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
98
101
  // no degraded mode; reconciliation and downstream keep running.
99
102
  const capability = resolveDiagnosticianCapability(config.effective);
100
103
  const diagnosticianDisabled = !capability.available;
101
- // Step 2 — Idempotent reconciliation (always runs; creates no LLM work).
102
- const reconcile = await reconcileGovernanceContinuation({ workspaceDir, conversationIngestionEnabled: false });
104
+ // Step 2 — Bounded transcript catch-up (PRI-1171 P2 ⑤). Runs BEFORE the
105
+ // consumer paused early-return, and performs ZERO transcript I/O when the
106
+ // flag or the consent record is off (both gates live in the orchestrator).
107
+ const ingestionEnabled = flags.workbuddy_conversation_ingestion?.enabled === true;
108
+ const catchUp = catchUpWorkbuddyIngestion({
109
+ workspaceDir,
110
+ ingestionEnabled,
111
+ ...(options.now !== undefined ? { now: options.now } : {}),
112
+ });
113
+ // Step 3 — Idempotent reconciliation (always runs; creates no LLM work).
114
+ // `codexConversationIngestionEnabled` gates the CODEX-only promotion
115
+ // recovery (it promotes Codex transcript evidence). The WorkBuddy worker has
116
+ // no authority over that consent, so it never passes its own flag: doing so
117
+ // would let opting into WorkBuddy ingestion unlock promotion of Codex
118
+ // session evidence after a Codex opt-out.
119
+ const reconcile = await reconcileGovernanceContinuation({
120
+ workspaceDir,
121
+ codexConversationIngestionEnabled: false,
122
+ // Legacy alias: both names must stay false for an older host-runtime.
123
+ conversationIngestionEnabled: false,
124
+ });
103
125
  // Steps 3–5 — execution authority: internalization_auto_consumer.
104
126
  let diagnostician = null;
105
127
  if (diagnosticianDisabled) {
@@ -116,7 +138,13 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
116
138
  mode: 'paused',
117
139
  reason: 'internalization_auto_consumer_disabled',
118
140
  nextAction: 'Automatic internalization execution is paused for this governance workspace; manual commands remain available: pd diagnose, pd runtime internalization run-once.',
119
- report: { reconcile, diagnostician: null, downstream: null },
141
+ // Catch-up ran BEFORE this early return. Keeping its degradation on the
142
+ // paused result means `pd workbuddy worker --once` can still report a
143
+ // broken transcript catch-up instead of exiting as a clean pause.
144
+ ...(catchUp.status === 'degraded'
145
+ ? { degradations: [`catch_up:${catchUp.reason ?? 'degraded'}`] }
146
+ : {}),
147
+ report: { catchUp, reconcile, diagnostician: null, downstream: null },
120
148
  };
121
149
  }
122
150
  else {
@@ -165,7 +193,7 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
165
193
  mode: 'degraded',
166
194
  reason: `diagnostician_execution_failed:${detail}`,
167
195
  nextAction: 'Inspect the governance workspace runtime profile and provider configuration; the task keeps its pending/retry state and no evidence was mutated.',
168
- report: { reconcile, diagnostician: null, downstream: null },
196
+ report: { catchUp, reconcile, diagnostician: null, downstream: null },
169
197
  };
170
198
  }
171
199
  }
@@ -173,7 +201,7 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
173
201
  // with the WorkBuddy host declaration (probe-verified tool names: Read /
174
202
  // Write / Edit / Bash are capitalized) persisted for host-neutral consumers.
175
203
  const declared = saveHostToolDeclaration(workspaceDir, {
176
- version: 1,
204
+ version: HOST_TOOL_DECLARATION_VERSION,
177
205
  hostKind: 'workbuddy',
178
206
  mappings: WORKBUDDY_TOOL_SEMANTIC_MAPPINGS,
179
207
  declaredAt: new Date().toISOString(),
@@ -185,7 +213,7 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
185
213
  mode: 'degraded',
186
214
  reason: `host_tool_declaration_persist_failed:${declared.reason}`,
187
215
  nextAction: 'Repair WorkBuddy host declaration persistence (.pd/host-tool-semantics/workbuddy.json) before running the downstream internalization cycle; the worker retries automatically on the next cycle.',
188
- report: { reconcile, diagnostician, downstream: null },
216
+ report: { catchUp, reconcile, diagnostician, downstream: null },
189
217
  };
190
218
  }
191
219
  const downstream = await runInternalizationConsumerCycle(workspaceDir, {
@@ -217,15 +245,16 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
217
245
  onEvent: emitEvent,
218
246
  });
219
247
  const degradedReason = !reconcile.ok ? `reconcile:${reconcile.reason ?? 'failed'}`
220
- : diagnostician?.status === 'failed' && diagnostician.errorCategory !== 'lease_conflict' ? `diagnostician_failed:${diagnostician.message ?? 'max_attempts_exceeded'}`
221
- : diagnostician?.status === 'degraded' ? `diagnostician_degraded:${diagnostician.message ?? 'unknown'}`
222
- : downstream.skipReason === 'runtime_config_error' || downstream.skipReason === 'cycle_error' || downstream.skipReason === 'config_malformed' ? `downstream:${downstream.skipReason}`
223
- : !stage2.ok ? `stage2:${stage2.reason ?? 'failed'}`
224
- : undefined;
248
+ : catchUp.status === 'degraded' ? `catch_up:${catchUp.reason ?? 'degraded'}`
249
+ : diagnostician?.status === 'failed' && diagnostician.errorCategory !== 'lease_conflict' ? `diagnostician_failed:${diagnostician.message ?? 'max_attempts_exceeded'}`
250
+ : diagnostician?.status === 'degraded' ? `diagnostician_degraded:${diagnostician.message ?? 'unknown'}`
251
+ : downstream.skipReason === 'runtime_config_error' || downstream.skipReason === 'cycle_error' || downstream.skipReason === 'config_malformed' ? `downstream:${downstream.skipReason}`
252
+ : !stage2.ok ? `stage2:${stage2.reason ?? 'failed'}`
253
+ : undefined;
225
254
  return {
226
255
  ...base,
227
256
  mode: degradedReason !== undefined ? 'degraded' : 'ready',
228
257
  ...(degradedReason !== undefined ? { reason: degradedReason, nextAction: 'Inspect the governance workspace .pd/config.yaml runtime profile and the per-step report above; the worker retries automatically on the next cycle.' } : {}),
229
- report: { reconcile, diagnostician, downstream, stage2 },
258
+ report: { catchUp, reconcile, diagnostician, downstream, stage2 },
230
259
  };
231
260
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/workbuddy-adapter",
3
- "version": "0.5.11",
3
+ "version": "0.6.0",
4
4
  "description": "WorkBuddy host adapter for Principles Disciple — implements the HostAdapter interface for WorkBuddy's Git Bash command-hook model (ADR-0020 third host, SPEC workbuddy-host-adapter v0.3.0).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -57,6 +57,17 @@
57
57
  }
58
58
  ]
59
59
  }
60
+ ],
61
+ "Stop": [
62
+ {
63
+ "hooks": [
64
+ {
65
+ "type": "command",
66
+ "command": "node \"${CODEBUDDY_PLUGIN_ROOT}/scripts/wrapper.cjs\" Stop",
67
+ "timeout": 30
68
+ }
69
+ ]
70
+ }
60
71
  ]
61
72
  }
62
73
  }