gentle-pi 4.7.0 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (365) hide show
  1. package/README.md +55 -44
  2. package/assets/agents/gentle-ai-explore.md +3 -3
  3. package/assets/agents/gentle-ai-verify.md +20 -6
  4. package/assets/agents/gentle-ai-worker.md +6 -6
  5. package/assets/agents/jd-judge-a.md +1 -3
  6. package/assets/agents/jd-judge-b.md +1 -3
  7. package/assets/agents/review-readability.md +1 -5
  8. package/assets/agents/review-reliability.md +1 -5
  9. package/assets/agents/review-resilience.md +1 -5
  10. package/assets/agents/review-risk.md +1 -5
  11. package/assets/design-canvas/canvas-api.js +45 -0
  12. package/assets/design-canvas/canvas-boards.js +456 -0
  13. package/assets/design-canvas/canvas-boot.js +217 -0
  14. package/assets/design-canvas/canvas-checks.js +491 -0
  15. package/assets/design-canvas/canvas-comments.js +315 -0
  16. package/assets/design-canvas/canvas-compare.js +159 -0
  17. package/assets/design-canvas/canvas-events.js +75 -0
  18. package/assets/design-canvas/canvas-export.js +393 -0
  19. package/assets/design-canvas/canvas-focus.js +203 -0
  20. package/assets/design-canvas/canvas-handoffs.js +150 -0
  21. package/assets/design-canvas/canvas-i18n-es.js +392 -0
  22. package/assets/design-canvas/canvas-i18n.js +108 -0
  23. package/assets/design-canvas/canvas-layout.js +526 -0
  24. package/assets/design-canvas/canvas-menu.js +213 -0
  25. package/assets/design-canvas/canvas-messages.js +86 -0
  26. package/assets/design-canvas/canvas-minimap.js +163 -0
  27. package/assets/design-canvas/canvas-parts.js +401 -0
  28. package/assets/design-canvas/canvas-popover.js +234 -0
  29. package/assets/design-canvas/canvas-rail.js +348 -0
  30. package/assets/design-canvas/canvas-sizes.js +524 -0
  31. package/assets/design-canvas/canvas-store.js +164 -0
  32. package/assets/design-canvas/canvas-tokens.js +674 -0
  33. package/assets/design-canvas/canvas-ui.js +24 -0
  34. package/assets/design-canvas/canvas-view.js +184 -0
  35. package/assets/design-canvas/canvas.css +746 -15
  36. package/assets/design-canvas/canvas.js +2 -1506
  37. package/assets/design-canvas/index.html +117 -36
  38. package/assets/design-canvas/inspector.js +546 -16
  39. package/assets/install-wizard/wizard.js +5 -1
  40. package/assets/migrations/agent-body-history.json +24 -0
  41. package/assets/orchestrator-delegation-reference.md +8 -14
  42. package/assets/orchestrator-delegation.md +4 -4
  43. package/assets/orchestrator-full-delegation-card.md +4 -5
  44. package/assets/orchestrator-full-delegation.md +8 -8
  45. package/assets/orchestrator-memory.md +2 -2
  46. package/assets/orchestrator-prompts.md +1 -1
  47. package/assets/orchestrator-quota-recovery.md +5 -0
  48. package/assets/orchestrator-skills.md +13 -12
  49. package/assets/orchestrator-tracking.md +10 -14
  50. package/assets/orchestrator-verification.md +10 -8
  51. package/assets/orchestrator-writer.md +4 -4
  52. package/assets/orchestrator.md +18 -22
  53. package/bin/gentle-shell.mjs +128 -9
  54. package/contracts/review-provider-contract-mirror/provider-contract.lock.json +8 -9
  55. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/manifest.json +3 -3
  56. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/orchestration/pi.md +1 -0
  57. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/routing/pi.md +6 -6
  58. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/generated/provider-capabilities.baseline.json +3 -3
  59. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/generated/provider-roles.baseline.json +1 -1
  60. package/docs/assets/brand/sponsor-banner.svg +60 -0
  61. package/docs/bundled-install.md +14 -6
  62. package/docs/delegated-verification.md +18 -2
  63. package/docs/desktop-rpc.md +1253 -0
  64. package/docs/gentle-agents-activity.md +26 -0
  65. package/docs/gentle-shell.md +39 -16
  66. package/docs/install-wizard.md +30 -21
  67. package/docs/odd-preparation-continuity.md +24 -0
  68. package/docs/permission-modes.md +9 -1
  69. package/docs/prompt-budget.md +12 -0
  70. package/docs/rdd-odd-friction-triage-2026-11-07.md +57 -0
  71. package/docs/readme-reference.md +76 -24
  72. package/docs/review-coordinator.md +29 -9
  73. package/docs/review-delivery-preflight.md +22 -0
  74. package/docs/work-continuity.md +11 -1
  75. package/extensions/ask-user-question.ts +2 -2
  76. package/extensions/child-context.ts +21 -7
  77. package/extensions/gentle-agents.ts +234 -33
  78. package/extensions/gentle-ai.ts +576 -135
  79. package/extensions/gentle-design.ts +69 -3
  80. package/extensions/gentle-desktop-rpc.ts +143 -0
  81. package/extensions/gentle-guide.ts +3 -0
  82. package/extensions/gentle-shell.ts +105 -52
  83. package/extensions/gentle-todo.ts +48 -25
  84. package/extensions/skill-registry.ts +248 -223
  85. package/lib/agent-assets.ts +30 -6
  86. package/lib/agent-tool-overlay.ts +117 -0
  87. package/lib/agents-config.ts +47 -6
  88. package/lib/agents-message-delivery.ts +17 -0
  89. package/lib/agents-messaging.ts +8 -2
  90. package/lib/agents-protocol.ts +15 -0
  91. package/lib/agents-report-cap.ts +115 -0
  92. package/lib/agents-runner.ts +91 -6
  93. package/lib/agents-session-transport.ts +17 -1
  94. package/lib/background-jobs-tools.ts +9 -4
  95. package/lib/bounded-writer-admission.ts +184 -31
  96. package/lib/child-context-files.ts +21 -6
  97. package/lib/codemode-renderer.ts +1 -0
  98. package/lib/delivery-conflict-markers.ts +349 -0
  99. package/lib/design-canvas-assets.ts +36 -0
  100. package/lib/design-canvas-server.ts +241 -23
  101. package/lib/design-comments.ts +94 -4
  102. package/lib/design-handoffs.ts +2 -1
  103. package/lib/design-layout.ts +125 -0
  104. package/lib/design-parts.ts +281 -0
  105. package/lib/design-system-tokens.ts +111 -0
  106. package/lib/desktop-agents-service.ts +294 -0
  107. package/lib/desktop-design-service.ts +233 -0
  108. package/lib/desktop-jobs-service.ts +263 -0
  109. package/lib/desktop-rpc-agents.ts +294 -0
  110. package/lib/desktop-rpc-config.ts +731 -0
  111. package/lib/desktop-rpc-design.ts +138 -0
  112. package/lib/desktop-rpc-jobs.ts +181 -0
  113. package/lib/desktop-rpc-permissions.ts +177 -0
  114. package/lib/desktop-rpc-profiles.ts +196 -0
  115. package/lib/desktop-rpc-usage.ts +229 -0
  116. package/lib/desktop-rpc.ts +225 -0
  117. package/lib/desktop-usage-service.ts +310 -0
  118. package/lib/destructive-command-guard.ts +188 -13
  119. package/lib/gentle-ai-renderer.ts +13 -1
  120. package/lib/gentle-design.ts +201 -14
  121. package/lib/gentle-shell-bundled.ts +100 -9
  122. package/lib/hidden-tools.ts +35 -0
  123. package/lib/inprocess-reviewer.ts +96 -12
  124. package/lib/model-fallback-policy.ts +9 -0
  125. package/lib/model-routing-authority.ts +9 -0
  126. package/lib/nan-provider.ts +42 -28
  127. package/lib/native-review-cli.ts +79 -4
  128. package/lib/orchestrator-discovery.ts +39 -2
  129. package/lib/reply-language-anchor.ts +27 -2
  130. package/lib/request-context-placement.ts +53 -0
  131. package/lib/review-candidate-view.ts +11 -1
  132. package/lib/review-continuation-registry.ts +17 -0
  133. package/lib/review-coordinator.ts +252 -8
  134. package/lib/review-delivery-preflight.ts +85 -0
  135. package/lib/review-host-relay.ts +5 -1
  136. package/lib/review-integration-v2.ts +56 -3
  137. package/lib/reviewer-stream.ts +87 -0
  138. package/lib/shell-prompt.ts +16 -3
  139. package/lib/shell-usage.ts +10 -0
  140. package/lib/vim-editor-adapter.ts +9 -2
  141. package/lib/writer-batch-admission.ts +55 -0
  142. package/lib/yolo-session-policy.ts +6 -1
  143. package/package.json +2 -2
  144. package/prompts/skill-creation.md +1 -10
  145. package/runtime/design-canvas-assets.mjs +37 -0
  146. package/runtime/gentle-shell-bundled.mjs +100 -9
  147. package/runtime/native-review-cli.mjs +79 -4
  148. package/runtime/review-integration-v2.mjs +56 -3
  149. package/scripts/bootstrap.cmd +2 -2
  150. package/scripts/bootstrap.sh +41 -4
  151. package/scripts/build-full-delegation-card.mjs +4 -0
  152. package/scripts/build-runtime-modules.mjs +1 -0
  153. package/scripts/gentle-ai-installer.mjs +10 -10
  154. package/scripts/gentle-ai-proxy.mjs +1 -1
  155. package/scripts/installer-downloads.mjs +34 -8
  156. package/scripts/installer-preflight.mjs +28 -17
  157. package/scripts/installer-probes.mjs +25 -5
  158. package/scripts/installer-server.mjs +38 -9
  159. package/scripts/installer-windows.mjs +2 -2
  160. package/scripts/pi-update.mjs +166 -27
  161. package/scripts/prepare-verifier.mjs +107 -0
  162. package/scripts/update-agent-body-history.mjs +55 -8
  163. package/scripts/verify-package-files.mjs +40 -19
  164. package/skills/branch-pr/SKILL.md +16 -16
  165. package/skills/comment-writer/SKILL.md +1 -1
  166. package/skills/design/SKILL.md +6 -6
  167. package/skills/gentle-ai/SKILL.md +5 -5
  168. package/skills/judgment-day/SKILL.md +2 -2
  169. package/skills/judgment-day/references/prompts-and-formats.md +1 -1
  170. package/skills/rdd-defect-workflow/SKILL.md +6 -6
  171. package/skills/skill-improver/SKILL.md +2 -2
  172. package/skills/skill-registry/SKILL.md +11 -13
  173. package/skills/tui-design/SKILL.md +1 -1
  174. package/skills/work-unit-commits/SKILL.md +5 -5
  175. package/tests/agent-prompt-diet-contract.test.ts +101 -0
  176. package/tests/agent-tool-overlay-acceptance.test.ts +158 -0
  177. package/tests/agent-tool-overlay.test.ts +89 -0
  178. package/tests/agents-config.test.ts +10 -1
  179. package/tests/agents-message-delivery.test.ts +36 -0
  180. package/tests/agents-queries.test.ts +144 -4
  181. package/tests/agents-report-cap.test.ts +126 -0
  182. package/tests/agents-runner.test.ts +37 -1
  183. package/tests/agents-session-transport.test.ts +34 -0
  184. package/tests/always-on-prompt-verdicts-contract.test.ts +188 -0
  185. package/tests/append-system-prompt-route.test.ts +10 -2
  186. package/tests/approved-text-leftovers-contract.test.ts +136 -0
  187. package/tests/artifact-language.test.ts +1 -1
  188. package/tests/ask-user-question.test.ts +2 -1
  189. package/tests/audit-leftovers-contract.test.ts +51 -0
  190. package/tests/bounded-stop-contract.test.ts +9 -1
  191. package/tests/branch-pr-skill.test.ts +10 -1
  192. package/tests/bundled-install.test.ts +1 -1
  193. package/tests/child-context-files.test.ts +64 -8
  194. package/tests/child-skills-catalog.test.ts +56 -0
  195. package/tests/codemode-rendering.test.ts +4 -1
  196. package/tests/delegate-for-reason-contract.test.ts +30 -8
  197. package/tests/delivery-conflict-markers.test.ts +348 -0
  198. package/tests/design-canvas-all-sizes.test.ts +631 -0
  199. package/tests/design-canvas-allowlist.test.ts +32 -0
  200. package/tests/design-canvas-assets.test.ts +11 -878
  201. package/tests/design-canvas-boards.test.ts +77 -0
  202. package/tests/design-canvas-checks.test.ts +655 -0
  203. package/tests/design-canvas-compare.test.ts +79 -0
  204. package/tests/design-canvas-events.test.ts +59 -0
  205. package/tests/design-canvas-export.test.ts +1168 -0
  206. package/tests/design-canvas-focus.test.ts +113 -0
  207. package/tests/design-canvas-handoffs.test.ts +59 -0
  208. package/tests/design-canvas-i18n-review.test.ts +513 -0
  209. package/tests/design-canvas-i18n-views.test.ts +259 -0
  210. package/tests/design-canvas-i18n.test.ts +526 -0
  211. package/tests/design-canvas-inspector.test.ts +937 -0
  212. package/tests/design-canvas-layout.test.ts +1222 -0
  213. package/tests/design-canvas-minimap.test.ts +413 -0
  214. package/tests/design-canvas-modules.test.ts +90 -0
  215. package/tests/design-canvas-parts.test.ts +721 -0
  216. package/tests/design-canvas-rail.test.ts +799 -0
  217. package/tests/design-canvas-server.test.ts +855 -17
  218. package/tests/design-canvas-sizes.test.ts +548 -0
  219. package/tests/design-canvas-store.test.ts +180 -0
  220. package/tests/design-canvas-tokens.test.ts +965 -0
  221. package/tests/design-canvas-view.test.ts +299 -0
  222. package/tests/design-comments.test.ts +201 -1
  223. package/tests/design-handoffs.test.ts +20 -0
  224. package/tests/design-layout.test.ts +100 -0
  225. package/tests/design-parts.test.ts +260 -0
  226. package/tests/design-system-tokens.test.ts +215 -0
  227. package/tests/desktop-rpc-agents.test.ts +893 -0
  228. package/tests/desktop-rpc-config.test.ts +1452 -0
  229. package/tests/desktop-rpc-design.test.ts +662 -0
  230. package/tests/desktop-rpc-jobs.test.ts +796 -0
  231. package/tests/desktop-rpc-permissions.test.ts +311 -0
  232. package/tests/desktop-rpc-profiles.test.ts +140 -0
  233. package/tests/desktop-rpc-safety.test.ts +119 -0
  234. package/tests/desktop-rpc-usage.test.ts +697 -0
  235. package/tests/desktop-rpc.test.ts +252 -0
  236. package/tests/devbinary/pi-host-relay.devtest.ts +149 -80
  237. package/tests/devbinary/review-session-consent.devtest.ts +84 -0
  238. package/tests/engram-safety.test.ts +111 -0
  239. package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.captured.json +92 -0
  240. package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.provenance.md +3 -0
  241. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +20 -29
  242. package/tests/fixtures/refusal-identity.probe.mjs +139 -0
  243. package/tests/full-delegation-closure.test.ts +29 -0
  244. package/tests/gentle-agents.test.ts +329 -4
  245. package/tests/gentle-ai-binary.test.ts +1 -1
  246. package/tests/gentle-ai-child-guards.test.ts +1 -0
  247. package/tests/gentle-ai-installer.test.ts +52 -51
  248. package/tests/gentle-ai-renderer.test.ts +36 -2
  249. package/tests/gentle-ai.test.ts +121 -6
  250. package/tests/gentle-design.test.ts +365 -1
  251. package/tests/gentle-shell-bundled.test.ts +91 -5
  252. package/tests/gentle-shell-launcher.test.ts +1 -1
  253. package/tests/gentle-shell.test.ts +118 -87
  254. package/tests/gentle-todo.test.ts +32 -9
  255. package/tests/hidden-tools.test.ts +188 -0
  256. package/tests/independent-recovery-delivery.test.ts +19 -5
  257. package/tests/inprocess-reviewer.test.ts +73 -0
  258. package/tests/install-wizard.test.ts +27 -1
  259. package/tests/installer-downloads.test.ts +30 -1
  260. package/tests/installer-posix-bootstrap.test.ts +114 -13
  261. package/tests/installer-preflight.test.ts +49 -1
  262. package/tests/installer-probes.test.ts +146 -0
  263. package/tests/installer-server.test.ts +203 -4
  264. package/tests/installer-windows-bootstrap.test.ts +19 -1
  265. package/tests/judgment-day-severity-admission.test.ts +46 -0
  266. package/tests/lazy-module-contradictions-contract.test.ts +158 -0
  267. package/tests/maintainer/desktop-rpc.maintest.ts +632 -0
  268. package/tests/maintainer/pi-update-source.maintest.ts +48 -18
  269. package/tests/model-fallback-policy.test.ts +26 -7
  270. package/tests/nan-provider-runtime.test.ts +17 -3
  271. package/tests/nan-provider.test.ts +111 -56
  272. package/tests/native-review-capability-contract.test.ts +11 -1
  273. package/tests/native-review-cli-nonblocking-findings.test.ts +165 -0
  274. package/tests/native-review-parity.test.ts +24 -5
  275. package/tests/native-review-refusal-identity.test.ts +25 -0
  276. package/tests/no-self-pause-contract.test.ts +11 -3
  277. package/tests/odd-integration.test.ts +11 -3
  278. package/tests/odd-routing-contract.test.ts +80 -28
  279. package/tests/orchestrator-budget.test.ts +30 -5
  280. package/tests/orchestrator-consultation-sdk.test.ts +32 -6
  281. package/tests/orchestrator-delegation-mode.test.ts +2 -1
  282. package/tests/orchestrator-discovery.test.ts +28 -0
  283. package/tests/orchestrator-prompt-budget.test.ts +11 -2
  284. package/tests/orchestrator-prompt-diet-contract.test.ts +221 -0
  285. package/tests/orchestrator-rdd-ownership.test.ts +2 -1
  286. package/tests/orchestrator-work-search.test.ts +4 -2
  287. package/tests/package-files.test.ts +25 -1
  288. package/tests/package-manifest.test.ts +11 -10
  289. package/tests/parallel-reason-contract.test.ts +6 -3
  290. package/tests/permission-allowlist.test.ts +200 -30
  291. package/tests/persona-neutral-voseo.test.ts +4 -4
  292. package/tests/persona-reply-language.test.ts +1 -1
  293. package/tests/persona-single-channel.test.ts +13 -5
  294. package/tests/pi-update-launcher.test.ts +17 -7
  295. package/tests/pi-update-source.test.ts +113 -6
  296. package/tests/pi-update.test.ts +294 -19
  297. package/tests/pnpm-workspace-policy.test.ts +47 -0
  298. package/tests/primary-context-files.test.ts +233 -0
  299. package/tests/primary-context-three-files.test.ts +174 -0
  300. package/tests/provider-defect-handoff.test.ts +9 -2
  301. package/tests/rdd-aware-verification-contract.test.ts +1 -1
  302. package/tests/rdd-status-line.test.ts +94 -1
  303. package/tests/reply-language-anchor-placement.test.ts +184 -0
  304. package/tests/reply-language-anchor.test.ts +17 -1
  305. package/tests/request-context-append-only.test.ts +218 -0
  306. package/tests/request-context-placement.test.ts +148 -0
  307. package/tests/review-agent-end-preflight.test.ts +79 -1
  308. package/tests/review-candidate-view.test.ts +65 -0
  309. package/tests/review-continuation-registry.test.ts +31 -0
  310. package/tests/review-contract-prompt.test.ts +1 -1
  311. package/tests/review-controller.test.ts +2 -1
  312. package/tests/review-coordinator-correction-gate.test.ts +105 -0
  313. package/tests/review-coordinator-findings.test.ts +206 -0
  314. package/tests/review-coordinator-nonblocking-scope.test.ts +169 -0
  315. package/tests/review-coordinator.test.ts +271 -4
  316. package/tests/review-delivery-preflight.test.ts +462 -0
  317. package/tests/review-due-compaction.test.ts +31 -0
  318. package/tests/review-due-public-boundary.test.ts +26 -0
  319. package/tests/review-integration-nonblocking-findings.test.ts +108 -0
  320. package/tests/review-json-arguments.test.ts +41 -2
  321. package/tests/review-ledger-contract.test.ts +19 -40
  322. package/tests/review-loadout-rdd-off-sdk.test.ts +30 -1
  323. package/tests/review-one-call-findings.test.ts +131 -0
  324. package/tests/review-one-call-followups.test.ts +308 -0
  325. package/tests/review-one-call-reviewer-requests.test.ts +207 -0
  326. package/tests/review-one-call.test.ts +452 -0
  327. package/tests/review-relay-transport-agent.test.ts +28 -1
  328. package/tests/review-reviewer-evidence.test.ts +41 -1
  329. package/tests/review-risk-assessment.test.ts +52 -5
  330. package/tests/review-run-statement-guidance-independent.test.ts +54 -0
  331. package/tests/review-session-standing-permission-controller.test.ts +32 -2
  332. package/tests/review-tool-prose-budget.test.ts +1 -0
  333. package/tests/reviewer-stream.test.ts +149 -0
  334. package/tests/session-profile-extension.test.ts +2 -2
  335. package/tests/shell-prompt.test.ts +17 -0
  336. package/tests/shell-usage.test.ts +59 -10
  337. package/tests/skill-contradictions-contract.test.ts +122 -0
  338. package/tests/skill-registry-watcher.test.ts +216 -2
  339. package/tests/skill-registry.test.ts +929 -306
  340. package/tests/support/design-canvas-dom.ts +369 -0
  341. package/tests/support/review-coordinator-runtime.ts +212 -17
  342. package/tests/task-size-routing-contract.test.ts +42 -11
  343. package/tests/test-strength-contract.test.ts +2 -1
  344. package/tests/todo-request-append-only.test.ts +214 -0
  345. package/tests/tool-batching-contract.test.ts +3 -1
  346. package/tests/update-agent-body-history.test.ts +138 -0
  347. package/tests/verification-tiers-contract.test.ts +229 -0
  348. package/tests/verifier-preparation.test.ts +229 -0
  349. package/tests/verify-agent-contract.test.ts +20 -2
  350. package/tests/verify-first-launch-contract.test.ts +87 -11
  351. package/tests/vim-editor-adapter.test.ts +2 -2
  352. package/tests/work-continuity-contract.test.ts +54 -11
  353. package/tests/writer-admission-messages.test.ts +232 -0
  354. package/tests/writer-batch-admission.test.ts +66 -0
  355. package/tests/writer-edit-surface-scope.test.ts +52 -20
  356. package/tests/writer-feature-document-admission.test.ts +184 -0
  357. package/tests/yolo-mode.test.ts +39 -0
  358. package/skills/_shared/review-ledger-contract.md +0 -106
  359. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/README.md +0 -0
  360. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/lens.schema.json +0 -0
  361. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/refuter.schema.json +0 -0
  362. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/targeted-validator.schema.json +0 -0
  363. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/lens.json +0 -0
  364. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/refuter.json +0 -0
  365. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/targeted-validator.json +0 -0
