gentle-pi 4.7.0 → 4.9.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 (617) hide show
  1. package/README.md +115 -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 +14 -13
  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 +476 -0
  13. package/assets/design-canvas/canvas-boot.js +219 -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 +397 -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 +219 -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 +351 -0
  30. package/assets/design-canvas/canvas-sizes.js +524 -0
  31. package/assets/design-canvas/canvas-store.js +167 -0
  32. package/assets/design-canvas/canvas-theme.js +69 -0
  33. package/assets/design-canvas/canvas-tokens.js +674 -0
  34. package/assets/design-canvas/canvas-ui.js +24 -0
  35. package/assets/design-canvas/canvas-view.js +184 -0
  36. package/assets/design-canvas/canvas.css +773 -17
  37. package/assets/design-canvas/canvas.js +2 -1506
  38. package/assets/design-canvas/index.html +120 -36
  39. package/assets/design-canvas/inspector.js +574 -21
  40. package/assets/design-canvas/theme-early.js +10 -0
  41. package/assets/install-wizard/wizard.js +5 -1
  42. package/assets/migrations/agent-body-history.json +30 -0
  43. package/assets/orchestrator-delegation-reference.md +8 -14
  44. package/assets/orchestrator-delegation.md +5 -9
  45. package/assets/orchestrator-full-delegation-card.md +11 -16
  46. package/assets/orchestrator-full-delegation.md +9 -9
  47. package/assets/orchestrator-memory.md +4 -4
  48. package/assets/orchestrator-prompts.md +3 -31
  49. package/assets/orchestrator-quota-recovery.md +5 -0
  50. package/assets/orchestrator-skills.md +13 -12
  51. package/assets/orchestrator-tracking.md +13 -17
  52. package/assets/orchestrator-verification.md +12 -10
  53. package/assets/orchestrator-writer.md +13 -13
  54. package/assets/orchestrator.md +20 -24
  55. package/bin/gentle-shell.mjs +205 -10
  56. package/contracts/review-provider-contract-mirror/provider-contract.lock.json +8 -9
  57. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.6.0}/bundle/manifest.json +3 -3
  58. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.6.0}/bundle/orchestration/pi.md +2 -1
  59. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.6.0}/bundle/routing/pi.md +16 -16
  60. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.6.0}/generated/provider-capabilities.baseline.json +3 -3
  61. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.6.0}/generated/provider-roles.baseline.json +1 -1
  62. package/docs/assets/brand/sponsor-banner.svg +60 -0
  63. package/docs/assets/features/gentle-tower.png +0 -0
  64. package/docs/auto-permission-answers.md +1 -1
  65. package/docs/bundled-install.md +14 -6
  66. package/docs/delegated-verification.md +23 -5
  67. package/docs/desktop-feed.md +303 -0
  68. package/docs/desktop-rpc.md +1931 -0
  69. package/docs/fast-mode.md +2 -2
  70. package/docs/gentle-agents-activity.md +26 -0
  71. package/docs/gentle-shell-desktop.md +465 -0
  72. package/docs/gentle-shell.md +102 -17
  73. package/docs/images/desktop/chat.png +0 -0
  74. package/docs/images/desktop/palette.png +0 -0
  75. package/docs/images/desktop/todo.png +0 -0
  76. package/docs/install-wizard.md +30 -21
  77. package/docs/odd-preparation-continuity.md +24 -0
  78. package/docs/permission-modes.md +9 -1
  79. package/docs/prompt-budget.md +12 -0
  80. package/docs/rdd-odd-friction-triage-2026-11-07.md +57 -0
  81. package/docs/readme-reference.md +113 -32
  82. package/docs/review-coordinator.md +29 -9
  83. package/docs/review-delivery-preflight.md +22 -0
  84. package/docs/work-continuity.md +19 -6
  85. package/extensions/ask-user-choice.ts +36 -18
  86. package/extensions/ask-user-question.ts +48 -9
  87. package/extensions/child-context.ts +21 -7
  88. package/extensions/gentle-agents.ts +436 -66
  89. package/extensions/gentle-ai.ts +809 -158
  90. package/extensions/gentle-design.ts +69 -3
  91. package/extensions/gentle-desktop-feed.ts +778 -0
  92. package/extensions/gentle-desktop-rpc.ts +276 -0
  93. package/extensions/gentle-guide.ts +3 -0
  94. package/extensions/gentle-herdr-desktop-status.ts +275 -0
  95. package/extensions/gentle-shell.ts +174 -59
  96. package/extensions/gentle-stats.ts +30 -1
  97. package/extensions/gentle-todo.ts +48 -25
  98. package/extensions/gentle-tower.ts +305 -0
  99. package/extensions/skill-registry.ts +260 -225
  100. package/herdr/RECIPE.md +157 -0
  101. package/herdr/keys.json +14 -0
  102. package/herdr/layouts/gentle-shell.json +202 -0
  103. package/herdr/mods/gentle-agents/icons/kind-herdr.svg +1 -0
  104. package/herdr/mods/gentle-agents/icons/kind-remote.svg +1 -0
  105. package/herdr/mods/gentle-agents/icons/kind-tui.svg +1 -0
  106. package/herdr/mods/gentle-agents/main.js +190 -0
  107. package/herdr/mods/gentle-agents/mod.json +1 -0
  108. package/herdr/mods/gentle-agents/snapshot.js +469 -0
  109. package/herdr/mods/gentle-agents/tokens.js +273 -0
  110. package/herdr/mods/gentle-chat/MINIMAL.md +69 -0
  111. package/herdr/mods/gentle-chat/actions.js +180 -0
  112. package/herdr/mods/gentle-chat/feed.js +321 -0
  113. package/herdr/mods/gentle-chat/icons/branch.svg +1 -0
  114. package/herdr/mods/gentle-chat/icons/chat.svg +1 -0
  115. package/herdr/mods/gentle-chat/icons/check.svg +1 -0
  116. package/herdr/mods/gentle-chat/icons/chev.svg +1 -0
  117. package/herdr/mods/gentle-chat/icons/clip.svg +1 -0
  118. package/herdr/mods/gentle-chat/icons/down.svg +1 -0
  119. package/herdr/mods/gentle-chat/icons/folder.svg +1 -0
  120. package/herdr/mods/gentle-chat/icons/kind-herdr.svg +1 -0
  121. package/herdr/mods/gentle-chat/icons/kind-remote.svg +1 -0
  122. package/herdr/mods/gentle-chat/icons/kind-tui.svg +1 -0
  123. package/herdr/mods/gentle-chat/icons/mark.svg +1 -0
  124. package/herdr/mods/gentle-chat/icons/send.svg +1 -0
  125. package/herdr/mods/gentle-chat/icons/shield.svg +1 -0
  126. package/herdr/mods/gentle-chat/icons/stop.svg +1 -0
  127. package/herdr/mods/gentle-chat/icons/term.svg +1 -0
  128. package/herdr/mods/gentle-chat/icons/user.svg +1 -0
  129. package/herdr/mods/gentle-chat/icons/x.svg +1 -0
  130. package/herdr/mods/gentle-chat/main.js +968 -0
  131. package/herdr/mods/gentle-chat/mod.json +1 -0
  132. package/herdr/mods/gentle-chat/session.js +212 -0
  133. package/herdr/mods/gentle-chat/snapshot.js +469 -0
  134. package/herdr/mods/gentle-chat/tokens.js +137 -0
  135. package/herdr/mods/gentle-chat/ui.js +883 -0
  136. package/herdr/mods/gentle-confirm/main.js +60 -0
  137. package/herdr/mods/gentle-confirm/mod.json +1 -0
  138. package/herdr/mods/gentle-inspector/actions.js +180 -0
  139. package/herdr/mods/gentle-inspector/icons/bolt.svg +1 -0
  140. package/herdr/mods/gentle-inspector/icons/bot.svg +1 -0
  141. package/herdr/mods/gentle-inspector/icons/check.svg +1 -0
  142. package/herdr/mods/gentle-inspector/icons/db.svg +1 -0
  143. package/herdr/mods/gentle-inspector/icons/diff.svg +1 -0
  144. package/herdr/mods/gentle-inspector/icons/jobs.svg +1 -0
  145. package/herdr/mods/gentle-inspector/icons/plug.svg +1 -0
  146. package/herdr/mods/gentle-inspector/icons/review.svg +1 -0
  147. package/herdr/mods/gentle-inspector/icons/stats.svg +1 -0
  148. package/herdr/mods/gentle-inspector/icons/stop.svg +1 -0
  149. package/herdr/mods/gentle-inspector/icons/todo.svg +1 -0
  150. package/herdr/mods/gentle-inspector/main.js +500 -0
  151. package/herdr/mods/gentle-inspector/mod.json +1 -0
  152. package/herdr/mods/gentle-inspector/snapshot.js +469 -0
  153. package/herdr/mods/gentle-inspector/tokens.js +273 -0
  154. package/herdr/mods/gentle-palette/actions.js +180 -0
  155. package/herdr/mods/gentle-palette/icons/bolt.svg +1 -0
  156. package/herdr/mods/gentle-palette/icons/bot.svg +1 -0
  157. package/herdr/mods/gentle-palette/icons/chat.svg +1 -0
  158. package/herdr/mods/gentle-palette/icons/check.svg +1 -0
  159. package/herdr/mods/gentle-palette/icons/cmd.svg +1 -0
  160. package/herdr/mods/gentle-palette/icons/diff.svg +1 -0
  161. package/herdr/mods/gentle-palette/icons/jobs.svg +1 -0
  162. package/herdr/mods/gentle-palette/icons/plus.svg +1 -0
  163. package/herdr/mods/gentle-palette/icons/review.svg +1 -0
  164. package/herdr/mods/gentle-palette/icons/search.svg +1 -0
  165. package/herdr/mods/gentle-palette/icons/shield.svg +1 -0
  166. package/herdr/mods/gentle-palette/icons/stats.svg +1 -0
  167. package/herdr/mods/gentle-palette/icons/stop.svg +1 -0
  168. package/herdr/mods/gentle-palette/icons/term.svg +1 -0
  169. package/herdr/mods/gentle-palette/icons/todo.svg +1 -0
  170. package/herdr/mods/gentle-palette/main.js +333 -0
  171. package/herdr/mods/gentle-palette/mod.json +1 -0
  172. package/herdr/mods/gentle-palette/snapshot.js +469 -0
  173. package/herdr/mods/gentle-palette/tokens.js +273 -0
  174. package/herdr/mods/gentle-pane/icons/chat.svg +1 -0
  175. package/herdr/mods/gentle-pane/icons/close.svg +1 -0
  176. package/herdr/mods/gentle-pane/icons/kind-herdr.svg +1 -0
  177. package/herdr/mods/gentle-pane/icons/kind-remote.svg +1 -0
  178. package/herdr/mods/gentle-pane/icons/kind-tui.svg +1 -0
  179. package/herdr/mods/gentle-pane/icons/split-down.svg +1 -0
  180. package/herdr/mods/gentle-pane/icons/split-right.svg +1 -0
  181. package/herdr/mods/gentle-pane/icons/term.svg +1 -0
  182. package/herdr/mods/gentle-pane/icons/unzoom.svg +1 -0
  183. package/herdr/mods/gentle-pane/icons/zoom.svg +1 -0
  184. package/herdr/mods/gentle-pane/main.js +91 -0
  185. package/herdr/mods/gentle-pane/mod.json +1 -0
  186. package/herdr/mods/gentle-pane/snapshot.js +469 -0
  187. package/herdr/mods/gentle-pane/tokens.js +273 -0
  188. package/herdr/mods/gentle-sidebar/actions.js +180 -0
  189. package/herdr/mods/gentle-sidebar/icons/gear.svg +1 -0
  190. package/herdr/mods/gentle-sidebar/icons/mark.svg +1 -0
  191. package/herdr/mods/gentle-sidebar/icons/refresh.svg +1 -0
  192. package/herdr/mods/gentle-sidebar/icons/server-plus.svg +1 -0
  193. package/herdr/mods/gentle-sidebar/main.js +171 -0
  194. package/herdr/mods/gentle-sidebar/mod.json +1 -0
  195. package/herdr/mods/gentle-sidebar/snapshot.js +469 -0
  196. package/herdr/mods/gentle-sidebar/tokens.js +273 -0
  197. package/herdr/mods/gentle-spaces/icons/kind-herdr.svg +1 -0
  198. package/herdr/mods/gentle-spaces/icons/kind-remote.svg +1 -0
  199. package/herdr/mods/gentle-spaces/icons/kind-tui.svg +1 -0
  200. package/herdr/mods/gentle-spaces/icons/monitor.svg +1 -0
  201. package/herdr/mods/gentle-spaces/icons/plus.svg +1 -0
  202. package/herdr/mods/gentle-spaces/icons/server.svg +1 -0
  203. package/herdr/mods/gentle-spaces/machines.js +31 -0
  204. package/herdr/mods/gentle-spaces/main.js +299 -0
  205. package/herdr/mods/gentle-spaces/mod.json +1 -0
  206. package/herdr/mods/gentle-spaces/snapshot.js +469 -0
  207. package/herdr/mods/gentle-spaces/tokens.js +273 -0
  208. package/herdr/mods/gentle-status/actions.js +180 -0
  209. package/herdr/mods/gentle-status/main.js +192 -0
  210. package/herdr/mods/gentle-status/mod.json +1 -0
  211. package/herdr/mods/gentle-status/snapshot.js +469 -0
  212. package/herdr/mods/gentle-status/tokens.js +273 -0
  213. package/herdr/mods/gentle-tabs/icons/close.svg +1 -0
  214. package/herdr/mods/gentle-tabs/icons/kind-herdr.svg +1 -0
  215. package/herdr/mods/gentle-tabs/icons/kind-remote.svg +1 -0
  216. package/herdr/mods/gentle-tabs/icons/kind-tui.svg +1 -0
  217. package/herdr/mods/gentle-tabs/icons/plus.svg +1 -0
  218. package/herdr/mods/gentle-tabs/icons/win-close.svg +1 -0
  219. package/herdr/mods/gentle-tabs/icons/win-max.svg +1 -0
  220. package/herdr/mods/gentle-tabs/icons/win-min.svg +1 -0
  221. package/herdr/mods/gentle-tabs/icons/win-restore.svg +1 -0
  222. package/herdr/mods/gentle-tabs/main.js +171 -0
  223. package/herdr/mods/gentle-tabs/mod.json +1 -0
  224. package/herdr/mods/gentle-tabs/snapshot.js +469 -0
  225. package/herdr/mods/gentle-tabs/tokens.js +273 -0
  226. package/herdr/mods/gentle-tokens/main.js +20 -0
  227. package/herdr/mods/gentle-tokens/mod.json +1 -0
  228. package/herdr/mods/gentle-tokens/snapshot.js +469 -0
  229. package/herdr/mods/gentle-tokens/tokens.js +273 -0
  230. package/herdr/preview.png +0 -0
  231. package/herdr/themes/gentle-shell-dark.json +33 -0
  232. package/herdr/themes/gentle-shell-light.json +34 -0
  233. package/lib/agent-assets.ts +30 -6
  234. package/lib/agent-tool-overlay.ts +117 -0
  235. package/lib/agents-config.ts +47 -6
  236. package/lib/agents-message-delivery.ts +17 -0
  237. package/lib/agents-messaging.ts +8 -2
  238. package/lib/agents-protocol.ts +17 -0
  239. package/lib/agents-report-cap.ts +115 -0
  240. package/lib/agents-rpc-publisher.ts +39 -12
  241. package/lib/agents-runner.ts +92 -6
  242. package/lib/agents-session-transport.ts +17 -1
  243. package/lib/auto-permission-answers.ts +2 -1
  244. package/lib/background-jobs-tools.ts +9 -4
  245. package/lib/background-jobs.ts +22 -2
  246. package/lib/bounded-writer-admission.ts +184 -31
  247. package/lib/change-diff.ts +104 -0
  248. package/lib/child-context-files.ts +21 -6
  249. package/lib/codemode-renderer.ts +1 -0
  250. package/lib/commit-slice-signal.ts +1 -1
  251. package/lib/delivery-conflict-markers.ts +349 -0
  252. package/lib/design-canvas-assets.ts +38 -0
  253. package/lib/design-canvas-server.ts +241 -23
  254. package/lib/design-comments.ts +94 -4
  255. package/lib/design-handoffs.ts +2 -1
  256. package/lib/design-layout.ts +125 -0
  257. package/lib/design-parts.ts +281 -0
  258. package/lib/design-system-tokens.ts +111 -0
  259. package/lib/desktop-agents-service.ts +315 -0
  260. package/lib/desktop-changes-service.ts +171 -0
  261. package/lib/desktop-design-service.ts +233 -0
  262. package/lib/desktop-feed-actions.ts +804 -0
  263. package/lib/desktop-feed-answers.ts +129 -0
  264. package/lib/desktop-feed-sources.ts +184 -0
  265. package/lib/desktop-feed-stats.ts +98 -0
  266. package/lib/desktop-feed-store.ts +124 -0
  267. package/lib/desktop-feed.ts +788 -0
  268. package/lib/desktop-jobs-service.ts +290 -0
  269. package/lib/desktop-review-service.ts +187 -0
  270. package/lib/desktop-rpc-agents.ts +403 -0
  271. package/lib/desktop-rpc-changes.ts +223 -0
  272. package/lib/desktop-rpc-config-watch.ts +285 -0
  273. package/lib/desktop-rpc-config.ts +885 -0
  274. package/lib/desktop-rpc-design.ts +138 -0
  275. package/lib/desktop-rpc-jobs.ts +290 -0
  276. package/lib/desktop-rpc-permissions.ts +328 -0
  277. package/lib/desktop-rpc-profiles.ts +196 -0
  278. package/lib/desktop-rpc-review.ts +180 -0
  279. package/lib/desktop-rpc-session.ts +203 -0
  280. package/lib/desktop-rpc-sessions.ts +250 -0
  281. package/lib/desktop-rpc-stats.ts +187 -0
  282. package/lib/desktop-rpc-updates.ts +143 -0
  283. package/lib/desktop-rpc-usage.ts +229 -0
  284. package/lib/desktop-rpc.ts +336 -0
  285. package/lib/desktop-session-service.ts +223 -0
  286. package/lib/desktop-sessions-service.ts +249 -0
  287. package/lib/desktop-stats-service.ts +142 -0
  288. package/lib/desktop-updates-service.ts +268 -0
  289. package/lib/desktop-usage-service.ts +310 -0
  290. package/lib/destructive-command-guard.ts +188 -13
  291. package/lib/gentle-ai-renderer.ts +13 -1
  292. package/lib/gentle-design.ts +201 -14
  293. package/lib/gentle-shell-bundled.ts +100 -9
  294. package/lib/gentle-shell-desktop.ts +1370 -0
  295. package/lib/gentle-shell-launcher.ts +45 -3
  296. package/lib/herdr-desktop-events.ts +40 -0
  297. package/lib/herdr-desktop-status.ts +229 -0
  298. package/lib/hidden-tools.ts +35 -0
  299. package/lib/inprocess-reviewer.ts +96 -12
  300. package/lib/jobs-sidebar-state.ts +5 -0
  301. package/lib/model-fallback-policy.ts +9 -0
  302. package/lib/model-routing-authority.ts +9 -0
  303. package/lib/nan-provider.ts +42 -28
  304. package/lib/native-review-cli.ts +86 -4
  305. package/lib/openai-fast-tier.ts +1 -0
  306. package/lib/orchestrator-discovery.ts +39 -2
  307. package/lib/reply-language-anchor.ts +27 -2
  308. package/lib/request-context-placement.ts +53 -0
  309. package/lib/review-candidate-view.ts +11 -1
  310. package/lib/review-continuation-registry.ts +17 -0
  311. package/lib/review-coordinator.ts +252 -8
  312. package/lib/review-delivery-preflight.ts +85 -0
  313. package/lib/review-host-relay.ts +5 -1
  314. package/lib/review-integration-v2.ts +56 -3
  315. package/lib/reviewer-stream.ts +87 -0
  316. package/lib/session-profile-freeze.ts +13 -5
  317. package/lib/shell-prompt.ts +16 -3
  318. package/lib/shell-usage.ts +10 -0
  319. package/lib/stats-collector.ts +56 -27
  320. package/lib/tower-actions.ts +100 -0
  321. package/lib/tower-hub.ts +73 -0
  322. package/lib/tower-launch.ts +111 -0
  323. package/lib/tower-open.ts +99 -0
  324. package/lib/tower-presence.ts +70 -0
  325. package/lib/tower-server.ts +234 -0
  326. package/lib/tower-snapshot.ts +298 -0
  327. package/lib/update-status.ts +238 -0
  328. package/lib/verifier-settle-reminder.ts +1 -1
  329. package/lib/vim-editor-adapter.ts +9 -2
  330. package/lib/writer-batch-admission.ts +55 -0
  331. package/lib/yolo-session-policy.ts +6 -1
  332. package/package.json +14 -5
  333. package/prompts/skill-creation.md +1 -10
  334. package/runtime/design-canvas-assets.mjs +39 -0
  335. package/runtime/gentle-shell-bundled.mjs +100 -9
  336. package/runtime/gentle-shell-desktop.mjs +1371 -0
  337. package/runtime/gentle-shell-launcher.mjs +44 -2
  338. package/runtime/native-review-cli.mjs +86 -4
  339. package/runtime/review-integration-v2.mjs +56 -3
  340. package/runtime/tower-actions.mjs +101 -0
  341. package/runtime/tower-hub.mjs +74 -0
  342. package/runtime/tower-launch.mjs +112 -0
  343. package/runtime/tower-open.mjs +100 -0
  344. package/runtime/tower-presence.mjs +71 -0
  345. package/runtime/tower-server.mjs +234 -0
  346. package/runtime/tower-snapshot.mjs +299 -0
  347. package/scripts/bootstrap.cmd +2 -2
  348. package/scripts/bootstrap.sh +41 -4
  349. package/scripts/build-full-delegation-card.mjs +5 -21
  350. package/scripts/build-runtime-modules.mjs +10 -0
  351. package/scripts/gentle-ai-installer.mjs +10 -10
  352. package/scripts/gentle-ai-proxy.mjs +1 -1
  353. package/scripts/installer-downloads.mjs +34 -8
  354. package/scripts/installer-preflight.mjs +28 -17
  355. package/scripts/installer-probes.mjs +25 -5
  356. package/scripts/installer-server.mjs +38 -9
  357. package/scripts/installer-windows.mjs +2 -2
  358. package/scripts/pi-update.mjs +166 -27
  359. package/scripts/prepare-verifier.mjs +107 -0
  360. package/scripts/update-agent-body-history.mjs +55 -8
  361. package/scripts/verify-package-files.mjs +61 -20
  362. package/skills/branch-pr/SKILL.md +16 -16
  363. package/skills/comment-writer/SKILL.md +1 -1
  364. package/skills/design/SKILL.md +6 -6
  365. package/skills/gentle-ai/SKILL.md +5 -5
  366. package/skills/judgment-day/SKILL.md +2 -2
  367. package/skills/judgment-day/references/prompts-and-formats.md +1 -1
  368. package/skills/provider-defect-report/SKILL.md +61 -0
  369. package/skills/rdd-defect-workflow/SKILL.md +6 -6
  370. package/skills/skill-improver/SKILL.md +2 -2
  371. package/skills/skill-registry/SKILL.md +11 -13
  372. package/skills/tui-design/SKILL.md +1 -1
  373. package/skills/work-unit-commits/SKILL.md +5 -5
  374. package/tests/agent-prompt-diet-contract.test.ts +101 -0
  375. package/tests/agent-tool-overlay-acceptance.test.ts +158 -0
  376. package/tests/agent-tool-overlay.test.ts +89 -0
  377. package/tests/agents-config.test.ts +10 -1
  378. package/tests/agents-message-delivery.test.ts +36 -0
  379. package/tests/agents-queries.test.ts +144 -4
  380. package/tests/agents-report-cap.test.ts +126 -0
  381. package/tests/agents-runner.test.ts +37 -1
  382. package/tests/agents-session-transport.test.ts +34 -0
  383. package/tests/always-on-prompt-verdicts-contract.test.ts +188 -0
  384. package/tests/append-system-prompt-route.test.ts +26 -7
  385. package/tests/approved-text-leftovers-contract.test.ts +136 -0
  386. package/tests/artifact-language.test.ts +1 -1
  387. package/tests/ask-user-choice.test.ts +78 -21
  388. package/tests/ask-user-question.test.ts +61 -6
  389. package/tests/audit-leftovers-contract.test.ts +51 -0
  390. package/tests/auto-permission-answers.test.ts +12 -1
  391. package/tests/background-jobs.test.ts +12 -0
  392. package/tests/bounded-stop-contract.test.ts +148 -27
  393. package/tests/branch-pr-skill.test.ts +10 -1
  394. package/tests/bundled-install.test.ts +1 -1
  395. package/tests/change-diff.test.ts +75 -0
  396. package/tests/child-context-files.test.ts +64 -8
  397. package/tests/child-skills-catalog.test.ts +56 -0
  398. package/tests/codemode-rendering.test.ts +4 -1
  399. package/tests/commit-slice-signal.test.ts +3 -2
  400. package/tests/decision-routing-contract.test.ts +390 -0
  401. package/tests/delegate-for-reason-contract.test.ts +30 -8
  402. package/tests/delegated-key-learnings-contract.test.ts +21 -28
  403. package/tests/delivery-b-rendered-surfaces.test.ts +32 -0
  404. package/tests/delivery-conflict-markers.test.ts +348 -0
  405. package/tests/design-canvas-all-sizes.test.ts +631 -0
  406. package/tests/design-canvas-allowlist.test.ts +32 -0
  407. package/tests/design-canvas-assets.test.ts +11 -878
  408. package/tests/design-canvas-boards.test.ts +77 -0
  409. package/tests/design-canvas-checks.test.ts +655 -0
  410. package/tests/design-canvas-compare.test.ts +79 -0
  411. package/tests/design-canvas-events.test.ts +59 -0
  412. package/tests/design-canvas-export.test.ts +1168 -0
  413. package/tests/design-canvas-focus.test.ts +113 -0
  414. package/tests/design-canvas-handoffs.test.ts +59 -0
  415. package/tests/design-canvas-i18n-review.test.ts +513 -0
  416. package/tests/design-canvas-i18n-views.test.ts +259 -0
  417. package/tests/design-canvas-i18n.test.ts +528 -0
  418. package/tests/design-canvas-inspector.test.ts +1004 -0
  419. package/tests/design-canvas-layout.test.ts +1222 -0
  420. package/tests/design-canvas-minimap.test.ts +413 -0
  421. package/tests/design-canvas-modules.test.ts +91 -0
  422. package/tests/design-canvas-parts.test.ts +721 -0
  423. package/tests/design-canvas-rail.test.ts +799 -0
  424. package/tests/design-canvas-server.test.ts +855 -17
  425. package/tests/design-canvas-sizes.test.ts +548 -0
  426. package/tests/design-canvas-store.test.ts +189 -0
  427. package/tests/design-canvas-theme.test.ts +198 -0
  428. package/tests/design-canvas-tokens.test.ts +965 -0
  429. package/tests/design-canvas-view.test.ts +299 -0
  430. package/tests/design-comments.test.ts +201 -1
  431. package/tests/design-handoffs.test.ts +20 -0
  432. package/tests/design-layout.test.ts +100 -0
  433. package/tests/design-parts.test.ts +260 -0
  434. package/tests/design-system-tokens.test.ts +215 -0
  435. package/tests/desktop-feed-actions-guards.test.ts +595 -0
  436. package/tests/desktop-feed-actions.test.ts +761 -0
  437. package/tests/desktop-feed-live-work.test.ts +209 -0
  438. package/tests/desktop-feed-performance.test.ts +369 -0
  439. package/tests/desktop-feed-plan-profiles.test.ts +509 -0
  440. package/tests/desktop-feed-send-prompt.test.ts +303 -0
  441. package/tests/desktop-feed-tool-summaries.test.ts +69 -0
  442. package/tests/desktop-feed.test.ts +615 -0
  443. package/tests/desktop-rpc-agents.test.ts +1319 -0
  444. package/tests/desktop-rpc-changes.test.ts +608 -0
  445. package/tests/desktop-rpc-config-watch.test.ts +1159 -0
  446. package/tests/desktop-rpc-config.test.ts +1462 -0
  447. package/tests/desktop-rpc-design.test.ts +672 -0
  448. package/tests/desktop-rpc-jobs.test.ts +1193 -0
  449. package/tests/desktop-rpc-permissions.test.ts +321 -0
  450. package/tests/desktop-rpc-profiles.test.ts +140 -0
  451. package/tests/desktop-rpc-review.test.ts +678 -0
  452. package/tests/desktop-rpc-safety.test.ts +119 -0
  453. package/tests/desktop-rpc-session.test.ts +642 -0
  454. package/tests/desktop-rpc-sessions.test.ts +647 -0
  455. package/tests/desktop-rpc-stats.test.ts +431 -0
  456. package/tests/desktop-rpc-updates.test.ts +525 -0
  457. package/tests/desktop-rpc-usage.test.ts +707 -0
  458. package/tests/desktop-rpc.test.ts +293 -0
  459. package/tests/devbinary/pi-host-relay.devtest.ts +149 -80
  460. package/tests/devbinary/review-session-consent.devtest.ts +84 -0
  461. package/tests/engram-safety.test.ts +111 -0
  462. package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.captured.json +92 -0
  463. package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.provenance.md +3 -0
  464. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +30 -41
  465. package/tests/fixtures/refusal-identity.probe.mjs +139 -0
  466. package/tests/fixtures/session-profile-v1/replay.ts +4 -1
  467. package/tests/full-delegation-closure.test.ts +48 -0
  468. package/tests/gentle-agents.test.ts +848 -8
  469. package/tests/gentle-ai-binary.test.ts +1 -1
  470. package/tests/gentle-ai-child-guards.test.ts +1 -0
  471. package/tests/gentle-ai-installer.test.ts +52 -51
  472. package/tests/gentle-ai-renderer.test.ts +36 -2
  473. package/tests/gentle-ai.test.ts +195 -21
  474. package/tests/gentle-design.test.ts +365 -1
  475. package/tests/gentle-fast.test.ts +15 -0
  476. package/tests/gentle-herdr-desktop-status.test.ts +595 -0
  477. package/tests/gentle-shell-bundled.test.ts +91 -5
  478. package/tests/gentle-shell-desktop-bin.test.ts +125 -0
  479. package/tests/gentle-shell-desktop.test.ts +927 -0
  480. package/tests/gentle-shell-launcher-tower.test.ts +104 -0
  481. package/tests/gentle-shell-launcher.test.ts +1 -1
  482. package/tests/gentle-shell.test.ts +121 -87
  483. package/tests/gentle-todo.test.ts +32 -9
  484. package/tests/gentle-tower.test.ts +578 -0
  485. package/tests/herdr-desktop-status.test.ts +285 -0
  486. package/tests/hidden-tools.test.ts +188 -0
  487. package/tests/independent-recovery-delivery.test.ts +35 -9
  488. package/tests/inprocess-reviewer.test.ts +73 -0
  489. package/tests/install-wizard.test.ts +27 -1
  490. package/tests/installer-downloads.test.ts +30 -1
  491. package/tests/installer-posix-bootstrap.test.ts +114 -13
  492. package/tests/installer-preflight.test.ts +49 -1
  493. package/tests/installer-probes.test.ts +146 -0
  494. package/tests/installer-server.test.ts +203 -4
  495. package/tests/installer-windows-bootstrap.test.ts +19 -1
  496. package/tests/judgment-day-severity-admission.test.ts +46 -0
  497. package/tests/lazy-module-contradictions-contract.test.ts +181 -0
  498. package/tests/maintainer/desktop-rpc.maintest.ts +907 -0
  499. package/tests/maintainer/pi-update-source.maintest.ts +48 -18
  500. package/tests/model-fallback-policy.test.ts +26 -7
  501. package/tests/nan-provider-runtime.test.ts +17 -3
  502. package/tests/nan-provider.test.ts +111 -56
  503. package/tests/native-review-capability-contract.test.ts +19 -1
  504. package/tests/native-review-cli-nonblocking-findings.test.ts +165 -0
  505. package/tests/native-review-parity.test.ts +24 -5
  506. package/tests/native-review-refusal-identity.test.ts +25 -0
  507. package/tests/no-self-pause-contract.test.ts +33 -15
  508. package/tests/odd-integration.test.ts +11 -3
  509. package/tests/odd-routing-canonical-ratchet.test.ts +10 -0
  510. package/tests/odd-routing-contract.test.ts +99 -31
  511. package/tests/orchestrator-budget.test.ts +32 -5
  512. package/tests/orchestrator-consultation-sdk.test.ts +32 -6
  513. package/tests/orchestrator-delegation-mode.test.ts +2 -1
  514. package/tests/orchestrator-discovery.test.ts +28 -0
  515. package/tests/orchestrator-prompt-budget.test.ts +12 -2
  516. package/tests/orchestrator-prompt-diet-contract.test.ts +249 -0
  517. package/tests/orchestrator-rdd-ownership.test.ts +2 -1
  518. package/tests/orchestrator-work-search.test.ts +4 -2
  519. package/tests/package-files.test.ts +25 -1
  520. package/tests/package-manifest.test.ts +15 -14
  521. package/tests/parallel-reason-contract.test.ts +6 -3
  522. package/tests/permission-allowlist.test.ts +200 -30
  523. package/tests/persona-neutral-voseo.test.ts +4 -4
  524. package/tests/persona-reply-language.test.ts +1 -1
  525. package/tests/persona-single-channel.test.ts +13 -5
  526. package/tests/pi-routing-measured-values.test.ts +24 -0
  527. package/tests/pi-update-launcher.test.ts +17 -7
  528. package/tests/pi-update-source.test.ts +113 -6
  529. package/tests/pi-update.test.ts +294 -19
  530. package/tests/pnpm-workspace-policy.test.ts +47 -0
  531. package/tests/primary-context-files.test.ts +233 -0
  532. package/tests/primary-context-three-files.test.ts +174 -0
  533. package/tests/primary-session-prompt.test.ts +25 -0
  534. package/tests/profile-fast-tier.test.ts +66 -1
  535. package/tests/provider-defect-handoff.test.ts +124 -99
  536. package/tests/rdd-aware-verification-contract.test.ts +1 -1
  537. package/tests/rdd-status-line.test.ts +94 -1
  538. package/tests/reply-language-anchor-placement.test.ts +184 -0
  539. package/tests/reply-language-anchor.test.ts +17 -1
  540. package/tests/request-context-append-only.test.ts +218 -0
  541. package/tests/request-context-placement.test.ts +148 -0
  542. package/tests/review-agent-end-preflight.test.ts +79 -1
  543. package/tests/review-candidate-view.test.ts +65 -0
  544. package/tests/review-continuation-registry.test.ts +31 -0
  545. package/tests/review-contract-prompt.test.ts +2 -1
  546. package/tests/review-controller.test.ts +2 -1
  547. package/tests/review-coordinator-correction-gate.test.ts +105 -0
  548. package/tests/review-coordinator-findings.test.ts +206 -0
  549. package/tests/review-coordinator-nonblocking-scope.test.ts +169 -0
  550. package/tests/review-coordinator.test.ts +271 -4
  551. package/tests/review-delivery-preflight.test.ts +462 -0
  552. package/tests/review-due-compaction.test.ts +31 -0
  553. package/tests/review-due-public-boundary.test.ts +27 -0
  554. package/tests/review-integration-nonblocking-findings.test.ts +108 -0
  555. package/tests/review-json-arguments.test.ts +41 -2
  556. package/tests/review-ledger-contract.test.ts +19 -40
  557. package/tests/review-loadout-rdd-off-sdk.test.ts +30 -1
  558. package/tests/review-one-call-findings.test.ts +131 -0
  559. package/tests/review-one-call-followups.test.ts +308 -0
  560. package/tests/review-one-call-reviewer-requests.test.ts +207 -0
  561. package/tests/review-one-call.test.ts +452 -0
  562. package/tests/review-relay-transport-agent.test.ts +28 -1
  563. package/tests/review-reviewer-evidence.test.ts +41 -1
  564. package/tests/review-risk-assessment.test.ts +52 -5
  565. package/tests/review-run-statement-guidance-independent.test.ts +54 -0
  566. package/tests/review-session-standing-permission-controller.test.ts +32 -2
  567. package/tests/review-tool-prose-budget.test.ts +1 -0
  568. package/tests/reviewer-stream.test.ts +149 -0
  569. package/tests/sensitive-path-tools.test.ts +138 -4
  570. package/tests/session-profile-extension.test.ts +312 -18
  571. package/tests/session-profile-freeze.test.ts +26 -0
  572. package/tests/session-profile-v1-compat.test.ts +20 -0
  573. package/tests/shell-prompt.test.ts +17 -0
  574. package/tests/shell-usage.test.ts +59 -10
  575. package/tests/skill-collision-prefixes.test.ts +1 -0
  576. package/tests/skill-contradictions-contract.test.ts +124 -0
  577. package/tests/skill-registry-watcher.test.ts +216 -2
  578. package/tests/skill-registry.test.ts +983 -306
  579. package/tests/stats-collector.test.ts +109 -2
  580. package/tests/support/design-canvas-dom.ts +386 -0
  581. package/tests/support/review-coordinator-runtime.ts +212 -17
  582. package/tests/task-size-routing-contract.test.ts +49 -14
  583. package/tests/test-strength-contract.test.ts +2 -1
  584. package/tests/todo-request-append-only.test.ts +214 -0
  585. package/tests/tool-batching-contract.test.ts +3 -1
  586. package/tests/tower-actions.test.ts +247 -0
  587. package/tests/tower-artifacts.test.ts +114 -0
  588. package/tests/tower-open.test.ts +97 -0
  589. package/tests/tower-presence.test.ts +175 -0
  590. package/tests/tower-server.test.ts +122 -0
  591. package/tests/tower-snapshot.test.ts +236 -0
  592. package/tests/tower-web-echo.test.ts +125 -0
  593. package/tests/tower-web-hover.test.ts +251 -0
  594. package/tests/update-agent-body-history.test.ts +138 -0
  595. package/tests/verification-scoped-stop-contract.test.ts +32 -0
  596. package/tests/verification-tiers-contract.test.ts +229 -0
  597. package/tests/verifier-preparation.test.ts +229 -0
  598. package/tests/verifier-settle-reminder.test.ts +2 -2
  599. package/tests/verify-agent-contract.test.ts +20 -2
  600. package/tests/verify-first-launch-contract.test.ts +88 -12
  601. package/tests/vim-editor-adapter.test.ts +2 -2
  602. package/tests/work-continuity-contract.test.ts +136 -27
  603. package/tests/writer-admission-messages.test.ts +232 -0
  604. package/tests/writer-batch-admission.test.ts +66 -0
  605. package/tests/writer-edit-surface-scope.test.ts +52 -20
  606. package/tests/writer-feature-document-admission.test.ts +184 -0
  607. package/tests/writer-rejection-next-step.test.ts +55 -0
  608. package/tests/writer-surface-authority-contract.test.ts +158 -0
  609. package/tests/yolo-mode.test.ts +39 -0
  610. package/skills/_shared/review-ledger-contract.md +0 -106
  611. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.6.0}/bundle/README.md +0 -0
  612. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.6.0}/bundle/schemas/lens.schema.json +0 -0
  613. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.6.0}/bundle/schemas/refuter.schema.json +0 -0
  614. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.6.0}/bundle/schemas/targeted-validator.schema.json +0 -0
  615. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.6.0}/bundle/vectors/lens.json +0 -0
  616. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.6.0}/bundle/vectors/refuter.json +0 -0
  617. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.6.0}/bundle/vectors/targeted-validator.json +0 -0
