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,1452 @@
1
+ import assert from "node:assert/strict";
2
+ import { createHash } from "node:crypto";
3
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { test } from "node:test";
7
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
8
+ import desktopRpc from "../extensions/gentle-desktop-rpc.ts";
9
+ import { parseAgentsConfig, loadAgentsConfig } from "../lib/agents-config.ts";
10
+ import { FALLBACKS_KIND, FALLBACKS_VERSION, fallbacksFilePath, normalizeFallbacksFile } from "../lib/model-fallback-store.ts";
11
+ import { PROFILES_KIND, PROFILES_VERSION, normalizeProfilesFile, profilesFilePath, serializeProfilesFile } from "../lib/agent-profiles.ts";
12
+ import { PROFILE_PIN_KIND, PROFILE_PIN_VERSION, localProfilePinPath, repoProfileDeclarationPath, serializeProfilePin } from "../lib/agent-profile-pin.ts";
13
+ import { DESKTOP_CONFIG_EVENTS, DESKTOP_CONFIG_METHODS, DESKTOP_CONFIG_STORES, DesktopConfigBridge } from "../lib/desktop-rpc-config.ts";
14
+ import { DESKTOP_RPC_SCHEMA, DESKTOP_RPC_WIDGET } from "../lib/desktop-rpc.ts";
15
+ import { beginDesktopProfileApply, endDesktopProfileApply } from "../lib/desktop-rpc-profiles.ts";
16
+ import { INTERACTIVE_HOST_ENV } from "../lib/rpc-host.ts";
17
+ import type { WorktreeIdentity } from "../lib/session-worktree-registry.ts";
18
+
19
+ // The Desktop read-side config slice: `get_config` over the existing owner
20
+ // readers. Every test runs in an isolated temporary root, so no real user
21
+ // config, auth file, or repository store is ever read.
22
+
23
+ interface Env {
24
+ root: string;
25
+ configHome: string;
26
+ agentHome: string;
27
+ workspace: string;
28
+ }
29
+
30
+ function isolatedEnvironment(t: test.TestContext): Env {
31
+ const root = mkdtempSync(join(tmpdir(), "gentle-desktop-config-"));
32
+ const configHome = join(root, "config");
33
+ const agentHome = join(root, "agent");
34
+ const workspace = join(root, "workspace");
35
+ for (const directory of [configHome, agentHome, workspace]) mkdirSync(directory, { recursive: true });
36
+ t.after(() => rmSync(root, { recursive: true, force: true }));
37
+ return { root, configHome, agentHome, workspace };
38
+ }
39
+
40
+ function writeJson(path: string, value: unknown): void {
41
+ mkdirSync(dirname(path), { recursive: true });
42
+ writeFileSync(path, `${JSON.stringify(value)}\n`);
43
+ }
44
+
45
+ function profilesFixture(): Record<string, unknown> {
46
+ return {
47
+ kind: PROFILES_KIND,
48
+ version: PROFILES_VERSION,
49
+ active: "team",
50
+ profiles: {
51
+ team: {
52
+ explore: { model: "anthropic/claude-explore" },
53
+ orchestrator: { model: "openai/gpt-orchestrator" },
54
+ },
55
+ ops: { worker: { model: "openai/gpt-worker", thinking: "high" } },
56
+ },
57
+ };
58
+ }
59
+
60
+ function pin(profile: string): Record<string, unknown> {
61
+ return { kind: PROFILE_PIN_KIND, version: PROFILE_PIN_VERSION, profile };
62
+ }
63
+
64
+ function bridgeFor(env: Env, resolveWorktree?: () => WorktreeIdentity | undefined): DesktopConfigBridge {
65
+ const bridge = new DesktopConfigBridge({
66
+ configHome: env.configHome,
67
+ agentHome: env.agentHome,
68
+ ...(resolveWorktree === undefined ? {} : { resolveWorktree }),
69
+ });
70
+ bridge.attach({ cwd: env.workspace } as unknown as ExtensionContext);
71
+ return bridge;
72
+ }
73
+
74
+ async function readStore(bridge: DesktopConfigBridge, store: string, params: Record<string, unknown> = {}): Promise<any> {
75
+ const outcome = await bridge.handle("get_config", { store, ...params });
76
+ assert.ok(outcome, "get_config must answer");
77
+ assert.equal(outcome.ok, true, `unexpected failure: ${JSON.stringify(outcome)}`);
78
+ return outcome.data;
79
+ }
80
+
81
+ function expectedRevision(payload: unknown): string {
82
+ const canonical = (value: unknown): string => {
83
+ if (value === undefined) return "null";
84
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
85
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
86
+ const entries = Object.entries(value as Record<string, unknown>)
87
+ .filter(([, entry]) => entry !== undefined)
88
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
89
+ .map(([key, entry]) => `${JSON.stringify(key)}:${canonical(entry)}`);
90
+ return `{${entries.join(",")}}`;
91
+ };
92
+ return `sha256:${createHash("sha256").update(canonical(payload)).digest("hex").slice(0, 32)}`;
93
+ }
94
+
95
+ test("profiles reads the normalized global store with stable revisions and mutable metadata", async (t) => {
96
+ const env = isolatedEnvironment(t);
97
+ writeJson(profilesFilePath(env.configHome), profilesFixture());
98
+ const bridge = bridgeFor(env);
99
+
100
+ const first = await readStore(bridge, "profiles");
101
+ const second = await readStore(bridge, "profiles");
102
+
103
+ assert.equal(first.store, "profiles");
104
+ assert.equal(first.scope, "global");
105
+ assert.equal(first.readOnly, false, "profiles is an authoritative, later-mutable store");
106
+ assert.equal(first.status, "ok");
107
+ assert.deepEqual(first.layers, [{ source: "global", status: "ok" }]);
108
+ assert.deepEqual(first.value, {
109
+ kind: PROFILES_KIND,
110
+ version: PROFILES_VERSION,
111
+ active: "team",
112
+ profiles: {
113
+ team: {
114
+ explore: { model: "anthropic/claude-explore" },
115
+ orchestrator: { model: "openai/gpt-orchestrator" },
116
+ },
117
+ ops: { worker: { model: "openai/gpt-worker", thinking: "high" } },
118
+ },
119
+ });
120
+ assert.match(first.revision, /^sha256:[a-f0-9]{32}$/);
121
+ assert.equal(second.revision, first.revision, "equivalent reads keep one revision");
122
+ assert.equal(
123
+ first.revision,
124
+ expectedRevision({ store: "profiles", status: "ok", value: first.value }),
125
+ "the revision is derived from the canonical current content",
126
+ );
127
+ assert.deepEqual(second.value, first.value);
128
+ });
129
+
130
+ test("profiles reports missing and malformed files without repairing them", async (t) => {
131
+ const env = isolatedEnvironment(t);
132
+ const bridge = bridgeFor(env);
133
+ const path = profilesFilePath(env.configHome);
134
+
135
+ const missing = await readStore(bridge, "profiles");
136
+ assert.equal(missing.status, "missing");
137
+ assert.equal(missing.value, undefined, "a missing store carries no invented value");
138
+ assert.equal(missing.readOnly, false);
139
+ assert.deepEqual(missing.layers, [{ source: "global", status: "missing" }]);
140
+ assert.equal(missing.revision, expectedRevision({ store: "profiles", status: "missing" }));
141
+
142
+ mkdirSync(dirname(path), { recursive: true });
143
+ writeFileSync(path, "{ not json\n");
144
+ const before = { text: readFileSync(path, "utf8"), mtimeMs: statSync(path).mtimeMs };
145
+ const malformed = await readStore(bridge, "profiles");
146
+ const after = { text: readFileSync(path, "utf8"), mtimeMs: statSync(path).mtimeMs };
147
+
148
+ assert.equal(malformed.status, "invalid");
149
+ assert.equal(malformed.value, undefined);
150
+ assert.deepEqual(malformed.layers, [{ source: "global", status: "invalid" }]);
151
+ assert.equal(malformed.revision, expectedRevision({ store: "profiles", status: "invalid" }));
152
+ assert.deepEqual(after, before, "a read never repairs or rewrites a malformed file");
153
+ assert.notEqual(malformed.revision, missing.revision, "missing and invalid are different content");
154
+ });
155
+
156
+ test("models merges the global store over the legacy project store read-only", async (t) => {
157
+ const env = isolatedEnvironment(t);
158
+ const globalConfig = {
159
+ explore: { model: "anthropic/claude-global" },
160
+ worker: { model: "openai/gpt-global" },
161
+ "__proto__": { model: "openai/gpt-hostile" },
162
+ };
163
+ const projectConfig = {
164
+ explore: { model: "anthropic/claude-project" },
165
+ review: { model: "openai/gpt-project", thinking: "low" },
166
+ };
167
+ writeJson(join(env.configHome, "models.json"), globalConfig);
168
+ writeJson(join(env.workspace, ".pi", "gentle-ai", "models.json"), projectConfig);
169
+
170
+ const data = await readStore(bridgeFor(env), "models");
171
+
172
+ assert.equal(data.scope, "global+project");
173
+ assert.equal(data.readOnly, true, "models is materialized routing, never a Desktop write target");
174
+ assert.equal(data.status, "ok");
175
+ assert.deepEqual(data.layers, [
176
+ { source: "global", status: "ok" },
177
+ { source: "project", status: "ok" },
178
+ ]);
179
+ // Global wins per agent, project-only agents merge in, and unsafe keys are dropped.
180
+ assert.deepEqual(data.value, {
181
+ explore: { model: "anthropic/claude-global" },
182
+ worker: { model: "openai/gpt-global" },
183
+ review: { model: "openai/gpt-project", thinking: "low" },
184
+ });
185
+ assert.equal(Object.prototype.hasOwnProperty.call(data.value, "__proto__"), false);
186
+ });
187
+
188
+ test("models reports missing layers and a malformed layer truthfully", async (t) => {
189
+ const env = isolatedEnvironment(t);
190
+ const bridge = bridgeFor(env);
191
+
192
+ const missing = await readStore(bridge, "models");
193
+ assert.equal(missing.status, "missing");
194
+ assert.equal(missing.value, undefined);
195
+ assert.deepEqual(missing.layers, [
196
+ { source: "global", status: "missing" },
197
+ { source: "project", status: "missing" },
198
+ ]);
199
+
200
+ writeJson(join(env.workspace, ".pi", "gentle-ai", "models.json"), { worker: { model: "openai/gpt-project" } });
201
+ const projectOnly = await readStore(bridge, "models");
202
+ assert.equal(projectOnly.status, "ok");
203
+ assert.deepEqual(projectOnly.value, { worker: { model: "openai/gpt-project" } });
204
+ assert.deepEqual(projectOnly.layers, [
205
+ { source: "global", status: "missing" },
206
+ { source: "project", status: "ok" },
207
+ ]);
208
+
209
+ mkdirSync(env.configHome, { recursive: true });
210
+ writeFileSync(join(env.configHome, "models.json"), "[1,2,3]\n");
211
+ const invalid = await readStore(bridge, "models");
212
+ assert.equal(invalid.status, "invalid");
213
+ assert.equal(invalid.value, undefined, "a broken global layer never yields a partial value");
214
+ assert.deepEqual(invalid.layers, [
215
+ { source: "global", status: "invalid" },
216
+ { source: "project", status: "ok" },
217
+ ]);
218
+ });
219
+
220
+ test("profile_fallbacks reads normalized chains and reports malformed content", async (t) => {
221
+ const env = isolatedEnvironment(t);
222
+ const path = fallbacksFilePath(env.configHome);
223
+ writeJson(path, {
224
+ kind: FALLBACKS_KIND,
225
+ version: FALLBACKS_VERSION,
226
+ profiles: {
227
+ team: {
228
+ "*": [{ model: "openai/gpt-shared" }],
229
+ worker: [{ model: "openai/gpt-worker", thinking: "low" }],
230
+ },
231
+ },
232
+ });
233
+ const bridge = bridgeFor(env);
234
+
235
+ const data = await readStore(bridge, "profile_fallbacks");
236
+ assert.equal(data.scope, "global");
237
+ assert.equal(data.readOnly, false, "fallback chains are authoritative and later mutable");
238
+ assert.equal(data.status, "ok");
239
+ assert.deepEqual(data.layers, [{ source: "global", status: "ok" }]);
240
+ assert.deepEqual(data.value, {
241
+ kind: FALLBACKS_KIND,
242
+ version: FALLBACKS_VERSION,
243
+ profiles: {
244
+ team: {
245
+ "*": [{ model: "openai/gpt-shared" }],
246
+ worker: [{ model: "openai/gpt-worker", thinking: "low" }],
247
+ },
248
+ },
249
+ });
250
+
251
+ writeFileSync(path, `${JSON.stringify({ kind: FALLBACKS_KIND, version: FALLBACKS_VERSION, profiles: { team: { worker: "nope" } } })}\n`);
252
+ const invalid = await readStore(bridge, "profile_fallbacks");
253
+ assert.equal(invalid.status, "invalid");
254
+ assert.equal(invalid.value, undefined);
255
+ });
256
+
257
+ test("subagents merges global and project stores through the owner parser read-only", async (t) => {
258
+ const env = isolatedEnvironment(t);
259
+ const globalConfig = {
260
+ default_model: "anthropic/claude-default",
261
+ model_profiles: {
262
+ explore: { model: "anthropic/claude-sub-global", effort: "medium" },
263
+ worker: { model: "openai/gpt-sub-global" },
264
+ },
265
+ max_concurrency: 7,
266
+ };
267
+ const projectConfig = {
268
+ model_profiles: {
269
+ explore: { model: "anthropic/claude-sub-project" },
270
+ review: { model: "openai/gpt-sub-project" },
271
+ },
272
+ max_concurrency: 3,
273
+ };
274
+ writeJson(join(env.agentHome, "subagents.json"), globalConfig);
275
+ writeJson(join(env.workspace, ".pi", "subagents.json"), projectConfig);
276
+
277
+ const data = await readStore(bridgeFor(env), "subagents");
278
+
279
+ assert.equal(data.scope, "global+project");
280
+ assert.equal(data.readOnly, true, "subagents.json is owner-materialized routing");
281
+ assert.equal(data.status, "ok");
282
+ assert.deepEqual(data.layers, [
283
+ { source: "global", status: "ok" },
284
+ { source: "project", status: "ok" },
285
+ ]);
286
+ // The owner parser is the oracle; the projection matches its wire form.
287
+ assert.deepEqual(data.value, JSON.parse(JSON.stringify(parseAgentsConfig(globalConfig, projectConfig))));
288
+ assert.equal(data.value.maxConcurrency, 3);
289
+ assert.equal(data.value.modelProfiles.explore.model.id, "claude-sub-project");
290
+ assert.equal(data.value.modelProfiles.explore.thinking, "medium");
291
+ });
292
+
293
+ test("subagents merges the valid layer when the other layer is malformed", async (t) => {
294
+ const env = isolatedEnvironment(t);
295
+ const globalConfig = {
296
+ model_profiles: { explore: { model: "anthropic/claude-sub-global" } },
297
+ max_concurrency: 7,
298
+ };
299
+ writeJson(join(env.agentHome, "subagents.json"), globalConfig);
300
+ mkdirSync(join(env.workspace, ".pi"), { recursive: true });
301
+ const projectPath = join(env.workspace, ".pi", "subagents.json");
302
+ writeFileSync(projectPath, "[not, an, object]\n");
303
+
304
+ const data = await readStore(bridgeFor(env), "subagents");
305
+
306
+ // The runtime's own reader skips a layer it cannot parse and merges the rest,
307
+ // so the projection must answer the same way while still naming the bad layer.
308
+ assert.equal(data.status, "ok", "one malformed layer must not invalidate the whole store");
309
+ assert.deepEqual(data.layers, [
310
+ { source: "global", status: "ok" },
311
+ { source: "project", status: "invalid" },
312
+ ]);
313
+ assert.deepEqual(
314
+ data.value,
315
+ JSON.parse(JSON.stringify(loadAgentsConfig({ cwd: env.workspace, home: env.agentHome, agentHome: env.agentHome }))),
316
+ "the projection matches the owner config a launch would read",
317
+ );
318
+ assert.equal(data.value.maxConcurrency, 7);
319
+
320
+ // Every layer unusable is reported as such: the owner would fall back to its
321
+ // defaults, which is not the content of this store.
322
+ writeFileSync(join(env.agentHome, "subagents.json"), "{ broken\n");
323
+ const allInvalid = await readStore(bridgeFor(env), "subagents");
324
+ assert.equal(allInvalid.status, "invalid");
325
+ assert.equal(allInvalid.value, undefined);
326
+ assert.deepEqual(allInvalid.layers, [
327
+ { source: "global", status: "invalid" },
328
+ { source: "project", status: "invalid" },
329
+ ]);
330
+ assert.notEqual(allInvalid.revision, data.revision);
331
+
332
+ // A missing layer is not a malformed one: the other layer still merges.
333
+ writeJson(join(env.agentHome, "subagents.json"), globalConfig);
334
+ rmSync(projectPath);
335
+ const missingProject = await readStore(bridgeFor(env), "subagents");
336
+ assert.equal(missingProject.status, "ok");
337
+ assert.deepEqual(missingProject.layers, [
338
+ { source: "global", status: "ok" },
339
+ { source: "project", status: "missing" },
340
+ ]);
341
+ assert.equal(missingProject.value.maxConcurrency, 7);
342
+ });
343
+
344
+ test("pins resolve local over repo without exposing layer paths", async (t) => {
345
+ const env = isolatedEnvironment(t);
346
+ writeJson(profilesFilePath(env.configHome), profilesFixture());
347
+ const identity: WorktreeIdentity = { root: env.workspace, commonDir: join(env.root, "git-common") };
348
+ writeJson(localProfilePinPath(identity.commonDir), pin("team"));
349
+ writeJson(repoProfileDeclarationPath(identity.root), pin("ops"));
350
+
351
+ const data = await readStore(bridgeFor(env, () => identity), "pins");
352
+
353
+ assert.equal(data.scope, "local+repo");
354
+ assert.equal(data.readOnly, false, "a repository pin stays an authoritative store");
355
+ assert.equal(data.status, "ok");
356
+ assert.deepEqual(data.layers, [
357
+ { source: "local", status: "ok" },
358
+ { source: "repo", status: "ok" },
359
+ ]);
360
+ assert.deepEqual(data.value, {
361
+ resolved: true,
362
+ winner: { source: "local", profile: "team" },
363
+ invalid: [],
364
+ stale: [],
365
+ });
366
+ assert.equal(JSON.stringify(data).includes(env.root), false, "no physical path crosses the contract");
367
+ });
368
+
369
+ test("pins report stale and invalid layers instead of hiding them", async (t) => {
370
+ const env = isolatedEnvironment(t);
371
+ writeJson(profilesFilePath(env.configHome), profilesFixture());
372
+ const identity: WorktreeIdentity = { root: env.workspace, commonDir: join(env.root, "git-common") };
373
+ const bridge = bridgeFor(env, () => identity);
374
+
375
+ writeJson(localProfilePinPath(identity.commonDir), pin("gone"));
376
+ writeJson(repoProfileDeclarationPath(identity.root), pin("ops"));
377
+ const stale = await readStore(bridge, "pins");
378
+ assert.equal(stale.status, "ok", "a lower layer still resolves");
379
+ assert.deepEqual(stale.value, {
380
+ resolved: true,
381
+ winner: { source: "repo", profile: "ops" },
382
+ invalid: [],
383
+ stale: [{ source: "local", profile: "gone" }],
384
+ });
385
+ assert.deepEqual(stale.layers, [
386
+ { source: "local", status: "ok" },
387
+ { source: "repo", status: "ok" },
388
+ ]);
389
+
390
+ mkdirSync(dirname(localProfilePinPath(identity.commonDir)), { recursive: true });
391
+ writeFileSync(localProfilePinPath(identity.commonDir), "{ broken\n");
392
+ const invalidLayer = await readStore(bridge, "pins");
393
+ assert.equal(invalidLayer.status, "ok");
394
+ assert.deepEqual(invalidLayer.layers, [
395
+ { source: "local", status: "invalid" },
396
+ { source: "repo", status: "ok" },
397
+ ]);
398
+ assert.deepEqual(invalidLayer.value.invalid, [{ source: "local" }]);
399
+ assert.deepEqual(invalidLayer.value.winner, { source: "repo", profile: "ops" });
400
+ });
401
+
402
+ test("pins report missing, unresolvable, and non-worktree cases truthfully", async (t) => {
403
+ const env = isolatedEnvironment(t);
404
+ writeJson(profilesFilePath(env.configHome), profilesFixture());
405
+ const identity: WorktreeIdentity = { root: env.workspace, commonDir: join(env.root, "git-common") };
406
+
407
+ const noPin = await readStore(bridgeFor(env, () => identity), "pins");
408
+ assert.equal(noPin.status, "missing");
409
+ assert.deepEqual(noPin.value, { resolved: false, invalid: [], stale: [] });
410
+
411
+ const outside = await readStore(bridgeFor(env, () => undefined), "pins");
412
+ assert.equal(outside.status, "invalid");
413
+ assert.equal(outside.layers.length, 0);
414
+ assert.deepEqual(outside.value, { resolved: false, invalid: [], stale: [], reason: "worktree_unresolved" });
415
+
416
+ writeJson(localProfilePinPath(identity.commonDir), pin("gone"));
417
+ const unresolvable = await readStore(bridgeFor(env, () => identity), "pins");
418
+ assert.equal(unresolvable.status, "invalid", "no layer resolves to a stored profile");
419
+ assert.deepEqual(unresolvable.value, {
420
+ resolved: false,
421
+ invalid: [],
422
+ stale: [{ source: "local", profile: "gone" }],
423
+ });
424
+ });
425
+
426
+ test("managed_assets reads the agent-home manifest read-only", async (t) => {
427
+ const env = isolatedEnvironment(t);
428
+ const path = join(env.agentHome, "gentle-ai", "managed-assets.json");
429
+ writeJson(path, { schemaVersion: 1, assets: { "agents/gentle-ai-worker.md": "a".repeat(64) } });
430
+
431
+ const data = await readStore(bridgeFor(env), "managed_assets");
432
+ assert.equal(data.scope, "global");
433
+ assert.equal(data.readOnly, true, "the managed-asset manifest belongs to the installer");
434
+ assert.equal(data.status, "ok");
435
+ assert.deepEqual(data.layers, [{ source: "global", status: "ok" }]);
436
+ assert.deepEqual(data.value, { schemaVersion: 1, assets: { "agents/gentle-ai-worker.md": "a".repeat(64) } });
437
+
438
+ writeJson(path, { schemaVersion: 99, assets: {} });
439
+ const unsupported = await readStore(bridgeFor(env), "managed_assets");
440
+ assert.equal(unsupported.status, "invalid");
441
+ assert.equal(unsupported.value, undefined);
442
+
443
+ rmSync(path);
444
+ const missing = await readStore(bridgeFor(env), "managed_assets");
445
+ assert.equal(missing.status, "missing");
446
+ });
447
+
448
+ test("managed_assets projects only ownership-shaped keys and hashes", async (t) => {
449
+ const env = isolatedEnvironment(t);
450
+ const path = join(env.agentHome, "gentle-ai", "managed-assets.json");
451
+ const hash = "b".repeat(64);
452
+ writeJson(path, {
453
+ schemaVersion: 1,
454
+ assets: {
455
+ "agents/gentle-ai-worker.md": hash,
456
+ "/etc/passwd": hash,
457
+ "agents/../../escape.md": hash,
458
+ "agents/back\\slash.md": hash,
459
+ "C:/windows/system32/evil.md": hash,
460
+ "agents//empty-segment.md": hash,
461
+ "/leading.md": hash,
462
+ "agents/empty-hash.md": "",
463
+ "agents/not-a-hash.md": "not-a-sha256-digest",
464
+ "agents/short-hash.md": hash.slice(0, 63),
465
+ },
466
+ });
467
+
468
+ const data = await readStore(bridgeFor(env), "managed_assets");
469
+
470
+ assert.equal(data.status, "ok");
471
+ assert.deepEqual(data.value, { schemaVersion: 1, assets: { "agents/gentle-ai-worker.md": hash } });
472
+ const wire = JSON.stringify(data);
473
+ for (const leaked of ["passwd", "escape", "windows", "not-a-sha256-digest"]) {
474
+ assert.equal(wire.includes(leaked), false, `a non-ownership entry never crosses the contract: ${leaked}`);
475
+ }
476
+ assert.equal(wire.includes(env.root), false);
477
+ });
478
+
479
+ test("managed_assets preserves a shipped legacy manifest without filtering valid entries", async (t) => {
480
+ const env = isolatedEnvironment(t);
481
+ const legacy = JSON.parse(readFileSync(new URL("../assets/migrations/managed-assets-v2.5.0.json", import.meta.url), "utf8"));
482
+ const path = join(env.agentHome, "gentle-ai", "managed-assets.json");
483
+ writeJson(path, legacy);
484
+
485
+ const data = await readStore(bridgeFor(env), "managed_assets");
486
+
487
+ assert.equal(data.status, "ok");
488
+ assert.deepEqual(data.value, { schemaVersion: legacy.schemaVersion, assets: legacy.assets });
489
+ assert.deepEqual(Object.keys(data.value.assets), Object.keys(legacy.assets), "every shipped ownership entry survives");
490
+ });
491
+
492
+ test("revisions stay stable for equivalent content and change when content changes", async (t) => {
493
+ const env = isolatedEnvironment(t);
494
+ const path = profilesFilePath(env.configHome);
495
+ const bridge = bridgeFor(env);
496
+ const fixture = profilesFixture();
497
+
498
+ writeJson(path, fixture);
499
+ const first = await readStore(bridge, "profiles");
500
+
501
+ // Same normalized content, different byte layout: the revision must not move.
502
+ writeFileSync(
503
+ path,
504
+ `{"profiles":${JSON.stringify(fixture.profiles)},"active":"team","version":1,"kind":"${PROFILES_KIND}"}`,
505
+ );
506
+ const reordered = await readStore(bridge, "profiles");
507
+ assert.notEqual(readFileSync(path, "utf8"), JSON.stringify(fixture), "the bytes really differ");
508
+ assert.equal(reordered.revision, first.revision, "revision tracks normalized content, not formatting");
509
+
510
+ writeJson(path, { ...fixture, active: "ops" });
511
+ const changed = await readStore(bridge, "profiles");
512
+ assert.notEqual(changed.revision, first.revision, "a content change moves the revision");
513
+ assert.equal(changed.value.active, "ops");
514
+ });
515
+
516
+ test("get_config rejects unknown stores, unsupported params, and physical paths", async (t) => {
517
+ const env = isolatedEnvironment(t);
518
+ writeJson(profilesFilePath(env.configHome), profilesFixture());
519
+ const bridge = bridgeFor(env);
520
+
521
+ const unknownStore = await bridge.handle("get_config", { store: "auth" });
522
+ assert.deepEqual(unknownStore, {
523
+ ok: false,
524
+ error: { code: "unknown_store", message: "Unknown Desktop config store" },
525
+ });
526
+
527
+ for (const params of [
528
+ {},
529
+ { store: 42 },
530
+ { store: "profiles", path: join(env.root, "config", "profiles.json") },
531
+ { store: "profiles", scope: "project" },
532
+ { store: "profiles", physical_path: "/etc/passwd" },
533
+ ]) {
534
+ const outcome = await bridge.handle("get_config", params as Record<string, unknown>);
535
+ assert.equal(outcome?.ok, false, `expected rejection for ${JSON.stringify(params)}`);
536
+ assert.equal((outcome as { error: { code: string } }).error.code, "invalid_request");
537
+ assert.equal(JSON.stringify(outcome).includes(env.root), false, "no physical path is echoed back");
538
+ }
539
+
540
+ assert.deepEqual(DESKTOP_CONFIG_METHODS, ["get_config", "set_config"]);
541
+ assert.deepEqual([...DESKTOP_CONFIG_EVENTS], ["config_changed"]);
542
+ assert.deepEqual([...DESKTOP_CONFIG_STORES], ["profiles", "models", "profile_fallbacks", "subagents", "pins", "managed_assets"]);
543
+ });
544
+
545
+ test("reads never mutate any store", async (t) => {
546
+ const env = isolatedEnvironment(t);
547
+ const identity: WorktreeIdentity = { root: env.workspace, commonDir: join(env.root, "git-common") };
548
+ writeJson(profilesFilePath(env.configHome), profilesFixture());
549
+ writeJson(join(env.configHome, "models.json"), { explore: { model: "anthropic/claude-global" } });
550
+ writeJson(fallbacksFilePath(env.configHome), { kind: FALLBACKS_KIND, version: FALLBACKS_VERSION, profiles: {} });
551
+ writeJson(join(env.agentHome, "subagents.json"), { model_profiles: { explore: { model: "anthropic/claude-sub" } } });
552
+ writeJson(join(env.workspace, ".pi", "gentle-ai", "models.json"), { worker: { model: "openai/gpt-project" } });
553
+ writeJson(join(env.workspace, ".pi", "subagents.json"), { max_concurrency: 2 });
554
+ writeJson(localProfilePinPath(identity.commonDir), pin("team"));
555
+ writeJson(repoProfileDeclarationPath(identity.root), pin("ops"));
556
+ writeJson(join(env.agentHome, "gentle-ai", "managed-assets.json"), { schemaVersion: 1, assets: {} });
557
+ const bridge = bridgeFor(env, () => identity);
558
+
559
+ const before = snapshotTree(env.root);
560
+ for (const store of DESKTOP_CONFIG_STORES) await readStore(bridge, store);
561
+ bridge.snapshotState();
562
+ assert.deepEqual(snapshotTree(env.root), before, "a read is not a write: bytes, mtimes, and file set are unchanged");
563
+ });
564
+
565
+ test("the snapshot projects bounded per-store metadata and no store content", async (t) => {
566
+ const env = isolatedEnvironment(t);
567
+ writeJson(profilesFilePath(env.configHome), profilesFixture());
568
+ const bridge = bridgeFor(env);
569
+
570
+ const state = bridge.snapshotState() as { config: { stores: Array<Record<string, unknown>> } };
571
+
572
+ assert.deepEqual(
573
+ state.config.stores.map((entry) => entry.store),
574
+ [...DESKTOP_CONFIG_STORES],
575
+ );
576
+ for (const entry of state.config.stores) {
577
+ assert.deepEqual(Object.keys(entry).sort(), ["readOnly", "revision", "scope", "status", "store"]);
578
+ assert.match(String(entry.revision), /^sha256:[a-f0-9]{32}$/);
579
+ }
580
+ assert.equal(state.config.stores[0]!.status, "ok");
581
+ assert.equal(state.config.stores[1]!.status, "missing");
582
+ assert.equal(JSON.stringify(state).includes("claude-explore"), false, "raw store content never enters a snapshot");
583
+ assert.equal(JSON.stringify(state).includes(env.root), false);
584
+ assert.ok(JSON.stringify(state).length < 2048, "the projection stays bounded");
585
+ });
586
+
587
+ test("stores carry the documented read-only split", async (t) => {
588
+ const env = isolatedEnvironment(t);
589
+ const bridge = bridgeFor(env);
590
+ const readOnly: Record<string, boolean> = {};
591
+ for (const store of DESKTOP_CONFIG_STORES) readOnly[store] = (await readStore(bridge, store)).readOnly;
592
+ assert.deepEqual(readOnly, {
593
+ profiles: false,
594
+ models: true,
595
+ profile_fallbacks: false,
596
+ subagents: true,
597
+ pins: false,
598
+ managed_assets: true,
599
+ });
600
+ });
601
+
602
+ test("a host without a session cwd answers unavailable instead of guessing paths", async (t) => {
603
+ const env = isolatedEnvironment(t);
604
+ const bridge = new DesktopConfigBridge({ configHome: env.configHome, agentHome: env.agentHome });
605
+ bridge.attach({ mode: "rpc" } as unknown as ExtensionContext);
606
+
607
+ const outcome = await bridge.handle("get_config", { store: "profiles" });
608
+ assert.deepEqual(outcome, {
609
+ ok: false,
610
+ error: { code: "config_unavailable", message: "Config stores unavailable for this session" },
611
+ });
612
+ assert.deepEqual(bridge.snapshotState(), {}, "no session cwd means no truthful projection");
613
+
614
+ bridge.reset();
615
+ assert.deepEqual(await bridge.handle("get_config", { store: "profiles" }), {
616
+ ok: false,
617
+ error: { code: "config_unavailable", message: "Config stores unavailable for this session" },
618
+ });
619
+ });
620
+
621
+ // ---- Write contract: `set_config` over the authoritative owners ----
622
+
623
+ async function writeTargetRevision(bridge: DesktopConfigBridge, store: string, target = "global"): Promise<string> {
624
+ const data = await readStore(bridge, store);
625
+ const targets = data.writeTargets as Array<{ target: string; status: string; writeRevision: string }> | undefined;
626
+ assert.ok(targets, `${store} must expose its write targets`);
627
+ const entry = targets.find((candidate) => candidate.target === target);
628
+ assert.ok(entry, `${store} must expose the ${target} write target`);
629
+ assert.match(entry.writeRevision, /^sha256:[a-f0-9]{32}$/);
630
+ return entry.writeRevision;
631
+ }
632
+
633
+ async function setConfig(bridge: DesktopConfigBridge, params: Record<string, unknown>): Promise<any> {
634
+ const outcome = await bridge.handle("set_config", params);
635
+ assert.ok(outcome, "set_config must answer");
636
+ return outcome;
637
+ }
638
+
639
+ function assertError(outcome: any, code: string): void {
640
+ assert.equal(outcome.ok, false, `expected ${code}: ${JSON.stringify(outcome)}`);
641
+ assert.equal(outcome.error.code, code);
642
+ assert.equal(outcome.event, undefined, "a rejected write emits nothing");
643
+ }
644
+
645
+ function withProfile(name: string, model: string): Record<string, unknown> {
646
+ const fixture = profilesFixture();
647
+ return {
648
+ ...fixture,
649
+ profiles: { ...(fixture.profiles as Record<string, unknown>), [name]: { worker: { model } } },
650
+ };
651
+ }
652
+
653
+ test("profiles accepts a validated write and reports the resulting store", async (t) => {
654
+ const env = isolatedEnvironment(t);
655
+ const path = profilesFilePath(env.configHome);
656
+ writeJson(path, profilesFixture());
657
+ const bridge = bridgeFor(env);
658
+ const before = await readStore(bridge, "profiles");
659
+ const beforeWrite = await writeTargetRevision(bridge, "profiles");
660
+ const data = withProfile("extra", "openai/gpt-extra");
661
+
662
+ const outcome = await setConfig(bridge, { store: "profiles", data, expectedRevision: beforeWrite });
663
+
664
+ assert.equal(outcome.ok, true, JSON.stringify(outcome));
665
+ assert.equal(outcome.data.store, "profiles");
666
+ assert.equal(outcome.data.scope, "global");
667
+ assert.equal(outcome.data.readOnly, false);
668
+ assert.equal(outcome.data.status, "ok");
669
+ assert.equal(outcome.data.writeTarget, "global");
670
+ assert.equal(outcome.data.changed, true);
671
+ assert.deepEqual(Object.keys(outcome.data.value.profiles).sort(), ["extra", "ops", "team"]);
672
+ assert.notEqual(outcome.data.revision, before.revision, "the read revision moved");
673
+ assert.notEqual(outcome.data.writeRevision, beforeWrite, "the write revision moved");
674
+ assert.equal(
675
+ readFileSync(path, "utf8"),
676
+ serializeProfilesFile(normalizeProfilesFile(data)!.file),
677
+ "the store holds exactly the owner-serialized normalized data",
678
+ );
679
+ assert.equal(outcome.event?.name, "config_changed");
680
+ assert.deepEqual(outcome.event?.data, {
681
+ store: "profiles",
682
+ scope: "global",
683
+ writeTarget: "global",
684
+ revision: outcome.data.revision,
685
+ writeRevision: outcome.data.writeRevision,
686
+ source: "desktop",
687
+ });
688
+ assert.equal(JSON.stringify(outcome).includes(env.root), false, "no physical path crosses the contract");
689
+ });
690
+
691
+ test("profile writes wait for a running apply_profile instead of racing its store snapshot", async (t) => {
692
+ const env = isolatedEnvironment(t);
693
+ const path = profilesFilePath(env.configHome);
694
+ writeJson(path, profilesFixture());
695
+ const bridge = bridgeFor(env);
696
+ const beforeWrite = await writeTargetRevision(bridge, "profiles");
697
+ const bytes = readFileSync(path, "utf8");
698
+ assert.equal(beginDesktopProfileApply(), true);
699
+ t.after(() => endDesktopProfileApply());
700
+ assert.equal(beginDesktopProfileApply(), false, "only one apply holds the gate");
701
+ for (const store of ["profiles", "profile_fallbacks", "pins"]) {
702
+ const outcome = await setConfig(bridge, { store, data: store === "profiles" ? withProfile("extra", "openai/gpt-extra") : {}, expectedRevision: beforeWrite });
703
+ assertError(outcome, "profile_apply_busy");
704
+ assert.equal(outcome.event, undefined, store);
705
+ }
706
+ assert.equal(readFileSync(path, "utf8"), bytes, "a refused write leaves the store untouched");
707
+ await readStore(bridge, "profiles"); // reads still answer during an apply
708
+ endDesktopProfileApply();
709
+ const outcome = await setConfig(bridge, { store: "profiles", data: withProfile("extra", "openai/gpt-extra"), expectedRevision: beforeWrite });
710
+ assert.equal(outcome.ok, true, JSON.stringify(outcome));
711
+ });
712
+
713
+ test("profiles creates a missing store from its missing-state write revision", async (t) => {
714
+ const env = isolatedEnvironment(t);
715
+ const path = profilesFilePath(env.configHome);
716
+ const bridge = bridgeFor(env);
717
+ const missing = await readStore(bridge, "profiles");
718
+ assert.equal(missing.status, "missing");
719
+ const beforeWrite = await writeTargetRevision(bridge, "profiles");
720
+
721
+ const outcome = await setConfig(bridge, { store: "profiles", data: profilesFixture(), expectedRevision: beforeWrite });
722
+
723
+ assert.equal(outcome.ok, true, JSON.stringify(outcome));
724
+ assert.equal(outcome.data.changed, true);
725
+ assert.equal(outcome.data.status, "ok");
726
+ assert.notEqual(outcome.data.writeRevision, beforeWrite);
727
+ assert.equal(readFileSync(path, "utf8"), serializeProfilesFile(normalizeProfilesFile(profilesFixture())!.file));
728
+ });
729
+
730
+ test("profile_fallbacks writes normalized chains and refuses content the owner would drop", async (t) => {
731
+ const env = isolatedEnvironment(t);
732
+ const path = fallbacksFilePath(env.configHome);
733
+ const bridge = bridgeFor(env);
734
+ const data = {
735
+ kind: FALLBACKS_KIND,
736
+ version: FALLBACKS_VERSION,
737
+ profiles: { team: { worker: [{ model: "openai/gpt-fallback", thinking: "low" }] } },
738
+ };
739
+ const empty = await readStore(bridge, "profile_fallbacks");
740
+
741
+ const outcome = await setConfig(bridge, {
742
+ store: "profile_fallbacks",
743
+ data,
744
+ expectedRevision: await writeTargetRevision(bridge, "profile_fallbacks"),
745
+ });
746
+
747
+ assert.equal(outcome.ok, true, JSON.stringify(outcome));
748
+ assert.equal(outcome.data.scope, "global");
749
+ assert.equal(outcome.data.writeTarget, "global");
750
+ assert.equal(outcome.data.changed, true);
751
+ assert.notEqual(outcome.data.revision, empty.revision);
752
+ assert.deepEqual(outcome.data.value.profiles.team.worker, [{ model: "openai/gpt-fallback", thinking: "low" }]);
753
+ assert.equal(
754
+ readFileSync(path, "utf8"),
755
+ `${JSON.stringify(normalizeFallbacksFile(data), null, 2)}\n`,
756
+ "the store holds exactly the owner-normalized chains",
757
+ );
758
+ assert.equal(outcome.event?.name, "config_changed");
759
+
760
+ const before = snapshotTree(env.root);
761
+ for (const invalid of [
762
+ { kind: FALLBACKS_KIND, version: FALLBACKS_VERSION, profiles: { team: { worker: [] } } },
763
+ { kind: FALLBACKS_KIND, version: FALLBACKS_VERSION, profiles: { team: { worker: [{ model: "openai/gpt-a" }, { model: "openai/gpt-a" }] } } },
764
+ { kind: FALLBACKS_KIND, version: FALLBACKS_VERSION, profiles: { team: { worker: [{ model: "not a model" }] } } },
765
+ { kind: FALLBACKS_KIND, version: FALLBACKS_VERSION, profiles: {}, extra: true },
766
+ { kind: "gentle-pi.something_else", version: 1, profiles: {} },
767
+ ]) {
768
+ const rejected = await setConfig(bridge, {
769
+ store: "profile_fallbacks",
770
+ data: invalid,
771
+ expectedRevision: await writeTargetRevision(bridge, "profile_fallbacks"),
772
+ });
773
+ assertError(rejected, "invalid_data");
774
+ }
775
+ assert.deepEqual(snapshotTree(env.root), before, "rejected data never touches the store");
776
+ });
777
+
778
+ test("pins writes only the layer the request names", async (t) => {
779
+ const env = isolatedEnvironment(t);
780
+ writeJson(profilesFilePath(env.configHome), profilesFixture());
781
+ const identity: WorktreeIdentity = { root: env.workspace, commonDir: join(env.root, "git-common") };
782
+ const bridge = bridgeFor(env, () => identity);
783
+ const targets = (await readStore(bridge, "pins")).writeTargets;
784
+ assert.deepEqual(
785
+ targets.map((entry: any) => [entry.target, entry.status]),
786
+ [["local", "missing"], ["repo", "missing"]],
787
+ "both owner layers are write targets before either file exists",
788
+ );
789
+
790
+ const local = await setConfig(bridge, {
791
+ store: "pins",
792
+ data: { source: "local", profile: "ops" },
793
+ expectedRevision: targets[0].writeRevision,
794
+ });
795
+
796
+ assert.equal(local.ok, true, JSON.stringify(local));
797
+ assert.equal(local.data.scope, "local+repo");
798
+ assert.equal(local.data.writeTarget, "local");
799
+ assert.equal(local.data.changed, true);
800
+ assert.deepEqual(local.data.value.winner, { source: "local", profile: "ops" });
801
+ assert.equal(readFileSync(localProfilePinPath(identity.commonDir), "utf8"), serializeProfilePin("ops"));
802
+ assert.equal(existsSync(repoProfileDeclarationPath(identity.root)), false, "the other layer is untouched");
803
+ assert.equal(local.event?.name, "config_changed");
804
+ assert.equal(local.event?.data.writeTarget, "local");
805
+ assert.equal(JSON.stringify(local.data).includes(env.root), false, "no pin path crosses the contract");
806
+
807
+ const afterLocal = await readStore(bridge, "pins");
808
+ const repo = await setConfig(bridge, {
809
+ store: "pins",
810
+ data: { source: "repo", profile: "team" },
811
+ expectedRevision: afterLocal.writeTargets[1].writeRevision,
812
+ });
813
+
814
+ assert.equal(repo.ok, true, JSON.stringify(repo));
815
+ assert.equal(repo.data.writeTarget, "repo");
816
+ assert.equal(repo.data.changed, true);
817
+ assert.equal(readFileSync(repoProfileDeclarationPath(identity.root), "utf8"), serializeProfilePin("team"));
818
+ assert.equal(readFileSync(localProfilePinPath(identity.commonDir), "utf8"), serializeProfilePin("ops"));
819
+ assert.deepEqual(repo.data.value.winner, { source: "local", profile: "ops" }, "the local layer still wins the read");
820
+ });
821
+
822
+ test("stale or missing expectedRevision is a revision conflict without writes", async (t) => {
823
+ const env = isolatedEnvironment(t);
824
+ const path = profilesFilePath(env.configHome);
825
+ writeJson(path, profilesFixture());
826
+ const bridge = bridgeFor(env);
827
+ const revision = await writeTargetRevision(bridge, "profiles");
828
+ const data = { ...profilesFixture(), active: "ops" };
829
+ const before = snapshotTree(env.root);
830
+
831
+ for (const expectedRevision of [undefined, 42, "sha256:00000000000000000000000000000000"]) {
832
+ const params: Record<string, unknown> = { store: "profiles", data };
833
+ if (expectedRevision !== undefined) params.expectedRevision = expectedRevision;
834
+ assertError(await setConfig(bridge, params), "revision_conflict");
835
+ }
836
+ assert.deepEqual(snapshotTree(env.root), before, "a conflict never writes");
837
+
838
+ const applied = await setConfig(bridge, { store: "profiles", data, expectedRevision: revision });
839
+ assert.equal(applied.ok, true, JSON.stringify(applied));
840
+ const stale = await setConfig(bridge, { store: "profiles", data: profilesFixture(), expectedRevision: revision });
841
+ assertError(stale, "revision_conflict");
842
+ assert.equal((await readStore(bridge, "profiles")).value.active, "ops", "the stale write never applied");
843
+ });
844
+
845
+ test("invalid data never creates or modifies a file", async (t) => {
846
+ const env = isolatedEnvironment(t);
847
+ writeJson(profilesFilePath(env.configHome), profilesFixture());
848
+ const identity: WorktreeIdentity = { root: env.workspace, commonDir: join(env.root, "git-common") };
849
+ const bridge = bridgeFor(env, () => identity);
850
+ const before = snapshotTree(env.root);
851
+ const cases: Array<[string, unknown]> = [
852
+ ["profiles", []],
853
+ ["profiles", { kind: "gentle-pi.something_else", version: 1, profiles: {} }],
854
+ ["profiles", { kind: PROFILES_KIND, version: PROFILES_VERSION, profiles: { "bad name": { worker: { model: "openai/gpt-a" } } } }],
855
+ ["profiles", { kind: PROFILES_KIND, version: PROFILES_VERSION, profiles: { team: { "bad agent!": { model: "openai/gpt-a" } } } }],
856
+ ["profiles", { ...profilesFixture(), active: "ghost" }],
857
+ ["profiles", { ...profilesFixture(), profiles: { team: { explore: { model: "openai/gpt-a", effort: "high" } } } }],
858
+ ["profiles", { ...profilesFixture(), profiles: { team: { explore: { model: "openai/gpt-a", unknown_member: 1 } } } }],
859
+ ["profiles", { ...profilesFixture(), workflow: { team: { orchestratorMode: "organic" } } }],
860
+ ["profile_fallbacks", { kind: FALLBACKS_KIND, version: FALLBACKS_VERSION, profiles: { team: { worker: [{ model: "openai/gpt-a" }, { model: "openai/gpt-a" }] } } }],
861
+ ["pins", { source: "local", profile: "ghost" }],
862
+ ["pins", { source: "global", profile: "team" }],
863
+ ["pins", { source: "local", profile: "bad name" }],
864
+ ["pins", { profile: "team" }],
865
+ ["pins", { source: "local", profile: "team", path: "/etc/passwd" }],
866
+ ["pins", "local"],
867
+ ];
868
+ for (const [store, data] of cases) {
869
+ const revision = await writeTargetRevision(bridge, store, store === "pins" ? "local" : "global");
870
+ const outcome = await setConfig(bridge, { store, data, expectedRevision: revision });
871
+ assertError(outcome, "invalid_data");
872
+ assert.equal(JSON.stringify(outcome).includes("/etc/passwd"), false, "no path is echoed back");
873
+ }
874
+ assert.deepEqual(snapshotTree(env.root), before, "no rejected write creates or modifies a store");
875
+ });
876
+
877
+ test("read-only and unknown stores reject writes without creating anything", async (t) => {
878
+ const env = isolatedEnvironment(t);
879
+ const bridge = bridgeFor(env);
880
+ const before = snapshotTree(env.root);
881
+
882
+ for (const store of ["models", "subagents", "managed_assets"]) {
883
+ const outcome = await setConfig(bridge, { store, data: {}, expectedRevision: "sha256:x" });
884
+ assertError(outcome, "read_only");
885
+ }
886
+ assertError(await setConfig(bridge, { store: "auth", data: {}, expectedRevision: "sha256:x" }), "unknown_store");
887
+ assert.deepEqual(snapshotTree(env.root), before, "no read-only store is created or materialized");
888
+ });
889
+
890
+ test("set_config rejects extra keys, missing data, and physical paths", async (t) => {
891
+ const env = isolatedEnvironment(t);
892
+ writeJson(profilesFilePath(env.configHome), profilesFixture());
893
+ const bridge = bridgeFor(env);
894
+ const revision = await writeTargetRevision(bridge, "profiles");
895
+ const data = { ...profilesFixture(), active: "ops" };
896
+ const before = snapshotTree(env.root);
897
+
898
+ for (const params of [
899
+ { store: "profiles", data, expectedRevision: revision, path: join(env.configHome, "profiles.json") },
900
+ { store: "profiles", data, expectedRevision: revision, scope: "global" },
901
+ { store: "profiles", data, expectedRevision: revision, file: "profiles.json" },
902
+ { store: "profiles", data, expectedRevision: revision, physical_path: "/etc/passwd" },
903
+ { store: "profiles", expectedRevision: revision },
904
+ { store: 42, data, expectedRevision: revision },
905
+ ]) {
906
+ const outcome = await setConfig(bridge, params as Record<string, unknown>);
907
+ assertError(outcome, "invalid_request");
908
+ assert.equal(JSON.stringify(outcome).includes(env.root), false, "no physical path is echoed back");
909
+ }
910
+ assert.deepEqual(snapshotTree(env.root), before, "a malformed request never writes");
911
+ });
912
+
913
+ test("an identical write is a no-op with untouched bytes and no event", async (t) => {
914
+ const env = isolatedEnvironment(t);
915
+ const path = profilesFilePath(env.configHome);
916
+ writeJson(path, profilesFixture());
917
+ const bridge = bridgeFor(env);
918
+ const before = { text: readFileSync(path, "utf8"), mtimeMs: statSync(path).mtimeMs };
919
+
920
+ const outcome = await setConfig(bridge, {
921
+ store: "profiles",
922
+ data: profilesFixture(),
923
+ expectedRevision: await writeTargetRevision(bridge, "profiles"),
924
+ });
925
+
926
+ assert.equal(outcome.ok, true, JSON.stringify(outcome));
927
+ assert.equal(outcome.data.changed, false);
928
+ assert.equal(outcome.data.readOnly, false);
929
+ assert.equal(outcome.data.status, "ok");
930
+ assert.equal(outcome.event, undefined, "a no-op emits no event");
931
+ assert.deepEqual(
932
+ { text: readFileSync(path, "utf8"), mtimeMs: statSync(path).mtimeMs },
933
+ before,
934
+ "identical content is not rewritten",
935
+ );
936
+ });
937
+
938
+ test("writes require a bound session with a working directory", async (t) => {
939
+ const env = isolatedEnvironment(t);
940
+ const before = snapshotTree(env.root);
941
+ const bridge = new DesktopConfigBridge({ configHome: env.configHome, agentHome: env.agentHome });
942
+ bridge.attach({ mode: "rpc" } as unknown as ExtensionContext);
943
+
944
+ assertError(
945
+ await setConfig(bridge, { store: "profiles", data: profilesFixture(), expectedRevision: "sha256:x" }),
946
+ "config_unavailable",
947
+ );
948
+ assert.equal(bridge.handle("get_permission_mode", {}), undefined, "other domains still fall through");
949
+ assert.equal(bridge.handle("set_permission_mode", { mode: "auto" }), undefined);
950
+ bridge.reset();
951
+ assertError(
952
+ await setConfig(bridge, { store: "profiles", data: profilesFixture(), expectedRevision: "sha256:x" }),
953
+ "config_unavailable",
954
+ );
955
+ assert.deepEqual(snapshotTree(env.root), before, "nothing is written without a session cwd");
956
+ });
957
+
958
+ test("pins write only inside a resolvable worktree", async (t) => {
959
+ const env = isolatedEnvironment(t);
960
+ writeJson(profilesFilePath(env.configHome), profilesFixture());
961
+ const bridge = bridgeFor(env, () => undefined);
962
+
963
+ assertError(
964
+ await setConfig(bridge, { store: "pins", data: { source: "repo", profile: "team" }, expectedRevision: "sha256:x" }),
965
+ "config_unavailable",
966
+ );
967
+ assertError(
968
+ await setConfig(bridge, { store: "pins", data: { source: "repo", profile: null }, expectedRevision: "sha256:x" }),
969
+ "config_unavailable",
970
+ );
971
+ assert.equal(existsSync(repoProfileDeclarationPath(env.workspace)), false, "no target is invented without a worktree");
972
+ });
973
+
974
+ test("pins clears the layer the request names and reports the remaining store", async (t) => {
975
+ const env = isolatedEnvironment(t);
976
+ writeJson(profilesFilePath(env.configHome), profilesFixture());
977
+ const identity: WorktreeIdentity = { root: env.workspace, commonDir: join(env.root, "git-common") };
978
+ writeJson(localProfilePinPath(identity.commonDir), pin("ops"));
979
+ writeJson(repoProfileDeclarationPath(identity.root), pin("team"));
980
+ const bridge = bridgeFor(env, () => identity);
981
+ const repoBytes = readFileSync(repoProfileDeclarationPath(identity.root), "utf8");
982
+
983
+ const targets = (await readStore(bridge, "pins")).writeTargets;
984
+ assert.deepEqual(targets.map((entry: any) => [entry.target, entry.status]), [["local", "ok"], ["repo", "ok"]]);
985
+
986
+ const cleared = await setConfig(bridge, {
987
+ store: "pins",
988
+ data: { source: "local", profile: null },
989
+ expectedRevision: targets[0].writeRevision,
990
+ });
991
+
992
+ assert.equal(cleared.ok, true, JSON.stringify(cleared));
993
+ assert.equal(cleared.data.store, "pins");
994
+ assert.equal(cleared.data.scope, "local+repo");
995
+ assert.equal(cleared.data.readOnly, false);
996
+ assert.equal(cleared.data.writeTarget, "local");
997
+ assert.equal(cleared.data.changed, true);
998
+ assert.deepEqual(cleared.data.value.winner, { source: "repo", profile: "team" }, "the lower layer now resolves");
999
+ assert.deepEqual(cleared.data.layers, [
1000
+ { source: "local", status: "missing" },
1001
+ { source: "repo", status: "ok" },
1002
+ ]);
1003
+ assert.equal(existsSync(localProfilePinPath(identity.commonDir)), false, "the cleared layer file is gone");
1004
+ assert.equal(
1005
+ readFileSync(repoProfileDeclarationPath(identity.root), "utf8"),
1006
+ repoBytes,
1007
+ "the layer the request did not name is untouched",
1008
+ );
1009
+ assert.equal(cleared.event?.name, "config_changed");
1010
+ assert.deepEqual(cleared.event?.data, {
1011
+ store: "pins",
1012
+ scope: "local+repo",
1013
+ writeTarget: "local",
1014
+ revision: cleared.data.revision,
1015
+ writeRevision: cleared.data.writeRevision,
1016
+ source: "desktop",
1017
+ });
1018
+ assert.equal(JSON.stringify(cleared).includes(env.root), false, "no pin path crosses the contract");
1019
+
1020
+ // The repo layer needs its own write revision, and the winner changes again.
1021
+ const repoRevision = (await readStore(bridge, "pins")).writeTargets[1].writeRevision;
1022
+ const repo = await setConfig(bridge, {
1023
+ store: "pins",
1024
+ data: { source: "repo", profile: null },
1025
+ expectedRevision: repoRevision,
1026
+ });
1027
+ assert.equal(repo.ok, true, JSON.stringify(repo));
1028
+ assert.equal(repo.data.writeTarget, "repo");
1029
+ assert.equal(repo.data.changed, true);
1030
+ assert.equal(existsSync(repoProfileDeclarationPath(identity.root)), false);
1031
+ assert.equal(repo.data.value.resolved, false);
1032
+ assert.equal((await readStore(bridge, "pins")).status, "missing");
1033
+ });
1034
+
1035
+ test("clearing an already-missing pin layer is a no-op with no event", async (t) => {
1036
+ const env = isolatedEnvironment(t);
1037
+ writeJson(profilesFilePath(env.configHome), profilesFixture());
1038
+ const identity: WorktreeIdentity = { root: env.workspace, commonDir: join(env.root, "git-common") };
1039
+ const bridge = bridgeFor(env, () => identity);
1040
+ const before = snapshotTree(env.root);
1041
+
1042
+ const outcome = await setConfig(bridge, {
1043
+ store: "pins",
1044
+ data: { source: "local", profile: null },
1045
+ expectedRevision: (await readStore(bridge, "pins")).writeTargets[0].writeRevision,
1046
+ });
1047
+
1048
+ assert.equal(outcome.ok, true, JSON.stringify(outcome));
1049
+ assert.equal(outcome.data.changed, false);
1050
+ assert.equal(outcome.event, undefined, "clearing nothing emits nothing");
1051
+ assert.deepEqual(snapshotTree(env.root), before, "a no-op clear creates and removes nothing");
1052
+
1053
+ // A layer that exists but is not a readable pin is still removed by an explicit clear.
1054
+ mkdirSync(dirname(localProfilePinPath(identity.commonDir)), { recursive: true });
1055
+ writeFileSync(localProfilePinPath(identity.commonDir), "{ broken\n");
1056
+ const broken = await setConfig(bridge, {
1057
+ store: "pins",
1058
+ data: { source: "local", profile: null },
1059
+ expectedRevision: (await readStore(bridge, "pins")).writeTargets[0].writeRevision,
1060
+ });
1061
+ assert.equal(broken.ok, true, JSON.stringify(broken));
1062
+ assert.equal(broken.data.changed, true);
1063
+ assert.equal(existsSync(localProfilePinPath(identity.commonDir)), false);
1064
+ });
1065
+
1066
+ test("a clear with a stale or missing revision is a conflict without writes", async (t) => {
1067
+ const env = isolatedEnvironment(t);
1068
+ writeJson(profilesFilePath(env.configHome), profilesFixture());
1069
+ const identity: WorktreeIdentity = { root: env.workspace, commonDir: join(env.root, "git-common") };
1070
+ writeJson(localProfilePinPath(identity.commonDir), pin("ops"));
1071
+ writeJson(repoProfileDeclarationPath(identity.root), pin("team"));
1072
+ const bridge = bridgeFor(env, () => identity);
1073
+ const targets = (await readStore(bridge, "pins")).writeTargets;
1074
+ const before = snapshotTree(env.root);
1075
+ const repoBytes = readFileSync(repoProfileDeclarationPath(identity.root), "utf8");
1076
+
1077
+ // Another layer's revision is not this layer's precondition.
1078
+ assertError(
1079
+ await setConfig(bridge, { store: "pins", data: { source: "local", profile: null }, expectedRevision: targets[1].writeRevision }),
1080
+ "revision_conflict",
1081
+ );
1082
+ assertError(
1083
+ await setConfig(bridge, { store: "pins", data: { source: "local", profile: null } }),
1084
+ "revision_conflict",
1085
+ );
1086
+ assert.deepEqual(snapshotTree(env.root), before, "a conflicted clear removes nothing");
1087
+
1088
+ const applied = await setConfig(bridge, {
1089
+ store: "pins",
1090
+ data: { source: "local", profile: null },
1091
+ expectedRevision: targets[0].writeRevision,
1092
+ });
1093
+ assert.equal(applied.ok, true, JSON.stringify(applied));
1094
+ assertError(
1095
+ await setConfig(bridge, { store: "pins", data: { source: "repo", profile: null }, expectedRevision: targets[0].writeRevision }),
1096
+ "revision_conflict",
1097
+ );
1098
+ assert.equal(
1099
+ readFileSync(repoProfileDeclarationPath(identity.root), "utf8"),
1100
+ repoBytes,
1101
+ "the stale clear left the other layer in place",
1102
+ );
1103
+ });
1104
+
1105
+ test("pins rejects a null-clearing shape that is not explicit", async (t) => {
1106
+ const env = isolatedEnvironment(t);
1107
+ writeJson(profilesFilePath(env.configHome), profilesFixture());
1108
+ const identity: WorktreeIdentity = { root: env.workspace, commonDir: join(env.root, "git-common") };
1109
+ const bridge = bridgeFor(env, () => identity);
1110
+ const before = snapshotTree(env.root);
1111
+ const revision = (await readStore(bridge, "pins")).writeTargets[0].writeRevision;
1112
+
1113
+ for (const data of [
1114
+ { source: "local" },
1115
+ { source: "local", profile: 7 },
1116
+ { source: "local", profile: "" },
1117
+ { source: "local", profile: "bad name" },
1118
+ { source: "local", profile: [] },
1119
+ { source: "local", profile: "ghost" },
1120
+ { profile: null },
1121
+ { source: "global", profile: null },
1122
+ { source: "local", profile: null, path: "/etc/passwd" },
1123
+ ]) {
1124
+ const outcome = await setConfig(bridge, { store: "pins", data, expectedRevision: revision });
1125
+ assertError(outcome, "invalid_data");
1126
+ assert.equal(JSON.stringify(outcome).includes("/etc/passwd"), false);
1127
+ }
1128
+ assert.deepEqual(snapshotTree(env.root), before, "a rejected shape never creates or removes a pin");
1129
+ });
1130
+
1131
+ test("an owner write failure is a typed write_failed with no path and no event", async (t) => {
1132
+ const env = isolatedEnvironment(t);
1133
+ const path = profilesFilePath(env.configHome);
1134
+ // A hostile but real filesystem shape: the store path is a directory, so the
1135
+ // owner's atomic rename cannot land and the write throws.
1136
+ mkdirSync(path, { recursive: true });
1137
+ writeFileSync(join(path, "marker"), "x");
1138
+ const bridge = bridgeFor(env);
1139
+ const target = await writeTargetRevision(bridge, "profiles");
1140
+ const before = snapshotTree(env.root);
1141
+
1142
+ const outcome = await setConfig(bridge, { store: "profiles", data: profilesFixture(), expectedRevision: target });
1143
+
1144
+ assert.equal(outcome.ok, false, JSON.stringify(outcome));
1145
+ assert.equal(outcome.error.code, "write_failed");
1146
+ assert.equal(outcome.error.message, "Config store write failed", "the message is fixed, not owner detail");
1147
+ assert.equal(outcome.event, undefined, "a failed write emits no event");
1148
+ const wire = JSON.stringify(outcome);
1149
+ assert.equal(wire.includes(env.root), false, "no physical path leaks");
1150
+ for (const leak of ["EISDIR", "ENOTDIR", "EPERM", "EACCES", "EEXIST", "EROFS", "errno", "syscall", "profiles.json"]) {
1151
+ assert.equal(wire.includes(leak), false, `no OS detail leaks: ${leak}`);
1152
+ }
1153
+ assert.deepEqual(snapshotTree(env.root), before, "the failed write leaves the tree exactly as it was, temp file included");
1154
+ });
1155
+
1156
+ test("pins replaces an unreadable layer explicitly, and invalid revisions stay coarse", async (t) => {
1157
+ const env = isolatedEnvironment(t);
1158
+ writeJson(profilesFilePath(env.configHome), profilesFixture());
1159
+ const identity: WorktreeIdentity = { root: env.workspace, commonDir: join(env.root, "git-common") };
1160
+ const path = localProfilePinPath(identity.commonDir);
1161
+ mkdirSync(dirname(path), { recursive: true });
1162
+ writeFileSync(path, "{ broken\n");
1163
+ const bridge = bridgeFor(env, () => identity);
1164
+ const targets = (await readStore(bridge, "pins")).writeTargets;
1165
+ assert.equal(targets[0].status, "invalid");
1166
+
1167
+ // Two different broken contents share one write revision: the invalid-state digest
1168
+ // covers only `{store, target, status}`, so this guard is deliberately coarse.
1169
+ writeFileSync(path, "[different, broken]\n");
1170
+ const rewritten = (await readStore(bridge, "pins")).writeTargets;
1171
+ assert.equal(rewritten[0].writeRevision, targets[0].writeRevision, "broken-to-broken is invisible to the guard");
1172
+
1173
+ const outcome = await setConfig(bridge, {
1174
+ store: "pins",
1175
+ data: { source: "local", profile: "ops" },
1176
+ expectedRevision: targets[0].writeRevision,
1177
+ });
1178
+
1179
+ assert.equal(outcome.ok, true, JSON.stringify(outcome));
1180
+ assert.equal(outcome.data.changed, true);
1181
+ assert.deepEqual(outcome.data.layers, [
1182
+ { source: "local", status: "ok" },
1183
+ { source: "repo", status: "missing" },
1184
+ ]);
1185
+ assert.deepEqual(outcome.data.value.winner, { source: "local", profile: "ops" });
1186
+ assert.equal(readFileSync(path, "utf8"), serializeProfilePin("ops"), "the broken layer is replaced, not merged");
1187
+ assert.equal(outcome.event?.name, "config_changed");
1188
+ assert.equal(outcome.event?.data.writeTarget, "local");
1189
+ });
1190
+
1191
+ test("set_config validates in one documented order", async (t) => {
1192
+ const env = isolatedEnvironment(t);
1193
+ const bridge = bridgeFor(env);
1194
+ const revision = "sha256:00000000000000000000000000000000";
1195
+ const before = snapshotTree(env.root);
1196
+
1197
+ // 1. Envelope: exact keys, `store` as a string, and `data` present.
1198
+ assertError(await setConfig(bridge, { store: "models" }), "invalid_request");
1199
+ assertError(await setConfig(bridge, { store: "auth" }), "invalid_request");
1200
+ assertError(await setConfig(bridge, { store: 42, data: {}, expectedRevision: revision }), "invalid_request");
1201
+ // 2. Store identity.
1202
+ assertError(await setConfig(bridge, { store: "auth", data: {}, expectedRevision: revision }), "unknown_store");
1203
+ // 3. Mutability, before the payload is inspected or the revision is read.
1204
+ assertError(await setConfig(bridge, { store: "models", data: "not an object", expectedRevision: 42 }), "read_only");
1205
+ // 4. A usable revision, before the payload is validated.
1206
+ assertError(await setConfig(bridge, { store: "profiles", data: [] }), "revision_conflict");
1207
+ assertError(await setConfig(bridge, { store: "profiles", data: [], expectedRevision: "" }), "revision_conflict");
1208
+ // 5. Session roots.
1209
+ assertError(
1210
+ await (async () => {
1211
+ const unbound = new DesktopConfigBridge({ configHome: env.configHome, agentHome: env.agentHome });
1212
+ unbound.attach({ mode: "rpc" } as unknown as ExtensionContext);
1213
+ return setConfig(unbound, { store: "profiles", data: profilesFixture(), expectedRevision: revision });
1214
+ })(),
1215
+ "config_unavailable",
1216
+ );
1217
+ // 6. Payload, 7. revision comparison.
1218
+ assertError(await setConfig(bridge, { store: "profiles", data: [], expectedRevision: revision }), "invalid_data");
1219
+ assertError(await setConfig(bridge, { store: "profiles", data: profilesFixture(), expectedRevision: revision }), "revision_conflict");
1220
+ assert.deepEqual(snapshotTree(env.root), before, "no rejected request writes");
1221
+ });
1222
+
1223
+ test("a pin write is not claimed after its worktree disappears", async (t) => {
1224
+ const env = isolatedEnvironment(t);
1225
+ writeJson(profilesFilePath(env.configHome), profilesFixture());
1226
+ const identity: WorktreeIdentity = { root: env.workspace, commonDir: join(env.root, "git-common") };
1227
+ let current: WorktreeIdentity | undefined = identity;
1228
+ const bridge = bridgeFor(env, () => current);
1229
+ const targets = (await readStore(bridge, "pins")).writeTargets;
1230
+
1231
+ const written = await setConfig(bridge, {
1232
+ store: "pins",
1233
+ data: { source: "local", profile: "ops" },
1234
+ expectedRevision: targets[0].writeRevision,
1235
+ });
1236
+ assert.equal(written.ok, true, JSON.stringify(written));
1237
+
1238
+ // The session survives its worktree: reads must stop claiming a pin target.
1239
+ current = undefined;
1240
+ const after = await readStore(bridge, "pins");
1241
+ assert.equal(after.status, "invalid");
1242
+ assert.deepEqual(after.value, { resolved: false, invalid: [], stale: [], reason: "worktree_unresolved" });
1243
+ assert.deepEqual(after.writeTargets, [], "no target is reported for a vanished worktree");
1244
+ assert.equal(JSON.stringify(after).includes("ops"), false, "no stale pin claim survives the worktree");
1245
+ assertError(
1246
+ await setConfig(bridge, { store: "pins", data: { source: "local", profile: null }, expectedRevision: written.data.writeRevision }),
1247
+ "config_unavailable",
1248
+ );
1249
+ assert.equal(
1250
+ readFileSync(localProfilePinPath(identity.commonDir), "utf8"),
1251
+ serializeProfilePin("ops"),
1252
+ "the pin file itself is untouched; only the session lost its target",
1253
+ );
1254
+ });
1255
+
1256
+ // ---- Transport-level coverage: capabilities, dispatch, and prior slices ----
1257
+
1258
+ type WidgetCall = { key: string; lines: string[] };
1259
+
1260
+ function isolatedTransport(t: test.TestContext) {
1261
+ const env = isolatedEnvironment(t);
1262
+ const previous = {
1263
+ host: process.env[INTERACTIVE_HOST_ENV],
1264
+ configHome: process.env.GENTLE_PI_CONFIG_HOME,
1265
+ agentHome: process.env.GENTLE_PI_AGENT_HOME,
1266
+ };
1267
+ process.env[INTERACTIVE_HOST_ENV] = "1";
1268
+ process.env.GENTLE_PI_CONFIG_HOME = env.configHome;
1269
+ process.env.GENTLE_PI_AGENT_HOME = env.agentHome;
1270
+ t.after(() => {
1271
+ const restore = (key: string, value: string | undefined) => {
1272
+ if (value === undefined) delete process.env[key];
1273
+ else process.env[key] = value;
1274
+ };
1275
+ restore(INTERACTIVE_HOST_ENV, previous.host);
1276
+ restore("GENTLE_PI_CONFIG_HOME", previous.configHome);
1277
+ restore("GENTLE_PI_AGENT_HOME", previous.agentHome);
1278
+ });
1279
+
1280
+ const commands = new Map<string, { handler: (args: string, ctx: any) => Promise<void> }>();
1281
+ const events = new Map<string, (event: unknown, ctx: any) => void>();
1282
+ const pi = {
1283
+ registerCommand(name: string, command: any) { commands.set(name, command); },
1284
+ on(name: string, handler: any) { events.set(name, handler); },
1285
+ } as unknown as ExtensionAPI;
1286
+ desktopRpc(pi);
1287
+ const widgets: WidgetCall[] = [];
1288
+ const ctx = {
1289
+ mode: "rpc",
1290
+ cwd: env.workspace,
1291
+ ui: { setWidget(key: string, lines: string[]) { widgets.push({ key, lines }); } },
1292
+ };
1293
+ return {
1294
+ env,
1295
+ ctx,
1296
+ widgets,
1297
+ events,
1298
+ start() { events.get("session_start")?.({}, ctx); },
1299
+ async invoke(method: string, params: Record<string, unknown> = {}, requestId = `request-${method}`) {
1300
+ await commands.get("gentle:desktop")!.handler(
1301
+ JSON.stringify({ schema: DESKTOP_RPC_SCHEMA, requestId, method, params }),
1302
+ ctx,
1303
+ );
1304
+ },
1305
+ last(): any {
1306
+ const call = widgets.at(-1)!;
1307
+ assert.equal(call.key, DESKTOP_RPC_WIDGET);
1308
+ return JSON.parse(call.lines[0]!);
1309
+ },
1310
+ };
1311
+ }
1312
+
1313
+ test("capabilities advertise the wired config read and write surface", async (t) => {
1314
+ const app = isolatedTransport(t);
1315
+ app.start();
1316
+ await app.invoke("capabilities");
1317
+ const response = app.last();
1318
+ assert.deepEqual(response.data.methods, [
1319
+ "capabilities",
1320
+ "get_snapshot",
1321
+ "get_config",
1322
+ "set_config",
1323
+ "get_permission_mode",
1324
+ "set_permission_mode",
1325
+ "get_subscription_usage",
1326
+ "refresh_subscription_usage",
1327
+ "get_design_canvas",
1328
+ "list_jobs",
1329
+ "cancel_job",
1330
+ "apply_profile",
1331
+ "list_subagents",
1332
+ "cancel_subagent",
1333
+ ]);
1334
+ assert.deepEqual(response.data.events, ["config_changed", "permission_mode_changed", "rate_limit", "design_canvas", "jobs_update", "profile_applied", "agents_update"]);
1335
+ });
1336
+
1337
+ test("get_config answers through the transport with no physical path in the response", async (t) => {
1338
+ const app = isolatedTransport(t);
1339
+ writeJson(profilesFilePath(app.env.configHome), profilesFixture());
1340
+ app.start();
1341
+
1342
+ await app.invoke("get_config", { store: "profiles" });
1343
+ const response = app.last();
1344
+ assert.equal(response.kind, "response");
1345
+ assert.equal(response.ok, true);
1346
+ assert.equal(response.data.store, "profiles");
1347
+ assert.equal(response.data.status, "ok");
1348
+ assert.equal(response.data.readOnly, false);
1349
+ assert.match(response.data.revision, /^sha256:[a-f0-9]{32}$/);
1350
+ assert.equal(JSON.stringify(response).includes(app.env.root), false);
1351
+
1352
+ await app.invoke("get_config", { store: "profiles", path: "/etc/passwd" });
1353
+ const rejected = app.last();
1354
+ assert.equal(rejected.ok, false);
1355
+ assert.equal(rejected.error.code, "invalid_request");
1356
+ });
1357
+
1358
+ test("the snapshot exposes the config projection and keeps the permission slice working", async (t) => {
1359
+ const app = isolatedTransport(t);
1360
+ app.start();
1361
+
1362
+ await app.invoke("get_snapshot");
1363
+ const snapshot = app.last();
1364
+ assert.equal(snapshot.data.schema, DESKTOP_RPC_SCHEMA);
1365
+ assert.equal(snapshot.data.sequence, 0);
1366
+ assert.deepEqual(
1367
+ snapshot.data.state.config.stores.map((entry: any) => entry.store),
1368
+ [...DESKTOP_CONFIG_STORES],
1369
+ );
1370
+ assert.equal(JSON.stringify(snapshot).includes(app.env.root), false);
1371
+
1372
+ // The dispatcher must still fall through to the permission bridge.
1373
+ await app.invoke("get_permission_mode");
1374
+ const permission = app.last();
1375
+ assert.equal(permission.ok, false);
1376
+ assert.equal(permission.error.code, "permission_unavailable", "no owner extension in this process");
1377
+ });
1378
+
1379
+ test("set_config answers before exactly one config_changed and the snapshot reflects it", async (t) => {
1380
+ const app = isolatedTransport(t);
1381
+ writeJson(profilesFilePath(app.env.configHome), profilesFixture());
1382
+ app.start();
1383
+
1384
+ await app.invoke("get_config", { store: "profiles" }, "read-1");
1385
+ const read = app.last();
1386
+ assert.equal(read.ok, true);
1387
+ const revision = read.data.writeTargets[0].writeRevision;
1388
+
1389
+ await app.invoke("set_config", { store: "profiles", data: { ...profilesFixture(), active: "ops" }, expectedRevision: revision }, "write-1");
1390
+ assert.equal(app.widgets.length, 3, "a read, its response, and one event");
1391
+ const response = JSON.parse(app.widgets[1]!.lines[0]!);
1392
+ const event = JSON.parse(app.widgets[2]!.lines[0]!);
1393
+ assert.equal(response.kind, "response");
1394
+ assert.equal(response.requestId, "write-1");
1395
+ assert.equal(response.data.changed, true);
1396
+ assert.equal(response.data.writeTarget, "global");
1397
+
1398
+ assert.equal(event.kind, "event");
1399
+ assert.equal(event.event, "config_changed");
1400
+ assert.equal(event.seq, 1);
1401
+ assert.deepEqual(event.data, {
1402
+ store: "profiles",
1403
+ scope: "global",
1404
+ writeTarget: "global",
1405
+ revision: response.data.revision,
1406
+ writeRevision: response.data.writeRevision,
1407
+ source: "desktop",
1408
+ });
1409
+ assert.equal(JSON.stringify([response, event]).includes(app.env.root), false);
1410
+
1411
+ await app.invoke("get_snapshot", {}, "snap-1");
1412
+ assert.equal(app.last().data.sequence, 1, "a delivered event advances the sequence");
1413
+ assert.equal(app.last().data.state.config.stores[0].status, "ok");
1414
+
1415
+ const published = app.widgets.length;
1416
+ await app.invoke("set_config", { store: "profiles", data: profilesFixture(), expectedRevision: revision }, "write-2");
1417
+ assert.equal(app.last().error.code, "revision_conflict");
1418
+ assert.equal(app.widgets.length, published + 1, "a conflict publishes only its response");
1419
+ });
1420
+
1421
+ test("a stopped session answers nothing and writes nothing", async (t) => {
1422
+ const app = isolatedTransport(t);
1423
+ writeJson(profilesFilePath(app.env.configHome), profilesFixture());
1424
+ app.start();
1425
+ await app.invoke("get_config", { store: "profiles" }, "read-1");
1426
+ const revision = app.last().data.writeTargets[0].writeRevision;
1427
+ const before = snapshotTree(app.env.root);
1428
+
1429
+ app.events.get("session_shutdown")?.({}, app.ctx);
1430
+ await app.invoke("set_config", { store: "profiles", data: withProfile("late", "openai/gpt-late"), expectedRevision: revision }, "write-1");
1431
+
1432
+ assert.equal(app.widgets.length, 1, "a stopped router publishes nothing");
1433
+ assert.deepEqual(snapshotTree(app.env.root), before, "a stopped session never writes");
1434
+ });
1435
+
1436
+ function snapshotTree(root: string): Record<string, string> {
1437
+ const tree: Record<string, string> = {};
1438
+ const walk = (directory: string) => {
1439
+ for (const entry of readdirSync(directory, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name))) {
1440
+ const path = join(directory, entry.name);
1441
+ if (entry.isDirectory()) {
1442
+ tree[`${path}/`] = "dir";
1443
+ walk(path);
1444
+ continue;
1445
+ }
1446
+ const stat = statSync(path);
1447
+ tree[path] = `${stat.size}:${stat.mtimeMs}:${readFileSync(path, "utf8")}`;
1448
+ }
1449
+ };
1450
+ walk(root);
1451
+ return tree;
1452
+ }