@@ -0,0 +1,22 @@
1
+ # Host delivery preflight
2
+
3
+ Shell's host workflow now checks recognizable `git push`, `gh pr create` and `gh pr merge` calls before execution (issue #2997). This changes Shell's previous unconditional delivery bypass. It does not restore the provider's retired receipt/gate APIs or change its byte-pinned contract artifacts. The vendored `review-integration.md` remains an exact upstream snapshot; this document describes the newer Shell-owned ordering policy.
4
+
5
+ With RDD on, select the actual delivery slice through `gentle_review` assess with explicit `baseRef` and `committedOnly: true`. `workspaceRoot` selects its worktree. The host resolves that selector to a fixed commit before assessment; a confirmed committed-range assessment retains only that base commit in the existing session continuation registry. Invalid or unresolved selections leave the existing hint unchanged. No parallel registry, cached verdict, capture/confirmation state or stored HEAD snapshot is created. The native assessment is always fresh and compares that fixed base to current HEAD, including commits made since selection. This also covers assessments invoked by the coordinator. Committed-only delivery requests omit untracked selection flags because they require no untracked inventory.
6
+
7
+ After command authorization, each foreground call gets one assessment per selected repository, even for a batch such as `git push && gh pr create`. A shell wrapper alone does not block the call. Native `reviewDue: false` preserves ordinary policy. A due review requires following the facade transitions or an exact host-recorded human decline; caller-supplied outcomes grant nothing. HEAD/base and session checks around the fresh read prevent using a result that changed during admission. A new HEAD before admission is assessed automatically, without requiring another registration cycle.
8
+
9
+ Commands that change the candidate (commit, revert, switch, rebase, etc.) must finish before its delivery can be evaluated. Delivery through the background or monitor tools still needs a separate foreground call because the job can run after its preflight is stale; background waits without delivery remain available. Missing base, cancellation and unavailable native evidence remain concrete blockers. Dynamic or implicit directory changes and recognized inline Git/environment repository redirects (such as `--git-dir`, `GIT_WORK_TREE` or `env -C`) are unresolved targets: run delivery inside its repository or use literal `cd` or `git -C`. The host cannot infer a redirected target's RDD mode from the session repository. For resolved repositories, RDD off retains ordinary command policy. The check runs no review, consent answer, acknowledgement, mode change or network lookup, and does not authorize delivery.
10
+
11
+ This covers recognizable shell invocations, including common shell wrappers and substitutions. It is not a shell sandbox or an installed Git hook. Script files, arbitrary interpreter programs and external actors are outside its detection boundary. The caller owns the actual slice, every pushed ref and the PR/remote destination: checking a local candidate does not verify an explicit remote override, prove an arbitrary PR number matches local HEAD or prevent later remote edits after auto-merge scheduling.
12
+
13
+ Literal `cd` is resolved only in a direct leading `&&` chain without other control operators, including inside a supported shell wrapper. A later `;` or other control operator also makes the directory state ambiguous if the `cd` fails. `cd` in subshells, pipelines, background syntax or ambiguous conditional flow, and any `pushd`/`popd`, make the delivery target unresolved. Split those steps and issue delivery from the intended repository or use literal `git -C`; the host does not simulate shell directory state.
14
+
15
+ Recognizable scheduling and exported routing are checked as follows:
16
+
17
+ - Shell `&` applies to its whole and/or list or compound command, not merely the last segment. With RDD on, recognized delivery such as `sleep 30 && git push &` or `git push && echo done &` must be separated into a new foreground call before assessment. Scheduling metadata also follows supported wrappers and substitutions. Background work outside the delivery's list does not by itself mark a later foreground delivery asynchronous; resolved RDD-off targets retain ordinary policy.
18
+ - Literal exports of `GIT_DIR`, `GIT_WORK_TREE`, `GIT_COMMON_DIR` or `GIT_NAMESPACE` make later delivery in that environment unresolved, including exports through same-shell `eval`. This is rejected before reading the session repository's RDD mode. Exports inside a subshell, background list or backtick substitution do not contaminate a later parent-shell delivery; a delivery within that same child environment still has an unresolved target. Separate routing changes from delivery and issue it from the intended repository. This is bounded recognition of literal shell forms, not general shell-variable evaluation.
19
+
20
+ The provider's assessment policy, including `under_budget`, remains unchanged. The companion provider report #6028 remains separate; this host change does not claim to resolve inconsistent outcomes between provider assessment and other hosts' Stop hooks.
21
+
22
+ Regression coverage uses the real Shell hook and isolated Git repositories with stubbed native answers, plus the real native client's request validation with a stubbed process adapter. It checks one assessment per delivery batch, zero added asynchronous Git reads when retaining a base (canonical selection now performs synchronous Git resolution), fixed HEAD/branch bases, foreground batching/wrappers/eval, asynchronous delivery lists, process-scoped exports, unresolved-directory rejection, candidate-changing boundaries, late HEAD/selector/session changes, cancellation, and native non-due/human-decline paths. An additional Bash probe uses an inert local function to confirm scheduling and export visibility; it executes no Git delivery. These checks do not perform a real remote push/merge or claim a complete live-model journey or production latency improvement.
@@ -8,12 +8,22 @@ This is a Shell prompt-guidance improvement, not an incident closure for #2211 o
8
8
  | --- | --- |
