@productbrain/cli 0.1.0-beta.14 → 0.1.0-beta.1406

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 (908) hide show
  1. package/README.md +75 -115
  2. package/dist/__tests__/adapters.test.d.ts +2 -0
  3. package/dist/__tests__/adapters.test.d.ts.map +1 -0
  4. package/dist/__tests__/adapters.test.js +417 -0
  5. package/dist/__tests__/adapters.test.js.map +1 -0
  6. package/dist/__tests__/audit.test.js +49 -44
  7. package/dist/__tests__/audit.test.js.map +1 -1
  8. package/dist/__tests__/authority-domains-queue.test.d.ts +2 -0
  9. package/dist/__tests__/authority-domains-queue.test.d.ts.map +1 -0
  10. package/dist/__tests__/authority-domains-queue.test.js +169 -0
  11. package/dist/__tests__/authority-domains-queue.test.js.map +1 -0
  12. package/dist/__tests__/authority-domains.test.d.ts +2 -0
  13. package/dist/__tests__/authority-domains.test.d.ts.map +1 -0
  14. package/dist/__tests__/authority-domains.test.js +48 -0
  15. package/dist/__tests__/authority-domains.test.js.map +1 -0
  16. package/dist/__tests__/batch-transformations.test.d.ts +2 -0
  17. package/dist/__tests__/batch-transformations.test.d.ts.map +1 -0
  18. package/dist/__tests__/batch-transformations.test.js +263 -0
  19. package/dist/__tests__/batch-transformations.test.js.map +1 -0
  20. package/dist/__tests__/canonicalRefs.vocab.test.d.ts +2 -0
  21. package/dist/__tests__/canonicalRefs.vocab.test.d.ts.map +1 -0
  22. package/dist/__tests__/canonicalRefs.vocab.test.js +251 -0
  23. package/dist/__tests__/canonicalRefs.vocab.test.js.map +1 -0
  24. package/dist/__tests__/capture-receipt-domain.test.d.ts +2 -0
  25. package/dist/__tests__/capture-receipt-domain.test.d.ts.map +1 -0
  26. package/dist/__tests__/capture-receipt-domain.test.js +29 -0
  27. package/dist/__tests__/capture-receipt-domain.test.js.map +1 -0
  28. package/dist/__tests__/capture.test.js +309 -18
  29. package/dist/__tests__/capture.test.js.map +1 -1
  30. package/dist/__tests__/config-prod-fallthrough.test.d.ts +2 -0
  31. package/dist/__tests__/config-prod-fallthrough.test.d.ts.map +1 -0
  32. package/dist/__tests__/config-prod-fallthrough.test.js +82 -0
  33. package/dist/__tests__/config-prod-fallthrough.test.js.map +1 -0
  34. package/dist/__tests__/config.test.d.ts +8 -0
  35. package/dist/__tests__/config.test.d.ts.map +1 -0
  36. package/dist/__tests__/config.test.js +566 -0
  37. package/dist/__tests__/config.test.js.map +1 -0
  38. package/dist/__tests__/constants.test.d.ts +2 -0
  39. package/dist/__tests__/constants.test.d.ts.map +1 -0
  40. package/dist/__tests__/constants.test.js +146 -0
  41. package/dist/__tests__/constants.test.js.map +1 -0
  42. package/dist/__tests__/constellation.test.js +16 -22
  43. package/dist/__tests__/constellation.test.js.map +1 -1
  44. package/dist/__tests__/context-strategy.test.js +8 -8
  45. package/dist/__tests__/context-strategy.test.js.map +1 -1
  46. package/dist/__tests__/envelope-contract.test.d.ts +15 -0
  47. package/dist/__tests__/envelope-contract.test.d.ts.map +1 -0
  48. package/dist/__tests__/envelope-contract.test.js +152 -0
  49. package/dist/__tests__/envelope-contract.test.js.map +1 -0
  50. package/dist/__tests__/errors.test.d.ts +2 -0
  51. package/dist/__tests__/errors.test.d.ts.map +1 -0
  52. package/dist/__tests__/errors.test.js +118 -0
  53. package/dist/__tests__/errors.test.js.map +1 -0
  54. package/dist/__tests__/experiment.test.d.ts +6 -0
  55. package/dist/__tests__/experiment.test.d.ts.map +1 -0
  56. package/dist/__tests__/experiment.test.js +69 -0
  57. package/dist/__tests__/experiment.test.js.map +1 -0
  58. package/dist/__tests__/fields.test.js +36 -36
  59. package/dist/__tests__/fields.test.js.map +1 -1
  60. package/dist/__tests__/glossary.test.d.ts +2 -0
  61. package/dist/__tests__/glossary.test.d.ts.map +1 -0
  62. package/dist/__tests__/glossary.test.js +32 -0
  63. package/dist/__tests__/glossary.test.js.map +1 -0
  64. package/dist/__tests__/handshake-augment.test.d.ts +2 -0
  65. package/dist/__tests__/handshake-augment.test.d.ts.map +1 -0
  66. package/dist/__tests__/handshake-augment.test.js +423 -0
  67. package/dist/__tests__/handshake-augment.test.js.map +1 -0
  68. package/dist/__tests__/handshake-dormancy.test.d.ts +2 -0
  69. package/dist/__tests__/handshake-dormancy.test.d.ts.map +1 -0
  70. package/dist/__tests__/handshake-dormancy.test.js +207 -0
  71. package/dist/__tests__/handshake-dormancy.test.js.map +1 -0
  72. package/dist/__tests__/handshake-formatter.test.d.ts +2 -0
  73. package/dist/__tests__/handshake-formatter.test.d.ts.map +1 -0
  74. package/dist/__tests__/handshake-formatter.test.js +67 -0
  75. package/dist/__tests__/handshake-formatter.test.js.map +1 -0
  76. package/dist/__tests__/handshake-preview.test.d.ts +2 -0
  77. package/dist/__tests__/handshake-preview.test.d.ts.map +1 -0
  78. package/dist/__tests__/handshake-preview.test.js +949 -0
  79. package/dist/__tests__/handshake-preview.test.js.map +1 -0
  80. package/dist/__tests__/handshake.e2e.test.d.ts +2 -0
  81. package/dist/__tests__/handshake.e2e.test.d.ts.map +1 -0
  82. package/dist/__tests__/handshake.e2e.test.js +1252 -0
  83. package/dist/__tests__/handshake.e2e.test.js.map +1 -0
  84. package/dist/__tests__/handshake.test.js +813 -19
  85. package/dist/__tests__/handshake.test.js.map +1 -1
  86. package/dist/__tests__/hook-intents.test.d.ts +2 -0
  87. package/dist/__tests__/hook-intents.test.d.ts.map +1 -0
  88. package/dist/__tests__/hook-intents.test.js +184 -0
  89. package/dist/__tests__/hook-intents.test.js.map +1 -0
  90. package/dist/__tests__/ingest.test.js +28 -28
  91. package/dist/__tests__/ingest.test.js.map +1 -1
  92. package/dist/__tests__/init.test.d.ts +7 -0
  93. package/dist/__tests__/init.test.d.ts.map +1 -0
  94. package/dist/__tests__/init.test.js +146 -0
  95. package/dist/__tests__/init.test.js.map +1 -0
  96. package/dist/__tests__/login.test.d.ts +2 -0
  97. package/dist/__tests__/login.test.d.ts.map +1 -0
  98. package/dist/__tests__/login.test.js +167 -0
  99. package/dist/__tests__/login.test.js.map +1 -0
  100. package/dist/__tests__/manifest.test.d.ts +6 -0
  101. package/dist/__tests__/manifest.test.d.ts.map +1 -0
  102. package/dist/__tests__/manifest.test.js +255 -0
  103. package/dist/__tests__/manifest.test.js.map +1 -0
  104. package/dist/__tests__/method-registry.integration.test.d.ts +6 -0
  105. package/dist/__tests__/method-registry.integration.test.d.ts.map +1 -0
  106. package/dist/__tests__/method-registry.integration.test.js +18 -0
  107. package/dist/__tests__/method-registry.integration.test.js.map +1 -0
  108. package/dist/__tests__/method-registry.test.d.ts +14 -0
  109. package/dist/__tests__/method-registry.test.d.ts.map +1 -0
  110. package/dist/__tests__/method-registry.test.js +134 -0
  111. package/dist/__tests__/method-registry.test.js.map +1 -0
  112. package/dist/__tests__/notice-marker.test.d.ts +2 -0
  113. package/dist/__tests__/notice-marker.test.d.ts.map +1 -0
  114. package/dist/__tests__/notice-marker.test.js +41 -0
  115. package/dist/__tests__/notice-marker.test.js.map +1 -0
  116. package/dist/__tests__/onboarding-path-b.test.d.ts +2 -0
  117. package/dist/__tests__/onboarding-path-b.test.d.ts.map +1 -0
  118. package/dist/__tests__/onboarding-path-b.test.js +46 -0
  119. package/dist/__tests__/onboarding-path-b.test.js.map +1 -0
  120. package/dist/__tests__/onboarding.test.d.ts +6 -0
  121. package/dist/__tests__/onboarding.test.d.ts.map +1 -0
  122. package/dist/__tests__/onboarding.test.js +347 -0
  123. package/dist/__tests__/onboarding.test.js.map +1 -0
  124. package/dist/__tests__/orient.test.d.ts +2 -0
  125. package/dist/__tests__/orient.test.d.ts.map +1 -0
  126. package/dist/__tests__/orient.test.js +424 -0
  127. package/dist/__tests__/orient.test.js.map +1 -0
  128. package/dist/__tests__/perimeter.test.d.ts +2 -0
  129. package/dist/__tests__/perimeter.test.d.ts.map +1 -0
  130. package/dist/__tests__/perimeter.test.js +165 -0
  131. package/dist/__tests__/perimeter.test.js.map +1 -0
  132. package/dist/__tests__/personal-layer.test.d.ts +11 -0
  133. package/dist/__tests__/personal-layer.test.d.ts.map +1 -0
  134. package/dist/__tests__/personal-layer.test.js +268 -0
  135. package/dist/__tests__/personal-layer.test.js.map +1 -0
  136. package/dist/__tests__/preview-key-refresh.test.d.ts +2 -0
  137. package/dist/__tests__/preview-key-refresh.test.d.ts.map +1 -0
  138. package/dist/__tests__/preview-key-refresh.test.js +126 -0
  139. package/dist/__tests__/preview-key-refresh.test.js.map +1 -0
  140. package/dist/__tests__/profiles.test.d.ts +2 -0
  141. package/dist/__tests__/profiles.test.d.ts.map +1 -0
  142. package/dist/__tests__/profiles.test.js +316 -0
  143. package/dist/__tests__/profiles.test.js.map +1 -0
  144. package/dist/__tests__/promote-batch.test.d.ts +2 -0
  145. package/dist/__tests__/promote-batch.test.d.ts.map +1 -0
  146. package/dist/__tests__/promote-batch.test.js +185 -0
  147. package/dist/__tests__/promote-batch.test.js.map +1 -0
  148. package/dist/__tests__/promote.test.js +121 -30
  149. package/dist/__tests__/promote.test.js.map +1 -1
  150. package/dist/__tests__/prompts.test.d.ts +6 -0
  151. package/dist/__tests__/prompts.test.d.ts.map +1 -0
  152. package/dist/__tests__/prompts.test.js +146 -0
  153. package/dist/__tests__/prompts.test.js.map +1 -0
  154. package/dist/__tests__/proof-run.test.d.ts +2 -0
  155. package/dist/__tests__/proof-run.test.d.ts.map +1 -0
  156. package/dist/__tests__/proof-run.test.js +255 -0
  157. package/dist/__tests__/proof-run.test.js.map +1 -0
  158. package/dist/__tests__/proposals.test.js +24 -47
  159. package/dist/__tests__/proposals.test.js.map +1 -1
  160. package/dist/__tests__/relate.test.js +34 -36
  161. package/dist/__tests__/relate.test.js.map +1 -1
  162. package/dist/__tests__/repo-detect.test.js +97 -1
  163. package/dist/__tests__/repo-detect.test.js.map +1 -1
  164. package/dist/__tests__/runner.test.js +19 -15
  165. package/dist/__tests__/runner.test.js.map +1 -1
  166. package/dist/__tests__/session-close-loop.test.d.ts +2 -0
  167. package/dist/__tests__/session-close-loop.test.d.ts.map +1 -0
  168. package/dist/__tests__/session-close-loop.test.js +231 -0
  169. package/dist/__tests__/session-close-loop.test.js.map +1 -0
  170. package/dist/__tests__/session-reset.test.d.ts +2 -0
  171. package/dist/__tests__/session-reset.test.d.ts.map +1 -0
  172. package/dist/__tests__/session-reset.test.js +122 -0
  173. package/dist/__tests__/session-reset.test.js.map +1 -0
  174. package/dist/__tests__/session-resume-backstop.test.d.ts +2 -0
  175. package/dist/__tests__/session-resume-backstop.test.d.ts.map +1 -0
  176. package/dist/__tests__/session-resume-backstop.test.js +97 -0
  177. package/dist/__tests__/session-resume-backstop.test.js.map +1 -0
  178. package/dist/__tests__/session-start-key-refresh.test.d.ts +2 -0
  179. package/dist/__tests__/session-start-key-refresh.test.d.ts.map +1 -0
  180. package/dist/__tests__/session-start-key-refresh.test.js +179 -0
  181. package/dist/__tests__/session-start-key-refresh.test.js.map +1 -0
  182. package/dist/__tests__/session-state-machine.test.d.ts +2 -0
  183. package/dist/__tests__/session-state-machine.test.d.ts.map +1 -0
  184. package/dist/__tests__/session-state-machine.test.js +198 -0
  185. package/dist/__tests__/session-state-machine.test.js.map +1 -0
  186. package/dist/__tests__/session-switch.test.d.ts +2 -0
  187. package/dist/__tests__/session-switch.test.d.ts.map +1 -0
  188. package/dist/__tests__/session-switch.test.js +130 -0
  189. package/dist/__tests__/session-switch.test.js.map +1 -0
  190. package/dist/__tests__/session-touch.test.js +11 -11
  191. package/dist/__tests__/session-touch.test.js.map +1 -1
  192. package/dist/__tests__/session.test.js +4 -10
  193. package/dist/__tests__/session.test.js.map +1 -1
  194. package/dist/__tests__/setup-ingest.test.d.ts +2 -0
  195. package/dist/__tests__/setup-ingest.test.d.ts.map +1 -0
  196. package/dist/__tests__/setup-ingest.test.js +71 -0
  197. package/dist/__tests__/setup-ingest.test.js.map +1 -0
  198. package/dist/__tests__/setup-resolver.test.d.ts +14 -0
  199. package/dist/__tests__/setup-resolver.test.d.ts.map +1 -0
  200. package/dist/__tests__/setup-resolver.test.js +228 -0
  201. package/dist/__tests__/setup-resolver.test.js.map +1 -0
  202. package/dist/__tests__/skill-vocabulary.test.d.ts +21 -0
  203. package/dist/__tests__/skill-vocabulary.test.d.ts.map +1 -0
  204. package/dist/__tests__/skill-vocabulary.test.js +192 -0
  205. package/dist/__tests__/skill-vocabulary.test.js.map +1 -0
  206. package/dist/__tests__/spinner-labels.test.d.ts +2 -0
  207. package/dist/__tests__/spinner-labels.test.d.ts.map +1 -0
  208. package/dist/__tests__/spinner-labels.test.js +23 -0
  209. package/dist/__tests__/spinner-labels.test.js.map +1 -0
  210. package/dist/__tests__/state.test.d.ts +6 -0
  211. package/dist/__tests__/state.test.d.ts.map +1 -0
  212. package/dist/__tests__/state.test.js +97 -0
  213. package/dist/__tests__/state.test.js.map +1 -0
  214. package/dist/__tests__/surface-profiles.test.d.ts +2 -0
  215. package/dist/__tests__/surface-profiles.test.d.ts.map +1 -0
  216. package/dist/__tests__/surface-profiles.test.js +233 -0
  217. package/dist/__tests__/surface-profiles.test.js.map +1 -0
  218. package/dist/__tests__/surfaces.test.d.ts +2 -0
  219. package/dist/__tests__/surfaces.test.d.ts.map +1 -0
  220. package/dist/__tests__/surfaces.test.js +46 -0
  221. package/dist/__tests__/surfaces.test.js.map +1 -0
  222. package/dist/__tests__/update-check.test.d.ts +2 -0
  223. package/dist/__tests__/update-check.test.d.ts.map +1 -0
  224. package/dist/__tests__/update-check.test.js +215 -0
  225. package/dist/__tests__/update-check.test.js.map +1 -0
  226. package/dist/__tests__/update.test.js +63 -72
  227. package/dist/__tests__/update.test.js.map +1 -1
  228. package/dist/__tests__/upgrade-runner.test.d.ts +2 -0
  229. package/dist/__tests__/upgrade-runner.test.d.ts.map +1 -0
  230. package/dist/__tests__/upgrade-runner.test.js +54 -0
  231. package/dist/__tests__/upgrade-runner.test.js.map +1 -0
  232. package/dist/__tests__/upgrade.test.d.ts +2 -0
  233. package/dist/__tests__/upgrade.test.d.ts.map +1 -0
  234. package/dist/__tests__/upgrade.test.js +56 -0
  235. package/dist/__tests__/upgrade.test.js.map +1 -0
  236. package/dist/__tests__/vocabulary-leak.test.d.ts +39 -0
  237. package/dist/__tests__/vocabulary-leak.test.d.ts.map +1 -0
  238. package/dist/__tests__/vocabulary-leak.test.js +534 -0
  239. package/dist/__tests__/vocabulary-leak.test.js.map +1 -0
  240. package/dist/__tests__/workspace.test.d.ts +2 -0
  241. package/dist/__tests__/workspace.test.d.ts.map +1 -0
  242. package/dist/__tests__/workspace.test.js +328 -0
  243. package/dist/__tests__/workspace.test.js.map +1 -0
  244. package/dist/commands/__tests__/connect-handoff.test.d.ts +11 -0
  245. package/dist/commands/__tests__/connect-handoff.test.d.ts.map +1 -0
  246. package/dist/commands/__tests__/connect-handoff.test.js +111 -0
  247. package/dist/commands/__tests__/connect-handoff.test.js.map +1 -0
  248. package/dist/commands/__tests__/setup-detect-surfaces.test.d.ts +15 -0
  249. package/dist/commands/__tests__/setup-detect-surfaces.test.d.ts.map +1 -0
  250. package/dist/commands/__tests__/setup-detect-surfaces.test.js +149 -0
  251. package/dist/commands/__tests__/setup-detect-surfaces.test.js.map +1 -0
  252. package/dist/commands/__tests__/setup-state.test.d.ts +2 -0
  253. package/dist/commands/__tests__/setup-state.test.d.ts.map +1 -0
  254. package/dist/commands/__tests__/setup-state.test.js +194 -0
  255. package/dist/commands/__tests__/setup-state.test.js.map +1 -0
  256. package/dist/commands/accept.d.ts.map +1 -1
  257. package/dist/commands/accept.js +10 -6
  258. package/dist/commands/accept.js.map +1 -1
  259. package/dist/commands/admin/cockpit.d.ts +90 -0
  260. package/dist/commands/admin/cockpit.d.ts.map +1 -0
  261. package/dist/commands/admin/cockpit.js +618 -0
  262. package/dist/commands/admin/cockpit.js.map +1 -0
  263. package/dist/commands/admin/index.d.ts +21 -0
  264. package/dist/commands/admin/index.d.ts.map +1 -0
  265. package/dist/commands/admin/index.js +256 -0
  266. package/dist/commands/admin/index.js.map +1 -0
  267. package/dist/commands/admin/inspect.d.ts +30 -0
  268. package/dist/commands/admin/inspect.d.ts.map +1 -0
  269. package/dist/commands/admin/inspect.js +555 -0
  270. package/dist/commands/admin/inspect.js.map +1 -0
  271. package/dist/commands/admin/inspect.test.d.ts +7 -0
  272. package/dist/commands/admin/inspect.test.d.ts.map +1 -0
  273. package/dist/commands/admin/inspect.test.js +90 -0
  274. package/dist/commands/admin/inspect.test.js.map +1 -0
  275. package/dist/commands/admin/manage.d.ts +8 -0
  276. package/dist/commands/admin/manage.d.ts.map +1 -0
  277. package/dist/commands/admin/manage.js +260 -0
  278. package/dist/commands/admin/manage.js.map +1 -0
  279. package/dist/commands/admin/manage.test.d.ts +16 -0
  280. package/dist/commands/admin/manage.test.d.ts.map +1 -0
  281. package/dist/commands/admin/manage.test.js +159 -0
  282. package/dist/commands/admin/manage.test.js.map +1 -0
  283. package/dist/commands/admin/seed.d.ts +75 -0
  284. package/dist/commands/admin/seed.d.ts.map +1 -0
  285. package/dist/commands/admin/seed.js +944 -0
  286. package/dist/commands/admin/seed.js.map +1 -0
  287. package/dist/commands/admin/seed.test.d.ts +11 -0
  288. package/dist/commands/admin/seed.test.d.ts.map +1 -0
  289. package/dist/commands/admin/seed.test.js +127 -0
  290. package/dist/commands/admin/seed.test.js.map +1 -0
  291. package/dist/commands/admin/seedRegistryEntries.generated.d.ts +14 -0
  292. package/dist/commands/admin/seedRegistryEntries.generated.d.ts.map +1 -0
  293. package/dist/commands/admin/seedRegistryEntries.generated.js +144 -0
  294. package/dist/commands/admin/seedRegistryEntries.generated.js.map +1 -0
  295. package/dist/commands/admin/seedRegistryEntries.test.d.ts +11 -0
  296. package/dist/commands/admin/seedRegistryEntries.test.d.ts.map +1 -0
  297. package/dist/commands/admin/seedRegistryEntries.test.js +70 -0
  298. package/dist/commands/admin/seedRegistryEntries.test.js.map +1 -0
  299. package/dist/commands/audit.d.ts.map +1 -1
  300. package/dist/commands/audit.js +34 -7
  301. package/dist/commands/audit.js.map +1 -1
  302. package/dist/commands/authority-domains.d.ts +157 -0
  303. package/dist/commands/authority-domains.d.ts.map +1 -0
  304. package/dist/commands/authority-domains.js +356 -0
  305. package/dist/commands/authority-domains.js.map +1 -0
  306. package/dist/commands/brief.d.ts.map +1 -1
  307. package/dist/commands/brief.js +10 -5
  308. package/dist/commands/brief.js.map +1 -1
  309. package/dist/commands/capture.d.ts +11 -0
  310. package/dist/commands/capture.d.ts.map +1 -1
  311. package/dist/commands/capture.js +269 -19
  312. package/dist/commands/capture.js.map +1 -1
  313. package/dist/commands/chain-walk.d.ts.map +1 -1
  314. package/dist/commands/chain-walk.js +8 -3
  315. package/dist/commands/chain-walk.js.map +1 -1
  316. package/dist/commands/changes.d.ts.map +1 -1
  317. package/dist/commands/changes.js +8 -3
  318. package/dist/commands/changes.js.map +1 -1
  319. package/dist/commands/codex-prep.d.ts +13 -0
  320. package/dist/commands/codex-prep.d.ts.map +1 -0
  321. package/dist/commands/codex-prep.js +125 -0
  322. package/dist/commands/codex-prep.js.map +1 -0
  323. package/dist/commands/collections.d.ts +22 -0
  324. package/dist/commands/collections.d.ts.map +1 -0
  325. package/dist/commands/collections.js +77 -0
  326. package/dist/commands/collections.js.map +1 -0
  327. package/dist/commands/connect-config.test.d.ts +2 -0
  328. package/dist/commands/connect-config.test.d.ts.map +1 -0
  329. package/dist/commands/connect-config.test.js +44 -0
  330. package/dist/commands/connect-config.test.js.map +1 -0
  331. package/dist/commands/connect-context.d.ts +45 -0
  332. package/dist/commands/connect-context.d.ts.map +1 -0
  333. package/dist/commands/connect-context.js +64 -0
  334. package/dist/commands/connect-context.js.map +1 -0
  335. package/dist/commands/connect-context.test.d.ts +2 -0
  336. package/dist/commands/connect-context.test.d.ts.map +1 -0
  337. package/dist/commands/connect-context.test.js +110 -0
  338. package/dist/commands/connect-context.test.js.map +1 -0
  339. package/dist/commands/connect-handoff.d.ts +51 -0
  340. package/dist/commands/connect-handoff.d.ts.map +1 -0
  341. package/dist/commands/connect-handoff.js +70 -0
  342. package/dist/commands/connect-handoff.js.map +1 -0
  343. package/dist/commands/connect-integration.test.d.ts +7 -0
  344. package/dist/commands/connect-integration.test.d.ts.map +1 -0
  345. package/dist/commands/connect-integration.test.js +212 -0
  346. package/dist/commands/connect-integration.test.js.map +1 -0
  347. package/dist/commands/connect-screens.d.ts +23 -0
  348. package/dist/commands/connect-screens.d.ts.map +1 -0
  349. package/dist/commands/connect-screens.js +90 -0
  350. package/dist/commands/connect-screens.js.map +1 -0
  351. package/dist/commands/connect.d.ts +36 -0
  352. package/dist/commands/connect.d.ts.map +1 -0
  353. package/dist/commands/connect.js +264 -0
  354. package/dist/commands/connect.js.map +1 -0
  355. package/dist/commands/connect.test.d.ts +6 -0
  356. package/dist/commands/connect.test.d.ts.map +1 -0
  357. package/dist/commands/connect.test.js +297 -0
  358. package/dist/commands/connect.test.js.map +1 -0
  359. package/dist/commands/constellation.d.ts.map +1 -1
  360. package/dist/commands/constellation.js +8 -3
  361. package/dist/commands/constellation.js.map +1 -1
  362. package/dist/commands/context.d.ts.map +1 -1
  363. package/dist/commands/context.js +8 -3
  364. package/dist/commands/context.js.map +1 -1
  365. package/dist/commands/cross-cut.js +2 -2
  366. package/dist/commands/cross-cut.js.map +1 -1
  367. package/dist/commands/doctor.d.ts +18 -0
  368. package/dist/commands/doctor.d.ts.map +1 -0
  369. package/dist/commands/doctor.js +297 -0
  370. package/dist/commands/doctor.js.map +1 -0
  371. package/dist/commands/doctor.test.d.ts +8 -0
  372. package/dist/commands/doctor.test.d.ts.map +1 -0
  373. package/dist/commands/doctor.test.js +461 -0
  374. package/dist/commands/doctor.test.js.map +1 -0
  375. package/dist/commands/fields.d.ts.map +1 -1
  376. package/dist/commands/fields.js +8 -4
  377. package/dist/commands/fields.js.map +1 -1
  378. package/dist/commands/get.d.ts.map +1 -1
  379. package/dist/commands/get.js +14 -6
  380. package/dist/commands/get.js.map +1 -1
  381. package/dist/commands/handshake.d.ts +233 -2
  382. package/dist/commands/handshake.d.ts.map +1 -1
  383. package/dist/commands/handshake.js +2366 -81
  384. package/dist/commands/handshake.js.map +1 -1
  385. package/dist/commands/ingest.d.ts.map +1 -1
  386. package/dist/commands/ingest.js +17 -9
  387. package/dist/commands/ingest.js.map +1 -1
  388. package/dist/commands/init.d.ts +14 -0
  389. package/dist/commands/init.d.ts.map +1 -0
  390. package/dist/commands/init.js +109 -0
  391. package/dist/commands/init.js.map +1 -0
  392. package/dist/commands/login.d.ts +4 -0
  393. package/dist/commands/login.d.ts.map +1 -1
  394. package/dist/commands/login.js +101 -38
  395. package/dist/commands/login.js.map +1 -1
  396. package/dist/commands/method.d.ts +99 -0
  397. package/dist/commands/method.d.ts.map +1 -0
  398. package/dist/commands/method.js +785 -0
  399. package/dist/commands/method.js.map +1 -0
  400. package/dist/commands/migrate-setup.d.ts +18 -0
  401. package/dist/commands/migrate-setup.d.ts.map +1 -0
  402. package/dist/commands/migrate-setup.js +198 -0
  403. package/dist/commands/migrate-setup.js.map +1 -0
  404. package/dist/commands/orient.d.ts +183 -3
  405. package/dist/commands/orient.d.ts.map +1 -1
  406. package/dist/commands/orient.js +122 -6
  407. package/dist/commands/orient.js.map +1 -1
  408. package/dist/commands/profile.d.ts +34 -0
  409. package/dist/commands/profile.d.ts.map +1 -0
  410. package/dist/commands/profile.js +165 -0
  411. package/dist/commands/profile.js.map +1 -0
  412. package/dist/commands/promote.d.ts +4 -1
  413. package/dist/commands/promote.d.ts.map +1 -1
  414. package/dist/commands/promote.js +164 -30
  415. package/dist/commands/promote.js.map +1 -1
  416. package/dist/commands/proof-run.d.ts +51 -0
  417. package/dist/commands/proof-run.d.ts.map +1 -0
  418. package/dist/commands/proof-run.js +209 -0
  419. package/dist/commands/proof-run.js.map +1 -0
  420. package/dist/commands/proposals.js +2 -2
  421. package/dist/commands/proposals.js.map +1 -1
  422. package/dist/commands/reject.d.ts.map +1 -1
  423. package/dist/commands/reject.js +14 -7
  424. package/dist/commands/reject.js.map +1 -1
  425. package/dist/commands/relate.d.ts.map +1 -1
  426. package/dist/commands/relate.js +49 -16
  427. package/dist/commands/relate.js.map +1 -1
  428. package/dist/commands/search.js +2 -2
  429. package/dist/commands/search.js.map +1 -1
  430. package/dist/commands/session.d.ts +26 -2
  431. package/dist/commands/session.d.ts.map +1 -1
  432. package/dist/commands/session.js +355 -41
  433. package/dist/commands/session.js.map +1 -1
  434. package/dist/commands/setup-audit.d.ts +59 -0
  435. package/dist/commands/setup-audit.d.ts.map +1 -0
  436. package/dist/commands/setup-audit.js +250 -0
  437. package/dist/commands/setup-audit.js.map +1 -0
  438. package/dist/commands/setup-detect-surfaces.d.ts +38 -0
  439. package/dist/commands/setup-detect-surfaces.d.ts.map +1 -0
  440. package/dist/commands/setup-detect-surfaces.js +76 -0
  441. package/dist/commands/setup-detect-surfaces.js.map +1 -0
  442. package/dist/commands/setup-ingest.d.ts +17 -0
  443. package/dist/commands/setup-ingest.d.ts.map +1 -0
  444. package/dist/commands/setup-ingest.js +226 -0
  445. package/dist/commands/setup-ingest.js.map +1 -0
  446. package/dist/commands/setup-resolver.d.ts +58 -0
  447. package/dist/commands/setup-resolver.d.ts.map +1 -0
  448. package/dist/commands/setup-resolver.js +150 -0
  449. package/dist/commands/setup-resolver.js.map +1 -0
  450. package/dist/commands/setup-state.d.ts +42 -0
  451. package/dist/commands/setup-state.d.ts.map +1 -0
  452. package/dist/commands/setup-state.js +93 -0
  453. package/dist/commands/setup-state.js.map +1 -0
  454. package/dist/commands/setup.d.ts +23 -0
  455. package/dist/commands/setup.d.ts.map +1 -0
  456. package/dist/commands/setup.js +69 -0
  457. package/dist/commands/setup.js.map +1 -0
  458. package/dist/commands/update.d.ts +1 -0
  459. package/dist/commands/update.d.ts.map +1 -1
  460. package/dist/commands/update.js +66 -26
  461. package/dist/commands/update.js.map +1 -1
  462. package/dist/commands/upgrade.d.ts +5 -0
  463. package/dist/commands/upgrade.d.ts.map +1 -0
  464. package/dist/commands/upgrade.js +110 -0
  465. package/dist/commands/upgrade.js.map +1 -0
  466. package/dist/commands/usage.d.ts +40 -0
  467. package/dist/commands/usage.d.ts.map +1 -0
  468. package/dist/commands/usage.js +232 -0
  469. package/dist/commands/usage.js.map +1 -0
  470. package/dist/commands/verify.d.ts.map +1 -1
  471. package/dist/commands/verify.js +14 -7
  472. package/dist/commands/verify.js.map +1 -1
  473. package/dist/commands/welcome.d.ts +21 -0
  474. package/dist/commands/welcome.d.ts.map +1 -0
  475. package/dist/commands/welcome.js +50 -0
  476. package/dist/commands/welcome.js.map +1 -0
  477. package/dist/commands/whoami.d.ts +12 -0
  478. package/dist/commands/whoami.d.ts.map +1 -0
  479. package/dist/commands/whoami.js +70 -0
  480. package/dist/commands/whoami.js.map +1 -0
  481. package/dist/commands/whoami.test.d.ts +2 -0
  482. package/dist/commands/whoami.test.d.ts.map +1 -0
  483. package/dist/commands/whoami.test.js +50 -0
  484. package/dist/commands/whoami.test.js.map +1 -0
  485. package/dist/commands/workspace.d.ts +113 -0
  486. package/dist/commands/workspace.d.ts.map +1 -0
  487. package/dist/commands/workspace.js +263 -0
  488. package/dist/commands/workspace.js.map +1 -0
  489. package/dist/formatters/__tests__/orient-provenance.test.d.ts +7 -0
  490. package/dist/formatters/__tests__/orient-provenance.test.d.ts.map +1 -0
  491. package/dist/formatters/__tests__/orient-provenance.test.js +454 -0
  492. package/dist/formatters/__tests__/orient-provenance.test.js.map +1 -0
  493. package/dist/formatters/__tests__/session.test.d.ts +2 -0
  494. package/dist/formatters/__tests__/session.test.d.ts.map +1 -0
  495. package/dist/formatters/__tests__/session.test.js +113 -0
  496. package/dist/formatters/__tests__/session.test.js.map +1 -0
  497. package/dist/formatters/audit.d.ts +6 -0
  498. package/dist/formatters/audit.d.ts.map +1 -1
  499. package/dist/formatters/audit.js.map +1 -1
  500. package/dist/formatters/capture.d.ts +26 -3
  501. package/dist/formatters/capture.d.ts.map +1 -1
  502. package/dist/formatters/capture.js +25 -1
  503. package/dist/formatters/capture.js.map +1 -1
  504. package/dist/formatters/collections.d.ts +40 -0
  505. package/dist/formatters/collections.d.ts.map +1 -0
  506. package/dist/formatters/collections.js +93 -0
  507. package/dist/formatters/collections.js.map +1 -0
  508. package/dist/formatters/entry.d.ts +27 -4
  509. package/dist/formatters/entry.d.ts.map +1 -1
  510. package/dist/formatters/entry.js +67 -14
  511. package/dist/formatters/entry.js.map +1 -1
  512. package/dist/formatters/handshake.d.ts +45 -0
  513. package/dist/formatters/handshake.d.ts.map +1 -1
  514. package/dist/formatters/handshake.js +150 -3
  515. package/dist/formatters/handshake.js.map +1 -1
  516. package/dist/formatters/orient.d.ts +222 -5
  517. package/dist/formatters/orient.d.ts.map +1 -1
  518. package/dist/formatters/orient.js +308 -34
  519. package/dist/formatters/orient.js.map +1 -1
  520. package/dist/formatters/promote.d.ts +1 -0
  521. package/dist/formatters/promote.d.ts.map +1 -1
  522. package/dist/formatters/promote.js +1 -0
  523. package/dist/formatters/promote.js.map +1 -1
  524. package/dist/formatters/relate.d.ts +2 -0
  525. package/dist/formatters/relate.d.ts.map +1 -1
  526. package/dist/formatters/relate.js +3 -0
  527. package/dist/formatters/relate.js.map +1 -1
  528. package/dist/formatters/search.d.ts +0 -4
  529. package/dist/formatters/search.d.ts.map +1 -1
  530. package/dist/formatters/search.js +4 -1
  531. package/dist/formatters/search.js.map +1 -1
  532. package/dist/formatters/session.d.ts +39 -2
  533. package/dist/formatters/session.d.ts.map +1 -1
  534. package/dist/formatters/session.js +130 -9
  535. package/dist/formatters/session.js.map +1 -1
  536. package/dist/formatters/update.d.ts.map +1 -1
  537. package/dist/formatters/update.js +2 -0
  538. package/dist/formatters/update.js.map +1 -1
  539. package/dist/generators/adapters.d.ts +37 -3
  540. package/dist/generators/adapters.d.ts.map +1 -1
  541. package/dist/generators/adapters.js +196 -8
  542. package/dist/generators/adapters.js.map +1 -1
  543. package/dist/generators/adapters.test.d.ts +2 -0
  544. package/dist/generators/adapters.test.d.ts.map +1 -0
  545. package/dist/generators/adapters.test.js +27 -0
  546. package/dist/generators/adapters.test.js.map +1 -0
  547. package/dist/generators/archetypes.d.ts +52 -0
  548. package/dist/generators/archetypes.d.ts.map +1 -0
  549. package/dist/generators/archetypes.js +190 -0
  550. package/dist/generators/archetypes.js.map +1 -0
  551. package/dist/generators/archetypes.test.d.ts +2 -0
  552. package/dist/generators/archetypes.test.d.ts.map +1 -0
  553. package/dist/generators/archetypes.test.js +272 -0
  554. package/dist/generators/archetypes.test.js.map +1 -0
  555. package/dist/generators/boundary-manifest.d.ts +29 -0
  556. package/dist/generators/boundary-manifest.d.ts.map +1 -0
  557. package/dist/generators/boundary-manifest.js +183 -0
  558. package/dist/generators/boundary-manifest.js.map +1 -0
  559. package/dist/generators/boundary-manifest.test.d.ts +2 -0
  560. package/dist/generators/boundary-manifest.test.d.ts.map +1 -0
  561. package/dist/generators/boundary-manifest.test.js +91 -0
  562. package/dist/generators/boundary-manifest.test.js.map +1 -0
  563. package/dist/generators/chain-classifier.d.ts +63 -0
  564. package/dist/generators/chain-classifier.d.ts.map +1 -0
  565. package/dist/generators/chain-classifier.js +131 -0
  566. package/dist/generators/chain-classifier.js.map +1 -0
  567. package/dist/generators/chain-classifier.test.d.ts +2 -0
  568. package/dist/generators/chain-classifier.test.d.ts.map +1 -0
  569. package/dist/generators/chain-classifier.test.js +371 -0
  570. package/dist/generators/chain-classifier.test.js.map +1 -0
  571. package/dist/generators/chain-rules.d.ts +42 -0
  572. package/dist/generators/chain-rules.d.ts.map +1 -0
  573. package/dist/generators/chain-rules.js +152 -0
  574. package/dist/generators/chain-rules.js.map +1 -0
  575. package/dist/generators/chain-rules.test.d.ts +2 -0
  576. package/dist/generators/chain-rules.test.d.ts.map +1 -0
  577. package/dist/generators/chain-rules.test.js +211 -0
  578. package/dist/generators/chain-rules.test.js.map +1 -0
  579. package/dist/generators/context-md.d.ts +1 -1
  580. package/dist/generators/context-md.d.ts.map +1 -1
  581. package/dist/generators/context-md.js +18 -7
  582. package/dist/generators/context-md.js.map +1 -1
  583. package/dist/generators/handshake-diff.d.ts +67 -0
  584. package/dist/generators/handshake-diff.d.ts.map +1 -0
  585. package/dist/generators/handshake-diff.js +183 -0
  586. package/dist/generators/handshake-diff.js.map +1 -0
  587. package/dist/generators/handshake-diff.test.d.ts +2 -0
  588. package/dist/generators/handshake-diff.test.d.ts.map +1 -0
  589. package/dist/generators/handshake-diff.test.js +264 -0
  590. package/dist/generators/handshake-diff.test.js.map +1 -0
  591. package/dist/generators/manifest.d.ts +115 -0
  592. package/dist/generators/manifest.d.ts.map +1 -0
  593. package/dist/generators/manifest.js +277 -0
  594. package/dist/generators/manifest.js.map +1 -0
  595. package/dist/generators/portable-knowledge.d.ts +96 -9
  596. package/dist/generators/portable-knowledge.d.ts.map +1 -1
  597. package/dist/generators/portable-knowledge.js +367 -17
  598. package/dist/generators/portable-knowledge.js.map +1 -1
  599. package/dist/generators/portable-knowledge.test.js +529 -1
  600. package/dist/generators/portable-knowledge.test.js.map +1 -1
  601. package/dist/generators/region-projections.d.ts +18 -0
  602. package/dist/generators/region-projections.d.ts.map +1 -0
  603. package/dist/generators/region-projections.js +49 -0
  604. package/dist/generators/region-projections.js.map +1 -0
  605. package/dist/generators/region-projections.test.d.ts +2 -0
  606. package/dist/generators/region-projections.test.d.ts.map +1 -0
  607. package/dist/generators/region-projections.test.js +63 -0
  608. package/dist/generators/region-projections.test.js.map +1 -0
  609. package/dist/generators/region.d.ts +24 -0
  610. package/dist/generators/region.d.ts.map +1 -0
  611. package/dist/generators/region.js +87 -0
  612. package/dist/generators/region.js.map +1 -0
  613. package/dist/generators/region.test.d.ts +2 -0
  614. package/dist/generators/region.test.d.ts.map +1 -0
  615. package/dist/generators/region.test.js +126 -0
  616. package/dist/generators/region.test.js.map +1 -0
  617. package/dist/generators/surface-profiles.d.ts +48 -0
  618. package/dist/generators/surface-profiles.d.ts.map +1 -0
  619. package/dist/generators/surface-profiles.js +98 -0
  620. package/dist/generators/surface-profiles.js.map +1 -0
  621. package/dist/index.js +775 -250
  622. package/dist/index.js.map +1 -1
  623. package/dist/lib/activation.d.ts +28 -0
  624. package/dist/lib/activation.d.ts.map +1 -0
  625. package/dist/lib/activation.js +57 -0
  626. package/dist/lib/activation.js.map +1 -0
  627. package/dist/lib/activation.test.d.ts +6 -0
  628. package/dist/lib/activation.test.d.ts.map +1 -0
  629. package/dist/lib/activation.test.js +121 -0
  630. package/dist/lib/activation.test.js.map +1 -0
  631. package/dist/lib/canonicalRefs.d.ts +141 -0
  632. package/dist/lib/canonicalRefs.d.ts.map +1 -0
  633. package/dist/lib/canonicalRefs.js +150 -0
  634. package/dist/lib/canonicalRefs.js.map +1 -0
  635. package/dist/lib/client.d.ts +33 -6
  636. package/dist/lib/client.d.ts.map +1 -1
  637. package/dist/lib/client.js +201 -42
  638. package/dist/lib/client.js.map +1 -1
  639. package/dist/lib/collectionRegistry.d.ts +40 -0
  640. package/dist/lib/collectionRegistry.d.ts.map +1 -0
  641. package/dist/lib/collectionRegistry.js +112 -0
  642. package/dist/lib/collectionRegistry.js.map +1 -0
  643. package/dist/lib/compose-wrapup-view.d.ts +48 -0
  644. package/dist/lib/compose-wrapup-view.d.ts.map +1 -0
  645. package/dist/lib/compose-wrapup-view.js +37 -0
  646. package/dist/lib/compose-wrapup-view.js.map +1 -0
  647. package/dist/lib/config.d.ts +204 -4
  648. package/dist/lib/config.d.ts.map +1 -1
  649. package/dist/lib/config.js +594 -42
  650. package/dist/lib/config.js.map +1 -1
  651. package/dist/lib/connectKeyLabel.d.ts +9 -0
  652. package/dist/lib/connectKeyLabel.d.ts.map +1 -0
  653. package/dist/lib/connectKeyLabel.js +12 -0
  654. package/dist/lib/connectKeyLabel.js.map +1 -0
  655. package/dist/lib/constants.d.ts +46 -0
  656. package/dist/lib/constants.d.ts.map +1 -0
  657. package/dist/lib/constants.js +83 -0
  658. package/dist/lib/constants.js.map +1 -0
  659. package/dist/lib/conversation-engine.d.ts +45 -0
  660. package/dist/lib/conversation-engine.d.ts.map +1 -0
  661. package/dist/lib/conversation-engine.js +112 -0
  662. package/dist/lib/conversation-engine.js.map +1 -0
  663. package/dist/lib/conversation-phases.d.ts +59 -0
  664. package/dist/lib/conversation-phases.d.ts.map +1 -0
  665. package/dist/lib/conversation-phases.js +11 -0
  666. package/dist/lib/conversation-phases.js.map +1 -0
  667. package/dist/lib/conversation-signals.d.ts +30 -0
  668. package/dist/lib/conversation-signals.d.ts.map +1 -0
  669. package/dist/lib/conversation-signals.js +64 -0
  670. package/dist/lib/conversation-signals.js.map +1 -0
  671. package/dist/lib/deployment.d.ts +23 -0
  672. package/dist/lib/deployment.d.ts.map +1 -0
  673. package/dist/lib/deployment.js +78 -0
  674. package/dist/lib/deployment.js.map +1 -0
  675. package/dist/lib/deployment.test.d.ts +5 -0
  676. package/dist/lib/deployment.test.d.ts.map +1 -0
  677. package/dist/lib/deployment.test.js +54 -0
  678. package/dist/lib/deployment.test.js.map +1 -0
  679. package/dist/lib/errors.d.ts +63 -0
  680. package/dist/lib/errors.d.ts.map +1 -0
  681. package/dist/lib/errors.js +72 -0
  682. package/dist/lib/errors.js.map +1 -0
  683. package/dist/lib/experiment.d.ts +18 -0
  684. package/dist/lib/experiment.d.ts.map +1 -0
  685. package/dist/lib/experiment.js +28 -0
  686. package/dist/lib/experiment.js.map +1 -0
  687. package/dist/lib/format.d.ts +10 -0
  688. package/dist/lib/format.d.ts.map +1 -0
  689. package/dist/lib/format.js +27 -0
  690. package/dist/lib/format.js.map +1 -0
  691. package/dist/lib/glossary.d.ts +19 -0
  692. package/dist/lib/glossary.d.ts.map +1 -0
  693. package/dist/lib/glossary.js +53 -0
  694. package/dist/lib/glossary.js.map +1 -0
  695. package/dist/lib/hook-intents.d.ts +51 -0
  696. package/dist/lib/hook-intents.d.ts.map +1 -0
  697. package/dist/lib/hook-intents.js +85 -0
  698. package/dist/lib/hook-intents.js.map +1 -0
  699. package/dist/lib/inferSourceDate.d.ts +12 -0
  700. package/dist/lib/inferSourceDate.d.ts.map +1 -0
  701. package/dist/lib/inferSourceDate.js +44 -0
  702. package/dist/lib/inferSourceDate.js.map +1 -0
  703. package/dist/lib/method-registry.d.ts +32 -0
  704. package/dist/lib/method-registry.d.ts.map +1 -0
  705. package/dist/lib/method-registry.js +53 -0
  706. package/dist/lib/method-registry.js.map +1 -0
  707. package/dist/lib/normalizeMaterializedFilename.d.ts +28 -0
  708. package/dist/lib/normalizeMaterializedFilename.d.ts.map +1 -0
  709. package/dist/lib/normalizeMaterializedFilename.js +56 -0
  710. package/dist/lib/normalizeMaterializedFilename.js.map +1 -0
  711. package/dist/lib/normalizeMaterializedFilename.test.d.ts +16 -0
  712. package/dist/lib/normalizeMaterializedFilename.test.d.ts.map +1 -0
  713. package/dist/lib/normalizeMaterializedFilename.test.js +90 -0
  714. package/dist/lib/normalizeMaterializedFilename.test.js.map +1 -0
  715. package/dist/lib/notice-marker.d.ts +3 -0
  716. package/dist/lib/notice-marker.d.ts.map +1 -0
  717. package/dist/lib/notice-marker.js +53 -0
  718. package/dist/lib/notice-marker.js.map +1 -0
  719. package/dist/lib/onboarding-path-b.d.ts +10 -0
  720. package/dist/lib/onboarding-path-b.d.ts.map +1 -0
  721. package/dist/lib/onboarding-path-b.js +213 -0
  722. package/dist/lib/onboarding-path-b.js.map +1 -0
  723. package/dist/lib/onboarding-shared.d.ts +80 -0
  724. package/dist/lib/onboarding-shared.d.ts.map +1 -0
  725. package/dist/lib/onboarding-shared.js +174 -0
  726. package/dist/lib/onboarding-shared.js.map +1 -0
  727. package/dist/lib/onboarding-topics.d.ts +27 -0
  728. package/dist/lib/onboarding-topics.d.ts.map +1 -0
  729. package/dist/lib/onboarding-topics.js +57 -0
  730. package/dist/lib/onboarding-topics.js.map +1 -0
  731. package/dist/lib/onboarding.d.ts +17 -0
  732. package/dist/lib/onboarding.d.ts.map +1 -0
  733. package/dist/lib/onboarding.js +350 -0
  734. package/dist/lib/onboarding.js.map +1 -0
  735. package/dist/lib/profiles.d.ts +41 -0
  736. package/dist/lib/profiles.d.ts.map +1 -0
  737. package/dist/lib/profiles.js +188 -0
  738. package/dist/lib/profiles.js.map +1 -0
  739. package/dist/lib/prompts.d.ts +65 -0
  740. package/dist/lib/prompts.d.ts.map +1 -0
  741. package/dist/lib/prompts.js +132 -0
  742. package/dist/lib/prompts.js.map +1 -0
  743. package/dist/lib/repo-detect.d.ts +19 -0
  744. package/dist/lib/repo-detect.d.ts.map +1 -1
  745. package/dist/lib/repo-detect.js +25 -0
  746. package/dist/lib/repo-detect.js.map +1 -1
  747. package/dist/lib/runner.d.ts +2 -0
  748. package/dist/lib/runner.d.ts.map +1 -1
  749. package/dist/lib/runner.js +21 -7
  750. package/dist/lib/runner.js.map +1 -1
  751. package/dist/lib/session.d.ts +35 -0
  752. package/dist/lib/session.d.ts.map +1 -1
  753. package/dist/lib/session.js +94 -3
  754. package/dist/lib/session.js.map +1 -1
  755. package/dist/lib/spinner.d.ts +27 -0
  756. package/dist/lib/spinner.d.ts.map +1 -0
  757. package/dist/lib/spinner.js +76 -0
  758. package/dist/lib/spinner.js.map +1 -0
  759. package/dist/lib/spinner.test.d.ts +2 -0
  760. package/dist/lib/spinner.test.d.ts.map +1 -0
  761. package/dist/lib/spinner.test.js +39 -0
  762. package/dist/lib/spinner.test.js.map +1 -0
  763. package/dist/lib/startup-resolution-signals.d.ts +34 -0
  764. package/dist/lib/startup-resolution-signals.d.ts.map +1 -0
  765. package/dist/lib/startup-resolution-signals.js +118 -0
  766. package/dist/lib/startup-resolution-signals.js.map +1 -0
  767. package/dist/lib/startup-resolution-signals.test.d.ts +2 -0
  768. package/dist/lib/startup-resolution-signals.test.d.ts.map +1 -0
  769. package/dist/lib/startup-resolution-signals.test.js +113 -0
  770. package/dist/lib/startup-resolution-signals.test.js.map +1 -0
  771. package/dist/lib/state.d.ts +51 -0
  772. package/dist/lib/state.d.ts.map +1 -0
  773. package/dist/lib/state.js +90 -0
  774. package/dist/lib/state.js.map +1 -0
  775. package/dist/lib/strip.d.ts +1 -0
  776. package/dist/lib/strip.d.ts.map +1 -1
  777. package/dist/lib/strip.js +15 -0
  778. package/dist/lib/strip.js.map +1 -1
  779. package/dist/lib/style.d.ts +96 -0
  780. package/dist/lib/style.d.ts.map +1 -0
  781. package/dist/lib/style.js +169 -0
  782. package/dist/lib/style.js.map +1 -0
  783. package/dist/lib/style.test.d.ts +7 -0
  784. package/dist/lib/style.test.d.ts.map +1 -0
  785. package/dist/lib/style.test.js +263 -0
  786. package/dist/lib/style.test.js.map +1 -0
  787. package/dist/lib/telemetry.d.ts +15 -0
  788. package/dist/lib/telemetry.d.ts.map +1 -0
  789. package/dist/lib/telemetry.js +47 -0
  790. package/dist/lib/telemetry.js.map +1 -0
  791. package/dist/lib/tokenConstants.d.ts +19 -0
  792. package/dist/lib/tokenConstants.d.ts.map +1 -0
  793. package/dist/lib/tokenConstants.js +19 -0
  794. package/dist/lib/tokenConstants.js.map +1 -0
  795. package/dist/lib/update-check.d.ts +56 -0
  796. package/dist/lib/update-check.d.ts.map +1 -0
  797. package/dist/lib/update-check.js +296 -0
  798. package/dist/lib/update-check.js.map +1 -0
  799. package/dist/lib/upgrade-runner.d.ts +22 -0
  800. package/dist/lib/upgrade-runner.d.ts.map +1 -0
  801. package/dist/lib/upgrade-runner.js +110 -0
  802. package/dist/lib/upgrade-runner.js.map +1 -0
  803. package/dist/lib/wizard-surfaces.d.ts +47 -0
  804. package/dist/lib/wizard-surfaces.d.ts.map +1 -0
  805. package/dist/lib/wizard-surfaces.js +176 -0
  806. package/dist/lib/wizard-surfaces.js.map +1 -0
  807. package/dist/lib/wizard-surfaces.test.d.ts +2 -0
  808. package/dist/lib/wizard-surfaces.test.d.ts.map +1 -0
  809. package/dist/lib/wizard-surfaces.test.js +127 -0
  810. package/dist/lib/wizard-surfaces.test.js.map +1 -0
  811. package/dist/lib/wizard-trust.d.ts +31 -0
  812. package/dist/lib/wizard-trust.d.ts.map +1 -0
  813. package/dist/lib/wizard-trust.js +66 -0
  814. package/dist/lib/wizard-trust.js.map +1 -0
  815. package/dist/lib/wizard-trust.test.d.ts +2 -0
  816. package/dist/lib/wizard-trust.test.d.ts.map +1 -0
  817. package/dist/lib/wizard-trust.test.js +32 -0
  818. package/dist/lib/wizard-trust.test.js.map +1 -0
  819. package/dist/lib/workspace-probe.d.ts +19 -0
  820. package/dist/lib/workspace-probe.d.ts.map +1 -0
  821. package/dist/lib/workspace-probe.js +27 -0
  822. package/dist/lib/workspace-probe.js.map +1 -0
  823. package/dist/lib/workspaceVocabCache.d.ts +60 -0
  824. package/dist/lib/workspaceVocabCache.d.ts.map +1 -0
  825. package/dist/lib/workspaceVocabCache.js +98 -0
  826. package/dist/lib/workspaceVocabCache.js.map +1 -0
  827. package/dist/setup/__tests__/coach-traces.test.d.ts +2 -0
  828. package/dist/setup/__tests__/coach-traces.test.d.ts.map +1 -0
  829. package/dist/setup/__tests__/coach-traces.test.js +189 -0
  830. package/dist/setup/__tests__/coach-traces.test.js.map +1 -0
  831. package/dist/setup/__tests__/setup-commands.test.d.ts +2 -0
  832. package/dist/setup/__tests__/setup-commands.test.d.ts.map +1 -0
  833. package/dist/setup/__tests__/setup-commands.test.js +177 -0
  834. package/dist/setup/__tests__/setup-commands.test.js.map +1 -0
  835. package/dist/setup/__tests__/state-machine.test.d.ts +2 -0
  836. package/dist/setup/__tests__/state-machine.test.d.ts.map +1 -0
  837. package/dist/setup/__tests__/state-machine.test.js +341 -0
  838. package/dist/setup/__tests__/state-machine.test.js.map +1 -0
  839. package/dist/setup/detect-surfaces.d.ts +21 -0
  840. package/dist/setup/detect-surfaces.d.ts.map +1 -0
  841. package/dist/setup/detect-surfaces.js +39 -0
  842. package/dist/setup/detect-surfaces.js.map +1 -0
  843. package/dist/setup/manifest-writer.d.ts +17 -0
  844. package/dist/setup/manifest-writer.d.ts.map +1 -0
  845. package/dist/setup/manifest-writer.js +153 -0
  846. package/dist/setup/manifest-writer.js.map +1 -0
  847. package/dist/setup/perimeter.d.ts +72 -0
  848. package/dist/setup/perimeter.d.ts.map +1 -0
  849. package/dist/setup/perimeter.js +128 -0
  850. package/dist/setup/perimeter.js.map +1 -0
  851. package/dist/setup/state-machine.d.ts +67 -0
  852. package/dist/setup/state-machine.d.ts.map +1 -0
  853. package/dist/setup/state-machine.js +124 -0
  854. package/dist/setup/state-machine.js.map +1 -0
  855. package/dist/surfaces/__tests__/adapter.test.d.ts +2 -0
  856. package/dist/surfaces/__tests__/adapter.test.d.ts.map +1 -0
  857. package/dist/surfaces/__tests__/adapter.test.js +90 -0
  858. package/dist/surfaces/__tests__/adapter.test.js.map +1 -0
  859. package/dist/surfaces/__tests__/pb-setup-passthrough.test.d.ts +2 -0
  860. package/dist/surfaces/__tests__/pb-setup-passthrough.test.d.ts.map +1 -0
  861. package/dist/surfaces/__tests__/pb-setup-passthrough.test.js +132 -0
  862. package/dist/surfaces/__tests__/pb-setup-passthrough.test.js.map +1 -0
  863. package/dist/surfaces/__tests__/telemetry.test.d.ts +2 -0
  864. package/dist/surfaces/__tests__/telemetry.test.d.ts.map +1 -0
  865. package/dist/surfaces/__tests__/telemetry.test.js +55 -0
  866. package/dist/surfaces/__tests__/telemetry.test.js.map +1 -0
  867. package/dist/surfaces/adapter.d.ts +70 -0
  868. package/dist/surfaces/adapter.d.ts.map +1 -0
  869. package/dist/surfaces/adapter.js +2 -0
  870. package/dist/surfaces/adapter.js.map +1 -0
  871. package/dist/surfaces/adapters/claude.d.ts +3 -0
  872. package/dist/surfaces/adapters/claude.d.ts.map +1 -0
  873. package/dist/surfaces/adapters/claude.js +67 -0
  874. package/dist/surfaces/adapters/claude.js.map +1 -0
  875. package/dist/surfaces/adapters/codex.d.ts +3 -0
  876. package/dist/surfaces/adapters/codex.d.ts.map +1 -0
  877. package/dist/surfaces/adapters/codex.js +61 -0
  878. package/dist/surfaces/adapters/codex.js.map +1 -0
  879. package/dist/surfaces/adapters/copilot.d.ts +3 -0
  880. package/dist/surfaces/adapters/copilot.d.ts.map +1 -0
  881. package/dist/surfaces/adapters/copilot.js +59 -0
  882. package/dist/surfaces/adapters/copilot.js.map +1 -0
  883. package/dist/surfaces/adapters/cursor.d.ts +3 -0
  884. package/dist/surfaces/adapters/cursor.d.ts.map +1 -0
  885. package/dist/surfaces/adapters/cursor.js +78 -0
  886. package/dist/surfaces/adapters/cursor.js.map +1 -0
  887. package/dist/surfaces/registry.d.ts +76 -0
  888. package/dist/surfaces/registry.d.ts.map +1 -0
  889. package/dist/surfaces/registry.js +117 -0
  890. package/dist/surfaces/registry.js.map +1 -0
  891. package/dist/surfaces/telemetry.d.ts +17 -0
  892. package/dist/surfaces/telemetry.d.ts.map +1 -0
  893. package/dist/surfaces/telemetry.js +31 -0
  894. package/dist/surfaces/telemetry.js.map +1 -0
  895. package/package.json +12 -4
  896. package/templates/archetypes/boundary.md +23 -0
  897. package/templates/archetypes/constraint.md +23 -0
  898. package/templates/archetypes/convention.md +23 -0
  899. package/templates/archetypes/policy.md +23 -0
  900. package/templates/archetypes/quality-gate.md +23 -0
  901. package/templates/archetypes/workflow.md +23 -0
  902. package/templates/general/code-integrity.md +11 -0
  903. package/templates/general/getting-started.md +12 -0
  904. package/templates/method-registry.json +16 -0
  905. package/templates/node-ts/code-integrity.md +13 -0
  906. package/templates/node-ts/testing.md +12 -0
  907. package/templates/python/code-integrity.md +13 -0
  908. package/templates/python/testing.md +12 -0
