gentle-pi 4.7.0 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (365) hide show
  1. package/README.md +55 -44
  2. package/assets/agents/gentle-ai-explore.md +3 -3
  3. package/assets/agents/gentle-ai-verify.md +20 -6
  4. package/assets/agents/gentle-ai-worker.md +6 -6
  5. package/assets/agents/jd-judge-a.md +1 -3
  6. package/assets/agents/jd-judge-b.md +1 -3
  7. package/assets/agents/review-readability.md +1 -5
  8. package/assets/agents/review-reliability.md +1 -5
  9. package/assets/agents/review-resilience.md +1 -5
  10. package/assets/agents/review-risk.md +1 -5
  11. package/assets/design-canvas/canvas-api.js +45 -0
  12. package/assets/design-canvas/canvas-boards.js +456 -0
  13. package/assets/design-canvas/canvas-boot.js +217 -0
  14. package/assets/design-canvas/canvas-checks.js +491 -0
  15. package/assets/design-canvas/canvas-comments.js +315 -0
  16. package/assets/design-canvas/canvas-compare.js +159 -0
  17. package/assets/design-canvas/canvas-events.js +75 -0
  18. package/assets/design-canvas/canvas-export.js +393 -0
  19. package/assets/design-canvas/canvas-focus.js +203 -0
  20. package/assets/design-canvas/canvas-handoffs.js +150 -0
  21. package/assets/design-canvas/canvas-i18n-es.js +392 -0
  22. package/assets/design-canvas/canvas-i18n.js +108 -0
  23. package/assets/design-canvas/canvas-layout.js +526 -0
  24. package/assets/design-canvas/canvas-menu.js +213 -0
  25. package/assets/design-canvas/canvas-messages.js +86 -0
  26. package/assets/design-canvas/canvas-minimap.js +163 -0
  27. package/assets/design-canvas/canvas-parts.js +401 -0
  28. package/assets/design-canvas/canvas-popover.js +234 -0
  29. package/assets/design-canvas/canvas-rail.js +348 -0
  30. package/assets/design-canvas/canvas-sizes.js +524 -0
  31. package/assets/design-canvas/canvas-store.js +164 -0
  32. package/assets/design-canvas/canvas-tokens.js +674 -0
  33. package/assets/design-canvas/canvas-ui.js +24 -0
  34. package/assets/design-canvas/canvas-view.js +184 -0
  35. package/assets/design-canvas/canvas.css +746 -15
  36. package/assets/design-canvas/canvas.js +2 -1506
  37. package/assets/design-canvas/index.html +117 -36
  38. package/assets/design-canvas/inspector.js +546 -16
  39. package/assets/install-wizard/wizard.js +5 -1
  40. package/assets/migrations/agent-body-history.json +24 -0
  41. package/assets/orchestrator-delegation-reference.md +8 -14
  42. package/assets/orchestrator-delegation.md +4 -4
  43. package/assets/orchestrator-full-delegation-card.md +4 -5
  44. package/assets/orchestrator-full-delegation.md +8 -8
  45. package/assets/orchestrator-memory.md +2 -2
  46. package/assets/orchestrator-prompts.md +1 -1
  47. package/assets/orchestrator-quota-recovery.md +5 -0
  48. package/assets/orchestrator-skills.md +13 -12
  49. package/assets/orchestrator-tracking.md +10 -14
  50. package/assets/orchestrator-verification.md +10 -8
  51. package/assets/orchestrator-writer.md +4 -4
  52. package/assets/orchestrator.md +18 -22
  53. package/bin/gentle-shell.mjs +128 -9
  54. package/contracts/review-provider-contract-mirror/provider-contract.lock.json +8 -9
  55. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/manifest.json +3 -3
  56. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/orchestration/pi.md +1 -0
  57. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/routing/pi.md +6 -6
  58. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/generated/provider-capabilities.baseline.json +3 -3
  59. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/generated/provider-roles.baseline.json +1 -1
  60. package/docs/assets/brand/sponsor-banner.svg +60 -0
  61. package/docs/bundled-install.md +14 -6
  62. package/docs/delegated-verification.md +18 -2
  63. package/docs/desktop-rpc.md +1253 -0
  64. package/docs/gentle-agents-activity.md +26 -0
  65. package/docs/gentle-shell.md +39 -16
  66. package/docs/install-wizard.md +30 -21
  67. package/docs/odd-preparation-continuity.md +24 -0
  68. package/docs/permission-modes.md +9 -1
  69. package/docs/prompt-budget.md +12 -0
  70. package/docs/rdd-odd-friction-triage-2026-11-07.md +57 -0
  71. package/docs/readme-reference.md +76 -24
  72. package/docs/review-coordinator.md +29 -9
  73. package/docs/review-delivery-preflight.md +22 -0
  74. package/docs/work-continuity.md +11 -1
  75. package/extensions/ask-user-question.ts +2 -2
  76. package/extensions/child-context.ts +21 -7
  77. package/extensions/gentle-agents.ts +234 -33
  78. package/extensions/gentle-ai.ts +576 -135
  79. package/extensions/gentle-design.ts +69 -3
  80. package/extensions/gentle-desktop-rpc.ts +143 -0
  81. package/extensions/gentle-guide.ts +3 -0
  82. package/extensions/gentle-shell.ts +105 -52
  83. package/extensions/gentle-todo.ts +48 -25
  84. package/extensions/skill-registry.ts +248 -223
  85. package/lib/agent-assets.ts +30 -6
  86. package/lib/agent-tool-overlay.ts +117 -0
  87. package/lib/agents-config.ts +47 -6
  88. package/lib/agents-message-delivery.ts +17 -0
  89. package/lib/agents-messaging.ts +8 -2
  90. package/lib/agents-protocol.ts +15 -0
  91. package/lib/agents-report-cap.ts +115 -0
  92. package/lib/agents-runner.ts +91 -6
  93. package/lib/agents-session-transport.ts +17 -1
  94. package/lib/background-jobs-tools.ts +9 -4
  95. package/lib/bounded-writer-admission.ts +184 -31
  96. package/lib/child-context-files.ts +21 -6
  97. package/lib/codemode-renderer.ts +1 -0
  98. package/lib/delivery-conflict-markers.ts +349 -0
  99. package/lib/design-canvas-assets.ts +36 -0
  100. package/lib/design-canvas-server.ts +241 -23
  101. package/lib/design-comments.ts +94 -4
  102. package/lib/design-handoffs.ts +2 -1
  103. package/lib/design-layout.ts +125 -0
  104. package/lib/design-parts.ts +281 -0
  105. package/lib/design-system-tokens.ts +111 -0
  106. package/lib/desktop-agents-service.ts +294 -0
  107. package/lib/desktop-design-service.ts +233 -0
  108. package/lib/desktop-jobs-service.ts +263 -0
  109. package/lib/desktop-rpc-agents.ts +294 -0
  110. package/lib/desktop-rpc-config.ts +731 -0
  111. package/lib/desktop-rpc-design.ts +138 -0
  112. package/lib/desktop-rpc-jobs.ts +181 -0
  113. package/lib/desktop-rpc-permissions.ts +177 -0
  114. package/lib/desktop-rpc-profiles.ts +196 -0
  115. package/lib/desktop-rpc-usage.ts +229 -0
  116. package/lib/desktop-rpc.ts +225 -0
  117. package/lib/desktop-usage-service.ts +310 -0
  118. package/lib/destructive-command-guard.ts +188 -13
  119. package/lib/gentle-ai-renderer.ts +13 -1
  120. package/lib/gentle-design.ts +201 -14
  121. package/lib/gentle-shell-bundled.ts +100 -9
  122. package/lib/hidden-tools.ts +35 -0
  123. package/lib/inprocess-reviewer.ts +96 -12
  124. package/lib/model-fallback-policy.ts +9 -0
  125. package/lib/model-routing-authority.ts +9 -0
  126. package/lib/nan-provider.ts +42 -28
  127. package/lib/native-review-cli.ts +79 -4
  128. package/lib/orchestrator-discovery.ts +39 -2
  129. package/lib/reply-language-anchor.ts +27 -2
  130. package/lib/request-context-placement.ts +53 -0
  131. package/lib/review-candidate-view.ts +11 -1
  132. package/lib/review-continuation-registry.ts +17 -0
  133. package/lib/review-coordinator.ts +252 -8
  134. package/lib/review-delivery-preflight.ts +85 -0
  135. package/lib/review-host-relay.ts +5 -1
  136. package/lib/review-integration-v2.ts +56 -3
  137. package/lib/reviewer-stream.ts +87 -0
  138. package/lib/shell-prompt.ts +16 -3
  139. package/lib/shell-usage.ts +10 -0
  140. package/lib/vim-editor-adapter.ts +9 -2
  141. package/lib/writer-batch-admission.ts +55 -0
  142. package/lib/yolo-session-policy.ts +6 -1
  143. package/package.json +2 -2
  144. package/prompts/skill-creation.md +1 -10
  145. package/runtime/design-canvas-assets.mjs +37 -0
  146. package/runtime/gentle-shell-bundled.mjs +100 -9
  147. package/runtime/native-review-cli.mjs +79 -4
  148. package/runtime/review-integration-v2.mjs +56 -3
  149. package/scripts/bootstrap.cmd +2 -2
  150. package/scripts/bootstrap.sh +41 -4
  151. package/scripts/build-full-delegation-card.mjs +4 -0
  152. package/scripts/build-runtime-modules.mjs +1 -0
  153. package/scripts/gentle-ai-installer.mjs +10 -10
  154. package/scripts/gentle-ai-proxy.mjs +1 -1
  155. package/scripts/installer-downloads.mjs +34 -8
  156. package/scripts/installer-preflight.mjs +28 -17
  157. package/scripts/installer-probes.mjs +25 -5
  158. package/scripts/installer-server.mjs +38 -9
  159. package/scripts/installer-windows.mjs +2 -2
  160. package/scripts/pi-update.mjs +166 -27
  161. package/scripts/prepare-verifier.mjs +107 -0
  162. package/scripts/update-agent-body-history.mjs +55 -8
  163. package/scripts/verify-package-files.mjs +40 -19
  164. package/skills/branch-pr/SKILL.md +16 -16
  165. package/skills/comment-writer/SKILL.md +1 -1
  166. package/skills/design/SKILL.md +6 -6
  167. package/skills/gentle-ai/SKILL.md +5 -5
  168. package/skills/judgment-day/SKILL.md +2 -2
  169. package/skills/judgment-day/references/prompts-and-formats.md +1 -1
  170. package/skills/rdd-defect-workflow/SKILL.md +6 -6
  171. package/skills/skill-improver/SKILL.md +2 -2
  172. package/skills/skill-registry/SKILL.md +11 -13
  173. package/skills/tui-design/SKILL.md +1 -1
  174. package/skills/work-unit-commits/SKILL.md +5 -5
  175. package/tests/agent-prompt-diet-contract.test.ts +101 -0
  176. package/tests/agent-tool-overlay-acceptance.test.ts +158 -0
  177. package/tests/agent-tool-overlay.test.ts +89 -0
  178. package/tests/agents-config.test.ts +10 -1
  179. package/tests/agents-message-delivery.test.ts +36 -0
  180. package/tests/agents-queries.test.ts +144 -4
  181. package/tests/agents-report-cap.test.ts +126 -0
  182. package/tests/agents-runner.test.ts +37 -1
  183. package/tests/agents-session-transport.test.ts +34 -0
  184. package/tests/always-on-prompt-verdicts-contract.test.ts +188 -0
  185. package/tests/append-system-prompt-route.test.ts +10 -2
  186. package/tests/approved-text-leftovers-contract.test.ts +136 -0
  187. package/tests/artifact-language.test.ts +1 -1
  188. package/tests/ask-user-question.test.ts +2 -1
  189. package/tests/audit-leftovers-contract.test.ts +51 -0
  190. package/tests/bounded-stop-contract.test.ts +9 -1
  191. package/tests/branch-pr-skill.test.ts +10 -1
  192. package/tests/bundled-install.test.ts +1 -1
  193. package/tests/child-context-files.test.ts +64 -8
  194. package/tests/child-skills-catalog.test.ts +56 -0
  195. package/tests/codemode-rendering.test.ts +4 -1
  196. package/tests/delegate-for-reason-contract.test.ts +30 -8
  197. package/tests/delivery-conflict-markers.test.ts +348 -0
  198. package/tests/design-canvas-all-sizes.test.ts +631 -0
  199. package/tests/design-canvas-allowlist.test.ts +32 -0
  200. package/tests/design-canvas-assets.test.ts +11 -878
  201. package/tests/design-canvas-boards.test.ts +77 -0
  202. package/tests/design-canvas-checks.test.ts +655 -0
  203. package/tests/design-canvas-compare.test.ts +79 -0
  204. package/tests/design-canvas-events.test.ts +59 -0
  205. package/tests/design-canvas-export.test.ts +1168 -0
  206. package/tests/design-canvas-focus.test.ts +113 -0
  207. package/tests/design-canvas-handoffs.test.ts +59 -0
  208. package/tests/design-canvas-i18n-review.test.ts +513 -0
  209. package/tests/design-canvas-i18n-views.test.ts +259 -0
  210. package/tests/design-canvas-i18n.test.ts +526 -0
  211. package/tests/design-canvas-inspector.test.ts +937 -0
  212. package/tests/design-canvas-layout.test.ts +1222 -0
  213. package/tests/design-canvas-minimap.test.ts +413 -0
  214. package/tests/design-canvas-modules.test.ts +90 -0
  215. package/tests/design-canvas-parts.test.ts +721 -0
  216. package/tests/design-canvas-rail.test.ts +799 -0
  217. package/tests/design-canvas-server.test.ts +855 -17
  218. package/tests/design-canvas-sizes.test.ts +548 -0
  219. package/tests/design-canvas-store.test.ts +180 -0
  220. package/tests/design-canvas-tokens.test.ts +965 -0
  221. package/tests/design-canvas-view.test.ts +299 -0
  222. package/tests/design-comments.test.ts +201 -1
  223. package/tests/design-handoffs.test.ts +20 -0
  224. package/tests/design-layout.test.ts +100 -0
  225. package/tests/design-parts.test.ts +260 -0
  226. package/tests/design-system-tokens.test.ts +215 -0
  227. package/tests/desktop-rpc-agents.test.ts +893 -0
  228. package/tests/desktop-rpc-config.test.ts +1452 -0
  229. package/tests/desktop-rpc-design.test.ts +662 -0
  230. package/tests/desktop-rpc-jobs.test.ts +796 -0
  231. package/tests/desktop-rpc-permissions.test.ts +311 -0
  232. package/tests/desktop-rpc-profiles.test.ts +140 -0
  233. package/tests/desktop-rpc-safety.test.ts +119 -0
  234. package/tests/desktop-rpc-usage.test.ts +697 -0
  235. package/tests/desktop-rpc.test.ts +252 -0
  236. package/tests/devbinary/pi-host-relay.devtest.ts +149 -80
  237. package/tests/devbinary/review-session-consent.devtest.ts +84 -0
  238. package/tests/engram-safety.test.ts +111 -0
  239. package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.captured.json +92 -0
  240. package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.provenance.md +3 -0
  241. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +20 -29
  242. package/tests/fixtures/refusal-identity.probe.mjs +139 -0
  243. package/tests/full-delegation-closure.test.ts +29 -0
  244. package/tests/gentle-agents.test.ts +329 -4
  245. package/tests/gentle-ai-binary.test.ts +1 -1
  246. package/tests/gentle-ai-child-guards.test.ts +1 -0
  247. package/tests/gentle-ai-installer.test.ts +52 -51
  248. package/tests/gentle-ai-renderer.test.ts +36 -2
  249. package/tests/gentle-ai.test.ts +121 -6
  250. package/tests/gentle-design.test.ts +365 -1
  251. package/tests/gentle-shell-bundled.test.ts +91 -5
  252. package/tests/gentle-shell-launcher.test.ts +1 -1
  253. package/tests/gentle-shell.test.ts +118 -87
  254. package/tests/gentle-todo.test.ts +32 -9
  255. package/tests/hidden-tools.test.ts +188 -0
  256. package/tests/independent-recovery-delivery.test.ts +19 -5
  257. package/tests/inprocess-reviewer.test.ts +73 -0
  258. package/tests/install-wizard.test.ts +27 -1
  259. package/tests/installer-downloads.test.ts +30 -1
  260. package/tests/installer-posix-bootstrap.test.ts +114 -13
  261. package/tests/installer-preflight.test.ts +49 -1
  262. package/tests/installer-probes.test.ts +146 -0
  263. package/tests/installer-server.test.ts +203 -4
  264. package/tests/installer-windows-bootstrap.test.ts +19 -1
  265. package/tests/judgment-day-severity-admission.test.ts +46 -0
  266. package/tests/lazy-module-contradictions-contract.test.ts +158 -0
  267. package/tests/maintainer/desktop-rpc.maintest.ts +632 -0
  268. package/tests/maintainer/pi-update-source.maintest.ts +48 -18
  269. package/tests/model-fallback-policy.test.ts +26 -7
  270. package/tests/nan-provider-runtime.test.ts +17 -3
  271. package/tests/nan-provider.test.ts +111 -56
  272. package/tests/native-review-capability-contract.test.ts +11 -1
  273. package/tests/native-review-cli-nonblocking-findings.test.ts +165 -0
  274. package/tests/native-review-parity.test.ts +24 -5
  275. package/tests/native-review-refusal-identity.test.ts +25 -0
  276. package/tests/no-self-pause-contract.test.ts +11 -3
  277. package/tests/odd-integration.test.ts +11 -3
  278. package/tests/odd-routing-contract.test.ts +80 -28
  279. package/tests/orchestrator-budget.test.ts +30 -5
  280. package/tests/orchestrator-consultation-sdk.test.ts +32 -6
  281. package/tests/orchestrator-delegation-mode.test.ts +2 -1
  282. package/tests/orchestrator-discovery.test.ts +28 -0
  283. package/tests/orchestrator-prompt-budget.test.ts +11 -2
  284. package/tests/orchestrator-prompt-diet-contract.test.ts +221 -0
  285. package/tests/orchestrator-rdd-ownership.test.ts +2 -1
  286. package/tests/orchestrator-work-search.test.ts +4 -2
  287. package/tests/package-files.test.ts +25 -1
  288. package/tests/package-manifest.test.ts +11 -10
  289. package/tests/parallel-reason-contract.test.ts +6 -3
  290. package/tests/permission-allowlist.test.ts +200 -30
  291. package/tests/persona-neutral-voseo.test.ts +4 -4
  292. package/tests/persona-reply-language.test.ts +1 -1
  293. package/tests/persona-single-channel.test.ts +13 -5
  294. package/tests/pi-update-launcher.test.ts +17 -7
  295. package/tests/pi-update-source.test.ts +113 -6
  296. package/tests/pi-update.test.ts +294 -19
  297. package/tests/pnpm-workspace-policy.test.ts +47 -0
  298. package/tests/primary-context-files.test.ts +233 -0
  299. package/tests/primary-context-three-files.test.ts +174 -0
  300. package/tests/provider-defect-handoff.test.ts +9 -2
  301. package/tests/rdd-aware-verification-contract.test.ts +1 -1
  302. package/tests/rdd-status-line.test.ts +94 -1
  303. package/tests/reply-language-anchor-placement.test.ts +184 -0
  304. package/tests/reply-language-anchor.test.ts +17 -1
  305. package/tests/request-context-append-only.test.ts +218 -0
  306. package/tests/request-context-placement.test.ts +148 -0
  307. package/tests/review-agent-end-preflight.test.ts +79 -1
  308. package/tests/review-candidate-view.test.ts +65 -0
  309. package/tests/review-continuation-registry.test.ts +31 -0
  310. package/tests/review-contract-prompt.test.ts +1 -1
  311. package/tests/review-controller.test.ts +2 -1
  312. package/tests/review-coordinator-correction-gate.test.ts +105 -0
  313. package/tests/review-coordinator-findings.test.ts +206 -0
  314. package/tests/review-coordinator-nonblocking-scope.test.ts +169 -0
  315. package/tests/review-coordinator.test.ts +271 -4
  316. package/tests/review-delivery-preflight.test.ts +462 -0
  317. package/tests/review-due-compaction.test.ts +31 -0
  318. package/tests/review-due-public-boundary.test.ts +26 -0
  319. package/tests/review-integration-nonblocking-findings.test.ts +108 -0
  320. package/tests/review-json-arguments.test.ts +41 -2
  321. package/tests/review-ledger-contract.test.ts +19 -40
  322. package/tests/review-loadout-rdd-off-sdk.test.ts +30 -1
  323. package/tests/review-one-call-findings.test.ts +131 -0
  324. package/tests/review-one-call-followups.test.ts +308 -0
  325. package/tests/review-one-call-reviewer-requests.test.ts +207 -0
  326. package/tests/review-one-call.test.ts +452 -0
  327. package/tests/review-relay-transport-agent.test.ts +28 -1
  328. package/tests/review-reviewer-evidence.test.ts +41 -1
  329. package/tests/review-risk-assessment.test.ts +52 -5
  330. package/tests/review-run-statement-guidance-independent.test.ts +54 -0
  331. package/tests/review-session-standing-permission-controller.test.ts +32 -2
  332. package/tests/review-tool-prose-budget.test.ts +1 -0
  333. package/tests/reviewer-stream.test.ts +149 -0
  334. package/tests/session-profile-extension.test.ts +2 -2
  335. package/tests/shell-prompt.test.ts +17 -0
  336. package/tests/shell-usage.test.ts +59 -10
  337. package/tests/skill-contradictions-contract.test.ts +122 -0
  338. package/tests/skill-registry-watcher.test.ts +216 -2
  339. package/tests/skill-registry.test.ts +929 -306
  340. package/tests/support/design-canvas-dom.ts +369 -0
  341. package/tests/support/review-coordinator-runtime.ts +212 -17
  342. package/tests/task-size-routing-contract.test.ts +42 -11
  343. package/tests/test-strength-contract.test.ts +2 -1
  344. package/tests/todo-request-append-only.test.ts +214 -0
  345. package/tests/tool-batching-contract.test.ts +3 -1
  346. package/tests/update-agent-body-history.test.ts +138 -0
  347. package/tests/verification-tiers-contract.test.ts +229 -0
  348. package/tests/verifier-preparation.test.ts +229 -0
  349. package/tests/verify-agent-contract.test.ts +20 -2
  350. package/tests/verify-first-launch-contract.test.ts +87 -11
  351. package/tests/vim-editor-adapter.test.ts +2 -2
  352. package/tests/work-continuity-contract.test.ts +54 -11
  353. package/tests/writer-admission-messages.test.ts +232 -0
  354. package/tests/writer-batch-admission.test.ts +66 -0
  355. package/tests/writer-edit-surface-scope.test.ts +52 -20
  356. package/tests/writer-feature-document-admission.test.ts +184 -0
  357. package/tests/yolo-mode.test.ts +39 -0
  358. package/skills/_shared/review-ledger-contract.md +0 -106
  359. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/README.md +0 -0
  360. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/lens.schema.json +0 -0
  361. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/refuter.schema.json +0 -0
  362. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/targeted-validator.schema.json +0 -0
  363. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/lens.json +0 -0
  364. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/refuter.json +0 -0
  365. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/targeted-validator.json +0 -0
