create-principles-disciple 1.155.2 → 1.156.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 (247) hide show
  1. package/_release/product-identity.json +2 -2
  2. package/codex-adapter/dist/ingestion/pain-receipt-fallback.d.ts +28 -1
  3. package/codex-adapter/dist/ingestion/pain-receipt-fallback.js +53 -17
  4. package/codex-adapter/dist/worker/workspace-worker.js +86 -66
  5. package/codex-adapter/package.json +1 -1
  6. package/console/dist/server/index.d.ts +11 -1
  7. package/console/dist/server/index.js +84 -19
  8. package/console/dist/server/release-handover.d.ts +256 -0
  9. package/console/dist/server/release-handover.js +402 -0
  10. package/console/dist/server/routes/onboarding.js +1 -0
  11. package/console/dist/server/routes/update-transaction.js +37 -3
  12. package/console/dist/server/routes/update.js +21 -1
  13. package/console/dist/server/successor.d.ts +46 -0
  14. package/console/dist/server/successor.js +128 -0
  15. package/console/dist/web/assets/app.css +18 -0
  16. package/console/dist/web/assets/app.js +32 -31
  17. package/console/package.json +2 -2
  18. package/core/dist/runtime/candidate-intake-service.d.ts +1 -1
  19. package/core/dist/runtime/candidate-intake-service.d.ts.map +1 -1
  20. package/core/dist/runtime/candidate-intake-service.js +89 -12
  21. package/core/dist/runtime/candidate-intake-service.js.map +1 -1
  22. package/core/dist/runtime/context-payload.d.ts +11 -0
  23. package/core/dist/runtime/context-payload.d.ts.map +1 -1
  24. package/core/dist/runtime/context-payload.js +27 -0
  25. package/core/dist/runtime/context-payload.js.map +1 -1
  26. package/core/dist/runtime/host-submission-context.d.ts +13 -6
  27. package/core/dist/runtime/host-submission-context.d.ts.map +1 -1
  28. package/core/dist/runtime/host-submission-context.js +77 -8
  29. package/core/dist/runtime/host-submission-context.js.map +1 -1
  30. package/core/dist/runtime/index.d.ts +2 -1
  31. package/core/dist/runtime/index.d.ts.map +1 -1
  32. package/core/dist/runtime/index.js +8 -0
  33. package/core/dist/runtime/index.js.map +1 -1
  34. package/core/dist/runtime/pain-ingress.d.ts +8 -0
  35. package/core/dist/runtime/pain-ingress.d.ts.map +1 -1
  36. package/core/dist/runtime/pain-ingress.js +8 -1
  37. package/core/dist/runtime/pain-ingress.js.map +1 -1
  38. package/core/dist/runtime/pain-recall-read-model.d.ts +72 -0
  39. package/core/dist/runtime/pain-recall-read-model.d.ts.map +1 -1
  40. package/core/dist/runtime/pain-recall-read-model.js +46 -21
  41. package/core/dist/runtime/pain-recall-read-model.js.map +1 -1
  42. package/core/dist/runtime/pain-receipt-recovery.d.ts +4 -1
  43. package/core/dist/runtime/pain-receipt-recovery.d.ts.map +1 -1
  44. package/core/dist/runtime/pain-receipt-recovery.js +28 -10
  45. package/core/dist/runtime/pain-receipt-recovery.js.map +1 -1
  46. package/core/dist/runtime/pain-signal-bridge.d.ts +38 -23
  47. package/core/dist/runtime/pain-signal-bridge.d.ts.map +1 -1
  48. package/core/dist/runtime/pain-signal-bridge.js +533 -182
  49. package/core/dist/runtime/pain-signal-bridge.js.map +1 -1
  50. package/core/dist/runtime/pain-signal-runtime-factory.d.ts +8 -1
  51. package/core/dist/runtime/pain-signal-runtime-factory.d.ts.map +1 -1
  52. package/core/dist/runtime/pain-signal-runtime-factory.js +196 -25
  53. package/core/dist/runtime/pain-signal-runtime-factory.js.map +1 -1
  54. package/core/dist/runtime/pain-target-evidence-reconcile.d.ts +78 -4
  55. package/core/dist/runtime/pain-target-evidence-reconcile.d.ts.map +1 -1
  56. package/core/dist/runtime/pain-target-evidence-reconcile.js +229 -18
  57. package/core/dist/runtime/pain-target-evidence-reconcile.js.map +1 -1
  58. package/core/dist/runtime/pain-to-principle-service.d.ts +26 -5
  59. package/core/dist/runtime/pain-to-principle-service.d.ts.map +1 -1
  60. package/core/dist/runtime/pain-to-principle-service.js +63 -52
  61. package/core/dist/runtime/pain-to-principle-service.js.map +1 -1
  62. package/core/dist/runtime/store/candidate/admission-document.d.ts +43 -0
  63. package/core/dist/runtime/store/candidate/admission-document.d.ts.map +1 -1
  64. package/core/dist/runtime/store/candidate/admission-document.js +130 -0
  65. package/core/dist/runtime/store/candidate/admission-document.js.map +1 -1
  66. package/core/dist/runtime/store/candidate/candidate-store.d.ts +3 -1
  67. package/core/dist/runtime/store/candidate/candidate-store.d.ts.map +1 -1
  68. package/core/dist/runtime/store/candidate/memory-candidate-store.d.ts +2 -1
  69. package/core/dist/runtime/store/candidate/memory-candidate-store.d.ts.map +1 -1
  70. package/core/dist/runtime/store/candidate/memory-candidate-store.js +27 -1
  71. package/core/dist/runtime/store/candidate/memory-candidate-store.js.map +1 -1
  72. package/core/dist/runtime/store/candidate/sqlite-candidate-store.d.ts +2 -1
  73. package/core/dist/runtime/store/candidate/sqlite-candidate-store.d.ts.map +1 -1
  74. package/core/dist/runtime/store/candidate/sqlite-candidate-store.js +59 -2
  75. package/core/dist/runtime/store/candidate/sqlite-candidate-store.js.map +1 -1
  76. package/core/dist/runtime/store/context/sqlite-context-assembler.d.ts.map +1 -1
  77. package/core/dist/runtime/store/context/sqlite-context-assembler.js +18 -3
  78. package/core/dist/runtime/store/context/sqlite-context-assembler.js.map +1 -1
  79. package/core/dist/runtime/store/runtime-state-manager.d.ts +2 -1
  80. package/core/dist/runtime/store/runtime-state-manager.d.ts.map +1 -1
  81. package/core/dist/runtime/store/runtime-state-manager.js +4 -0
  82. package/core/dist/runtime/store/runtime-state-manager.js.map +1 -1
  83. package/core/dist/telemetry-event.d.ts +2 -2
  84. package/core/dist/telemetry-event.d.ts.map +1 -1
  85. package/core/dist/telemetry-event.js +5 -0
  86. package/core/dist/telemetry-event.js.map +1 -1
  87. package/core/package.json +1 -1
  88. package/dist/i18n.d.ts.map +1 -1
  89. package/dist/i18n.js +72 -0
  90. package/dist/i18n.js.map +1 -1
  91. package/dist/index.d.ts +15 -0
  92. package/dist/index.d.ts.map +1 -1
  93. package/dist/index.js +145 -35
  94. package/dist/index.js.map +1 -1
  95. package/dist/installer.d.ts +149 -9
  96. package/dist/installer.d.ts.map +1 -1
  97. package/dist/installer.js +562 -38
  98. package/dist/installer.js.map +1 -1
  99. package/dist/installers/codex-host-installer.js +1 -1
  100. package/dist/installers/codex-host-installer.js.map +1 -1
  101. package/dist/installers/index.d.ts +10 -0
  102. package/dist/installers/index.d.ts.map +1 -1
  103. package/dist/installers/index.js +4 -0
  104. package/dist/installers/index.js.map +1 -1
  105. package/dist/mvp-config.js +1 -1
  106. package/dist/mvp-config.js.map +1 -1
  107. package/dist/prompts.d.ts +36 -12
  108. package/dist/prompts.d.ts.map +1 -1
  109. package/dist/prompts.js +102 -30
  110. package/dist/prompts.js.map +1 -1
  111. package/dist/service-host-bridge.d.ts +71 -12
  112. package/dist/service-host-bridge.d.ts.map +1 -1
  113. package/dist/service-host-bridge.js +228 -48
  114. package/dist/service-host-bridge.js.map +1 -1
  115. package/dist/service-host-provisioning.d.ts +102 -0
  116. package/dist/service-host-provisioning.d.ts.map +1 -0
  117. package/dist/service-host-provisioning.js +595 -0
  118. package/dist/service-host-provisioning.js.map +1 -0
  119. package/dist/uninstaller.js +1 -1
  120. package/dist/uninstaller.js.map +1 -1
  121. package/dist/update/apply-payload.d.ts +9 -0
  122. package/dist/update/apply-payload.d.ts.map +1 -1
  123. package/dist/update/apply-payload.js +44 -2
  124. package/dist/update/apply-payload.js.map +1 -1
  125. package/dist/update/console-surface.d.ts +2 -1
  126. package/dist/update/console-surface.d.ts.map +1 -1
  127. package/dist/update/console-surface.js +6 -1
  128. package/dist/update/console-surface.js.map +1 -1
  129. package/dist/update/install-layout.d.ts +12 -0
  130. package/dist/update/install-layout.d.ts.map +1 -1
  131. package/dist/update/install-layout.js +49 -7
  132. package/dist/update/install-layout.js.map +1 -1
  133. package/dist/update/release-manager-authority.d.ts +16 -0
  134. package/dist/update/release-manager-authority.d.ts.map +1 -1
  135. package/dist/update/release-manager-authority.js +45 -3
  136. package/dist/update/release-manager-authority.js.map +1 -1
  137. package/dist/update/release-manager.d.ts +8 -3
  138. package/dist/update/release-manager.d.ts.map +1 -1
  139. package/dist/update/release-manager.js +29 -1
  140. package/dist/update/release-manager.js.map +1 -1
  141. package/dist/update/transaction-progress.d.ts +63 -0
  142. package/dist/update/transaction-progress.d.ts.map +1 -0
  143. package/dist/update/transaction-progress.js +207 -0
  144. package/dist/update/transaction-progress.js.map +1 -0
  145. package/dist/utils/env.d.ts +16 -1
  146. package/dist/utils/env.d.ts.map +1 -1
  147. package/dist/utils/env.js +55 -43
  148. package/dist/utils/env.js.map +1 -1
  149. package/host-runtime/dist/diagnostician-auto-run.js +37 -31
  150. package/host-runtime/dist/governance-observation-store.d.ts +38 -0
  151. package/host-runtime/dist/governance-observation-store.js +41 -0
  152. package/host-runtime/dist/governance-trajectory-turn-reader.js +26 -33
  153. package/host-runtime/package.json +1 -1
  154. package/install-layout/dist/background-execution-transition.d.ts +11 -1
  155. package/install-layout/dist/background-execution-transition.js +45 -1
  156. package/install-layout/dist/index.d.ts +3 -3
  157. package/install-layout/dist/index.js +10 -4
  158. package/install-layout/dist/pd-home.d.ts +12 -0
  159. package/install-layout/dist/pd-home.js +6 -1
  160. package/install-layout/package.json +1 -1
  161. package/package.json +10 -10
  162. package/pd-cli/dist/commands/candidate.d.ts +15 -0
  163. package/pd-cli/dist/commands/candidate.d.ts.map +1 -1
  164. package/pd-cli/dist/commands/candidate.js +449 -93
  165. package/pd-cli/dist/commands/candidate.js.map +1 -1
  166. package/pd-cli/dist/commands/console.d.ts.map +1 -1
  167. package/pd-cli/dist/commands/console.js +10 -0
  168. package/pd-cli/dist/commands/console.js.map +1 -1
  169. package/pd-cli/dist/commands/diagnose.d.ts.map +1 -1
  170. package/pd-cli/dist/commands/diagnose.js +254 -160
  171. package/pd-cli/dist/commands/diagnose.js.map +1 -1
  172. package/pd-cli/dist/commands/intake-outcome-guidance.d.ts +57 -0
  173. package/pd-cli/dist/commands/intake-outcome-guidance.d.ts.map +1 -0
  174. package/pd-cli/dist/commands/intake-outcome-guidance.js +206 -0
  175. package/pd-cli/dist/commands/intake-outcome-guidance.js.map +1 -0
  176. package/pd-cli/dist/commands/mcp-probe.d.ts.map +1 -1
  177. package/pd-cli/dist/commands/mcp-probe.js +1 -0
  178. package/pd-cli/dist/commands/mcp-probe.js.map +1 -1
  179. package/pd-cli/dist/commands/pain-record.d.ts.map +1 -1
  180. package/pd-cli/dist/commands/pain-record.js +18 -4
  181. package/pd-cli/dist/commands/pain-record.js.map +1 -1
  182. package/pd-cli/dist/commands/pain-retry.d.ts.map +1 -1
  183. package/pd-cli/dist/commands/pain-retry.js +91 -21
  184. package/pd-cli/dist/commands/pain-retry.js.map +1 -1
  185. package/pd-cli/dist/commands/runtime-uat.d.ts.map +1 -1
  186. package/pd-cli/dist/commands/runtime-uat.js +1 -0
  187. package/pd-cli/dist/commands/runtime-uat.js.map +1 -1
  188. package/pd-cli/dist/commands/service-lifecycle.js +1 -1
  189. package/pd-cli/dist/commands/service-lifecycle.js.map +1 -1
  190. package/pd-cli/dist/commands/service-run-once.d.ts +1 -1
  191. package/pd-cli/dist/commands/service-run-once.d.ts.map +1 -1
  192. package/pd-cli/dist/commands/service-run-once.js +9 -5
  193. package/pd-cli/dist/commands/service-run-once.js.map +1 -1
  194. package/pd-cli/dist/program.d.ts.map +1 -1
  195. package/pd-cli/dist/program.js +14 -3
  196. package/pd-cli/dist/program.js.map +1 -1
  197. package/pd-cli/dist/services/admission-write-gate.d.ts +4 -0
  198. package/pd-cli/dist/services/admission-write-gate.d.ts.map +1 -1
  199. package/pd-cli/dist/services/admission-write-gate.js +50 -48
  200. package/pd-cli/dist/services/admission-write-gate.js.map +1 -1
  201. package/pd-cli/dist/services/console-launcher.js +3 -3
  202. package/pd-cli/dist/services/console-launcher.js.map +1 -1
  203. package/pd-cli/dist/services/service-host/managed-run.d.ts.map +1 -1
  204. package/pd-cli/dist/services/service-host/managed-run.js +25 -8
  205. package/pd-cli/dist/services/service-host/managed-run.js.map +1 -1
  206. package/pd-cli/dist/services/service-host/scheduler/service-status.d.ts +12 -0
  207. package/pd-cli/dist/services/service-host/scheduler/service-status.d.ts.map +1 -1
  208. package/pd-cli/dist/services/service-host/scheduler/service-status.js +16 -7
  209. package/pd-cli/dist/services/service-host/scheduler/service-status.js.map +1 -1
  210. package/pd-cli/dist/services/service-host/status/service-run-status.d.ts +7 -5
  211. package/pd-cli/dist/services/service-host/status/service-run-status.d.ts.map +1 -1
  212. package/pd-cli/dist/services/service-host/status/service-run-status.js +1 -1
  213. package/pd-cli/dist/services/service-host/status/service-run-status.js.map +1 -1
  214. package/pd-cli/package.json +1 -1
  215. package/pd-mcp-server/dist/submit-assembly.js +61 -18
  216. package/pd-mcp-server/dist/version.d.ts +1 -1
  217. package/pd-mcp-server/dist/version.js +1 -1
  218. package/pd-mcp-server/package.json +1 -1
  219. package/plugin/dist/bundle.js +493 -493
  220. package/plugin/dist/openclaw-worker.js +263 -263
  221. package/plugin/dist/openclaw.plugin.json +1 -1
  222. package/plugin/openclaw.plugin.json +1 -1
  223. package/plugin/package.json +1 -1
  224. package/release-manager/dist/i18n.js +72 -0
  225. package/release-manager/dist/installer.js +562 -38
  226. package/release-manager/dist/installers/codex-host-installer.js +1 -1
  227. package/release-manager/dist/installers/index.js +4 -0
  228. package/release-manager/dist/mvp-config.js +1 -1
  229. package/release-manager/dist/service-host-bridge.js +228 -48
  230. package/release-manager/dist/service-host-provisioning.js +595 -0
  231. package/release-manager/dist/update/apply-payload.js +44 -2
  232. package/release-manager/dist/update/console-surface.js +6 -1
  233. package/release-manager/dist/update/install-layout.js +49 -7
  234. package/release-manager/dist/update/release-manager-authority.js +45 -3
  235. package/release-manager/dist/update/release-manager.js +29 -1
  236. package/release-manager/dist/update/transaction-progress.js +207 -0
  237. package/release-manager/dist/utils/env.js +55 -43
  238. package/release-manager/package.json +8 -8
  239. package/workbuddy-adapter/dist/codec/input-decoder.d.ts +21 -0
  240. package/workbuddy-adapter/dist/codec/input-decoder.js +50 -1
  241. package/workbuddy-adapter/dist/ingestion/pain-receipt-fallback.d.ts +68 -0
  242. package/workbuddy-adapter/dist/ingestion/pain-receipt-fallback.js +225 -0
  243. package/workbuddy-adapter/dist/pd-hook.js +60 -0
  244. package/workbuddy-adapter/dist/worker/workspace-worker.js +46 -44
  245. package/workbuddy-adapter/package.json +1 -1
  246. package/console/dist/server/utils/gateway.d.ts +0 -29
  247. package/console/dist/server/utils/gateway.js +0 -175