@@ -1,19 +1,253 @@
1
1
  /**
2
2
  * pb handshake — generate context files for AI developer tools.
3
- * The fourth delivery surface: context export (GLO-63, DEC-161).
3
+ * Context export wiring (read-only filesystem bridge; GLO-63, DEC-161) — not a product surface.
4
4
  */
5
- import { mkdirSync, writeFileSync, existsSync, readFileSync } from 'fs';
6
- import { join } from 'path';
5
+ import { mkdirSync, writeFileSync, existsSync, readFileSync, readdirSync, copyFileSync, appendFileSync, unlinkSync, statSync, renameSync, rmSync, realpathSync } from 'fs';
6
+ import { join, dirname, resolve, basename, relative, sep, isAbsolute } from 'path';
7
7
  import { homedir } from 'os';
8
- import { createInterface } from 'readline';
8
+ import { fileURLToPath } from 'url';
9
+ import { createHash } from 'crypto';
10
+ import { execSync } from 'child_process';
9
11
  import { getConfigOrGuide } from '../lib/config.js';
10
- import { mcpCall } from '../lib/client.js';
11
- import { detectRepo } from '../lib/repo-detect.js';
12
+ import { select as promptSelect, confirm as promptConfirm } from '../lib/prompts.js';
13
+ import { composeHooksFromIntents, getHookStatusForSurface } from '../lib/hook-intents.js';
14
+ import { kernelCall, kernelCallWithSession } from '../lib/client.js';
15
+ import { readSession } from '../lib/session.js';
16
+ import { detectRepo, extractWorkspaceProfile } from '../lib/repo-detect.js';
12
17
  import { generateContextMd } from '../generators/context-md.js';