9
9
  | A test or harness check fails, but a correction and rerun remain in scope and within the existing budget | Correct and continue without asking for approval of each transition. Do not reset the budget or weaken the check. |
10
10
  | The human specified one run, no retries, or diagnostic only | Honor that limit; do not propose diagnostic-only or single-attempt authorization unless requested. |
11
- | Proof is genuinely inaccessible, consent is required, an action is denied, or the correction budget is exhausted | Stop and report the blocker. Terminal outcomes and existing bounded-stop rules remain binding; an unavailable verifier is not retried. |
11
+ | Proof is genuinely inaccessible, consent is required, an action is denied, or the correction budget is exhausted | Stop and report the blocker. Terminal outcomes and existing bounded-stop rules remain binding; an unavailable verifier is not retried automatically. The narrow human-requested quota recovery below is a separate attempt. |
12
12
  | A worker cannot perform an upgrade | Only the parent may act after explicit authorization of the operation, exact scope and ownership, preservation, permitted tools, applicable fresh consent and guards, a validated backup, applicable artifact/migration validation, and a recovery path are established. |
13
13
  | An authorized rollback mixes task changes and unrelated changes, even in one file | Preserve unrelated edits; remove only proven task-created helpers. Never blanket restore, reset, or clean. Ambiguous ownership or denial stops the operation. |