@@ -0,0 +1,1371 @@
1
+ // Generated by scripts/build-runtime-modules.mjs. Do not edit.
2
+ import { spawn, spawnSync } from "node:child_process";
3
+ import { createHash } from "node:crypto";
4
+ import { accessSync, constants as fsConstants, cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
5
+ import { delimiter, join } from "node:path";
6
+
7
+ // `gentle-shell desktop` (Gentle Shell Desktop, odd/tasks/herdr-desktop.md T8):
8
+ // the pinned Herdr app, unchanged, plus our gentle-* mods and the gentle-shell
9
+ // layout from this package's herdr/ folder, the way Gentle Shell ships Pi.
10
+ // Everything it writes in Herdr's home is a gentle-* mod folder,
11
+ // layouts/gentle-shell.json or a themes/gentle-shell-*.json (the layout's light
12
+ // and dark palettes, S14); its own state and backups live in
13
+ // ~/.gentle-shell/desktop. Whatever was at one of those paths before Gentle
14
+ // Shell first installed there (state.json says which paths are ours) is kept
15
+ // in ~/.gentle-shell/desktop/originals, never rotated, and put back exactly by
16
+ // --uninstall. The one shared file it edits is keys.json: it adds only the
17
+ // layout:gentle-shell shortcuts of herdr/keys.json (state.json records each
18
+ // one), never changes a key the person binds, and --uninstall removes exactly
19
+ // those entries.
20
+
21
+ // The Herdr app the mods were built and checked against (`herdr-app check`,
22
+ // live fidelity passes). Newer apps are accepted; older or missing ones get
23
+ // exactly this release.
24
+ export const HERDR_APP_VERSION = "0.1.16";
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+ // From Herdr's immutable per-version manifest,
33
+ // https://releases.herdr.dev/app/0.1.16/manifest.json (the file the official
34
+ // install.sh reads through app/latest.json). Pinned here so a changed or
35
+ // replaced download never installs.
36
+ export const HERDR_APP_RELEASE = {
37
+ version: HERDR_APP_VERSION,
38
+ sha256: {
39
+ "linux-aarch64": "efeef4f1759b0e8900f205c2c22b14287a112f874406539b4ea1b3be24b73631",
40
+ "linux-x86_64": "282d2632196b238206cfe66bfb61c0faf299ca1c91843bd076521bbe36571216",
41
+ "macos-aarch64": "99000875ead9333a33f5cb60274ccd9cf9d3e47360f03613a467295105c71c04",
42
+ "windows-x86_64": "abdc5400679cb730223a43b2a5216999a1edad3c2e80368f0ad3c43ea9895fe3",
43
+ },
44
+ };
45
+
46
+ export const HERDR_RELEASES_URL = "https://releases.herdr.dev";
47
+ export const DESKTOP_LAYOUT = "gentle-shell";
48
+ const OFFICIAL_WINDOWS_INSTALL = 'powershell -c "irm https://releases.herdr.dev/app/install.ps1 | iex"';
49
+ const START_ATTEMPTS = 40;
50
+ const START_INTERVAL_MS = 500;
51
+ // The keys.json section our shortcuts live in: they apply only while the gentle-shell layout shows.
52
+ export const DESKTOP_KEYS_SECTION = `layout:${DESKTOP_LAYOUT}`;
53
+ // A running Herdr reloads keys.json on its file event and writes keys.error when it rejects it.
54
+ const KEYS_CHECK_ATTEMPTS = 4;
55
+ const KEYS_CHECK_INTERVAL_MS = 250;
56
+ // After starting the window: how long to wait for the keys.json Herdr writes on its first start.
57
+ const KEYS_WAIT_ATTEMPTS = 10;
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+
93
+ export function desktopUsage() {
94
+ return [
95
+ "Usage: gentle-shell desktop [--yes] [--no-open]",
96
+ " gentle-shell desktop --status",
97
+ " gentle-shell desktop --uninstall",
98
+ "",
99
+ `Gentle Shell Desktop is Herdr app (${HERDR_APP_VERSION} or newer, unchanged) with Gentle Shell's`,
100
+ "gentle-* mods and its gentle-shell layout.",
101
+ "",
102
+ " (no option) Install what is missing, then open Herdr on the gentle-shell layout with a",
103
+ " Gentle Shell space in this folder. Shows what it will install and where, and",
104
+ ` asks first. A missing or older Herdr app gets the pinned ${HERDR_APP_VERSION} release`,
105
+ " from releases.herdr.dev, verified against its pinned SHA-256. Each mod must",
106
+ " pass 'herdr-app check' before anything is installed. Only gentle-* mods,",
107
+ " layouts/gentle-shell.json and its light and dark themes (themes/gentle-shell-*.json)",
108
+ " are written in Herdr's home: anything Gentle Shell",
109
+ " did not install there is kept in ~/.gentle-shell/desktop/originals until",
110
+ " --uninstall puts it back; our own previous copy goes to .../desktop/backup.",
111
+ " The Gentle shortcuts (layout:gentle-shell: Cmd-K palette, Cmd-J chat/terminal,",
112
+ " Cmd-. stop, Cmd-Alt-1..6 inspector tabs) are added to Herdr's keys.json; a key",
113
+ " you already bind there stays yours and is reported.",
114
+ " --yes, -y Do not ask (needed when not run in an interactive terminal).",
115
+ " --no-open Install only; do not start or switch Herdr app.",
116
+ " --status Print versions and what is installed.",
117
+ " --uninstall Remove our mods, layout, themes and shortcuts (a copy stays in the backup), put back",
118
+ " what was there before, and switch Herdr back to your previous layout. Herdr",
119
+ " app itself stays installed.",
120
+ " --refresh Reinstall our mods, layout, themes and shortcuts from this Gentle Shell when they are installed;",
121
+ " 'gentle-shell upgrade' runs it. Does nothing if desktop was never installed.",
122
+ ].join("\n");
123
+ }
124
+
125
+
126
+
127
+ function parseDesktopArgs(args ) {
128
+ let yes = false;
129
+ let open = true;
130
+ const actions = [];
131
+ for (const arg of args) {
132
+ if (arg === "--yes" || arg === "-y") yes = true;
133
+ else if (arg === "--no-open") open = false;
134
+ else if (arg === "--status") actions.push("status");
135
+ else if (arg === "--uninstall") actions.push("uninstall");
136
+ else if (arg === "--refresh") actions.push("refresh");
137
+ else if (arg === "--help" || arg === "-h") return { action: "help", yes, open };
138
+ else return { error: `unknown option ${arg}` };
139
+ }
140
+ if (actions.length > 1) return { error: "choose one of --status, --uninstall or --refresh" };
141
+ return { action: actions[0] ?? "open", yes, open };
142
+ }
143
+
144
+ // Whether the Gentle Shell package at `packageRoot` has the `desktop` command:
145
+ // a version without this module treats `desktop` as a prompt for the model, so
146
+ // `gentle-shell upgrade` only asks a package that ships it to refresh.
147
+ export function supportsDesktop(packageRoot ) {
148
+ return existsSync(join(packageRoot, "runtime", "gentle-shell-desktop.mjs")) && existsSync(join(packageRoot, "bin", "gentle-shell.mjs"));
149
+ }
150
+
151
+ // --- paths -------------------------------------------------------------------
152
+
153
+
154
+
155
+
156
+
157
+
158
+
159
+
160
+
161
+
162
+
163
+
164
+
165
+
166
+
167
+
168
+
169
+
170
+
171
+
172
+ const nonEmpty = (value ) => (value !== undefined && value.length > 0 ? value : undefined);
173
+
174
+ // Herdr's own rule (herdr-app src/mods.rs app_dir): $HERDR_APP_HOME, else
175
+ // $XDG_CONFIG_HOME/herdr-app, else ~/.config/herdr-app, on every OS.
176
+ export function desktopPaths(env , home ) {
177
+ const herdrHome = nonEmpty(env.HERDR_APP_HOME) ?? join(nonEmpty(env.XDG_CONFIG_HOME) ?? join(home, ".config"), "herdr-app");
178
+ const stateDir = join(home, ".gentle-shell", "desktop");
179
+ return {
180
+ herdrHome,
181
+ mods: join(herdrHome, "mods"),
182
+ layouts: join(herdrHome, "layouts"),
183
+ layoutFile: join(herdrHome, "layouts", `${DESKTOP_LAYOUT}.json`),
184
+ themes: join(herdrHome, "themes"),
185
+ stateDir,
186
+ stateFile: join(stateDir, "state.json"),
187
+ stage: join(stateDir, "stage"),
188
+ backup: join(stateDir, "backup"),
189
+ backupNext: join(stateDir, "backup.next"),
190
+ originals: join(stateDir, "originals"),
191
+ localBin: join(home, ".local", "bin"),
192
+ // One keys.json on every OS; only Herdr's built-in defaults differ (keys.macos.json on macOS).
193
+ keysFile: join(herdrHome, "keys.json"),
194
+ keysError: join(herdrHome, "keys.error"),
195
+ keysBackup: join(stateDir, "keys-backup.json"),
196
+ keysOriginal: join(stateDir, "originals", "keys.json"),
197
+ };
198
+ }
199
+
200
+ // --- shipped assets ------------------------------------------------------------
201
+
202
+ // Herdr regenerates gpui-kit.d.ts and jsconfig.json next to a mod per version
203
+ // (the mods' own .gitignore); FIDELITY*/SPIKE* are our design notes.
204
+ export function isShippedModFile(name ) {
205
+ if (name === "gpui-kit.d.mjs" || name === "jsconfig.json" || name === ".gitignore") return false;
206
+ return !/^(FIDELITY|SPIKE).*\.md$/.test(name);
207
+ }
208
+
209
+
210
+
211
+
212
+
213
+
214
+
215
+
216
+
217
+
218
+
219
+
220
+
221
+ function shippedAssets(packageRoot ) {
222
+ const root = join(packageRoot, "herdr");
223
+ const modsDir = join(root, "mods");
224
+ const layoutFile = join(root, "layouts", `${DESKTOP_LAYOUT}.json`);
225
+ let mods = [];
226
+ try {
227
+ mods = readdirSync(modsDir).filter((name) => name.startsWith("gentle-") && isDirectory(join(modsDir, name))).sort();
228
+ } catch {
229
+ mods = [];
230
+ }
231
+ if (mods.length === 0 || !existsSync(layoutFile)) return { error: `this Gentle Shell (${packageRoot}) has no herdr/ mods and layout to install` };
232
+ const themesDir = join(root, "themes");
233
+ let themes = [];
234
+ try {
235
+ themes = readdirSync(themesDir).filter((name) => isThemeFile(name) && !isDirectory(join(themesDir, name))).sort();
236
+ } catch {
237
+ themes = [];
238
+ }
239
+ const keysFile = join(root, "keys.json");
240
+ if (!existsSync(keysFile)) return { mods, modsDir, layoutFile, themes, themesDir };
241
+ const keys = readKeysText(readFileSync(keysFile, "utf8"));
242
+ if ("problem" in keys) return { error: `this Gentle Shell's ${keysFile} ${keys.problem}` };
243
+ const section = keys.sections[DESKTOP_KEYS_SECTION] ;
244
+ return { mods, modsDir, layoutFile, themes, themesDir, ...(section ? { keys: { ...section } } : {}) };
245
+ }
246
+
247
+ // Our theme files: themes/gentle-shell-<appearance>.json, named after the layout.
248
+ const isThemeFile = (name ) => new RegExp(`^${DESKTOP_LAYOUT}-[A-Za-z0-9._-]+\\.json$`).test(name);
249
+
250
+ function isDirectory(path ) {
251
+ try {
252
+ return lstatSync(path).isDirectory();
253
+ } catch {
254
+ return false;
255
+ }
256
+ }
257
+
258
+ function shippedFiles(dir , rel = "") {
259
+ const files = [];
260
+ for (const name of readdirSync(join(dir, rel)).sort()) {
261
+ const relPath = rel ? join(rel, name) : name;
262
+ if (isDirectory(join(dir, relPath))) files.push(...shippedFiles(dir, relPath));
263
+ else if (isShippedModFile(name)) files.push(relPath);
264
+ }
265
+ return files;
266
+ }
267
+
268
+ function sameFile(a , b ) {
269
+ try {
270
+ return readFileSync(a).equals(readFileSync(b));
271
+ } catch {
272
+ return false;
273
+ }
274
+ }
275
+
276
+ function assetsUpToDate(assets , paths ) {
277
+ if (!sameFile(assets.layoutFile, paths.layoutFile)) return false;
278
+ if (!assets.themes.every((name) => sameFile(join(assets.themesDir, name), join(paths.themes, name)))) return false;
279
+ return assets.mods.every((mod) => shippedFiles(join(assets.modsDir, mod)).every((file) => sameFile(join(assets.modsDir, mod, file), join(paths.mods, mod, file))));
280
+ }
281
+
282
+ // --- state -------------------------------------------------------------------
283
+
284
+ // The paths in Herdr's home that are ours: `mods` folders, `themes` files and,
285
+ // when `layout`, layouts/gentle-shell.json. Anything else there is the user's.
286
+
287
+
288
+
289
+
290
+
291
+
292
+
293
+
294
+ function readState(paths ) {
295
+ try {
296
+ const parsed = JSON.parse(readFileSync(paths.stateFile, "utf8"));
297
+ const mods = Array.isArray(parsed?.mods) ? parsed.mods.filter((name ) => typeof name === "string" && /^gentle-[A-Za-z0-9._-]+$/.test(name)) : [];
298
+ const previousLayout = typeof parsed?.previousLayout === "string" && parsed.previousLayout !== DESKTOP_LAYOUT ? parsed.previousLayout : undefined;
299
+ const keys = parseKeysState(parsed?.keys);
300
+ const themes = Array.isArray(parsed?.themes) ? parsed.themes.filter((name ) => typeof name === "string" && isThemeFile(name)) : [];
301
+ return { mods, ...(themes.length > 0 ? { themes } : {}), layout: parsed?.layout !== false, ...(previousLayout ? { previousLayout } : {}), ...(keys ? { keys } : {}) };
302
+ } catch {
303
+ return undefined;
304
+ }
305
+ }
306
+
307
+ function writeState(paths , state ) {
308
+ mkdirSync(paths.stateDir, { recursive: true });
309
+ const temp = `${paths.stateFile}.${process.pid}.tmp`;
310
+ writeFileSync(temp, `${JSON.stringify(state, null, 2)}\n`);
311
+ renameSync(temp, paths.stateFile);
312
+ }
313
+
314
+ // --- Herdr app -----------------------------------------------------------------
315
+
316
+ function findOnPath(name , env , platform ) {
317
+ const extensions = platform === "win32" ? (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";") : [""];
318
+ for (const dir of (env.PATH ?? "").split(platform === "win32" ? ";" : delimiter).filter(Boolean)) {
319
+ for (const extension of extensions) {
320
+ const candidate = join(dir, `${name}${extension}`);
321
+ try {
322
+ accessSync(candidate, fsConstants.X_OK);
323
+ if (!isDirectory(candidate)) return candidate;
324
+ } catch {
325
+ // keep looking
326
+ }
327
+ }
328
+ }
329
+ return undefined;
330
+ }
331
+
332
+ export function findHerdrApp(env , home , platform ) {
333
+ const onPath = findOnPath("herdr-app", env, platform);
334
+ if (onPath) return onPath;
335
+ const local = join(home, ".local", "bin", platform === "win32" ? "herdr-app.exe" : "herdr-app");
336
+ return existsSync(local) ? local : undefined;
337
+ }
338
+
339
+ export function compareVersions(a , b ) {
340
+ const parts = (value ) => value.split(".").map((part) => Number.parseInt(part, 10) || 0);
341
+ const left = parts(a);
342
+ const right = parts(b);
343
+ for (let i = 0; i < Math.max(left.length, right.length); i += 1) {
344
+ const diff = (left[i] ?? 0) - (right[i] ?? 0);
345
+ if (diff !== 0) return diff < 0 ? -1 : 1;
346
+ }
347
+ return 0;
348
+ }
349
+
350
+
351
+
352
+
353
+
354
+
355
+ function detectApp(ctx ) {
356
+ const path = findHerdrApp(ctx.env, ctx.home, ctx.platform);
357
+ if (!path) return undefined;
358
+ const result = ctx.io.run(path, ["--version"], { env: ctx.env });
359
+ const version = /herdr-app\s+v?(\d+\.\d+\.\d+)/.exec(`${result.stdout}`)?.[1];
360
+ return { path, ...(version ? { version } : {}) };
361
+ }
362
+
363
+ function herdrTarget(platform , arch ) {
364
+ const cpu = arch === "arm64" ? "aarch64" : arch === "x64" ? "x86_64" : undefined;
365
+ if (!cpu) return undefined;
366
+ if (platform === "darwin") return cpu === "aarch64" ? "macos-aarch64" : undefined;
367
+ if (platform === "linux") return `linux-${cpu}`;
368
+ if (platform === "win32") return cpu === "x86_64" ? "windows-x86_64" : undefined;
369
+ return undefined;
370
+ }
371
+
372
+
373
+
374
+
375
+
376
+
377
+
378
+
379
+
380
+
381
+ function planApp(ctx , installed , release ) {
382
+ if (installed?.version && compareVersions(installed.version, release.version) >= 0) return undefined;
383
+ const target = herdrTarget(ctx.platform, ctx.arch);
384
+ const have = installed ? `Herdr app ${installed.version ?? "(unknown version)"} at ${installed.path} is older than ${release.version}` : `Herdr app ${release.version} or newer is not installed`;
385
+ if (ctx.platform === "win32") {
386
+ return { error: `${have}. Install it with Herdr's official installer, then run gentle-shell desktop again:\n ${OFFICIAL_WINDOWS_INSTALL}` };
387
+ }
388
+ const sha256 = target ? release.sha256[target] : undefined;
389
+ if (!target || !sha256) {
390
+ return { error: `${have}, and Herdr publishes no ${release.version} build for ${ctx.platform}-${ctx.arch}. See https://herdr.dev/download/` };
391
+ }
392
+ const releases = (nonEmpty(ctx.env.HERDR_RELEASES_URL) ?? HERDR_RELEASES_URL).replace(/\/+$/, "");
393
+ const destination = ctx.platform === "darwin"
394
+ ? join(ctx.home, "Applications", "Herdr.app")
395
+ : join(nonEmpty(ctx.env.XDG_DATA_HOME) ?? join(ctx.home, ".local", "share"), "herdr-app");
396
+ return {
397
+ target,
398
+ url: `${releases}/app/${release.version}/herdr-app-${target}.tar.gz`,
399
+ sha256,
400
+ destination,
401
+ link: join(ctx.home, ".local", "bin", "herdr-app"),
402
+ ...(installed ? { replaces: installed } : {}),
403
+ };
404
+ }
405
+
406
+ function replacePath(source , destination , scratch ) {
407
+ const old = join(scratch, "previous");
408
+ const hadOld = existsSync(destination) || isSymlink(destination);
409
+ if (hadOld) moveSync(destination, old);
410
+ try {
411
+ moveSync(source, destination);
412
+ } catch (error) {
413
+ if (hadOld) moveSync(old, destination);
414
+ throw error;
415
+ }
416
+ rmSync(old, { recursive: true, force: true });
417
+ }
418
+
419
+ function isSymlink(path ) {
420
+ try {
421
+ return lstatSync(path).isSymbolicLink();
422
+ } catch {
423
+ return false;
424
+ }
425
+ }
426
+
427
+ function linkBinary(target , link ) {
428
+ mkdirSync(join(link, ".."), { recursive: true });
429
+ if (isSymlink(link) || existsSync(link)) rmSync(link, { force: true });
430
+ symlinkSync(target, link);
431
+ }
432
+
433
+ // The official install.sh steps (herdr-app distribution/install.sh) for one
434
+ // pinned version: download the release tarball, refuse it unless its SHA-256
435
+ // matches the pin, unpack, then place it where the official installer does.
436
+ // herdr-core is not installed here: Herdr app offers to set it up when it opens.
437
+ async function installApp(ctx , paths , plan ) {
438
+ mkdirSync(paths.stateDir, { recursive: true });
439
+ const scratch = join(paths.stateDir, `download-${process.pid}`);
440
+ rmSync(scratch, { recursive: true, force: true });
441
+ mkdirSync(join(scratch, "unpacked"), { recursive: true });
442
+ try {
443
+ const archive = join(scratch, `herdr-app-${plan.target}.tar.gz`);
444
+ ctx.io.out(`Downloading ${plan.url} ...`);
445
+ await ctx.io.download(plan.url, archive);
446
+ const actual = ctx.io.sha256(archive);
447
+ if (actual !== plan.sha256) throw new Error(`the Herdr app download failed its checksum (checksum mismatch: expected ${plan.sha256}, got ${actual}); nothing was installed`);
448
+ const unpack = ctx.io.run("tar", ["-xzf", archive, "-C", join(scratch, "unpacked")], { env: ctx.env });
449
+ if (unpack.status !== 0) throw new Error(`could not unpack ${archive}: ${unpack.stderr || unpack.error?.message || "tar failed"}`);
450
+ if (ctx.platform === "darwin") {
451
+ const app = join(scratch, "unpacked", "Herdr.app");
452
+ if (!existsSync(app)) throw new Error("the Herdr app download has no Herdr.app");
453
+ const signature = ctx.io.verifyMacSignature(app);
454
+ if (signature !== undefined) throw new Error(`the Herdr app download is not validly signed: ${signature}`);
455
+ mkdirSync(join(plan.destination, ".."), { recursive: true });
456
+ replacePath(app, plan.destination, scratch);
457
+ const binary = join(plan.destination, "Contents", "MacOS", "Herdr");
458
+ linkBinary(binary, plan.link);
459
+ ctx.io.run("/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister", ["-f", plan.destination], { env: ctx.env });
460
+ return plan.link;
461
+ }
462
+ const unpacked = join(scratch, "unpacked", "herdr-app");
463
+ if (!existsSync(join(unpacked, "herdr-app"))) throw new Error("the Herdr app download has no herdr-app/herdr-app");
464
+ mkdirSync(join(plan.destination, ".."), { recursive: true });
465
+ replacePath(unpacked, plan.destination, scratch);
466
+ linkBinary(join(plan.destination, "herdr-app"), plan.link);
467
+ const data = join(plan.destination, "..");
468
+ try {
469
+ mkdirSync(join(data, "applications"), { recursive: true });
470
+ mkdirSync(join(data, "icons", "hicolor", "scalable", "apps"), { recursive: true });
471
+ if (existsSync(join(plan.destination, "herdr-app.svg"))) cpSync(join(plan.destination, "herdr-app.svg"), join(data, "icons", "hicolor", "scalable", "apps", "herdr-app.svg"));
472
+ writeFileSync(join(data, "applications", "herdr-app.desktop"), [
473
+ "[Desktop Entry]", "Type=Application", "Name=Herdr", "Comment=Terminals and coding agents that keep running",
474
+ `Exec=${plan.link}`, "Icon=herdr-app", "Terminal=false", "Categories=Development;", "StartupWMClass=herdr-app", "",
475
+ ].join("\n"));
476
+ } catch {
477
+ // The launcher entry is a convenience; the app and its command are installed.
478
+ }
479
+ return plan.link;
480
+ } finally {
481
+ rmSync(scratch, { recursive: true, force: true });
482
+ }
483
+ }
484
+
485
+ // --- mods and layout -----------------------------------------------------------
486
+
487
+ // rename, or copy + remove across file systems ($HERDR_APP_HOME elsewhere).
488
+ function moveSync(source , destination ) {
489
+ try {
490
+ renameSync(source, destination);
491
+ } catch (error) {
492
+ if ((error ).code !== "EXDEV") throw error;
493
+ cpSync(source, destination, { recursive: true, verbatimSymlinks: true });
494
+ rmSync(source, { recursive: true, force: true });
495
+ }
496
+ }
497
+
498
+
499
+
500
+
501
+
502
+
503
+ function rollback(swaps ) {
504
+ for (const swap of [...swaps].reverse()) {
505
+ rmSync(swap.target, { recursive: true, force: true });
506
+ if (swap.movedTo) moveSync(swap.movedTo, swap.target);
507
+ }
508
+ }
509
+
510
+ // Removes each folder that is empty, in order (deepest first); others stay.
511
+ function removeEmptyDirs(dirs ) {
512
+ for (const dir of dirs) {
513
+ try {
514
+ rmdirSync(dir);
515
+ } catch {
516
+ // not empty, or already gone
517
+ }
518
+ }
519
+ }
520
+
521
+ function promoteBackup(paths ) {
522
+ const kept = existsSync(paths.backupNext) && readdirSync(paths.backupNext).some((name) => readdirSync(join(paths.backupNext, name)).length > 0);
523
+ if (kept) {
524
+ rmSync(paths.backup, { recursive: true, force: true });
525
+ moveSync(paths.backupNext, paths.backup);
526
+ } else {
527
+ rmSync(paths.backupNext, { recursive: true, force: true });
528
+ }
529
+ }
530
+
531
+ function prepareScratch(paths ) {
532
+ for (const dir of [paths.stage, paths.backupNext]) rmSync(dir, { recursive: true, force: true });
533
+ for (const kind of ["mods", "layouts", "themes"]) for (const dir of [join(paths.stage, kind), join(paths.backupNext, kind)]) mkdirSync(dir, { recursive: true });
534
+ }
535
+
536
+ function cleanOriginals(paths ) {
537
+ removeEmptyDirs([join(paths.originals, "mods"), join(paths.originals, "layouts"), join(paths.originals, "themes"), paths.originals]);
538
+ }
539
+
540
+ // Where a path in Herdr's home goes when it is replaced or removed: our own
541
+ // copy rotates through backup.next; anything else is an original, kept until
542
+ // --uninstall. An original is never overwritten.
543
+ function moveAside(target , ours , backupName , originalName ) {
544
+ if (ours) {
545
+ moveSync(target, backupName);
546
+ return backupName;
547
+ }
548
+ if (existsSync(originalName) || isSymlink(originalName)) {
549
+ throw new Error(`${target} was not installed by Gentle Shell Desktop and ${originalName} already keeps an earlier original; move one of them elsewhere and run gentle-shell desktop again`);
550
+ }
551
+ mkdirSync(join(originalName, ".."), { recursive: true });
552
+ moveSync(target, originalName);
553
+ return originalName;
554
+ }
555
+
556
+ // Stages our mods and layout and runs `herdr-app check` on every staged mod;
557
+ // only then swaps each into Herdr's home. A path that was ours moves to the
558
+ // backup; anything else moves to the originals. Any failure puts every
559
+ // previous copy back and removes folders this install created.
560
+ function installAssets(ctx , paths , assets , app , previous ) {
561
+ prepareScratch(paths);
562
+ const ownedMods = previous?.mods ?? [];
563
+ const ownedThemes = previous?.themes ?? [];
564
+ const ownedLayout = previous?.layout === true;
565
+ try {
566
+ for (const mod of assets.mods) {
567
+ const staged = join(paths.stage, "mods", mod);
568
+ mkdirSync(staged);
569
+ for (const file of shippedFiles(join(assets.modsDir, mod))) {
570
+ mkdirSync(join(staged, file, ".."), { recursive: true });
571
+ cpSync(join(assets.modsDir, mod, file), join(staged, file));
572
+ }
573
+ }
574
+ cpSync(assets.layoutFile, join(paths.stage, "layouts", `${DESKTOP_LAYOUT}.json`));
575
+ for (const name of assets.themes) cpSync(join(assets.themesDir, name), join(paths.stage, "themes", name));
576
+ } catch (error) {
577
+ rmSync(paths.stage, { recursive: true, force: true });
578
+ rmSync(paths.backupNext, { recursive: true, force: true });
579
+ return `could not stage the Gentle mods in ${paths.stage}: ${(error ).message}; nothing in ${paths.herdrHome} was changed`;
580
+ }
581
+ for (const mod of assets.mods) {
582
+ const result = ctx.io.run(app, ["check", join(paths.stage, "mods", mod)], { env: ctx.env });
583
+ if (result.status !== 0) {
584
+ rmSync(paths.stage, { recursive: true, force: true });
585
+ rmSync(paths.backupNext, { recursive: true, force: true });
586
+ const detail = `${result.stderr}${result.stdout}`.trim() || result.error?.message || `exit ${result.status}`;
587
+ return `herdr-app check failed for ${mod}:\n${detail}\nthe Gentle mods and layout were not installed; nothing in ${paths.herdrHome} was changed`;
588
+ }
589
+ }
590
+ const created = [paths.layouts, paths.mods, ...(assets.themes.length > 0 ? [paths.themes] : []), paths.herdrHome].filter((dir) => !existsSync(dir));
591
+ const swaps = [];
592
+ const swapIn = (staged , target , ours , kind , name ) => {
593
+ const swap = { target };
594
+ if (existsSync(target) || isSymlink(target)) swap.movedTo = moveAside(target, ours, join(paths.backupNext, kind, name), join(paths.originals, kind, name));
595
+ swaps.push(swap);
596
+ if (staged) moveSync(staged, target);
597
+ };
598
+ try {
599
+ mkdirSync(paths.mods, { recursive: true });
600
+ mkdirSync(paths.layouts, { recursive: true });
601
+ for (const mod of assets.mods) swapIn(join(paths.stage, "mods", mod), join(paths.mods, mod), ownedMods.includes(mod), "mods", mod);
602
+ // A gentle-* mod an earlier Gentle Shell installed and this one no longer ships;
603
+ // what was there before it comes back.
604
+ for (const mod of ownedMods) {
605
+ if (assets.mods.includes(mod)) continue;
606
+ const target = join(paths.mods, mod);
607
+ if (existsSync(target)) swapIn("", target, true, "mods", mod);
608
+ const original = join(paths.originals, "mods", mod);
609
+ if (existsSync(original)) {
610
+ moveSync(original, target);
611
+ swaps.push({ target: original, movedTo: target });
612
+ }
613
+ }
614
+ // The layout's themes go in before the layout that names them.
615
+ if (assets.themes.length > 0) mkdirSync(paths.themes, { recursive: true });
616
+ for (const name of assets.themes) swapIn(join(paths.stage, "themes", name), join(paths.themes, name), ownedThemes.includes(name), "themes", name);
617
+ // A theme an earlier Gentle Shell installed and this one no longer ships; what was there before comes back.
618
+ for (const name of ownedThemes) {
619
+ if (assets.themes.includes(name)) continue;
620
+ const target = join(paths.themes, name);
621
+ if (existsSync(target)) swapIn("", target, true, "themes", name);
622
+ const original = join(paths.originals, "themes", name);
623
+ if (existsSync(original)) {
624
+ moveSync(original, target);
625
+ swaps.push({ target: original, movedTo: target });
626
+ }
627
+ }
628
+ swapIn(join(paths.stage, "layouts", `${DESKTOP_LAYOUT}.json`), paths.layoutFile, ownedLayout, "layouts", `${DESKTOP_LAYOUT}.json`);
629
+ } catch (error) {
630
+ rollback(swaps);
631
+ removeEmptyDirs(created);
632
+ cleanOriginals(paths);
633
+ rmSync(paths.stage, { recursive: true, force: true });
634
+ rmSync(paths.backupNext, { recursive: true, force: true });
635
+ return `could not install the Gentle mods into ${paths.herdrHome}: ${(error ).message}; restored the previous Gentle mods and layout`;
636
+ }
637
+ rmSync(paths.stage, { recursive: true, force: true });
638
+ promoteBackup(paths);
639
+ return undefined;
640
+ }
641
+
642
+ // --- keys.json ---------------------------------------------------------------------
643
+
644
+ // keys.json is the whole keymap: Herdr writes its defaults there on first start
645
+ // and never layers them under it (herdr-app src/keys.rs), so Gentle Shell only
646
+ // ever edits an existing file, as text: every byte outside the entries it adds
647
+ // stays as the person wrote it. state.json's `keys` is the tag: the entries in
648
+ // `entries` are ours while they still hold the action we wrote; a Gentle key
649
+ // the person deleted or rebound is theirs (`dropped`) and is never added again.
650
+
651
+
652
+
653
+
654
+
655
+
656
+
657
+
658
+
659
+
660
+
661
+
662
+
663
+
664
+
665
+
666
+ const isPlainObject = (value ) => typeof value === "object" && value !== null && !Array.isArray(value);
667
+ const stringList = (value ) => (Array.isArray(value) ? value.filter((item) => typeof item === "string") : []);
668
+
669
+ function parseKeysState(value ) {
670
+ if (!isPlainObject(value) || !isPlainObject(value.entries) || typeof value.written !== "string") return undefined;
671
+ const entries = {};
672
+ for (const [key, action] of Object.entries(value.entries)) if (typeof action === "string" || isPlainObject(action)) entries[key] = action;
673
+ return { entries, dropped: stringList(value.dropped), conflicts: stringList(value.conflicts), createdSection: value.createdSection === true, written: value.written, ...(typeof value.firstWritten === "string" ? { firstWritten: value.firstWritten } : {}) };
674
+ }
675
+
676
+ const sha256Text = (text ) => createHash("sha256").update(text).digest("hex");
677
+ const sameAction = (a , b ) => JSON.stringify(a) === JSON.stringify(b);
678
+
679
+ // Herdr's sections (keys.rs `tab`): anything else makes Herdr reject the whole file.
680
+ const knownSection = (name ) => name === "global" || name === "terminal" || /^(layout|mod):.+$/.test(name);
681
+
682
+ function readKeysText(text ) {
683
+ let parsed ;
684
+ try {
685
+ parsed = JSON.parse(text);
686
+ } catch (error) {
687
+ return { problem: `is not valid JSON (${(error ).message})` };
688
+ }
689
+ if (!isPlainObject(parsed)) return { problem: "must be a JSON object of sections (global, terminal, layout:<name>, mod:<name>)" };
690
+ for (const [section, bindings] of Object.entries(parsed)) {
691
+ if (!knownSection(section)) return { problem: `is not a keys file Herdr accepts: section ${JSON.stringify(section)} is not global, terminal, layout:<name> or mod:<name>` };
692
+ if (!isPlainObject(bindings)) return { problem: `is not a keys file Herdr accepts: ${section} must be an object of key bindings` };
693
+ for (const [keys, action] of Object.entries(bindings)) {
694
+ if (typeof action !== "string" && !isPlainObject(action)) return { problem: `is not a keys file Herdr accepts: ${section}.${keys} must be a command string or an object` };
695
+ }
696
+ }
697
+ return { sections: parsed };
698
+ }
699
+
700
+ // The same keystroke however it is spelled: modifiers in any order and case, cmd = super = win.
701
+ export function normalizeKeystroke(keys ) {
702
+ const alias = { super: "cmd", win: "cmd", command: "cmd", option: "alt", control: "ctrl" };
703
+ return keys.trim().split(/\s+/).map((stroke) => {
704
+ if (stroke === "-") return "-";
705
+ const parts = stroke.endsWith("--") ? [...stroke.slice(0, -2).split("-"), "-"] : stroke.split("-");
706
+ const key = (parts.pop() ?? "").toLowerCase();
707
+ const modifiers = parts.map((part) => alias[part.toLowerCase()] ?? part.toLowerCase());
708
+ return [...new Set(modifiers)].sort().concat(key).join("-");
709
+ }).join(" ");
710
+ }
711
+
712
+ // A minimal scanner for text JSON.parse already accepted: where each member of an
713
+ // object starts and ends, so entries are added, replaced or removed in place.
714
+
715
+
716
+
717
+
718
+
719
+
720
+
721
+
722
+
723
+
724
+
725
+
726
+
727
+ const isJsonSpace = (char ) => char === " " || char === "\t" || char === "\n" || char === "\r";
728
+
729
+ function skipSpace(text , index ) {
730
+ let i = index;
731
+ while (isJsonSpace(text[i])) i += 1;
732
+ return i;
733
+ }
734
+
735
+ function skipString(text , index ) {
736
+ let i = index + 1;
737
+ while (text[i] !== '"') i += text[i] === "\\" ? 2 : 1;
738
+ return i + 1;
739
+ }
740
+
741
+ function skipValue(text , index ) {
742
+ const first = text[index];
743
+ if (first === '"') return skipString(text, index);
744
+ if (first === "{" || first === "[") {
745
+ let depth = 0;
746
+ let i = index;
747
+ for (;;) {
748
+ const char = text[i];
749
+ if (char === '"') {
750
+ i = skipString(text, i);
751
+ continue;
752
+ }
753
+ if (char === "{" || char === "[") depth += 1;
754
+ else if (char === "}" || char === "]") {
755
+ depth -= 1;
756
+ if (depth === 0) return i + 1;
757
+ }
758
+ i += 1;
759
+ }
760
+ }
761
+ let i = index;
762
+ while (i < text.length && !isJsonSpace(text[i]) && text[i] !== "," && text[i] !== "}" && text[i] !== "]") i += 1;
763
+ return i;
764
+ }
765
+
766
+ function objectAt(text , open ) {
767
+ const members = [];
768
+ let i = skipSpace(text, open + 1);
769
+ if (text[i] === "}") return { open, close: i, members };
770
+ for (;;) {
771
+ const keyStart = skipSpace(text, i);
772
+ const keyEnd = skipString(text, keyStart);
773
+ const valueStart = skipSpace(text, skipSpace(text, keyEnd) + 1);
774
+ const valueEnd = skipValue(text, valueStart);
775
+ members.push({ key: JSON.parse(text.slice(keyStart, keyEnd)), keyStart, valueStart, valueEnd });
776
+ i = skipSpace(text, valueEnd);
777
+ if (text[i] !== ",") return { open, close: i, members };
778
+ i += 1;
779
+ }
780
+ }
781
+
782
+ // JSON.parse keeps the last of duplicate keys; so do we.
783
+ const lastMember = (object , key ) => {
784
+ for (let i = object.members.length - 1; i >= 0; i -= 1) if (object.members[i].key === key) return i;
785
+ return -1;
786
+ };
787
+
788
+ // The whitespace from the start of the line to `index`, when only whitespace precedes it there.
789
+ function indentAt(text , index ) {
790
+ if (index === undefined) return undefined;
791
+ const lineStart = text.lastIndexOf("\n", index - 1) + 1;
792
+ const before = text.slice(lineStart, index);
793
+ return lineStart > 0 && /^[ \t]*$/.test(before) ? before : undefined;
794
+ }
795
+
796
+ function sectionAt(text ) {
797
+ const root = objectAt(text, skipSpace(text, 0));
798
+ const index = lastMember(root, DESKTOP_KEYS_SECTION);
799
+ const member = root.members[index];
800
+ return { root, index, ...(member && text[member.valueStart] === "{" ? { section: objectAt(text, member.valueStart) } : {}) };
801
+ }
802
+
803
+ // Appends `"key": value` after the last member, or fills an empty object.
804
+ function insertMember(text , object , key , value , indent , closeIndent ) {
805
+ const last = object.members.at(-1);
806
+ if (last) return `${text.slice(0, last.valueEnd)},\n${indent}${JSON.stringify(key)}: ${value}${text.slice(last.valueEnd)}`;
807
+ return `${text.slice(0, object.open + 1)}\n${indent}${JSON.stringify(key)}: ${value}\n${closeIndent}${text.slice(object.close)}`;
808
+ }
809
+
810
+ // The inverse of insertMember: the member and the separator before it.
811
+ function removeMember(text , object , index ) {
812
+ const member = object.members[index];
813
+ if (object.members.length === 1) return `${text.slice(0, object.open + 1)}${text.slice(object.close)}`;
814
+ if (index > 0) return `${text.slice(0, object.members[index - 1].valueEnd)}${text.slice(member.valueEnd)}`;
815
+ return `${text.slice(0, member.keyStart)}${text.slice(object.members[1].keyStart)}`;
816
+ }
817
+
818
+ function addKey(text , key , action ) {
819
+ let at = sectionAt(text);
820
+ const unit = indentAt(text, at.root.members[0]?.keyStart) ?? " ";
821
+ if (!at.section) {
822
+ text = insertMember(text, at.root, DESKTOP_KEYS_SECTION, "{}", unit, "");
823
+ at = sectionAt(text);
824
+ }
825
+ const section = at.section ;
826
+ const sectionIndent = indentAt(text, at.root.members[at.index].keyStart) ?? unit;
827
+ const indent = indentAt(text, section.members[0]?.keyStart) ?? `${sectionIndent}${unit}`;
828
+ return insertMember(text, section, key, JSON.stringify(action), indent, sectionIndent);
829
+ }
830
+
831
+ function replaceKey(text , key , action ) {
832
+ const { section } = sectionAt(text);
833
+ const member = section?.members[lastMember(section, key)];
834
+ return member ? `${text.slice(0, member.valueStart)}${JSON.stringify(action)}${text.slice(member.valueEnd)}` : text;
835
+ }
836
+
837
+ function removeKey(text , key ) {
838
+ const { section } = sectionAt(text);
839
+ const index = section ? lastMember(section, key) : -1;
840
+ return section && index >= 0 ? removeMember(text, section, index) : text;
841
+ }
842
+
843
+ // The section Gentle Shell added, once nothing is left in it.
844
+ function removeEmptySection(text , created ) {
845
+ const at = sectionAt(text);
846
+ return created && at.section && at.section.members.length === 0 ? removeMember(text, at.root, at.index) : text;
847
+ }
848
+
849
+
850
+
851
+
852
+
853
+
854
+
855
+
856
+
857
+
858
+
859
+
860
+
861
+
862
+
863
+ // keys.json text with `shipped` (our layout:gentle-shell entries) merged in.
864
+ // `previous` says which entries are ours from an earlier merge.
865
+ function mergeKeys(original , shipped , previous ) {
866
+ const read = readKeysText(original);
867
+ if ("problem" in read) return read;
868
+ let text = original;
869
+ const sectionNow = () => (JSON.parse(text) )[DESKTOP_KEYS_SECTION] ?? {};
870
+ const own = (object , key ) => (Object.hasOwn(object, key) ? object[key] : undefined);
871
+ const entries = {};
872
+ const dropped = new Set(previous?.dropped ?? []);
873
+ const createdSection = previous ? previous.createdSection : !Object.hasOwn(read.sections, DESKTOP_KEYS_SECTION);
874
+ for (const [key, action] of Object.entries(previous?.entries ?? {})) {
875
+ const value = own(sectionNow(), key);
876
+ if (value === undefined || !sameAction(value, action)) {
877
+ dropped.add(key);
878
+ continue;
879
+ }
880
+ if (!Object.hasOwn(shipped, key)) {
881
+ text = removeKey(text, key);
882
+ continue;
883
+ }
884
+ if (!sameAction(shipped[key], value)) text = replaceKey(text, key, shipped[key]);
885
+ entries[key] = shipped[key];
886
+ }
887
+ const added = [];
888
+ const conflicts = [];
889
+ for (const [key, action] of Object.entries(shipped)) {
890
+ if (Object.hasOwn(entries, key) || dropped.has(key)) continue;
891
+ const section = sectionNow();
892
+ const theirs = Object.keys(section).find((bound) => normalizeKeystroke(bound) === normalizeKeystroke(key));
893
+ if (theirs !== undefined) {
894
+ if (theirs !== key || !sameAction(section[theirs], action)) conflicts.push({ key, theirs, theirAction: section[theirs], action });
895
+ continue;
896
+ }
897
+ text = addKey(text, key, action);
898
+ entries[key] = action;
899
+ added.push(key);
900
+ }
901
+ text = removeEmptySection(text, createdSection);
902
+ // What we wrote must read back as exactly what we meant.
903
+ const check = readKeysText(text);
904
+ if ("problem" in check || Object.entries(entries).some(([key, action]) => !sameAction(own(sectionNow(), key), action))) {
905
+ return { problem: "could not be merged safely" };
906
+ }
907
+ return { text, keys: { entries, dropped: [...dropped], conflicts: conflicts.map((conflict) => conflict.key), createdSection }, added, conflicts };
908
+ }
909
+
910
+ // keys.json without the entries that are still ours.
911
+ function unmergeKeys(original , previous ) {
912
+ const read = readKeysText(original);
913
+ if ("problem" in read) return read;
914
+ const section = read.sections[DESKTOP_KEYS_SECTION] ?? {};
915
+ let text = original;
916
+ for (const [key, action] of Object.entries(previous.entries)) {
917
+ if (Object.hasOwn(section, key) && sameAction(section[key], action)) text = removeKey(text, key);
918
+ }
919
+ return removeEmptySection(text, previous.createdSection);
920
+ }
921
+
922
+ function writeAtomic(file , text ) {
923
+ let mode = 0o644;
924
+ try {
925
+ mode = statSync(file).mode & 0o777;
926
+ } catch {
927
+ // a new file
928
+ }
929
+ const temp = `${file}.gentle-${process.pid}.tmp`;
930
+ writeFileSync(temp, text, { mode });
931
+ renameSync(temp, file);
932
+ }
933
+
934
+ const keysRefusal = (subject ) => `gentle-shell desktop: ${subject}; it was not changed and the Gentle shortcuts were not added. Fix it and run gentle-shell desktop again.`;
935
+
936
+ // Writes keys.json atomically, the previous file kept in keys-backup.json. A
937
+ // running Herdr reloads it at once: if it writes keys.error, the previous file
938
+ // goes back. Returns why it did not apply, or undefined.
939
+ async function writeKeys(ctx , paths , previousText , text , running ) {
940
+ mkdirSync(paths.stateDir, { recursive: true });
941
+ writeAtomic(paths.keysBackup, previousText);
942
+ writeAtomic(paths.keysFile, text);
943
+ if (!running) return undefined;
944
+ for (let attempt = 0; attempt < KEYS_CHECK_ATTEMPTS; attempt += 1) {
945
+ await ctx.io.sleep(KEYS_CHECK_INTERVAL_MS);
946
+ if (existsSync(paths.keysError)) {
947
+ const why = readTextOr(paths.keysError).trim() || "keys.error";
948
+ writeAtomic(paths.keysFile, previousText);
949
+ return why;
950
+ }
951
+ }
952
+ return undefined;
953
+ }
954
+
955
+ function readTextOr(file ) {
956
+ try {
957
+ return readFileSync(file, "utf8");
958
+ } catch {
959
+ return "";
960
+ }
961
+ }
962
+
963
+ const isRunning = (ctx , app ) => app !== undefined && windowStatus(ctx, app) !== undefined;
964
+
965
+ // Adds or refreshes our shortcuts in keys.json. "missing": Herdr has not written
966
+ // keys.json yet (it does on its first start), so nothing was done.
967
+ async function syncKeys(ctx , paths , shipped , app ) {
968
+ const state = readState(paths);
969
+ if (!state) return "failed";
970
+ if (!existsSync(paths.keysFile)) return "missing";
971
+ const original = readFileSync(paths.keysFile, "utf8");
972
+ const merged = mergeKeys(original, shipped, state.keys);
973
+ if ("problem" in merged) {
974
+ ctx.io.err(keysRefusal(`${paths.keysFile} ${merged.problem}`));
975
+ return "failed";
976
+ }
977
+ const changed = merged.text !== original;
978
+ const running = changed && isRunning(ctx, app);
979
+ if (running && existsSync(paths.keysError)) {
980
+ ctx.io.err(keysRefusal(`Herdr app reports a problem in your ${paths.keysFile} (${readTextOr(paths.keysError).trim()})`));
981
+ return "failed";
982
+ }
983
+ if (changed) {
984
+ if (!state.keys) {
985
+ mkdirSync(join(paths.keysOriginal, ".."), { recursive: true });
986
+ writeAtomic(paths.keysOriginal, original);
987
+ }
988
+ const rejected = await writeKeys(ctx, paths, original, merged.text, running);
989
+ if (rejected !== undefined) {
990
+ if (!state.keys) rmSync(paths.keysOriginal, { force: true });
991
+ cleanOriginals(paths);
992
+ ctx.io.err(`gentle-shell desktop: Herdr app did not accept the Gentle shortcuts (${rejected}); put back the previous ${paths.keysFile}.`);
993
+ return "failed";
994
+ }
995
+ }
996
+ const known = new Set(state.keys?.conflicts ?? []);
997
+ for (const conflict of merged.conflicts) {
998
+ if (known.has(conflict.key)) continue;
999
+ ctx.io.err(`gentle-shell desktop: your ${paths.keysFile} binds ${conflict.theirs} to ${JSON.stringify(conflict.theirAction)} in ${DESKTOP_KEYS_SECTION}; kept yours, so the Gentle shortcut ${conflict.key} (${typeof conflict.action === "string" ? conflict.action : JSON.stringify(conflict.action)}) was not added.`);
1000
+ }
1001
+ const written = changed ? sha256Text(merged.text) : state.keys?.written ?? sha256Text(original);
1002
+ const firstWritten = state.keys ? state.keys.firstWritten : changed ? written : undefined;
1003
+ writeState(paths, { ...state, keys: { ...merged.keys, written, ...(firstWritten ? { firstWritten } : {}) } });
1004
+ if (merged.added.length > 0) ctx.io.out(`Added the Gentle shortcuts ${merged.added.join(", ")} to ${paths.keysFile} (${DESKTOP_KEYS_SECTION}); the previous file is in ${paths.keysBackup}.`);
1005
+ else if (changed) ctx.io.out(`Updated the Gentle shortcuts in ${paths.keysFile} (${DESKTOP_KEYS_SECTION}); the previous file is in ${paths.keysBackup}.`);
1006
+ return "done";
1007
+ }
1008
+
1009
+ // Removes the entries that are still ours. Returns false when keys.json could not be changed.
1010
+ async function removeKeys(ctx , paths , keys , app ) {
1011
+ if (!existsSync(paths.keysFile)) {
1012
+ rmSync(paths.keysOriginal, { force: true });
1013
+ return true;
1014
+ }
1015
+ const current = readFileSync(paths.keysFile, "utf8");
1016
+ // Untouched since our first write: the file from before Gentle Shell, byte for byte.
1017
+ const text = sha256Text(current) === keys.firstWritten && existsSync(paths.keysOriginal) ? readFileSync(paths.keysOriginal, "utf8") : unmergeKeys(current, keys);
1018
+ if (typeof text !== "string") {
1019
+ ctx.io.err(`gentle-shell desktop: ${paths.keysFile} ${text.problem}; it was not changed, so the Gentle shortcuts are still in it. Fix it and run gentle-shell desktop --uninstall again.`);
1020
+ return false;
1021
+ }
1022
+ if (text !== current) {
1023
+ const rejected = await writeKeys(ctx, paths, current, text, isRunning(ctx, app));
1024
+ if (rejected !== undefined) {
1025
+ ctx.io.err(`gentle-shell desktop: Herdr app did not accept ${paths.keysFile} without the Gentle shortcuts (${rejected}); put it back as it was.`);
1026
+ return false;
1027
+ }
1028
+ }
1029
+ rmSync(paths.keysOriginal, { force: true });
1030
+ ctx.io.out(`Removed the Gentle shortcuts from ${paths.keysFile}; your own keys are unchanged.`);
1031
+ return true;
1032
+ }
1033
+
1034
+ // --- the Herdr window ------------------------------------------------------------
1035
+
1036
+ function windowStatus(ctx , app ) {
1037
+ const result = ctx.io.run(app, ["status"], { env: ctx.env });
1038
+ if (result.status !== 0) return undefined;
1039
+ try {
1040
+ const parsed = JSON.parse(result.stdout);
1041
+ return { ...(typeof parsed?.layout === "string" ? { layout: parsed.layout } : {}), errors: Array.isArray(parsed?.errors) ? parsed.errors : [] };
1042
+ } catch {
1043
+ return { errors: [] };
1044
+ }
1045
+ }
1046
+
1047
+ async function ensureWindow(ctx , app ) {
1048
+ const running = windowStatus(ctx, app);
1049
+ if (running) return running;
1050
+ ctx.io.out("Starting Herdr app ...");
1051
+ ctx.io.spawnDetached(app, [], { env: ctx.env, cwd: ctx.cwd });
1052
+ for (let attempt = 0; attempt < START_ATTEMPTS; attempt += 1) {
1053
+ await ctx.io.sleep(START_INTERVAL_MS);
1054
+ const status = windowStatus(ctx, app);
1055
+ if (status) return status;
1056
+ }
1057
+ return undefined;
1058
+ }
1059
+
1060
+ function sameFolder(a , b ) {
1061
+ if (typeof a !== "string") return false;
1062
+ const real = (path ) => {
1063
+ try {
1064
+ return realpathSync(path);
1065
+ } catch {
1066
+ return path;
1067
+ }
1068
+ };
1069
+ return real(a) === real(b);
1070
+ }
1071
+
1072
+ function hasGentleSpace(listing , cwd ) {
1073
+ const spaces = (listing )?.spaces;
1074
+ if (!Array.isArray(spaces)) return false;
1075
+ return spaces.some((space) => sameFolder(space?.folder, cwd) && Array.isArray(space?.tabs)
1076
+ && space.tabs.some((tab ) => Array.isArray(tab?.terminals) && tab.terminals.some((terminal ) => terminal?.app === "gentle-shell")));
1077
+ }
1078
+
1079
+ function herdrDo(ctx , app , command , payload ) {
1080
+ return ctx.io.run(app, ["do", command, JSON.stringify(payload)], { env: ctx.env, cwd: ctx.cwd });
1081
+ }
1082
+
1083
+ const keysDeferred = (paths ) => `Herdr writes ${paths.keysFile} when its window first opens; the Gentle shortcuts are added the next time gentle-shell desktop opens Herdr.`;
1084
+
1085
+ async function openDesktop(ctx , paths , app , keys ) {
1086
+ const status = await ensureWindow(ctx, app);
1087
+ if (!status) {
1088
+ ctx.io.err("gentle-shell desktop: Herdr app did not open its window. Open Herdr (it may ask to set up herdr-core), then run gentle-shell desktop again.");
1089
+ return 1;
1090
+ }
1091
+ // Shortcuts waiting for the keys.json Herdr writes on its first start.
1092
+ if (keys) {
1093
+ for (let attempt = 0; attempt < KEYS_WAIT_ATTEMPTS && !existsSync(paths.keysFile); attempt += 1) await ctx.io.sleep(START_INTERVAL_MS);
1094
+ if ((await syncKeys(ctx, paths, keys, app)) === "missing") ctx.io.out(keysDeferred(paths));
1095
+ }
1096
+ const state = readState(paths);
1097
+ if (state && status.layout && status.layout !== DESKTOP_LAYOUT && state.previousLayout !== status.layout) {
1098
+ writeState(paths, { ...state, previousLayout: status.layout });
1099
+ }
1100
+ const switched = herdrDo(ctx, app, "layout.switch", { name: DESKTOP_LAYOUT });
1101
+ if (switched.status !== 0) {
1102
+ ctx.io.err(`gentle-shell desktop: Herdr app could not switch to the ${DESKTOP_LAYOUT} layout: ${`${switched.stderr}${switched.stdout}`.trim() || `exit ${switched.status}`}`);
1103
+ return 1;
1104
+ }
1105
+ const listed = ctx.io.run(app, ["ls"], { env: ctx.env });
1106
+ let listing ;
1107
+ try {
1108
+ listing = JSON.parse(listed.stdout);
1109
+ } catch {
1110
+ listing = undefined;
1111
+ }
1112
+ if (listed.status === 0 && !hasGentleSpace(listing, ctx.cwd)) {
1113
+ const created = herdrDo(ctx, app, "space.new", { folder: ctx.cwd, argv: ["gentle-shell"] });
1114
+ if (created.status !== 0) ctx.io.err(`gentle-shell desktop: could not open a Gentle Shell space in ${ctx.cwd}: ${`${created.stderr}${created.stdout}`.trim()}`);
1115
+ }
1116
+ const after = windowStatus(ctx, app);
1117
+ if (after && after.errors.length > 0) ctx.io.err(`gentle-shell desktop: Herdr app reports: ${JSON.stringify(after.errors)}`);
1118
+ ctx.io.out(`Herdr app is showing the ${DESKTOP_LAYOUT} layout.`);
1119
+ return 0;
1120
+ }
1121
+
1122
+ // --- commands ----------------------------------------------------------------------
1123
+
1124
+ function printStatus(ctx , paths , assets , release ) {
1125
+ const app = detectApp(ctx);
1126
+ const shipped = "mods" in assets ? assets.mods : [];
1127
+ const installed = (readState(paths)?.mods ?? []).concat(shipped).filter((mod, index, all) => all.indexOf(mod) === index && existsSync(join(paths.mods, mod))).sort();
1128
+ const missing = shipped.filter((mod) => !installed.includes(mod));
1129
+ const window = app ? windowStatus(ctx, app.path) : undefined;
1130
+ const needs = `needs ${release.version} or newer`;
1131
+ ctx.io.out("Gentle Shell Desktop");
1132
+ ctx.io.out(` Gentle Shell: ${ctx.shellVersion}`);
1133
+ ctx.io.out(app ? ` Herdr app: ${app.version ?? "unknown version"} at ${app.path} (${needs})` : ` Herdr app: not installed (${needs})`);
1134
+ ctx.io.out(` Herdr home: ${paths.herdrHome}`);
1135
+ ctx.io.out(existsSync(paths.layoutFile) ? ` Layout ${DESKTOP_LAYOUT}: installed at ${paths.layoutFile}` : ` Layout ${DESKTOP_LAYOUT}: not installed`);
1136
+ const themes = "mods" in assets ? assets.themes : [];
1137
+ if (themes.length > 0) {
1138
+ const present = themes.filter((name) => existsSync(join(paths.themes, name)));
1139
+ ctx.io.out(present.length === 0 ? ` Themes: none installed (ships ${themes.join(", ")})` : ` Themes: ${present.join(", ")} installed in ${paths.themes}${present.length < themes.length ? `; missing ${themes.filter((name) => !present.includes(name)).join(", ")}` : ""}`);
1140
+ }
1141
+ if (installed.length === 0) ctx.io.out(` Mods: none installed (ships ${shipped.join(", ")})`);
1142
+ else ctx.io.out(` Mods: ${installed.join(", ")} installed in ${paths.mods}${missing.length > 0 ? `; missing ${missing.join(", ")}` : ""}`);
1143
+ if ("mods" in assets && assets.keys) {
1144
+ const keys = readState(paths)?.keys;
1145
+ ctx.io.out(keys ? ` Keys: ${Object.keys(keys.entries).length} Gentle shortcuts in ${paths.keysFile} (${DESKTOP_KEYS_SECTION})` : " Keys: Gentle shortcuts not added");
1146
+ }
1147
+ ctx.io.out(window ? ` Window: running, layout ${window.layout ?? "unknown"}` : " Window: not running");
1148
+ return 0;
1149
+ }
1150
+
1151
+ async function uninstall(ctx , paths ) {
1152
+ const state = readState(paths);
1153
+ const ours = (state?.mods ?? []).filter((mod) => existsSync(join(paths.mods, mod)));
1154
+ const layoutOurs = state?.layout === true && existsSync(paths.layoutFile);
1155
+ const themesOurs = (state?.themes ?? []).filter((name) => existsSync(join(paths.themes, name)));
1156
+ if (ours.length === 0 && !layoutOurs && themesOurs.length === 0 && !state?.keys) {
1157
+ rmSync(paths.stateFile, { force: true });
1158
+ ctx.io.out(`Gentle Shell Desktop mods and layout are not installed in ${paths.herdrHome}; nothing to remove.`);
1159
+ return 0;
1160
+ }
1161
+ const app = detectApp(ctx);
1162
+ const keysKept = state?.keys && !(await removeKeys(ctx, paths, state.keys, app?.path)) ? state.keys : undefined;
1163
+ const restored = [];
1164
+ if (ours.length > 0 || layoutOurs || themesOurs.length > 0) {
1165
+ prepareScratch(paths);
1166
+ rmSync(paths.stage, { recursive: true, force: true });
1167
+ const putBack = (kind , name , target ) => {
1168
+ const original = join(paths.originals, kind, name);
1169
+ if (!existsSync(original) && !isSymlink(original)) return;
1170
+ moveSync(original, target);
1171
+ restored.push(kind === "mods" ? `mods ${name}` : kind === "themes" ? `theme ${name}` : `layout ${DESKTOP_LAYOUT}`);
1172
+ };
1173
+ for (const mod of ours) {
1174
+ moveSync(join(paths.mods, mod), join(paths.backupNext, "mods", mod));
1175
+ putBack("mods", mod, join(paths.mods, mod));
1176
+ }
1177
+ if (layoutOurs) {
1178
+ moveSync(paths.layoutFile, join(paths.backupNext, "layouts", `${DESKTOP_LAYOUT}.json`));
1179
+ putBack("layouts", `${DESKTOP_LAYOUT}.json`, paths.layoutFile);
1180
+ }
1181
+ for (const name of themesOurs) {
1182
+ moveSync(join(paths.themes, name), join(paths.backupNext, "themes", name));
1183
+ putBack("themes", name, join(paths.themes, name));
1184
+ }
1185
+ promoteBackup(paths);
1186
+ }
1187
+ cleanOriginals(paths);
1188
+ // Shortcuts that could not be removed stay recorded, so a later --uninstall still finds them.
1189
+ if (keysKept) writeState(paths, { mods: [], layout: false, keys: keysKept });
1190
+ else rmSync(paths.stateFile, { force: true });
1191
+ if (ours.length === 0 && !layoutOurs && themesOurs.length === 0) return keysKept ? 1 : 0;
1192
+ const window = app ? windowStatus(ctx, app.path) : undefined;
1193
+ if (app && window?.layout === DESKTOP_LAYOUT) {
1194
+ const back = state?.previousLayout ?? "main";
1195
+ const switched = herdrDo(ctx, app.path, "layout.switch", { name: back });
1196
+ if (switched.status !== 0) ctx.io.err(`gentle-shell desktop: could not switch Herdr app back to the ${back} layout; choose another layout in Herdr.`);
1197
+ }
1198
+ ctx.io.out(`Removed Gentle Shell Desktop ${themesOurs.length > 0 ? "mods, layout and themes" : "mods and layout"} from ${paths.herdrHome}; a copy is in ${paths.backup}. Herdr app itself stays installed.`);
1199
+ if (restored.length > 0) ctx.io.out(`Put back what was there before Gentle Shell Desktop: ${restored.join(", ")} in ${paths.herdrHome}.`);
1200
+ return keysKept ? 1 : 0;
1201
+ }
1202
+
1203
+ // "mods a, b and layout gentle-shell", or with themes "mods a, b, layout gentle-shell and themes x, y".
1204
+ const assetsText = (assets ) => (assets.themes.length > 0
1205
+ ? `mods ${assets.mods.join(", ")}, layout ${DESKTOP_LAYOUT} and themes ${assets.themes.join(", ")}`
1206
+ : `mods ${assets.mods.join(", ")} and layout ${DESKTOP_LAYOUT}`);
1207
+
1208
+ async function refresh(ctx , paths , assets ) {
1209
+ const state = readState(paths);
1210
+ if (!state) return 0;
1211
+ if ("error" in assets) {
1212
+ ctx.io.err(`gentle-shell desktop: ${assets.error}`);
1213
+ return 1;
1214
+ }
1215
+ const app = detectApp(ctx);
1216
+ if (!app) {
1217
+ ctx.io.err("gentle-shell desktop: Herdr app is not installed, so the Gentle mods were not refreshed; run gentle-shell desktop.");
1218
+ return 1;
1219
+ }
1220
+ if (!assetsUpToDate(assets, paths) || !(state.mods ?? []).every((mod) => assets.mods.includes(mod)) || !(state.themes ?? []).every((name) => assets.themes.includes(name))) {
1221
+ const failure = installAssets(ctx, paths, assets, app.path, state);
1222
+ if (failure !== undefined) {
1223
+ ctx.io.err(`gentle-shell desktop: ${failure}`);
1224
+ return 1;
1225
+ }
1226
+ writeState(paths, { ...state, mods: assets.mods, themes: assets.themes, layout: true });
1227
+ ctx.io.out(`Gentle Shell Desktop: refreshed ${assetsText(assets)} in ${paths.herdrHome}.`);
1228
+ }
1229
+ // Only shortcuts the person already accepted with gentle-shell desktop are refreshed.
1230
+ if (assets.keys && state.keys) await syncKeys(ctx, paths, assets.keys, app.path);
1231
+ return 0;
1232
+ }
1233
+
1234
+ export async function runDesktop(ctx ) {
1235
+ const parsed = parseDesktopArgs(ctx.args);
1236
+ if ("error" in parsed) {
1237
+ ctx.io.err(`gentle-shell desktop: ${parsed.error}`);
1238
+ ctx.io.err(desktopUsage());
1239
+ return 2;
1240
+ }
1241
+ if (parsed.action === "help") {
1242
+ ctx.io.out(desktopUsage());
1243
+ return 0;
1244
+ }
1245
+ const release = ctx.release ?? HERDR_APP_RELEASE;
1246
+ const paths = desktopPaths(ctx.env, ctx.home);
1247
+ const assets = shippedAssets(ctx.packageRoot);
1248
+ if (parsed.action === "status") return printStatus(ctx, paths, assets, release);
1249
+ if (parsed.action === "uninstall") return await uninstall(ctx, paths);
1250
+ if (parsed.action === "refresh") return await refresh(ctx, paths, assets);
1251
+ if ("error" in assets) {
1252
+ ctx.io.err(`gentle-shell desktop: ${assets.error}`);
1253
+ return 1;
1254
+ }
1255
+
1256
+ const installed = detectApp(ctx);
1257
+ const planned = planApp(ctx, installed, release);
1258
+ if (planned && "error" in planned) {
1259
+ ctx.io.err(`gentle-shell desktop: ${planned.error}`);
1260
+ return 1;
1261
+ }
1262
+ const appPlan = planned ;
1263
+ const previous = readState(paths);
1264
+ const assetsNeeded = !previous || !assetsUpToDate(assets, paths);
1265
+ // Never merged yet: asked for with the rest. A keys.json Herdr has not written yet is
1266
+ // merged once the window opens (and with --no-open, the next time it does).
1267
+ const keysNeeded = assets.keys !== undefined && !previous?.keys && (parsed.open || existsSync(paths.keysFile));
1268
+ if (appPlan || assetsNeeded || keysNeeded) {
1269
+ ctx.io.out("Gentle Shell Desktop will:");
1270
+ if (appPlan) {
1271
+ const where = `${appPlan.destination} and link ${appPlan.link}`;
1272
+ ctx.io.out(appPlan.replaces
1273
+ ? ` - replace Herdr app ${appPlan.replaces.version ?? "(unknown version)"} at ${appPlan.replaces.path} with ${release.version} (${appPlan.target}) into ${where}`
1274
+ : ` - install Herdr app ${release.version} (${appPlan.target}) into ${where}`);
1275
+ ctx.io.out(` from ${appPlan.url}`);
1276
+ ctx.io.out(` verified against SHA-256 ${appPlan.sha256} (pinned by Gentle Shell ${ctx.shellVersion})`);
1277
+ }
1278
+ if (assetsNeeded) {
1279
+ ctx.io.out(` - install mods ${assets.mods.join(", ")} into ${paths.mods}`);
1280
+ ctx.io.out(` - install layout ${DESKTOP_LAYOUT} into ${paths.layoutFile}`);
1281
+ if (assets.themes.length > 0) ctx.io.out(` - install its light and dark themes ${assets.themes.join(", ")} into ${paths.themes}`);
1282
+ ctx.io.out(` - check each mod with herdr-app check before installing anything`);
1283
+ ctx.io.out(` - keep anything Gentle Shell did not install at those paths in ${paths.originals}, put back by --uninstall`);
1284
+ ctx.io.out(` - keep our own previous copy in ${paths.backup}`);
1285
+ }
1286
+ if (keysNeeded) {
1287
+ ctx.io.out(` - add the Gentle shortcuts (${DESKTOP_KEYS_SECTION}) to ${paths.keysFile}, keeping every key you already use`);
1288
+ ctx.io.out(` a key you already bind there stays yours; --uninstall removes exactly ours`);
1289
+ }
1290
+ if (assetsNeeded || keysNeeded) {
1291
+ ctx.io.out(` Your other mods, layouts, keys and settings in ${paths.herdrHome} are not touched.`);
1292
+ }
1293
+ if (!parsed.yes) {
1294
+ if (!ctx.interactive) {
1295
+ ctx.io.err("gentle-shell desktop: nothing was installed. Run it in an interactive terminal to confirm, or pass --yes.");
1296
+ return 1;
1297
+ }
1298
+ const answer = (await ctx.io.ask("Install Gentle Shell Desktop as shown above? [y/N] ")).trim().toLowerCase();
1299
+ if (answer !== "y" && answer !== "yes") {
1300
+ ctx.io.err("gentle-shell desktop: nothing was installed.");
1301
+ return 1;
1302
+ }
1303
+ }
1304
+ }
1305
+
1306
+ let app = installed?.path;
1307
+ if (appPlan) {
1308
+ try {
1309
+ app = await installApp(ctx, paths, appPlan);
1310
+ } catch (error) {
1311
+ ctx.io.err(`gentle-shell desktop: ${(error ).message}`);
1312
+ return 1;
1313
+ }
1314
+ ctx.io.out(`Installed Herdr app ${release.version} at ${appPlan.destination}.`);
1315
+ if (!findOnPath("herdr-core", ctx.env, ctx.platform) && !existsSync(join(paths.localBin, "herdr-core"))) {
1316
+ ctx.io.out("Herdr app sets up herdr-core (the terminal runtime) itself when it opens.");
1317
+ }
1318
+ }
1319
+ if (!app) {
1320
+ ctx.io.err("gentle-shell desktop: Herdr app is not available.");
1321
+ return 1;
1322
+ }
1323
+ if (assetsNeeded) {
1324
+ const failure = installAssets(ctx, paths, assets, app, previous);
1325
+ if (failure !== undefined) {
1326
+ ctx.io.err(`gentle-shell desktop: ${failure}`);
1327
+ return 1;
1328
+ }
1329
+ writeState(paths, { mods: assets.mods, themes: assets.themes, layout: true, ...(previous?.previousLayout ? { previousLayout: previous.previousLayout } : {}), ...(previous?.keys ? { keys: previous.keys } : {}) });
1330
+ ctx.io.out(`Installed ${assetsText(assets)} in ${paths.herdrHome}.`);
1331
+ } else {
1332
+ ctx.io.out("Gentle Shell Desktop is up to date.");
1333
+ }
1334
+ const keysPending = assets.keys !== undefined && (await syncKeys(ctx, paths, assets.keys, app)) === "missing";
1335
+ if (!parsed.open) {
1336
+ if (keysPending) ctx.io.out(keysDeferred(paths));
1337
+ return 0;
1338
+ }
1339
+ return openDesktop(ctx, paths, app, keysPending ? assets.keys : undefined);
1340
+ }
1341
+
1342
+ // --- the real process --------------------------------------------------------------
1343
+
1344
+ export function nodeDesktopIO() {
1345
+ const run = (command, args, options) => {
1346
+ const result = spawnSync(command, args, { env: options.env, cwd: options.cwd, encoding: "utf8", timeout: 10 * 60_000, stdio: ["ignore", "pipe", "pipe"] });
1347
+ return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "", ...(result.error ? { error: result.error } : {}) };
1348
+ };
1349
+ return {
1350
+ run,
1351
+ spawnDetached: (command, args, options) => {
1352
+ const child = spawn(command, args, { env: options.env, cwd: options.cwd, detached: true, stdio: "ignore" });
1353
+ child.on("error", () => {});
1354
+ child.unref();
1355
+ },
1356
+ // curl, as the official installer uses; the pinned SHA-256 is what is trusted.
1357
+ download: async (url, file) => {
1358
+ const result = run("curl", ["-fsSL", "--retry", "2", "-o", file, url], { env: process.env });
1359
+ if (result.status !== 0) throw new Error(`download of ${url} failed: ${result.stderr.trim() || result.error?.message || `curl exit ${result.status}`}`);
1360
+ },
1361
+ sha256: (file) => createHash("sha256").update(readFileSync(file)).digest("hex"),
1362
+ // The official installer's rule for release builds: a Developer ID signature that verifies.
1363
+ verifyMacSignature: (app) => {
1364
+ const info = run("/usr/bin/codesign", ["-dvv", app], { env: process.env });
1365
+ if (!/^Authority=Developer ID Application:/m.test(`${info.stderr}${info.stdout}`)) return `no Developer ID signature (${info.stderr.trim() || info.error?.message || "codesign failed"})`;
1366
+ const verify = run("/usr/bin/codesign", ["--verify", "--deep", "--strict", app], { env: process.env });
1367
+ return verify.status === 0 ? undefined : `invalid signature: ${verify.stderr.trim()}`;
1368
+ },
1369
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
1370
+ };
1371
+ }