13
18
  import { generateBriefingMd } from '../generators/briefing-md.js';
14
- import { MARKER, generateClaudeMd, generateCursorMdc, generateCopilotMd } from '../generators/adapters.js';
15
- import { readCanonicalSkills, readCanonicalRules, generateCursorSkill, generateCursorRule, generateClaudeRule, generateClaudeSkillRouter, shouldEmitToTarget, filterByLevel, } from '../generators/portable-knowledge.js';
19
+ import { MARKER, generateAgentsMd, generateClaudeMd, generateCursorMdc, generateCopilotMd } from '../generators/adapters.js';
20
+ import { readCanonicalSkills, readCanonicalRules, readPersonalLayer, readPersonalSkillsLayer, generateCursorSkill, generateCursorRule, generateCodexSkill, generateCodexSkillIndex, generateClaudeRule, generateClaudeSkillRouter, shouldEmitToTarget, filterByLevel, validateCodexSkills, evaluateConditions, STAGE_TO_MAX_LEVEL, LEVEL_ORDER, } from '../generators/portable-knowledge.js';
21
+ import { generateChainRules } from '../generators/chain-rules.js';
22
+ import { saveHandshakeState, loadPreviousState, diffHandshakeState, formatDiff, buildCurrentState, } from '../generators/handshake-diff.js';
23
+ import { resolveSurfaceProfile } from '../generators/surface-profiles.js';
16
24
  import { formatHandshakeReport } from '../formatters/handshake.js';