14
14
 
15
15
  Broad feature approval is not destructive-operation authority. Do not reroute a denial to another worker or tool. No real maintenance, backup, migration, rollback, destructive Git operation, or model/provider operation was performed for this work.
16
16
 
17
+ ## Temporary verifier quota recovery
18
+
19
+ The always-on prompt points to `assets/orchestrator-quota-recovery.md`; the parent loads these conditions only when recovery is requested.
20
+
21
+ A verifier that ended on a temporary quota error without a verdict has not supplied proof or approval. Its automatic cycle stops. After availability is restored, the human can explicitly request one new bounded attempt at the missing verification for the same candidate. A general request to continue implementation is not that request.
22
+
23
+ Preserve the failed attempt and still-valid successful checks; run the missing verification rather than replaying passed suites. Before dispatch, confirm the previous child has ended and no child has uncertain status. A candidate change requires the ordinary verification decision for that changed candidate. Do not automatically wait, retry, or substitute a provider/model. Consent, actual denials, explicit one-run/no-retry limits, terminal native outcomes and exhausted native budgets remain binding; this request does not reset them.
24
+
25
+ This guidance changes no runtime quota detection, provider selection, or native review authority. The provider-owned Close text and pinned contracts remain unchanged. Delivered-instruction tests do not establish model adherence or a successful subscription-recovery journey.
26
+
17
27
  ## Current bounded checks
18
28
 
19
29
  On the current Windows workspace, with existing dependencies and no installation, network, provider, or model calls, the bounded verification run recorded these results:
@@ -247,12 +247,12 @@ export default function askUserQuestion(pi: ExtensionAPI): void {
247
247
  label: "Ask User Question",
248
248
  description: "Ask one to four structured questions in a single call, each with two to four ordered options, and read the user's answers back in one result.",
249
249
  promptGuidelines: [
250
- "Use ask_user_question to collect decisions in one batch: ask one to four questions at a time, each with two to four options.",
250
+ "Use ask_user_question to collect decisions in one batch.",
251
251
  "Keep each header a short chip of at most 16 characters and each option label at most 60 characters.",
252
252
  "Add a preview to an option when the user needs to compare rich detail side-by-side with the options.",
253
253
  "Set multiSelect when the choices are not mutually exclusive.",
254
254
  "The free-text \"Type something.\" row is always available and is also how the user bails out into a normal conversation; never rely on it as a hidden escape hatch.",
255
- "Never use this tool for decisions that must not be delegated to the user.",
255
+ "Consent, maintenance authorizations and exact-token decisions use ask_user_choice, never this tool.",
256
256
  ],
257
257
  parameters: QuestionParamsSchema,
258
258
  executionMode: "sequential",
@@ -1,14 +1,15 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { filterChildSessionContextFiles, type ContextFileOptions } from "../lib/child-context-files.ts";
3
- import { REQUESTED_TOOLS_ENV } from "../lib/agents-runner.ts";
3
+ import { CHILD_SKILLS_CATALOG_ENV, REQUESTED_TOOLS_ENV } from "../lib/agents-runner.ts";
4
4
  import { registerCodeGraphTool } from "./codegraph-tools.ts";
5
5
 
6
6
  // gentle-shell#1587: delegated children drop the orchestrator-only gentle-ai
7
- // managed blocks from their context files. Gentle Agents passes this file to
8
- // every child with --extension because children do not load the gentle-pi
9
- // package in the isolated Gentle Shell home. At startup it also supplies the
10
- // existing CodeGraph implementation only when explicitly requested and absent
11
- // (the full package already registers it). Outside a child session it is inert.
7
+ // managed blocks and the engram-protocol memory block from their context files
8
+ // and keep everything else. Gentle Agents passes this file to every child with
9
+ // --extension because children do not load the gentle-pi package in the
10
+ // isolated Gentle Shell home. At startup it also supplies the existing
11
+ // CodeGraph implementation only when explicitly requested and absent (the full
12
+ // package already registers it). Outside a child session it is inert.
12
13
  export function createChildContextExtension(env: NodeJS.ProcessEnv = process.env): (pi: ExtensionAPI) => void {
13
14
  return (pi) => {
14
15
  const requested = (env[REQUESTED_TOOLS_ENV] ?? "").split(",").map(name => name.trim());
@@ -22,14 +23,27 @@ export function createChildContextExtension(env: NodeJS.ProcessEnv = process.env
22
23
  // The filtered copies replace contextFiles on the same options object
23
24
  // (pi-claude-bridge rebuilds its prompt from it). This never throws,
24
25
  // keeps the original files on any error or malformed markers, and is
25
- // idempotent: already-filtered content has nothing left to remove.
26
+ // idempotent: already-filtered content has nothing left to remove. The
27
+ // engram-protocol block goes too, because gentle-engram injects its own
28
+ // memory protocol every turn; the file on disk keeps it.
26
29
  const options = (event as { systemPromptOptions?: ContextFileOptions | null } | undefined)?.systemPromptOptions;
27
30
  filterChildSessionContextFiles(options);
31
+ dropSkillsCatalog(event, env);
28
32
  return undefined;
29
33
  });
30
34
  };
31
35
  }
32
36
 
37
+ // The runner marks the children of the package-owned generic agents, whose
38
+ // parent passes exact skill paths. Emptying the loaded skills in place removes
39
+ // Pi's `<available_skills>` section under every launch form, including skills
40
+ // of a package passed with --extension, which --no-skills keeps.
41
+ function dropSkillsCatalog(event: unknown, env: NodeJS.ProcessEnv): void {
42
+ if (env[CHILD_SKILLS_CATALOG_ENV] !== "1") return;
43
+ const skills = (event as { systemPromptOptions?: { skills?: unknown } | null } | undefined)?.systemPromptOptions?.skills;
44
+ if (Array.isArray(skills)) skills.length = 0;
45
+ }
46
+
33
47
  export default function childContextExtension(pi: ExtensionAPI): void {
34
48
  createChildContextExtension()(pi);
35
49
  }
@@ -22,8 +22,10 @@ import { join, resolve, isAbsolute } from "node:path";
22
22
  import { fileURLToPath } from "node:url";