@@ -16,6 +16,29 @@ import * as net from 'net';
16
16
  import { findForeignWorkspaceOwner } from './host-workspace-ownership.js';
17
17
  import { errnoCode } from './config-file-io.js';
18
18
  import { resolvePdHome } from '@principles/install-layout';
19
+ /** Core files whose presence marks a workspace as already initialized. */
20
+ const CORE_WORKSPACE_FILES = ['AGENTS.md', 'SOUL.md', 'USER.md'];
21
+ /**
22
+ * Inspect ONE workspace directory with the exact rule `detectWorkspace` uses.
23
+ *
24
+ * PRI-1278 Phase 5 review: the install MODE must be recommended from the
25
+ * workspace the operator actually selected. Deriving it from a different
26
+ * (pre-prompt / neutral) directory let `force` overwrite user files in the
27
+ * final target.
28
+ */
29
+ export function inspectWorkspaceDir(dir) {
30
+ if (!fs.existsSync(dir)) {
31
+ return { exists: false, hasPrinciples: false, isFirstInstall: true, coreFiles: [] };
32
+ }
33
+ const hasPrinciples = fs.existsSync(path.join(dir, '.principles', 'THINKING_OS.md'));
34
+ const coreFiles = CORE_WORKSPACE_FILES.filter((file) => fs.existsSync(path.join(dir, file)));
35
+ return {
36
+ exists: true,
37
+ hasPrinciples,
38
+ isFirstInstall: !hasPrinciples && coreFiles.length === 0,
39
+ coreFiles,
40
+ };
41
+ }
19
42
  const IS_WIN32 = process.platform === 'win32';