25
+ import { classifyAdapterFile, detectEol, spliceAppend, spliceReplace } from '../generators/region.js';
26
+ import { REGION_PROJECTIONS } from '../generators/region-projections.js';
27
+ import { readManifest, readManifestStatus, filterByAdoptionState } from '../generators/manifest.js';
28
+ import { generateBoundaryManifest, getBoundaryEnforcementMode } from '../generators/boundary-manifest.js';
29
+ import { loadMethodRegistry } from '../lib/method-registry.js';
30
+ import { CLIError, ErrorCode } from '../lib/errors.js';
31
+ import { trackEvent } from '../lib/telemetry.js';
32
+ import { replaceVocabTokens } from '../lib/canonicalRefs.js';
33
+ // WP-436 S3: vocab projector — resolves {{vocab:...}} tokens before writing to disk.
34
+ import { getOrFetchVocabCtx } from '../lib/workspaceVocabCache.js';
35
+ import { normalizeMaterializedFilename } from '../lib/normalizeMaterializedFilename.js';
36
+ import { sanitizeStartupResolutionSignals } from '../lib/startup-resolution-signals.js';
37
+ import { assertSetupWritePath } from '../setup/perimeter.js';
38
+ // WP-421 S3: SurfaceAdapter reverse-map for tampered prompts (DEC-952, doneWhen #34).
39
+ import { canonicalPathForAnySurface, SURFACE_GOVERN_NO_SURFACES, SURFACE_REGISTRY, validateSurfacesForMode, } from '../surfaces/registry.js';
40
+ import { getReverseMapFallbackMessage, reportReverseMapMissing } from '../surfaces/telemetry.js';
41
+ const MAX_HANDSHAKE_WAIT_MS = 10_000; // 10 seconds
42
+ const POLL_INTERVAL_MS = 500; // 500 ms per poll
43
+ const MAX_POLLS = MAX_HANDSHAKE_WAIT_MS / POLL_INTERVAL_MS; // 20
44
+ // ── WP-379 S4: Dormant marker ─────────────────────────────────────────────────
45
+ /**
46
+ * DORMANT_MARKER — appended to previously-projected asset files when the asset's
47
+ * gate deactivates (e.g. workspace readiness exceeds the max threshold).
48
+ *
49
+ * Contract:
50
+ * - The file is NOT deleted. It persists on disk so that history is preserved
51
+ * and the agent surface remains inspectable.
52
+ * - The marker is appended at the end of the file, idempotent — if it already
53
+ * exists, no second append occurs.
54
+ * - The marker does NOT trigger a drift TEN. Dormant files are intentionally
55
+ * deactivated, not accidentally forked.
56
+ * - The marker is never included in active file writes — only dormant writes.
57
+ *
58
+ * Used by: writeDormantMarker() (write) and hasDormantMarker() (idempotency check).
59
+ * Exported for use in tests.
60
+ *
61
+ * Chain: WP-379 S4.
62
+ */
63
+ export const DORMANT_MARKER = '<!-- pb-status: dormant -->';
64
+ /**
65
+ * hasDormantMarker — check whether a file on disk already has the dormant marker.
66
+ * Used for idempotency: if the marker is already present, skip the append.
67
+ */
68
+ function hasDormantMarker(content) {
69
+ return content.includes(DORMANT_MARKER);
70
+ }
71
+ /**
72
+ * writeDormantMarker — append the dormant marker to a previously-projected file.
73
+ *
74
+ * Idempotent: if DORMANT_MARKER is already present, no-op.
75
+ * Only operates on files that have the auto-gen MARKER — we never touch
76
+ * manually-authored files.
77
+ *
78
+ * @param filePath Absolute path to the file.
79
+ * @returns 'written' | 'already-dormant' | 'skipped' (no auto-gen marker)
80
+ */
81
+ export function writeDormantMarkerToFile(filePath) {
82
+ if (!existsSync(filePath))
83
+ return 'skipped';
84
+ const content = readFileSync(filePath, 'utf8');
85
+ // Only mark files that were originally projected by pb handshake.
86
+ // Files without the auto-gen MARKER are manually authored — leave them alone.
87
+ if (!content.includes(MARKER))
88
+ return 'skipped';
89
+ if (hasDormantMarker(content))
90
+ return 'already-dormant';
91
+ // Append the marker on its own line. No trailing newline assumption —
92
+ // appendFileSync adds to whatever is already there.
93
+ appendFileSync(filePath, `\n${DORMANT_MARKER}\n`);
94
+ return 'written';
95
+ }
96
+ /**
97
+ * renameSurfaceForDormancy — rename a projected surface file to `<path>.dormant`
98
+ * so external scanners (which glob *.md / *.mdc) stop loading it. WP-426 E4.
99
+ * The HTML-comment marker is invisible to scanners; the extension change removes
100
+ * the file from their glob set. Only touches files carrying the auto-gen MARKER.
101
+ * Runs on an INDEPENDENT existence check (not gated on marker-write result) so
102
+ * legacy WP-379 marker-only files still rename. Idempotent.
103
+ * Codex P1: when a .dormant already exists, only replace it if its body matches the
104
+ * live file. A divergent .dormant (user edited it) is preserved and reported as 'drift'
105
+ * rather than force-deleted — no silent data loss.
106
+ * @returns 'renamed' | 'replaced' | 'already-dormant' | 'skipped' | 'drift'
107
+ */
108
+ export function renameSurfaceForDormancy(filePath) {
109
+ const dormantPath = `${filePath}.dormant`;
110
+ if (!existsSync(filePath))
111
+ return existsSync(dormantPath) ? 'already-dormant' : 'skipped';
112
+ if (!readFileSync(filePath, 'utf8').includes(MARKER))
113
+ return 'skipped';
114
+ const replacing = existsSync(dormantPath);
115
+ if (replacing) {
116
+ // Codex P1: the existing .dormant may carry user edits (e.g. the user reactivated to
117
+ // the live path but kept an edited dormant sibling). Compare normalized bodies
118
+ // (DORMANT_MARKER + volatile auto-gen timestamp stripped from both); if they diverge,
119
+ // preserve the .dormant and signal drift instead of force-replacing it.
120
+ const strip = (s) => normalizeHandshakeContentForComparison(s.split(DORMANT_MARKER).join('')).trimEnd();
121
+ if (strip(readFileSync(filePath, 'utf8')) !== strip(readFileSync(dormantPath, 'utf8'))) {
122
+ return 'drift';
123
+ }
124
+ rmSync(dormantPath, { force: true });
125
+ }
126
+ renameSync(filePath, dormantPath);
127
+ return replacing ? 'replaced' : 'renamed';
128
+ }
129
+ /**
130
+ * restoreSurfaceFromDormant — clean the orphan `<path>.dormant` sibling after a
131
+ * raised (observe→project) asset has been re-projected fresh from the DB body by
132
+ * the normal write loop. WP-426 E4.
133
+ * Normalizes the volatile auto-gen timestamp (via normalizeHandshakeContentForComparison)
134
+ * before comparing, else the lowering-time timestamp would always force a false
135
+ * 'orphan-drift'. Identical body → remove. Differs (user edited) → preserve + drift.
136
+ * @returns 'restored' | 'orphan-drift' | 'skipped'
137
+ */
138
+ export function restoreSurfaceFromDormant(filePath) {
139
+ const dormantPath = `${filePath}.dormant`;
140
+ if (!existsSync(dormantPath))
141
+ return 'skipped';
142
+ // WP-426 E4: no fresh live projection this run (surface filtered / user-owned / not written) →
143
+ // nothing to reconcile; absence of fresh is NOT evidence of a user edit. Leave the .dormant.
144
+ if (!existsSync(filePath))
145
+ return 'skipped';
146
+ const fresh = readFileSync(filePath, 'utf8');
147
+ // Codex P2: only reconcile against a PB-managed projection. A live file WITHOUT the auto-gen
148
+ // MARKER is a user-owned file (shouldWriteAdapter would have skipped reprojecting it),
149
+ // so it was NOT raised this run — comparing the .dormant against it would wrongly delete it or
150
+ // re-fire "edited while dormant" drift. Leave the .dormant untouched.
151
+ if (!fresh.includes(MARKER))
152
+ return 'skipped';
153
+ const dormant = readFileSync(dormantPath, 'utf8').split(DORMANT_MARKER).join('');
154
+ const norm = (s) => normalizeHandshakeContentForComparison(s).trimEnd();
155
+ if (norm(dormant) === norm(fresh)) {
156
+ rmSync(dormantPath, { force: true });
157
+ return 'restored';
158
+ }
159
+ return 'orphan-drift';
160
+ }
161
+ /**
162
+ * deriveDormantFilePaths — compute the set of on-disk file paths that would have
163
+ * been projected for a given dormant asset (by name and assetKind).
164
+ *
165
+ * Assets are projected to one or more surfaces (cursor/claude/codex) depending
166
+ * on shouldEmitToTarget. Since we don't re-run shouldEmitToTarget here, we
167
+ * speculatively probe all known surface paths and let writeDormantMarkerToFile
168
+ * decide whether each exists and has the auto-gen MARKER.
169
+ *
170
+ * @param asset The dormant asset from the server.
171
+ * @param cwd Current working directory (project root).
172
+ * @returns Each candidate path paired with its owning surface, so callers can
173
+ * filter by the run's allowedTargets (--surfaces) and the perimeter.
174
+ */
175
+ function deriveDormantFilePaths(asset, cwd) {
176
+ // Defense-in-depth: even though `name` originates from platform-seeded DB
177
+ // entries (not user input), validate it against a strict charset before
178
+ // interpolating into a filesystem path. Reject anything that could traverse
179
+ // out of the expected directories. WP-379 S4 review finding.
180
+ if (!/^[A-Za-z0-9 ._-]+$/.test(asset.name)) {
181
+ return [];
182
+ }
183
+ const out = [];
184
+ const { name, assetKind } = asset;
185
+ if (assetKind === 'skill') {
186
+ out.push({ path: join(cwd, '.cursor', 'skills', name, 'SKILL.md'), surface: 'cursor' });
187
+ out.push({ path: join(cwd, '.codex', 'skills', `${name}.md`), surface: 'codex' });
188
+ }
189
+ else if (assetKind === 'rule' || assetKind === 'hook') {
190
+ out.push({ path: join(cwd, '.cursor', 'rules', `${name}.mdc`), surface: 'cursor' });
191
+ out.push({ path: join(cwd, '.claude', 'rules', `${name}.md`), surface: 'claude' });
192
+ }
193
+ return out;
194
+ }
195
+ /**
196
+ * Single-shot health probe — calls `workspace.health` and inspects
197
+ * `starterSetupSeeded`. Does NOT poll internally; polling is the caller's
198
+ * responsibility (connect-context.ts).
199
+ *
200
+ * Returns:
201
+ * - `seeds-ready` — health query succeeded AND starterSetupSeeded is true
202
+ * - `seeds-pending` — health query succeeded but starterSetupSeeded is false
203
+ * - `probe-failed` — health query threw (network, auth, etc.)
204
+ */
205
+ export async function probeStarterSetupSeeded() {
206
+ try {
207
+ const health = await kernelCall('workspace.health', {});
208
+ if (health.starterSetupSeeded) {
209
+ return { status: 'seeds-ready' };
210
+ }
211
+ const starterGaps = (health.gaps ?? []).filter((g) => g.kind === 'starter-setup-missing' || g.kind === 'platform-domains-missing');
212
+ return {
213
+ status: 'seeds-pending',
214
+ gaps: starterGaps.length > 0 ? starterGaps : [
215
+ {
216
+ kind: 'starter-setup-missing',
217
+ severity: 'warn',
218
+ message: 'Starter setup seeds are still running.',
219
+ },
220
+ ],
221
+ };
222
+ }
223
+ catch (err) {
224
+ return {
225
+ status: 'probe-failed',
226
+ error: err instanceof Error ? err.message : String(err),
227
+ };
228
+ }
229
+ }
230
+ /**
231
+ * Poll `probeStarterSetupSeeded` up to MAX_POLLS times (10s at 500ms intervals).
232
+ * Returns the final probe result — caller decides how to render the outcome.
233
+ *
234
+ * Exported so connect-context.ts can use it without re-implementing the loop.
235
+ */
236
+ export async function pollUntilSeedsReady() {
237
+ for (let poll = 0; poll < MAX_POLLS; poll++) {
238
+ const result = await probeStarterSetupSeeded();
239
+ if (result.status === 'seeds-ready')
240
+ return result;
241
+ if (result.status === 'probe-failed')
242
+ return result; // don't retry on auth/network errors
243
+ // seeds-pending — wait before next poll
244
+ if (poll < MAX_POLLS - 1) {
245
+ await new Promise((res) => setTimeout(res, POLL_INTERVAL_MS));
246
+ }
247
+ }
248
+ // Final probe after exhausting waits — return whatever state we have
249
+ return probeStarterSetupSeeded();
250
+ }
17
251
  const LEVELS = {
18
252
  guide: {
19
253
  label: 'Guide me',
@@ -45,9 +279,6 @@ const LEVEL_KEYS = ['guide', 'work', 'silent', 'full-trust'];
45
279
  // Hook failure contract (TEN-712): all hook commands MUST end with '2>/dev/null || true'
46
280
  // so Claude Code always starts even if pb is unavailable. Never remove this suffix.
47
281
  const INIT_PERMISSION = 'Bash(pb:*)';
48
- const INIT_SESSION_START_CMD = 'pb session start 2>/dev/null || true';
49
- const INIT_SESSION_CLOSE_CMD = 'pb session close 2>/dev/null || true';
50
- const INIT_PRECOMPACT_CMD = 'pb session id > /dev/null 2>&1 && echo \'{"systemMessage": "pb session active — capture decisions/tensions before compacting: pb capture \\"DEC: ...\\""}\' || true';
51
282
  function readSettings(filePath) {
52
283
  if (!existsSync(filePath))
53
284
  return {};
@@ -59,9 +290,6 @@ function readSettings(filePath) {
59
290
  return {};
60
291
  }
61
292
  }
62
- function hasCommand(groups, cmd) {
63
- return (groups ?? []).some((g) => g.hooks?.some((h) => h.command === cmd));
64
- }
65
293
  // Team write: hooks + Bash(pb:*) → .claude/settings.json (safe to commit)
66
294
  function writeTeamSettings(cwd, dryRun) {
67
295
  const claudeDir = join(cwd, '.claude');
@@ -77,26 +305,10 @@ function writeTeamSettings(cwd, dryRun) {
77
305
  }
78
306
  settings.permissions = permissions;
79
307
  const hooks = (settings.hooks ?? {});
80
- if (!hasCommand(hooks.SessionStart, INIT_SESSION_START_CMD)) {
81
- hooks.SessionStart = [
82
- ...(hooks.SessionStart ?? []),
83
- { hooks: [{ type: 'command', command: INIT_SESSION_START_CMD, statusMessage: 'Opening pb session...' }] },
84
- ];
85
- added.push('SessionStart → pb session start');
86
- }
87
- if (!hasCommand(hooks.Stop, INIT_SESSION_CLOSE_CMD)) {
88
- hooks.Stop = [
89
- ...(hooks.Stop ?? []),
90
- { hooks: [{ type: 'command', command: INIT_SESSION_CLOSE_CMD, statusMessage: 'Closing pb session...' }] },
91
- ];
92
- added.push('Stop → pb session close');
93
- }
94
- if (!hasCommand(hooks.PreCompact, INIT_PRECOMPACT_CMD)) {
95
- hooks.PreCompact = [
96
- ...(hooks.PreCompact ?? []),
97
- { hooks: [{ type: 'command', command: INIT_PRECOMPACT_CMD }] },
98
- ];
99
- added.push('PreCompact → decision capture reminder');
308
+ const hookAdditions = composeHooksFromIntents(['session-start', 'session-close', 'pre-compact'], hooks);
309
+ for (const addition of hookAdditions) {
310
+ hooks[addition.event] = [...(hooks[addition.event] ?? []), addition.entry];
311
+ added.push(addition.label);
100
312
  }
101
313
  settings.hooks = hooks;
102
314
  if (!dryRun) {
@@ -133,31 +345,26 @@ function writePersonalSettings(levelKey, dryRun) {
133
345
  return added;
134
346
  }
135
347
  async function promptLevel() {
136
- const rl = createInterface({ input: process.stdin, output: process.stdout });
137
- console.log('\nHow much should Claude explain before acting?\n');
138
- LEVEL_KEYS.forEach((key, i) => {
139
- const l = LEVELS[key];
140
- console.log(` ${i + 1}. ${l.label.padEnd(12)} — ${l.description}`);
141
- });
142
- console.log('');
143
- return new Promise((resolve) => {
144
- rl.question('> ', (answer) => {
145
- rl.close();
146
- const n = parseInt(answer.trim(), 10);
147
- if (!(n >= 1 && n <= LEVEL_KEYS.length)) {
148
- console.log(' (Invalid choice — defaulting to "Just work")');
149
- }
150
- resolve(n >= 1 && n <= LEVEL_KEYS.length ? LEVEL_KEYS[n - 1] : 'work');
151
- });
348
+ const result = await promptSelect({
349
+ message: 'How much should Claude explain before acting?',
350
+ options: LEVEL_KEYS.map((key) => ({
351
+ value: key,
352
+ label: LEVELS[key].label,
353
+ hint: LEVELS[key].description,
354
+ })),
152
355
  });
356
+ return result;
153
357
  }
154
358
  export async function runHandshakeInit(options = {}) {
155
359
  const cwd = process.cwd();
156
360
  const dryRun = options.dryRun ?? false;
157
361
  const suffix = dryRun ? ' (dry run)' : '';
158
362
  if (options.level && !LEVEL_KEYS.includes(options.level)) {
159
- console.error(`Unknown level "${options.level}". Valid: ${LEVEL_KEYS.join(', ')}`);
160
- process.exit(1);
363
+ throw new CLIError(`Unknown level "${options.level}".`, {
364
+ code: ErrorCode.VALIDATION_FAILED,
365
+ category: 'validation',
366
+ guidance: `Valid levels: ${LEVEL_KEYS.join(', ')}`,
367
+ });
161
368
  }
162
369
  console.log('Setting up Claude Code integration...\n');
163
370
  // Step 1: Team config — always, no prompt
@@ -172,7 +379,7 @@ export async function runHandshakeInit(options = {}) {
172
379
  console.log(` + ${item}`);
173
380
  }
174
381
  // Step 2: Personal config — wizard or --level flag
175
- // Cast is safe: LEVEL_KEYS.includes() validated above; invalid level already called process.exit(1).
382
+ // Cast is safe: LEVEL_KEYS.includes() validated above; invalid level already threw CLIError.
176
383
  const levelKey = options.level ? options.level : await promptLevel();
177
384
  const level = LEVELS[levelKey];
178
385
  const personalAdded = writePersonalSettings(levelKey, dryRun);
@@ -194,6 +401,319 @@ export async function runHandshakeInit(options = {}) {
194
401
  if (!dryRun)
195
402
  console.log('Reload /hooks in Claude Code (or restart) to activate.');
196
403
  console.log('Run `pb handshake --init --level <guide|work|silent|full-trust>` to change level.');
404
+ // Step 2b: Report multi-surface hook opt-in status (WP-310 E3b)
405
+ // Reads manifest.hooks.{cursor,copilot} and prints an informational note for
406
+ // each opted-in surface. Silence = no manifest or no hooks flags set.
407
+ // DEC-536: Claude-native default is already wired above; this block only fires
408
+ // when the user has explicitly opted in via manifest.
409
+ const pbDirForManifest = join(cwd, '.productbrain');
410
+ const initManifest = readManifest(pbDirForManifest);
411
+ const multiSurfaceOptIns = [];
412
+ if (initManifest?.hooks?.cursor)
413
+ multiSurfaceOptIns.push('cursor');
414
+ if (initManifest?.hooks?.copilot)
415
+ multiSurfaceOptIns.push('copilot');
416
+ if (multiSurfaceOptIns.length > 0) {
417
+ console.log('');
418
+ for (const surface of multiSurfaceOptIns) {
419
+ const status = getHookStatusForSurface(surface);
420
+ if (status.writable) {
421
+ // Future-proofing path: surface has hook events, would write files.
422
+ console.log(`ℹ ${surface} hooks: opted in — hooks will be written`);
423
+ }
424
+ else {
425
+ console.log(`ℹ ${surface} hooks: opted in — no auto-hooks (${surface} has no session events; run \`pb session start\` manually)`);
426
+ }
427
+ }
428
+ }
429
+ // Step 3: Scaffold starter templates if .productbrain/rules/ is empty
430
+ const rulesDir = join(cwd, '.productbrain', 'rules');
431
+ const hasExistingRules = existsSync(rulesDir) && readdirSync(rulesDir).filter((f) => f.endsWith('.md')).length > 0;
432
+ if (!hasExistingRules) {
433
+ // Detect stack from repo to pick template set
434
+ const repo = detectRepo(cwd);
435
+ const stack = repo.detectedStack.map((s) => s.toLowerCase());
436
+ let templateSet;
437
+ if (stack.some((s) => ['typescript', 'sveltekit', 'nextjs', 'react'].includes(s))) {
438
+ templateSet = 'node-ts';
439
+ }
440
+ else if (stack.includes('python')) {
441
+ templateSet = 'python';
442
+ }
443
+ else {
444
+ templateSet = 'general';
445
+ }
446
+ // Resolve templates directory relative to this file
447
+ const __filename = fileURLToPath(import.meta.url);
448
+ const __dirname = dirname(__filename);
449
+ // From dist/commands/handshake.js → ../../templates/
450
+ const templatesRoot = resolve(__dirname, '..', '..', 'templates');
451
+ const templateDir = join(templatesRoot, templateSet);
452
+ if (existsSync(templateDir)) {
453
+ const templateFiles = readdirSync(templateDir).filter((f) => f.endsWith('.md'));
454
+ if (templateFiles.length > 0) {
455
+ console.log('');
456
+ console.log(`Scaffolding starter rules from ${templateSet} template...`);
457
+ if (!dryRun) {
458
+ mkdirSync(rulesDir, { recursive: true });
459
+ for (const file of templateFiles) {
460
+ const src = join(templateDir, file);
461
+ const dest = join(rulesDir, file);
462
+ copyFileSync(src, dest);
463
+ console.log(` + .productbrain/rules/${file}`);
464
+ }
465
+ console.log('');
466
+ console.log('Run `pb handshake` to sync the scaffolded rules to your AI tools.');
467
+ }
468
+ else {
469
+ for (const file of templateFiles) {
470
+ console.log(` + .productbrain/rules/${file} (dry run)`);
471
+ }
472
+ }
473
+ }
474
+ }
475
+ }
476
+ }
477
+ const LOCAL_REF_REGEX = /\b(?:WP|TEN|DEC|BET|FEAT|INS|STD|PRI|ARCH)[-\s#]*\d+\b|\bPR\s*#?\s*\d+\b/gi;
478
+ const STARTUP_RESOLUTION_RESOLVER_VERSION = 'startup-resolution-v1';
479
+ // Global cap on collected refs (spec "Contract: StartupResolutionSignals" — arrays are capped).
480
+ const LOCAL_REF_GLOBAL_CAP = 25;
481
+ // Per-source cap so a broad source (context.md) cannot starve the task-specific
482
+ // briefing.md refs (Codex@677). With the global cap at 25, a single source capped
483
+ // at 18 always leaves slots for at least one other source's distinct refs.
484
+ const LOCAL_REF_PER_SOURCE_CAP = 18;
485
+ // PR-ref diff dereference is time-boxed so an unauthed/slow `gh` cannot stall
486
+ // session-start (F4 — guard: time-box + skip gracefully on failure).
487
+ const PR_DIFF_TIMEOUT_MS = 4_000;
488
+ // Cap on how many PR refs we dereference per handshake — bounds the worst-case
489
+ // number of `gh` subprocess invocations.
490
+ const PR_DIFF_MAX_REFS = 5;
491
+ function runGitText(cwd, command) {
492
+ try {
493
+ const value = execSync(command, {
494
+ cwd,
495
+ encoding: 'utf8',
496
+ stdio: ['ignore', 'pipe', 'ignore'],
497
+ }).trim();
498
+ return value.length > 0 ? value : undefined;
499
+ }
500
+ catch {
501
+ return undefined;
502
+ }
503
+ }
504
+ /**
505
+ * Dereference a "PR #N" ref to its changed paths via `gh pr diff <N> --name-only`.
506
+ * F4 (spec "PR refs must dereference to diff paths when available"): the server
507
+ * resolver has no git/gh access, so PR-domain evidence can only be produced
508
+ * here in the CLI. Guarded: `gh` may be absent/unauthed or the PR may not exist,
509
+ * so failures are swallowed (returns []) and the call is time-boxed.
510
+ *
511
+ * Injectable via `run` so tests can drive the dereference without a real `gh`.
512
+ */
513
+ export function dereferencePrRefToPaths(cwd, prNumber, run = runGitTextTimeboxed) {
514
+ if (!Number.isInteger(prNumber) || prNumber <= 0)
515
+ return [];
516
+ const raw = run(cwd, `gh pr diff ${prNumber} --name-only`, PR_DIFF_TIMEOUT_MS);
517
+ if (!raw)
518
+ return [];
519
+ return raw.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
520
+ }
521
+ /** Time-boxed variant of runGitText for the PR-diff dereference (F4). */
522
+ function runGitTextTimeboxed(cwd, command, timeoutMs) {
523
+ try {
524
+ const value = execSync(command, {
525
+ cwd,
526
+ encoding: 'utf8',
527
+ stdio: ['ignore', 'pipe', 'ignore'],
528
+ timeout: timeoutMs,
529
+ }).trim();
530
+ return value.length > 0 ? value : undefined;
531
+ }
532
+ catch {
533
+ return undefined;
534
+ }
535
+ }
536
+ function readOptionalLocalText(cwd, path) {
537
+ const fullPath = join(cwd, path);
538
+ if (!existsSync(fullPath))
539
+ return undefined;
540
+ try {
541
+ return readFileSync(fullPath, 'utf8');
542
+ }
543
+ catch {
544
+ return undefined;
545
+ }
546
+ }
547
+ function normalizeLocalRef(ref) {
548
+ const trimmed = ref.trim().replace(/\s+/g, ' ');
549
+ const pr = trimmed.match(/^PR\s*#?\s*(\d+)$/i);
550
+ if (pr)
551
+ return `PR #${pr[1]}`;
552
+ const entry = trimmed.match(/^([A-Z]+)[-\s#]*(\d+)$/i);
553
+ if (entry)
554
+ return `${entry[1].toUpperCase()}-${entry[2]}`;
555
+ return trimmed;
556
+ }
557
+ /**
558
+ * Collect normalized local refs across several text sources, deduped.
559
+ *
560
+ * Codex@677: a per-source cap (LOCAL_REF_PER_SOURCE_CAP) is applied in addition
561
+ * to the global cap so a broad source (e.g. a context.md carrying 25+ IDs) cannot
562
+ * consume the whole budget before a later, task-specific source (briefing.md) is
563
+ * even read. Each source contributes at most its quota; refs already collected by
564
+ * an earlier source still dedupe across sources (and do not count against the
565
+ * later source's quota, since they are skipped before the per-source counter).
566
+ */
567
+ function collectLocalRefs(texts) {
568
+ const refs = [];
569
+ const seen = new Set();
570
+ for (const text of texts) {
571
+ if (!text)
572
+ continue;
573
+ let fromThisSource = 0;
574
+ for (const match of text.matchAll(LOCAL_REF_REGEX)) {
575
+ const ref = normalizeLocalRef(match[0]);
576
+ const key = ref.toLowerCase();
577
+ if (seen.has(key))
578
+ continue;
579
+ if (fromThisSource >= LOCAL_REF_PER_SOURCE_CAP)
580
+ break;
581
+ seen.add(key);
582
+ refs.push(ref);
583
+ fromThisSource++;
584
+ if (refs.length >= LOCAL_REF_GLOBAL_CAP)
585
+ return refs;
586
+ }
587
+ }
588
+ return refs;
589
+ }
590
+ function deriveHandshakeStartupTask(refs, changedPaths, callerTask) {
591
+ if (callerTask && callerTask.trim())
592
+ return callerTask.trim();
593
+ const parts = [];
594
+ if (refs.length > 0)
595
+ parts.push(refs.join(' '));
596
+ if (changedPaths.length > 0)
597
+ parts.push(`changed paths ${changedPaths.slice(0, 5).join(' ')}`);
598
+ return parts.length > 0 ? parts.join(' ') : undefined;
599
+ }
600
+ const DEFAULT_HANDSHAKE_SIGNAL_DEPS = {
601
+ runGit: runGitText,
602
+ prDiff: (cwd, prNumber) => dereferencePrRefToPaths(cwd, prNumber),
603
+ };
604
+ /** Extract the PR number from a normalized "PR #N" ref, else null. */
605
+ function prNumberFromRef(ref) {
606
+ const m = ref.match(/^PR\s*#?\s*(\d+)$/i);
607
+ if (!m)
608
+ return null;
609
+ const n = Number(m[1]);
610
+ return Number.isInteger(n) && n > 0 ? n : null;
611
+ }
612
+ export function deriveHandshakeStartupSignals(cwd, callerSignals = {}, deps = DEFAULT_HANDSHAKE_SIGNAL_DEPS) {
613
+ const { runGit, prDiff } = deps;
614
+ const branchName = runGit(cwd, 'git branch --show-current');
615
+ const commitSha = runGit(cwd, 'git rev-parse --short HEAD');
616
+ // Changed paths come from THREE sources, unioned + deduped:
617
+ // 1. Dirty worktree (`git diff --name-only HEAD`) — existing behavior.
618
+ // 2. Committed branch delta vs the merge-base with origin/main (Codex@665):
619
+ // after the branch is committed and the worktree is clean, source #1 is
620
+ // empty and the branch delta would be invisible without this.
621
+ // 3. PR-ref dereference (F4) — appended later, once refs are collected.
622
+ const dirtyChangedPaths = runGit(cwd, 'git diff --name-only HEAD')?.split(/\r?\n/).filter(Boolean) ?? [];
623
+ const mergeBase = runGit(cwd, 'git merge-base HEAD origin/main');
624
+ const branchChangedPaths = mergeBase
625
+ ? (runGit(cwd, `git diff --name-only ${mergeBase} HEAD`)?.split(/\r?\n/).filter(Boolean) ?? [])
626
+ : [];
627
+ const worktreeName = basename(cwd);
628
+ const contextText = readOptionalLocalText(cwd, '.productbrain/context.md');
629
+ const briefingText = readOptionalLocalText(cwd, '.productbrain/briefing.md');
630
+ const callerRefs = Array.isArray(callerSignals.reviewedArtifactRefs) ? callerSignals.reviewedArtifactRefs.join('\n') : undefined;
631
+ // Codex@677: briefing.md (task-specific) is read BEFORE context.md (broad) so
632
+ // its refs are collected first; combined with the per-source cap in
633
+ // collectLocalRefs, a context.md with 25+ IDs can no longer starve the briefing.
634
+ const refs = collectLocalRefs([
635
+ callerSignals.taskText ?? undefined,
636
+ callerSignals.explicitScope ?? undefined,
637
+ callerRefs,
638
+ branchName,
639
+ worktreeName,
640
+ briefingText,
641
+ contextText,
642
+ ]);
643
+ // F4: dereference any "PR #N" ref to its diff paths and fold them into the
644
+ // changedPaths evidence so PR refs contribute real path-domain signal. The
645
+ // server resolver records PR refs as dereferenced:false (no git access), so
646
+ // this is the only place the dereference can happen. Time-boxed + try/catch
647
+ // inside prDiff → absent/unauthed gh is a graceful no-op.
648
+ const prDiffPaths = [];
649
+ if (callerSignals.changedPaths === undefined) {
650
+ let derefed = 0;
651
+ for (const ref of refs) {
652
+ const prNumber = prNumberFromRef(ref);
653
+ if (prNumber === null)
654
+ continue;
655
+ if (derefed >= PR_DIFF_MAX_REFS)
656
+ break;
657
+ derefed++;
658
+ try {
659
+ for (const p of prDiff(cwd, prNumber))
660
+ prDiffPaths.push(p);
661
+ }
662
+ catch {
663
+ // gh absent / unauthed / PR missing — skip gracefully, leave existing behavior.
664
+ }
665
+ }
666
+ }
667
+ // Caller-supplied changedPaths win (backward compat); otherwise union the
668
+ // three local sources, deduped, order-stable.
669
+ const unionedChangedPaths = callerSignals.changedPaths ??
670
+ Array.from(new Set([...dirtyChangedPaths, ...branchChangedPaths, ...prDiffPaths]));
671
+ const baseSignals = sanitizeStartupResolutionSignals({
672
+ ...callerSignals,
673
+ sourceSurface: callerSignals.sourceSurface ?? 'cli',
674
+ resolverVersion: callerSignals.resolverVersion ?? STARTUP_RESOLUTION_RESOLVER_VERSION,
675
+ branchName: callerSignals.branchName ?? branchName,
676
+ worktreeName: callerSignals.worktreeName ?? worktreeName,
677
+ changedPaths: unionedChangedPaths,
678
+ reviewedArtifactRefs: callerSignals.reviewedArtifactRefs ?? refs,
679
+ commitSha: callerSignals.commitSha ?? commitSha,
680
+ });
681
+ const taskText = deriveHandshakeStartupTask(baseSignals.reviewedArtifactRefs ?? [], baseSignals.changedPaths ?? [], baseSignals.taskText);
682
+ const sanitized = sanitizeStartupResolutionSignals({
683
+ ...baseSignals,
684
+ taskText,
685
+ });
686
+ const hasMeaningfulEvidence = Boolean(sanitized.taskText) ||
687
+ (sanitized.changedPaths?.length ?? 0) > 0 ||
688
+ (sanitized.reviewedArtifactRefs?.length ?? 0) > 0 ||
689
+ Boolean(sanitized.explicitScope);
690
+ if (hasMeaningfulEvidence)
691
+ return sanitized;
692
+ // Codex@704: even with no task/path/ref/scope evidence, still emit a minimal
693
+ // envelope carrying the attribution fields (resolverVersion, commitSha,
694
+ // branchName). Returning {} here would drop the whole startup block at the
695
+ // caller, losing attribution AND the loud domain-unresolved signal exactly in
696
+ // the low-evidence case the resolver is meant to make queryable
697
+ // (spec "Loud Unresolved State"; AC #4). The envelope has no evidence fields,
698
+ // so the resolver sees no domain and emits domain-unresolved.
699
+ return sanitizeStartupResolutionSignals({
700
+ sourceSurface: sanitized.sourceSurface ?? 'cli',
701
+ resolverVersion: sanitized.resolverVersion ?? STARTUP_RESOLUTION_RESOLVER_VERSION,
702
+ branchName: sanitized.branchName,
703
+ worktreeName: sanitized.worktreeName,
704
+ commitSha: sanitized.commitSha,
705
+ changeId: sanitized.changeId,
706
+ });
707
+ }
708
+ /**
709
+ * Normalize volatile handshake-only timestamps before comparing generated files.
710
+ * This keeps the visible timestamps in generated artifacts while avoiding
711
+ * meaningless rewrites when semantic content is unchanged.
712
+ */
713
+ export function normalizeHandshakeContentForComparison(content) {
714
+ return content
715
+ .replace(/<!-- auto-generated by pb handshake — [0-9]{4}-[0-9]{2}-[0-9]{2}T[^>]+ -->/g, '<!-- auto-generated by pb handshake — <TIMESTAMP> -->')
716
+ .replace(/^_Generated: [0-9]{4}-[0-9]{2}-[0-9]{2}T.*_$/gm, '_Generated: <TIMESTAMP>_');
197
717
  }
198
718
  function shouldWriteAdapter(filePath, force) {
199
719
  if (force)
@@ -203,6 +723,256 @@ function shouldWriteAdapter(filePath, force) {
203
723
  const content = readFileSync(filePath, 'utf8');
204
724
  return content.includes(MARKER);
205
725
  }
726
+ function normalizeSurfaceName(surface) {
727
+ const stripped = surface.startsWith('.') ? surface.slice(1) : surface;
728
+ const normalized = stripped === 'github' ? 'copilot' : stripped;
729
+ return normalized in SURFACE_REGISTRY ? normalized : null;
730
+ }
731
+ function surfacePerimeterRoots(surface) {
732
+ if (surface === 'codex')
733
+ return ['.codex', SURFACE_REGISTRY.codex.hookFilePath];
734
+ if (surface === 'copilot')
735
+ return ['.github', SURFACE_REGISTRY.copilot.hookFilePath];
736
+ if (surface === 'claude')
737
+ return ['.claude', 'CLAUDE.md'];
738
+ return [`.${surface}`];
739
+ }
740
+ function modeRank(mode) {
741
+ return { off: 0, observe: 1, project: 2, govern: 3 }[mode];
742
+ }
743
+ function normalizeSetupAuthoringBody(body) {
744
+ return body.replace(/\r\n/g, '\n').replace(/\r/g, '\n').trimEnd();
745
+ }
746
+ function setupAuthoringAssetHash(asset) {
747
+ const canonical = {
748
+ entryId: asset.entryId,
749
+ name: asset.name,
750
+ description: asset.description ?? '',
751
+ assetKind: asset.assetKind,
752
+ triggers: asset.triggers ?? [],
753
+ semanticRefs: asset.semanticRefs ?? [],
754
+ body: normalizeSetupAuthoringBody(asset.body),
755
+ };
756
+ return `sha256:${createHash('sha256').update(JSON.stringify(canonical), 'utf8').digest('hex')}`;
757
+ }
758
+ function parseSetupAuthoringFrontmatter(raw) {
759
+ const fmMatch = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
760
+ if (!fmMatch) {
761
+ const h1 = raw.match(/^# (.+)$/m);
762
+ return { name: h1?.[1] ?? '', description: '', body: raw, triggers: [], semanticRefs: [] };
763
+ }
764
+ const fields = new Map();
765
+ const arrayFields = new Map();
766
+ const lines = fmMatch[1].split('\n');
767
+ let currentArrayKey = null;
768
+ let currentArrayValues = [];
769
+ for (const line of lines) {
770
+ const arrayItemMatch = line.match(/^\s+-\s+(.+)$/);
771
+ const keyValueMatch = line.match(/^(\w+):\s*(.*)$/);
772
+ if (arrayItemMatch && currentArrayKey) {
773
+ currentArrayValues.push(arrayItemMatch[1].trim().replace(/^['"]|['"]$/g, ''));
774
+ }
775
+ else if (keyValueMatch) {
776
+ if (currentArrayKey) {
777
+ arrayFields.set(currentArrayKey, currentArrayValues);
778
+ currentArrayKey = null;
779
+ currentArrayValues = [];
780
+ }
781
+ const [, key, value] = keyValueMatch;
782
+ if (value.trim() === '') {
783
+ currentArrayKey = key;
784
+ }
785
+ else {
786
+ fields.set(key, value.trim().replace(/^['"]|['"]$/g, ''));
787
+ }
788
+ }
789
+ }
790
+ if (currentArrayKey)
791
+ arrayFields.set(currentArrayKey, currentArrayValues);
792
+ const body = fmMatch[2];
793
+ return {
794
+ frontmatterId: fields.get('id'),
795
+ name: fields.get('name') ?? body.match(/^# (.+)$/m)?.[1] ?? '',
796
+ description: fields.get('description') ?? '',
797
+ body,
798
+ triggers: arrayFields.get('triggers') ?? [],
799
+ semanticRefs: arrayFields.get('semanticRefs') ?? [],
800
+ };
801
+ }
802
+ function deriveSetupAuthoringEntryId(filename, kind) {
803
+ const base = basename(filename, '.md');
804
+ const snakeCase = base.toUpperCase().replace(/[^A-Z0-9]+/g, '_');
805
+ return `SETUP-${kind.toUpperCase()}-${snakeCase}`;
806
+ }
807
+ function scanSetupAuthoringFiles(productbrainDir) {
808
+ const dirs = [
809
+ { dir: 'skills', kind: 'skill' },
810
+ { dir: 'rules', kind: 'rule' },
811
+ { dir: 'hooks', kind: 'hook' },
812
+ ];
813
+ const items = [];
814
+ for (const { dir, kind } of dirs) {
815
+ const absDir = join(productbrainDir, dir);
816
+ if (!existsSync(absDir))
817
+ continue;
818
+ for (const file of readdirSync(absDir).filter((f) => f.endsWith('.md'))) {
819
+ const filePath = join(absDir, file);
820
+ const parsed = parseSetupAuthoringFrontmatter(readFileSync(filePath, 'utf8'));
821
+ const fallbackName = basename(file, '.md');
822
+ items.push({
823
+ filePath,
824
+ derivedEntryId: deriveSetupAuthoringEntryId(file, kind),
825
+ frontmatterId: parsed.frontmatterId,
826
+ name: parsed.name || fallbackName,
827
+ description: parsed.description,
828
+ body: parsed.body,
829
+ assetKind: kind,
830
+ triggers: parsed.triggers,
831
+ semanticRefs: parsed.semanticRefs,
832
+ });
833
+ }
834
+ }
835
+ return items.sort((a, b) => a.filePath.localeCompare(b.filePath));
836
+ }
837
+ function setupAuthoringDirForKind(kind) {
838
+ if (kind === 'skill')
839
+ return 'skills';
840
+ if (kind === 'rule')
841
+ return 'rules';
842
+ if (kind === 'hook')
843
+ return 'hooks';
844
+ return null;
845
+ }
846
+ function setupAuthoringFilename(name, entryId) {
847
+ const base = (name || entryId)
848
+ .replace(/[\/\\:*?"<>|]/g, '-')
849
+ .replace(/\s+/g, ' ')
850
+ .trim();
851
+ return `${base || entryId}.md`;
852
+ }
853
+ function setupAuthoringPath(cwd, asset) {
854
+ const dir = setupAuthoringDirForKind(asset.assetKind);
855
+ if (!dir)
856
+ return null;
857
+ // WP-426 E3: recorded authoring source path wins so reprojection lands where the
858
+ // user authored — no duplicate (TEN-1920). Stored relative to .productbrain/.
859
+ if (asset.authoringPath && asset.authoringPath.trim()) {
860
+ // Codex P1/P2: authoringPath comes from the DB and is untrusted at projection
861
+ // time. It is probed via existsSync/readFileSync (and later writeFileSync) in the
862
+ // writeback loop BEFORE any assertSetupWritePath guard runs. Containment alone is
863
+ // not enough — a bad DB row could still point at a directory (e.g. "skills") or an
864
+ // internal PB file (".authoring-sync.json", "manifest.yaml"), which the loop would
865
+ // mis-handle as markdown (throw on a directory read, or overwrite PB state).
866
+ // Constrain to a kind-appropriate markdown file (<dir>/**/*.md); otherwise fall
867
+ // back to the safe name-derived path.
868
+ const pbDir = join(cwd, '.productbrain');
869
+ const candidate = resolve(pbDir, asset.authoringPath);
870
+ const within = relative(pbDir, candidate);
871
+ const withinPosix = within.split(sep).join('/');
872
+ if (!within.startsWith('..') &&
873
+ !isAbsolute(within) &&
874
+ withinPosix.startsWith(`${dir}/`) &&
875
+ withinPosix.toLowerCase().endsWith('.md')) {
876
+ return candidate;
877
+ }
878
+ }
879
+ return join(cwd, '.productbrain', dir, setupAuthoringFilename(asset.name, asset.entryId));
880
+ }
881
+ function renderSetupAuthoringFile(asset) {
882
+ const lines = [
883
+ '---',
884
+ `id: ${asset.entryId}`,
885
+ `name: ${JSON.stringify(asset.name)}`,
886
+ `description: ${JSON.stringify(asset.description ?? '')}`,
887
+ `assetKind: ${asset.assetKind}`,
888
+ ];
889
+ const pushArray = (key, values) => {
890
+ if (!values || values.length === 0)
891
+ return;
892
+ lines.push(`${key}:`);
893
+ for (const value of values)
894
+ lines.push(` - ${JSON.stringify(value)}`);
895
+ };
896
+ pushArray('triggers', asset.triggers);
897
+ pushArray('semanticRefs', asset.semanticRefs);
898
+ lines.push('---', normalizeSetupAuthoringBody(asset.body), '');
899
+ return lines.join('\n');
900
+ }
901
+ function loadAuthoringSyncState(productbrainDir) {
902
+ const statePath = join(productbrainDir, '.authoring-sync.json');
903
+ if (!existsSync(statePath))
904
+ return { version: 1, assets: {} };
905
+ try {
906
+ const parsed = JSON.parse(readFileSync(statePath, 'utf8'));
907
+ if (parsed.version !== 1 || !parsed.assets || typeof parsed.assets !== 'object') {
908
+ return { version: 1, assets: {} };
909
+ }
910
+ // Codex P2: the dormant registries are consumed via .includes() in the dormant loop
911
+ // BEFORE its per-file try/catch, so a malformed .authoring-sync.json (a field set to
912
+ // an object/number instead of an array) would throw a TypeError and abort the whole
913
+ // handshake. Coerce to a string[] (mirrors the assets validation above) to fail open.
914
+ const toStringArray = (v) => Array.isArray(v) ? v.filter((x) => typeof x === 'string') : [];
915
+ return {
916
+ version: 1,
917
+ assets: parsed.assets,
918
+ dormantRenamed: toStringArray(parsed.dormantRenamed),
919
+ dormantReactivated: toStringArray(parsed.dormantReactivated),
920
+ };
921
+ }
922
+ catch {
923
+ return { version: 1, assets: {} };
924
+ }
925
+ }
926
+ function saveAuthoringSyncState(productbrainDir, state) {
927
+ const statePath = join(productbrainDir, '.authoring-sync.json');
928
+ assertSetupWritePath(statePath, { surfaces: [] });
929
+ mkdirSync(productbrainDir, { recursive: true });
930
+ writeFileSync(statePath, JSON.stringify(state, null, 2) + '\n');
931
+ }
932
+ const DRIFT_HASH_TRAILER_REGEX = /^<!--\s*pb-hash:\s*sha256:([0-9a-f]+)\s*-->\s*$/m;
933
+ const DRIFT_HASH_TRAILER_STRIP = /^<!--\s*pb-hash:.*-->\s*$/gm;
934
+ const DRIFT_TIMESTAMP_STRIP = /^<!--\s*pb-generated-at:.*-->\s*$/gm;
935
+ /**
936
+ * Classify a single projection-target file into one of the three drift buckets.
937
+ *
938
+ * Returns `null` when `filePath` does not exist (first-run / unprojected) — the
939
+ * write loop treats that as "would-write" and the file is not part of any bucket.
940
+ *
941
+ * @param filePath Absolute path to the projection file on disk.
942
+ * @returns { bucket, expectedHash, actualHash } when the file exists.
943
+ * `expectedHash`/`actualHash` are populated only for the
944
+ * tampered bucket so the headless refusal payload can include
945
+ * them verbatim. For clean / user-owned, both are `''`.
946
+ */
947
+ export function classifyDriftBucket(filePath) {
948
+ if (!existsSync(filePath))
949
+ return null;
950
+ const content = readFileSync(filePath, 'utf8');
951
+ // No auto-gen MARKER → user-owned. Never touch.
952
+ if (!content.includes(MARKER)) {
953
+ return { bucket: 'user-owned', expectedHash: '', actualHash: '' };
954
+ }
955
+ // Marker present but no hash trailer → legacy / pre-S0c projection: treat as
956
+ // clean (the hash trailer was added in WP-345 S0c). The user-owned-vs-clean
957
+ // semantic falls back to existing shouldWriteAdapter behavior.
958
+ const trailerMatch = content.match(DRIFT_HASH_TRAILER_REGEX);
959
+ if (!trailerMatch) {
960
+ return { bucket: 'pb-managed-clean', expectedHash: '', actualHash: '' };
961
+ }
962
+ const expectedHash = `sha256:${trailerMatch[1]}`;
963
+ // Recompute the actual hash from the body (strip trailer + timestamp, LF, trim).
964
+ const normalized = content
965
+ .replace(DRIFT_HASH_TRAILER_STRIP, '')
966
+ .replace(DRIFT_TIMESTAMP_STRIP, '')
967
+ .replace(/\r\n/g, '\n')
968
+ .replace(/\r/g, '\n')
969
+ .trimEnd();
970
+ const actualHash = `sha256:${createHash('sha256').update(normalized, 'utf8').digest('hex')}`;
971
+ if (actualHash === expectedHash) {
972
+ return { bucket: 'pb-managed-clean', expectedHash, actualHash };
973
+ }
974
+ return { bucket: 'pb-managed-tampered', expectedHash, actualHash };
975
+ }
206
976
  function deduplicateEntries(entries) {
207
977
  const seen = new Set();
208
978
  const result = [];
@@ -215,15 +985,178 @@ function deduplicateEntries(entries) {
215
985
  }
216
986
  return result;
217
987
  }
988
+ /**
989
+ * resolveProjectionCollision — WP-379 S5b
990
+ *
991
+ * Marker-scoped orphan unlink: enumerates target dirs (.cursor/rules/,
992
+ * .claude/rules/, .claude/skills/, .codex/skills/); for each file that has
993
+ * the auto-gen MARKER whose lowercase-normalized filename does NOT match any
994
+ * current active-asset materializedFilename, the file is unlinked.
995
+ *
996
+ * User-owned files (no MARKER) are never touched, regardless of name.
997
+ *
998
+ * Linux case-collision disambiguation:
999
+ * 1. Exact match (lowercase name == any canonical name): survives.
1000
+ * 2. Case-variant with MARKER (marker file, no exact canonical match): unlinked.
1001
+ * 3. Ambiguous (zero exact, multiple case-variants with MARKER):
1002
+ * newest mtime wins; all others are unlinked; a collision TEN is
1003
+ * appended to the session capture queue (not fired inline).
1004
+ *
1005
+ * Returns a list of unlink results so the caller can log/report them.
1006
+ *
1007
+ * @param cwd Project root (absolute path).
1008
+ * @param assetNames The current set of canonical asset names from the server
1009
+ * (e.g. ["Setup-ProductBrain", "chain-rules"]).
1010
+ * @param log Progress log function.
1011
+ * @param logErr Error log function.
1012
+ */
1013
+ export function resolveProjectionCollision(cwd, assetNames, log, logErr) {
1014
+ // Target directories by extension suffix.
1015
+ const TARGET_DIRS_BY_EXT = [
1016
+ { dir: join(cwd, '.cursor', 'rules'), ext: '.mdc' },
1017
+ { dir: join(cwd, '.claude', 'rules'), ext: '.md' },
1018
+ { dir: join(cwd, '.claude', 'skills'), ext: '.md' },
1019
+ { dir: join(cwd, '.codex', 'skills'), ext: '.md' },
1020
+ ];
1021
+ // Build a set of normalized canonical names (without extension) for fast lookup.
1022
+ // We normalize all asset names to detect case-variant collisions.
1023
+ // For each asset name we derive the normalized basename (the part before the ext).
1024
+ // canonicalNormalizedNames: Set<normalized-stem> (lowercase + slug).
1025
+ const canonicalNormalizedStems = new Set(assetNames.map((n) => normalizeMaterializedFilename(n)));
1026
+ const results = [];
1027
+ const collisionTens = [];
1028
+ for (const { dir, ext } of TARGET_DIRS_BY_EXT) {
1029
+ if (!existsSync(dir))
1030
+ continue;
1031
+ let files;
1032
+ try {
1033
+ files = readdirSync(dir);
1034
+ }
1035
+ catch {
1036
+ continue; // unreadable dir — skip
1037
+ }
1038
+ // Group files by their normalized stem.
1039
+ // normalizedStem → [ { filename, fullPath } ]
1040
+ const groups = new Map();
1041
+ for (const filename of files) {
1042
+ if (!filename.endsWith(ext))
1043
+ continue;
1044
+ const fullPath = join(dir, filename);
1045
+ // Only operate on files that have the auto-gen MARKER.
1046
+ let content;
1047
+ try {
1048
+ content = readFileSync(fullPath, 'utf8');
1049
+ }
1050
+ catch {
1051
+ continue; // unreadable file — skip
1052
+ }
1053
+ if (!content.includes(MARKER))
1054
+ continue; // user-owned — never touch
1055
+ const stem = basename(filename, ext);
1056
+ const normalizedStem = normalizeMaterializedFilename(stem);
1057
+ const group = groups.get(normalizedStem) ?? [];
1058
+ group.push({ filename, fullPath });
1059
+ groups.set(normalizedStem, group);
1060
+ }
1061
+ // Evaluate each normalized stem group.
1062
+ for (const [normalizedStem, members] of groups) {
1063
+ const isKnownCanonical = canonicalNormalizedStems.has(normalizedStem);
1064
+ if (!isKnownCanonical) {
1065
+ // All members of this group are orphans (no canonical asset with this stem).
1066
+ // Unlink them all — they're stale projections of an asset no longer in the server.
1067
+ for (const { filename, fullPath } of members) {
1068
+ try {
1069
+ unlinkSync(fullPath);
1070
+ log(`Orphan unlinked: ${fullPath}`);
1071
+ results.push({ action: 'unlinked', filePath: fullPath, reason: 'orphan-no-canonical-match' });
1072
+ }
1073
+ catch (err) {
1074
+ logErr(`Warning: could not unlink orphan ${fullPath} — ${err instanceof Error ? err.message : String(err)}`);
1075
+ results.push({ action: 'kept', filePath: fullPath, reason: 'unlink-failed' });
1076
+ }
1077
+ }
1078
+ continue;
1079
+ }
1080
+ // The stem IS known canonical. Check for case-collision.
1081
+ if (members.length === 1) {
1082
+ // Single file — no collision.
1083
+ results.push({ action: 'kept', filePath: members[0].fullPath, reason: 'canonical-exact' });
1084
+ continue;
1085
+ }
1086
+ // Multiple files with the same normalized stem → case-collision.
1087
+ // Rule: exact match (filename stem === normalized stem, i.e. already lowercase) wins.
1088
+ const exactMatches = members.filter(({ filename }) => {
1089
+ const stem = basename(filename, ext);
1090
+ return stem === normalizedStem; // lowercase-equal means already normalized
1091
+ });
1092
+ if (exactMatches.length === 1) {
1093
+ // Rule 1: exactly one exact match → keep it, unlink all case-variants.
1094
+ const keeper = exactMatches[0];
1095
+ results.push({ action: 'kept', filePath: keeper.fullPath, reason: 'case-exact-match-wins' });
1096
+ for (const member of members) {
1097
+ if (member.fullPath === keeper.fullPath)
1098
+ continue;
1099
+ try {
1100
+ unlinkSync(member.fullPath);
1101
+ log(`Case-variant unlinked: ${member.fullPath} (kept: ${keeper.filename})`);
1102
+ results.push({ action: 'unlinked', filePath: member.fullPath, reason: 'case-variant-unlinked' });
1103
+ }
1104
+ catch (err) {
1105
+ logErr(`Warning: could not unlink case-variant ${member.fullPath} — ${err instanceof Error ? err.message : String(err)}`);
1106
+ results.push({ action: 'kept', filePath: member.fullPath, reason: 'unlink-failed' });
1107
+ }
1108
+ }
1109
+ continue;
1110
+ }
1111
+ // Rule 3: ambiguous — zero exact matches (or multiple exact matches, which
1112
+ // can't happen on a case-sensitive FS). Newest mtime wins.
1113
+ // Sort by mtime descending: highest mtime = newest = winner.
1114
+ const withStats = members.map(({ filename, fullPath }) => {
1115
+ try {
1116
+ const { mtimeMs } = statSync(fullPath);
1117
+ return { filename, fullPath, mtimeMs };
1118
+ }
1119
+ catch {
1120
+ return { filename, fullPath, mtimeMs: 0 };
1121
+ }
1122
+ });
1123
+ withStats.sort((a, b) => b.mtimeMs - a.mtimeMs);
1124
+ const winner = withStats[0];
1125
+ log(`Case-collision ambiguous for ${normalizedStem}${ext}: newest mtime wins (${winner.filename})`);
1126
+ results.push({ action: 'collision-ten', filePath: winner.fullPath, reason: 'ambiguous-newest-mtime-wins' });
1127
+ const tenMsg = `Handshake case-collision: ambiguous filename for stem "${normalizedStem}${ext}" ` +
1128
+ `(${members.map((m) => m.filename).join(', ')}). ` +
1129
+ `Kept newest: ${winner.filename}. Consider renaming to ${normalizedStem}${ext}.`;
1130
+ collisionTens.push(tenMsg);
1131
+ for (const member of withStats.slice(1)) {
1132
+ try {
1133
+ unlinkSync(member.fullPath);
1134
+ log(`Case-variant (ambiguous) unlinked: ${member.fullPath}`);
1135
+ results.push({ action: 'unlinked', filePath: member.fullPath, reason: 'ambiguous-case-variant-unlinked' });
1136
+ }
1137
+ catch (err) {
1138
+ logErr(`Warning: could not unlink ambiguous case-variant ${member.fullPath} — ${err instanceof Error ? err.message : String(err)}`);
1139
+ results.push({ action: 'kept', filePath: member.fullPath, reason: 'unlink-failed' });
1140
+ }
1141
+ }
1142
+ }
1143
+ }
1144
+ return { results, collisionTens };
1145
+ }
218
1146
  export async function runHandshake(options = {}) {
219
- const config = await getConfigOrGuide(() => runHandshake(options));
1147
+ const config = await getConfigOrGuide(async () => { await runHandshake(options); });
220
1148
  if (!config)
221
- return;
1149
+ return undefined;
222
1150
  const cwd = process.cwd();
223
1151
  const force = options.force ?? false;
224
1152
  const dryRun = options.dryRun ?? false;
1153
+ // Preview mode: default when neither --apply nor --dry-run is passed.
1154
+ // --dry-run is kept as a backward-compat alias for preview (same behavior).
1155
+ const preview = !options.apply && !dryRun;
1156
+ const applyMode = options.apply === true && !dryRun;
225
1157
  const level = options.level;
226
1158
  const quiet = options.quiet ?? false;
1159
+ const generate = options.generate ?? false;
227
1160
  const timestamp = new Date().toISOString();
228
1161
  // Helper: emit progress line only when not quiet (used when handshake is a sub-step)
229
1162
  const log = (msg) => { if (!quiet)
@@ -233,8 +1166,11 @@ export async function runHandshake(options = {}) {
233
1166
  // Validate --level if provided (for handshake content filtering, not --init trust level)
234
1167
  const VALID_HANDSHAKE_LEVELS = ['beginner', 'intermediate', 'expert'];
235
1168
  if (level && !VALID_HANDSHAKE_LEVELS.includes(level)) {
236
- process.stderr.write(`Unknown level "${level}". Valid levels: ${VALID_HANDSHAKE_LEVELS.join(', ')}\n`);
237
- process.exit(1);
1169
+ throw new CLIError(`Unknown level "${level}".`, {
1170
+ code: ErrorCode.VALIDATION_FAILED,
1171
+ category: 'validation',
1172
+ guidance: `Valid levels: ${VALID_HANDSHAKE_LEVELS.join(', ')}`,
1173
+ });
238
1174
  }
239
1175
  // 1. Detect repo
240
1176
  const repo = detectRepo(cwd);
@@ -242,16 +1178,39 @@ export async function runHandshake(options = {}) {
242
1178
  if (repo.detectedStack.length > 0) {
243
1179
  log(`Stack: ${repo.detectedStack.join(', ')}`);
244
1180
  }
245
- // 2. Fetch orient view
1181
+ const startupSignals = deriveHandshakeStartupSignals(cwd, options.startupSignals ?? {});
1182
+ const orientArgs = { tier: 'standard' };
1183
+ if (options.invocationPath)
1184
+ orientArgs.invocationPath = options.invocationPath;
1185
+ if (Object.keys(startupSignals).length > 0) {
1186
+ orientArgs.startupSignals = startupSignals;
1187
+ if (startupSignals.taskText)
1188
+ orientArgs.task = startupSignals.taskText;
1189
+ }
1190
+ // 2. Fetch orient view + workspace readiness in parallel (budget max +200ms added latency)
246
1191
  log('Fetching workspace context...');
247
1192
  let orientView = null;
1193
+ let workspaceProfile = null;
248
1194
  try {
249
- orientView = await mcpCall('chain.getOrientView', {});
1195
+ const workspaceReadinessPromise = kernelCall('chain.workspaceReadiness', {}).catch(() => null);
1196
+ const [orientResult, readinessRaw] = await Promise.all([
1197
+ kernelCall('chain.getOrientView', orientArgs).catch((err) => {
1198
+ logErr(`Warning: could not fetch workspace context — ${err instanceof Error ? err.message : err}`);
1199
+ logErr('Continuing with limited context (Chain search + portable knowledge only).');
1200
+ return null;
1201
+ }),
1202
+ workspaceReadinessPromise,
1203
+ ]);
1204
+ orientView = orientResult;
1205
+ workspaceProfile = extractWorkspaceProfile(readinessRaw);
250
1206
  }
251
1207
  catch (err) {
252
1208
  logErr(`Warning: could not fetch workspace context — ${err instanceof Error ? err.message : err}`);
253
1209
  logErr('Continuing with limited context (Chain search + portable knowledge only).');
254
1210
  }
1211
+ if (workspaceProfile) {
1212
+ log(`Workspace profile: stage=${workspaceProfile.stage}, entries=${workspaceProfile.totalEntries}, governance=${workspaceProfile.governanceMode}`);
1213
+ }
255
1214
  // 3. Build search queries from repo context
256
1215
  const searchQueries = [];
257
1216
  if (repo.name && repo.name.length >= 2)
@@ -269,76 +1228,718 @@ export async function runHandshake(options = {}) {
269
1228
  let matchedEntries = [];
270
1229
  if (uniqueQueries.length > 0) {
271
1230
  log(`Searching Chain for: ${uniqueQueries.join(', ')}...`);
272
- const searchResults = await Promise.all(uniqueQueries.map((q) => mcpCall('chain.searchEntries', { query: q }).catch(() => [])));
1231
+ const searchResults = await Promise.all(uniqueQueries.map((q) => kernelCall('chain.searchEntries', { query: q }).catch(() => [])));
273
1232
  matchedEntries = deduplicateEntries(searchResults.flat());
274
1233
  }
275
- // 5. Read canonical skills & rules from .productbrain/
1234
+ // 5. Read canonical skills & rules DB-first (WP-345 S0c, TEN-1459), FS fallback.
1235
+ // Primary: query setup.listAssetsForUser from DB (workspace SSOT).
1236
+ // Fallback: read from .productbrain/ filesystem (legacy — used when DB is empty or unavailable).
276
1237
  const pbDir = join(cwd, '.productbrain');
277
- const allSkills = readCanonicalSkills(pbDir);
278
- const allRules = readCanonicalRules(pbDir);
279
- // Apply level filtering (after read, before target filtering in write loop)
280
- const canonicalSkills = filterByLevel(allSkills, level);
281
- const canonicalRules = filterByLevel(allRules, level);
1238
+ const manifestStatus = readManifestStatus(pbDir);
1239
+ const manifest = manifestStatus.manifest;
1240
+ const surfaceValidation = validateSurfacesForMode(manifestStatus.mode, manifestStatus.surfaces);
1241
+ if (applyMode && surfaceValidation.error === SURFACE_GOVERN_NO_SURFACES) {
1242
+ throw new CLIError('materialize: govern requires at least one registered manifest surface.', {
1243
+ code: ErrorCode.VALIDATION_FAILED,
1244
+ category: 'validation',
1245
+ guidance: 'Add surfaces such as `.cursor` or `.claude` to .productbrain/manifest.yaml.',
1246
+ });
1247
+ }
1248
+ for (const surface of surfaceValidation.unregisteredSurfaces) {
1249
+ logErr(`Warning: manifest surface "${surface}" is not registered; skipping it.`);
1250
+ }
1251
+ const manifestTargets = new Set(surfaceValidation.registeredSurfaces);
1252
+ const cliTargets = new Set();
1253
+ const ignoredCliSurfaces = [];
1254
+ for (const surface of options.surfaces ?? []) {
1255
+ const normalized = normalizeSurfaceName(surface);
1256
+ if (normalized && manifestTargets.has(normalized)) {
1257
+ cliTargets.add(normalized);
1258
+ }
1259
+ else {
1260
+ ignoredCliSurfaces.push(surface);
1261
+ }
1262
+ }
1263
+ if (ignoredCliSurfaces.length > 0) {
1264
+ logErr(`Warning: --surfaces ignored outside manifest.surfaces: ${ignoredCliSurfaces.join(', ')}`);
1265
+ }
1266
+ const allowedTargets = options.surfaces && options.surfaces.length > 0
1267
+ ? cliTargets
1268
+ : manifestTargets;
1269
+ const perimeterManifest = {
1270
+ surfaces: [...manifestTargets].flatMap(surfacePerimeterRoots),
1271
+ };
1272
+ const authorityCanWrite = manifestStatus.mode === 'project' || manifestStatus.mode === 'govern';
1273
+ const authorityPreviewOnly = applyMode && !authorityCanWrite;
1274
+ const writeMode = applyMode && authorityCanWrite;
1275
+ let dbSkills = [];
1276
+ let dbRules = [];
1277
+ let usedDbSource = false;
1278
+ let dbAssetRows = [];
1279
+ // WP-379 S4: dormant assets (gate-failed) — their on-disk files get the dormant marker.
1280
+ let dormantDbAssetRows = [];
1281
+ // WP-428 S2 (Finding #5): tracks entryIds whose body fetch from storage failed.
1282
+ // Hoisted here (same scope as dbAssetRows) so both the skills/rules projection loop
1283
+ // AND the authoring-file projection loop can skip failed assets.
1284
+ const bodyFetchFailedEntryIds = new Set();
1285
+ const dbProjectionHashes = new Map();
1286
+ const syncDriftTensToFire = [];
1287
+ const deferredAuthoringBaselineEntryIds = new Set();
1288
+ if (writeMode) {
1289
+ const authoringItems = scanSetupAuthoringFiles(pbDir);
1290
+ if (authoringItems.length > 0) {
1291
+ // WP-428 S2 (Critical #1): ingestSetupAssetsBatch is an internalMutation — it cannot
1292
+ // call ctx.storage.store(). We now call ingestSetupAssetWithBody (action) per-asset so
1293
+ // each asset gets bodyStorageId written. This loses intra-batch collision detection;
1294
+ // canonical-id collision check is now client-side before dispatch.
1295
+ //
1296
+ // Client-side collision detection (replaces server-side DEC-954 check in the batch mutation):
1297
+ const idToPaths = new Map();
1298
+ for (const item of authoringItems) {
1299
+ const canonicalId = item.frontmatterId?.trim() || item.derivedEntryId;
1300
+ const paths = idToPaths.get(canonicalId) ?? [];
1301
+ paths.push(item.filePath);
1302
+ idToPaths.set(canonicalId, paths);
1303
+ }
1304
+ const conflictingPaths = new Set();
1305
+ for (const [, paths] of idToPaths) {
1306
+ if (paths.length > 1) {
1307
+ for (const p of paths)
1308
+ conflictingPaths.add(p);
1309
+ }
1310
+ }
1311
+ if (conflictingPaths.size > 0) {
1312
+ logErr(`Setup authoring import partial: ${conflictingPaths.size} file(s) refused for duplicate setup id. ` +
1313
+ [...conflictingPaths].join(', '));
1314
+ }
1315
+ const itemsToIngest = authoringItems.filter((item) => !conflictingPaths.has(item.filePath));
1316
+ if (itemsToIngest.length > 0) {
1317
+ try {
1318
+ // Parallel uploads — concurrency limit 10 to avoid overwhelming the gateway.
1319
+ const CONCURRENCY = 10;
1320
+ const ingestResults = [];
1321
+ for (let i = 0; i < itemsToIngest.length; i += CONCURRENCY) {
1322
+ const batch = itemsToIngest.slice(i, i + CONCURRENCY);
1323
+ const settled = await Promise.allSettled(batch.map(async (item) => {
1324
+ const result = await kernelCall('setup.ingestSetupAssetWithBody', {
1325
+ entryId: item.derivedEntryId,
1326
+ frontmatterId: item.frontmatterId,
1327
+ name: item.name,
1328
+ description: item.description,
1329
+ body: item.body,
1330
+ assetKind: item.assetKind,
1331
+ triggers: item.triggers,
1332
+ semanticRefs: item.semanticRefs,
1333
+ authoringPath: relative(pbDir, item.filePath).split(sep).join('/'),
1334
+ });
1335
+ return { filePath: item.filePath, ...result };
1336
+ }));
1337
+ for (const r of settled) {
1338
+ if (r.status === 'fulfilled') {
1339
+ ingestResults.push(r.value);
1340
+ if (r.value.conflict === 'repo-wins') {
1341
+ syncDriftTensToFire.push(`Repo authoring file won setup sync conflict for ${r.value.entryId} at ${r.value.filePath}.`);
1342
+ logErr(`Warning: repo authoring file won sync conflict for ${r.value.entryId}; DB edit was overwritten.`);
1343
+ }
1344
+ }
1345
+ else {
1346
+ trackEvent('setup.authoring_import.item_failed', { error: r.reason instanceof Error ? r.reason.message : String(r.reason) });
1347
+ logErr(`Warning: setup authoring import failed for one asset — ${r.reason instanceof Error ? r.reason.message : String(r.reason)}`);
1348
+ }
1349
+ }
1350
+ }
1351
+ if (ingestResults.length > 0) {
1352
+ log(`Setup authoring import: ${ingestResults.length} file(s) checked (with bodyStorageId).`);
1353
+ }
1354
+ }
1355
+ catch (err) {
1356
+ trackEvent('setup.authoring_import.failed', { error: err instanceof Error ? err.message : String(err) });
1357
+ logErr(`Warning: setup authoring import failed — ${err instanceof Error ? err.message : String(err)}`);
1358
+ }
1359
+ }
1360
+ }
1361
+ }
1362
+ try {
1363
+ // WP-379 S4: listAssetsForUser now returns { activeAssets, dormantAssets }.
1364
+ // Wire format changed from DbAsset[] to { activeAssets: DbAsset[], dormantAssets: DbAsset[] }.
1365
+ // Fall back to empty arrays if the server returns the old flat-array shape (graceful degradation).
1366
+ const rawResponse = await kernelCall('setup.listAssetsForUser', {}).catch(() => null);
1367
+ let dbAssets = [];
1368
+ if (rawResponse !== null) {
1369
+ if (Array.isArray(rawResponse)) {
1370
+ // Pre-S4 server — treat entire response as active assets with no dormant list.
1371
+ dbAssets = rawResponse;
1372
+ dormantDbAssetRows = [];
1373
+ }
1374
+ else {
1375
+ dbAssets = rawResponse.activeAssets ?? [];
1376
+ dormantDbAssetRows = rawResponse.dormantAssets ?? [];
1377
+ }
1378
+ }
1379
+ if (dbAssets.length > 0) {
1380
+ dbAssetRows = dbAssets;
1381
+ // WP-428 S2: body is no longer inline — fetch from storage per-asset when bodyStorageId is set.
1382
+ // Projectable assets: non-disabled skill/rule/hook entries. Fetch bodies in parallel (bounded).
1383
+ const projectableAssets = dbAssets.filter((a) => !a.disabledByOwner && (a.assetKind === 'skill' || a.assetKind === 'rule' || a.assetKind === 'hook'));
1384
+ const assetsNeedingBodyFetch = projectableAssets.filter((a) => a.bodyStorageId);
1385
+ const bodyFetchMap = new Map(); // entryId → body
1386
+ // WP-428 S2 (Finding #5/#12): track fetch-failed assets so we can skip their projection.
1387
+ // Failed entryIds are excluded from dbSkills/dbRules — no empty body written, no lastProjectedHash update.
1388
+ // bodyFetchFailedEntryIds is declared at outer scope (also used by authoring-file projection loop).
1389
+ if (assetsNeedingBodyFetch.length > 0) {
1390
+ log(`Fetching ${assetsNeedingBodyFetch.length} asset body(s) from storage...`);
1391
+ const bodyFetchResults = await Promise.allSettled(assetsNeedingBodyFetch.map(async (asset) => {
1392
+ const result = await kernelCall('setup.fetchAssetBody', { bodyStorageId: asset.bodyStorageId });
1393
+ return { entryId: asset.entryId, name: asset.name, body: result.body };
1394
+ }));
1395
+ for (let i = 0; i < bodyFetchResults.length; i++) {
1396
+ const result = bodyFetchResults[i];
1397
+ if (result.status === 'fulfilled') {
1398
+ bodyFetchMap.set(result.value.entryId, result.value.body);
1399
+ }
1400
+ else {
1401
+ // WP-428 S2 (Finding #12): include entryId and name in the warning (Finding #5: skip projection).
1402
+ const asset = assetsNeedingBodyFetch[i];
1403
+ logErr(`Warning: failed to fetch body for ${asset.entryId} (${asset.name}) — ${result.reason instanceof Error ? result.reason.message : String(result.reason)}`);
1404
+ bodyFetchFailedEntryIds.add(asset.entryId);
1405
+ }
1406
+ }
1407
+ if (bodyFetchFailedEntryIds.size > 0) {
1408
+ // WP-439 S4: strict-by-default. Any body-fetch failure is a hard
1409
+ // failure unless --lenient is passed. The strict path surfaces an
1410
+ // actionable pointer at the audit/repair command operators can run
1411
+ // to diagnose and fix orphaned setup-asset rows.
1412
+ const failedList = [...bodyFetchFailedEntryIds].join(', ');
1413
+ if (options.lenient) {
1414
+ logErr(`Warning: ${bodyFetchFailedEntryIds.size} asset(s) skipped due to body fetch failure (--lenient): ${failedList}`);
1415
+ }
1416
+ else {
1417
+ throw new CLIError(`${bodyFetchFailedEntryIds.size} asset(s) failed body fetch: ${failedList}. ` +
1418
+ `Run \`pb setup-audit\` to diagnose, then \`pb setup-audit --repair\` to reseed. ` +
1419
+ `Pass --lenient to suppress this and continue with affected entries skipped (legacy behaviour).`, { code: ErrorCode.INTERNAL, category: 'internal' });
1420
+ }
1421
+ }
1422
+ }
1423
+ // Map DB assets to CanonicalSkill/CanonicalRule shapes
1424
+ for (const asset of dbAssets) {
1425
+ if (asset.disabledByOwner)
1426
+ continue;
1427
+ // WP-428 S2 (Finding #5): skip projection for assets whose body fetch failed.
1428
+ // Do NOT write empty body to disk and do NOT update lastProjectedHash.
1429
+ if (bodyFetchFailedEntryIds.has(asset.entryId))
1430
+ continue;
1431
+ // WP-428 S2: resolve body — prefer storage-fetched body, fall back to inline body (pre-S2 servers).
1432
+ // Fallback: pre-S2 servers (no bodyStorageId) return inline body. Once all servers are S2+, this can be deleted.
1433
+ const resolvedBody = bodyFetchMap.get(asset.entryId) ?? asset.body ?? '';
1434
+ if (asset.assetKind === 'skill') {
1435
+ dbSkills.push({
1436
+ name: asset.name,
1437
+ description: asset.description,
1438
+ triggers: asset.triggers ?? [],
1439
+ body: resolvedBody,
1440
+ sourcePath: `db:${asset.entryId}`,
1441
+ });
1442
+ }
1443
+ else if (asset.assetKind === 'rule' || asset.assetKind === 'hook') {
1444
+ dbRules.push({
1445
+ name: asset.name,
1446
+ description: asset.description,
1447
+ autoApply: false,
1448
+ body: resolvedBody,
1449
+ sourcePath: `db:${asset.entryId}`,
1450
+ });
1451
+ }
1452
+ }
1453
+ usedDbSource = true;
1454
+ log(`Setup assets: ${dbSkills.length} skills, ${dbRules.length} rules/hooks from DB (WP-345 DB-first path)`);
1455
+ if (dormantDbAssetRows.length > 0) {
1456
+ log(`Setup assets: ${dormantDbAssetRows.length} dormant (gate-filtered) asset(s) will be marked on disk`);
1457
+ }
1458
+ }
1459
+ }
1460
+ catch {
1461
+ // DB source unavailable — silently fall through to FS path
1462
+ }
1463
+ const allSkills = usedDbSource ? dbSkills : readCanonicalSkills(pbDir);
1464
+ const manualRules = usedDbSource ? dbRules : readCanonicalRules(pbDir);
1465
+ if (!usedDbSource) {
1466
+ log('Setup assets: reading from filesystem (DB source unavailable or empty)');
1467
+ }
1468
+ // 5a-pre. E4: Resolve semantic refs in DB assets (WP-345, DEC-A, DEC-C, DEC-K)
1469
+ // For each asset with semanticRefs[], resolve them via the Convex resolver and
1470
+ // replace {{ref:key}} placeholders in the body. Runs in apply mode only (not preview).
1471
+ // NG11: PostHog events fire from CLI side only (never inside Convex mutations).
1472
+ if (usedDbSource && writeMode) {
1473
+ const projectableDbAssets = dbAssetRows.filter((a) => !a.disabledByOwner && (a.assetKind === 'skill' || a.assetKind === 'rule' || a.assetKind === 'hook'));
1474
+ const assetsWithRefs = projectableDbAssets.filter((a) => a.semanticRefs && a.semanticRefs.length > 0);
1475
+ if (assetsWithRefs.length > 0) {
1476
+ log(`Resolving semantic refs for ${assetsWithRefs.length} asset(s)...`);
1477
+ // Collect unique ref keys across all assets
1478
+ const allRefKeys = [...new Set(assetsWithRefs.flatMap((a) => a.semanticRefs))];
1479
+ // Resolve all refs in a single batch call. Shape: SetupRefResolution[]
1480
+ // (DEC-767 / WP-354 Build-Order #6 — kind + status discriminator).
1481
+ let resolvedRefs = [];
1482
+ try {
1483
+ resolvedRefs = await kernelCall('setup.resolveSemanticRefs', { semanticRefs: allRefKeys });
1484
+ }
1485
+ catch (err) {
1486
+ trackEvent('setup.refs.resolve_failed', { error: err instanceof Error ? err.message : String(err) });
1487
+ logErr(`Warning: could not resolve semantic refs — ${err instanceof Error ? err.message : String(err)}`);
1488
+ }
1489
+ // Build resolved map: canonicalKey → display name. Only required refs
1490
+ // count as unresolved warnings; seed/unknown refs are not gates.
1491
+ const resolvedMap = new Map();
1492
+ let unresolvedCount = 0;
1493
+ for (const result of resolvedRefs) {
1494
+ if (result.status === 'resolved' && result.localEntryId) {
1495
+ resolvedMap.set(result.ref, result.localEntryId);
1496
+ trackEvent('skill.ref.resolved', { ref: result.ref, kind: result.kind });
1497
+ }
1498
+ else if (result.status === 'unsupported-future') {
1499
+ // seed: refs are explicitly future scope per WP-354 Build-Order #6 — not a warning.
1500
+ trackEvent('skill.ref.future', { ref: result.ref, kind: result.kind });
1501
+ }
1502
+ else if (result.required) {
1503
+ unresolvedCount++;
1504
+ trackEvent('skill.ref.unresolved', { ref: result.ref, kind: result.kind, status: result.status });
1505
+ }
1506
+ }
1507
+ if (unresolvedCount > 0) {
1508
+ logErr(`Warning: ${unresolvedCount} required semantic ref(s) could not be resolved.`);
1509
+ }
1510
+ // Projection must preserve ref tokens as portable machine-readable refs.
1511
+ // resolvedMap is only used for validation/telemetry here; generated setup
1512
+ // artifacts keep {{ref:domain:...}} / {{ref:entry:...}} intact.
1513
+ }
1514
+ // Compute projection hash for each projected DB asset (DEC-K).
1515
+ // The stored hash is sha256 of the normalized resolved asset body; DB persistence
1516
+ // is deferred until the write loop confirms a matching file was emitted.
1517
+ // Strip existing hash trailer and timestamp lines, normalize to LF, then hash.
1518
+ const HASH_TRAILER_REGEX = /^<!--\s*pb-hash:.*-->\s*$/gm;
1519
+ const TIMESTAMP_REGEX = /^<!--\s*pb-generated-at:.*-->\s*$/gm;
1520
+ for (const rawAsset of projectableDbAssets) {
1521
+ const resolvedAsset = [...dbSkills, ...dbRules].find((a) => a.sourcePath === `db:${rawAsset.entryId}`);
1522
+ if (!resolvedAsset)
1523
+ continue;
1524
+ try {
1525
+ // Build the projected body (what will be written to disk)
1526
+ const projectedBody = resolvedAsset.body;
1527
+ // Normalize: strip existing hash/timestamp trailers, convert to LF
1528
+ const normalized = projectedBody
1529
+ .replace(HASH_TRAILER_REGEX, '')
1530
+ .replace(TIMESTAMP_REGEX, '')
1531
+ .replace(/\r\n/g, '\n')
1532
+ .replace(/\r/g, '\n')
1533
+ .trimEnd();
1534
+ // Compute sha256 hash
1535
+ const hash = createHash('sha256').update(normalized, 'utf8').digest('hex');
1536
+ const hashTrailer = `<!-- pb-hash: sha256:${hash} -->`;
1537
+ // Append hash trailer to the projected body
1538
+ resolvedAsset.body = `${normalized}\n${hashTrailer}`;
1539
+ dbProjectionHashes.set(rawAsset.entryId, {
1540
+ hash: `sha256:${hash}`,
1541
+ assetKind: rawAsset.assetKind,
1542
+ });
1543
+ // Drift detection: compare against last known hash
1544
+ if (rawAsset.lastProjectedHash && rawAsset.lastProjectedHash !== `sha256:${hash}`) {
1545
+ trackEvent('skill.drift.detected', {
1546
+ entryId: rawAsset.entryId,
1547
+ assetKind: rawAsset.assetKind,
1548
+ });
1549
+ log(`Drift detected for asset ${rawAsset.entryId} — projecting updated version.`);
1550
+ }
1551
+ trackEvent('skill.projection.succeeded', {
1552
+ entryId: rawAsset.entryId,
1553
+ assetKind: rawAsset.assetKind,
1554
+ });
1555
+ }
1556
+ catch (err) {
1557
+ trackEvent('skill.projection.failed', {
1558
+ entryId: rawAsset.entryId,
1559
+ assetKind: rawAsset.assetKind,
1560
+ });
1561
+ logErr(`Warning: projection failed for ${rawAsset.entryId} — ${err instanceof Error ? err.message : String(err)}`);
1562
+ }
1563
+ }
1564
+ }
1565
+ // 5a. Optionally fetch and merge Chain-derived rules (--generate flag)
1566
+ let chainRulesStats = null;
1567
+ let chainGaps = [];
1568
+ let allRules = manualRules;
1569
+ if (generate) {
1570
+ log('Generating Chain-derived rules...');
1571
+ const chainResult = await generateChainRules(kernelCall, manualRules);
1572
+ if (chainResult.sentinel) {
1573
+ // MCP unavailable — inject sentinel rule and warn
1574
+ allRules = [...manualRules, chainResult.sentinel];
1575
+ logErr('Warning: Chain MCP unavailable — generated rules are disabled. Sentinel rule injected.');
1576
+ }
1577
+ else {
1578
+ // Merge generated rules after manual rules (manual takes precedence on dedup)
1579
+ allRules = [...manualRules, ...chainResult.rules];
1580
+ chainRulesStats = chainResult.stats;
1581
+ chainGaps = chainResult.gaps;
1582
+ const { generatedRules, suppressedByManual, suppressedByZeroEntries } = chainResult.stats;
1583
+ log(`Chain-derived rules: ${generatedRules} generated, ${suppressedByManual} suppressed by manual, ${suppressedByZeroEntries} gaps`);
1584
+ if (chainGaps.length > 0) {
1585
+ log(`Gaps (no matching governance entries): ${chainGaps.join(', ')}`);
1586
+ }
1587
+ // Diff: compare current state against previous run
1588
+ const previousState = loadPreviousState(pbDir);
1589
+ const currentState = buildCurrentState(chainResult.rules, chainResult.classified);
1590
+ saveHandshakeState(pbDir, chainResult.rules, chainResult.classified);
1591
+ const diff = diffHandshakeState(currentState, previousState);
1592
+ const diffText = formatDiff(diff);
1593
+ log(diffText);
1594
+ }
1595
+ }
1596
+ // 5b. Read personal layer (WP-310 E2) — machine-local rules/skills from .productbrain/.local/
1597
+ // Returns [] when the directory is absent. All returned entries have persist: 'local'.
1598
+ const personalRules = readPersonalLayer(pbDir);
1599
+ if (personalRules.length > 0) {
1600
+ // Name collision detection — warn when a personal rule overrides a team rule
1601
+ const teamRuleNames = new Set(allRules.map((r) => r.name));
1602
+ for (const pr of personalRules) {
1603
+ if (teamRuleNames.has(pr.name)) {
1604
+ logErr(`Personal rule "${pr.name}" overrides team rule (local takes precedence).`);
1605
+ }
1606
+ }
1607
+ // Merge: team rules first, personal rules appended (personal takes precedence via name collision above)
1608
+ allRules = [...allRules, ...personalRules];
1609
+ }
1610
+ const personalSkills = readPersonalSkillsLayer(pbDir);
1611
+ if (personalSkills.length > 0) {
1612
+ const teamSkillNames = new Set(allSkills.map((s) => s.name));
1613
+ for (const ps of personalSkills) {
1614
+ if (teamSkillNames.has(ps.name)) {
1615
+ logErr(`Personal skill "${ps.name}" overrides team skill (local takes precedence).`);
1616
+ }
1617
+ }
1618
+ allSkills.push(...personalSkills);
1619
+ }
1620
+ // 5d. Load method registry (WP-310 E4) — only when manifest is present.
1621
+ let registrySource;
1622
+ let registryStale;
1623
+ if (manifest) {
1624
+ const registryResult = await loadMethodRegistry(manifest.method_source, kernelCall).catch(() => null);
1625
+ if (registryResult) {
1626
+ registrySource = registryResult.source;
1627
+ registryStale = registryResult.stale;
1628
+ }
1629
+ }
1630
+ const adoptionFilteredSkills = filterByAdoptionState(allSkills, manifest);
1631
+ const adoptionFilteredRules = filterByAdoptionState(allRules, manifest);
1632
+ // Compute adoption counts for report (only meaningful when manifest is present)
1633
+ const adoptedRulesCount = manifest ? adoptionFilteredRules.length : undefined;
1634
+ const rejectedRulesCount = manifest ? allRules.length - adoptionFilteredRules.length : undefined;
1635
+ // Apply level filtering with stage-gating (after adoption filter, before target filtering in write loop)
1636
+ // Stage caps the effective level: blank→beginner, seed→intermediate, grounded+→expert.
1637
+ // If stage caps below the requested level, log it so the user knows why items were dropped.
1638
+ const profileStage = workspaceProfile?.stage;
1639
+ const levelFilteredSkills = filterByLevel(adoptionFilteredSkills, level, profileStage);
1640
+ const levelFilteredRules = filterByLevel(adoptionFilteredRules, level, profileStage);
1641
+ // Log when stage gating changes the effective level
1642
+ if (profileStage) {
1643
+ const stageCap = STAGE_TO_MAX_LEVEL[profileStage];
1644
+ if (stageCap) {
1645
+ const requestedIdx = level ? LEVEL_ORDER.indexOf(level) : LEVEL_ORDER.length - 1;
1646
+ const capIdx = LEVEL_ORDER.indexOf(stageCap);
1647
+ if (capIdx < requestedIdx) {
1648
+ log(`Stage "${profileStage}" caps level from ${level || 'expert'} to ${stageCap}`);
1649
+ }
1650
+ }
1651
+ }
1652
+ // Apply when-condition filtering (stage-aware, workspace profile + repo context)
1653
+ const canonicalSkills = levelFilteredSkills.filter((skill) => {
1654
+ const result = evaluateConditions(skill.conditions ?? {}, workspaceProfile, repo);
1655
+ if (dryRun && !result.included) {
1656
+ log(` EXCLUDED skill ${skill.name}: ${result.reasons.join(', ')}`);
1657
+ }
1658
+ return result.included;
1659
+ });
1660
+ const canonicalRules = levelFilteredRules.filter((rule) => {
1661
+ const result = evaluateConditions(rule.conditions ?? {}, workspaceProfile, repo);
1662
+ if (dryRun && !result.included) {
1663
+ log(` EXCLUDED rule ${rule.name}: ${result.reasons.join(', ')}`);
1664
+ }
1665
+ return result.included;
1666
+ });
1667
+ if (dryRun && canonicalSkills.length > 0) {
1668
+ log(` INCLUDED skills: ${canonicalSkills.map((s) => s.name).join(', ')}`);
1669
+ }
1670
+ if (dryRun && canonicalRules.length > 0) {
1671
+ log(` INCLUDED rules: ${canonicalRules.map((r) => r.name).join(', ')}`);
1672
+ }
282
1673
  if (canonicalSkills.length > 0 || canonicalRules.length > 0) {
283
1674
  const levelSuffix = level ? ` (level: ${level})` : '';
284
- log(`Portable knowledge: ${canonicalSkills.length} skill(s), ${canonicalRules.length} rule(s)${levelSuffix}`);
1675
+ const stageSuffix = profileStage ? `, stage: ${profileStage}` : '';
1676
+ const stackSuffix = repo.detectedStack.length > 0 ? `, stack: [${repo.detectedStack.join(', ')}]` : '';
1677
+ const totalSkills = allSkills.length;
1678
+ const totalRules = allRules.length;
1679
+ log(`Portable knowledge: ${canonicalSkills.length}/${totalSkills} skills, ${canonicalRules.length}/${totalRules} rules${levelSuffix}${stageSuffix}${stackSuffix}`);
285
1680
  }
286
1681
  // 6. Generate file contents
287
- const contextContent = orientView ? generateContextMd(orientView, repo, timestamp) : null;
1682
+ // Build workspace context for AGENTS.md enrichment (stage, focus, governance, entry count)
1683
+ const agentsWorkspaceContext = workspaceProfile
1684
+ ? {
1685
+ stage: workspaceProfile.stage,
1686
+ focus: orientView?.strategicContext?.currentWorkPackage ?? undefined,
1687
+ governanceMode: workspaceProfile.governanceMode,
1688
+ totalEntries: workspaceProfile.totalEntries,
1689
+ }
1690
+ : undefined;
1691
+ // Collect codex-targeted skills for AGENTS.md skill directory.
1692
+ // persist: 'local' entries are included; all projections are now local-only.
1693
+ const agentsCodexSkills = canonicalSkills
1694
+ .filter((s) => shouldEmitToTarget(s, 'codex'))
1695
+ .map((s) => ({
1696
+ name: s.name,
1697
+ description: s.description,
1698
+ triggers: s.triggers,
1699
+ }));
1700
+ // Collect copilot-targeted skills for copilot-instructions.md skill summaries
1701
+ const copilotSkills = canonicalSkills
1702
+ .filter((s) => shouldEmitToTarget(s, 'copilot'))
1703
+ .map((s) => ({
1704
+ name: s.name,
1705
+ description: s.description,
1706
+ triggers: s.triggers,
1707
+ }));
1708
+ // Collect copilot-targeted rules for copilot-instructions.md rule summaries
1709
+ const copilotRules = canonicalRules
1710
+ .filter((r) => shouldEmitToTarget(r, 'copilot'))
1711
+ .map((r) => ({
1712
+ name: r.name,
1713
+ description: r.description,
1714
+ }));
1715
+ const copilotProfile = resolveSurfaceProfile('copilot');
1716
+ const copilotOptions = {
1717
+ profile: copilotProfile,
1718
+ workspaceContext: agentsWorkspaceContext,
1719
+ skills: copilotSkills.length > 0 ? copilotSkills : undefined,
1720
+ rules: copilotRules.length > 0 ? copilotRules : undefined,
1721
+ };
1722
+ const contextContent = orientView ? generateContextMd(orientView, repo, timestamp, workspaceProfile?.stage) : null;
288
1723
  const briefingContent = generateBriefingMd(matchedEntries, repo, uniqueQueries, timestamp);
1724
+ const agentsContent = generateAgentsMd(timestamp, {
1725
+ workspaceContext: agentsWorkspaceContext,
1726
+ skills: agentsCodexSkills.length > 0 ? agentsCodexSkills : undefined,
1727
+ });
289
1728
  const claudeContent = generateClaudeMd(timestamp);
290
1729
  const cursorContent = generateCursorMdc(timestamp);
291
- const copilotContent = generateCopilotMd(timestamp);
1730
+ const copilotContent = generateCopilotMd(timestamp, copilotOptions);
1731
+ const boundaryEnforcementMode = getBoundaryEnforcementMode(manifest);
1732
+ const boundaryManifestContent = boundaryEnforcementMode === 'advisory'
1733
+ ? null
1734
+ : generateBoundaryManifest(pbDir);
292
1735
  // 7. Write files
293
1736
  const filesWritten = [];
294
1737
  const filesSkipped = [];
1738
+ const previewPlan = [];
1739
+ if (writeMode && usedDbSource) {
1740
+ const authoringSyncState = loadAuthoringSyncState(pbDir);
1741
+ let authoringSyncStateChanged = false;
1742
+ const personalAssets = dbAssetRows.filter((asset) => asset.scope === 'personal' &&
1743
+ !asset.disabledByOwner &&
1744
+ (asset.assetKind === 'skill' || asset.assetKind === 'rule' || asset.assetKind === 'hook'));
1745
+ for (const asset of personalAssets) {
1746
+ // WP-428 S2 (Finding #5): skip projection for assets whose body fetch failed.
1747
+ // Do NOT write the authoring file with empty body, do NOT update lastProjectedHash.
1748
+ if (bodyFetchFailedEntryIds.has(asset.entryId))
1749
+ continue;
1750
+ const authoringPath = setupAuthoringPath(cwd, asset);
1751
+ if (!authoringPath)
1752
+ continue;
1753
+ // Review: use relative() for correct cross-platform path computation (string-replace
1754
+ // mis-fires when cwd uses a non-'/' separator), matching the dormant passes below.
1755
+ const relativeAuthoringPath = relative(cwd, authoringPath);
1756
+ const bodyHash = setupAuthoringAssetHash(asset);
1757
+ const authoringExists = existsSync(authoringPath);
1758
+ const tracked = authoringSyncState.assets[asset.entryId];
1759
+ const trackedHere = tracked?.path === relativeAuthoringPath;
1760
+ const trackedMatchesServer = Boolean(trackedHere && asset.lastProjectedHash && tracked?.hash === asset.lastProjectedHash);
1761
+ if (!authoringExists && asset.lastProjectedHash && trackedHere && trackedMatchesServer) {
1762
+ try {
1763
+ const dormantResult = await kernelCall('setup.markPersonalSetupAssetDormantFromSync', { entryId: asset.entryId, expectedLastProjectedHash: tracked.hash });
1764
+ if (dormantResult.action === 'conflict') {
1765
+ syncDriftTensToFire.push(`Repo authoring deletion skipped for ${asset.entryId}; server baseline changed during sync, so writeback was deferred until the next DB read.`);
1766
+ logErr(`Warning: authoring deletion for ${asset.entryId} was not applied because the DB baseline changed during sync.`);
1767
+ deferredAuthoringBaselineEntryIds.add(asset.entryId);
1768
+ continue;
1769
+ }
1770
+ else {
1771
+ syncDriftTensToFire.push(`Repo authoring file was deleted for ${asset.entryId}; caller-owned personal setup asset marked dormant.`);
1772
+ log(`Setup authoring deletion: ${asset.entryId} marked dormant.`);
1773
+ delete authoringSyncState.assets[asset.entryId];
1774
+ authoringSyncStateChanged = true;
1775
+ continue;
1776
+ }
1777
+ }
1778
+ catch (err) {
1779
+ logErr(`Warning: could not mark ${asset.entryId} dormant after authoring deletion — ${err instanceof Error ? err.message : String(err)}`);
1780
+ continue;
1781
+ }
1782
+ }
1783
+ else if (!authoringExists && asset.lastProjectedHash && trackedHere) {
1784
+ syncDriftTensToFire.push(`Repo authoring deletion skipped for ${asset.entryId}; local sync baseline is stale, so DB writeback wins.`);
1785
+ logErr(`Warning: authoring deletion for ${asset.entryId} was not applied because the DB baseline changed.`);
1786
+ }
1787
+ const nextAuthoringContent = renderSetupAuthoringFile(asset);
1788
+ if (authoringExists) {
1789
+ const parsed = parseSetupAuthoringFrontmatter(readFileSync(authoringPath, 'utf8'));
1790
+ const fileHash = setupAuthoringAssetHash({
1791
+ entryId: parsed.frontmatterId?.trim() || asset.entryId,
1792
+ name: parsed.name || asset.name,
1793
+ description: parsed.description,
1794
+ body: parsed.body,
1795
+ assetKind: asset.assetKind,
1796
+ triggers: parsed.triggers,
1797
+ semanticRefs: parsed.semanticRefs,
1798
+ });
1799
+ if (fileHash === bodyHash) {
1800
+ if (asset.lastProjectedHash !== bodyHash) {
1801
+ await kernelCall('setup.updateLastProjectedHash', {
1802
+ entryId: asset.entryId,
1803
+ hash: bodyHash,
1804
+ }).catch(() => null);
1805
+ }
1806
+ authoringSyncState.assets[asset.entryId] = { path: relativeAuthoringPath, hash: bodyHash };
1807
+ authoringSyncStateChanged = true;
1808
+ continue;
1809
+ }
1810
+ if (!asset.lastProjectedHash) {
1811
+ syncDriftTensToFire.push(`Repo authoring file differs from DB for ${asset.entryId} at ${authoringPath} with no shared baseline; DB writeback skipped.`);
1812
+ logErr(`Warning: setup authoring drift for ${asset.entryId}; DB writeback skipped because no shared baseline exists.`);
1813
+ continue;
1814
+ }
1815
+ if (fileHash !== asset.lastProjectedHash &&
1816
+ bodyHash !== asset.lastProjectedHash) {
1817
+ syncDriftTensToFire.push(`Repo authoring file won setup sync conflict for ${asset.entryId} at ${authoringPath}.`);
1818
+ logErr(`Warning: repo authoring file won sync conflict for ${asset.entryId}; DB writeback skipped.`);
1819
+ continue;
1820
+ }
1821
+ if (fileHash !== asset.lastProjectedHash) {
1822
+ syncDriftTensToFire.push(`Repo authoring file differs from DB baseline for ${asset.entryId} at ${authoringPath}; DB writeback skipped.`);
1823
+ logErr(`Warning: setup authoring drift for ${asset.entryId}; DB writeback skipped.`);
1824
+ continue;
1825
+ }
1826
+ }
1827
+ try {
1828
+ assertSetupWritePath(authoringPath, perimeterManifest);
1829
+ mkdirSync(dirname(authoringPath), { recursive: true });
1830
+ writeFileSync(authoringPath, nextAuthoringContent);
1831
+ filesWritten.push(relativeAuthoringPath);
1832
+ await kernelCall('setup.updateLastProjectedHash', {
1833
+ entryId: asset.entryId,
1834
+ hash: bodyHash,
1835
+ }).catch(() => null);
1836
+ authoringSyncState.assets[asset.entryId] = { path: relativeAuthoringPath, hash: bodyHash };
1837
+ authoringSyncStateChanged = true;
1838
+ }
1839
+ catch (err) {
1840
+ logErr(`Warning: could not write setup authoring file for ${asset.entryId} — ${err instanceof Error ? err.message : String(err)}`);
1841
+ }
1842
+ }
1843
+ if (authoringSyncStateChanged) {
1844
+ try {
1845
+ saveAuthoringSyncState(pbDir, authoringSyncState);
1846
+ }
1847
+ catch (err) {
1848
+ logErr(`Warning: could not persist setup authoring sync state — ${err instanceof Error ? err.message : String(err)}`);
1849
+ }
1850
+ }
1851
+ }
295
1852
  const writes = [
296
1853
  ...(contextContent ? [{ path: join(cwd, '.productbrain', 'context.md'), relative: '.productbrain/context.md', content: contextContent, dirs: join(cwd, '.productbrain'), isAdapter: false }] : []),
297
1854
  { path: join(cwd, '.productbrain', 'briefing.md'), relative: '.productbrain/briefing.md', content: briefingContent, isAdapter: false },
298
- { path: join(cwd, 'CLAUDE.md'), relative: 'CLAUDE.md', content: claudeContent, isAdapter: true },
299
- { path: join(cwd, '.cursor', 'rules', 'chain.mdc'), relative: '.cursor/rules/chain.mdc', content: cursorContent, dirs: join(cwd, '.cursor', 'rules'), isAdapter: true },
300
- { path: join(cwd, '.github', 'copilot-instructions.md'), relative: '.github/copilot-instructions.md', content: copilotContent, dirs: join(cwd, '.github'), isAdapter: true },
1855
+ { path: join(cwd, 'AGENTS.md'), relative: 'AGENTS.md', content: agentsContent, isAdapter: true, target: 'codex', augmentTarget: true },
1856
+ { path: join(cwd, 'CLAUDE.md'), relative: 'CLAUDE.md', content: claudeContent, isAdapter: true, target: 'claude', augmentTarget: true },
1857
+ { path: join(cwd, '.cursor', 'rules', 'chain.mdc'), relative: '.cursor/rules/chain.mdc', content: cursorContent, dirs: join(cwd, '.cursor', 'rules'), isAdapter: true, target: 'cursor' },
1858
+ { path: join(cwd, '.github', 'copilot-instructions.md'), relative: '.github/copilot-instructions.md', content: copilotContent, dirs: join(cwd, '.github'), isAdapter: true, target: 'copilot' },
1859
+ ...(boundaryManifestContent ? [{
1860
+ path: join(cwd, '.productbrain', 'generated', 'boundaries.json'),
1861
+ relative: '.productbrain/generated/boundaries.json',
1862
+ content: boundaryManifestContent,
1863
+ dirs: join(cwd, '.productbrain', 'generated'),
1864
+ isAdapter: false,
1865
+ }] : []),
301
1866
  ];
302
1867
  // Add Cursor skill copies (filtered by target)
1868
+ const cursorProfile = resolveSurfaceProfile('cursor');
303
1869
  for (const skill of canonicalSkills) {
304
1870
  if (!shouldEmitToTarget(skill, 'cursor'))
305
1871
  continue;
1872
+ const dbAssetEntryId = skill.sourcePath.startsWith('db:') ? skill.sourcePath.slice(3) : undefined;
306
1873
  const skillDir = join(cwd, '.cursor', 'skills', skill.name);
307
1874
  writes.push({
308
1875
  path: join(skillDir, 'SKILL.md'),
309
1876
  relative: `.cursor/skills/${skill.name}/SKILL.md`,
310
- content: generateCursorSkill(skill),
1877
+ content: generateCursorSkill(skill, cursorProfile),
311
1878
  dirs: skillDir,
312
1879
  isAdapter: true,
1880
+ target: 'cursor',
1881
+ dbAssetEntryId,
1882
+ });
1883
+ }
1884
+ // Add Codex skill copies (projected markdown + index)
1885
+ const codexProfile = resolveSurfaceProfile('codex');
1886
+ const codexSkills = canonicalSkills.filter((s) => shouldEmitToTarget(s, 'codex'));
1887
+ for (const skill of codexSkills) {
1888
+ const dbAssetEntryId = skill.sourcePath.startsWith('db:') ? skill.sourcePath.slice(3) : undefined;
1889
+ writes.push({
1890
+ path: join(cwd, '.codex', 'skills', `${skill.name}.md`),
1891
+ relative: `.codex/skills/${skill.name}.md`,
1892
+ content: generateCodexSkill(skill, codexProfile),
1893
+ dirs: join(cwd, '.codex', 'skills'),
1894
+ isAdapter: true,
1895
+ target: 'codex',
1896
+ dbAssetEntryId,
313
1897
  });
314
1898
  }
1899
+ writes.push({
1900
+ path: join(cwd, '.codex', 'skills', 'README.md'),
1901
+ relative: '.codex/skills/README.md',
1902
+ content: generateCodexSkillIndex(codexSkills),
1903
+ dirs: join(cwd, '.codex', 'skills'),
1904
+ isAdapter: true,
1905
+ target: 'codex',
1906
+ });
1907
+ // Validate Codex-projected skills for dead references
1908
+ const codexWarnings = validateCodexSkills(codexSkills);
315
1909
  // Add Cursor rule copies (filtered by target)
316
1910
  for (const rule of canonicalRules) {
317
1911
  if (!shouldEmitToTarget(rule, 'cursor'))
318
1912
  continue;
1913
+ const dbAssetEntryId = rule.sourcePath.startsWith('db:') ? rule.sourcePath.slice(3) : undefined;
319
1914
  writes.push({
320
1915
  path: join(cwd, '.cursor', 'rules', `${rule.name}.mdc`),
321
1916
  relative: `.cursor/rules/${rule.name}.mdc`,
322
- content: generateCursorRule(rule),
1917
+ content: generateCursorRule(rule, cursorProfile),
323
1918
  dirs: join(cwd, '.cursor', 'rules'),
324
1919
  isAdapter: true,
1920
+ target: 'cursor',
1921
+ dbAssetEntryId,
325
1922
  });
326
1923
  }
327
1924
  // Add Claude Code rule copies (filtered by target)
1925
+ const claudeProfile = resolveSurfaceProfile('claude');
328
1926
  for (const rule of canonicalRules) {
329
1927
  if (!shouldEmitToTarget(rule, 'claude'))
330
1928
  continue;
1929
+ const dbAssetEntryId = rule.sourcePath.startsWith('db:') ? rule.sourcePath.slice(3) : undefined;
331
1930
  writes.push({
332
1931
  path: join(cwd, '.claude', 'rules', `${rule.name}.md`),
333
1932
  relative: `.claude/rules/${rule.name}.md`,
334
- content: generateClaudeRule(rule),
1933
+ content: generateClaudeRule(rule, claudeProfile),
335
1934
  dirs: join(cwd, '.claude', 'rules'),
336
1935
  isAdapter: true,
1936
+ target: 'claude',
1937
+ dbAssetEntryId,
337
1938
  });
338
1939
  }
339
1940
  // Add Claude Code skill router (filtered by target)
340
1941
  const claudeSkills = canonicalSkills.filter((s) => shouldEmitToTarget(s, 'claude'));
341
- const skillRouterContent = generateClaudeSkillRouter(claudeSkills);
1942
+ const skillRouterContent = generateClaudeSkillRouter(claudeSkills, claudeProfile);
342
1943
  if (skillRouterContent) {
343
1944
  writes.push({
344
1945
  path: join(cwd, '.claude', 'rules', 'skill-router.md'),
@@ -346,33 +1947,717 @@ export async function runHandshake(options = {}) {
346
1947
  content: skillRouterContent,
347
1948
  dirs: join(cwd, '.claude', 'rules'),
348
1949
  isAdapter: true,
1950
+ target: 'claude',
349
1951
  });
350
1952
  }
1953
+ // 7a. WP-379 S5b: Resolve projection collisions before writing.
1954
+ // In apply mode, enumerate target dirs and unlink any auto-generated files
1955
+ // whose normalized name no longer matches any active asset from the server.
1956
+ // This prevents case-variant orphans from accumulating across handshakes.
1957
+ // Runs only when we have a DB asset list (usedDbSource) — without a DB source,
1958
+ // we can't determine which files are canonical vs. orphan.
1959
+ const collisionTensToFire = [];
1960
+ if (writeMode && usedDbSource) {
1961
+ const activeAssetNames = dbAssetRows
1962
+ .filter((a) => !a.disabledByOwner)
1963
+ .map((a) => a.name);
1964
+ const { collisionTens } = resolveProjectionCollision(cwd, activeAssetNames, log, logErr);
1965
+ collisionTensToFire.push(...collisionTens);
1966
+ }
1967
+ // ── WP-436 S3: Vocab projector — fetch workspace vocab context once per handshake ──
1968
+ // Source-side (.productbrain/skills/*.md + rules/*.md) stays tokenized.
1969
+ // The projector resolves {{vocab:...}} tokens before writing adapter output to disk
1970
+ // (.cursor/rules/, .claude/rules/, CLAUDE.md, AGENTS.md, .github/copilot-instructions.md).
1971
+ // Fail-open: if vocab fetch fails, skip resolution and write raw token (no breakage).
1972
+ const handshakeVocabCtx = await getOrFetchVocabCtx(config.apiKey, async () => {
1973
+ try {
1974
+ const vocab = await kernelCall('chain.getVocabulary', {});
1975
+ if (vocab?.collectionLabels || vocab?.collectionDefaults) {
1976
+ return {
1977
+ ...(vocab.collectionLabels ? { collectionLabels: vocab.collectionLabels } : {}),
1978
+ ...(vocab.collectionDefaults ? { collectionDefaults: vocab.collectionDefaults } : {}),
1979
+ };
1980
+ }
1981
+ return null;
1982
+ }
1983
+ catch {
1984
+ return null; // fail-open
1985
+ }
1986
+ });
1987
+ const userOwnedSkipped = [];
1988
+ const projectedHashUpdates = new Map();
1989
+ const cleanBucketPaths = [];
1990
+ const tamperedBucket = [];
1991
+ const recordProjectedHash = (entryId) => {
1992
+ if (!applyMode || !entryId)
1993
+ return;
1994
+ if (deferredAuthoringBaselineEntryIds.has(entryId))
1995
+ return;
1996
+ const projection = dbProjectionHashes.get(entryId);
1997
+ if (projection)
1998
+ projectedHashUpdates.set(entryId, projection.hash);
1999
+ };
2000
+ // TEN-2155: region augmentation context + symlink dedupe.
2001
+ // codexActive gates the AGENTS.md skills-index pointer (region-projections.ts).
2002
+ const regionCtx = { codexActive: allowedTargets.has('codex') };
2003
+ const malformedRegionPaths = [];
2004
+ // If two augment targets resolve to the same inode (e.g. CLAUDE.md symlinked to AGENTS.md),
2005
+ // augment only the first-seen (AGENTS.md precedes CLAUDE.md in `writes`) to avoid double-injection.
2006
+ const seenAugmentRealpaths = new Set();
2007
+ const augmentTargetSkip = new Set();
351
2008
  for (const w of writes) {
2009
+ if (!w.augmentTarget || !w.target || !allowedTargets.has(w.target) || !existsSync(w.path))
2010
+ continue;
2011
+ let real;
2012
+ try {
2013
+ real = realpathSync(w.path);
2014
+ }
2015
+ catch {
2016
+ real = w.path;
2017
+ }
2018
+ if (seenAugmentRealpaths.has(real))
2019
+ augmentTargetSkip.add(w.path);
2020
+ else
2021
+ seenAugmentRealpaths.add(real);
2022
+ }
2023
+ for (const w of writes) {
2024
+ // Surface filtering: skip adapter writes for targets not in the allowed set
2025
+ if (w.target && !allowedTargets.has(w.target)) {
2026
+ filesSkipped.push({ path: w.relative, reason: `filtered (surface: ${w.target})` });
2027
+ if (preview)
2028
+ previewPlan.push({ path: w.relative, status: 'filtered' });
2029
+ continue;
2030
+ }
2031
+ // ── TEN-2155: augment user-owned CLAUDE.md / AGENTS.md with a marked PB region ──
2032
+ // Runs ahead of the legacy MARKER-keyed gates. Only existing augmentable/region-present
2033
+ // files are spliced here; absent + legacy-pb-managed fall through to the legacy path.
2034
+ if (w.augmentTarget) {
2035
+ const projection = REGION_PROJECTIONS[w.target];
2036
+ if (projection && existsSync(w.path)) {
2037
+ if (augmentTargetSkip.has(w.path)) {
2038
+ filesSkipped.push({ path: w.relative, reason: 'symlinked to another augment target — augmented once' });
2039
+ continue;
2040
+ }
2041
+ const disk = readFileSync(w.path, 'utf8');
2042
+ const cls = classifyAdapterFile(disk);
2043
+ if (cls === 'augmentable' || cls === 'region-present') {
2044
+ const eol = detectEol(disk);
2045
+ const region = replaceVocabTokens(projection.build(regionCtx, eol), handshakeVocabCtx);
2046
+ // Defense-in-depth: the composed region (post vocab-token resolution) must itself be a
2047
+ // single well-formed region. v1 content has no vocab tokens so this is a no-op, but it
2048
+ // guards the documented future override/vocab seam from injecting a stray sentinel/MARKER.
2049
+ if (classifyAdapterFile(region) !== 'region-present') {
2050
+ filesSkipped.push({ path: w.relative, reason: 'internal: composed PB region malformed — skipped to protect your file' });
2051
+ if (preview)
2052
+ previewPlan.push({ path: w.relative, status: 'needs-attention' });
2053
+ continue;
2054
+ }
2055
+ const candidate = cls === 'augmentable' ? spliceAppend(disk, region, eol) : spliceReplace(disk, region);
2056
+ if (candidate === disk) {
2057
+ filesSkipped.push({ path: w.relative, reason: 'unchanged' });
2058
+ if (preview)
2059
+ previewPlan.push({ path: w.relative, status: 'unchanged' });
2060
+ continue;
2061
+ }
2062
+ if (preview || dryRun) {
2063
+ filesWritten.push(w.relative + (dryRun ? ' (dry run)' : ''));
2064
+ if (preview)
2065
+ previewPlan.push({ path: w.relative, status: 'would-augment' });
2066
+ continue;
2067
+ }
2068
+ if (authorityPreviewOnly) {
2069
+ // apply + materialize observe/off: honor authority — do NOT write; mirror the legacy
2070
+ // preview-only skip so the report does not falsely list it as written.
2071
+ filesSkipped.push({ path: w.relative, reason: `preview-only (materialize: ${manifestStatus.mode})` });
2072
+ continue;
2073
+ }
2074
+ assertSetupWritePath(w.path, perimeterManifest);
2075
+ writeFileSync(w.path, candidate);
2076
+ filesWritten.push(w.relative);
2077
+ continue;
2078
+ }
2079
+ if (cls === 'malformed') {
2080
+ filesSkipped.push({ path: w.relative, reason: 'malformed PB region — left untouched; fix the pb:region sentinels' });
2081
+ if (preview)
2082
+ previewPlan.push({ path: w.relative, status: 'needs-attention' });
2083
+ malformedRegionPaths.push(w.relative);
2084
+ continue;
2085
+ }
2086
+ // cls 'pb-managed' → fall through to the legacy whole-file re-projection path below.
2087
+ // cls 'opt-out' (file carries the pb:no-augment sentinel — e.g. this repo's committed
2088
+ // constitution) → fall through too, landing on the legacy user-owned skip: left untouched,
2089
+ // never spliced. This is how a file declines augmentation without losing its user-owned status.
2090
+ }
2091
+ // absent file → fall through to legacy whole-file CREATE.
2092
+ }
352
2093
  if (w.isAdapter && !shouldWriteAdapter(w.path, force)) {
353
- filesSkipped.push({ path: w.relative, reason: 'exists without auto-generated marker (use --force to overwrite)' });
2094
+ // User-owned: a file at an adapter path without our auto-gen MARKER is the
2095
+ // user's own file. Leave it untouched — never overwrite, never treat as drift
2096
+ // or log a TEN (TEN-2150). Relayed to the connect screen via userOwnedSkipped.
2097
+ filesSkipped.push({ path: w.relative, reason: 'user-owned — left untouched (pb won\'t overwrite your file)' });
2098
+ if (preview) {
2099
+ previewPlan.push({ path: w.relative, status: 'user-owned' });
2100
+ }
2101
+ else {
2102
+ userOwnedSkipped.push(w.relative);
2103
+ }
2104
+ continue;
2105
+ }
2106
+ if (authorityPreviewOnly) {
2107
+ filesSkipped.push({
2108
+ path: w.relative,
2109
+ reason: `preview-only (materialize: ${manifestStatus.mode})`,
2110
+ });
354
2111
  continue;
355
2112
  }
356
- if (dryRun) {
357
- filesWritten.push(w.relative + ' (dry run)');
2113
+ if (preview || dryRun) {
2114
+ // In preview/dry-run mode: check content to distinguish new/update/unchanged
2115
+ if (existsSync(w.path)) {
2116
+ const current = readFileSync(w.path, 'utf8');
2117
+ const nextNormalized = normalizeHandshakeContentForComparison(w.content);
2118
+ const currentNormalized = normalizeHandshakeContentForComparison(current);
2119
+ if (nextNormalized === currentNormalized) {
2120
+ filesSkipped.push({ path: w.relative, reason: 'unchanged' });
2121
+ if (preview)
2122
+ previewPlan.push({ path: w.relative, status: 'unchanged' });
2123
+ }
2124
+ else {
2125
+ filesWritten.push(w.relative + (dryRun ? ' (dry run)' : ''));
2126
+ if (preview)
2127
+ previewPlan.push({ path: w.relative, status: 'would-update' });
2128
+ }
2129
+ }
2130
+ else {
2131
+ filesWritten.push(w.relative + (dryRun ? ' (dry run)' : ''));
2132
+ if (preview)
2133
+ previewPlan.push({ path: w.relative, status: 'would-write' });
2134
+ }
358
2135
  continue;
359
2136
  }
2137
+ // ── WP-421 S3: defer tampered adapter writes (doneWhen #17) ──────────────
2138
+ // For adapter projections that already exist on disk, classify into
2139
+ // pb-managed-clean / pb-managed-tampered. Tampered = MARKER present +
2140
+ // hash trailer mismatches body. Defer (do NOT overwrite); post-loop
2141
+ // resolution handles them. --force bypasses the tampered defer (legacy
2142
+ // semantic: explicit user opt-in to overwrite).
2143
+ if (w.isAdapter && !force) {
2144
+ const drift = classifyDriftBucket(w.path);
2145
+ if (drift && drift.bucket === 'pb-managed-tampered') {
2146
+ tamperedBucket.push({
2147
+ path: w.path,
2148
+ relative: w.relative,
2149
+ content: w.content,
2150
+ expectedHash: drift.expectedHash,
2151
+ actualHash: drift.actualHash,
2152
+ dirs: w.dirs,
2153
+ dbAssetEntryId: w.dbAssetEntryId,
2154
+ });
2155
+ // Do NOT write — defer until prompt/refusal resolves the file.
2156
+ continue;
2157
+ }
2158
+ if (drift && drift.bucket === 'pb-managed-clean') {
2159
+ cleanBucketPaths.push(w.relative);
2160
+ }
2161
+ }
2162
+ assertSetupWritePath(w.path, perimeterManifest);
360
2163
  if (w.dirs)
361
2164
  mkdirSync(w.dirs, { recursive: true });
362
- writeFileSync(w.path, w.content);
2165
+ // WP-436 S3: resolve {{vocab:...}} tokens before writing projected adapter files.
2166
+ // Source-side (.productbrain/skills/*.md, rules/*.md) stays tokenized.
2167
+ // Only adapter projections (cursor/rules, claude/rules, CLAUDE.md, AGENTS.md, etc.) get resolved.
2168
+ // Fail-open: if vocabCtx is undefined, replaceVocabTokens falls back to canonicalKey literals.
2169
+ const resolvedContent = w.isAdapter
2170
+ ? replaceVocabTokens(w.content, handshakeVocabCtx)
2171
+ : w.content;
2172
+ if (existsSync(w.path)) {
2173
+ const current = readFileSync(w.path, 'utf8');
2174
+ const nextNormalized = normalizeHandshakeContentForComparison(resolvedContent);
2175
+ const currentNormalized = normalizeHandshakeContentForComparison(current);
2176
+ if (nextNormalized === currentNormalized) {
2177
+ filesSkipped.push({ path: w.relative, reason: 'unchanged' });
2178
+ recordProjectedHash(w.dbAssetEntryId);
2179
+ continue;
2180
+ }
2181
+ }
2182
+ writeFileSync(w.path, resolvedContent);
363
2183
  filesWritten.push(w.relative);
2184
+ recordProjectedHash(w.dbAssetEntryId);
2185
+ }
2186
+ if (projectedHashUpdates.size > 0) {
2187
+ const updates = [...projectedHashUpdates];
2188
+ const results = await Promise.allSettled(updates.map(([entryId, hash]) => kernelCall('setup.updateLastProjectedHash', { entryId, hash })));
2189
+ results.forEach((result, index) => {
2190
+ if (result.status === 'rejected') {
2191
+ const [entryId] = updates[index];
2192
+ trackEvent('skill.projection.failed', {
2193
+ entryId,
2194
+ reason: result.reason instanceof Error ? result.reason.message : String(result.reason),
2195
+ });
2196
+ }
2197
+ });
2198
+ }
2199
+ // Ordering note: this refusal runs AFTER the projected-hash flush so that files legitimately
2200
+ // written THIS run still record their hashes; malformed files were never written (no hash to record).
2201
+ // TEN-2155: in non-interactive apply, a malformed PB region is a refusal, not a silent skip.
2202
+ // Gated on applyMode (NOT writeMode): a malformed region is a user-file INTEGRITY fault, so the
2203
+ // refusal fires on any headless `--apply` regardless of materialize authority (STD-263 invariant vi —
2204
+ // "headless → non-zero refusal", unqualified). writeMode would suppress it under observe/off, where
2205
+ // the malformed file still gets enumerated but the corruption signal would be silently dropped.
2206
+ if (applyMode && malformedRegionPaths.length > 0 && (options.noPrompt || !process.stdout.isTTY)) {
2207
+ throw new CLIError(`Malformed PB region in: ${malformedRegionPaths.join(', ')}`, {
2208
+ code: ErrorCode.VALIDATION_FAILED,
2209
+ category: 'validation',
2210
+ guidance: 'Fix the `<!-- pb:region:start -->` / `<!-- pb:region:end -->` sentinels (one balanced pair), then re-run `pb handshake`.',
2211
+ });
2212
+ }
2213
+ // ── WP-421 S3: tampered-bucket resolution (doneWhen #17) ────────────────────
2214
+ // Apply mode only. Tampered files were DEFERRED in the write loop above;
2215
+ // here we either prompt the user (interactive TTY) or refuse (headless).
2216
+ //
2217
+ // Headless = `--no-prompt` flag OR `process.stdout.isTTY === false`. When
2218
+ // headless: enumerate each tampered file to stderr, write a setup_receipt
2219
+ // row with kind='transition' (DEC-962) capturing `refusedTamperedFiles[]`,
2220
+ // then exit non-zero. NEVER auto-resolve. (#17 + exclusions: edits to
2221
+ // projection dirs are detected, NOT silently overwritten.)
2222
+ //
2223
+ // Interactive: for each tampered file, present adopt-or-revert. Adopt =
2224
+ // create a personal-scoped setup_asset draft from the tampered content
2225
+ // (see helper below). Revert = re-project canonical content over the
2226
+ // tampered file (write w.content to w.path).
2227
+ const adoptedTamperedPaths = [];
2228
+ const revertedTamperedPaths = [];
2229
+ if (writeMode && tamperedBucket.length > 0) {
2230
+ const headless = options.noPrompt === true || !process.stdout.isTTY;
2231
+ if (headless) {
2232
+ // ── Headless refusal path (doneWhen #17) ────────────────────────────────
2233
+ logErr('');
2234
+ logErr(`pb handshake: ${tamperedBucket.length} PB-managed projection file(s) were edited downstream of the auto-gen marker.`);
2235
+ logErr('Headless mode (--no-prompt or no TTY) cannot resolve adopt-or-revert — refusing.');
2236
+ logErr('');
2237
+ const refusedTamperedFiles = tamperedBucket.map((t) => ({
2238
+ path: t.relative,
2239
+ expectedHash: t.expectedHash,
2240
+ actualHash: t.actualHash,
2241
+ }));
2242
+ for (const refused of refusedTamperedFiles) {
2243
+ // Per #17: stderr enumerates each tampered file as
2244
+ // {path, expectedHash, actualHash, bucket}.
2245
+ logErr(` ${JSON.stringify({ ...refused, bucket: 'pb-managed-tampered' })}`);
2246
+ }
2247
+ logErr('');
2248
+ logErr('Re-run interactively to resolve, or use --force to overwrite (data loss).');
2249
+ // Write the kind='transition' setup_receipt row. Fail-open on the
2250
+ // network/auth side: if the row cannot be written, we still exit non-zero
2251
+ // (the audit trail is best-effort; refusal is mandatory).
2252
+ try {
2253
+ const manifestStatus = readManifestStatus(pbDir);
2254
+ await kernelCall('setup.recordTamperRefusal', {
2255
+ mode: manifestStatus.mode,
2256
+ refusedTamperedFiles,
2257
+ });
2258
+ trackEvent('setup.transition.refused', {
2259
+ fileCount: refusedTamperedFiles.length,
2260
+ mode: manifestStatus.mode,
2261
+ });
2262
+ }
2263
+ catch (err) {
2264
+ trackEvent('setup.transition.refused.write_failed', {
2265
+ error: err instanceof Error ? err.message : String(err),
2266
+ });
2267
+ logErr(`Warning: could not record transition receipt — ${err instanceof Error ? err.message : String(err)}`);
2268
+ }
2269
+ // Surface the report counts before exit (visibility for CI logs).
2270
+ if (!quiet) {
2271
+ process.stdout.write('\n');
2272
+ process.stdout.write(formatHandshakeReport({
2273
+ filesWritten,
2274
+ filesSkipped,
2275
+ matchedEntries,
2276
+ searchQueries: uniqueQueries,
2277
+ repo,
2278
+ codexWarnings: codexWarnings.length > 0 ? codexWarnings : undefined,
2279
+ chainRulesStats: chainRulesStats ?? undefined,
2280
+ chainGaps: chainGaps.length > 0 ? chainGaps : undefined,
2281
+ adoptedCount: adoptedRulesCount,
2282
+ rejectedCount: rejectedRulesCount,
2283
+ personalRuleCount: personalRules.length > 0 ? personalRules.length : undefined,
2284
+ personalSkillCount: personalSkills.length > 0 ? personalSkills.length : undefined,
2285
+ registrySource,
2286
+ registryStale,
2287
+ userOwnedSkipped: userOwnedSkipped.length > 0 ? userOwnedSkipped : undefined,
2288
+ managedCleanCount: cleanBucketPaths.length || undefined,
2289
+ tamperedFiles: refusedTamperedFiles,
2290
+ }) + '\n');
2291
+ }
2292
+ // Exit non-zero per #17.
2293
+ process.exit(1);
2294
+ }
2295
+ // ── Interactive path: prompt adopt-or-revert per file ──────────────────────
2296
+ log('');
2297
+ log(`pb handshake: ${tamperedBucket.length} PB-managed projection file(s) were edited downstream of the auto-gen marker.`);
2298
+ log('You can ADOPT (capture your edits as a personal-scoped draft) or REVERT (overwrite with canonical content).');
2299
+ // Batch yes-to-all / no-to-all when the user has many tampered files.
2300
+ // Threshold: 5 (arbitrary; mirrors the typical handshake projection set).
2301
+ let batchChoice = null;
2302
+ if (tamperedBucket.length >= 5) {
2303
+ const useBatch = await promptConfirm({
2304
+ message: `Apply the same choice to all ${tamperedBucket.length} tampered files?`,
2305
+ initialValue: false,
2306
+ });
2307
+ if (useBatch) {
2308
+ const choice = await promptSelect({
2309
+ message: 'Apply to all:',
2310
+ options: [
2311
+ { value: 'adopt', label: 'Adopt all — capture each as a personal-scoped draft' },
2312
+ { value: 'revert', label: 'Revert all — overwrite with canonical content' },
2313
+ ],
2314
+ });
2315
+ batchChoice = choice === 'adopt' ? 'adopt-all' : 'revert-all';
2316
+ }
2317
+ }
2318
+ for (const tamper of tamperedBucket) {
2319
+ // Reverse-map the projection path back to the canonical authoring path.
2320
+ const reverse = canonicalPathForAnySurface(tamper.relative);
2321
+ const canonicalHint = reverse
2322
+ ? `Canonical authoring path: ${reverse.canonicalPath}`
2323
+ : (() => {
2324
+ // Telemetry + fallback message per surfaces/telemetry.ts.
2325
+ reportReverseMapMissing({ surface: 'unknown', projectionPath: tamper.relative }, logErr);
2326
+ return `Canonical authoring path: ${getReverseMapFallbackMessage()}`;
2327
+ })();
2328
+ log('');
2329
+ log(`Tampered: ${tamper.relative}`);
2330
+ log(` expected: ${tamper.expectedHash}`);
2331
+ log(` actual: ${tamper.actualHash}`);
2332
+ log(` ${canonicalHint}`);
2333
+ let action;
2334
+ if (batchChoice === 'adopt-all')
2335
+ action = 'adopt';
2336
+ else if (batchChoice === 'revert-all')
2337
+ action = 'revert';
2338
+ else {
2339
+ action = await promptSelect({
2340
+ message: 'Adopt or revert?',
2341
+ options: [
2342
+ { value: 'adopt', label: 'Adopt — capture this as a personal-scoped setup_asset draft' },
2343
+ { value: 'revert', label: 'Revert — overwrite with canonical content' },
2344
+ ],
2345
+ });
2346
+ }
2347
+ if (action === 'revert') {
2348
+ // Re-project canonical content over the tampered file.
2349
+ // WP-436 S3: resolve vocab tokens before writing (all tampered files are adapters).
2350
+ if (tamper.dirs)
2351
+ mkdirSync(tamper.dirs, { recursive: true });
2352
+ assertSetupWritePath(tamper.path, perimeterManifest);
2353
+ writeFileSync(tamper.path, replaceVocabTokens(tamper.content, handshakeVocabCtx));
2354
+ revertedTamperedPaths.push(tamper.relative);
2355
+ recordProjectedHash(tamper.dbAssetEntryId);
2356
+ trackEvent('setup.tampered.reverted', { path: tamper.relative });
2357
+ }
2358
+ else {
2359
+ // Adopt: capture the tampered content as a personal-scoped draft.
2360
+ // Per DEC-953 sync rules: personal scope = push (no fork required).
2361
+ // The mutation is best-effort — if the adopt write fails, the file is
2362
+ // kept on disk untouched and a warning is logged. Adopt does NOT
2363
+ // revert; it preserves the user's edits AND records them as a draft.
2364
+ const draftName = basename(tamper.relative).replace(/\.(md|mdc)$/, '') + ' (adopted)';
2365
+ try {
2366
+ const tamperedContent = readFileSync(tamper.path, 'utf8');
2367
+ const session = readSession();
2368
+ const caller = session ? kernelCallWithSession : kernelCall;
2369
+ await caller('setup.ingestSetupAsset', {
2370
+ entryId: `SETUP-ADOPTED-${Date.now()}-${draftName.replace(/\s+/g, '-')}`,
2371
+ name: draftName,
2372
+ // WP-421 S3
2373
+ description: `Adopted from tampered projection at ${tamper.relative}.`,
2374
+ body: tamperedContent,
2375
+ assetKind: tamper.relative.includes('/skills/') ? 'skill' : 'rule',
2376
+ triggers: [],
2377
+ semanticRefs: [],
2378
+ });
2379
+ adoptedTamperedPaths.push(tamper.relative);
2380
+ trackEvent('setup.tampered.adopted', { path: tamper.relative });
2381
+ }
2382
+ catch (err) {
2383
+ logErr(`Warning: could not adopt ${tamper.relative} as draft — ${err instanceof Error ? err.message : String(err)}`);
2384
+ trackEvent('setup.tampered.adopt_failed', {
2385
+ path: tamper.relative,
2386
+ error: err instanceof Error ? err.message : String(err),
2387
+ });
2388
+ }
2389
+ }
2390
+ }
2391
+ }
2392
+ // 8a. Dormant marker + .dormant rename (WP-379 S4 + WP-426 E4) — apply mode only.
2393
+ const dormantMarkedPaths = [];
2394
+ if (writeMode && dormantDbAssetRows.length > 0) {
2395
+ const dormantState = loadAuthoringSyncState(pbDir);
2396
+ let dormantStateChanged = false;
2397
+ for (const dormantAsset of dormantDbAssetRows) {
2398
+ for (const { path: filePath, surface } of deriveDormantFilePaths(dormantAsset, cwd)) {
2399
+ // Codex P2: deriveDormantFilePaths emits every known surface path. Honor the run's
2400
+ // target set (allowedTargets = the --surfaces selection, else all manifest surfaces)
2401
+ // so a `--surfaces cursor` run never renames .claude/.codex to .dormant, and surfaces
2402
+ // outside the manifest are skipped silently (no false "could not dormant-mark" warning).
2403
+ if (!allowedTargets.has(surface))
2404
+ continue;
2405
+ // FIX 4: use relative() instead of string-replace for correct cross-platform behaviour.
2406
+ const rel = relative(cwd, filePath);
2407
+ const alreadyReactivated = dormantState.dormantReactivated?.includes(rel) ?? false;
2408
+ const previouslyRenamed = dormantState.dormantRenamed?.includes(rel) ?? false;
2409
+ try {
2410
+ assertSetupWritePath(filePath, perimeterManifest);
2411
+ // WP-426 E4: BUG 1 fix — hands-off set.
2412
+ //
2413
+ // Step 1: permanently hands-off — user already reactivated this path on a
2414
+ // prior run. Skip silently every time until they re-lower or raise in PB.
2415
+ // (Task 7 raise-cleanup must later also prune dormantReactivated for raised
2416
+ // assets — see the `dormantReactivated` comment on AuthoringSyncState.)
2417
+ if (alreadyReactivated) {
2418
+ continue; // leave file untouched; no TEN (already fired on first detection)
2419
+ }
2420
+ // Step 2: FIRST detection of manual reactivation — we previously renamed
2421
+ // this to .dormant but the user renamed it back to a live file. Push the
2422
+ // drift TEN exactly once, add to the permanent hands-off set, remove from
2423
+ // dormantRenamed, leave file untouched.
2424
+ if (previouslyRenamed && existsSync(filePath) && !existsSync(`${filePath}.dormant`)) {
2425
+ syncDriftTensToFire.push(`Dormant asset ${dormantAsset.entryId} was manually reactivated at ${rel}; left untouched. Re-lower or raise it in PB to resync.`);
2426
+ logErr(`Warning: ${rel} was manually un-dormanted; leaving it in place (drift).`);
2427
+ dormantState.dormantReactivated = [...(dormantState.dormantReactivated ?? []), rel];
2428
+ dormantState.dormantRenamed = (dormantState.dormantRenamed ?? []).filter((p) => p !== rel);
2429
+ dormantStateChanged = true;
2430
+ continue;
2431
+ }
2432
+ // Step 3: normal lowering — write dormant marker + rename to .dormant.
2433
+ // WP-426 E4 spec: every rename TARGET must also pass the perimeter guard.
2434
+ // Check the post-rename .dormant path BEFORE any FS mutation, so a guard
2435
+ // failure can't leave a half-dormant file (marker appended but not renamed).
2436
+ assertSetupWritePath(`${filePath}.dormant`, perimeterManifest);
2437
+ const markerResult = writeDormantMarkerToFile(filePath);
2438
+ if (markerResult === 'written')
2439
+ log(`Dormant marker written: ${filePath}`);
2440
+ const renameResult = renameSurfaceForDormancy(filePath);
2441
+ if (renameResult === 'renamed' || renameResult === 'replaced') {
2442
+ // dormantMarkedPaths holds post-rename .dormant paths (not the original surface paths).
2443
+ dormantMarkedPaths.push(`${filePath}.dormant`);
2444
+ if (!dormantState.dormantRenamed?.includes(rel)) {
2445
+ dormantState.dormantRenamed = [...(dormantState.dormantRenamed ?? []), rel];
2446
+ dormantStateChanged = true;
2447
+ }
2448
+ log(`Dormant rename: ${filePath} → ${filePath}.dormant`);
2449
+ }
2450
+ else if (renameResult === 'drift') {
2451
+ // Codex P1: an edited .dormant already exists alongside the live file. Preserve
2452
+ // both and flag, rather than overwriting the user's edited dormant copy.
2453
+ syncDriftTensToFire.push(`Edited dormant copy ${rel}.dormant diverges from the live surface for ${dormantAsset.entryId}; left both in place. Resolve manually.`);
2454
+ logErr(`Warning: ${rel}.dormant diverges from the live file; not replacing (possible manual edit).`);
2455
+ }
2456
+ }
2457
+ catch (err) {
2458
+ logErr(`Warning: could not dormant-mark ${filePath} — ${err instanceof Error ? err.message : String(err)}`);
2459
+ }
2460
+ }
2461
+ }
2462
+ if (dormantMarkedPaths.length > 0) {
2463
+ log('Run `pb setup observe --purge` to remove these instead of dormant-renaming.');
2464
+ }
2465
+ if (dormantStateChanged) {
2466
+ try {
2467
+ saveAuthoringSyncState(pbDir, dormantState);
2468
+ }
2469
+ catch (err) {
2470
+ logErr(`Warning: could not persist dormancy state — ${err instanceof Error ? err.message : String(err)}`);
2471
+ }
2472
+ }
2473
+ }
2474
+ // 8b. Raise-cleanup (WP-426 E4): for assets active this run, drop any orphan
2475
+ // <surface>.dormant left by a prior lowering (active surface was re-projected
2476
+ // fresh above). User-edited dormant copies are preserved + flagged. Fail-open.
2477
+ if (writeMode) {
2478
+ const raiseState = loadAuthoringSyncState(pbDir);
2479
+ let raiseStateChanged = false;
2480
+ const dormantIds = new Set(dormantDbAssetRows.map((a) => a.entryId));
2481
+ const activeRows = dbAssetRows.filter((a) => !dormantIds.has(a.entryId) &&
2482
+ (a.assetKind === 'skill' || a.assetKind === 'rule' || a.assetKind === 'hook'));
2483
+ for (const asset of activeRows) {
2484
+ // Codex P2: if this asset's body fetch failed, the write loop did NOT reproject its
2485
+ // surfaces this run (same skip the authoring loop applies), so there's no fresh surface
2486
+ // to reconcile against — skip raise-cleanup to avoid acting on stale content.
2487
+ if (bodyFetchFailedEntryIds.has(asset.entryId))
2488
+ continue;
2489
+ for (const { path: filePath, surface } of deriveDormantFilePaths(asset, cwd)) {
2490
+ // Codex P2: honor the run's target set (parity with the dormant pass) — a
2491
+ // `--surfaces cursor` run must not touch .claude/.codex .dormant files, and surfaces
2492
+ // outside the manifest are skipped silently (no false "raise-cleanup failed" warning).
2493
+ if (!allowedTargets.has(surface))
2494
+ continue;
2495
+ const rel = relative(cwd, filePath);
2496
+ try {
2497
+ assertSetupWritePath(filePath, perimeterManifest); // WP-426 E4: perimeter before any FS mutation (parity with the dormant pass)
2498
+ // E4 spec parity (review): restoreSurfaceFromDormant deletes the .dormant
2499
+ // sibling, so guard that delete TARGET too — exactly as the lowering pass
2500
+ // guards both filePath and ${filePath}.dormant.
2501
+ assertSetupWritePath(`${filePath}.dormant`, perimeterManifest);
2502
+ const r = restoreSurfaceFromDormant(filePath);
2503
+ if (r === 'restored') {
2504
+ log(`Raised: removed superseded ${filePath}.dormant`);
2505
+ }
2506
+ else if (r === 'orphan-drift') {
2507
+ syncDriftTensToFire.push(`Dormant copy ${rel}.dormant was edited while dormant for ${asset.entryId}; preserved on raise. Resolve manually.`);
2508
+ logErr(`Warning: ${rel}.dormant differs from the freshly raised projection; left in place.`);
2509
+ }
2510
+ // Prune the registry only when no .dormant sibling remains for this surface:
2511
+ // • 'restored' removed it, or
2512
+ // • it was already gone (manual .dormant→live reactivation; 'skipped', no .dormant).
2513
+ // Carry-over obligation (Phase 3) + Codex P1: the manual-reactivation case must
2514
+ // leave the hands-off set so a future lowering can re-evaluate the surface.
2515
+ // Codex P2: but if a .dormant STILL exists (surface-filtered 'skipped' with no
2516
+ // fresh live file, or a preserved 'orphan-drift'), KEEP the registry evidence —
2517
+ // otherwise a later manual .dormant→live reactivation would not be recognized as
2518
+ // previouslyRenamed and would be silently re-dormanted on the next lowering.
2519
+ if (!existsSync(`${filePath}.dormant`)) {
2520
+ if (raiseState.dormantRenamed?.includes(rel)) {
2521
+ raiseState.dormantRenamed = raiseState.dormantRenamed.filter((p) => p !== rel);
2522
+ raiseStateChanged = true;
2523
+ }
2524
+ if (raiseState.dormantReactivated?.includes(rel)) {
2525
+ raiseState.dormantReactivated = raiseState.dormantReactivated.filter((p) => p !== rel);
2526
+ raiseStateChanged = true;
2527
+ }
2528
+ }
2529
+ }
2530
+ catch (err) {
2531
+ logErr(`Warning: raise-cleanup failed for ${filePath} — ${err instanceof Error ? err.message : String(err)}`);
2532
+ }
2533
+ }
2534
+ }
2535
+ if (raiseStateChanged) {
2536
+ try {
2537
+ saveAuthoringSyncState(pbDir, raiseState);
2538
+ }
2539
+ catch { /* fail-open */ }
2540
+ }
2541
+ }
2542
+ // 8. User-owned files left untouched are NOT drift (TEN-2150).
2543
+ // A marker-less file at an adapter path is the user's own file: handshake never
2544
+ // wrote it, so there is nothing to "sync" and no draft TEN is logged. These files
2545
+ // are surfaced benignly under "Skipped:" and relayed to the connect screen via
2546
+ // report.userOwnedSkipped. (The legitimate "tampered" and authoring-sync drift
2547
+ // signals below are unaffected.)
2548
+ if (syncDriftTensToFire.length > 0) {
2549
+ const session = readSession();
2550
+ if (session) {
2551
+ for (const driftDescription of syncDriftTensToFire) {
2552
+ kernelCallWithSession('chain.createEntry', {
2553
+ collectionSlug: 'tensions',
2554
+ name: 'TEN: setup authoring sync drift — repo wins',
2555
+ status: 'draft',
2556
+ data: {
2557
+ kind: 'drift',
2558
+ description: driftDescription,
2559
+ },
2560
+ sessionId: session.sessionId,
2561
+ createdBy: `agent:${session.sessionId}`,
2562
+ }).catch(() => { });
2563
+ }
2564
+ }
2565
+ }
2566
+ // 8. Case-collision TENs (WP-379 S5b).
2567
+ // These are distinct from drift TENs: they record ambiguous filename collisions
2568
+ // where the "newest mtime wins" heuristic was applied. They always fire on a
2569
+ // detected collision (collision is a data quality issue, not a drift issue).
2570
+ if (collisionTensToFire.length > 0) {
2571
+ const session = readSession();
2572
+ if (session) {
2573
+ for (const tenDescription of collisionTensToFire) {
2574
+ kernelCallWithSession('chain.createEntry', {
2575
+ collectionSlug: 'tensions',
2576
+ name: `TEN: handshake case-collision — ambiguous filename resolved by mtime`,
2577
+ // Collision audit TENs intentionally stay draft — they need explicit human review,
2578
+ // not auto-commit, even in Open mode (mirrors smart-capture.ts recordCommitFailure).
2579
+ status: 'draft',
2580
+ data: { description: tenDescription },
2581
+ sessionId: session.sessionId,
2582
+ createdBy: `agent:${session.sessionId}`,
2583
+ }).catch(() => { });
2584
+ }
2585
+ }
2586
+ }
2587
+ // 8b. Setup receipt — record which assets were materialized (apply mode only)
2588
+ // Fail-open: receipt write is advisory, never blocks the handshake.
2589
+ if (applyMode) {
2590
+ const session = readSession();
2591
+ const caller = session ? kernelCallWithSession : kernelCall;
2592
+ try {
2593
+ const currentState = await caller('setup.getCurrentSetupState', {});
2594
+ const fromMode = currentState?.effectiveMode ?? 'observe';
2595
+ if (fromMode !== manifestStatus.mode) {
2596
+ await caller('setup.recordTransition', {
2597
+ fromMode,
2598
+ toMode: manifestStatus.mode,
2599
+ parseStatus: manifestStatus.parseStatus,
2600
+ surfaces: manifestStatus.surfaces,
2601
+ lock: manifestStatus.lock,
2602
+ });
2603
+ if (modeRank(manifestStatus.mode) < modeRank(fromMode)) {
2604
+ trackEvent('setup.transition.lowered', { fromMode, toMode: manifestStatus.mode });
2605
+ }
2606
+ }
2607
+ }
2608
+ catch (err) {
2609
+ trackEvent('setup.transition.write_failed', { error: err instanceof Error ? err.message : String(err) });
2610
+ logErr(`Warning: could not record setup transition — ${err instanceof Error ? err.message : String(err)}`);
2611
+ }
2612
+ }
2613
+ if (writeMode) {
2614
+ const session = readSession();
2615
+ const caller = session ? kernelCallWithSession : kernelCall;
2616
+ try {
2617
+ const receiptResult = await caller('setup.materializeSetup', {});
2618
+ if (receiptResult?.assetCount > 0) {
2619
+ log(`Setup receipt: ${receiptResult.assetCount} asset(s) recorded.`);
2620
+ }
2621
+ }
2622
+ catch (err) {
2623
+ trackEvent('setup.receipt.write_failed', { error: err instanceof Error ? err.message : String(err) });
2624
+ logErr(`Warning: could not write setup receipt — ${err instanceof Error ? err.message : String(err)}`);
2625
+ }
364
2626
  }
365
- // 8. Report
2627
+ // 9. Report
366
2628
  const report = {
367
2629
  filesWritten,
368
2630
  filesSkipped,
369
2631
  matchedEntries,
370
2632
  searchQueries: uniqueQueries,
371
2633
  repo,
2634
+ codexWarnings: codexWarnings.length > 0 ? codexWarnings : undefined,
2635
+ chainRulesStats: chainRulesStats ?? undefined,
2636
+ chainGaps: chainGaps.length > 0 ? chainGaps : undefined,
2637
+ adoptedCount: adoptedRulesCount,
2638
+ rejectedCount: rejectedRulesCount,
2639
+ personalRuleCount: personalRules.length > 0 ? personalRules.length : undefined,
2640
+ personalSkillCount: personalSkills.length > 0 ? personalSkills.length : undefined,
2641
+ registrySource,
2642
+ registryStale,
2643
+ preview: preview ? true : undefined,
2644
+ previewPlan: preview && previewPlan.length > 0 ? previewPlan : undefined,
2645
+ userOwnedSkipped: userOwnedSkipped.length > 0 ? userOwnedSkipped : undefined,
2646
+ // WP-421 S3: three-bucket drift report (doneWhen #17). PB-managed-clean is
2647
+ // the count of files whose marker + hash matched. Tampered files were
2648
+ // resolved (adopted/reverted) above and are reported separately.
2649
+ managedCleanCount: cleanBucketPaths.length > 0 ? cleanBucketPaths.length : undefined,
2650
+ adoptedTamperedPaths: adoptedTamperedPaths.length > 0 ? adoptedTamperedPaths : undefined,
2651
+ revertedTamperedPaths: revertedTamperedPaths.length > 0 ? revertedTamperedPaths : undefined,
372
2652
  };
373
2653
  if (!quiet) {
374
2654
  process.stdout.write('\n');
375
2655
  process.stdout.write(formatHandshakeReport(report) + '\n');
376
2656
  }
2657
+ // Return the report so non-UI callers (e.g. prepareConnectContext) can surface
2658
+ // skipped/user-owned files without re-deriving the skip logic (TEN-2107).
2659
+ return report;
377
2660
  }
2661
+ // WP-426 E3/E4: exported test-only surface (not part of the public CLI API).
2662
+ export const __test = { setupAuthoringPath, renameSurfaceForDormancy, restoreSurfaceFromDormant, loadAuthoringSyncState, MARKER };
378
2663
  //# sourceMappingURL=handshake.js.map