@@ -0,0 +1,731 @@
1
+ // Gentle Desktop config access (`get_config`) and the bounded write slice
2
+ // (`set_config`).
3
+ //
4
+ // Desktop names a store, never a path: this module maps each store identifier to
5
+ // the existing owner reader and its current precedence, then reports the
6
+ // normalized content plus an opaque revision. Writes exist only for the three
7
+ // stores whose owners already accept validated, atomic writes — `profiles`,
8
+ // `profile_fallbacks`, and `pins` — and they go through those same owner writers,
9
+ // so no invariant is re-implemented here. A pin layer is set or cleared through
10
+ // the owner's `writeProfilePinSync` / `clearProfilePinSync`, one explicitly named
11
+ // layer per request. `models`, `subagents`, and `managed_assets` are derived or
12
+ // installer-owned and answer a typed `read_only` error to every write. There is no
13
+ // second store, no cached copy, and no filesystem watcher.
14
+ //
15
+ // The write revision is the digest of the exact single file the owner rewrites,
16
+ // which is why `pins` reports one revision per layer instead of the merged read
17
+ // revision. `expectedRevision` is re-checked against a fresh read immediately
18
+ // before the owner write, in the same synchronous step, so an interleaved Desktop
19
+ // request in this process cannot pass the check with a stale token. That is a
20
+ // per-process serialization, not a cross-process transaction: there is no lock,
21
+ // so a second `pi` process can still write between the check and the rename.
22
+
23
+ import { createHash } from "node:crypto";
24
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
25
+ import { managedAssetsManifestPath, readManagedAssetsManifestResult, type ManagedAssetsManifest } from "./agent-assets.ts";
26
+ import { gentlePiConfigHome, resolveGentlePiAgentHome } from "./agent-home.ts";
27
+ import {
28
+ isValidProfileName,
29
+ normalizeProfilesFile,
30
+ parseProfilesFileText,
31
+ profilesFilePath,
32
+ readProfilesFileResult,
33
+ serializeProfilesFile,
34
+ writeProfilesFileSync,
35
+ type ProfilesParseDrops,
36
+ } from "./agent-profiles.ts";
37
+ import { evaluateProfilePin, clearProfilePinSync, readProfilePinStatus, writeProfilePinSync } from "./agent-profile-pin.ts";
38
+ import { parseAgentsConfig, readSubagentsFileResult, subagentsConfigPaths } from "./agents-config.ts";
39
+ import type { DesktopRpcOutcome, DesktopRpcState } from "./desktop-rpc.ts";
40
+ import { isDesktopProfileApplyRunning } from "./desktop-rpc-profiles.ts";
41
+ import { fallbacksFilePath, normalizeFallbacksFile, readFallbacksFile, writeFallbacksFile } from "./model-fallback-store.ts";
42
+ import { modelConfigPaths, normalizeModelConfig, readModelConfigFile, readSavedModelConfig } from "./model-routing-authority.ts";
43
+ import type { WorktreeResolver } from "./session-worktree-registry.ts";
44
+
45
+ export const DESKTOP_CONFIG_METHODS = ["get_config", "set_config"] as const;
46
+ /** Advertised only because this module wires the writer that publishes it. */
47
+ export const DESKTOP_CONFIG_EVENTS = ["config_changed"] as const;
48
+ export const DESKTOP_CONFIG_EVENT = "config_changed";
49
+
50
+ /** Every store this channel can read, in the order `get_snapshot` projects them. */
51
+ export const DESKTOP_CONFIG_STORES = [
52
+ "profiles",
53
+ "models",
54
+ "profile_fallbacks",
55
+ "subagents",
56
+ "pins",
57
+ "managed_assets",
58
+ ] as const;
59
+
60
+ export type DesktopConfigStore = (typeof DESKTOP_CONFIG_STORES)[number];
61
+
62
+ /** A layer status is the owner reader's own answer, never an inferred one. */
63
+ export type DesktopConfigStatus = "ok" | "missing" | "invalid";
64
+ export type DesktopConfigLayerSource = "global" | "project" | "local" | "repo";
65
+ export type DesktopConfigScope = "global" | "global+project" | "local+repo";
66
+
67
+ export interface DesktopConfigLayer {
68
+ source: DesktopConfigLayerSource;
69
+ status: DesktopConfigStatus;
70
+ }
71
+
72
+ export interface DesktopConfigData {
73
+ store: DesktopConfigStore;
74
+ scope: DesktopConfigScope;
75
+ /** See `storeReadOnly`: only the persistent family is written by this slice. */
76
+ readOnly: boolean;
77
+ status: DesktopConfigStatus;
78
+ /** Opaque digest of the canonical normalized content; stable across equivalent reads. */
79
+ revision: string;
80
+ /**
81
+ * Normalized owner content. Absent when the owner produced none: a missing store
82
+ * or one whose layers are all unreadable. `pins` is the deliberate exception —
83
+ * it always reports what its layers amount to, because a broken or stale pin is
84
+ * exactly the state an operator needs to see.
85
+ */
86
+ value?: unknown;
87
+ layers: DesktopConfigLayer[];
88
+ /**
89
+ * One entry per file this store's owner rewrites, each with its own write
90
+ * revision. Present only for stores this slice may write.
91
+ */
92
+ writeTargets?: DesktopConfigWriteTargetInfo[];
93
+ }
94
+
95
+ /**
96
+ * A write target is one file, not one store: `profiles` and `profile_fallbacks`
97
+ * each own a single global file, while `pins` owns two independent layers that a
98
+ * request must select explicitly.
99
+ */
100
+ export type DesktopConfigWriteTarget = "global" | "local" | "repo";
101
+
102
+ export interface DesktopConfigWriteTargetInfo {
103
+ target: DesktopConfigWriteTarget;
104
+ status: DesktopConfigStatus;
105
+ /** Digest of the target's current content, not of a merged multi-layer read. */
106
+ writeRevision: string;
107
+ }
108
+
109
+ const INVALID_PARAMS = { code: "invalid_request", message: "Invalid Desktop config parameters" } as const;
110
+ const UNKNOWN_STORE = { code: "unknown_store", message: "Unknown Desktop config store" } as const;
111
+ const UNAVAILABLE = { code: "config_unavailable", message: "Config stores unavailable for this session" } as const;
112
+ const READ_ONLY = { code: "read_only", message: "Config store is read-only over Desktop RPC" } as const;
113
+ const APPLY_BUSY = { code: "profile_apply_busy", message: "A profile apply is in progress" } as const;
114
+ const INVALID_DATA = { code: "invalid_data", message: "Invalid config data for this store" } as const;
115
+ const UNKNOWN_PIN_PROFILE = { code: "invalid_data", message: "Pin target profile is not defined by the profiles store" } as const;
116
+ const MISSING_REVISION = { code: "revision_conflict", message: "expectedRevision is required before writing" } as const;
117
+ const STALE_REVISION = { code: "revision_conflict", message: "Config changed since expectedRevision was read" } as const;
118
+ const WRITE_FAILED = { code: "write_failed", message: "Config store write failed" } as const;
119
+
120
+ /** Authoritative stores this slice may write; every other store is read-only. */
121
+ const AUTHORITATIVE_STORES: ReadonlySet<DesktopConfigStore> = new Set(["profiles", "profile_fallbacks", "pins"]);
122
+
123
+ export function storeReadOnly(store: DesktopConfigStore): boolean {
124
+ return !AUTHORITATIVE_STORES.has(store);
125
+ }
126
+
127
+ export function isDesktopConfigStore(value: unknown): value is DesktopConfigStore {
128
+ return typeof value === "string" && (DESKTOP_CONFIG_STORES as readonly string[]).includes(value);
129
+ }
130
+
131
+ /** Paths are resolved by the owner helpers so a store spelling cannot move. */
132
+ export interface DesktopConfigRoots {
133
+ cwd: string;
134
+ configHome: string;
135
+ agentHome: string;
136
+ resolveWorktree?: WorktreeResolver;
137
+ }
138
+
139
+ export interface DesktopConfigOverrides {
140
+ configHome?: string;
141
+ agentHome?: string;
142
+ resolveWorktree?: WorktreeResolver;
143
+ }
144
+
145
+ /**
146
+ * The project and pin layers depend on the live session cwd, so a host without
147
+ * one has no truthful roots to report: the bridge answers unavailable instead of
148
+ * inventing a directory or exposing the process cwd.
149
+ */
150
+ function withRoots(context: ExtensionContext, overrides: DesktopConfigOverrides): DesktopConfigRoots | undefined {
151
+ if (typeof context.cwd !== "string" || context.cwd.length === 0) return undefined;
152
+ return {
153
+ cwd: context.cwd,
154
+ configHome: overrides.configHome ?? gentlePiConfigHome(),
155
+ agentHome: overrides.agentHome ?? resolveGentlePiAgentHome(),
156
+ ...(overrides.resolveWorktree === undefined ? {} : { resolveWorktree: overrides.resolveWorktree }),
157
+ };
158
+ }
159
+
160
+ /**
161
+ * Canonical JSON: sorted keys, `undefined` members dropped exactly like
162
+ * `JSON.stringify` would drop them on the wire, so the digest describes the
163
+ * content the client actually receives and formatting never moves it.
164
+ */
165
+ function canonicalJson(value: unknown): string {
166
+ if (value === undefined) return "null";
167
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
168
+ if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item)).join(",")}]`;
169
+ const entries = Object.entries(value as Record<string, unknown>)
170
+ .filter(([, entry]) => entry !== undefined)
171
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
172
+ .map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`);
173
+ return `{${entries.join(",")}}`;
174
+ }
175
+
176
+ /** Read-time content digest. It orders nothing across processes and is not a transaction token. */
177
+ export function configRevision(store: DesktopConfigStore, status: DesktopConfigStatus, value: unknown): string {
178
+ const payload = value === undefined ? { store, status } : { store, status, value };
179
+ return `sha256:${createHash("sha256").update(canonicalJson(payload)).digest("hex").slice(0, 32)}`;
180
+ }
181
+
182
+ /**
183
+ * Write-time digest of exactly one target file. It is deliberately a different
184
+ * token from the read `revision` (the payload names the target), because the value
185
+ * a write replaces is one file while a multi-layer read describes a merge: a pin
186
+ * layer's write revision must not be confusable with the merged `pins` revision.
187
+ */
188
+ export function configWriteRevision(
189
+ store: DesktopConfigStore,
190
+ target: DesktopConfigWriteTarget,
191
+ status: DesktopConfigStatus,
192
+ value: unknown,
193
+ ): string {
194
+ const payload = value === undefined ? { store, target, status } : { store, target, status, value };
195
+ return `sha256:${createHash("sha256").update(canonicalJson(payload)).digest("hex").slice(0, 32)}`;
196
+ }
197
+
198
+ /**
199
+ * The projection is the JSON a client receives, so absent owner fields are
200
+ * dropped here instead of surviving as `undefined` members that no consumer of
201
+ * the wire format can ever see.
202
+ */
203
+ function wireValue<T>(value: T): T {
204
+ if (Array.isArray(value)) return value.map((entry) => wireValue(entry)) as unknown as T;
205
+ if (value === null || typeof value !== "object") return value;
206
+ const projected: Record<string, unknown> = {};
207
+ for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {
208
+ if (entry === undefined) continue;
209
+ projected[key] = wireValue(entry);
210
+ }
211
+ return projected as T;
212
+ }
213
+
214
+ interface StoreRead {
215
+ status: DesktopConfigStatus;
216
+ value?: unknown;
217
+ layers: DesktopConfigLayer[];
218
+ }
219
+
220
+ function layer(source: DesktopConfigLayerSource, status: "missing" | "invalid" | "valid"): DesktopConfigLayer {
221
+ return { source, status: status === "valid" ? "ok" : status };
222
+ }
223
+
224
+ type LayerReadStatus = "missing" | "invalid" | "valid";
225
+
226
+ /**
227
+ * Store status for a store the owner assembles from layers it reads independently.
228
+ * `missing` only when every layer is absent, `invalid` only when no layer produced
229
+ * content, and `ok` as soon as one layer is usable — the same merge the runtime
230
+ * performs, with the broken layers still named in `layers`.
231
+ */
232
+ function layeredStatus(...statuses: LayerReadStatus[]): DesktopConfigStatus {
233
+ if (statuses.every((status) => status === "missing")) return "missing";
234
+ return statuses.some((status) => status === "valid") ? "ok" : "invalid";
235
+ }
236
+
237
+ function readProfiles(root: DesktopConfigRoots): StoreRead {
238
+ const read = readProfilesFileResult(profilesFilePath(root.configHome));
239
+ const status: DesktopConfigStatus = read.status === "valid" ? "ok" : read.status;
240
+ return {
241
+ status,
242
+ ...(read.status === "valid" ? { value: read.file } : {}),
243
+ layers: [layer("global", read.status)],
244
+ };
245
+ }
246
+
247
+ function readModels(root: DesktopConfigRoots): StoreRead {
248
+ const paths = modelConfigPaths(root.configHome, root.cwd);
249
+ // The owner merge stays authoritative: it decides precedence and rejects a
250
+ // broken layer, and `normalizeModelConfig` keeps the same safe-key policy the
251
+ // rest of the routing uses. The per-layer reads exist only to report which
252
+ // layer is missing or malformed.
253
+ const global = readModelConfigFile(paths.global);
254
+ const project = readModelConfigFile(paths.project);
255
+ const merged = readSavedModelConfig(paths.global, paths.project);
256
+ const status: DesktopConfigStatus = merged.status === "valid" ? "ok" : merged.status;
257
+ return {
258
+ status,
259
+ ...(merged.status === "valid" ? { value: normalizeModelConfig(merged.config) ?? {} } : {}),
260
+ layers: [layer("global", global.status), layer("project", project.status)],
261
+ };
262
+ }
263
+
264
+ function readProfileFallbacks(root: DesktopConfigRoots): StoreRead {
265
+ const read = readFallbacksFile(fallbacksFilePath(root.configHome));
266
+ const status: DesktopConfigStatus = read.status === "valid" ? "ok" : read.status;
267
+ return {
268
+ status,
269
+ ...(read.status === "valid" ? { value: read.file } : {}),
270
+ layers: [layer("global", read.status)],
271
+ };
272
+ }
273
+
274
+ function readSubagents(root: DesktopConfigRoots): StoreRead {
275
+ const paths = subagentsConfigPaths({ cwd: root.cwd, home: root.agentHome, agentHome: root.agentHome });
276
+ const global = readSubagentsFileResult(paths.global);
277
+ const project = readSubagentsFileResult(paths.project);
278
+ const layers = [layer("global", global.status), layer("project", project.status)];
279
+ const status = layeredStatus(global.status, project.status);
280
+ if (status !== "ok") return { status, layers };
281
+ // The same parser the runtime uses, so the projection cannot drift from the
282
+ // routing a launch would read. Like the owner, a layer that cannot be parsed is
283
+ // skipped and the remaining layer still merges; `layers` reports which one it was.
284
+ const value = parseAgentsConfig(
285
+ global.status === "valid" ? global.value : undefined,
286
+ project.status === "valid" ? project.value : undefined,
287
+ );
288
+ return { status, value, layers };
289
+ }
290
+
291
+ function readPins(root: DesktopConfigRoots): StoreRead {
292
+ const status = readProfilePinStatus(root.cwd, root.resolveWorktree);
293
+ if (!status) {
294
+ // Outside a resolvable worktree there are no pin layers to report: say so
295
+ // instead of pretending the repository declares nothing.
296
+ return {
297
+ status: "invalid",
298
+ value: { resolved: false, invalid: [], stale: [], reason: "worktree_unresolved" },
299
+ layers: [],
300
+ };
301
+ }
302
+ const store = readProfilesFileResult(profilesFilePath(root.configHome));
303
+ const evaluation = evaluateProfilePin(status, store.status === "valid" ? store.file.profiles : {});
304
+ const bothMissing = status.local.status === "missing" && status.repo.status === "missing";
305
+ const storeStatus: DesktopConfigStatus = bothMissing ? "missing" : evaluation.winner ? "ok" : "invalid";
306
+ // The owner reports layer paths for the panel; Desktop only needs which layer
307
+ // and what it held, so the paths are dropped here. The layers are already read,
308
+ // so even an all-missing or unresolvable pin set is reported instead of hidden.
309
+ return {
310
+ status: storeStatus,
311
+ value: {
312
+ resolved: evaluation.winner !== undefined,
313
+ ...(evaluation.winner === undefined
314
+ ? {}
315
+ : { winner: { source: evaluation.winner.source, profile: evaluation.winner.profile } }),
316
+ invalid: evaluation.invalid.map((issue) => ({ source: issue.source })),
317
+ stale: evaluation.stale.map((issue) => ({ source: issue.source, profile: issue.profile })),
318
+ },
319
+ layers: [layer("local", status.local.status), layer("repo", status.repo.status)],
320
+ };
321
+ }
322
+
323
+ const OWNERSHIP_KEY_MAX_LENGTH = 256;
324
+ const OWNERSHIP_HASH_PATTERN = /^[a-fA-F0-9]{64}$/;
325
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/;
326
+
327
+ function ownershipAssetKey(key: string): boolean {
328
+ if (key.length === 0 || key.length > OWNERSHIP_KEY_MAX_LENGTH) return false;
329
+ if (CONTROL_CHARACTERS.test(key) || key.includes("\\")) return false;
330
+ // An ownership key is a relative POSIX-style asset path below the agent home.
331
+ if (key.startsWith("/") || /^[A-Za-z]:/.test(key)) return false;
332
+ return key.includes("/") && key.split("/").every((segment) => segment.length > 0 && segment !== "." && segment !== "..");
333
+ }
334
+
335
+ /**
336
+ * The manifest is installer state, but it reaches a protocol, so it is filtered:
337
+ * only ownership-shaped entries are projected and an absolute path, a traversal
338
+ * segment, or an arbitrary string can never be echoed to a Desktop client. The
339
+ * installer's own current and legacy manifests hold sha256 digests over relative
340
+ * keys, so they pass unchanged.
341
+ */
342
+ function projectManagedAssets(manifest: ManagedAssetsManifest): ManagedAssetsManifest {
343
+ return {
344
+ schemaVersion: manifest.schemaVersion,
345
+ assets: Object.fromEntries(
346
+ Object.entries(manifest.assets).filter(
347
+ ([key, hash]) => ownershipAssetKey(key) && OWNERSHIP_HASH_PATTERN.test(hash),
348
+ ),
349
+ ),
350
+ };
351
+ }
352
+
353
+ function readManagedAssets(root: DesktopConfigRoots): StoreRead {
354
+ const read = readManagedAssetsManifestResult(managedAssetsManifestPath(root.agentHome));
355
+ const status: DesktopConfigStatus = read.status === "valid" ? "ok" : read.status;
356
+ return {
357
+ status,
358
+ ...(read.status === "valid" ? { value: projectManagedAssets(read.manifest) } : {}),
359
+ layers: [layer("global", read.status)],
360
+ };
361
+ }
362
+
363
+ const STORE_READERS: Record<DesktopConfigStore, { scope: DesktopConfigScope; read: (root: DesktopConfigRoots) => StoreRead }> = {
364
+ profiles: { scope: "global", read: readProfiles },
365
+ models: { scope: "global+project", read: readModels },
366
+ profile_fallbacks: { scope: "global", read: readProfileFallbacks },
367
+ subagents: { scope: "global+project", read: readSubagents },
368
+ pins: { scope: "local+repo", read: readPins },
369
+ managed_assets: { scope: "global", read: readManagedAssets },
370
+ };
371
+
372
+ export function readConfigStore(store: DesktopConfigStore, root: DesktopConfigRoots): DesktopConfigData {
373
+ const reader = STORE_READERS[store];
374
+ const read = reader.read(root);
375
+ const value = read.value === undefined ? undefined : wireValue(read.value);
376
+ const revision = configRevision(store, read.status, value);
377
+ const writeTargets = writeTargetsFor(store, root);
378
+ return {
379
+ store,
380
+ scope: reader.scope,
381
+ readOnly: storeReadOnly(store),
382
+ status: read.status,
383
+ revision,
384
+ ...(value === undefined ? {} : { value }),
385
+ layers: read.layers,
386
+ ...(writeTargets === undefined ? {} : { writeTargets }),
387
+ };
388
+ }
389
+
390
+ function layerWriteInfo(
391
+ store: DesktopConfigStore,
392
+ target: DesktopConfigWriteTarget,
393
+ status: DesktopConfigStatus,
394
+ value: unknown,
395
+ ): DesktopConfigWriteTargetInfo {
396
+ return { target, status, writeRevision: configWriteRevision(store, target, status, value) };
397
+ }
398
+
399
+ /**
400
+ * The files a store's owner rewrites, one entry each, or `undefined` for a store
401
+ * this slice never writes. `pins` returns an empty list outside a resolvable Git
402
+ * worktree: there is no truthful pin target then, so none is reported or written.
403
+ */
404
+ function writeTargetsFor(
405
+ store: DesktopConfigStore,
406
+ root: DesktopConfigRoots,
407
+ ): DesktopConfigWriteTargetInfo[] | undefined {
408
+ switch (store) {
409
+ case "profiles": {
410
+ const read = readProfilesFileResult(profilesFilePath(root.configHome));
411
+ const status: DesktopConfigStatus = read.status === "valid" ? "ok" : read.status;
412
+ return [layerWriteInfo(store, "global", status, read.status === "valid" ? read.file : undefined)];
413
+ }
414
+ case "profile_fallbacks": {
415
+ const read = readFallbacksFile(fallbacksFilePath(root.configHome));
416
+ const status: DesktopConfigStatus = read.status === "valid" ? "ok" : read.status;
417
+ return [layerWriteInfo(store, "global", status, read.status === "valid" ? read.file : undefined)];
418
+ }
419
+ case "pins": {
420
+ const status = readProfilePinStatus(root.cwd, root.resolveWorktree);
421
+ if (!status) return [];
422
+ return (["local", "repo"] as const).map((source) => {
423
+ const layerRead = source === "local" ? status.local : status.repo;
424
+ const layerStatus: DesktopConfigStatus = layerRead.status === "valid" ? "ok" : layerRead.status;
425
+ return layerWriteInfo(
426
+ store,
427
+ source,
428
+ layerStatus,
429
+ layerRead.status === "valid" ? { profile: layerRead.profile } : undefined,
430
+ );
431
+ });
432
+ }
433
+ default:
434
+ return undefined;
435
+ }
436
+ }
437
+
438
+ // ---- Write slice: validated, owner-delegated, revision-guarded ----
439
+
440
+ /**
441
+ * One write plan: either a typed rejection before anything is touched, or the
442
+ * exact target, its revision as re-read now, whether the content really differs,
443
+ * and the owner writer to call.
444
+ */
445
+ type WritePlan =
446
+ | { error: { code: string; message: string } }
447
+ | { target: DesktopConfigWriteTarget; writeRevision: string; changed: boolean; write: () => void };
448
+
449
+ function isRecordValue(value: unknown): value is Record<string, unknown> {
450
+ return typeof value === "object" && value !== null && !Array.isArray(value);
451
+ }
452
+
453
+ /**
454
+ * `expectedRevision` is mandatory and is compared before the payload is validated,
455
+ * so "you did not prove you saw the current state" never depends on what the data
456
+ * happens to look like. Absent, empty, and non-string tokens are the same answer.
457
+ */
458
+ function revisionConflict(
459
+ expected: string,
460
+ current: string,
461
+ ): typeof STALE_REVISION | undefined {
462
+ return expected === current ? undefined : STALE_REVISION;
463
+ }
464
+
465
+ /**
466
+ * The owner normalizer drops entries it cannot keep (an illegal profile name, an
467
+ * unsafe agent key, a stale `active` marker, an unknown workflow mode). Writing
468
+ * that result would silently delete operator data, so any drop rejects the write
469
+ * instead.
470
+ */
471
+ function hasNormalizationDrops(drops: ProfilesParseDrops): boolean {
472
+ return (
473
+ drops.droppedProfiles.length > 0 ||
474
+ drops.droppedAgents.length > 0 ||
475
+ drops.droppedActive !== undefined ||
476
+ (drops.droppedWorkflow?.length ?? 0) > 0
477
+ );
478
+ }
479
+
480
+ function planProfilesWrite(data: unknown, root: DesktopConfigRoots, expected: string): WritePlan {
481
+ const normalized = normalizeProfilesFile(data);
482
+ if (!normalized || hasNormalizationDrops(normalized.drops)) return { error: INVALID_DATA };
483
+ const file = normalized.file;
484
+ // The request must already be in the owner's canonical form: anything the
485
+ // normalizer would rewrite (the `effort` alias, an organic workflow entry) is
486
+ // rejected instead of being applied behind the client's back.
487
+ if (canonicalJson(file) !== canonicalJson(data)) return { error: INVALID_DATA };
488
+ // The owner's serializer must be lossless for this file; data it cannot
489
+ // round-trip is data this channel refuses to write.
490
+ const reparsed = parseProfilesFileText(serializeProfilesFile(file));
491
+ if (reparsed.status !== "valid" || canonicalJson(reparsed.file) !== canonicalJson(file)) {
492
+ return { error: INVALID_DATA };
493
+ }
494
+ const path = profilesFilePath(root.configHome);
495
+ const current = readProfilesFileResult(path);
496
+ const currentStatus: DesktopConfigStatus = current.status === "valid" ? "ok" : current.status;
497
+ const currentValue = current.status === "valid" ? current.file : undefined;
498
+ const writeRevision = configWriteRevision("profiles", "global", currentStatus, currentValue);
499
+ const conflict = revisionConflict(expected, writeRevision);
500
+ if (conflict) return { error: conflict };
501
+ const changed = current.status !== "valid" || canonicalJson(currentValue) !== canonicalJson(file);
502
+ return { target: "global", writeRevision, changed, write: () => writeProfilesFileSync(path, file) };
503
+ }
504
+
505
+ function planFallbacksWrite(data: unknown, root: DesktopConfigRoots, expected: string): WritePlan {
506
+ const normalized = normalizeFallbacksFile(data);
507
+ // The owner normalizer drops an empty chain and an emptied profile block. A
508
+ // Desktop write must be lossless, so the normalized value has to equal the
509
+ // request exactly; anything else would delete content the client sent.
510
+ if (!normalized || canonicalJson(normalized) !== canonicalJson(data)) return { error: INVALID_DATA };
511
+ const path = fallbacksFilePath(root.configHome);
512
+ const current = readFallbacksFile(path);
513
+ const currentStatus: DesktopConfigStatus = current.status === "valid" ? "ok" : current.status;
514
+ const currentValue = current.status === "valid" ? current.file : undefined;
515
+ const writeRevision = configWriteRevision("profile_fallbacks", "global", currentStatus, currentValue);
516
+ const conflict = revisionConflict(expected, writeRevision);
517
+ if (conflict) return { error: conflict };
518
+ const changed = current.status !== "valid" || canonicalJson(currentValue) !== canonicalJson(normalized);
519
+ return { target: "global", writeRevision, changed, write: () => writeFallbacksFile(path, normalized) };
520
+ }
521
+
522
+ function planPinsWrite(data: unknown, root: DesktopConfigRoots, expected: string): WritePlan {
523
+ if (!isRecordValue(data)) return { error: INVALID_DATA };
524
+ if (!Object.keys(data).every((key) => key === "source" || key === "profile")) return { error: INVALID_DATA };
525
+ const source = data.source;
526
+ // The layer is chosen by the request, never by which file happens to exist.
527
+ if (source !== "local" && source !== "repo") return { error: INVALID_DATA };
528
+ // `profile: null` is the explicit clear; every other value must be a pinnable
529
+ // name. There is no "clear everything" and no implicit clear by omission.
530
+ const requested = data.profile;
531
+ let profile: string | undefined;
532
+ if (requested !== null) {
533
+ if (!isValidProfileName(requested)) return { error: INVALID_DATA };
534
+ profile = requested;
535
+ // The invariant the `/gentle:profiles` panel enforces: only a profile the store
536
+ // still defines can be pinned, so this channel never writes a stale pin.
537
+ const store = readProfilesFileResult(profilesFilePath(root.configHome));
538
+ if (store.status !== "valid" || !Object.prototype.hasOwnProperty.call(store.file.profiles, profile)) {
539
+ return { error: UNKNOWN_PIN_PROFILE };
540
+ }
541
+ }
542
+ const status = readProfilePinStatus(root.cwd, root.resolveWorktree);
543
+ if (!status) return { error: UNAVAILABLE };
544
+ const layer = source === "local" ? status.local : status.repo;
545
+ const path = source === "local" ? status.localPath : status.repoPath;
546
+ const layerStatus: DesktopConfigStatus = layer.status === "valid" ? "ok" : layer.status;
547
+ const writeRevision = configWriteRevision(
548
+ "pins",
549
+ source,
550
+ layerStatus,
551
+ layer.status === "valid" ? { profile: layer.profile } : undefined,
552
+ );
553
+ const conflict = revisionConflict(expected, writeRevision);
554
+ if (conflict) return { error: conflict };
555
+ // Clearing a layer that holds no file is already the desired state; a layer that
556
+ // exists but is not a readable pin is still removed by an explicit clear.
557
+ if (profile === undefined) {
558
+ return {
559
+ target: source,
560
+ writeRevision,
561
+ changed: layer.status !== "missing",
562
+ write: () => clearProfilePinSync(path),
563
+ };
564
+ }
565
+ return {
566
+ target: source,
567
+ writeRevision,
568
+ changed: !(layer.status === "valid" && layer.profile === profile),
569
+ write: () => writeProfilePinSync(path, profile),
570
+ };
571
+ }
572
+
573
+ /** Params are exactly `{store}`: no path, no scope selector, no store options. */
574
+ function parseStoreParam(params: Record<string, unknown>): DesktopConfigStore | { error: typeof INVALID_PARAMS | typeof UNKNOWN_STORE } {
575
+ const keys = Object.keys(params);
576
+ if (keys.length !== 1 || keys[0] !== "store" || typeof params.store !== "string") {
577
+ return { error: INVALID_PARAMS };
578
+ }
579
+ if (!isDesktopConfigStore(params.store)) return { error: UNKNOWN_STORE };
580
+ return params.store;
581
+ }
582
+
583
+ /**
584
+ * `get_config` and the bounded `set_config` writer, over the owner readers and
585
+ * the three owner writers.
586
+ *
587
+ * The host context is bound per Desktop command, exactly like the permission
588
+ * bridge, because the pin and project layers depend on the live session cwd.
589
+ * Reads never write, so a read can never advance a store.
590
+ */
591
+ export class DesktopConfigBridge {
592
+ private host: ExtensionContext | undefined;
593
+ private readonly overrides: DesktopConfigOverrides;
594
+
595
+ constructor(overrides: DesktopConfigOverrides = {}) {
596
+ this.overrides = overrides;
597
+ }
598
+
599
+ attach(context: ExtensionContext): void {
600
+ this.host = context;
601
+ }
602
+
603
+ reset(): void {
604
+ this.host = undefined;
605
+ }
606
+
607
+ handle(method: string, params: Record<string, unknown>): DesktopRpcOutcome | undefined {
608
+ // Only the config methods are this bridge's business; anything else falls
609
+ // through to the next domain (the permission bridge) untouched.
610
+ if (method !== "get_config" && method !== "set_config") return undefined;
611
+ const host = this.host;
612
+ if (!host) return { ok: false, error: UNAVAILABLE };
613
+ return method === "get_config" ? this.read(host, params) : this.write(host, params);
614
+ }
615
+
616
+ private read(host: ExtensionContext, params: Record<string, unknown>): DesktopRpcOutcome {
617
+ const parsed = parseStoreParam(params);
618
+ if (typeof parsed !== "string") return { ok: false, error: parsed.error };
619
+ const root = withRoots(host, this.overrides);
620
+ if (!root) return { ok: false, error: UNAVAILABLE };
621
+ const data = readConfigStore(parsed, root);
622
+ return { ok: true, data: data as unknown as Record<string, unknown> };
623
+ }
624
+
625
+ /**
626
+ * `set_config`: validate the store-specific data with the owner, re-check
627
+ * `expectedRevision` against a fresh read, then let the owner write.
628
+ *
629
+ * Everything here is synchronous on purpose. Pi dispatches Desktop prompts
630
+ * concurrently, and only an `await` can interleave another request, so the check
631
+ * and the owner's atomic rename cannot be split by another Desktop request in
632
+ * this process. That is a per-process guarantee only; it is not a cross-process
633
+ * transaction (see `docs/desktop-rpc.md`).
634
+ */
635
+ private write(host: ExtensionContext, params: Record<string, unknown>): DesktopRpcOutcome {
636
+ for (const key of Object.keys(params)) {
637
+ if (key !== "store" && key !== "data" && key !== "expectedRevision") {
638
+ return { ok: false, error: INVALID_PARAMS };
639
+ }
640
+ }
641
+ if (typeof params.store !== "string" || params.data === undefined) {
642
+ return { ok: false, error: INVALID_PARAMS };
643
+ }
644
+ if (!isDesktopConfigStore(params.store)) return { ok: false, error: UNKNOWN_STORE };
645
+ // A read-only store is rejected before its data is inspected: the reason a
646
+ // write cannot happen is the store itself, not the payload.
647
+ if (storeReadOnly(params.store)) return { ok: false, error: READ_ONLY };
648
+ // An apply_profile reads these stores, awaits, then rewrites the profiles
649
+ // store (and restores it on failure) from that snapshot; a write accepted in
650
+ // between would be silently overwritten, so it waits for the apply instead.
651
+ if (isDesktopProfileApplyRunning()) return { ok: false, error: APPLY_BUSY };
652
+ // A usable revision is required before the payload is validated: absent, empty,
653
+ // and non-string tokens are all "the client did not prove current state".
654
+ const expected =
655
+ typeof params.expectedRevision === "string" && params.expectedRevision.length > 0
656
+ ? params.expectedRevision
657
+ : undefined;
658
+ if (expected === undefined) return { ok: false, error: MISSING_REVISION };
659
+ const root = withRoots(host, this.overrides);
660
+ if (!root) return { ok: false, error: UNAVAILABLE };
661
+
662
+ const store = params.store;
663
+ const plan =
664
+ store === "profiles"
665
+ ? planProfilesWrite(params.data, root, expected)
666
+ : store === "profile_fallbacks"
667
+ ? planFallbacksWrite(params.data, root, expected)
668
+ : planPinsWrite(params.data, root, expected);
669
+ if ("error" in plan) return { ok: false, error: plan.error };
670
+
671
+ // Identical content is not a change: the owner writer would skip the rename
672
+ // anyway, and skipping it here keeps a no-op free of a rewrite and an event.
673
+ if (plan.changed) {
674
+ try {
675
+ plan.write();
676
+ } catch {
677
+ // Owner failures carry paths and OS detail; none of it crosses the contract.
678
+ return { ok: false, error: WRITE_FAILED };
679
+ }
680
+ }
681
+
682
+ // The response reports what the store now holds, re-read through the owner,
683
+ // not an echo of the request. The resulting write revision also decides
684
+ // whether this request really changed anything.
685
+ const after = readConfigStore(store, root);
686
+ const writeRevision = after.writeTargets?.find((entry) => entry.target === plan.target)?.writeRevision;
687
+ const changed = writeRevision !== plan.writeRevision;
688
+ const data = { ...after, writeTarget: plan.target, writeRevision, changed } as Record<string, unknown>;
689
+ if (!changed) return { ok: true, data };
690
+ return {
691
+ ok: true,
692
+ data,
693
+ event: {
694
+ name: DESKTOP_CONFIG_EVENT,
695
+ data: {
696
+ store: after.store,
697
+ scope: after.scope,
698
+ writeTarget: plan.target,
699
+ revision: after.revision,
700
+ writeRevision,
701
+ source: "desktop",
702
+ },
703
+ },
704
+ };
705
+ }
706
+
707
+ /** Bounded status/revision/readOnly projection; store content never enters a snapshot. */
708
+ snapshotState(): DesktopRpcState {
709
+ const host = this.host;
710
+ if (!host) return {};
711
+ const root = withRoots(host, this.overrides);
712
+ // Without a session cwd the project and pin layers cannot be read truthfully,
713
+ // so the snapshot stays empty rather than reporting a guess.
714
+ if (!root) return {};
715
+ return {
716
+ config: {
717
+ stores: DESKTOP_CONFIG_STORES.map((store) => {
718
+ const reader = STORE_READERS[store];
719
+ const read = reader.read(root);
720
+ return {
721
+ store,
722
+ scope: reader.scope,
723
+ readOnly: storeReadOnly(store),
724
+ status: read.status,
725
+ revision: configRevision(store, read.status, read.value),
726
+ };
727
+ }),
728
+ },
729
+ };
730
+ }
731
+ }