20
43
  /** 探测超时:卡死的 .cmd shim / 挂起的二进制不应挂住安装器(rc-9 降级)。 */
21
44
  const DETECT_TIMEOUT_MS = 5000;
@@ -48,8 +71,8 @@ export function checkEnvironment() {
48
71
  // nvm-windows 等场景),CreateProcess 直连会跳过它命中真 node.exe,
49
72
  // 让版本门形同虚设。
50
73
  const nodeVersion = IS_WIN32
51
- ? probeVersion(() => execFileSync('cmd.exe', ['/c', 'node', '-v'], { encoding: 'utf-8', timeout: DETECT_TIMEOUT_MS }))
52
- : probeVersion(() => execFileSync('node', ['-v'], { encoding: 'utf-8', timeout: DETECT_TIMEOUT_MS }));
74
+ ? probeVersion(() => execFileSync('cmd.exe', ['/c', 'node', '-v'], { encoding: 'utf-8', timeout: DETECT_TIMEOUT_MS, windowsHide: true }))
75
+ : probeVersion(() => execFileSync('node', ['-v'], { encoding: 'utf-8', timeout: DETECT_TIMEOUT_MS, windowsHide: true }));
53
76
  if (nodeVersion !== null && nodeVersion.length > 0) {
54
77
  result.nodeVersion = nodeVersion;
55
78
  // 注:此处刻意用 String.match 并禁用 prefer-regexp-exec——写门确定性
@@ -62,8 +85,8 @@ export function checkEnvironment() {
62
85
  }
63
86
  // 检测 OpenClaw(win32 上 openclaw 是 .cmd shim,无 .exe,须经 cmd.exe /c)
64
87
  const openclawVersion = IS_WIN32
65
- ? probeVersion(() => execFileSync('cmd.exe', ['/c', 'openclaw', '--version'], { encoding: 'utf-8', timeout: DETECT_TIMEOUT_MS }))
66
- : probeVersion(() => execFileSync('openclaw', ['--version'], { encoding: 'utf-8', timeout: DETECT_TIMEOUT_MS }));
88
+ ? probeVersion(() => execFileSync('cmd.exe', ['/c', 'openclaw', '--version'], { encoding: 'utf-8', timeout: DETECT_TIMEOUT_MS, windowsHide: true }))
89
+ : probeVersion(() => execFileSync('openclaw', ['--version'], { encoding: 'utf-8', timeout: DETECT_TIMEOUT_MS, windowsHide: true }));
67
90
  if (openclawVersion !== null) {
68
91
  result.openclawVersion = openclawVersion;
69
92
  result.hasOpenClaw = true;
@@ -71,17 +94,17 @@ export function checkEnvironment() {
71
94
  else {
72
95
  // 尝试 clawd 命令
73
96
  const clawdVersion = IS_WIN32
74
- ? probeVersion(() => execFileSync('cmd.exe', ['/c', 'clawd', '--version'], { encoding: 'utf-8', timeout: DETECT_TIMEOUT_MS }))
75
- : probeVersion(() => execFileSync('clawd', ['--version'], { encoding: 'utf-8', timeout: DETECT_TIMEOUT_MS }));
97
+ ? probeVersion(() => execFileSync('cmd.exe', ['/c', 'clawd', '--version'], { encoding: 'utf-8', timeout: DETECT_TIMEOUT_MS, windowsHide: true }))
98
+ : probeVersion(() => execFileSync('clawd', ['--version'], { encoding: 'utf-8', timeout: DETECT_TIMEOUT_MS, windowsHide: true }));
76
99
  if (clawdVersion !== null) {
77
100
  result.openclawVersion = clawdVersion;
78
101
  result.hasOpenClaw = true;
79
102
  }
80
103
  }
81
104
  // 检测 Python(win32 上 python.org 安装通常只提供 python.exe,python3 可能不在 PATH)
82
- let pythonVersion = probeVersion(() => execFileSync('python3', ['--version'], { encoding: 'utf-8', timeout: DETECT_TIMEOUT_MS }));
105
+ let pythonVersion = probeVersion(() => execFileSync('python3', ['--version'], { encoding: 'utf-8', timeout: DETECT_TIMEOUT_MS, windowsHide: true }));
83
106
  if (pythonVersion === null && IS_WIN32) {
84
- pythonVersion = probeVersion(() => execFileSync('python', ['--version'], { encoding: 'utf-8', timeout: DETECT_TIMEOUT_MS }));
107
+ pythonVersion = probeVersion(() => execFileSync('python', ['--version'], { encoding: 'utf-8', timeout: DETECT_TIMEOUT_MS, windowsHide: true }));
85
108
  }
86
109
  if (pythonVersion !== null) {
87
110
  const [, version] = pythonVersion.split(' ');
@@ -89,7 +112,7 @@ export function checkEnvironment() {
89
112
  result.hasPython = true;
90
113
  }
91
114
  // 检测 Git
92
- const gitVersion = probeVersion(() => execFileSync('git', ['--version'], { encoding: 'utf-8', timeout: DETECT_TIMEOUT_MS }));
115
+ const gitVersion = probeVersion(() => execFileSync('git', ['--version'], { encoding: 'utf-8', timeout: DETECT_TIMEOUT_MS, windowsHide: true }));
93
116
  if (gitVersion !== null) {
94
117
  result.hasGit = true;
95
118
  }
@@ -180,6 +203,15 @@ export function detectWorkspace(options = {}) {
180
203
  else if (host === 'workbuddy') {
181
204
  candidates.push(hostRoots.workbuddyWorkspaceDir);
182
205
  }
206
+ else if (host === 'none') {
207
+ // Service-Host-only (PRI-1278 Phase 5): no host owns a default workspace,
208
+ // so the neutral PD-owned location is the only honest default. Never
209
+ // inherit OpenClaw's ~/clawd — that would imply a host that isn't installed.
210
+ if (typeof env.PD_WORKSPACE_DIR === 'string' && env.PD_WORKSPACE_DIR.trim().length > 0) {
211
+ candidates.push(env.PD_WORKSPACE_DIR);
212
+ }
213
+ candidates.push(path.join(homePaths.homeDir, 'pd-workspace'));
214
+ }
183
215
  else {
184
216
  // OpenClaw owns its default workspace under the active OpenClaw state dir.
185
217
  if (typeof env.OPENCLAW_WORKSPACE === 'string' && env.OPENCLAW_WORKSPACE.trim().length > 0) {
@@ -191,35 +223,12 @@ export function detectWorkspace(options = {}) {
191
223
  candidates.push(path.join(hostRoots.homeDir, 'clawd'));
192
224
  candidates.push(path.join(hostRoots.openclawHome, 'workspace'));
193
225
  }
194
- // 核心文件列表(用于检测是否已安装)
195
- const CORE_FILES = [
196
- 'AGENTS.md',
197
- 'SOUL.md',
198
- 'USER.md',
199
- ];
200
226
  for (const candidate of candidates) {
201
- if (fs.existsSync(candidate)) {
202
- // Fix-8 (P1-BUG-2): detect via THINKING_OS.md — the file the installer
203
- // actually creates under .principles/. The previous check for
204
- // PRINCIPLES.md never matched because the installer doesn't create
205
- // that file, so hasPrinciples was always false on reinstall.
206
- const principlesPath = path.join(candidate, '.principles', 'THINKING_OS.md');
207
- const hasPrinciples = fs.existsSync(principlesPath);
208
- // 检测已存在的核心文件
209
- const coreFiles = [];
210
- for (const file of CORE_FILES) {
211
- if (fs.existsSync(path.join(candidate, file))) {
212
- coreFiles.push(file);
213
- }
214
- }
215
- // 判断是否首次安装:没有 THINKING_OS.md 且没有核心文件
216
- const isFirstInstall = !hasPrinciples && coreFiles.length === 0;
227
+ const inspection = inspectWorkspaceDir(candidate);
228
+ if (inspection.exists) {
217
229
  return {
218
230
  detectedPath: candidate,
219
- exists: true,
220
- hasPrinciples,
221
- isFirstInstall,
222
- coreFiles,
231
+ ...inspection,
223
232
  };
224
233
  }
225
234
  }
@@ -228,7 +237,9 @@ export function detectWorkspace(options = {}) {
228
237
  ? hostRoots.codexWorkspaceDir
229
238
  : host === 'workbuddy'
230
239
  ? hostRoots.workbuddyWorkspaceDir
231
- : path.join(hostRoots.homeDir, 'clawd');
240
+ : host === 'none'
241
+ ? path.join(homePaths.homeDir, 'pd-workspace')
242
+ : path.join(hostRoots.homeDir, 'clawd');
232
243
  return {
233
244
  detectedPath: defaultPath,
234
245
  exists: false,
@@ -331,8 +342,8 @@ export async function checkOpenClawGateway() {
331
342
  // element or a JS-side output match — it never enters a shell string.
332
343
  if (Number.isInteger(port) && port > 0 && port < 65536) {
333
344
  const output = IS_WIN32
334
- ? execFileSync('netstat.exe', ['-ano', '-p', 'tcp'], { encoding: 'utf-8', timeout: 5000 })
335
- : execFileSync('lsof', ['-i', `:${port}`, '-t', '-sTCP:LISTEN'], { encoding: 'utf-8', timeout: 5000 });
345
+ ? execFileSync('netstat.exe', ['-ano', '-p', 'tcp'], { encoding: 'utf-8', timeout: 5000, windowsHide: true })
346
+ : execFileSync('lsof', ['-i', `:${port}`, '-t', '-sTCP:LISTEN'], { encoding: 'utf-8', timeout: 5000, windowsHide: true });
336
347
  const text = output.trim();
337
348
  if (text) {
338
349
  let listeningLine;
@@ -381,7 +392,7 @@ function runGatewayServiceCommand(subcommand) {
381
392
  execFileSync('cmd.exe', ['/c', 'openclaw', 'gateway', 'stop', '--force'], { encoding: 'utf-8', timeout: 15000, windowsHide: true });
382
393
  }
383
394
  else {
384
- execFileSync('openclaw', ['gateway', 'stop', '--force'], { encoding: 'utf-8', timeout: 15000 });
395
+ execFileSync('openclaw', ['gateway', 'stop', '--force'], { encoding: 'utf-8', timeout: 15000, windowsHide: true });
385
396
  }
386
397
  }
387
398
  else {
@@ -389,7 +400,7 @@ function runGatewayServiceCommand(subcommand) {
389
400
  execFileSync('cmd.exe', ['/c', 'openclaw', 'gateway', 'start'], { encoding: 'utf-8', timeout: 15000, windowsHide: true });
390
401
  }
391
402
  else {
392
- execFileSync('openclaw', ['gateway', 'start'], { encoding: 'utf-8', timeout: 15000 });
403
+ execFileSync('openclaw', ['gateway', 'start'], { encoding: 'utf-8', timeout: 15000, windowsHide: true });
393
404
  }
394
405
  }
395
406
  return { ok: true };
@@ -418,9 +429,10 @@ const GATEWAY_STOP_POLL_INTERVAL_MS = 1_000;
418
429
  * Deliberately NOT a copy of the two sibling liveness probes
419
430
  * (`openclaw-plugin/src/utils/file-lock.ts` and
420
431
  * `principles-core/src/principle-tree-ledger.ts`), which read ANY
421
- * `process.kill` failure as "dead". The sibling stop leg in
422
- * `pd-console/src/server/utils/gateway.ts` decides by exit code alone and has
423
- * no liveness probe to reuse. The OpenClaw gateway is a high-integrity
432
+ * `process.kill` failure as "dead". The Console's former stop leg
433
+ * (`pd-console/src/server/utils/gateway.ts`) decided by exit code alone and had
434
+ * no liveness probe to reuse; it was unreferenced and has been removed, so
435
+ * this stays the only stop-side liveness probe. The OpenClaw gateway is a high-integrity
424
436
  * scheduled task on Windows, and a medium-IL installer that signals it gets
425
437
  * EPERM — which means ALIVE. A false "dead" here would confirm a stop that
426
438
  * never happened, so win32 asks the SCM read-only via tasklist and POSIX
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-principles-disciple",
3
- "version": "1.155.2",
3
+ "version": "1.156.0",
4
4
  "description": "Interactive CLI installer for Principles Disciple OpenClaw plugin",
5
5
  "type": "module",
6
6
  "bin": {
@@ -63,23 +63,23 @@
63
63
  "author": "csuzngjh",
64
64
  "license": "Apache-2.0",
65
65
  "dependencies": {
66
- "@earendil-works/pi-agent-core": "1.2.0",
67
- "@earendil-works/pi-ai": "1.4.0",
66
+ "@earendil-works/pi-agent-core": "1.6.0",
67
+ "@earendil-works/pi-ai": "1.6.0",
68
68
  "@principles/install-layout": "file:../install-layout",
69
69
  "@sinclair/typebox": "^0.34.52",
70
70
  "@tufjs/models": "3.0.1",
71
- "@inquirer/prompts": "^8.7.2",
71
+ "@inquirer/prompts": "^8.8.0",
72
72
  "better-sqlite3": "^13.0.3",
73
- "commander": "^14.0.3",
74
- "fs-extra": "^11.4.0",
73
+ "commander": "^15.1.0",
74
+ "fs-extra": "^11.4.1",
75
75
  "js-yaml": "^5.4.3",
76
76
  "micromatch": "^4.0.8",
77
- "ora": "^9.4.1",
77
+ "ora": "^10.0.0",
78
78
  "picocolors": "^1.0.0",
79
79
  "semver": "^7.8.6",
80
80
  "tar": "^7.5.22",
81
81
  "typebox": "^1.3.16",
82
- "tuf-js": "6.0.2",
82
+ "tuf-js": "6.0.3",
83
83
  "undici": "^8.13.0"
84
84
  },
85
85
  "devDependencies": {
@@ -41,3 +41,24 @@ export declare function normalizeWorkbuddyToolResponse(toolResponse: unknown, ev
41
41
  * contract violation. Absent optional identity is never fabricated (rc-6).
42
42
  */
43
43
  export declare function decodeWorkbuddyInput(raw: unknown): HostEvent;
44
+ /** The MCP server ids whose `pd_submit_pain` the receipt fallback serves.
45
+ * WorkBuddy keeps the hyphen — the real installed engine (probe 2026-11-24)
46
+ * registers `mcp__pd-recall__pd_submit_pain` verbatim, with NO identifier
47
+ * sanitization (unlike Codex, whose CLI sanitizes `-`→`_`). A literal
48
+ * `pd_recall` server on this host is a DIFFERENT third-party server and must
49
+ * never reach the recovery path (Devin review, receipt-forgery surface). */
50
+ export declare const PAIN_SUBMIT_MCP_SERVER_IDS: ReadonlySet<string>;
51
+ export interface ParsedWorkbuddyMcpToolName {
52
+ readonly serverId: string;
53
+ readonly toolId: string;
54
+ }
55
+ /** Decompose a WorkBuddy MCP tool name into (serverId, toolId); null when
56
+ * the name is not a namespaced MCP tool name. No substring semantics. */
57
+ export declare function parseWorkbuddyMcpToolName(toolName: string): ParsedWorkbuddyMcpToolName | null;
58
+ /**
59
+ * Exact gate: the tool must be `pd_submit_pain` served by the PD MCP server
60
+ * (`pd-recall`). Every other tool — including an identically-named tool on a
61
+ * DIFFERENT MCP server — fails (equality on both parsed segments, never a
62
+ * substring match).
63
+ */
64
+ export declare function isPainSubmitWorkbuddyToolName(toolName: string): boolean;
@@ -185,8 +185,24 @@ export function normalizeWorkbuddyToolResponse(toolResponse, eventForDiagnostics
185
185
  ? { toolResponse }
186
186
  : toolResponse;
187
187
  }
188
+ if (Array.isArray(toolResponse)) {
189
+ // PRI-1275: MCP tool completions arrive as the CallToolResult CONTENT
190
+ // BLOCK ARRAY (`[{type:'text',text:…}, …]`) — probe-verified on the real
191
+ // installed engine (CodeBuddy Code 2.165.0, 2026-11-24): the engine puts
192
+ // `result.content` directly into the PostToolUse `tool_response`. The
193
+ // channel contract still holds (PostToolUseFailure is the separate
194
+ // failure registration), and the shared classifier already classifies an
195
+ // array envelope as success (normalizeOutcome). rc-4: validating "is
196
+ // array" is not enough — every content block must be a record; anything
197
+ // else is a malformed completion and fails loud. The array passes through
198
+ // UNCHANGED: the structured-receipt fallback reads the exact blocks.
199
+ if (toolResponse.length === 0 || !toolResponse.every((block) => typeof block === 'object' && block !== null)) {
200
+ throw new WorkBuddyDecoderError(`malformed required field "tool_response"`, `${eventForDiagnostics} MCP tool_response must be a non-empty array of content-block objects from ${HOST_CONTRACT_BASELINE}.`);
201
+ }
202
+ return toolResponse;
203
+ }
188
204
  if (!isRecord(toolResponse)) {
189
- throw new WorkBuddyDecoderError(`malformed required field "tool_response"`, `${eventForDiagnostics} tool_response must be the rendered string or the engine result object from ${HOST_CONTRACT_BASELINE}.`);
205
+ throw new WorkBuddyDecoderError(`malformed required field "tool_response"`, `${eventForDiagnostics} tool_response must be the rendered string, the engine result object, or the MCP content-block array from ${HOST_CONTRACT_BASELINE}.`);
190
206
  }
191
207
  const isError = field(toolResponse, 'is_error') === true;
192
208
  const exitCodeValue = field(toolResponse, 'exitCode');
@@ -315,3 +331,36 @@ export function decodeWorkbuddyInput(raw) {
315
331
  const source = `workbuddy:${eventName.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase()}`;
316
332
  return { kind, context, rawPayload, source };
317
333
  }
334
+ // ─── PRI-1275 (B2): the MCP namespace gate for the receipt fallback ─────────
335
+ // The real installed engine (CodeBuddy Code 2.165.0, probe 2026-11-24) names
336
+ // MCP tools `mcp__<server>__<tool>` — the same convention the Codex adapter
337
+ // froze in P1-1. Identical semantics here: exact parse of BOTH segments,
338
+ // never a substring match.
339
+ /** The MCP server ids whose `pd_submit_pain` the receipt fallback serves.
340
+ * WorkBuddy keeps the hyphen — the real installed engine (probe 2026-11-24)
341
+ * registers `mcp__pd-recall__pd_submit_pain` verbatim, with NO identifier
342
+ * sanitization (unlike Codex, whose CLI sanitizes `-`→`_`). A literal
343
+ * `pd_recall` server on this host is a DIFFERENT third-party server and must
344
+ * never reach the recovery path (Devin review, receipt-forgery surface). */
345
+ export const PAIN_SUBMIT_MCP_SERVER_IDS = new Set(['pd-recall']);
346
+ /** Decompose a WorkBuddy MCP tool name into (serverId, toolId); null when
347
+ * the name is not a namespaced MCP tool name. No substring semantics. */
348
+ export function parseWorkbuddyMcpToolName(toolName) {
349
+ if (!toolName.startsWith('mcp__'))
350
+ return null;
351
+ const rest = toolName.slice('mcp__'.length);
352
+ const separator = rest.indexOf('__');
353
+ if (separator <= 0 || separator + 2 >= rest.length)
354
+ return null;
355
+ return { serverId: rest.slice(0, separator), toolId: rest.slice(separator + 2) };
356
+ }
357
+ /**
358
+ * Exact gate: the tool must be `pd_submit_pain` served by the PD MCP server
359
+ * (`pd-recall`). Every other tool — including an identically-named tool on a
360
+ * DIFFERENT MCP server — fails (equality on both parsed segments, never a
361
+ * substring match).
362
+ */
363
+ export function isPainSubmitWorkbuddyToolName(toolName) {
364
+ const parsed = parseWorkbuddyMcpToolName(toolName);
365
+ return parsed !== null && PAIN_SUBMIT_MCP_SERVER_IDS.has(parsed.serverId) && parsed.toolId === 'pd_submit_pain';
366
+ }
@@ -0,0 +1,68 @@
1
+ import type { TargetTurnEvidenceRead } from '@principles/core/runtime';
2
+ import { type PainReceiptRecoveryOutcome } from '@principles/core/runtime';
3
+ /** The MCP tool id this fallback processes (the server gate lives in the
4
+ * codec parser — exact match on both namespace segments, never a pattern). */
5
+ export declare const PAIN_SUBMIT_TOOL_NAME: 'pd_submit_pain';
6
+ export type PainReceiptFallbackResult = {
7
+ readonly status: 'not_applicable';
8
+ } | {
9
+ readonly status: 'attempted';
10
+ readonly outcome: PainReceiptRecoveryOutcome;
11
+ };
12
+ /**
13
+ * WorkBuddy MCP envelope: the tool_response is the CallToolResult content
14
+ * block ARRAY. More than one text block is AMBIGUOUS — two text blocks
15
+ * could each carry a different task's receipt, so the whole envelope is
16
+ * rejected instead of quietly trusting the first block (P2 rule, mirrored
17
+ * from the Codex adapter).
18
+ */
19
+ export declare function extractReceiptText(toolResponse: unknown): {
20
+ ok: true;
21
+ text: string;
22
+ } | {
23
+ ok: false;
24
+ reasonCode: string;
25
+ };
26
+ /**
27
+ * The structured target-turn evidence read for the WorkBuddy host boundary —
28
+ * the exact contract the Codex adapter froze (PRI-1273): the consent ledger
29
+ * FIRST (a denial returns blocked_by_consent BEFORE any store query), then
30
+ * the EXACT (rollout identity, host turn id) — never a session scan, never
31
+ * the submission turn, never a recent-turn fallback.
32
+ */
33
+ export declare function readWorkbuddyTargetTurnEvidence(workspaceDir: string, sessionId: string, turnId: string): TargetTurnEvidenceRead;
34
+ /**
35
+ * Does the authorized governance store already hold readable text for the
36
+ * EXACT (session, turn)? Shared by the receipt fallback (disposition choice)
37
+ * and the workspace worker's waiting-task reconcile (the flip).
38
+ */
39
+ export declare function workbuddyTargetTurnTextAvailable(workspaceDir: string, sessionId: string, turnId: string): boolean;
40
+ export interface PainReceiptFallbackInput {
41
+ readonly workspaceDir: string;
42
+ /** Raw host event `tool_name` — gated by the codec MCP namespace parser
43
+ * before anything else happens (P1-1). */
44
+ readonly toolName: string;
45
+ /** Raw `tool_response` from the PostToolUse payload. */
46
+ readonly toolResponse: unknown;
47
+ /** Host-authoritative identity from the event itself. NO submission turn:
48
+ * the WorkBuddy event's `generation_id` is not a proven turn id (SPEC TD
49
+ * §1.3 field rules), so the type physically omits it (review round). */
50
+ readonly identity: {
51
+ readonly sessionId: string;
52
+ readonly toolCallId: string;
53
+ };
54
+ /** Caller-resolved `host_identity_minimal_metadata` flag verdict. */
55
+ readonly minimalMetadataGranted: boolean;
56
+ readonly now?: () => Date;
57
+ }
58
+ /**
59
+ * Attempt the receipt fallback for one PostToolUse event. Never throws —
60
+ * every failure is a structured result the hook surfaces as one bounded
61
+ * diagnostic (rc-9); the hook result itself is unaffected (fail-open belt).
62
+ */
63
+ export declare function attemptPainReceiptFallback(input: PainReceiptFallbackInput): Promise<PainReceiptFallbackResult>;
64
+ /**
65
+ * One bounded stderr diagnostic line for the hook (ids and codes only —
66
+ * never receipt content, prompts or tool input/output).
67
+ */
68
+ export declare function painReceiptFallbackDiagnostic(result: PainReceiptFallbackResult): string | null;
@@ -0,0 +1,225 @@
1
+ /**
2
+ * PRI-1275 (B2) — WorkBuddy PostToolUse structured-receipt fallback.
3
+ *
4
+ * When a `pd_submit_pain` MCP request carried no trusted host `_meta`, the
5
+ * original Pain/Task was legally persisted unbound (`host_session_claim_empty`
6
+ * — the WorkBuddy designated fallback territory, PRI-1275 extension of the
7
+ * PRI-1274 P1-2 whitelist). WorkBuddy's formal PostToolUse completion event
8
+ * then carries PD's own structured receipt (`pd.pain-submit-receipt.v1`) in
9
+ * the CallToolResult CONTENT BLOCK ARRAY (`[{type:'text',text:...}, ...]`),
10
+ * probe-verified on the REAL installed engine (CodeBuddy Code 2.165.0,
11
+ * 2026-11-24) — never assumed from Codex's single object envelope. Together
12
+ * with the event's own host-authoritative identity (`session_id` /
13
+ * `generation_id` / `call_id` — never model parameters), this module
14
+ * restores the SAME original task's submission identity through the Core
15
+ * CAS recovery.
16
+ *
17
+ * P1-1 (mirrored from PRI-1274): the gate is an exact parse of
18
+ * `mcp__<server>__<tool>` against the PD server id `pd-recall` + the tool id
19
+ * `pd_submit_pain`. The real WorkBuddy engine keeps the hyphen (probe
20
+ * 2026-11-24) — the sanitized `pd_recall` spelling is NOT admitted, because a
21
+ * locally registered server literally named `pd_recall` is a DIFFERENT
22
+ * third-party server. A bare `pd_submit_pain` or an identically-named tool on
23
+ * another MCP server never enters this path.
24
+ *
25
+ * Authorization: the Workspace-level `host_identity_minimal_metadata` quiet
26
+ * flag — deliberately INDEPENDENT of `workbuddy_conversation_ingestion`
27
+ * (full conversation ingestion may stay off; this path reads no transcript
28
+ * and persists ids only).
29
+ *
30
+ * No recovery is EVER attempted from free text, ordinary tool_call rows, or
31
+ * look-alike strings (SPEC TD §1.3).
32
+ */
33
+ import * as path from 'node:path';
34
+ import { readSourceMaterialAuthorization } from '@principles/host-runtime';
35
+ import { isSentinelSessionId } from '@principles/core/runtime';
36
+ import { listGovernanceConversationTextsForHostTurn } from '@principles/host-runtime';
37
+ import { recoverTaskIdentityFromReceipt, validatePainSubmitReceipt, } from '@principles/core/runtime';
38
+ import { isPainSubmitWorkbuddyToolName } from '../codec/input-decoder.js';
39
+ /** The MCP tool id this fallback processes (the server gate lives in the
40
+ * codec parser — exact match on both namespace segments, never a pattern). */
41
+ export const PAIN_SUBMIT_TOOL_NAME = 'pd_submit_pain';
42
+ /**
43
+ * WorkBuddy MCP envelope: the tool_response is the CallToolResult content
44
+ * block ARRAY. More than one text block is AMBIGUOUS — two text blocks
45
+ * could each carry a different task's receipt, so the whole envelope is
46
+ * rejected instead of quietly trusting the first block (P2 rule, mirrored
47
+ * from the Codex adapter).
48
+ */
49
+ export function extractReceiptText(toolResponse) {
50
+ if (!Array.isArray(toolResponse)) {
51
+ return { ok: false, reasonCode: 'receipt_envelope_not_content_array' };
52
+ }
53
+ const textBlocks = [];
54
+ for (const block of toolResponse) {
55
+ if (typeof block !== 'object' || block === null || Array.isArray(block)) {
56
+ return { ok: false, reasonCode: 'receipt_envelope_block_invalid' };
57
+ }
58
+ const record = block;
59
+ const type = Object.hasOwn(record, 'type') ? record.type : undefined;
60
+ const text = Object.hasOwn(record, 'text') ? record.text : undefined;
61
+ if (type === 'text' && typeof text === 'string')
62
+ textBlocks.push(text);
63
+ }
64
+ if (textBlocks.length === 0)
65
+ return { ok: false, reasonCode: 'receipt_envelope_content_missing' };
66
+ const [firstText] = textBlocks;
67
+ if (firstText === undefined)
68
+ return { ok: false, reasonCode: 'receipt_envelope_content_missing' };
69
+ if (textBlocks.length > 1)
70
+ return { ok: false, reasonCode: 'receipt_envelope_ambiguous_content' };
71
+ return { ok: true, text: firstText };
72
+ }
73
+ /**
74
+ * Normalize host ids at the adapter boundary, matching the trusted `_meta`
75
+ * reader. `null` means malformed; `undefined` means absent (or an empty
76
+ * optional id). Only the normalized value may cross into Core.
77
+ */
78
+ function normalizeEventId(value, opts) {
79
+ if (value === undefined)
80
+ return undefined;
81
+ if (typeof value !== 'string')
82
+ return null;
83
+ const id = value.trim();
84
+ if (opts.allowEmpty && id.length === 0)
85
+ return undefined;
86
+ return id.length > 0 && id.length <= 200 && !isSentinelSessionId(id) ? id : null;
87
+ }
88
+ /**
89
+ * The structured target-turn evidence read for the WorkBuddy host boundary —
90
+ * the exact contract the Codex adapter froze (PRI-1273): the consent ledger
91
+ * FIRST (a denial returns blocked_by_consent BEFORE any store query), then
92
+ * the EXACT (rollout identity, host turn id) — never a session scan, never
93
+ * the submission turn, never a recent-turn fallback.
94
+ */
95
+ export function readWorkbuddyTargetTurnEvidence(workspaceDir, sessionId, turnId) {
96
+ const authorization = readSourceMaterialAuthorization({ workspaceDir, hostKind: 'workbuddy' });
97
+ if (authorization.status === 'blocked') {
98
+ return { status: 'blocked_by_consent', reason: authorization.reason };
99
+ }
100
+ try {
101
+ const result = listGovernanceConversationTextsForHostTurn({
102
+ workspaceDir,
103
+ hostKind: 'workbuddy',
104
+ rolloutIdentity: sessionId,
105
+ hostTurnId: turnId,
106
+ limit: 12,
107
+ });
108
+ if (!result.ok) {
109
+ return { status: 'read_failed', reason: result.reason };
110
+ }
111
+ const entries = result.rows.map((row) => ({
112
+ sourceRef: 'governance_observation:' + row.logicalKey,
113
+ note: row.visibleText.slice(0, 2000),
114
+ }));
115
+ return entries.length > 0
116
+ ? { status: 'available', entries }
117
+ : { status: 'not_found' };
118
+ }
119
+ catch (error) {
120
+ return { status: 'read_failed', reason: error instanceof Error ? error.message.slice(0, 120) : 'store_exception' };
121
+ }
122
+ }
123
+ /**
124
+ * Does the authorized governance store already hold readable text for the
125
+ * EXACT (session, turn)? Shared by the receipt fallback (disposition choice)
126
+ * and the workspace worker's waiting-task reconcile (the flip).
127
+ */
128
+ export function workbuddyTargetTurnTextAvailable(workspaceDir, sessionId, turnId) {
129
+ return readWorkbuddyTargetTurnEvidence(workspaceDir, sessionId, turnId).status === 'available';
130
+ }
131
+ /**
132
+ * Attempt the receipt fallback for one PostToolUse event. Never throws —
133
+ * every failure is a structured result the hook surfaces as one bounded
134
+ * diagnostic (rc-9); the hook result itself is unaffected (fail-open belt).
135
+ */
136
+ export async function attemptPainReceiptFallback(input) {
137
+ // P1-1: exact namespace gate first — only the PD MCP server's
138
+ // `pd_submit_pain` completion may enter the recovery path.
139
+ if (!isPainSubmitWorkbuddyToolName(input.toolName)) {
140
+ return { status: 'not_applicable' };
141
+ }
142
+ // P2: validate AND normalize at the host boundary. Validating a trimmed
143
+ // copy while forwarding the raw value would create a second identity
144
+ // spelling in Core/SQLite (and make exact target-turn joins miss).
145
+ const sessionId = normalizeEventId(input.identity.sessionId, { allowEmpty: false });
146
+ const toolCallId = normalizeEventId(input.identity.toolCallId, { allowEmpty: false });
147
+ if (sessionId === null || toolCallId === null) {
148
+ return { status: 'attempted', outcome: { status: 'rejected', reasonCode: 'event_identity_invalid' } };
149
+ }
150
+ if (sessionId === undefined || toolCallId === undefined) {
151
+ return { status: 'attempted', outcome: { status: 'rejected', reasonCode: 'event_identity_missing' } };
152
+ }
153
+ const envelope = extractReceiptText(input.toolResponse);
154
+ if (!envelope.ok) {
155
+ return { status: 'attempted', outcome: { status: 'rejected', reasonCode: envelope.reasonCode } };
156
+ }
157
+ let parsed;
158
+ try {
159
+ parsed = JSON.parse(envelope.text);
160
+ }
161
+ catch {
162
+ // Degraded transport forms (plain-text statement) and foreign payloads
163
+ // are not receipts — no recovery from free text.
164
+ return { status: 'attempted', outcome: { status: 'rejected', reasonCode: 'receipt_text_not_json' } };
165
+ }
166
+ // P2: normalize the workspace spellings BEFORE validation — the same
167
+ // directory written differently (`/w/p` vs `/w/p/.`) is the same
168
+ // workspace; a genuinely different directory is still rejected by the
169
+ // validated exact comparison. Platform path knowledge stays in the
170
+ // adapter (Core stays path-free).
171
+ const normalizedWorkspace = path.resolve(input.workspaceDir);
172
+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
173
+ const parsedRecord = parsed;
174
+ const rawDir = Object.hasOwn(parsedRecord, 'workspaceDir') ? parsedRecord.workspaceDir : undefined;
175
+ if (typeof rawDir === 'string' && rawDir.length > 0) {
176
+ parsed = { ...parsedRecord, workspaceDir: path.resolve(rawDir) };
177
+ }
178
+ }
179
+ const validated = validatePainSubmitReceipt(parsed, { workspaceDir: normalizedWorkspace });
180
+ if (!validated.ok) {
181
+ return { status: 'attempted', outcome: { status: 'rejected', reasonCode: validated.reasonCode } };
182
+ }
183
+ // Nothing to repair: a `submitted` receipt whose association is already
184
+ // `verified` means the trusted `_meta` path bound the identity at the
185
+ // INITIAL write. Running the recovery anyway could only answer
186
+ // `already_bound`, which the hook renders as a routine `status=degraded`
187
+ // line on EVERY successful submission — drowning the genuinely actionable
188
+ // degraded signals (and the `blocked_by_consent` nextAction). This is the
189
+ // normal WorkBuddy happy path, not a fallback case at all.
190
+ // `submit_unconfirmed` is deliberately NOT skipped: its write outcome is
191
+ // unknown, so the read-back-confirmed recovery still applies.
192
+ if (validated.receipt.status === 'submitted' && validated.receipt.sessionAssociation.status === 'verified') {
193
+ return { status: 'not_applicable' };
194
+ }
195
+ const outcome = await recoverTaskIdentityFromReceipt({
196
+ workspaceDir: normalizedWorkspace,
197
+ hostKind: 'workbuddy',
198
+ receipt: validated.receipt,
199
+ // No submissionTurnId: the WorkBuddy host provides no proven turn id.
200
+ // An absent turn never negates the session binding (SPEC §G2); a target
201
+ // turn pinned to an unproven id would wedge the task's evidence wait.
202
+ identity: { sessionId, toolCallId },
203
+ authorization: { minimalMetadataGranted: input.minimalMetadataGranted },
204
+ targetTurnTextAvailable: (hostSessionId, targetTurnId) => workbuddyTargetTurnTextAvailable(normalizedWorkspace, hostSessionId, targetTurnId),
205
+ ...(input.now !== undefined ? { now: input.now } : {}),
206
+ });
207
+ return { status: 'attempted', outcome };
208
+ }
209
+ /**
210
+ * One bounded stderr diagnostic line for the hook (ids and codes only —
211
+ * never receipt content, prompts or tool input/output).
212
+ */
213
+ export function painReceiptFallbackDiagnostic(result) {
214
+ if (result.status === 'not_applicable')
215
+ return null;
216
+ const { outcome } = result;
217
+ switch (outcome.status) {
218
+ case 'recovered':
219
+ return `pain_receipt_recovered:taskId=${outcome.taskId}:state=${outcome.disposition.state}`;
220
+ case 'already_bound':
221
+ return `pain_receipt_idempotent:taskId=${outcome.taskId}`;
222
+ case 'rejected':
223
+ return `pain_receipt_rejected:${outcome.reasonCode}${outcome.detail !== undefined ? `:detail=${Array.from(outcome.detail).slice(0, 80).join('')}` : ''}${outcome.taskId !== undefined ? `:taskId=${outcome.taskId}` : ''}`;
224
+ }
225
+ }