23
23
  import { createLocalBashOperations, keyHint, SettingsManager, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
24
24
  import { createJobRegistry, isStandaloneSleep, type JobExecOperations, type JobRecord } from "../lib/background-jobs.ts";
25
- import { JOB_GLYPH, JOB_NOTICE_TYPE, jobDetails, jobNoticeText, monitorEventsText, monitorStoppedText, registerBackgroundJobTools } from "../lib/background-jobs-tools.ts";
25
+ import { JOB_GLYPH, JOB_NOTICE_TYPE, jobDetails, jobNoticeText, monitorEventsText, monitorStoppedText, registerBackgroundJobTools, type BackgroundJobsChange } from "../lib/background-jobs-tools.ts";
26
26
  import { createMonitorController, mergeMonitorBatches, type MonitorNotice } from "../lib/background-monitor.ts";
27
+ import { DESKTOP_JOBS_SERVICE_CHANNEL, DESKTOP_JOBS_SERVICE_SCHEMA, projectDesktopJob, selectDesktopJobs, type DesktopJobsCancelOutcome, type DesktopJobsOwnerRead, type DesktopJobsService } from "../lib/desktop-rpc-jobs.ts";
28
+ import { DESKTOP_AGENTS_SERVICE_CHANNEL, DESKTOP_AGENTS_SERVICE_SCHEMA, accumulateTaskUsage, projectDesktopAgent, selectDesktopAgents, type DesktopAgentsCancelOutcome, type DesktopAgentsOwnerRead, type DesktopAgentsService } from "../lib/desktop-rpc-agents.ts";
27
29
  import { JobsView } from "../lib/jobs-view.ts";
28
30
  import { JOBS_FINISHED_TTL_MS } from "../lib/jobs-widget.ts";
29
31
  import { JOBS_SIDEBAR_EVENT, JOBS_STATUS_KEY } from "../lib/jobs-sidebar-state.ts";
@@ -34,6 +36,7 @@ import { NativePointerRegion } from "../lib/native-pointer-region.ts";
34
36
  import { resolveVisualSettings } from "../lib/visual-customization-policy.ts";
35
37
  import { createCompletionQueue } from "../lib/agents-completion-delivery.ts";
36
38
  import { createAgentMessageQueue, type PendingAgentMessage } from "../lib/agents-message-delivery.ts";
39
+ import { capReport, withReportCap } from "../lib/agents-report-cap.ts";
37
40
  import { parseModelRef, AGENT_MODE, PROFILE_SOURCE, PROVIDER_REVIEW_ROLES, discoverAgents, formatModelRef, loadAgentsConfig, resolveAgentProfile, unmatchedProfileKeys, withPinnedModelProfiles, type AgentDefinition, type AgentMode, type ProfileSource } from "../lib/agents-config.ts";
38
41
  import { freezeSessionProfileAtStartup, inheritedProfileDriftNotice, resolveSessionProfile, sessionProfileRoutingAt, type InheritedProfileOptions, type SessionProfileResolution } from "../lib/session-profile-freeze.ts";
39
42
  import { resolveProfilePin, resolveUnversionedProjectProfile } from "../lib/agent-profile-pin.ts";
@@ -43,7 +46,7 @@ import { installBackgroundCacheWarming } from "../lib/background-cache-warming.t
43
46
  import { isFinished, MISSING_TOOLS_NOTE_PREFIX, TASK_EVENT, TASK_STATUS, TaskStore, type AskRequest, type TaskRecord } from "../lib/agents-protocol.ts";
44
47
  import { AgentRunner, piCommand, abortReasonText, CHILD_JOBS_ENV, REQUESTED_TOOLS_ENV, type AskAnswer, type RunnerDeps, type TaskRequest } from "../lib/agents-runner.ts";
45
48
  import { parseChildPackageInjection } from "../lib/child-package-injection.ts";
46
- import { ChildMessenger, formatChildJobState, type IpcEndpoint } from "../lib/agents-messaging.ts";
49
+ import { CHILD_MESSAGE_MAX_BYTES, ChildMessenger, formatChildJobState, type IpcEndpoint } from "../lib/agents-messaging.ts";
47
50
  import { ActiveSessionClient, ActiveSessionListener, SessionPresenceError, SessionPresenceRegistry, type PresenceRecord, type ReceivedNotification, type SentNotification, type SessionPresenceCandidate } from "../lib/agents-session-transport.ts";
48
51
  import { WindowsActiveSessionClient, WindowsActiveSessionListener, WindowsSessionPresenceRegistry, WindowsSessionRegistryPhaseSequence, isWindowsSessionBootstrapDiagnosticCode, type WindowsSessionBootstrapDiagnosticCode, type WindowsSessionBootstrapDiagnosticObserver, type WindowsSessionRegistryPhaseObserver } from "../lib/windows-session-transport.ts";
49
52
  import { hasReviewSessionPermission, resolveCanonicalGitRepositoryIdentitySync, type ReviewSessionManager } from "../lib/review-session-standing-permission.ts";
@@ -77,6 +80,8 @@ import { allowedEditSurfaces, inheritAllowedEditSurfaces, isBoundedWriter, isDev
77
80
  import { CHILD_METRICS_EVENT, CHILD_METRICS_REVOKED, childEvent, launchSelection, type LaunchSelection } from "../lib/runtime-metrics-children.ts";
78
81
  import { runtimeMetricsEnvAllows, type RuntimeMetricsPolicyDeps } from "../lib/runtime-metrics-policy.ts";
79
82
  import { publishTaskStatusChanges } from "../lib/notification-events.ts";
83
+ import { appendSystemPromptOnce } from "../lib/append-system-prompt.ts";
84
+ import { codemodeReaches, COORDINATION_TOOLS_ROUTE, hideBehindCodemode } from "../lib/hidden-tools.ts";
80
85
 
81
86
  // Gentle Agents: subagents as isolated `pi --mode rpc` children, a task
82
87
  // store that notifies per task, and a Gentle Shell card above the editor.
@@ -702,9 +707,9 @@ export function resolveDefaultSubagentMode(input: {
702
707
 
703
708
  // What the model reads when a background task ends: the outcome first, then
704
709
  // the answer itself. The expanded card shows the same text.
705
- export function completionText(task: TaskRecord): string {
710
+ export function completionText(task: TaskRecord, report: string = finishedText(task)): string {
706
711
  const outcome = task.status === "completed" ? "finished" : task.status.replace("_", " ");
707
- return `Subagent ${task.agent} (task ${task.id}, "${task.label}") ${outcome}.\n\n${finishedText(task)}`;
712
+ return `Subagent ${task.agent} (task ${task.id}, "${task.label}") ${outcome}.\n\n${report}`;
708
713
  }
709
714
 
710
715
  const COMPLETION_HEADER = /^Subagent [^\n]+ \(task [^\n]*\) [^\n]+\.$/;
@@ -1203,6 +1208,9 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1203
1208
  type JobNotice = { job: JobRecord; kind: "exit" } | MonitorNotice;
1204
1209
  const jobNotices: JobNotice[] = [];
1205
1210
  let jobOutputDir: string | undefined;
1211
+ // Shutdown stops every job through stopAll and then refreshes once; that
1212
+ // final refresh must not notify Desktop consumers (the channel is closing).
1213
+ let shuttingDown = false;
1206
1214
  const jobs = createJobRegistry({
1207
1215
  outputDir: deps.jobOutputDir ?? (() => (jobOutputDir ??= mkdtempSync(join(os.tmpdir(), "gentle-jobs-")))),
1208
1216
  now: deps.now,
@@ -1218,6 +1226,142 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1218
1226
  now: deps.now,
1219
1227
  deliver: (notice) => queueJobNotice(notice),
1220
1228
  });
1229
+ // Desktop's jobs slice reaches the single parent registry and monitor
1230
+ // controller only through this versioned, adapter-shaped seam — the jobs
1231
+ // analogue of the usage/design owner services. The adapter never runs or
1232
+ // stops a job itself: `cancel` is `job_stop`'s exact stop path
1233
+ // (`monitors.cancel` then `registry.stop`), and `observe` is driven by the
1234
+ // same actual registry changes below. There is no second registry, process
1235
+ // manager, or store.
1236
+ const desktopJobsObservers = new Set<(sessionId: string) => void>();
1237
+ const notifyDesktopJobs = (sessionId: string): void => {
1238
+ if (desktopJobsObservers.size === 0) return;
1239
+ for (const observer of [...desktopJobsObservers]) {
1240
+ try { observer(sessionId); } catch { /* an observer never breaks jobs */ }
1241
+ }
1242
+ };
1243
+ const unsubscribeDesktopJobsService = pi.events.on(DESKTOP_JOBS_SERVICE_CHANNEL, (payload: unknown) => {
1244
+ if (!payload || typeof payload !== "object") return;
1245
+ const request = payload as Partial<{ context: ExtensionContext; respond(service: DesktopJobsService): void }>;
1246
+ if (typeof request.respond !== "function" || !request.context) return;
1247
+ const ctx = request.context;
1248
+ try {
1249
+ let disposed = false;
1250
+ const subscriptions = new Set<(sessionId: string) => void>();
1251
+ const sessionId = ctx.sessionManager?.getSessionId?.() ?? "";
1252
+ const read = (): DesktopJobsOwnerRead => ({
1253
+ sessionId,
1254
+ jobs: disposed ? [] : selectDesktopJobs(jobs.list(sessionId), deps.now()),
1255
+ });
1256
+ const cancel = (id: string): DesktopJobsCancelOutcome => {
1257
+ if (disposed) return { kind: "not_found" };
1258
+ const job = jobs.get(id);
1259
+ // The same ownership check job_stop performs: a foreign or unknown
1260
+ // id is a typed not_found, never a stop of someone else's job.
1261
+ if (!job || job.ownerSessionId !== sessionId) return { kind: "not_found" };
1262
+ const wasRunning = job.status === "running";
1263
+ monitors.cancel(job.id);
1264
+ jobs.stop(job.id);
1265
+ return { kind: "ok", job: projectDesktopJob(job), changed: wasRunning };
1266
+ };
1267
+ request.respond({
1268
+ schema: DESKTOP_JOBS_SERVICE_SCHEMA,
1269
+ read,
1270
+ cancel,
1271
+ observe: (onChange) => {
1272
+ if (disposed) return () => {};
1273
+ subscriptions.add(onChange);
1274
+ desktopJobsObservers.add(onChange);
1275
+ return () => {
1276
+ subscriptions.delete(onChange);
1277
+ desktopJobsObservers.delete(onChange);
1278
+ };
1279
+ },
1280
+ dispose: () => {
1281
+ disposed = true;
1282
+ for (const onChange of subscriptions) desktopJobsObservers.delete(onChange);
1283
+ subscriptions.clear();
1284
+ },
1285
+ });
1286
+ } catch {
1287
+ /* obsolete trusted context: discovery expires closed */
1288
+ }
1289
+ });
1290
+ // Desktop subagents owner adapter: the agents analogue of the jobs/usage
1291
+ // owner services. The adapter never runs, stops, or spawns a subagent
1292
+ // itself: `cancel` is the exact `runner.cancel` stop path the agents panel
1293
+ // stop uses, `read` projects the single `TaskStore`, and `observe` is
1294
+ // driven by the same actual TaskStore transitions below. There is no second
1295
+ // store, runner, or process manager. `runner` is declared later in this
1296
+ // module; the adapter closes over the binding lazily.
1297
+ const desktopAgentsObservers = new Set<(sessionId: string) => void>();
1298
+ const notifyDesktopAgents = (sessionId: string): void => {
1299
+ if (desktopAgentsObservers.size === 0) return;
1300
+ for (const observer of [...desktopAgentsObservers]) {
1301
+ try { observer(sessionId); } catch { /* an observer never breaks agents */ }
1302
+ }
1303
+ };
1304
+ const unsubscribeDesktopAgentsService = pi.events.on(DESKTOP_AGENTS_SERVICE_CHANNEL, (payload: unknown) => {
1305
+ if (!payload || typeof payload !== "object") return;
1306
+ const request = payload as Partial<{ context: ExtensionContext; respond(service: DesktopAgentsService): void }>;
1307
+ if (typeof request.respond !== "function" || !request.context) return;
1308
+ const ctx = request.context;
1309
+ try {
1310
+ let disposed = false;
1311
+ const subscriptions = new Set<(sessionId: string) => void>();
1312
+ const sessionId = ctx.sessionManager?.getSessionId?.() ?? "";
1313
+ const read = (): DesktopAgentsOwnerRead => ({
1314
+ sessionId,
1315
+ agents: disposed ? [] : selectDesktopAgents(store.list(sessionId)),
1316
+ });
1317
+ const cancel = (id: string): DesktopAgentsCancelOutcome => {
1318
+ if (disposed) return { kind: "not_found" };
1319
+ const before = store.get(id);
1320
+ // The same ownership check the agents panel stop performs: a foreign
1321
+ // or unknown id is a typed not_found, never a stop of someone else's task.
1322
+ if (!before || before.parentSessionId !== sessionId) return { kind: "not_found" };
1323
+ // The same owner path the agents panel stop uses: runner.cancel. Its
1324
+ // boolean is honored verbatim, and `changed` reflects the store's actual
1325
+ // synchronous transition, not the request. A queued task transitions to
1326
+ // cancelled here; a running task's cancellation is asynchronous (no
1327
+ // synchronous transition), so a repeated in-flight cancel is `changed:
1328
+ // false` and never emits an immediate fabricated event.
1329
+ const requested = runner.cancel(id, "cancelled: stopped from desktop");
1330
+ const after = store.get(id) ?? before;
1331
+ const changed = requested && after.status !== before.status;
1332
+ return { kind: "ok", agent: projectDesktopAgent(after), requested, changed };
1333
+ };
1334
+ request.respond({
1335
+ schema: DESKTOP_AGENTS_SERVICE_SCHEMA,
1336
+ read,
1337
+ cancel,
1338
+ observe: (onChange) => {
1339
+ if (disposed) return () => {};
1340
+ subscriptions.add(onChange);
1341
+ desktopAgentsObservers.add(onChange);
1342
+ return () => {
1343
+ subscriptions.delete(onChange);
1344
+ desktopAgentsObservers.delete(onChange);
1345
+ };
1346
+ },
1347
+ dispose: () => {
1348
+ disposed = true;
1349
+ for (const onChange of subscriptions) desktopAgentsObservers.delete(onChange);
1350
+ subscriptions.clear();
1351
+ },
1352
+ });
1353
+ } catch {
1354
+ /* obsolete trusted context: discovery expires closed */
1355
+ }
1356
+ });
1357
+ // Actual TaskStore transitions (task add and every status change) notify the
1358
+ // Desktop bridge. Restored-from-disk snapshots are silent, matching the
1359
+ // status-change notification contract. The usage breakdown recorded at
1360
+ // completion is a status-unchanged update, so `onFinish` notifies it
1361
+ // explicitly; the bridge coalesces both into one event.
1362
+ const stopAgentsStatusNotifications = store.subscribeStatusChanges((change) => {
1363
+ notifyDesktopAgents(change.sessionId);
1364
+ });
1221
1365
  // A parent that sleeps while background work runs only burns the turn: each
1222
1366
  // completion already arrives as a session message (#1903). bash_background
1223
1367
  // and monitor stay allowed because they are the sanctioned way to wait.
@@ -1473,7 +1617,11 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1473
1617
  // Ownership is consulted at delivery time, matching onNotification and
1474
1618
  // onQuery: a completion owned by another session is dropped, not delivered.
1475
1619
  if (activeSessionId() !== task.parentSessionId) return;
1476
- sendToParent({ customType: AGENTS_RESULT_TYPE, content: completionText(task), display: true, details: taskDetails(task) }, route);
1620
+ // P9b: only the delivered copy is capped; subagent_result keeps the full text.
1621
+ let cwd = process.cwd();
1622
+ try { cwd = sessions?.getCwd() ?? cwd; } catch { /* A stale manager keeps the process directory, like the runner's config. */ }
1623
+ const capped = capReport(finishedText(task), loadAgentsConfig({ cwd, home: deps.home, agentHome }).reportMaxBytes, task.id, task.agent);
1624
+ sendToParent({ customType: AGENTS_RESULT_TYPE, content: completionText(task, capped.text), display: true, details: withReportCap(taskDetails(task), capped) }, route);
1477
1625
  };
1478
1626
 
1479
1627
  // Incoming orchestrator session messages. The transport has already
@@ -1584,22 +1732,26 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1584
1732
  const flushJobNotices = () => {
1585
1733
  const route = deliveryRoute(false);
1586
1734
  if (!route) return;
1587
- const failed: JobNotice[] = [];
1735
+ const retained: JobNotice[] = [];
1736
+ let deliveryFailed = false;
1588
1737
  for (const notice of jobNotices.splice(0)) {
1589
1738
  const { job } = notice;
1590
- if (activeSessionId() !== job.ownerSessionId) continue;
1739
+ if (activeSessionId() !== job.ownerSessionId) {
1740
+ retained.push(notice);
1741
+ continue;
1742
+ }
1591
1743
  const content = notice.kind === "events" ? monitorEventsText(job, notice.batch)
1592
1744
  : notice.kind === "stopped" ? monitorStoppedText(job, notice.reason) : jobNoticeText(job);
1593
1745
  const event = notice.kind === "events" ? "events" : notice.kind === "stopped" ? notice.reason : undefined;
1594
1746
  try {
1595
1747
  sendToParent({ customType: JOB_NOTICE_TYPE, content, display: true, details: jobDetails(job, event) }, route);
1596
1748
  } catch {
1597
- failed.push(notice);
1749
+ retained.push(notice);
1750
+ deliveryFailed = true;
1598
1751
  }
1599
1752
  }
1600
- if (failed.length === 0) return;
1601
- jobNotices.unshift(...failed);
1602
- if (route === "idle") armDeliveryRetry();
1753
+ jobNotices.unshift(...retained);
1754
+ if (deliveryFailed && route === "idle") armDeliveryRetry();
1603
1755
  };
1604
1756
 
1605
1757
  const flushAll = () => {
@@ -1660,6 +1812,11 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1660
1812
  ...finished.map(({ id, label, startedAt, status, endedAt, exitCode }) => ({ id, label, startedAt, status, endedAt, exitCode })),
1661
1813
  ] } });
1662
1814
  } catch { /* Display only. */ }
1815
+ // Every actual registry change funnels through this refresh, including
1816
+ // monitor self-timeout/flood stops (their `stopFor` delivers a notice
1817
+ // here). Notify Desktop consumers; the bridge dedupes byte-identical
1818
+ // lists so a stop that also flushes pending lines still emits once.
1819
+ if (!shuttingDown) notifyDesktopJobs(sessionId);
1663
1820
  }
1664
1821
  };
1665
1822
 
@@ -1710,8 +1867,10 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1710
1867
  // compaction ran inside or right before the run. `before_agent_start`
1711
1868
  // marks a prompt that is about to start a run, and the compaction events
1712
1869
  // release content held while the parent compacted without a run.
1713
- pi.on("before_agent_start", () => {
1870
+ pi.on("before_agent_start", (event) => {
1714
1871
  if (!parentRunActive) beginPromptStart();
1872
+ const options = event?.systemPromptOptions;
1873
+ if (codemodeReaches(options?.selectedTools) && ["orchestrator_list", "orchestrator_consult", "orchestrator_send_message"].some((name) => options?.selectedTools?.includes(name))) appendSystemPromptOnce(options, COORDINATION_TOOLS_ROUTE);
1715
1874
  });
1716
1875
  pi.on("agent_start", () => {
1717
1876
  activeAgentRuns += 1;
@@ -1784,7 +1943,8 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1784
1943
  },
1785
1944
  onQuerySettled: (taskId, requestId, outcome) => {
1786
1945
  if (outcome === "replied") messages.consumeQuery(taskId, requestId);
1787
- else messages.expireQuery(taskId, requestId);
1946
+ // A busy parent still sees a question that expired in its queue (S15 P9a).
1947
+ else messages.markQueryExpired(taskId, requestId);
1788
1948
  },
1789
1949
  onFallback: (task, change) => announceFallback({ agent: task.agent, from: change.from, to: change.to, category: change.category, ...(change.launch ? { launch: true } : {}) }, task.parentSessionId, task.id),
1790
1950
  onSuccessfulMutation: (task, tool) => {
@@ -1850,18 +2010,31 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
1850
2010
  if (event && metrics.current()) pi.events.emit(CHILD_METRICS_EVENT, event);
1851
2011
  }
1852
2012
  } catch { /* Metrics must never interrupt task finalization. */ }
2013
+ try {
2014
+ // Record the final-assistant token breakdown so the Desktop list can
2015
+ // project per-helper usage; in-flight tasks stay without it. This is a
2016
+ // status-unchanged update, so the agents owner notifies explicitly and
2017
+ // the Desktop bridge coalesces it with the terminal status change.
2018
+ if (observations && observations.responses.length > 0) {
2019
+ store.update(task.id, { usage: accumulateTaskUsage(observations.responses) });
2020
+ notifyDesktopAgents(parentSessionId);
2021
+ }
2022
+ } catch { /* Best-effort usage bookkeeping cannot strand runner waiters. */ }
1853
2023
  try {
1854
2024
  ownedTaskIds.delete(task.id);
1855
2025
  messages.invalidateTask(task.id);
1856
2026
  requestRender();
1857
- persist(task);
2027
+ // Persist the post-breakdown record so a restored finished task keeps
2028
+ // its final usage. `task` is the onFinish argument, which predates the
2029
+ // usage update above; the store now carries the merged record.
2030
+ persist(store.get(task.id) ?? task);
1858
2031
  const yielded = yieldedTaskIds.delete(task.id);
1859
2032
  if ((task.mode === AGENT_MODE.BACKGROUND && task.status !== TASK_STATUS.CANCELLED) || (yielded && task.status !== TASK_STATUS.CANCELLED && activeSessionId() === task.parentSessionId)) settleCompletion(task);
1860
2033
  } catch { /* Best-effort completion bookkeeping cannot strand runner waiters. */ }
1861
2034
  },
1862
2035
  });
1863
2036
 
1864
- registerBackgroundJobTools(pi, { registry: jobs, monitors, sessionId: (ctx) => ctx.sessionManager.getSessionId() ?? "", now: deps.now, onChange: () => { refreshJobStatus(); requestRender(); } });
2037
+ registerBackgroundJobTools(pi, { registry: jobs, monitors, sessionId: (ctx) => ctx.sessionManager.getSessionId() ?? "", now: deps.now, onChange: (change: BackgroundJobsChange) => { refreshJobStatus(); requestRender(); } });
1865
2038
 
1866
2039
  pi.registerMessageRenderer(AGENTS_MESSAGE_TYPE, (message, options, theme) => {
1867
2040
  const details = (message.details as { gentleAgents?: { taskId?: unknown; agent?: unknown } } | undefined)?.gentleAgents;
@@ -2270,7 +2443,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2270
2443
  };
2271
2444
  };
2272
2445
 
2273
- const roots = (ctx: ExtensionContext) => ({ cwd: ctx.sessionManager.getCwd(), home: deps.home, agentHome });
2446
+ const roots = (ctx: ExtensionContext) => ({ cwd: ctx.sessionManager.getCwd(), home: deps.home, agentHome, configHome: gentlePiConfigHome(deps.env) });
2274
2447
  // Issue #2400: parent sessions already told about model_profiles keys that
2275
2448
  // match no agent and suggest none, so the notice fires once per session.
2276
2449
  const unmatchedKeysNotifiedSessions = new Set<string>();
@@ -2579,7 +2752,8 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2579
2752
  messages.invalidateTask(finished.id);
2580
2753
  // The id rides in the text too: details never reach the model, which
2581
2754
  // otherwise guesses ordinal ids for subagent_continue (#1731 T19).
2582
- return text(completionText(finished), taskDetails(finished));
2755
+ const capped = capReport(finishedText(finished), loadAgentsConfig(roots(ctx)).reportMaxBytes, finished.id, finished.agent);
2756
+ return text(completionText(finished, capped.text), withReportCap(taskDetails(finished), capped));
2583
2757
  } finally {
2584
2758
  signal?.removeEventListener("abort", onAbort);
2585
2759
  }
@@ -2742,11 +2916,11 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2742
2916
  pi.registerTool({
2743
2917
  name: "orchestrator_session_id",
2744
2918
  label: "Orchestrator session ID",
2745
- description: "Return this session's stable routing ID, Initial alias (FIRST TASK), Current alias (CURRENT TASK), and separate human Session name. Subject updates Current even when named; Initial is the first declared branch topic, unknown for legacy history. Without subject, explicit state.work.topic updates Current; keep it current as tasks change. Before delegation or cross-session coordination, declare a short recognizable non-sensitive subject, not a prompt. Do not require a subject declaration for small direct tasks. Do not query all peers. Names never authenticate. Existing Pi names and human renames are preserved. Progress is published automatically from the todo list; publish state only for objective, decisions, blockers or work, never just progress. Classified work must publish objective and work.topic/area at session start and every task-topic change; never retain old task state. Catalog flags never-published peers. Owner-curated state: 2048 UTF-8 bytes total; null withdraws, omission leaves unchanged. Never include credentials, internal instructions, or raw prompts. Historical notes are not consent or an owner reply.",
2919
+ description: "Return this session's stable routing ID, Initial alias (FIRST TASK), Current alias (CURRENT TASK), and separate human Session name. Subject updates Current even when named; Initial is the first declared branch topic, unknown for legacy history. Without subject, explicit state.work.topic updates Current; keep it current as tasks change. Before delegation or cross-session coordination, declare a short recognizable non-sensitive subject, not a prompt. Do not require a subject declaration for small direct tasks. Do not query all peers. Names never authenticate. Existing Pi names and human renames are preserved. Progress is published automatically from the todo list; publish state only for objective, decisions, blockers or work, never just progress. If you publish classified work, keep objective and work.topic/area current on each task-topic change; never retain old task state. Catalog flags never-published peers. Owner-curated state: 2048 UTF-8 bytes total; null withdraws, omission leaves unchanged. Never include credentials, internal instructions, or raw prompts. Historical notes are not consent or an owner reply.",
2746
2920
  ...orchestratorToolRenderers("session", expandHint),
2747
2921
  parameters: { type: "object", additionalProperties: false, properties: {
2748
2922
  subject: { type: "string", maxLength: 120, description: "Short task subject; updates aliases independently of human names and names unnamed Pi sessions." },
2749
- state: { anyOf: [{ type: "null" }, { type: "object", additionalProperties: false, properties: {
2923
+ state: { anyOf: [{ type: "null" }, { type: "string" }, { type: "object", additionalProperties: false, properties: {
2750
2924
  objective: { type: "string" }, progress: { type: "string" }, decisions: { type: "string" }, blockers: { type: "string" },
2751
2925
  work: { type: "object", additionalProperties: false,
2752
2926
  description: "Historical, non-authoritative; topic requires area. Text and work JSON share 2048 UTF-8 bytes. Reject exact duplicate tags/refs; no ref resolution or routing.",
@@ -2762,7 +2936,17 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2762
2936
  async execute(_id, params, _signal, _onUpdate, ctx) {
2763
2937
  const transport = activeTransportFor(ctx);
2764
2938
  if (!transport) return text("Error: session messaging is not ready.", { error: "not ready" });
2765
- const { subject, state } = params as { subject?: unknown; state?: unknown };
2939
+ const { subject, state: rawState } = params as { subject?: unknown; state?: unknown };
2940
+ // Agents sometimes serialize the state object as a JSON string; accept
2941
+ // it with the same rules instead of a cryptic schema rejection, and
2942
+ // name the nesting rule when the parsed shape is flat.
2943
+ let state = rawState;
2944
+ if (typeof rawState === "string") {
2945
+ try { state = JSON.parse(rawState); }
2946
+ catch { throw new Error("invalid-state-json: state must be a JSON object string with objective/progress/decisions/blockers and optional work{area,topic,tags,refs,tasks} nested under \"work\"."); }
2947
+ if (state !== null && (typeof state !== "object" || Array.isArray(state))) throw new Error("invalid-state-json: the JSON string must encode an object or null.");
2948
+ if (state && Object.keys(state).some(key => !["objective", "progress", "decisions", "blockers", "work"].includes(key))) throw new Error("invalid-state-json: unknown top-level fields; area/topic/tags/refs/tasks must be nested under \"work\", not at the top level of state.");
2949
+ }
2766
2950
  const declared = normalizeTaskSubject(subject);
2767
2951
  // An owner object without `progress` keeps the automatic todo progress still on
2768
2952
  // display; null and an explicit `progress` win, and an over-budget merge does not fail the call.
@@ -2791,6 +2975,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2791
2975
  pi.registerTool({
2792
2976
  name: "orchestrator_consult",
2793
2977
  label: "Consult published context",
2978
+ prepareLoadout: hideBehindCodemode("orchestrator_consult"),
2794
2979
  ...orchestratorToolRenderers("consult", expandHint),
2795
2980
  description: "Read published metadata (default), request bounded helper reasoning with explicit UI model-cost permission and a question, or revoke-reasoning for an exact target. Never an owner reply, consent or private context access.",
2796
2981
  parameters: { type: "object", additionalProperties: false, required: ["recipient_session_id"], properties: {
@@ -2841,6 +3026,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2841
3026
  pi.registerTool({
2842
3027
  name: "orchestrator_list",
2843
3028
  label: "List orchestrators",
3029
+ prepareLoadout: hideBehindCodemode("orchestrator_list"),
2844
3030
  ...orchestratorToolRenderers("list", expandHint),
2845
3031
  description: "List other sessions advertised by the trusted local profile. Omit filter for the existing list; filter searches published classified work only: bounded, non-exhaustive, no authority, unknown reachability. Classified work must publish at session start and each task-topic change; flag peers doing classified work who never published state.",
2846
3032
  parameters: Type.Object({
@@ -2921,6 +3107,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2921
3107
  pi.registerTool({
2922
3108
  name: "orchestrator_send_message",
2923
3109
  label: "Send orchestrator message",
3110
+ prepareLoadout: hideBehindCodemode("orchestrator_send_message"),
2924
3111
  renderShell: "self",
2925
3112
  renderCall(args, theme, context) {
2926
3113
  return outgoingMessageCall(args as { message?: unknown }, theme, context, expandHint(context.expanded));
@@ -2998,26 +3185,26 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
2998
3185
  });
2999
3186
 
3000
3187
  tool("list_agents", "List the subagents defined for this project and user, with their descriptions and declared tool inventory.", { properties: {} }, async (_params, ctx) => {
3001
- const { agents, errors } = discoverAgents(roots(ctx));
3188
+ const { agents, errors, notices } = discoverAgents(roots(ctx));
3002
3189
  const lines = agents.map((agent) => `- ${agent.name} (${agent.scope}): ${agent.description || "no description"} ${declaredToolInventory(agent)}`);
3003
- const problems = errors.map((error) => `! ${error}`);
3190
+ const problems = [...errors, ...notices].map((problem) => `! ${problem}`);
3004
3191
  return text(lines.length === 0 ? "No subagents defined." : [...lines, ...problems].join("\n"));
3005
3192
  });
3006
3193
 
3007
3194
  tool(
3008
3195
  "run",
3009
- "Delegate a task to a named subagent. Task mode waits for the answer; background mode returns a task id immediately.",
3196
+ "Delegate a task to a named subagent. Admission rejects writers without repository-relative `## Allowed edit surfaces`; below the context backstop, organic writers without `Spec: odd/tasks/<existing>.md, T<n>` (2+ disjoint writers alone in one message pass) and `gentle-ai-verify` without that or `Risk: item N`.",
3010
3197
  {
3011
3198
  required: ["agent", "task"],
3012
3199
  properties: {
3013
3200
  agent: { type: "string", description: "Subagent name from subagent_list_agents." },
3014
3201
  task: { type: "string", description: "What the subagent must do, self-contained." },
3015
- label: { type: "string", description: "Three to six words naming the work, shown on the agents card, e.g. 'map footer data sources'." },
3202
+ label: { type: "string", description: "Three to six words naming the work for the agents card, e.g. 'map footer data sources'." },
3016
3203
  context: { type: "string", description: "Optional extra context appended to the task." },
3017
3204
  work: workDescriptorSchema,
3018
- workspace_root: { type: "string", description: "Optional canonical main or linked Git worktree within the parent's same clone only; mutually exclusive with repository_root." },
3019
- repository_root: { type: "string", description: "Optional canonical independent Git repository; requires direct interactive session-scoped consent before queueing; mutually exclusive with workspace_root." },
3020
- mode: { type: "string", enum: ["task", "background"], description: "task waits for the result (default); background returns immediately." },
3205
+ workspace_root: { type: "string", description: "Optional canonical main or linked Git worktree within the parent's clone only; exclusive with repository_root." },
3206
+ repository_root: { type: "string", description: "Optional canonical independent Git repository; needs direct interactive session-scoped consent before queueing; exclusive with workspace_root." },
3207
+ mode: { type: "string", enum: ["task", "background"], description: "task waits for the result (default); background returns a task id at once." },
3021
3208
  },
3022
3209
  },
3023
3210
  async (params, ctx, signal) => {
@@ -3092,11 +3279,18 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
3092
3279
  return text(reconciledTasks.length === 0 ? "No subagent tasks in this session." : reconciledTasks.map(describeTask).join("\n"));
3093
3280
  });
3094
3281
 
3095
- tool("reply", "Reply once to a live query from a child of the current parent session.", { required: ["task_id", "request_id", "message"], properties: { task_id: { type: "string" }, request_id: { type: "string" }, message: { type: "string" } } }, async (params, ctx) => {
3282
+ tool("reply", "Reply once to a child query; a late reply arrives as a message.", { required: ["task_id", "request_id", "message"], properties: { task_id: { type: "string" }, request_id: { type: "string" }, message: { type: "string" } } }, async (params, ctx) => {
3096
3283
  const taskId = String(params.task_id);
3097
3284
  const requestId = String(params.request_id);
3098
- const accepted = await runner.reply(taskId, requestId, typeof params.message === "string" ? params.message : "", ctx.sessionManager.getSessionId() ?? "");
3099
- return accepted ? text("Reply accepted for delivery.") : text("Error: query is unavailable.", { error: "query unavailable" });
3285
+ const message = typeof params.message === "string" ? params.message : "";
3286
+ const sessionId = ctx.sessionManager.getSessionId() ?? "";
3287
+ if (await runner.reply(taskId, requestId, message, sessionId)) return text("Reply accepted for delivery.");
3288
+ // S15 P9a: a busy parent answers after the deadline; the answer still reaches a running child.
3289
+ const late = runner.replyLate(taskId, requestId, message, sessionId);
3290
+ if (late === "delivered") return text(`Query ${requestId} had expired; the answer was delivered to task ${taskId} as a message.`);
3291
+ if (late === "too large") return text(`Error: the reply exceeds the ${CHILD_MESSAGE_MAX_BYTES}-byte message limit and was not delivered; query ${requestId} can still be answered with a shorter reply.`, { error: "reply too large" });
3292
+ if (late === "not running") return text(`Error: query ${requestId} had expired and task ${taskId} is no longer running, so the answer was not delivered. Pass it with subagent_continue.`, { error: "query expired" });
3293
+ return text("Error: query is unavailable.", { error: "query unavailable" });
3100
3294
  });
3101
3295
 
3102
3296
  tool("cancel", "Cancel a queued or running subagent task.", { required: ["task_id"], properties: { task_id: { type: "string" } } }, async (params) => {
@@ -3196,6 +3390,7 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
3196
3390
  publishActivityPrompt();
3197
3391
  });
3198
3392
  pi.on("session_start", async (event, ctx) => {
3393
+ shuttingDown = false;
3199
3394
  // gentle-shell#1064 slice 3b-ii: a parent session that has no explicit
3200
3395
  // profile binding freezes `p → P → G` now. This handler is parent-only (a
3201
3396
  // child returns before registering it) and runs for every reason Pi
@@ -3212,11 +3407,11 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
3212
3407
  });
3213
3408
  } catch { /* A launch freezes lazily through the same resolver. */ }
3214
3409
  stateCache.load(ctx.sessionManager);
3215
- // A resumed, reloaded, or replaced session starts with an empty completion
3216
- // queue so nothing pending from another session can replay here.
3410
+ // A resumed, reloaded, or replaced session starts with empty completion
3411
+ // and message queues so nothing pending from another session can replay here.
3217
3412
  completions.dropAll();
3218
3413
  messages.dropAll();
3219
- jobNotices.length = 0;
3414
+ // Job notices remain owner-scoped and survive until their session resumes.
3220
3415
  resetParentDelivery(ctx);
3221
3416
  presence?.dispose();
3222
3417
  registryFor(ctx);
@@ -3275,6 +3470,12 @@ export default function gentleAgents(pi: ExtensionAPI, env: NodeJS.ProcessEnv =
3275
3470
  pi.on("agent_start", (_event, ctx) => rearmSessionTransport(ctx));
3276
3471
  pi.on("turn_end", (_event, ctx) => rearmSessionTransport(ctx));
3277
3472
  pi.on("session_shutdown", async () => {
3473
+ shuttingDown = true;
3474
+ stopAgentsStatusNotifications();
3475
+ // Both Desktop owner services leave the bus with the session, so a
3476
+ // replaced runtime is never discovered through a stale owner.
3477
+ unsubscribeDesktopJobsService();
3478
+ unsubscribeDesktopAgentsService();
3278
3479
  completions.dropAll();
3279
3480
  messages.dropAll();
3280
3481
  // No stale busy may survive the runtime.