gentle-pi 4.0.0 → 4.1.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 (398) hide show
  1. package/README.md +122 -8
  2. package/assets/agents/gentle-ai-explore.md +11 -4
  3. package/assets/agents/gentle-ai-verify.md +23 -4
  4. package/assets/agents/gentle-ai-worker.md +6 -6
  5. package/assets/install-wizard/index.html +47 -0
  6. package/assets/install-wizard/wizard.css +1279 -0
  7. package/assets/install-wizard/wizard.js +951 -0
  8. package/assets/orchestrator-delegation.md +70 -163
  9. package/assets/orchestrator-memory.md +11 -4
  10. package/assets/orchestrator-prompts.md +48 -0
  11. package/assets/orchestrator-tracking.md +53 -0
  12. package/assets/orchestrator-verification.md +28 -0
  13. package/assets/orchestrator-writer.md +38 -0
  14. package/assets/orchestrator.md +29 -25
  15. package/assets/sounds/LICENSE.md +52 -0
  16. package/assets/sounds/attention.wav +0 -0
  17. package/assets/sounds/error.wav +0 -0
  18. package/assets/sounds/success.wav +0 -0
  19. package/bin/engram-guard +9 -0
  20. package/bin/gentle-shell-install.mjs +302 -0
  21. package/bin/gentle-shell.mjs +703 -22
  22. package/contracts/review-provider-contract-mirror/provider-contract.lock.json +7 -7
  23. package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/bundle/manifest.json +2 -2
  24. package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/bundle/orchestration/pi.md +16 -4
  25. package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/generated/provider-capabilities.baseline.json +2 -2
  26. package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/generated/provider-roles.baseline.json +1 -1
  27. package/docs/bundled-install.md +397 -0
  28. package/docs/delegated-verification.md +3 -5
  29. package/docs/gentle-agents-activity.md +513 -0
  30. package/docs/gentle-shell-uninstall.md +136 -0
  31. package/docs/gentle-shell.md +81 -31
  32. package/docs/install-wizard.md +2040 -0
  33. package/docs/native-authority-architecture.md +1 -1
  34. package/docs/permission-modes.md +82 -0
  35. package/docs/prompt-history.md +1 -1
  36. package/docs/readme-reference.md +267 -40
  37. package/docs/render-cache-performance.md +28 -0
  38. package/docs/sound-notifications-proposal.md +191 -0
  39. package/docs/sound-notifications.md +114 -0
  40. package/docs/yolo-mode.md +9 -9
  41. package/extensions/child-context.ts +11 -2
  42. package/extensions/child-safety.ts +4 -2
  43. package/extensions/codegraph-tools.ts +18 -5
  44. package/extensions/gentle-agents.ts +688 -88
  45. package/extensions/gentle-ai.ts +886 -238
  46. package/extensions/gentle-herdr-activity.ts +81 -0
  47. package/extensions/gentle-notifications.ts +104 -0
  48. package/extensions/gentle-shell.ts +265 -69
  49. package/extensions/gentle-todo.ts +108 -13
  50. package/extensions/history/index.ts +11 -6
  51. package/extensions/pi-pretty.ts +39 -3
  52. package/extensions/quiet-tools.ts +91 -21
  53. package/extensions/skill-registry.ts +175 -46
  54. package/extensions/startup-banner.ts +11 -2
  55. package/lib/agent-home.ts +10 -1
  56. package/lib/agent-model-resolution.ts +80 -0
  57. package/lib/agent-profiles.ts +13 -3
  58. package/lib/agents-completion-delivery.ts +11 -3
  59. package/lib/agents-messaging.ts +1 -1
  60. package/lib/agents-protocol.ts +40 -1
  61. package/lib/agents-runner.ts +90 -15
  62. package/lib/auto-permission-classifier.ts +280 -0
  63. package/lib/auto-permission-runtime.ts +268 -0
  64. package/lib/background-jobs-tools.ts +202 -0
  65. package/lib/background-jobs.ts +253 -0
  66. package/lib/background-monitor.ts +154 -0
  67. package/lib/bounded-writer-admission.ts +83 -10
  68. package/lib/builtin-codemode-optout.ts +166 -0
  69. package/lib/card-content-policy.ts +85 -0
  70. package/lib/child-package-injection.ts +62 -0
  71. package/lib/codemode-renderer.ts +14 -4
  72. package/lib/command-palette-catalog.ts +3 -2
  73. package/lib/context-threshold.ts +26 -0
  74. package/lib/gentle-ai-binary.ts +109 -4
  75. package/lib/gentle-shell-bundled.ts +517 -0
  76. package/lib/gentle-shell-launcher.ts +74 -23
  77. package/lib/gentle-shell-startup-flow.ts +54 -0
  78. package/lib/gentle-shell-startup-update.ts +92 -0
  79. package/lib/gentle-shell-uninstall.ts +840 -0
  80. package/lib/gentle-shell-update-panel.ts +231 -0
  81. package/lib/herdr-activity.ts +183 -0
  82. package/lib/inprocess-reviewer.ts +3 -0
  83. package/lib/jobs-sidebar-state.ts +20 -0
  84. package/lib/jobs-view.ts +161 -0
  85. package/lib/model-price-ratio.ts +83 -0
  86. package/lib/nan-provider.ts +33 -11
  87. package/lib/native-review-cli.ts +194 -73
  88. package/lib/notification-audio-native.ts +162 -0
  89. package/lib/notification-audio-windows.ts +399 -0
  90. package/lib/notification-audio.ts +332 -0
  91. package/lib/notification-customize.ts +241 -0
  92. package/lib/notification-events.ts +113 -0
  93. package/lib/notification-policy.ts +148 -0
  94. package/lib/notification-pulse-client.ts +367 -0
  95. package/lib/notification-pulse-protocol.ts +305 -0
  96. package/lib/notification-pulse-stream.ts +213 -0
  97. package/lib/notification-pulse-worker.ts +66 -0
  98. package/lib/notification-scheduler.ts +173 -0
  99. package/lib/notification-service.ts +202 -0
  100. package/lib/notification-ui.ts +87 -0
  101. package/lib/odd-phase.ts +1 -1
  102. package/lib/orchestrator-alias.ts +20 -0
  103. package/lib/orchestrator-catalog.ts +79 -0
  104. package/lib/orchestrator-consultation.ts +61 -0
  105. package/lib/orchestrator-discovery.ts +49 -0
  106. package/lib/orchestrator-helper-consent.ts +122 -0
  107. package/lib/orchestrator-helper.ts +167 -0
  108. package/lib/orchestrator-message-card.ts +105 -0
  109. package/lib/orchestrator-presence.ts +115 -14
  110. package/lib/orchestrator-scope.ts +80 -0
  111. package/lib/orchestrator-state.ts +107 -0
  112. package/lib/orchestrator-tool-card.ts +280 -0
  113. package/lib/orchestrator-work-search.ts +218 -0
  114. package/lib/orchestrator-work.ts +79 -0
  115. package/lib/permission-mode-policy.ts +59 -0
  116. package/lib/review-candidate-view-owner.ts +8 -6
  117. package/lib/review-candidate-view.ts +3 -2
  118. package/lib/review-compact-contract.ts +2 -2
  119. package/lib/review-host-relay.ts +7 -2
  120. package/lib/review-integration-v2.ts +100 -22
  121. package/lib/review-publication-gate.ts +1 -1
  122. package/lib/review-risk-assessment.ts +77 -51
  123. package/lib/review-sidebar-state.ts +2 -1
  124. package/lib/review-transaction.ts +72 -3
  125. package/lib/runtime-metrics-children.ts +1 -1
  126. package/lib/runtime-metrics-native.ts +3 -2
  127. package/lib/selection-engine.ts +18 -6
  128. package/lib/session-change-capture.ts +5 -4
  129. package/lib/session-changes.ts +27 -22
  130. package/lib/session-profile-binding.ts +83 -0
  131. package/lib/session-profile-freeze.ts +266 -0
  132. package/lib/session-worktree-registry.ts +74 -8
  133. package/lib/shell-bar.ts +41 -11
  134. package/lib/shell-changes-view.ts +40 -13
  135. package/lib/shell-changes.ts +86 -71
  136. package/lib/shell-sidebar-layout.ts +5 -1
  137. package/lib/shell-todo.ts +62 -19
  138. package/lib/shell-usage.ts +4 -3
  139. package/lib/status-timing-diagnostics.ts +201 -0
  140. package/lib/telemetry-trigger.ts +3 -1
  141. package/lib/vim-editor-adapter.ts +7 -3
  142. package/lib/visual-customization-policy.ts +20 -9
  143. package/lib/visual-customize-view.ts +171 -20
  144. package/lib/writer-surfaces.ts +162 -0
  145. package/lib/yolo-session-policy.ts +198 -121
  146. package/package.json +1 -1
  147. package/runtime/child-package-injection.mjs +63 -0
  148. package/runtime/gentle-ai-binary.mjs +109 -4
  149. package/runtime/gentle-shell-bundled.mjs +518 -0
  150. package/runtime/gentle-shell-launcher.mjs +73 -22
  151. package/runtime/gentle-shell-startup-flow.mjs +55 -0
  152. package/runtime/gentle-shell-startup-update.mjs +93 -0
  153. package/runtime/gentle-shell-uninstall.mjs +841 -0
  154. package/runtime/gentle-shell-update-panel.mjs +232 -0
  155. package/runtime/native-review-cli.mjs +191 -70
  156. package/runtime/review-integration-v2.mjs +100 -22
  157. package/runtime/review-risk-assessment.mjs +77 -51
  158. package/runtime/status-timing-diagnostics.mjs +202 -0
  159. package/runtime/telemetry-trigger.mjs +3 -1
  160. package/scripts/bootstrap.cmd +255 -0
  161. package/scripts/bootstrap.sh +168 -0
  162. package/scripts/build-distribution.mjs +157 -0
  163. package/scripts/build-installer-bundles.mjs +136 -0
  164. package/scripts/build-runtime-modules.mjs +7 -0
  165. package/scripts/bundled-install.mjs +1308 -0
  166. package/scripts/bundled-wizard.mjs +399 -0
  167. package/scripts/check-types.mjs +4 -6
  168. package/scripts/gentle-ai-installer.mjs +79 -32
  169. package/scripts/install-gentle-ai.mjs +48 -1
  170. package/scripts/install-tui-mode-setting.mjs +10 -1
  171. package/scripts/install-wizard-preview.mjs +154 -0
  172. package/scripts/installer-downloads.mjs +648 -0
  173. package/scripts/installer-preflight.mjs +387 -0
  174. package/scripts/installer-probes.mjs +564 -0
  175. package/scripts/installer-runner.mjs +1102 -0
  176. package/scripts/installer-server.mjs +881 -0
  177. package/scripts/installer-windows-artifacts.json +15 -0
  178. package/scripts/installer-windows.mjs +752 -0
  179. package/scripts/main-channel.mjs +452 -0
  180. package/scripts/npm-pack-result.mjs +31 -0
  181. package/scripts/render-cache-performance-worker.mjs +205 -0
  182. package/scripts/render-cache-performance.mjs +115 -0
  183. package/scripts/run-test-suite.mjs +22 -8
  184. package/scripts/test-installer-acceptance.sh +161 -0
  185. package/scripts/test-packed-runner.mjs +23 -5
  186. package/scripts/types-baseline.json +2 -92
  187. package/scripts/verify-package-files.mjs +82 -18
  188. package/skills/gentle-ai/SKILL.md +12 -11
  189. package/tests/agent-home.test.ts +56 -3
  190. package/tests/agent-model-resolution.test.ts +113 -0
  191. package/tests/agent-profiles.test.ts +12 -0
  192. package/tests/agent-risk-escalation.test.ts +123 -0
  193. package/tests/agents-completion-delivery.test.ts +17 -0
  194. package/tests/agents-protocol.test.ts +57 -0
  195. package/tests/agents-queries.test.ts +9 -9
  196. package/tests/agents-runner-process.test.ts +31 -0
  197. package/tests/agents-runner.test.ts +89 -4
  198. package/tests/auto-mode-invariants.test.ts +258 -0
  199. package/tests/auto-mode-sdk.test.ts +57 -0
  200. package/tests/auto-mode.test.ts +49 -0
  201. package/tests/auto-permission-classifier.test.ts +283 -0
  202. package/tests/auto-permission-runtime.test.ts +196 -0
  203. package/tests/background-cache-warming.test.ts +2 -1
  204. package/tests/background-jobs.test.ts +227 -0
  205. package/tests/background-monitor.test.ts +195 -0
  206. package/tests/background-subagents-default-mode.test.ts +28 -5
  207. package/tests/bounded-stop-contract.test.ts +85 -0
  208. package/tests/bounded-writer-admission.test.ts +52 -1
  209. package/tests/bridge-wake-lifecycle.test.ts +129 -0
  210. package/tests/bridge-wake-rendering.test.ts +56 -0
  211. package/tests/build-distribution.test.ts +269 -0
  212. package/tests/builtin-codemode-optout.test.ts +242 -0
  213. package/tests/bundled-install.test.ts +1319 -0
  214. package/tests/bundled-wizard.test.ts +505 -0
  215. package/tests/card-content-policy.test.ts +68 -0
  216. package/tests/card-style-policy.test.ts +34 -2
  217. package/tests/child-codegraph-bootstrap.test.ts +74 -0
  218. package/tests/child-package-entrypoints.test.ts +65 -0
  219. package/tests/child-package-injection.test.ts +74 -0
  220. package/tests/child-safety.test.ts +12 -0
  221. package/tests/child-web-package.test.ts +224 -0
  222. package/tests/codegraph-tools.test.ts +35 -0
  223. package/tests/codemode-rendering.test.ts +107 -2
  224. package/tests/command-palette.test.ts +5 -5
  225. package/tests/context-threshold.test.ts +31 -0
  226. package/tests/delegate-for-reason-contract.test.ts +327 -0
  227. package/tests/delegated-key-learnings-contract.test.ts +3 -2
  228. package/tests/devbinary/native-review-parity.devtest.ts +1 -1
  229. package/tests/devbinary/pi-host-relay.devtest.ts +173 -3
  230. package/tests/engram-safety.test.ts +288 -0
  231. package/tests/generic-agent-tools.test.ts +16 -1
  232. package/tests/gentle-agents.test.ts +1722 -59
  233. package/tests/gentle-ai-binary-isolation.test.ts +135 -0
  234. package/tests/gentle-ai-binary.test.ts +19 -2
  235. package/tests/gentle-ai-child-guards.test.ts +202 -0
  236. package/tests/gentle-ai-dev-binary-surfacing.test.ts +125 -15
  237. package/tests/gentle-ai-installer.test.ts +548 -58
  238. package/tests/gentle-ai-prompt-model-routing.test.ts +123 -0
  239. package/tests/gentle-ai-renderer.test.ts +6 -6
  240. package/tests/gentle-ai.test.ts +999 -31
  241. package/tests/gentle-herdr-activity.test.ts +100 -0
  242. package/tests/gentle-notifications.test.ts +427 -0
  243. package/tests/gentle-shell-bin.test.ts +249 -5
  244. package/tests/gentle-shell-bundled.test.ts +1002 -0
  245. package/tests/gentle-shell-launcher.test.ts +234 -13
  246. package/tests/gentle-shell-startup-flow.test.ts +75 -0
  247. package/tests/gentle-shell-startup-update.test.ts +85 -0
  248. package/tests/gentle-shell-uninstall.test.ts +978 -0
  249. package/tests/gentle-shell-update-panel.test.ts +158 -0
  250. package/tests/gentle-shell.test.ts +541 -96
  251. package/tests/gentle-todo.test.ts +253 -2
  252. package/tests/herdr-activity.test.ts +243 -0
  253. package/tests/history-agent-home.test.ts +81 -0
  254. package/tests/history-child-guard.test.ts +70 -0
  255. package/tests/inprocess-reviewer.test.ts +20 -0
  256. package/tests/install-gentle-ai-failure.test.ts +69 -0
  257. package/tests/install-tui-mode-setting.test.ts +15 -0
  258. package/tests/install-wizard.test.ts +1223 -0
  259. package/tests/installer-bundles.test.ts +122 -0
  260. package/tests/installer-posix-bootstrap.test.ts +1201 -0
  261. package/tests/installer-preflight.test.ts +750 -0
  262. package/tests/installer-probes.test.ts +1106 -0
  263. package/tests/installer-runner.test.ts +2158 -0
  264. package/tests/installer-server.test.ts +1567 -0
  265. package/tests/installer-windows-bootstrap.test.ts +2410 -0
  266. package/tests/jobs-view.test.ts +160 -0
  267. package/tests/main-channel-upgrade.test.ts +389 -0
  268. package/tests/main-channel.test.ts +344 -0
  269. package/tests/maintainer/provider-relay.maintest.ts +13 -12
  270. package/tests/model-price-ratio.test.ts +116 -0
  271. package/tests/model-profiles-preservation.test.ts +153 -0
  272. package/tests/model-routing-package.test.ts +10 -0
  273. package/tests/nan-provider-runtime.test.ts +156 -0
  274. package/tests/nan-provider.test.ts +28 -18
  275. package/tests/native-binary-gate.test.ts +2 -0
  276. package/tests/native-review-capability-contract.test.ts +7 -1
  277. package/tests/native-review-cli.test.ts +236 -1
  278. package/tests/native-review-consent.test.ts +2 -2
  279. package/tests/native-review-parity-runtime.test.ts +1 -1
  280. package/tests/native-review-parity.test.ts +12 -48
  281. package/tests/native-risk-evidence-parity.test.ts +21 -0
  282. package/tests/no-self-pause-contract.test.ts +87 -0
  283. package/tests/notification-audio-native.test.ts +281 -0
  284. package/tests/notification-audio-windows.test.ts +581 -0
  285. package/tests/notification-audio.test.ts +548 -0
  286. package/tests/notification-customize.test.ts +655 -0
  287. package/tests/notification-events.test.ts +115 -0
  288. package/tests/notification-policy.test.ts +201 -0
  289. package/tests/notification-pulse-client.test.ts +356 -0
  290. package/tests/notification-pulse-protocol.test.ts +213 -0
  291. package/tests/notification-pulse-stream.test.ts +320 -0
  292. package/tests/notification-scheduler.test.ts +258 -0
  293. package/tests/notification-ui.test.ts +157 -0
  294. package/tests/npm-pack-result.test.ts +41 -0
  295. package/tests/odd-integration.test.ts +14 -5
  296. package/tests/odd-routing-canonical-ratchet.test.ts +53 -12
  297. package/tests/odd-routing-contract.test.ts +80 -23
  298. package/tests/orchestrator-budget.test.ts +29 -6
  299. package/tests/orchestrator-catalog.test.ts +146 -0
  300. package/tests/orchestrator-consultation-sdk.test.ts +614 -0
  301. package/tests/orchestrator-consultation.test.ts +111 -0
  302. package/tests/orchestrator-discovery.test.ts +241 -0
  303. package/tests/orchestrator-helper-consent.test.ts +171 -0
  304. package/tests/orchestrator-helper.test.ts +297 -0
  305. package/tests/orchestrator-message-card.test.ts +190 -0
  306. package/tests/orchestrator-presence.test.ts +23 -0
  307. package/tests/orchestrator-rdd-ownership.test.ts +6 -5
  308. package/tests/orchestrator-scope.test.ts +107 -0
  309. package/tests/orchestrator-state.test.ts +114 -0
  310. package/tests/orchestrator-status-publication-contract.test.ts +34 -0
  311. package/tests/orchestrator-tool-card.test.ts +398 -0
  312. package/tests/orchestrator-work-search.test.ts +318 -0
  313. package/tests/orchestrator-work.test.ts +147 -0
  314. package/tests/package-manifest.test.ts +101 -17
  315. package/tests/packed-runner-owned-path.test.ts +35 -1
  316. package/tests/parallel-reason-contract.test.ts +21 -0
  317. package/tests/parallel-writer-admission.test.ts +210 -0
  318. package/tests/permission-mode-policy.test.ts +194 -0
  319. package/tests/persona-single-channel.test.ts +4 -12
  320. package/tests/pi-pretty.test.ts +56 -0
  321. package/tests/provider-defect-handoff.test.ts +4 -3
  322. package/tests/quiet-tool-rendering.test.ts +160 -3
  323. package/tests/rdd-aware-verification-contract.test.ts +29 -41
  324. package/tests/render-cache-performance.test.ts +48 -0
  325. package/tests/review-agent-end-preflight.test.ts +62 -10
  326. package/tests/review-candidate-view.test.ts +101 -12
  327. package/tests/review-contract-prompt.test.ts +33 -4
  328. package/tests/review-controller-native-recovery.test.ts +327 -17
  329. package/tests/review-controller-native-routing.test.ts +255 -1
  330. package/tests/review-controller-workspace-root.test.ts +43 -2
  331. package/tests/review-controller.test.ts +2 -2
  332. package/tests/review-correction-lifecycle.test.ts +2 -1
  333. package/tests/review-gate.test.ts +7 -4
  334. package/tests/review-graph-schema.test.ts +2 -2
  335. package/tests/review-host-relay-routing.test.ts +5 -3
  336. package/tests/review-host-relay.test.ts +49 -2
  337. package/tests/review-integration-v2-forward.test.ts +21 -1
  338. package/tests/review-json-arguments.test.ts +167 -0
  339. package/tests/review-last-event-closure.test.ts +157 -8
  340. package/tests/review-ledger-contract.test.ts +5 -4
  341. package/tests/review-policy-judgment-day.test.ts +1 -1
  342. package/tests/review-policy-ordinary.test.ts +2 -2
  343. package/tests/review-relay-transport-agent.test.ts +66 -1
  344. package/tests/review-risk-assessment.test.ts +109 -33
  345. package/tests/review-session-standing-permission-controller.test.ts +16 -17
  346. package/tests/review-session-standing-permission-ipc.test.ts +6 -5
  347. package/tests/review-test-fixtures.ts +7 -1
  348. package/tests/review-transaction.test.ts +18 -1
  349. package/tests/run-test-suite.test.ts +83 -5
  350. package/tests/runtime-harness.mjs +42 -15
  351. package/tests/runtime-metrics-extension.test.ts +1 -1
  352. package/tests/runtime-metrics-native.test.ts +31 -1
  353. package/tests/selection-engine.test.ts +30 -0
  354. package/tests/session-change-capture.test.ts +10 -10
  355. package/tests/session-changes-shell.test.ts +242 -48
  356. package/tests/session-changes.test.ts +17 -24
  357. package/tests/session-profile-binding.test.ts +163 -0
  358. package/tests/session-profile-freeze.test.ts +381 -0
  359. package/tests/session-subject-routing-contract.test.ts +34 -0
  360. package/tests/session-worktree-registry.test.ts +57 -2
  361. package/tests/shell-bar.test.ts +40 -0
  362. package/tests/shell-changes-view.test.ts +85 -34
  363. package/tests/shell-changes.test.ts +61 -62
  364. package/tests/shell-render-cache-runtime.test.ts +69 -0
  365. package/tests/shell-render-cache.test.ts +129 -0
  366. package/tests/shell-sidebar-layout.test.ts +27 -2
  367. package/tests/shell-todo.test.ts +120 -2
  368. package/tests/shell-usage-view.test.ts +1 -1
  369. package/tests/shell-usage.test.ts +35 -0
  370. package/tests/short-check-routing-contract.test.ts +49 -0
  371. package/tests/skill-registry-watcher.test.ts +119 -0
  372. package/tests/skill-registry.test.ts +311 -5
  373. package/tests/startup-banner.test.ts +117 -3
  374. package/tests/startup-home-repo.test.ts +170 -0
  375. package/tests/status-timing-diagnostics.test.ts +283 -0
  376. package/tests/support/orchestrator-modules.ts +19 -0
  377. package/tests/task-size-routing-contract.test.ts +241 -0
  378. package/tests/telemetry-trigger.test.ts +27 -1
  379. package/tests/test-strength-contract.test.ts +124 -0
  380. package/tests/verify-agent-contract.test.ts +90 -0
  381. package/tests/verify-first-launch-contract.test.ts +139 -0
  382. package/tests/verify-package-files.test.ts +56 -0
  383. package/tests/vim-editor-adapter.test.ts +7 -7
  384. package/tests/visual-customization-policy.test.ts +32 -3
  385. package/tests/visual-customize-view.test.ts +288 -10
  386. package/tests/writer-edit-surface-scope.test.ts +59 -2
  387. package/tests/writer-surfaces.test.ts +199 -0
  388. package/tests/yolo-customize.test.ts +18 -3
  389. package/tests/yolo-mode-runtime.test.ts +37 -10
  390. package/tests/yolo-mode.test.ts +32 -4
  391. package/tests/yolo-session-policy.test.ts +1 -1
  392. /package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/bundle/README.md +0 -0
  393. /package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/bundle/schemas/lens.schema.json +0 -0
  394. /package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/bundle/schemas/refuter.schema.json +0 -0
  395. /package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/bundle/schemas/targeted-validator.schema.json +0 -0
  396. /package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/bundle/vectors/lens.json +0 -0
  397. /package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/bundle/vectors/refuter.json +0 -0
  398. /package/contracts/review-provider-contract-mirror/{v1.2.0 → v1.3.0}/bundle/vectors/targeted-validator.json +0 -0
@@ -12,20 +12,24 @@ import { SessionChanges, type SessionChangeEvidence } from "../lib/session-chang
12
12
  import test, { after, afterEach, before, mock } from "node:test";
13
13
  import type { TestContext } from "node:test";
14
14
  import { generateUnifiedPatch, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
15
+ import { createAssistantMessageEventStream, type AssistantMessage } from "@earendil-works/pi-ai";
15
16
  import { visibleWidth, type TUI, type TuiMouseEvent } from "@earendil-works/pi-tui";
16
17
  import { sidebarState } from "../lib/shell-sidebar.ts";
18
+ import { CHILD_PACKAGE_INJECTION_ENV, encodeChildPackageInjection } from "../lib/child-package-injection.ts";
17
19
  import gentleAgents, { agentRuntimePaths, agentsCollapseKey, agentsEnabled, agentsStopKey, agentsViewKey, agentResultPreview, answerThroughUi, childContextExtensionPaths, completionText, createDefaultSessionTransport, legacySubagentsInstalled, PARENT_WAKE_GRACE_MS, type AgentsDeps, type SessionTransportFactory } from "../extensions/gentle-agents.ts";
18
20
  import { ActiveSessionClient, ActiveSessionListener, SessionPresenceRegistry } from "../lib/agents-session-transport.ts";
19
21
  import { WindowsActiveSessionClient, WindowsActiveSessionListener } from "../lib/windows-session-transport.ts";
20
22
  import { historyDir, loadHistory, saveTask } from "../lib/agents-history.ts";
21
23
  import { STALE_COMPLETION_MS } from "../lib/agents-completion-delivery.ts";
22
- import { applyTaskEvent, emptyThread, TASK_EVENT, TASK_STATUS, TaskStore, type TaskRecord } from "../lib/agents-protocol.ts";
24
+ import { applyTaskEvent, emptyThread, MISSING_TOOLS_NOTE_PREFIX, TASK_EVENT, TASK_STATUS, TaskStore, type TaskRecord } from "../lib/agents-protocol.ts";
23
25
  import { NativePointerScope } from "../lib/native-pointer-region.ts";
24
- import { PresenceCursor, PresencePublisher, listPresence, readActivity } from "../lib/orchestrator-presence.ts";
26
+ import { PresenceCursor, PresencePublisher, listPresence, readActivity, readDiscovery } from "../lib/orchestrator-presence.ts";
27
+ import { OrchestratorScopeCache } from "../lib/orchestrator-scope.ts";
25
28
  import { stripAnsi } from "../lib/terminal-theme.ts";
26
29
  import { fakeChild, type FakeChild } from "./agents-fake-child.ts";
27
- import { AgentRunner } from "../lib/agents-runner.ts";
30
+ import { AgentRunner, REQUESTED_TOOLS_ENV } from "../lib/agents-runner.ts";
28
31
  import { bindSessionRepositoryPreparation } from "../lib/bounded-writer-admission.ts";
32
+ import { bindSessionProfile, resetSessionProfileBindingsForTesting } from "../lib/session-profile-binding.ts";
29
33
  import { CHILD_METRICS_EVENT } from "../lib/runtime-metrics-children.ts";
30
34
  import { CARD_STYLE, cardStyle, setCardStyle } from "../lib/shell-card.ts";
31
35
  // The card style defaults to float; these assertions pin the outlined (neon)
@@ -48,6 +52,10 @@ interface Registered {
48
52
  }
49
53
 
50
54
  const plainTheme = { fg: (_color: string, text: string) => text };
55
+ // Session shutdown persists finished subagent history asynchronously, so a
56
+ // late write can race a teardown removal; Node retries ENOTEMPTY/EBUSY here
57
+ // instead of failing the test (macOS showed it, #1840).
58
+ const TEST_DIR_REMOVAL = { recursive: true, force: true, maxRetries: 5, retryDelay: 50 } as const;
51
59
  const fakeTui = { requestRender() {} };
52
60
  const inertSessionTransport: SessionTransportFactory = {
53
61
  createRegistry: async () => ({ list: async () => [], listActivations: async () => [] }),
@@ -98,7 +106,7 @@ after(async () => {
98
106
  finally {
99
107
  if (previousGentlePiConfigHome === undefined) delete process.env.GENTLE_PI_CONFIG_HOME;
100
108
  else process.env.GENTLE_PI_CONFIG_HOME = previousGentlePiConfigHome;
101
- rmSync(root, { recursive: true, force: true });
109
+ rmSync(root, TEST_DIR_REMOVAL);
102
110
  }
103
111
  });
104
112
  const home = join(root, "home");
@@ -110,19 +118,22 @@ mkdirSync(nonGitCwd, { recursive: true });
110
118
  writeFileSync(join(home, ".pi", "agent", "agents", "explore.md"), "---\ndescription: maps things\nmodel: openai-codex/gpt-5.6-terra\nthinking: high\ntools: [read, grep]\n---\nYou map things.");
111
119
  writeFileSync(join(home, ".pi", "agent", "subagents.json"), JSON.stringify({ max_concurrency: 2, model_profiles: { explore: { effort: "low" } } }));
112
120
 
113
- function fakePi() {
121
+ // Existing prompt-lifecycle regressions exercise the bridge route by default.
122
+ function fakePi(initialProvider: string = "claude-bridge") {
123
+ const transformers: Array<Parameters<ExtensionAPI["registerMarkdownTransformer"]>[0]> = [];
114
124
  const handlers = new Map<string, Handler[]>();
115
125
  const tools = new Map<string, Registered>();
116
126
  const shortcuts = new Map<string, { description: string; handler(ctx: ExtensionContext): Promise<void> }>();
117
127
  const commands = new Map<string, { handler(args: string, ctx: ExtensionContext): Promise<void> }>();
118
128
  const sent: Array<{ message: Record<string, unknown>; options: Record<string, unknown> }> = [];
119
- // Idle wake-ups go through pi.sendUserMessage; `delivery` records the
120
- // interleaving of custom messages and wake-ups so ordering stays provable.
129
+ // `delivery` records custom messages and user wakes in dispatch order.
121
130
  const userMessages: Array<{ content: unknown; options: Record<string, unknown> | undefined }> = [];
122
131
  const delivery: string[] = [];
123
132
  // A live idle flag shared by every context fired through this host, like
124
133
  // Pi's ctx.isIdle(): busy from agent_start until agent_settled. Tests can
125
134
  // force it to simulate compaction or other non-run busy states.
135
+ let selectedProvider: string | undefined = initialProvider;
136
+ const setProvider = (provider: string | undefined) => { selectedProvider = provider; };
126
137
  let parentIdle = true;
127
138
  const setIdle = (idle: boolean) => { parentIdle = idle; };
128
139
  const renderers = new Map<string, (message: unknown, options: { expanded: boolean }, theme: unknown) => { render(width: number): string[] }>();
@@ -132,6 +143,7 @@ function fakePi() {
132
143
  const listeners = new Map<string, Set<(data: unknown) => void>>();
133
144
  const pi = {
134
145
  appendEntry: (customType: string, data: unknown) => entries.push({ type: "custom", customType, data }),
146
+ registerMarkdownTransformer: (transformer: Parameters<ExtensionAPI["registerMarkdownTransformer"]>[0]) => transformers.push(transformer),
135
147
  events: {
136
148
  emit: (name: string, data: unknown) => { events.push({ name, data }); for (const listener of listeners.get(name) ?? []) listener(data); },
137
149
  on: (name: string, listener: (data: unknown) => void) => {
@@ -157,6 +169,10 @@ function fakePi() {
157
169
  const fire = async (event: string, ctx: ExtensionContext, payload: unknown = {}) => {
158
170
  const results: unknown[] = [];
159
171
  if (!("isIdle" in ctx)) Object.assign(ctx, { isIdle: () => parentIdle });
172
+ if (!("model" in ctx)) Object.defineProperty(ctx, "model", {
173
+ configurable: true,
174
+ get: () => selectedProvider === undefined ? undefined : { provider: selectedProvider },
175
+ });
160
176
  if (event === "agent_start") parentIdle = false;
161
177
  else if (event === "agent_settled") parentIdle = true;
162
178
  try {
@@ -172,7 +188,7 @@ function fakePi() {
172
188
  }
173
189
  }
174
190
  };
175
- return { pi, tools, shortcuts, commands, fire, sent, userMessages, delivery, setIdle, renderers, entryRenderers, entries, events, listeners };
191
+ return { pi, tools, shortcuts, commands, fire, sent, userMessages, delivery, setIdle, setProvider, renderers, entryRenderers, entries, events, listeners, transformers };
176
192
  }
177
193
 
178
194
  function fakeContext(tui: { requestRender(): void } = fakeTui, confirmResult: (title: string, message: string) => Promise<boolean> = async () => true, inputResult: (title: string, placeholder: string | undefined) => Promise<string | undefined> = async () => undefined, overlayTui: { terminal: { rows: number }; requestRender(): void } = { terminal: { rows: 30 }, requestRender() {} }, selectResult: (title: string, options: string[]) => Promise<string | undefined> = async (_title, options) => options[0]) {
@@ -185,7 +201,7 @@ function fakeContext(tui: { requestRender(): void } = fakeTui, confirmResult: (t
185
201
  cwd,
186
202
  hasUI: true,
187
203
  mode: "tui",
188
- sessionManager: { getSessionId: () => "s1", getCwd: () => cwd, getEntries: () => [] },
204
+ sessionManager: { getSessionId: () => "s1", getCwd: () => cwd, getEntries: () => [], getBranch: () => [] },
189
205
  ui: {
190
206
  notify: (message: string) => dialogs.push(`notify:${message}`),
191
207
  custom: (factory: (tui: unknown, theme: unknown, keybindings: unknown, done: (value: unknown) => void) => Overlay, options: unknown) =>
@@ -224,6 +240,68 @@ function fakeContext(tui: { requestRender(): void } = fakeTui, confirmResult: (t
224
240
  return { ctx, widget, dialogs, overlays, customCompletions, customOptions };
225
241
  }
226
242
 
243
+ for (const scenario of ["background", "task", "append-failure", "overflow", "bytes", "replacement", "task-replacement", "unsafe-id", "no-transport"] as const) {
244
+ test(`explicit run work publication: ${scenario}`, async t => {
245
+ const h = fakePi(), runtime = deps(), { ctx } = fakeContext();
246
+ gentleAgents(h.pi, {}, runtime.deps);
247
+ await h.fire("session_start", ctx);
248
+ const initial = { objective: "Keep objective", work: { area: "Owner", tasks: { historical: { area: "Old" } } as Record<string, { area: string }> } };
249
+ if (scenario === "overflow") for (let i = 0; i < 7; i++) initial.work.tasks[`old-${i}`] = { area: "Old" };
250
+ if (scenario === "bytes") initial.objective = "x".repeat(1980);
251
+ await h.tools.get("orchestrator_session_id")!.execute("publish", { state: initial }, undefined, undefined, ctx);
252
+ const before = h.entries.length;
253
+ if (scenario === "append-failure") t.mock.method(h.pi, "appendEntry", () => { throw new Error("private credential detail"); });
254
+ let allocated: TaskRecord;
255
+ const run = t.mock.method(AgentRunner.prototype, "run", request => {
256
+ assert.equal(Object.hasOwn(request, "work"), false);
257
+ assert.equal(request.prompt, "Map");
258
+ allocated = { id: scenario === "unsafe-id" ? "constructor" : "actual-allocated-id", agent: "explore", label: "Map", mode: request.mode,
259
+ status: TASK_STATUS.COMPLETED, cwd, prompt: request.prompt, parentSessionId: request.parentSessionId,
260
+ createdAt: 1, startedAt: 1, endedAt: 2, model: "fixture", thinking: undefined,
261
+ sessionPath: null, error: null, result: "Done", lastStep: "Done", lastActivityAt: 2,
262
+ turns: 1, toolCalls: 0, tokens: 0, cost: 0 };
263
+ if (scenario === "replacement") ctx.sessionManager = { ...ctx.sessionManager };
264
+ return allocated;
265
+ });
266
+ t.mock.method(AgentRunner.prototype, "waitForQuery", async () => undefined);
267
+ t.mock.method(AgentRunner.prototype, "waitFor", async () => {
268
+ if (scenario === "task-replacement") ctx.sessionManager = { ...ctx.sessionManager };
269
+ return allocated;
270
+ });
271
+ if (scenario === "no-transport") await h.fire("session_shutdown", ctx);
272
+ const result = await h.tools.get("subagent_run")!.execute("run", { agent: "explore", task: "Map",
273
+ mode: scenario === "task" || scenario === "task-replacement" ? "task" : "background", work: { area: "Auth" } }, undefined, undefined, ctx);
274
+ assert.equal(run.mock.callCount(), 1);
275
+ assert.equal((result.details.gentleAgents as { taskId: string }).taskId, allocated!.id);
276
+ assert.equal(Object.hasOwn(allocated!, "work"), false);
277
+ const success = scenario === "background" || scenario === "task";
278
+ assert.equal((result.details.workPublication as { status: string }).status, success ? "recorded" : "unavailable");
279
+ assert.equal(h.entries.length, before + (success || scenario === "task-replacement" ? 1 : 0));
280
+ assert.doesNotMatch(result.content[0].text, /private credential/);
281
+ if (success) {
282
+ const state = (h.entries.at(-1)!.data as { state: typeof initial }).state;
283
+ assert.equal(state.objective, "Keep objective");
284
+ assert.deepEqual(state.work.tasks, { historical: { area: "Old" }, "actual-allocated-id": { area: "Auth" } });
285
+ const unclassified = await h.tools.get("subagent_run")!.execute("plain", { agent: "explore", task: "Map", mode: "background" }, undefined, undefined, ctx);
286
+ assert.equal(unclassified.details.workPublication, undefined);
287
+ assert.equal(h.entries.length, before + 1);
288
+ }
289
+ });
290
+ }
291
+
292
+ test("invalid run work rejects before foreign consent or allocation", async t => {
293
+ const h = fakePi(), runtime = deps(), { ctx, dialogs } = fakeContext();
294
+ gentleAgents(h.pi, {}, runtime.deps);
295
+ await h.fire("session_start", ctx);
296
+ const run = t.mock.method(AgentRunner.prototype, "run", () => { throw new Error("allocation reached"); });
297
+ for (const work of [{}, { tasks: { guessed: { area: "Auth" } } }, { area: "bad\n" }]) {
298
+ await assert.rejects(h.tools.get("subagent_run")!.execute("invalid", { agent: "explore", task: "Map",
299
+ repository_root: "/foreign", work }, undefined, undefined, ctx), /invalid-published-state/);
300
+ }
301
+ assert.equal(run.mock.callCount(), 0);
302
+ assert.deepEqual(dialogs, []);
303
+ });
304
+
227
305
  // Records deps.schedule calls so a test fires exactly the timers it means to;
228
306
  // unrelated runner timers stay pending.
229
307
  function recordTimers(target: Partial<AgentsDeps>) {
@@ -236,6 +314,14 @@ function recordTimers(target: Partial<AgentsDeps>) {
236
314
  const due = (ms: number) => pending.filter((timer) => timer.ms === ms && !timer.cancelled);
237
315
  return {
238
316
  pending: (ms: number) => due(ms).length,
317
+ // Capture a known newly armed timer before other same-duration timers
318
+ // (for example child query expiry) are added.
319
+ takeLast: (ms: number) => {
320
+ const timer = due(ms).at(-1);
321
+ assert.ok(timer, `expected a pending ${ms}ms timer`);
322
+ pending.splice(pending.indexOf(timer), 1);
323
+ return () => { if (!timer.cancelled) timer.fn(); };
324
+ },
239
325
  run: (ms: number) => {
240
326
  const timers = due(ms);
241
327
  for (const timer of timers) {
@@ -341,15 +427,17 @@ test("cache warming follows actual Gentle Agents ownership and completion lifecy
341
427
  await decide(undefined);
342
428
  });
343
429
 
344
- const PRINT_BACKGROUND_ERROR = "Background subagents are unavailable in print mode: pi -p exits before a parent session can receive results. Use task mode, RPC mode, or interactive Pi.";
430
+ // `pi -p` and `pi --mode json` share pi's one-shot runner: it disposes the
431
+ // runtime once the prompt returns, so neither can receive a background result.
432
+ const SINGLE_SHOT_BACKGROUND_ERROR = "Background subagents are unavailable in single-shot modes: pi -p and pi --mode json exit before a parent session can receive results. Use task mode, RPC mode, or interactive Pi.";
345
433
 
346
- for (const continuation of [false, true]) {
347
- test(`print mode rejects background ${continuation ? "continuation" : "launch"} before allocating a task`, async (t) => {
434
+ for (const hostMode of ["print", "json"] as const) for (const continuation of [false, true]) {
435
+ test(`${hostMode} mode rejects background ${continuation ? "continuation" : "launch"} before allocating a task`, async (t) => {
348
436
  const h = fakePi();
349
437
  const runtime = deps();
350
438
  gentleAgents(h.pi, {}, runtime.deps);
351
439
  const { ctx } = fakeContext();
352
- Object.assign(ctx, { mode: "print", hasUI: false });
440
+ Object.assign(ctx, { mode: hostMode, hasUI: false });
353
441
  await h.fire("session_start", ctx);
354
442
  let taskId: string | undefined;
355
443
  if (continuation) {
@@ -368,7 +456,7 @@ for (const continuation of [false, true]) {
368
456
  const tool = h.tools.get(continuation ? "subagent_continue" : "subagent_run")!;
369
457
  await assert.rejects(tool.execute("denied", continuation
370
458
  ? { task_id: taskId, prompt: "Follow up", mode: "background" }
371
- : { agent: "explore", task: "Map", mode: "background" }, undefined, undefined, ctx), { message: PRINT_BACKGROUND_ERROR });
459
+ : { agent: "explore", task: "Map", mode: "background" }, undefined, undefined, ctx), { message: SINGLE_SHOT_BACKGROUND_ERROR });
372
460
  await tick();
373
461
  assert.equal(run.mock.callCount(), 0, "rejection must precede runner task ID allocation");
374
462
  assert.equal(runtime.spawned.length, spawnedBefore, "no child spawned");
@@ -378,8 +466,9 @@ for (const continuation of [false, true]) {
378
466
  });
379
467
  }
380
468
 
381
- for (const mode of ["print", "tui", "rpc"] as const) {
382
- test(`${mode} preserves ${mode === "print" ? "bounded task" : "background"} execution`, async () => {
469
+ for (const mode of ["print", "json", "tui", "rpc"] as const) {
470
+ const singleShot = mode === "print" || mode === "json";
471
+ test(`${mode} preserves ${singleShot ? "bounded task" : "background"} execution`, async () => {
383
472
  const h = fakePi();
384
473
  const runtime = deps();
385
474
  gentleAgents(h.pi, {}, runtime.deps);
@@ -387,17 +476,17 @@ for (const mode of ["print", "tui", "rpc"] as const) {
387
476
  Object.assign(ctx, { mode, hasUI: mode === "tui" });
388
477
  await h.fire("session_start", ctx);
389
478
  let resolved = false;
390
- const pending = h.tools.get("subagent_run")!.execute("control", { agent: "explore", task: "Map", mode: mode === "print" ? "task" : "background" }, undefined, undefined, ctx).then(result => { resolved = true; return result; });
479
+ const pending = h.tools.get("subagent_run")!.execute("control", { agent: "explore", task: "Map", mode: singleShot ? "task" : "background" }, undefined, undefined, ctx).then(result => { resolved = true; return result; });
391
480
  await tick();
392
481
  assert.equal(runtime.spawned.length, 1);
393
- assert.equal(resolved, mode !== "print", "only task mode waits for completion");
482
+ assert.equal(resolved, !singleShot, "only task mode waits for completion");
394
483
  runtime.children[0].emit({ type: "agent_end", messages: [{ role: "assistant", content: [{ type: "text", text: "mapped" }] }] });
395
484
  runtime.children[0].emit({ type: "agent_settled" });
396
485
  const result = await pending;
397
- if (mode === "print") assert.match(result.content[0].text, /mapped/);
398
486
  const taskId = (result.details.gentleAgents as { taskId: string }).taskId;
399
487
  assert.ok(taskId);
400
- if (mode !== "print") {
488
+ if (singleShot) assert.equal(result.content[0].text, `Subagent explore (task ${taskId}, "Map") finished.\n\nmapped`, "the task result names its real id for subagent_continue");
489
+ if (!singleShot) {
401
490
  await tick();
402
491
  assert.match((await h.tools.get("subagent_status")!.execute("status", { task_id: taskId }, undefined, undefined, ctx)).content[0].text, /completed · background/);
403
492
  assert.equal(h.sent.length, 1, "settlement delivers exactly one completion");
@@ -652,7 +741,7 @@ test("first handoff failure keeps ordinary completion, later failure retains yie
652
741
  firstHarness.children[0].message({ id: "q1", kind: "query", message: "q" });
653
742
  firstHarness.children[0].emit({ type: "agent_end", messages: [{ role: "assistant", content: [{ type: "text", text: "ordinary" }], stopReason: "stop" }] });
654
743
  firstHarness.children[0].emit({ type: "agent_settled" });
655
- assert.equal((await ordinary).content[0].text, "ordinary");
744
+ assert.match((await ordinary).content[0].text, /^Subagent explore \(task [^,]+, "fail handoff"\) finished\.\n\nordinary$/);
656
745
 
657
746
  const second = fakePi();
658
747
  const secondHarness = deps();
@@ -1230,10 +1319,16 @@ function liveProfile(name: string): string {
1230
1319
  return profile;
1231
1320
  }
1232
1321
 
1233
- function liveInstance(t: test.TestContext, profile: string, sessionId: string) {
1322
+ function liveInstance(t: test.TestContext, profile: string, sessionId: string, metadata = false) {
1234
1323
  const h = fakePi();
1235
1324
  const runtime = deps();
1236
1325
  const context = fakeContext();
1326
+ if (metadata) {
1327
+ runtime.deps.sessionTransport = {
1328
+ ...inertSessionTransport,
1329
+ createListener: registry => ({ registry, record: { version: 1, sessionId, endpoint: `/fixture/${sessionId}`, createdAt: 1 }, start: async () => {}, close: async () => {} }),
1330
+ };
1331
+ }
1237
1332
  Object.assign(context.ctx.sessionManager, {
1238
1333
  getSessionId: () => sessionId,
1239
1334
  getSessionName: () => sessionId,
@@ -1262,8 +1357,8 @@ async function liveOverlay(instance: ReturnType<typeof liveInstance>) {
1262
1357
 
1263
1358
  test("live-only extension instances discover same-profile peers across cwd boundaries without importing their tasks", async (t) => {
1264
1359
  const profile = liveProfile("live-peer-profile");
1265
- const local = liveInstance(t, profile, "local-live");
1266
- const peer = liveInstance(t, profile, "peer-live");
1360
+ const local = liveInstance(t, profile, "local-live", true);
1361
+ const peer = liveInstance(t, profile, "peer-live", true);
1267
1362
  assert.equal(listPresence(profile).entries.length, 0, "factory construction starts no presence resources");
1268
1363
  await local.fire("session_start", local.ctx, { reason: "startup" });
1269
1364
  await peer.fire("session_start", peer.ctx, { reason: "startup" });
@@ -1278,6 +1373,10 @@ test("live-only extension instances discover same-profile peers across cwd bound
1278
1373
  };
1279
1374
  await run(local, "local");
1280
1375
  const peerId = await run(peer, "peer");
1376
+ await eventually(() => listPresence(profile).entries.some(header => readDiscovery(profile, header)?.tasks.some(task => task.id === peerId)), "admitted runtime-owned tasks publish without subsequent child events");
1377
+ const scope = listPresence(profile).entries.map(header => readDiscovery(profile, header)?.scope).find(scope => scope?.tasks.some(task => task.id === peerId));
1378
+ assert.equal(scope?.tasks.find(task => task.id === peerId)?.repository.root, peer.ctx.sessionManager.getCwd());
1379
+ assert.equal(scope?.host.cloneHash, scope?.tasks.find(task => task.id === peerId)?.repository.cloneHash);
1281
1380
  await tick();
1282
1381
  peer.children[0].emit({ type: "message_update", assistantMessageEvent: { type: "text_delta", delta: "peer streamed text" } });
1283
1382
  await eventually(() => listPresence(profile).entries.some((header) => readActivity(profile, header).activity?.tasks.some((row) => row.summary.id === peerId && row.thread.items.some((item) => item.text === "peer streamed text"))), "task deltas, not just status changes, must publish peer activity");
@@ -1482,6 +1581,68 @@ test("live-only directory traverses presence overflow, excludes expired and othe
1482
1581
  await panel.opened;
1483
1582
  });
1484
1583
 
1584
+ // #1690: Pi drops unknown --tools names without a diagnostic, so the child
1585
+ // compares the runner's requested list with its own tools at the first
1586
+ // before_agent_start, after every extension's session_start has registered.
1587
+ function missingToolsChild(env: NodeJS.ProcessEnv, toolNames: string[] | (() => string[])) {
1588
+ const child = fakePi();
1589
+ Object.assign(child.pi, { getAllTools: () => (typeof toolNames === "function" ? toolNames() : toolNames).map((name) => ({ name })) });
1590
+ gentleAgents(child.pi, { GENTLE_PI_AGENTS_CHILD: "1", ...env });
1591
+ const notes: Array<{ message: string; type: unknown }> = [];
1592
+ const ctx = { hasUI: true, ui: { notify: (message: string, type?: unknown) => notes.push({ message, type }) } } as unknown as ExtensionContext;
1593
+ return {
1594
+ start: () => child.fire("session_start", ctx, { type: "session_start", reason: "startup" }),
1595
+ prompt: () => child.fire("before_agent_start", ctx, { type: "before_agent_start", prompt: "go", systemPrompt: "base", systemPromptOptions: {} }),
1596
+ notes,
1597
+ };
1598
+ }
1599
+
1600
+ test("a child warns once about requested tools it does not have", async () => {
1601
+ const child = missingToolsChild({ [REQUESTED_TOOLS_ENV]: "read,gentle_review_scope,grep,codegraph,subagent_parent_message" }, ["read", "grep", "subagent_parent_message"]);
1602
+ await child.start();
1603
+ assert.deepEqual(child.notes, [], "session_start runs before later extensions register their tools");
1604
+ assert.deepEqual(await child.prompt(), [undefined], "the check never alters the prompt");
1605
+ assert.deepEqual(child.notes, [{ message: `${MISSING_TOOLS_NOTE_PREFIX} gentle_review_scope, codegraph`, type: "warning" }]);
1606
+ await child.start();
1607
+ assert.deepEqual(await child.prompt(), [undefined]);
1608
+ assert.equal(child.notes.length, 1, "later prompts and session replacements do not repeat the warning");
1609
+ });
1610
+
1611
+ test("a child does not report a tool that a later extension registers in its own session_start", async () => {
1612
+ const tools = ["read", "grep"];
1613
+ const child = missingToolsChild({ [REQUESTED_TOOLS_ENV]: "read,late_tool" }, () => tools);
1614
+ await child.start();
1615
+ // Pi runs session_start handlers in load order; an extension loaded after
1616
+ // gentle-agents registers late_tool only now.
1617
+ tools.push("late_tool");
1618
+ const results = await child.prompt();
1619
+ assert.deepEqual(child.notes, []);
1620
+ assert.deepEqual(results, [undefined]);
1621
+ });
1622
+
1623
+ test("a child stays quiet when every checkable requested tool exists or nothing was requested", async () => {
1624
+ for (const [label, env] of [
1625
+ ["all present", { [REQUESTED_TOOLS_ENV]: "read,grep,subagent_parent_message" }],
1626
+ ["MCP names register late", { [REQUESTED_TOOLS_ENV]: "read,mcp__github__search,mcp__x" }],
1627
+ ["frontmatter wildcard entries are not tool names", { [REQUESTED_TOOLS_ENV]: "read,\"*\": false,*, ," }],
1628
+ ["no requested list", {}],
1629
+ ["empty requested list", { [REQUESTED_TOOLS_ENV]: "" }],
1630
+ ] as const) {
1631
+ const child = missingToolsChild(env, ["read", "grep", "subagent_parent_message"]);
1632
+ await child.start();
1633
+ const results = await child.prompt();
1634
+ assert.ok(results.every((result) => result === undefined), label);
1635
+ assert.deepEqual(child.notes, [], label);
1636
+ }
1637
+ });
1638
+
1639
+ test("the missing-tools check never throws into before_agent_start", async () => {
1640
+ const child = missingToolsChild({ [REQUESTED_TOOLS_ENV]: "read,codegraph" }, () => { throw new Error("tool registry unavailable"); });
1641
+ await child.start();
1642
+ assert.deepEqual(await child.prompt(), [undefined]);
1643
+ assert.deepEqual(child.notes, []);
1644
+ });
1645
+
1485
1646
  test("retired managed SDD child envelopes deny all tools without registering a delegation host", () => {
1486
1647
  for (const env of [{ GENTLE_PI_RESEARCH_TOOLS: '["read"]' }, { GENTLE_PI_RESEARCH_SELECTION: '{}' }, { GENTLE_PI_RESEARCH_ARTIFACT: '{}' }, { GENTLE_PI_SDD_REMEDIATION_PLAN: '{}' }]) {
1487
1648
  const hooks = new Map<string, (event: { toolName: string }) => { block: boolean }>();
@@ -1678,9 +1839,9 @@ test("C1 investigation: the relay mechanism is correct when every guard input is
1678
1839
  await h.fire("session_shutdown", ctx);
1679
1840
  await tick();
1680
1841
  } finally {
1681
- rmSync(repoRoot, { recursive: true, force: true });
1682
- rmSync(gitHome, { recursive: true, force: true });
1683
- rmSync(gitHooksDir, { recursive: true, force: true });
1842
+ rmSync(repoRoot, TEST_DIR_REMOVAL);
1843
+ rmSync(gitHome, TEST_DIR_REMOVAL);
1844
+ rmSync(gitHooksDir, TEST_DIR_REMOVAL);
1684
1845
  }
1685
1846
  });
1686
1847
 
@@ -2053,7 +2214,7 @@ test("default Node spawn adapter distinguishes IPC-only and permission-capable c
2053
2214
  mkdirSync(gitTemplate);
2054
2215
  execFileSync("git", ["init", "--quiet", `--template=${gitTemplate}`, canonicalGitCwd]);
2055
2216
  } catch (error) {
2056
- rmSync(canonicalGitFixture, { recursive: true, force: true });
2217
+ rmSync(canonicalGitFixture, TEST_DIR_REMOVAL);
2057
2218
  throw error;
2058
2219
  }
2059
2220
  childProcess.spawn = ((command: string, args: readonly string[], options: Record<string, unknown>) => {
@@ -2097,7 +2258,7 @@ test("default Node spawn adapter distinguishes IPC-only and permission-capable c
2097
2258
  assert.equal(captured[index]?.command, "/fixture/pi");
2098
2259
  assert.deepEqual(captured[index]?.args, args);
2099
2260
  assert.equal(captured[index]?.options.cwd, permissionChannel ? canonicalGitCwd : nonGitCwd);
2100
- assert.deepEqual(captured[index]?.options.env, { PATH: "/bin", FIXTURE: fixture, GENTLE_PI_AGENTS_CHILD: "1", GENTLE_PI_AGENTS_OWNED_IPC: ownedIpc, ...(permissionChannel ? { GENTLE_PI_AGENTS_PARENT_PERMISSION_FD: "3" } : {}) });
2261
+ assert.deepEqual(captured[index]?.options.env, { PATH: "/bin", FIXTURE: fixture, GENTLE_PI_AGENTS_CHILD: "1", GENTLE_PI_AGENTS_OWNED_IPC: ownedIpc, ...(permissionChannel ? { GENTLE_PI_AGENTS_PARENT_PERMISSION_FD: "3" } : {}), [REQUESTED_TOOLS_ENV]: "read,grep,subagent_parent_message" });
2101
2262
  assert.equal(captured[index]?.options.shell, undefined, "the adapter does not invoke a shell");
2102
2263
  assert.equal(captured[index]?.options.windowsHide, true, "the adapter always hides a Windows console");
2103
2264
  assert.equal(captured[index]?.options.detached, process.platform !== "win32", "the adapter forwards the runner's platform selection");
@@ -2110,7 +2271,7 @@ test("default Node spawn adapter distinguishes IPC-only and permission-capable c
2110
2271
  try {
2111
2272
  await shutdownAndRestoreNativeSpawn(childProcess, originalSpawn, () => Promise.all(shutdown.map((close) => close())));
2112
2273
  } finally {
2113
- rmSync(canonicalGitFixture, { recursive: true, force: true });
2274
+ rmSync(canonicalGitFixture, TEST_DIR_REMOVAL);
2114
2275
  }
2115
2276
  }
2116
2277
  });
@@ -2273,7 +2434,7 @@ test("foreign clone tool requires consent before queueing and never enters paren
2273
2434
  await tick();
2274
2435
  assert.equal(runtime.children.length, 3, "stale queued foreign task must fail before OS spawn");
2275
2436
  await h.fire("session_shutdown", successor);
2276
- } finally { rmSync(fixture, { recursive: true, force: true }); }
2437
+ } finally { rmSync(fixture, TEST_DIR_REMOVAL); }
2277
2438
  });
2278
2439
 
2279
2440
  test("foreign child Changes require successful target-bound tool evidence, never model claims or sibling writes", async () => {
@@ -2357,7 +2518,7 @@ test("foreign child Changes require successful target-bound tool evidence, never
2357
2518
  assert.equal(h.entries.filter(entry => entry.customType === "gentle-pi.session-change/v1").length, 3, "session replacement during a tool cannot attribute its result");
2358
2519
  assert.equal(h.entries.filter(entry => entry.customType === SESSION_WORKTREE_ENTRY).length, 0);
2359
2520
  await h.fire("session_shutdown", successor);
2360
- } finally { rmSync(fixture, { recursive: true, force: true }); }
2521
+ } finally { rmSync(fixture, TEST_DIR_REMOVAL); }
2361
2522
  });
2362
2523
 
2363
2524
  test("foreign task mode waits for the child and continuation reuses its live grant", async () => {
@@ -2405,7 +2566,7 @@ test("foreign task mode waits for the child and continuation reuses its live gra
2405
2566
  assert.equal(((await continued).details.gentleAgents as { cwd: string }).cwd, foreign);
2406
2567
  assert.equal(runtime.spawned.length, 2);
2407
2568
  await h.fire("session_shutdown", ctx);
2408
- } finally { rmSync(fixture, { recursive: true, force: true }); }
2569
+ } finally { rmSync(fixture, TEST_DIR_REMOVAL); }
2409
2570
  });
2410
2571
 
2411
2572
  test("aborting during foreign consent cannot grant or queue a background child", async () => {
@@ -2430,7 +2591,7 @@ test("aborting during foreign consent cannot grant or queue a background child",
2430
2591
  assert.equal(runtime.children.length, 0);
2431
2592
  assert.deepEqual(h.entries.filter(entry => entry.customType === SESSION_WORKTREE_ENTRY), []);
2432
2593
  await h.fire("session_shutdown", ctx);
2433
- } finally { rmSync(fixture, { recursive: true, force: true }); }
2594
+ } finally { rmSync(fixture, TEST_DIR_REMOVAL); }
2434
2595
  });
2435
2596
 
2436
2597
  test("an interactive non-Git umbrella can target an independent repository without registering it", async () => {
@@ -2450,7 +2611,7 @@ test("an interactive non-Git umbrella can target an independent repository witho
2450
2611
  assert.equal((launched.details.gentleAgents as { cwd: string }).cwd, foreign);
2451
2612
  assert.deepEqual(h.entries.filter(entry => entry.customType === SESSION_WORKTREE_ENTRY), []);
2452
2613
  await h.fire("session_shutdown", ctx);
2453
- } finally { rmSync(fixture, { recursive: true, force: true }); }
2614
+ } finally { rmSync(fixture, TEST_DIR_REMOVAL); }
2454
2615
  });
2455
2616
 
2456
2617
  test("foreign selector rejects RPC and retired SDD selections before consent", async () => {
@@ -2486,7 +2647,7 @@ test("foreign selector rejects RPC and retired SDD selections before consent", a
2486
2647
  assert.equal(dialogs.length, 0);
2487
2648
  assert.equal(runtime.children.length, 0);
2488
2649
  await h.fire("session_shutdown", ctx);
2489
- } finally { rmSync(fixture, { recursive: true, force: true }); }
2650
+ } finally { rmSync(fixture, TEST_DIR_REMOVAL); }
2490
2651
  });
2491
2652
 
2492
2653
  test("foreign clone rejects aliases, absent UI, decline and changed session before any child starts", async () => {
@@ -2520,7 +2681,7 @@ test("foreign clone rejects aliases, absent UI, decline and changed session befo
2520
2681
  assert.equal(dialogs.filter(dialog => dialog.startsWith("confirm:")).length, 2);
2521
2682
  assert.deepEqual(h.entries.filter(entry => entry.customType === SESSION_WORKTREE_ENTRY), []);
2522
2683
  await h.fire("session_shutdown", ctx);
2523
- } finally { rmSync(fixture, { recursive: true, force: true }); }
2684
+ } finally { rmSync(fixture, TEST_DIR_REMOVAL); }
2524
2685
  });
2525
2686
 
2526
2687
  test("explicit child roots launch and continue in the actual cwd, persist without shell, and reject other clones", async () => {
@@ -2548,6 +2709,7 @@ test("explicit child roots launch and continue in the actual cwd, persist withou
2548
2709
  await h.fire("session_start", ctx);
2549
2710
  const run = h.tools.get("subagent_run")!;
2550
2711
  await assert.rejects(run.execute("bad", { agent: "explore", task: "Map", workspace_root: "/other-clone", mode: "background" }, undefined, undefined, ctx), /same Git clone/);
2712
+ await assert.rejects(run.execute("bad", { agent: "explore", task: "Map", workspace_root: "/other-clone", mode: "background" }, undefined, undefined, ctx), /subagent_run with repository_root/);
2551
2713
  assert.deepEqual(launched, []);
2552
2714
  const result = await run.execute("one", { agent: "explore", task: "Map /other-clone mentioned in prose", workspace_root: childRoot, mode: "background" }, undefined, undefined, ctx);
2553
2715
  await tick();
@@ -2565,12 +2727,12 @@ test("explicit child roots launch and continue in the actual cwd, persist withou
2565
2727
  await tick();
2566
2728
  assert.deepEqual(launched, [childRoot, childRoot]);
2567
2729
  spawnEvents[1]();
2568
- assert.equal(h.entries.length, 1, "continuation dedupes the original root");
2730
+ assert.equal(h.entries.filter(entry => entry.customType === SESSION_WORKTREE_ENTRY).length, 1, "continuation dedupes the original root");
2569
2731
  const status = await h.tools.get("subagent_status")!.execute("status", { task_id: details.taskId }, undefined, undefined, ctx);
2570
2732
  assert.match(status.content[0].text, /cwd:/);
2571
2733
  await h.fire("session_shutdown", ctx);
2572
2734
  spawnEvents[1]();
2573
- assert.equal(h.entries.length, 1, "late process events after shutdown cannot write session state");
2735
+ assert.equal(h.entries.filter(entry => entry.customType === SESSION_WORKTREE_ENTRY).length, 1, "late process events after shutdown cannot register roots");
2574
2736
  await tick();
2575
2737
  });
2576
2738
 
@@ -2702,6 +2864,52 @@ for (const scenario of ["implicit-worker", "explicit-worker", "implicit-gentle-a
2702
2864
  });
2703
2865
  }
2704
2866
 
2867
+ // gentle-shell#1558 (barbatdev review): the non-git writer admission and the
2868
+ // launch path must resolve the same model. Before the session-binding layer,
2869
+ // both read pin/global only; with a binding present the launch resolves it
2870
+ // first while admission still read the declaration, so a bound session killed
2871
+ // its own writer mid-preparation with a false "profile or session changed".
2872
+ test("a session binding keeps writer admission and launch resolution in agreement", async t => {
2873
+ t.after(() => resetSessionProfileBindingsForTesting());
2874
+ const fixture = realpathSync(mkdtempSync(join(root, "writer-session-binding-")));
2875
+ const project = join(fixture, "project");
2876
+ const fixtureHome = join(fixture, "home");
2877
+ const definitions = join(fixtureHome, ".pi", "agent", "agents");
2878
+ mkdirSync(definitions, { recursive: true });
2879
+ mkdirSync(project);
2880
+ writeFileSync(join(definitions, "worker.md"), "---\ndescription: fixture\nmodel: offline/good\ntools: [read]\n---\nFixture");
2881
+ // The unversioned project declaration routes the writer at one model and the
2882
+ // session binding at another: only agreement between the two resolutions can
2883
+ // let this launch through, and both must pick the binding's model.
2884
+ mkdirSync(join(project, ".pi", "gentle-ai"), { recursive: true });
2885
+ writeFileSync(join(project, ".pi", "gentle-ai", "profile.json"), JSON.stringify({ kind: "gentle-pi.agent_model_profile_pin", version: 1, profile: "declared" }));
2886
+ const configHome = join(fixture, "config");
2887
+ mkdirSync(configHome, { recursive: true });
2888
+ writeFileSync(join(configHome, "profiles.json"), JSON.stringify({ kind: "gentle-pi.agent_model_profiles", version: 1, profiles: { declared: { worker: { model: "offline/pinned-good" } }, bound: { worker: { model: "offline/bound-good" } } } }));
2889
+ bindSessionProfile("s1", "bound", { worker: { model: "offline/bound-good" } });
2890
+ const h = fakePi();
2891
+ const runtime = deps();
2892
+ runtime.deps.home = fixtureHome;
2893
+ runtime.deps.env!.GENTLE_PI_CONFIG_HOME = configHome;
2894
+ runtime.deps.resolveWorktree = resolveSessionWorktree;
2895
+ gentleAgents(h.pi, {}, runtime.deps);
2896
+ const { ctx } = fakeContext();
2897
+ Object.assign(ctx, { cwd: project, modelRegistry: { find: (_provider: string, model: string) => ({ provider: "offline", id: model }) } });
2898
+ ctx.sessionManager.getCwd = () => project;
2899
+ await h.fire("session_start", ctx);
2900
+ const unbind = bindSessionRepositoryPreparation(ctx.sessionManager, project, async (_root, current) => {
2901
+ if (!current()) return false;
2902
+ execFileSync("git", ["init", "--quiet", project], { env: { PATH: process.env.PATH, HOME: fixtureHome, GIT_CONFIG_NOSYSTEM: "1" }, stdio: "pipe" });
2903
+ return true;
2904
+ }, () => true);
2905
+ try {
2906
+ await h.tools.get("subagent_run")!.execute("session-binding-admission", { agent: "worker", task: "Implement source\n## Allowed edit surfaces\nsrc/app.ts\n## Return\nReport", mode: "background" }, undefined, undefined, ctx);
2907
+ await tick();
2908
+ assert.equal(runtime.children.length, 1, "the bound session's writer launches instead of dying as a false profile/session drift");
2909
+ assert.ok(runtime.spawned[0]?.includes("offline/bound-good"), "admission and launch both resolve the binding ahead of the project declaration");
2910
+ } finally { unbind(); await h.fire("session_shutdown", ctx); await tick(); }
2911
+ });
2912
+
2705
2913
  for (const explicit of [false, true]) {
2706
2914
  test(`same manager and ID after bootstrap permit ${explicit ? "explicit" : "implicit"} launch registration`, async () => {
2707
2915
  const h = fakePi();
@@ -2757,7 +2965,7 @@ test("ordinary non-Git tasks still continue in their original cwd without regist
2757
2965
  await h.tools.get("subagent_continue")!.execute("continue", { task_id: taskId, prompt: "Follow up", mode: "background" }, undefined, undefined, ctx);
2758
2966
  await tick();
2759
2967
  assert.equal(runtime.children.length, 2);
2760
- assert.deepEqual(h.entries, []);
2968
+ assert.deepEqual(h.entries.filter(entry => entry.customType !== "gentle-agents.wake-identity"), []);
2761
2969
  await h.fire("session_shutdown", ctx);
2762
2970
  await tick();
2763
2971
  });
@@ -2788,7 +2996,7 @@ for (const sameId of [false, true]) {
2788
2996
  await h.fire("session_start", next.ctx);
2789
2997
  spawnEvents[0]();
2790
2998
  await tick();
2791
- assert.deepEqual(h.entries, [], "captured registry is closed instead of appending to the new bound API");
2999
+ assert.deepEqual(h.entries.filter(entry => entry.customType !== "gentle-agents.wake-identity"), [], "captured registry is closed instead of appending worktree state to the new bound API");
2792
3000
  await h.fire("session_shutdown", next.ctx);
2793
3001
  });
2794
3002
  }
@@ -2965,6 +3173,55 @@ test("a stale or unreadable pin degrades to the global routing instead of failin
2965
3173
  assert.equal(await launchPinned(base), "openai-codex/gpt-5.6-terra:low");
2966
3174
  });
2967
3175
 
3176
+ // gentle-shell#1558 (barbatdev review): the two registered launch-seam gaps.
3177
+ // The pure helpers were covered, but the real subagent_run seam had no
3178
+ // committed test for the session layer.
3179
+ test("a session binding outranks the repository pin at the launch seam", async t => {
3180
+ t.after(() => resetSessionProfileBindingsForTesting());
3181
+ const base = pinFixture("session-over-pin");
3182
+ base.writeStore({
3183
+ pinned: { explore: { model: "openai/alpha", thinking: "minimal" } },
3184
+ bound: { explore: { model: "openai/beta" } },
3185
+ });
3186
+ base.writePin("pinned");
3187
+ // fakeContext's session id is "s1"; the binding is process state, so it is
3188
+ // bound before the launch and reset by t.after so later pin tests stay pure.
3189
+ bindSessionProfile("s1", "bound", { explore: { model: "openai/beta" } });
3190
+ assert.equal(await launchPinned(base), "openai/beta:high", "the session binding wins over a winning repository pin");
3191
+ });
3192
+
3193
+ test("a queued launch keeps the session routing frozen across a rebind", async t => {
3194
+ t.after(() => resetSessionProfileBindingsForTesting());
3195
+ const base = pinFixture("queue-freeze");
3196
+ base.writeStore({
3197
+ first: { explore: { model: "openai/alpha", thinking: "minimal" } },
3198
+ second: { explore: { model: "openai/beta" } },
3199
+ });
3200
+ bindSessionProfile("s1", "first", { explore: { model: "openai/alpha", thinking: "minimal" } });
3201
+ const harness = deps();
3202
+ harness.deps.resolveWorktree = () => ({ root: base.root, commonDir: base.commonDir });
3203
+ harness.deps.env = { PATH: "/bin", GENTLE_PI_CONFIG_HOME: base.configHome };
3204
+ const { pi, tools, fire } = fakePi();
3205
+ gentleAgents(pi, {}, harness.deps);
3206
+ const { ctx } = fakeContext();
3207
+ await fire("session_start", ctx);
3208
+ try {
3209
+ const model = (args: string[]) => args[args.indexOf("--model") + 1];
3210
+ // The first launch freezes first's routing into its task request and its
3211
+ // spawned child. Rebinding the session must leave that request untouched;
3212
+ // only a request created afterwards resolves the new binding.
3213
+ await tools.get("subagent_run")!.execute("freeze-1", { agent: "explore", task: "Map first", mode: "background" }, undefined, undefined, ctx);
3214
+ bindSessionProfile("s1", "second", { explore: { model: "openai/beta" } });
3215
+ await tools.get("subagent_run")!.execute("freeze-2", { agent: "explore", task: "Map second", mode: "background" }, undefined, undefined, ctx);
3216
+ await tick();
3217
+ assert.equal(model(harness.spawned[0]), "openai/alpha:minimal", "the request created before the rebind keeps its frozen routing");
3218
+ assert.equal(model(harness.spawned[1]), "openai/beta:high", "only requests created after the rebind resolve the new binding");
3219
+ } finally {
3220
+ await fire("session_shutdown", ctx);
3221
+ await tick();
3222
+ }
3223
+ });
3224
+
2968
3225
  test("agentsEnabled and agentsCollapseKey read their flags and stay off inside a child", () => {
2969
3226
  assert.equal(agentsEnabled({}), true);
2970
3227
  assert.equal(agentsEnabled({ GENTLE_PI_AGENTS: "off" }), false);
@@ -2997,13 +3254,42 @@ test("while pi-subagents-j0k3r is still installed the tools stay unregistered an
2997
3254
  assert.match(notices[0] ?? "", /^warning:❀ Gentle Agents is waiting: remove the old package first with "pi remove npm:pi-subagents-j0k3r"/);
2998
3255
  });
2999
3256
 
3257
+ test("subagent_list_agents publishes each agent's declared tool inventory so routing can check capabilities", async () => {
3258
+ const fixture = mkdtempSync(join(tmpdir(), "capability-catalog-"));
3259
+ const agentHome = join(fixture, "agent-home");
3260
+ mkdirSync(join(agentHome, ".pi", "agent", "agents"), { recursive: true });
3261
+ writeFileSync(join(agentHome, ".pi", "agent", "agents", "explore.md"), "---\ndescription: maps things\ntools: [read, grep, find, codegraph]\n---\nYou map things.");
3262
+ writeFileSync(join(agentHome, ".pi", "agent", "agents", "open.md"), "---\ndescription: no allowlist\n---\nYou are open.");
3263
+ writeFileSync(join(agentHome, ".pi", "agent", "agents", "unknown.md"), "---\ndescription: unverified name\ntools: [glob]\n---\nYou explore.");
3264
+ writeFileSync(join(agentHome, ".pi", "agent", "agents", "lens.md"), "---\ndescription: review lane\ntools:\n - \"*\": false\n - read\n - grep\n - gentle_review_scope\n---\nYou review.");
3265
+ writeFileSync(join(agentHome, ".pi", "agent", "agents", "denied.md"), "---\ndescription: only a wildcard\ntools:\n - \"*\": false\n---\nYou are denied.");
3266
+ try {
3267
+ const h = fakePi(), runtime = deps();
3268
+ runtime.deps.home = agentHome;
3269
+ gentleAgents(h.pi, {}, runtime.deps);
3270
+ const { ctx } = fakeContext();
3271
+ await h.fire("session_start", ctx);
3272
+ const listed = await h.tools.get("subagent_list_agents")!.execute("c0", {}, undefined, undefined, ctx);
3273
+ assert.match(listed.content[0].text, /- explore \(global\): maps things \[declared tools \(not verified\): read, grep, find, codegraph\]/);
3274
+ // gentle-shell#1269: a definition without an allowlist keeps Pi's default
3275
+ // tool set, so the catalog must never render it as having no tools at all.
3276
+ assert.match(listed.content[0].text, /- open \(global\): no allowlist \[declared tools: Pi defaults \(no allowlist\)\]/);
3277
+ // The review lane declares the `"*": false` wildcard, which Pi drops: it is
3278
+ // not a capability and must not appear as one in the routing surface.
3279
+ assert.match(listed.content[0].text, /- lens \(global\): review lane \[declared tools \(not verified\): read, grep, gentle_review_scope\]/);
3280
+ assert.doesNotMatch(listed.content[0].text, /false/);
3281
+ assert.match(listed.content[0].text, /- unknown \(global\): unverified name \[declared tools \(not verified\): glob\]/);
3282
+ assert.match(listed.content[0].text, /- denied \(global\): only a wildcard \[declared tools: no tool names declared\]/);
3283
+ } finally { rmSync(fixture, TEST_DIR_REMOVAL); }
3284
+ });
3285
+
3000
3286
  test("subagent_list_agents and subagent_run in task mode launch a child with the resolved profile and return its answer", async () => {
3001
3287
  const { pi, tools, fire } = fakePi();
3002
3288
  const harness = deps();
3003
3289
  gentleAgents(pi, {}, harness.deps);
3004
3290
  const { ctx, widget } = fakeContext();
3005
3291
  await fire("session_start", ctx);
3006
- assert.deepEqual([...tools.keys()].sort(), ["orchestrator_list", "orchestrator_send_message", "orchestrator_session_id", "subagent_cancel", "subagent_continue", "subagent_list_agents", "subagent_list_tasks", "subagent_reply", "subagent_result", "subagent_run", "subagent_send_message", "subagent_status"]);
3292
+ assert.deepEqual([...tools.keys()].sort(), ["bash_background", "job_list", "job_stop", "monitor", "orchestrator_consult", "orchestrator_list", "orchestrator_send_message", "orchestrator_session_id", "subagent_cancel", "subagent_continue", "subagent_list_agents", "subagent_list_tasks", "subagent_reply", "subagent_result", "subagent_run", "subagent_send_message", "subagent_status"]);
3007
3293
  const listed = await tools.get("subagent_list_agents")!.execute("c0", {}, undefined, undefined, ctx);
3008
3294
  assert.match(listed.content[0].text, /- explore \(global\): maps things/);
3009
3295
 
@@ -3023,7 +3309,9 @@ test("subagent_list_agents and subagent_run in task mode launch a child with the
3023
3309
  harness.children[0].emit({ type: "agent_end", messages: [{ role: "assistant", content: [{ type: "text", text: "lib has three agent files." }] }] });
3024
3310
  harness.children[0].emit({ type: "agent_settled" });
3025
3311
  const result = await running;
3026
- assert.equal(result.content[0].text, "lib has three agent files.");
3312
+ const runId = (result.details.gentleAgents as { taskId: string }).taskId;
3313
+ assert.equal(result.content[0].text, `Subagent explore (task ${runId}, "map lib modules") finished.\n\nlib has three agent files.`, "the model sees the real task id and label, not only details");
3314
+ assert.deepEqual(tools.get("subagent_run")!.renderResult(result as Parameters<Registered["renderResult"]>[0], { expanded: false }, plainTheme).render(80).map((line) => line.trimEnd()), ["lib has three agent files."], "the collapsed card still leads with the answer");
3027
3315
  assert.equal((result.details.gentleAgents as { status: string }).status, "completed");
3028
3316
  assert.match(widget()![1], /✓ explore map lib modules/);
3029
3317
  const orphan = tools.get("subagent_run")!.execute("c9", { agent: "explore", task: "Orphan", mode: "background" }, undefined, undefined, ctx);
@@ -3129,9 +3417,15 @@ test("background runs return at once; status, result, send_message, cancel, and
3129
3417
  await tick();
3130
3418
  harness.children[1].emit({ type: "agent_end", messages: [{ role: "assistant", content: [{ type: "text", text: "Summary." }] }] });
3131
3419
  harness.children[1].emit({ type: "agent_settled" });
3132
- assert.equal((await resumed).content[0].text, "Summary.");
3420
+ const summary = await resumed;
3421
+ assert.equal(summary.content[0].text, `Subagent explore (task ${(summary.details.gentleAgents as { taskId: string }).taskId}, "Now summarize") finished.\n\nSummary.`);
3133
3422
  assert.match((await tools.get("subagent_cancel")!.execute("c9", { task_id: id }, undefined, undefined, ctx)).content[0].text, /not running/);
3134
3423
  assert.match((await tools.get("subagent_status")!.execute("c10", { task_id: "nope" }, undefined, undefined, ctx)).content[0].text, /Error: no task nope/);
3424
+ // gentle-shell#1713: a guessed id ("1") must point back to real ids.
3425
+ // Review follow-up: a call without a context still gets the structured error.
3426
+ assert.match((await tools.get("subagent_status")!.execute("c10c", { task_id: "1" }, undefined, undefined, undefined as never)).content[0].text, /^Error: no task 1\./);
3427
+ for (const name of ["subagent_status", "subagent_result"]) assert.match((await tools.get(name)!.execute("c10a", { task_id: "1" }, undefined, undefined, ctx)).content[0].text, new RegExp(`^Error: no task 1\\. Recent task ids: .*${id} \\(explore\\)`), name);
3428
+ assert.match((await tools.get("subagent_continue")!.execute("c10b", { task_id: "1", prompt: "more" }, undefined, undefined, ctx)).content[0].text, new RegExp(`^Error: no task 1\\. Recent task ids: .*${id} \\(explore\\)`));
3135
3429
  assert.match((await tools.get("subagent_run")!.execute("c11", { agent: "ghost", task: "x" }, undefined, undefined, ctx)).content[0].text, /no subagent named "ghost"\. Known: explore/);
3136
3430
  });
3137
3431
 
@@ -3329,7 +3623,7 @@ test("AgentsView production footer uses rendered bounds and invalidates them bef
3329
3623
  const harness = deps();
3330
3624
  gentleAgents(pi, {}, harness.deps);
3331
3625
  const { ctx, overlays, customCompletions } = fakeContext();
3332
- (ctx as unknown as { sessionManager: { getSessionId(): string; getCwd(): string } }).sessionManager = { getSessionId: () => "footer-session", getCwd: () => cwd };
3626
+ Object.assign(ctx.sessionManager, { getSessionId: () => "footer-session" });
3333
3627
  await fire("session_start", ctx);
3334
3628
  await tools.get("subagent_run")!.execute("c1", { agent: "寿司", task: "Footer target", mode: "background" }, undefined, undefined, ctx);
3335
3629
  await tick();
@@ -3530,17 +3824,45 @@ test("the overlay explains that stopping a waiting subagent dismisses its questi
3530
3824
  await opened;
3531
3825
  });
3532
3826
 
3533
- test("restored task history cannot enter the live panel or execute stop even with the current session ID", async () => {
3827
+ test("restored task history cannot enter the live panel or discovery during synchronous summary callbacks", async (t) => {
3534
3828
  const { pi, fire, commands, tools } = fakePi();
3535
3829
  const harness = deps();
3536
3830
  const historyHome = join(root, "history-home");
3537
3831
  const historical: TaskRecord = { id: "history-running", agent: "explore", mode: "background", prompt: "p", label: "p", cwd, parentSessionId: "s1", status: TASK_STATUS.RUNNING, createdAt: 1, startedAt: 1, endedAt: null, model: "m", thinking: undefined, sessionPath: null, error: null, result: null, lastStep: "working", lastActivityAt: 1, turns: 0, toolCalls: 0, tokens: 0, cost: 0 };
3538
- await saveTask(historyDir(historyHome), historical, emptyThread());
3539
3832
  harness.deps.home = historyHome;
3833
+ const profile = liveProfile("restored-discovery");
3834
+ await saveTask(historyDir(historyHome, profile), historical, emptyThread());
3835
+ chmodSync(join(profile, "gentle-agents"), 0o755);
3836
+ harness.deps.agentHome = profile;
3837
+ const registry = { list: async () => [], listActivations: async () => [] };
3838
+ harness.deps.sessionTransport = {
3839
+ createRegistry: async () => registry,
3840
+ createListener: (_, sessionId) => ({ registry, record: { version: 1, sessionId, endpoint: "/fixture/restore", createdAt: 1 }, start: async () => {}, close: async () => {} }),
3841
+ createClient: inertSessionTransport.createClient,
3842
+ };
3843
+ let checked = false;
3844
+ let leaked: unknown;
3845
+ const update = PresencePublisher.prototype.update;
3846
+ let snapshot: unknown;
3847
+ t.mock.method(PresencePublisher.prototype, "update", function (this: PresencePublisher, input: Parameters<PresencePublisher["update"]>[0]) {
3848
+ snapshot = input.map(row => row.task.id);
3849
+ return update.call(this, input);
3850
+ });
3851
+ const restore = TaskStore.prototype.restore;
3852
+ t.mock.method(TaskStore.prototype, "restore", function (this: TaskStore, ...args: Parameters<TaskStore["restore"]>) {
3853
+ const result = restore.apply(this, args);
3854
+ leaked = snapshot;
3855
+ checked = true;
3856
+ return result;
3857
+ });
3540
3858
  gentleAgents(pi, {}, harness.deps);
3541
3859
  const { ctx, dialogs, overlays } = fakeContext();
3542
3860
  await fire("session_start", ctx);
3543
- await tools.get("subagent_status")!.execute("restore", { task_id: historical.id }, undefined, undefined, ctx);
3861
+ await tick();
3862
+ await fire("session_start", ctx, { reason: "resume" });
3863
+ await eventually(() => checked, "restoration callback checked");
3864
+ assert.deepEqual(leaked, [], "summary callback must not publish restored running history");
3865
+ assert.deepEqual(readDiscovery(profile, listPresence(profile).entries[0])?.tasks, []);
3544
3866
  const opened = commands.get("gentle:agents")!.handler("", ctx);
3545
3867
  for (let attempt = 0; attempt < 40 && overlays.length === 0; attempt += 1) await new Promise((resolve) => setTimeout(resolve, 25));
3546
3868
  assert.doesNotMatch(stripAnsi(overlays[0]!.render(80).join("\n")), /Stop selected|Subagent explore/);
@@ -3690,8 +4012,8 @@ test("the card follows the active session: after /new the earlier session's task
3690
4012
  await tools.get("subagent_run")!.execute("c1", { agent: "explore", task: "Long job", mode: "background" }, undefined, undefined, ctx);
3691
4013
  await tick();
3692
4014
  assert.match(widget()![1], /◐ explore Long job/);
3693
- const sessions = ctx as unknown as { sessionManager: { getSessionId(): string; getCwd(): string } };
3694
- sessions.sessionManager = { getSessionId: () => "s2", getCwd: () => cwd };
4015
+ const sessions = ctx as unknown as { sessionManager: { getSessionId(): string; getCwd(): string; getBranch(): []; getEntries(): [] } };
4016
+ sessions.sessionManager = { getSessionId: () => "s2", getCwd: () => cwd, getBranch: () => [], getEntries: () => [] };
3695
4017
  await fire("session_start", ctx, { type: "session_start", reason: "new" });
3696
4018
  assert.deepEqual(widget(), [], "the new session starts with an empty card");
3697
4019
  assert.match((await tools.get("subagent_list_tasks")!.execute("c2", {}, undefined, undefined, ctx)).content[0].text, /No subagent tasks in this session/);
@@ -3703,7 +4025,7 @@ test("the card follows the active session: after /new the earlier session's task
3703
4025
  assert.doesNotMatch(overlay.render(80).map(stripAnsi).join("\n"), /◐ Subagent explore/, "retained children of a replaced session do not imply an open orchestrator");
3704
4026
  overlay.handleInput("\x1b");
3705
4027
  await opened;
3706
- sessions.sessionManager = { getSessionId: () => "s1", getCwd: () => cwd };
4028
+ sessions.sessionManager = { getSessionId: () => "s1", getCwd: () => cwd, getBranch: () => [], getEntries: () => [] };
3707
4029
  await fire("session_start", ctx, { type: "session_start", reason: "resume" });
3708
4030
  assert.match(widget()![1], /◐ explore Long job/, "resuming the first session shows its task again");
3709
4031
  });
@@ -3792,6 +4114,405 @@ test("session transport startup failure cleans the constructed Windows-capable t
3792
4114
  assert.match((await h.tools.get("orchestrator_session_id")!.execute("id", {}, undefined, undefined, ctx)).content[0].text, /not ready/);
3793
4115
  });
3794
4116
 
4117
+ test("registered task aliases persist independently of human names and curated state", async () => {
4118
+ const h = fakePi(), runtime = deps(), { ctx } = fakeContext();
4119
+ const profile = realpathSync(mkdtempSync(join(root, "aliases-runtime-")));
4120
+ runtime.deps.agentHome = profile;
4121
+ const peer = { version: 1 as const, sessionId: "s1", endpoint: "/fixture/aliases.sock", createdAt: 1 };
4122
+ const registry = { list: async () => [], listActivations: async () => [peer] };
4123
+ runtime.deps.sessionTransport = {
4124
+ createRegistry: async () => registry,
4125
+ createListener: () => ({ registry, record: peer, start: async () => {}, close: async () => {} }),
4126
+ createClient: () => ({ close() {}, sendNotification: async () => { throw new Error("unexpected message"); } }),
4127
+ };
4128
+ let name = "Human label";
4129
+ Object.assign(h.pi, { setSessionName: () => { throw new Error("named session must not be renamed"); } });
4130
+ let branch = h.entries;
4131
+ Object.assign(ctx.sessionManager, { getSessionName: () => name, getBranch: () => branch });
4132
+ gentleAgents(h.pi, {}, runtime.deps);
4133
+ await h.fire("session_start", ctx);
4134
+ const tool = h.tools.get("orchestrator_session_id")!;
4135
+ const declare = (params: unknown = {}, context = ctx) => tool.execute("aliases", params, undefined, undefined, context);
4136
+ const aliases = () => readDiscovery(profile, listPresence(profile).entries[0])?.aliases;
4137
+ const first = await declare({ subject: "Task A", state: { progress: "Starting", work: { area: "Auth" } } });
4138
+ const initial = h.entries.at(-1)!;
4139
+ assert.deepEqual(aliases(), { initialAlias: "Task A", currentAlias: "Task A" });
4140
+ assert.match(first.content[0].text, /Current alias \(CURRENT TASK\): Task A/);
4141
+ assert.match(first.content[0].text, /Initial alias \(FIRST TASK\): Task A/);
4142
+ const recordedAt = readDiscovery(profile, listPresence(profile).entries[0])?.state?.recordedAt;
4143
+ const second = await declare({ subject: "Task B" });
4144
+ assert.equal(readDiscovery(profile, listPresence(profile).entries[0])?.state?.recordedAt, recordedAt);
4145
+ assert.equal(readDiscovery(profile, listPresence(profile).entries[0])?.state?.state?.progress, "Starting");
4146
+ assert.deepEqual(aliases(), { initialAlias: "Task A", currentAlias: "Task B" });
4147
+ assert.match(second.content[0].text, /Session name: Human label/);
4148
+ assert.equal((second.details.gentleAgents as { senderSessionId: string }).senderSessionId, "s1");
4149
+ assert.equal(listPresence(profile).entries[0].label, name);
4150
+ const list = await h.tools.get("orchestrator_list")!.execute("list", {}, undefined, undefined, ctx);
4151
+ assert.match(list.content[0].text, /Task A/);
4152
+ assert.match(list.content[0].text, /Task B/);
4153
+ const consult = await h.tools.get("orchestrator_consult")!.execute("consult", { recipient_session_id: "s1" }, undefined, undefined, ctx);
4154
+ assert.deepEqual(JSON.parse(consult.content[0].text).snapshot.aliases, aliases());
4155
+ const filtered = await h.tools.get("orchestrator_list")!.execute("filter", { filter: { text: "Task B" } }, undefined, undefined, ctx);
4156
+ assert.equal(JSON.parse(filtered.content[0].text).matches[0].label, "Task B");
4157
+ name = "Human rename";
4158
+ await declare({ state: { progress: "Replacement" } });
4159
+ await declare({ state: null });
4160
+ const writes = h.entries.length;
4161
+ await declare();
4162
+ assert.equal(h.entries.length, writes);
4163
+ assert.deepEqual(aliases(), { initialAlias: "Task A", currentAlias: "Task B" });
4164
+ await h.fire("session_start", ctx, { reason: "resume" });
4165
+ assert.deepEqual(aliases(), { initialAlias: "Task A", currentAlias: "Task B" });
4166
+ branch = [initial];
4167
+ await h.fire("session_tree", ctx);
4168
+ assert.deepEqual(aliases(), { initialAlias: "Task A", currentAlias: "Task A" });
4169
+ branch = [{ ...initial, data: { ...(initial.data as object), aliases: undefined } }];
4170
+ // An actual legacy envelope has no alias field, not a malformed undefined field.
4171
+ delete (branch[0].data as { aliases?: unknown }).aliases;
4172
+ await h.fire("session_start", ctx, { reason: "reload" });
4173
+ assert.equal(aliases(), undefined);
4174
+ await declare({ subject: "Legacy current" });
4175
+ assert.deepEqual(aliases(), { initialAlias: null, currentAlias: "Legacy current" });
4176
+ const replacement = fakeContext().ctx;
4177
+ await h.fire("session_start", replacement);
4178
+ assert.match((await declare({ subject: "Stale" }, ctx)).content[0].text, /not ready/);
4179
+ assert.equal(aliases(), undefined);
4180
+ assert.equal(runtime.spawned.length + h.sent.length + h.userMessages.length, 0);
4181
+ });
4182
+
4183
+ test("registered session identity declares subjects and refreshes canonical idle renames", async (t) => {
4184
+ const h = fakePi();
4185
+ const runtime = deps();
4186
+ const profile = realpathSync(mkdtempSync(join(root, "subject-runtime-")));
4187
+ runtime.deps.agentHome = profile;
4188
+ let ready = false;
4189
+ const registry = { list: async () => [], listActivations: async () => [] };
4190
+ runtime.deps.sessionTransport = {
4191
+ createRegistry: async () => registry,
4192
+ createListener: (_registry, sessionId) => ({ registry,
4193
+ record: { version: 1 as const, sessionId, endpoint: "/fixture/subject.sock", createdAt: 1 },
4194
+ start: async () => { ready = true; }, close: async () => {} }),
4195
+ createClient: () => ({ close() {}, sendNotification: async () => { throw new Error("no messages expected"); } }),
4196
+ };
4197
+ const heartbeats: (() => void)[] = [];
4198
+ const interval = globalThis.setInterval;
4199
+ t.mock.method(globalThis, "setInterval", (callback: () => void, ms: number) => {
4200
+ if (ms === 5000) heartbeats.push(callback);
4201
+ return interval(callback, ms);
4202
+ });
4203
+ let name = "";
4204
+ const names: string[] = [];
4205
+ Object.assign(h.pi, { setSessionName: (value: string) => { name = value; names.push(value); } });
4206
+ gentleAgents(h.pi, {}, runtime.deps);
4207
+ const { ctx } = fakeContext();
4208
+ const registrations = [{ type: "custom", customType: SESSION_WORKTREE_ENTRY, data: { sessionId: "s1", root: cwd, evidence: "fixture" } }];
4209
+ Object.assign(ctx.sessionManager, { getSessionName: () => name, getEntries: () => registrations });
4210
+ await h.fire("session_start", ctx);
4211
+ await eventually(() => ready, "subject transport ready");
4212
+ const tool = h.tools.get("orchestrator_session_id")!;
4213
+ const declare = (subject?: unknown, context = ctx) => tool.execute("id", { subject }, undefined, undefined, context);
4214
+ const initialWrites = h.entries.length;
4215
+ await assert.rejects(() => tool.execute("invalid-work", { subject: "No effect", state: { work: { topic: "Login" } } }, undefined, undefined, ctx), /invalid/);
4216
+ assert.equal(name, "");
4217
+ assert.equal(h.entries.length, initialWrites);
4218
+ assert.equal(readDiscovery(profile, listPresence(profile).entries[0])?.state, undefined);
4219
+ const result = await declare("\u001b[31m Fix\n auth\u202e ");
4220
+ assert.equal(name, "Fix auth");
4221
+ assert.match(result.content[0].text, /Active session ID: s1.*\n.*Fix auth/);
4222
+ assert.deepEqual(result.details.gentleAgents, { senderSessionId: "s1", alias: "Fix auth", sessionName: "Fix auth", initialAlias: "Fix auth", currentAlias: "Fix auth" });
4223
+ const before = listPresence(profile).entries[0]!;
4224
+ assert.equal(before.label, "Fix auth");
4225
+ assert.equal(readDiscovery(profile, before)?.state?.state, null, "no implicit summary");
4226
+ Object.assign(ctx.sessionManager, { getBranch: () => h.entries });
4227
+ const work = { area: "Auth", topic: "Login", tags: ["Review"], refs: [
4228
+ { kind: "issue", repository: "github.com/Owner/Repo", id: "12" },
4229
+ ] };
4230
+ await tool.execute("publish", { state: { objective: "Verify auth", decisions: "Advisory only", work } }, undefined, undefined, ctx);
4231
+ assert.equal(readDiscovery(profile, listPresence(profile).entries[0])?.state?.state?.objective, "Verify auth");
4232
+ assert.deepEqual(readDiscovery(profile, listPresence(profile).entries[0])?.state?.state?.work, work);
4233
+ const published = h.entries.at(-1)!;
4234
+ const writes = h.entries.length;
4235
+ await assert.rejects(() => tool.execute("invalid", { subject: "No effect", state: { grant: "yes" } }, undefined, undefined, ctx), /invalid/);
4236
+ assert.equal(h.entries.length, writes);
4237
+ assert.equal(name, "Fix auth");
4238
+ await declare();
4239
+ assert.equal(h.entries.length, writes, "omission leaves notes unchanged");
4240
+ assert.equal(readDiscovery(profile, before)?.workspace, cwd);
4241
+ assert.equal(readDiscovery(profile, before)?.scope?.host.root, cwd);
4242
+ assert.equal(readDiscovery(profile, before)?.scope?.registered[0]?.root, cwd);
4243
+ name = "Human rename";
4244
+ heartbeats[0](); // Existing publisher heartbeat, without any task/model activity.
4245
+ const renamed = listPresence(profile).entries[0]!;
4246
+ assert.equal(renamed.label, name);
4247
+ assert.equal(renamed.generation, before.generation);
4248
+ assert.deepEqual(readActivity(profile, renamed).activity?.tasks, []);
4249
+ assert.equal(readDiscovery(profile, renamed)?.scope?.host.resolvedAt, readDiscovery(profile, before)?.scope?.host.resolvedAt);
4250
+ registrations.push({ ...registrations[0], data: { ...registrations[0].data, root: join(cwd, "registered") } });
4251
+ h.pi.events.emit(SESSION_WORKTREE_CHANGED, { sessionId: "s1" });
4252
+ assert.deepEqual(readDiscovery(profile, listPresence(profile).entries[0])?.scope?.registered.map(fact => fact.root), [cwd, join(cwd, "registered")]);
4253
+ await declare("Do not overwrite");
4254
+ assert.deepEqual(names, ["Fix auth"]);
4255
+ assert.match((await declare()).content[0].text, /Human rename/);
4256
+ name = "";
4257
+ await declare("\u0000\u001b[31m");
4258
+ assert.equal(name, "", "control-only subject never names a session");
4259
+ await declare("😀".repeat(130));
4260
+ assert.equal(Array.from(name).length, 120);
4261
+ await tool.execute("withdraw", { state: null }, undefined, undefined, ctx);
4262
+ await h.fire("session_start", ctx, { reason: "reload" });
4263
+ await eventually(() => readDiscovery(profile, listPresence(profile).entries[0])?.state?.state === null, "withdrawal reload");
4264
+ Object.assign(ctx.sessionManager, { getBranch: () => [published] });
4265
+ await h.fire("session_tree", ctx);
4266
+ assert.equal(readDiscovery(profile, listPresence(profile).entries[0])?.state?.state?.objective, "Verify auth");
4267
+ const sameId = fakeContext().ctx;
4268
+ Object.assign(sameId.sessionManager, { getSessionName: () => name, getBranch: () => [] });
4269
+ await h.fire("session_start", sameId, { reason: "resume" });
4270
+ assert.equal(readDiscovery(profile, listPresence(profile).entries[0])?.state, undefined);
4271
+ const replacement = fakeContext().ctx;
4272
+ Object.assign(replacement.sessionManager, { getSessionId: () => "s2", getSessionName: () => "Replacement" });
4273
+ await h.fire("session_start", replacement, { reason: "new" });
4274
+ heartbeats[0]();
4275
+ assert.equal(listPresence(profile).entries.length, 1);
4276
+ assert.equal(listPresence(profile).entries[0].label, "Replacement");
4277
+ assert.equal(readDiscovery(profile, listPresence(profile).entries[0])?.scope?.host.root, cwd);
4278
+ const stale = await declare("Stale subject", ctx);
4279
+ assert.match(stale.content[0].text, /not ready/);
4280
+ assert.equal(names.length, 2);
4281
+ assert.equal(runtime.spawned.length, 0);
4282
+ assert.equal(h.sent.length, 0);
4283
+ assert.equal(h.userMessages.length, 0);
4284
+ });
4285
+
4286
+ test("registered orchestrator_list joins peer metadata without child launches or messages", async () => {
4287
+ const h = fakePi();
4288
+ const runtime = deps();
4289
+ const profile = realpathSync(mkdtempSync(join(root, "discovery-runtime-")));
4290
+ const peer = { version: 1 as const, sessionId: "peer", endpoint: "/fixture/peer.sock", createdAt: 1 };
4291
+ const publisher = PresencePublisher.start({ profile, sessionId: "peer", label: "Auth review", activity: [] });
4292
+ try {
4293
+ const scope = new OrchestratorScopeCache(path => ({ root: path, commonDir: "/clone" })).project("/repo", [{ id: "child", cwd: "/repo-child" }], ["/repo"]);
4294
+ const tasks = [{ id: "child", label: "Check auth", status: "waiting", cwd: "/repo-child" },
4295
+ ...Array.from({ length: 9 }, (_, i) => ({ id: `extra${i}`, label: `Extra ${i}`, status: "running", cwd: `/child/${i}` }))];
4296
+ publisher.updateDiscovery(peer, { workspace: "/repo", tasks, registered: Array.from({ length: 10 }, (_, i) => `/registered/${i}`), scope,
4297
+ state: { schema: 2, sessionId: "peer", cwd: "/repo", recordedAt: 1, source: "owner-curated",
4298
+ ownerReply: false, authority: "none", state: { work: { tasks: { child: { area: "Auth" }, extra8: { area: "Billing" } } } } },
4299
+ });
4300
+ let ready = false;
4301
+ let probes = 0;
4302
+ const resolveWorktree = runtime.deps.resolveWorktree;
4303
+ runtime.deps.resolveWorktree = (...args) => { probes++; return resolveWorktree(...args); };
4304
+ let gate: (() => Promise<void>) | undefined;
4305
+ let scans = 0;
4306
+ const registry = { list: async () => [], listActivations: async () => { scans++; await gate?.(); return [peer]; } };
4307
+ runtime.deps.agentHome = profile;
4308
+ runtime.deps.sessionTransport = {
4309
+ createRegistry: async () => registry,
4310
+ createListener: () => ({ registry, start: async () => { ready = true; }, close: async () => {} }),
4311
+ createClient: () => ({ close() {}, sendNotification: async () => { throw new Error("no messages expected"); } }),
4312
+ };
4313
+ gentleAgents(h.pi, {}, runtime.deps);
4314
+ const { ctx } = fakeContext();
4315
+ await h.fire("session_start", ctx);
4316
+ await eventually(() => ready, "discovery transport ready");
4317
+ ctx.ui.select = async () => { throw new Error("metadata consultation must not ask for consent"); };
4318
+ const result = await h.tools.get("orchestrator_list")!.execute("list", {}, undefined, undefined, ctx);
4319
+ assert.match(result.content[0].text, /peer.*Auth review.*recorded workspace: \/repo/);
4320
+ assert.match(result.content[0].text, /Check auth \[waiting\].*launch workspace: \/repo-child/);
4321
+ assert.match(result.content[0].text, /reachability is unknown/);
4322
+ assert.equal((result.details.gentleAgents as any).candidates[0].scope.host.root, "/repo");
4323
+ assert.equal((result.details.gentleAgents as any).candidates[0].scope.tasks[0].repository.root, "/repo-child");
4324
+ assert.match(result.content[0].text, /clone: [a-f0-9]{64}/);
4325
+ const cursor = (result.details.gentleAgents as any).candidates[0].catalog.cursor;
4326
+ const next = await h.tools.get("orchestrator_list")!.execute("next", { recipient_session_id: "peer", cursor }, undefined, undefined, ctx);
4327
+ assert.deepEqual((next.details.gentleAgents as any).candidates[0].catalog.tasks.map((t: any) => t.id), ["extra7", "extra8"]);
4328
+ assert.deepEqual((next.details.gentleAgents as any).candidates[0].catalog.registered, ["/registered/8", "/registered/9"]);
4329
+ assert.equal(h.userMessages.length, 0);
4330
+ const selectedWork = await h.tools.get("orchestrator_list")!.execute("selected-work", {
4331
+ filter: {}, recipient_session_id: "peer", cursor,
4332
+ }, undefined, undefined, ctx);
4333
+ assert.deepEqual(JSON.parse(selectedWork.content[0].text).matches.map((row: any) => row.taskId), ["extra8"]);
4334
+ const firstWorkPage = await h.tools.get("orchestrator_list")!.execute("first-work", {
4335
+ filter: {}, recipient_session_id: "peer",
4336
+ }, undefined, undefined, ctx);
4337
+ assert.deepEqual(JSON.parse(firstWorkPage.content[0].text).matches.map((row: any) => row.taskId), ["child"]);
4338
+ publisher.updateDiscovery(peer, { workspace: "/repo", tasks: [], state: {
4339
+ schema: 2, sessionId: "peer", cwd: "/repo", recordedAt: 1, source: "owner-curated",
4340
+ ownerReply: false, authority: "none", state: { progress: "Explicit summary", work: { area: "Auth" } },
4341
+ } });
4342
+ const noted = await h.tools.get("orchestrator_list")!.execute("note", { recipient_session_id: "peer" }, undefined, undefined, ctx);
4343
+ assert.match(noted.content[0].text, /Explicit summary/);
4344
+ assert.equal((noted.details.gentleAgents as any).candidates[0].state.recordedAt, 1);
4345
+ assert.deepEqual((noted.details.gentleAgents as any).candidates[0].state.state.work, { area: "Auth" });
4346
+ const list = h.tools.get("orchestrator_list")!;
4347
+ const workResult = await list.execute("work", { filter: {} }, undefined, undefined, ctx);
4348
+ const work = JSON.parse(workResult.content[0].text);
4349
+ assert.deepEqual(JSON.parse(JSON.stringify((workResult.details.gentleAgents as any).workSearch)), work);
4350
+ assert.equal(work.schema, 1);
4351
+ assert.deepEqual(work.matches[0].work, { area: "Auth" });
4352
+ assert.equal(work.coverage.exhaustive, false);
4353
+ assert.doesNotMatch(workResult.content[0].text, /Explicit summary|endpoint|activation|cursor|capabilities/);
4354
+ const defaultList = await list.execute("default", {}, undefined, undefined, ctx);
4355
+ assert.doesNotMatch(defaultList.content[0].text, /Explicit summary|"work"/);
4356
+ assert.equal((defaultList.details.gentleAgents as any).candidates[0].state, undefined);
4357
+ const beforeInvalid = scans;
4358
+ for (const invalid of [null, [], { unexpected: true }, { filter: null }, { filter: { topic: "Login" } },
4359
+ { filter: { area: 1 } }, { filter: { area: "é".repeat(33) } }, { filter: { text: "bad\u0000text" } },
4360
+ { filter: { ref: { kind: "issue", repository: "github.com/A/B", id: "01" } } },
4361
+ { filter: { related_to: { session_id: "peer", extra: true } } }]) {
4362
+ await assert.rejects(list.execute("invalid", invalid, undefined, undefined, ctx), /Invalid orchestrator list/);
4363
+ }
4364
+ for (const args of [{ cursor: "x" }, { filter: {}, cursor: "x" }]) {
4365
+ const invalidCursor = await list.execute("cursor", args, undefined, undefined, ctx);
4366
+ assert.equal(invalidCursor.details.error, "invalid-cursor");
4367
+ assert.equal(invalidCursor.content[0].text, "Error: cursor requires recipient_session_id.");
4368
+ }
4369
+ assert.equal(scans, beforeInvalid, "invalid arguments never reach peer/profile discovery");
4370
+ const consult = h.tools.get("orchestrator_consult")!;
4371
+ const probesBeforeConsult = probes;
4372
+ const receipt = JSON.parse((await consult.execute("consult", { recipient_session_id: "peer" }, undefined, undefined, ctx)).content[0].text);
4373
+ assert.equal(receipt.snapshot.state.state.progress, "Explicit summary");
4374
+ assert.equal(receipt.snapshot.state.recordedAt, 1);
4375
+ assert.deepEqual(receipt.snapshot.state.state.work, { area: "Auth" });
4376
+ assert.equal(receipt.ownerReply, false);
4377
+ assert.equal(receipt.authority, "none");
4378
+ assert.equal(receipt.targetSessionId, "peer");
4379
+ assert.doesNotMatch(JSON.stringify(receipt), /endpoint|activation|prompt|thread/);
4380
+ for (const invalid of [{ recipient_session_id: "peer", kind: "reasoning" }, { recipient_session_id: "peer", question: "secret" }, {}]) {
4381
+ await assert.rejects(consult.execute("invalid", invalid, undefined, undefined, ctx), /Invalid metadata/);
4382
+ }
4383
+ assert.equal(probes, probesBeforeConsult);
4384
+ publisher.updateDiscovery(peer, { workspace: "/repo", tasks: [], state: {
4385
+ schema: 2, sessionId: "peer", cwd: "/repo", recordedAt: 2, source: "owner-curated",
4386
+ ownerReply: false, authority: "none", state: { work: { topic: "Missing area" } },
4387
+ } });
4388
+ const malformed = await h.tools.get("orchestrator_list")!.execute("malformed", { recipient_session_id: "peer" }, undefined, undefined, ctx);
4389
+ assert.equal((malformed.details.gentleAgents as any).candidates[0].sessionId, "peer");
4390
+ assert.equal((malformed.details.gentleAgents as any).candidates[0].state, undefined);
4391
+ assert.ok(readActivity(profile, listPresence(profile).entries[0]).activity);
4392
+ publisher.updateDiscovery(peer, { workspace: "/repo", tasks: [] });
4393
+ const legacy = await h.tools.get("orchestrator_list")!.execute("legacy", {}, undefined, undefined, ctx);
4394
+ assert.match(legacy.content[0].text, /repository: unknown/);
4395
+ assert.equal((legacy.details.gentleAgents as any).candidates[0].sessionId, "peer");
4396
+ let release!: () => void;
4397
+ gate = () => new Promise<void>(resolve => { release = resolve; });
4398
+ const pending = consult.execute("pending", { recipient_session_id: "peer" }, undefined, undefined, ctx);
4399
+ await h.fire("session_shutdown", ctx);
4400
+ release();
4401
+ assert.equal(JSON.parse((await pending).content[0].text).status, "unavailable");
4402
+ assert.equal(runtime.spawned.length, 0);
4403
+ assert.equal(h.sent.length, 0);
4404
+ assert.equal(h.userMessages.length, 0);
4405
+ await h.fire("session_shutdown", ctx);
4406
+ } finally { publisher.dispose(); }
4407
+ });
4408
+
4409
+ test("registered reasoning and revocation use live SDK host and published source only", async () => {
4410
+ const h = fakePi(), runtime = deps();
4411
+ const profile = realpathSync(mkdtempSync(join(root, "reasoning-runtime-")));
4412
+ const peer = { version: 1 as const, sessionId: "peer", endpoint: "/fixture/peer.sock", createdAt: 1 };
4413
+ const publisher = PresencePublisher.start({ profile, sessionId: "peer", label: "Published peer", activity: [] });
4414
+ const publish = (progress = "Recorded") => publisher.updateDiscovery(peer, { workspace: "/repo", tasks: [], state: {
4415
+ schema: 1, sessionId: "peer", cwd: "/repo", recordedAt: 1, source: "owner-curated",
4416
+ ownerReply: false, authority: "none", state: { progress },
4417
+ } });
4418
+ publish(); let ready = false, dialogs = 0, calls = 0, choice = "Decline";
4419
+ let complete: (() => void) | undefined, hang = false;
4420
+ let peers = [peer];
4421
+ let duringDialog: (() => Promise<void> | void) | undefined;
4422
+ const registry = { list: async () => [], listActivations: async () => peers };
4423
+ runtime.deps.agentHome = profile;
4424
+ runtime.deps.sessionTransport = {
4425
+ createRegistry: async () => registry,
4426
+ createListener: () => ({ registry, start: async () => { ready = true; }, close: async () => {} }),
4427
+ createClient: () => ({ close() {}, sendNotification: async () => { throw Error("no owner message"); } }),
4428
+ };
4429
+ gentleAgents(h.pi, {}, runtime.deps);
4430
+ const { ctx } = fakeContext();
4431
+ const answer = { role: "assistant", api: "fixture", provider: "fixture", model: "local", timestamp: 1,
4432
+ stopReason: "stop", content: [{ type: "text", text: "Published advice" }], usage: {
4433
+ input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2,
4434
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } } as AssistantMessage;
4435
+ Object.assign(ctx, { model: { id: "local", provider: "fixture", maxTokens: 1024 }, modelRegistry: {
4436
+ streamSimple(_model: unknown, context: { tools: unknown[]; messages: unknown[] }, options: { maxRetries: number }) {
4437
+ calls++; assert.deepEqual(context.tools, []); assert.equal(context.messages.length, 1);
4438
+ assert.equal(options.maxRetries, 0);
4439
+ const stream = createAssistantMessageEventStream();
4440
+ stream.result = hang ? () => new Promise(resolve => { complete = () => resolve(answer); }) : async () => answer;
4441
+ return stream;
4442
+ },
4443
+ } });
4444
+ // Test-simulated supported UI choices, NOT evidence of actual human approval.
4445
+ ctx.ui.select = async (title, options) => {
4446
+ dialogs++; assert.match(title, /Model-cost permission only/);
4447
+ assert.deepEqual(options, ["Allow once", "Allow this target + model for this session", "Decline"]);
4448
+ await duringDialog?.(); return choice;
4449
+ };
4450
+ try {
4451
+ await h.fire("session_start", ctx); await eventually(() => ready, "reasoning transport ready");
4452
+ const tool = h.tools.get("orchestrator_consult")!;
4453
+ const run = async (kind = "reasoning", patch = {}, caller = ctx, signal?: AbortSignal) => JSON.parse((await tool.execute("c",
4454
+ { recipient_session_id: "peer", kind, ...(kind === "reasoning" ? { question: "What is published?" } : {}), ...patch }, signal, undefined, caller)).content[0].text);
4455
+ assert.equal((await run("metadata")).status, "available"); assert.deepEqual([dialogs, calls], [0, 0]);
4456
+ assert.equal((await run()).code, "permission-required"); assert.deepEqual([dialogs, calls], [1, 0]);
4457
+ choice = "Allow once"; const advice = await run();
4458
+ assert.equal(advice.source, "helper_advice"); assert.equal(advice.ownerReply, false); assert.equal(advice.authority, "none");
4459
+ assert.equal(advice.requestCaps.maxTokens, 512); assert.equal(advice.usage.totalTokens, 2);
4460
+ assert.deepEqual(advice.actualModel, { provider: "fixture", id: "local" }); assert.deepEqual([dialogs, calls], [2, 1]);
4461
+ choice = "Allow this target + model for this session"; await run();
4462
+ publisher.updateDiscovery(peer, { workspace: "/updated-public", tasks: [] }); await run();
4463
+ assert.deepEqual([dialogs, calls], [3, 3]);
4464
+ Object.assign(ctx, { hasUI: false });
4465
+ assert.equal((await run("revoke-reasoning")).status, "revoked");
4466
+ assert.deepEqual([dialogs, calls], [3, 3]); Object.assign(ctx, { hasUI: true });
4467
+ choice = "Decline"; assert.equal((await run()).code, "permission-required");
4468
+ for (const patch of [{ hasUI: false }, { mode: "print" }, { mode: "json" }]) {
4469
+ Object.assign(ctx, patch); assert.equal((await run()).code, "permission-required");
4470
+ }
4471
+ Object.assign(ctx, { hasUI: true, mode: "rpc" }); choice = "Allow once";
4472
+ assert.equal((await run()).status, "available");
4473
+ const before = [dialogs, calls];
4474
+ for (const args of [{ question: "implicit" }, { kind: "reasoning" }, { kind: "revoke-reasoning", cursor: "x" },
4475
+ { kind: "metadata", question: "irrelevant" }, { kind: "reasoning", question: "é".repeat(513) },
4476
+ { kind: null }, { kind: "unknown" }, { cursor: "x".repeat(1025) }, { unexpected: true }]) {
4477
+ await assert.rejects(tool.execute("bad", { recipient_session_id: "peer", ...args }, undefined, undefined, ctx), /Invalid metadata/);
4478
+ }
4479
+ assert.deepEqual([dialogs, calls], before);
4480
+ choice = "Allow this target + model for this session"; await run();
4481
+ for (const event of ["session_tree", "resources_discover", "session_before_switch", "session_before_fork", "session_before_tree", "model_select", "session_start"]) {
4482
+ await h.fire(event, ctx); choice = "Decline";
4483
+ assert.equal((await run()).code, "permission-required");
4484
+ choice = "Allow this target + model for this session"; await run();
4485
+ }
4486
+ await run("revoke-reasoning"); choice = "Allow once"; hang = true;
4487
+ for (const change of ["public", "activation", "unavailable", "private", "abort", "revoke"]) {
4488
+ publish(); peers = [peer]; const controller = new AbortController();
4489
+ const pending = run("reasoning", {}, ctx, controller.signal);
4490
+ await eventually(() => !!complete, "helper pending");
4491
+ if (change === "public") publish("Changed progress");
4492
+ if (change === "activation") peers = [{ ...peer, endpoint: "/fixture/replaced.sock" }];
4493
+ if (change === "unavailable") peers = [];
4494
+ if (change === "private") { publisher.update([]); publisher.refreshLabel(); }
4495
+ if (change === "abort") controller.abort();
4496
+ if (change === "revoke") await run("revoke-reasoning");
4497
+ complete!(); complete = undefined;
4498
+ const outcome = await pending;
4499
+ assert.equal(outcome.status, change === "private" ? "available" : "unavailable");
4500
+ }
4501
+ hang = false; peers = [peer];
4502
+ for (const change of [() => Object.assign(ctx, { model: { ...ctx.model! } }),
4503
+ () => publish("Changed after dialog"),
4504
+ () => h.fire("session_tree", ctx), () => run("revoke-reasoning"),
4505
+ () => h.fire("session_shutdown", ctx),
4506
+ () => h.fire("session_start", fakeContext().ctx, { reason: "new" })]) {
4507
+ await h.fire("session_start", ctx); await new Promise(resolve => setImmediate(resolve));
4508
+ publish(); duringDialog = async () => { await change(); }; const count = calls;
4509
+ assert.equal((await run()).status, "unavailable"); assert.equal(calls, count);
4510
+ }
4511
+ assert.equal((await run("metadata", {}, ctx)).status, "unavailable");
4512
+ assert.equal(runtime.spawned.length, 0); assert.equal(h.sent.length, 0); assert.equal(h.userMessages.length, 0);
4513
+ } finally { await h.fire("session_shutdown", ctx); publisher.dispose(); }
4514
+ });
4515
+
3795
4516
  test("session transport adds host tools, forwards notifications, and closes on shutdown", async () => {
3796
4517
  const h = fakePi();
3797
4518
  const runtime = deps();
@@ -3799,7 +4520,7 @@ test("session transport adds host tools, forwards notifications, and closes on s
3799
4520
  let listenerStarts = 0;
3800
4521
  let listenerCloses = 0;
3801
4522
  let clientCloses = 0;
3802
- const registry = { list: async () => [{ sessionId: "peer", reachability: "unknown" }], listActivations: async () => [] };
4523
+ const registry = { list: async () => [{ sessionId: "peer", reachability: "unknown" }], listActivations: async () => [{ version: 1 as const, sessionId: "peer", endpoint: "/fixture/peer.sock", createdAt: 1 }] };
3803
4524
  runtime.deps.sessionTransport = {
3804
4525
  createRegistry: async () => registry,
3805
4526
  createListener: (_registry, _sessionId, received) => {
@@ -3818,10 +4539,20 @@ test("session transport adds host tools, forwards notifications, and closes on s
3818
4539
  assert.ok(h.tools.has("orchestrator_send_message"));
3819
4540
  assert.match((await h.tools.get("orchestrator_list")!.execute("list", {}, undefined, undefined, ctx)).content[0].text, /peer/);
3820
4541
  assert.ok(callback, "listener receives the inbound callback");
4542
+ Object.assign(ctx.sessionManager, { getSessionName: () => "Integration" });
3821
4543
  await callback!({ id: "message-1", senderSessionId: "peer", message: "\u001b[31mraw model content" });
3822
4544
  assert.equal(h.sent.at(-1)?.message.customType, "gentle-agents.orchestrator-message");
3823
4545
  assert.match(String(h.sent.at(-1)?.message.content), /\u001b\[31mraw model content/);
3824
4546
  assert.deepEqual(h.sent.at(-1)?.options, { deliverAs: "followUp", triggerTurn: true });
4547
+ const renderer = h.renderers.get("gentle-agents.orchestrator-message")!;
4548
+ const compact = renderer(h.sent.at(-1)!.message, { expanded: false }, plainTheme).render(80).join("\n");
4549
+ assert.match(compact, /Message received/);
4550
+ assert.match(compact, /🤖 Orchestrator → 🤖 Integration/);
4551
+ assert.match(compact, /raw model content/);
4552
+ assert.doesNotMatch(compact, /Session message from|correlation|message-1|\u001b/);
4553
+ const expanded = renderer(h.sent.at(-1)!.message, { expanded: true }, plainTheme).render(80).join("\n");
4554
+ assert.match(expanded, /message-1/);
4555
+ assert.match(expanded, /Sender session: peer/);
3825
4556
  await h.fire("session_shutdown", ctx);
3826
4557
  assert.equal(clientCloses, 1);
3827
4558
  assert.equal(listenerCloses, 1);
@@ -3877,6 +4608,7 @@ test("session transport selects a peer for outbound delivery and rejects stale c
3877
4608
  const { ctx, dialogs } = fakeContext();
3878
4609
  await h.fire("session_start", ctx);
3879
4610
  await eventually(() => callbacks.length === 1, "initial transport callback registration");
4611
+ Object.assign(ctx.sessionManager, { getSessionName: () => "Backend" });
3880
4612
  const result = await h.tools.get("orchestrator_send_message")!.execute("send", { message: "hello peer", reason: "because the peer needs an update" }, undefined, undefined, ctx);
3881
4613
  assert.deepEqual(dialogs, [
3882
4614
  "select:Select recipient orchestrator:Orchestrator alpha|Orchestrator beta",
@@ -3884,6 +4616,20 @@ test("session transport selects a peer for outbound delivery and rejects stale c
3884
4616
  ]);
3885
4617
  assert.deepEqual(sent, [{ recipient: "alpha", message: "hello peer", expectedActivation: records[0] }]);
3886
4618
  assert.match(result.content[0].text, /accepted for delivery; it is not a delivery or read receipt/);
4619
+ const tool = h.tools.get("orchestrator_send_message")!;
4620
+ assert.equal(tool.renderShell, "self", "do not nest the card in Pi's default tool box");
4621
+ const args = { message: "hello peer", reason: "because the peer needs an update" };
4622
+ const renderContext = { args, state: {}, expanded: false, isPartial: false };
4623
+ const call = (tool.renderCall as Function)(args, plainTheme, renderContext);
4624
+ const output = (tool.renderResult as Function)(result, { expanded: false }, plainTheme, renderContext);
4625
+ const compact = [...call.render(80), ...output.render(80)].join("\n");
4626
+ assert.match(compact, /Message queued/);
4627
+ assert.match(compact, /🤖 Backend → 🤖 Orchestrator/);
4628
+ assert.match(compact, /hello peer/);
4629
+ assert.doesNotMatch(compact, /accepted-1|Sender session:|Recipient session:|because the peer/);
4630
+ const expanded = (tool.renderResult as Function)(result, { expanded: true }, plainTheme, { ...renderContext, expanded: true }).render(80).join("\n");
4631
+ assert.match(expanded, /accepted-1/);
4632
+ assert.match(expanded, /not a delivery or read receipt/);
3887
4633
  const original = callbacks[0]!;
3888
4634
  (ctx.sessionManager as unknown as { getSessionId(): string }).getSessionId = () => "s2";
3889
4635
  await h.fire("session_start", ctx);
@@ -3893,6 +4639,17 @@ test("session transport selects a peer for outbound delivery and rejects stale c
3893
4639
  await h.fire("session_shutdown", ctx);
3894
4640
  });
3895
4641
 
4642
+ test("all orchestrator tools own compact and expanded card rendering", () => {
4643
+ const h = fakePi();
4644
+ gentleAgents(h.pi, {}, deps().deps);
4645
+ for (const name of ["orchestrator_session_id", "orchestrator_consult", "orchestrator_list", "orchestrator_send_message"]) {
4646
+ const tool = h.tools.get(name)!;
4647
+ assert.equal(tool.renderShell, "self", name);
4648
+ assert.equal(typeof tool.renderCall, "function", name);
4649
+ assert.equal(typeof tool.renderResult, "function", name);
4650
+ }
4651
+ });
4652
+
3896
4653
  // Issue #1364: user consent before cross-orchestrator communication
3897
4654
  test("orchestrator_send_message requires consent on explicit recipient ID and sends nothing when denied", async () => {
3898
4655
  const h = fakePi();
@@ -4143,10 +4900,166 @@ test("a background completion settling while the parent agent runs is delivered
4143
4900
  await fire("session_shutdown", ctx);
4144
4901
  });
4145
4902
 
4146
- // A direct custom-message turn (sendMessage + triggerTurn while idle) skips
4147
- // Pi's prompt lifecycle, so before_agent_start never runs and prompt-capture
4148
- // integrations such as the Claude bridge reject the turn. An idle parent must
4149
- // instead store the structured result durably and be woken by a user message.
4903
+ test("Bridge identity is durable, session-owned and registered once across session changes", async () => {
4904
+ const h = fakePi();
4905
+ const runtime = deps();
4906
+ gentleAgents(h.pi, {}, runtime.deps);
4907
+ const { ctx } = fakeContext();
4908
+ ctx.sessionManager.getEntries = () => h.entries as unknown as ReturnType<ExtensionContext["sessionManager"]["getEntries"]>;
4909
+ await h.fire("session_start", ctx);
4910
+ await h.tools.get("subagent_run")!.execute("one", { agent: "explore", task: "Wake identity", mode: "background" }, undefined, undefined, ctx);
4911
+ await tick();
4912
+ runtime.children[0].message({ id: "q1", kind: "query", message: "Question" });
4913
+ await tick();
4914
+ const wake = String(h.userMessages[0].content);
4915
+ const transform = h.transformers[0];
4916
+ const context = { messageType: "user" as const, isStreaming: false, availableWidth: 80 };
4917
+ assert.equal(transform(wake, context), "");
4918
+ assert.equal(h.entries.filter(entry => entry.customType === "gentle-agents.wake-identity").length, 1);
4919
+ await h.fire("session_start", ctx, { reason: "reload" });
4920
+ assert.equal(transform(wake, context), "", "reload reconstructs ownership");
4921
+ ctx.sessionManager.getSessionId = () => "other-session";
4922
+ await h.fire("session_start", ctx, { reason: "new" });
4923
+ assert.equal(transform(wake, context), wake, "another session cannot claim the old identity");
4924
+ ctx.sessionManager.getSessionId = () => "s1";
4925
+ await h.fire("session_start", ctx, { reason: "resume" });
4926
+ assert.equal(transform(wake, context), "");
4927
+ assert.equal(h.transformers.length, 1, "session changes do not register again");
4928
+ assert.equal(transform(`Quoted: ${wake}`, context), `Quoted: ${wake}`);
4929
+ assert.equal(transform(` ${wake}`, context), ` ${wake}`);
4930
+ await h.fire("session_shutdown", ctx);
4931
+ assert.equal(transform(wake, context), wake, "shutdown releases the old owner");
4932
+ });
4933
+
4934
+ for (const failure of ["missing-api", "persistence", "warning-ui"] as const) {
4935
+ test(`Bridge ${failure} fallback preserves continuation and flags visible wake`, async () => {
4936
+ const h = fakePi();
4937
+ const runtime = deps();
4938
+ if (failure !== "persistence") delete (h.pi as Partial<ExtensionAPI>).registerMarkdownTransformer;
4939
+ gentleAgents(h.pi, {}, runtime.deps);
4940
+ const { ctx, dialogs } = fakeContext();
4941
+ if (failure === "warning-ui") ctx.ui.notify = () => { throw new Error("UI unavailable"); };
4942
+ await h.fire("session_start", ctx);
4943
+ if (failure === "persistence") h.pi.appendEntry = () => { throw new Error("Persistence unavailable"); };
4944
+ await h.tools.get("subagent_run")!.execute("fallback", { agent: "explore", task: "Fallback", mode: "background" }, undefined, undefined, ctx);
4945
+ await tick();
4946
+ runtime.children[0].message({ id: "q1", kind: "query", message: "Question" });
4947
+ await tick();
4948
+ assert.equal(h.userMessages.length, 1);
4949
+ assert.equal(h.sent.length, 1, "payload is stored once despite compatibility fallback");
4950
+ assert.doesNotMatch(String(h.userMessages[0].content), /gentle-agents wake:/);
4951
+ if (failure !== "warning-ui") assert.ok(dialogs.some(message => message.includes("cannot hide Claude Bridge")));
4952
+ });
4953
+ }
4954
+
4955
+ for (const provider of ["openai", "anthropic", "custom-extension", undefined, "claude-bridge"]) {
4956
+ for (const kind of ["completion", "query"] as const) {
4957
+ test(`idle ${kind} wake uses the selected ${provider ?? "missing"} provider route`, async () => {
4958
+ const h = fakePi();
4959
+ h.setProvider(provider);
4960
+ const harness = deps();
4961
+ gentleAgents(h.pi, {}, harness.deps);
4962
+ const { ctx } = fakeContext();
4963
+ await h.fire("session_start", ctx);
4964
+ await h.tools.get("subagent_run")!.execute("c1", { agent: "explore", task: "Route wake", mode: "background" }, undefined, undefined, ctx);
4965
+ await tick();
4966
+ if (kind === "query") harness.children[0].message({ id: "q1", kind: "query", message: "Child payload" });
4967
+ else {
4968
+ harness.children[0].emit({ type: "agent_end", messages: [{ role: "assistant", content: [{ type: "text", text: "Child payload" }] }] });
4969
+ harness.children[0].emit({ type: "agent_settled" });
4970
+ }
4971
+ await tick();
4972
+ assert.deepEqual(h.sent[0]!.options, { triggerTurn: false });
4973
+ assert.match(String(h.sent[0]!.message.content), /Child payload/);
4974
+ if (provider === "claude-bridge") {
4975
+ assert.equal(h.sent.length, 1);
4976
+ assert.equal(h.userMessages.length, 1);
4977
+ assert.match(String(h.userMessages[0].content), /\[gentle-agents wake: [0-9a-f-]+\]$/);
4978
+ assert.deepEqual(h.userMessages[0].options, { deliverAs: "steer" });
4979
+ assert.equal(h.transformers[0](String(h.userMessages[0].content), { messageType: "user", isStreaming: false, availableWidth: 80 }), "");
4980
+ assert.equal(h.delivery.at(-1), "user");
4981
+ } else {
4982
+ assert.equal(h.userMessages.length, 0, "native and unclassified providers never receive a synthetic user turn");
4983
+ assert.equal(h.sent.length, 2, "the stored payload still gets a continuation turn");
4984
+ assert.deepEqual(h.sent[1]!.options, { deliverAs: "steer", triggerTurn: true });
4985
+ assert.equal(h.sent[1]!.message.display, false);
4986
+ assert.equal(h.sent[1]!.message.customType, "gentle-agents.wake");
4987
+ assert.equal(h.sent[1]!.message.content, "Review the delivered subagent output and continue.");
4988
+ assert.deepEqual(h.delivery, [`custom:gentle-agents.${kind === "query" ? "message" : "result"}`, "custom:gentle-agents.wake"]);
4989
+ }
4990
+ await h.fire("session_shutdown", ctx);
4991
+ });
4992
+ }
4993
+ }
4994
+
4995
+ for (const [from, to] of [["openai", "claude-bridge"], ["claude-bridge", "openai"]]) {
4996
+ test(`wake reads the live provider after storage: ${from} to ${to}`, async () => {
4997
+ const h = fakePi(from);
4998
+ const harness = deps();
4999
+ gentleAgents(h.pi, {}, harness.deps);
5000
+ const { ctx } = fakeContext();
5001
+ await h.fire("session_start", ctx);
5002
+ await h.tools.get("subagent_run")!.execute("c1", { agent: "explore", task: "Switch before dispatch", mode: "background" }, undefined, undefined, ctx);
5003
+ await tick();
5004
+ const sendMessage = h.pi.sendMessage;
5005
+ Object.assign(h.pi, { sendMessage: (...args: Parameters<ExtensionAPI["sendMessage"]>) => {
5006
+ sendMessage(...args);
5007
+ // Storage happens synchronously, dispatch in the queued microtask.
5008
+ if (args[0].customType === "gentle-agents.message") h.setProvider(to);
5009
+ } });
5010
+ harness.children[0].message({ id: "q1", kind: "query", message: "Switch?" });
5011
+ await tick();
5012
+ assert.equal(h.userMessages.length, to === "claude-bridge" ? 1 : 0);
5013
+ assert.equal(h.sent.filter((entry) => entry.message.customType === "gentle-agents.wake").length, to === "openai" ? 1 : 0);
5014
+ await h.fire("session_shutdown", ctx);
5015
+ });
5016
+ }
5017
+
5018
+ for (const boundary of ["session_compact", "session_compact_failed"] as const) {
5019
+ test(`native wake preserves holds, coalescing and grace after ${boundary}`, async () => {
5020
+ const h = fakePi("openai");
5021
+ const harness = deps();
5022
+ const timers = recordTimers(harness.deps);
5023
+ gentleAgents(h.pi, {}, harness.deps);
5024
+ const { ctx } = fakeContext();
5025
+ await h.fire("session_start", ctx);
5026
+ for (const task of ["Ask", "Finish"]) await h.tools.get("subagent_run")!.execute(task, { agent: "explore", task, mode: "background" }, undefined, undefined, ctx);
5027
+ await tick();
5028
+ h.setIdle(false);
5029
+ harness.children[0].message({ id: "q1", kind: "query", message: "Held question" });
5030
+ harness.children[1].emit({ type: "agent_settled" });
5031
+ await tick();
5032
+ assert.equal(h.sent.length, 0);
5033
+ await h.fire(boundary, ctx);
5034
+ assert.equal(h.sent.length, 0);
5035
+ h.setIdle(true);
5036
+ assert.equal(timers.run(0), 1);
5037
+ await tick();
5038
+ assert.deepEqual(h.delivery, ["custom:gentle-agents.message", "custom:gentle-agents.result", "custom:gentle-agents.wake"]);
5039
+ assert.deepEqual(h.sent.map((entry) => entry.options), [{ triggerTurn: false }, { triggerTurn: false }, { deliverAs: "steer", triggerTurn: true }]);
5040
+ const expireWakeGrace = timers.takeLast(PARENT_WAKE_GRACE_MS);
5041
+ harness.children[0].message({ id: "q2", kind: "query", message: "Later question" });
5042
+ await tick();
5043
+ assert.equal(h.sent.length, 4, "content arriving in the grace window shares the pending wake");
5044
+ expireWakeGrace();
5045
+ await tick();
5046
+ assert.equal(h.sent.length, 5, "an unstarted wake cannot suppress new content beyond grace");
5047
+ assert.equal(h.sent[4]!.message.display, false);
5048
+ assert.deepEqual(h.sent[4]!.options, { deliverAs: "steer", triggerTurn: true });
5049
+ await h.fire("agent_start", ctx);
5050
+ harness.children[0].message({ id: "q3", kind: "query", message: "Busy question" });
5051
+ await tick();
5052
+ assert.equal(h.sent.length, 5, "busy content stays queued until the turn boundary");
5053
+ await h.fire("turn_end", ctx);
5054
+ assert.equal(h.sent.at(-1)!.message.customType, "gentle-agents.message");
5055
+ assert.deepEqual(h.sent.at(-1)!.options, { deliverAs: "steer", triggerTurn: true }, "busy native delivery keeps the original steering route");
5056
+ assert.equal(h.userMessages.length, 0);
5057
+ await h.fire("session_shutdown", ctx);
5058
+ });
5059
+ }
5060
+
5061
+ // Bridge custom-message turns skip the prompt lifecycle needed for capture.
5062
+ // Store the structured result durably and wake the bridge by a user message.
4150
5063
  test("an idle parent stores the structured completion and is woken through the normal prompt lifecycle", async () => {
4151
5064
  const { pi, tools, fire, sent, userMessages, delivery, renderers } = fakePi();
4152
5065
  const harness = deps();
@@ -4390,7 +5303,7 @@ test("a stale parent context fails closed: child completions and notifications a
4390
5303
  await fire("session_shutdown", ctx);
4391
5304
  });
4392
5305
 
4393
- test("a completion held past the stale window becomes transcript-only content and never re-enters the conversation", async () => {
5306
+ test("a completion held past the stale window keeps its report out of the conversation and shows the human a stale card", async () => {
4394
5307
  const { pi, tools, fire, sent, entries, entryRenderers } = fakePi();
4395
5308
  const harness = deps();
4396
5309
  let clock = 1000;
@@ -4419,6 +5332,171 @@ test("a completion held past the stale window becomes transcript-only content an
4419
5332
  await fire("session_shutdown", ctx);
4420
5333
  });
4421
5334
 
5335
+ // Issue #1821/#1092: the parent is told never to poll, so an unread stale
5336
+ // completion must still tell the model a result is waiting, without replaying
5337
+ // the report itself.
5338
+ test("an unread completion held past the stale window steers a compact notice into the running parent", async () => {
5339
+ const { pi, tools, fire, sent } = fakePi();
5340
+ const harness = deps();
5341
+ let clock = 1000;
5342
+ harness.deps.now = () => clock;
5343
+ gentleAgents(pi, {}, harness.deps);
5344
+ const { ctx } = fakeContext();
5345
+ await fire("session_start", ctx);
5346
+ const started = await tools.get("subagent_run")!.execute("c1", { agent: "explore", task: "Long tool call", mode: "background" }, undefined, undefined, ctx);
5347
+ const id = (started.details.gentleAgents as { taskId: string }).taskId;
5348
+ await tick();
5349
+ await fire("agent_start", ctx);
5350
+ harness.children[0].emit({ type: "agent_end", messages: [{ role: "assistant", content: [{ type: "text", text: "Late answer." }] }] });
5351
+ harness.children[0].emit({ type: "agent_settled" });
5352
+ await tick();
5353
+ clock += STALE_COMPLETION_MS + 1_000;
5354
+ await fire("turn_end", ctx);
5355
+ const notices = sent.filter((entry) => entry.message.customType === "gentle-agents.stale-notice");
5356
+ assert.equal(notices.length, 1, "the model is told once that an unread result is waiting");
5357
+ assert.deepEqual(notices[0]!.options, { deliverAs: "steer", triggerTurn: true });
5358
+ const content = String(notices[0]!.message.content);
5359
+ assert.match(content, new RegExp(id));
5360
+ assert.match(content, /subagent_result/);
5361
+ assert.doesNotMatch(content, /Late answer\./, "the stale report itself is never replayed");
5362
+ assert.equal(sent.filter((entry) => entry.message.customType === "gentle-agents.result").length, 0);
5363
+ await fire("turn_end", ctx);
5364
+ assert.equal(sent.filter((entry) => entry.message.customType === "gentle-agents.stale-notice").length, 1, "the notice is sent at most once");
5365
+ await fire("session_shutdown", ctx);
5366
+ });
5367
+
5368
+ test("an unread stale completion flushed at an idle boundary stores its notice and wakes the parent", async () => {
5369
+ const { pi, tools, fire, sent, userMessages, setIdle } = fakePi();
5370
+ const harness = deps();
5371
+ let clock = 1000;
5372
+ harness.deps.now = () => clock;
5373
+ gentleAgents(pi, {}, harness.deps);
5374
+ const { ctx } = fakeContext();
5375
+ await fire("session_start", ctx);
5376
+ await tools.get("subagent_run")!.execute("c1", { agent: "explore", task: "Ends idle", mode: "background" }, undefined, undefined, ctx);
5377
+ await tick();
5378
+ await fire("agent_start", ctx);
5379
+ harness.children[0].emit({ type: "agent_end", messages: [{ role: "assistant", content: [{ type: "text", text: "Late answer." }] }] });
5380
+ harness.children[0].emit({ type: "agent_settled" });
5381
+ await tick();
5382
+ clock += STALE_COMPLETION_MS + 1_000;
5383
+ setIdle(true);
5384
+ await fire("agent_end", ctx);
5385
+ await tick();
5386
+ const notices = sent.filter((entry) => entry.message.customType === "gentle-agents.stale-notice");
5387
+ assert.equal(notices.length, 1);
5388
+ assert.deepEqual(notices[0]!.options, { triggerTurn: false });
5389
+ assert.equal(userMessages.length, 1, "an idle parent is woken instead of waiting forever");
5390
+ await fire("session_shutdown", ctx);
5391
+ });
5392
+
5393
+ test("a completion whose forwarding throws stays queued and is delivered at the next boundary", async () => {
5394
+ const { pi, tools, fire, sent } = fakePi();
5395
+ const harness = deps();
5396
+ gentleAgents(pi, {}, harness.deps);
5397
+ const { ctx } = fakeContext();
5398
+ await fire("session_start", ctx);
5399
+ await tools.get("subagent_run")!.execute("c1", { agent: "explore", task: "Flaky host", mode: "background" }, undefined, undefined, ctx);
5400
+ await tick();
5401
+ await fire("agent_start", ctx);
5402
+ harness.children[0].emit({ type: "agent_end", messages: [{ role: "assistant", content: [{ type: "text", text: "Retried answer." }] }] });
5403
+ harness.children[0].emit({ type: "agent_settled" });
5404
+ await tick();
5405
+ const sendMessage = pi.sendMessage;
5406
+ Object.assign(pi, { sendMessage: () => { throw new Error("host busy"); } });
5407
+ await fire("turn_end", ctx);
5408
+ assert.equal(sent.length, 0);
5409
+ Object.assign(pi, { sendMessage });
5410
+ await fire("turn_end", ctx);
5411
+ const results = sent.filter((entry) => entry.message.customType === "gentle-agents.result");
5412
+ assert.equal(results.length, 1, "a failed forward is retried, not lost");
5413
+ assert.match(String(results[0]!.message.content), /Retried answer\./);
5414
+ await fire("turn_end", ctx);
5415
+ assert.equal(sent.filter((entry) => entry.message.customType === "gentle-agents.result").length, 1, "a delivered completion is never sent twice");
5416
+ await fire("session_shutdown", ctx);
5417
+ });
5418
+
5419
+ test("a completion whose forwarding throws while the parent is idle is retried after the bounded grace", async () => {
5420
+ const { pi, tools, fire, sent, userMessages } = fakePi();
5421
+ const harness = deps();
5422
+ const timers = recordTimers(harness.deps);
5423
+ gentleAgents(pi, {}, harness.deps);
5424
+ const { ctx } = fakeContext();
5425
+ await fire("session_start", ctx);
5426
+ await tools.get("subagent_run")!.execute("c1", { agent: "explore", task: "Idle flaky host", mode: "background" }, undefined, undefined, ctx);
5427
+ await tick();
5428
+ const sendMessage = pi.sendMessage;
5429
+ Object.assign(pi, { sendMessage: () => { throw new Error("host busy"); } });
5430
+ harness.children[0].emit({ type: "agent_end", messages: [{ role: "assistant", content: [{ type: "text", text: "Idle retried answer." }] }] });
5431
+ harness.children[0].emit({ type: "agent_settled" });
5432
+ await tick();
5433
+ assert.equal(sent.length, 0);
5434
+ assert.equal(userMessages.length, 0);
5435
+ Object.assign(pi, { sendMessage });
5436
+ // No turn boundary is coming for an idle parent, so the retry is a timer.
5437
+ assert.equal(timers.run(PARENT_WAKE_GRACE_MS), 1, "one bounded retry flush is armed");
5438
+ await tick();
5439
+ const results = sent.filter((entry) => entry.message.customType === "gentle-agents.result");
5440
+ assert.equal(results.length, 1, "the requeued completion reaches the idle parent");
5441
+ assert.match(String(results[0]!.message.content), /Idle retried answer\./);
5442
+ assert.equal(userMessages.length, 1, "and the idle parent is woken for it");
5443
+ // Only the dispatched wake's own grace remains; expiring it resends nothing.
5444
+ assert.equal(timers.run(PARENT_WAKE_GRACE_MS), 1);
5445
+ await tick();
5446
+ assert.equal(sent.length, 1, "a successful retry never delivers the completion twice");
5447
+ assert.equal(userMessages.length, 1);
5448
+ await fire("session_shutdown", ctx);
5449
+ });
5450
+
5451
+ test("retries for a failing idle delivery stop after the bounded limit", async () => {
5452
+ const { pi, tools, fire, sent, userMessages } = fakePi();
5453
+ const harness = deps();
5454
+ const timers = recordTimers(harness.deps);
5455
+ gentleAgents(pi, {}, harness.deps);
5456
+ const { ctx } = fakeContext();
5457
+ await fire("session_start", ctx);
5458
+ await tools.get("subagent_run")!.execute("c1", { agent: "explore", task: "Broken host", mode: "background" }, undefined, undefined, ctx);
5459
+ await tick();
5460
+ Object.assign(pi, { sendUserMessage: () => { throw new Error("host rejected prompt"); } });
5461
+ harness.children[0].emit({ type: "agent_end", messages: [{ role: "assistant", content: [{ type: "text", text: "done" }] }] });
5462
+ harness.children[0].emit({ type: "agent_settled" });
5463
+ await tick();
5464
+ let retries = 0;
5465
+ while (timers.run(PARENT_WAKE_GRACE_MS) > 0) {
5466
+ retries += 1;
5467
+ await tick();
5468
+ assert.ok(retries <= 3, "a permanently failing wake never retries forever");
5469
+ }
5470
+ assert.equal(retries, 3);
5471
+ assert.equal(sent.length, 1, "retries never store the completion twice");
5472
+ assert.equal(userMessages.length, 0);
5473
+ await fire("session_shutdown", ctx);
5474
+ });
5475
+
5476
+ test("a wake that throws stays owed and is retried after the bounded grace", async () => {
5477
+ const { pi, tools, fire, sent, userMessages } = fakePi();
5478
+ const harness = deps();
5479
+ const timers = recordTimers(harness.deps);
5480
+ gentleAgents(pi, {}, harness.deps);
5481
+ const { ctx } = fakeContext();
5482
+ await fire("session_start", ctx);
5483
+ await tools.get("subagent_run")!.execute("c1", { agent: "explore", task: "Lost wake", mode: "background" }, undefined, undefined, ctx);
5484
+ await tick();
5485
+ const sendUserMessage = pi.sendUserMessage;
5486
+ Object.assign(pi, { sendUserMessage: () => { throw new Error("host rejected prompt"); } });
5487
+ harness.children[0].emit({ type: "agent_end", messages: [{ role: "assistant", content: [{ type: "text", text: "done" }] }] });
5488
+ harness.children[0].emit({ type: "agent_settled" });
5489
+ await tick();
5490
+ assert.equal(sent.length, 1, "the completion is stored before the wake fails");
5491
+ assert.equal(userMessages.length, 0);
5492
+ Object.assign(pi, { sendUserMessage });
5493
+ assert.equal(timers.run(PARENT_WAKE_GRACE_MS), 1, "one bounded retry is armed");
5494
+ await tick();
5495
+ assert.equal(userMessages.length, 1, "the idle parent is finally woken");
5496
+ assert.equal(sent.length, 1, "the retry wakes without storing the completion again");
5497
+ await fire("session_shutdown", ctx);
5498
+ });
5499
+
4422
5500
  test("a completion the parent already pulled is dropped silently at the next turn end", async () => {
4423
5501
  const { pi, tools, fire, sent } = fakePi();
4424
5502
  const harness = deps();
@@ -4660,7 +5738,10 @@ test("issue #1162: task-mode subagent_run includes question directly in waiting
4660
5738
  test("children receive context and safety extensions, and missing files are omitted", async () => {
4661
5739
  const expected = join(dirname(fileURLToPath(import.meta.url)), "..", "extensions", "child-context.ts");
4662
5740
  const safety = join(dirname(fileURLToPath(import.meta.url)), "..", "extensions", "child-safety.ts");
4663
- assert.deepEqual(childContextExtensionPaths(), [resolve(expected), resolve(safety)]);
5741
+ // gentle-shell#1731 T32: the nan provider is registered by a gentle-pi
5742
+ // extension, so a child routed to nan/* could not resolve its model.
5743
+ const nanProvider = join(dirname(fileURLToPath(import.meta.url)), "..", "extensions", "nan-provider.ts");
5744
+ assert.deepEqual(childContextExtensionPaths(), [resolve(expected), resolve(safety), resolve(nanProvider)]);
4664
5745
  assert.deepEqual(childContextExtensionPaths(() => false), [], "a missing extension file fails safe to no --extension");
4665
5746
  const extensionArguments = (args: string[]) => args.filter((_, index) => args[index - 1] === "--extension");
4666
5747
  for (const scenario of ["present", "missing"] as const) {
@@ -4674,10 +5755,592 @@ test("children receive context and safety extensions, and missing files are omit
4674
5755
  await h.tools.get("subagent_run")!.execute(`child-context-${scenario}`, { agent: "explore", task: "Map", mode: "background" }, undefined, undefined, ctx);
4675
5756
  await tick();
4676
5757
  assert.equal(runtime.spawned.length, 1);
4677
- assert.deepEqual(extensionArguments(runtime.spawned[0]!), scenario === "present" ? [resolve(expected), resolve(safety)] : []);
5758
+ assert.deepEqual(extensionArguments(runtime.spawned[0]!), scenario === "present" ? [resolve(expected), resolve(safety), resolve(nanProvider)] : []);
5759
+ } finally {
5760
+ await h.fire("session_shutdown", ctx);
5761
+ await tick();
5762
+ }
5763
+ }
5764
+ });
5765
+
5766
+ // gentle-shell#1713 (review R3-001): prove the subagent_continue wiring end to
5767
+ // end, not only the helper. A writer follow-up without its own section reaches
5768
+ // the child with the surfaces its original launch was admitted with.
5769
+ test("a writer continuation without its own section inherits the admitted surfaces end to end", async () => {
5770
+ const h = fakePi();
5771
+ const runtime = deps();
5772
+ const profile = mkdtempSync(join(tmpdir(), "gentle-agents-continue-"));
5773
+ mkdirSync(join(profile, "agents"), { recursive: true });
5774
+ writeFileSync(join(profile, "agents", "gentle-ai-worker.md"), readFileSync(new URL("../assets/agents/gentle-ai-worker.md", import.meta.url)));
5775
+ writeFileSync(join(profile, "subagents.json"), JSON.stringify({ model_profiles: { "gentle-ai-worker": { model: "openai/gpt-4o", effort: "high" } } }));
5776
+ const env: NodeJS.ProcessEnv = {};
5777
+ gentleAgents(h.pi, env, { ...runtime.deps, env, agentHome: profile });
5778
+ const { ctx } = fakeContext();
5779
+ await h.fire("session_start", ctx);
5780
+ const launched = h.tools.get("subagent_run")!.execute("run", { agent: "gentle-ai-worker", task: "Do T2.\n\n## Allowed edit surfaces\n- src/app.ts\n- `docs/with space.md`\n\n## Return\nReport", mode: "task" }, undefined, undefined, ctx);
5781
+ await tick();
5782
+ runtime.children[0].emit({ type: "agent_end", messages: [{ role: "assistant", content: [{ type: "text", text: "partial" }] }] });
5783
+ runtime.children[0].emit({ type: "agent_settled" });
5784
+ const taskId = ((await launched).details.gentleAgents as { taskId: string }).taskId;
5785
+ const continued = h.tools.get("subagent_continue")!.execute("follow", { task_id: taskId, prompt: "Continue with the remaining specs.", mode: "task" }, undefined, undefined, ctx);
5786
+ await tick();
5787
+ assert.equal(runtime.children.length, 2, "the continuation is admitted instead of rejected");
5788
+ const prompt = String(runtime.children[1].written.find(frame => typeof frame.message === "string")?.message);
5789
+ assert.match(prompt, /^Continue with the remaining specs\.\n\n## Allowed edit surfaces\n`docs\/with space\.md`\n`src\/app\.ts`\n/);
5790
+ runtime.children[1].emit({ type: "agent_end", messages: [{ role: "assistant", content: [{ type: "text", text: "done" }] }] });
5791
+ runtime.children[1].emit({ type: "agent_settled" });
5792
+ await continued;
5793
+ await h.fire("session_shutdown", ctx);
5794
+ rmSync(profile, TEST_DIR_REMOVAL);
5795
+ });
5796
+
5797
+ // #1690: the launcher's injection signal in the host env replaces the curated
5798
+ // child entries; without a valid signal children keep the curated entries.
5799
+ test("children receive the launcher's package injection instead of the curated entries", async () => {
5800
+ const curated = ["/curated/child-context.ts", "/curated/child-safety.ts"];
5801
+ const takeover = ["/agent/npm/node_modules/other", "/agent/extensions/a b.ts", "/pkg"];
5802
+ const scenarios: Array<{ name: string; value: string | undefined; expected: string[] }> = [
5803
+ { name: "takeover", value: encodeChildPackageInjection({ noExtensions: true, extensionPaths: takeover }), expected: ["--no-extensions", ...takeover.flatMap((path) => ["--extension", path])] },
5804
+ { name: "package-root", value: encodeChildPackageInjection({ noExtensions: false, extensionPaths: ["/pkg"] }), expected: ["--extension", "/pkg"] },
5805
+ { name: "absent", value: undefined, expected: curated.flatMap((path) => ["--extension", path]) },
5806
+ { name: "malformed", value: JSON.stringify({ version: 1, noExtensions: true, extensionPaths: ["relative/pkg"] }), expected: curated.flatMap((path) => ["--extension", path]) },
5807
+ ];
5808
+ for (const scenario of scenarios) {
5809
+ const h = fakePi();
5810
+ const runtime = deps();
5811
+ runtime.deps.childExtensionPaths = curated;
5812
+ runtime.deps.env = { PATH: "/bin", ...(scenario.value === undefined ? {} : { [CHILD_PACKAGE_INJECTION_ENV]: scenario.value }) };
5813
+ gentleAgents(h.pi, {}, runtime.deps);
5814
+ const { ctx } = fakeContext();
5815
+ await h.fire("session_start", ctx);
5816
+ try {
5817
+ await h.tools.get("subagent_run")!.execute(`injection-${scenario.name}`, { agent: "explore", task: "Map", mode: "background" }, undefined, undefined, ctx);
5818
+ await tick();
5819
+ assert.equal(runtime.spawned.length, 1, scenario.name);
5820
+ const argv = runtime.spawned[0]!;
5821
+ const start = argv.indexOf("--session-dir") + 2;
5822
+ assert.deepEqual(argv.slice(start, start + scenario.expected.length), scenario.expected, scenario.name);
5823
+ assert.equal(argv[start + scenario.expected.length], "--model", `${scenario.name}: no other extension arguments`);
5824
+ assert.equal(argv[argv.indexOf("--tools") + 1], "read,grep,subagent_parent_message", scenario.name);
4678
5825
  } finally {
4679
5826
  await h.fire("session_shutdown", ctx);
4680
5827
  await tick();
4681
5828
  }
4682
5829
  }
4683
5830
  });
5831
+
5832
+ // gentle-shell#1731 T4 (S2, AC6): subagent_run and subagent_continue admit a
5833
+ // writer only while no live writer in the same worktree claims an overlapping
5834
+ // `## Allowed edit surfaces` entry; read-only agents are never registered.
5835
+ test("parallel writers are admitted only with disjoint Allowed edit surfaces end to end", async () => {
5836
+ const h = fakePi();
5837
+ const runtime = deps();
5838
+ const profile = mkdtempSync(join(tmpdir(), "gentle-agents-parallel-writers-"));
5839
+ mkdirSync(join(profile, "agents"), { recursive: true });
5840
+ writeFileSync(join(profile, "agents", "gentle-ai-worker.md"), readFileSync(new URL("../assets/agents/gentle-ai-worker.md", import.meta.url)));
5841
+ writeFileSync(join(profile, "agents", "explore.md"), "---\ndescription: maps things\ntools: [read, grep]\n---\nYou map things.");
5842
+ writeFileSync(join(profile, "subagents.json"), JSON.stringify({ max_concurrency: 5, model_profiles: { "gentle-ai-worker": { model: "openai/gpt-4o", effort: "high" } } }));
5843
+ const env: NodeJS.ProcessEnv = {};
5844
+ gentleAgents(h.pi, env, { ...runtime.deps, env, agentHome: profile });
5845
+ const { ctx } = fakeContext();
5846
+ await h.fire("session_start", ctx);
5847
+ const scoped = (surface: string) => `Write it.\n\n## Allowed edit surfaces\n${surface}\n\n## Return\nReport`;
5848
+ const run = (agent: string, task: string) => h.tools.get("subagent_run")!.execute("run", { agent, task, mode: "background" }, undefined, undefined, ctx);
5849
+ const taskId = (result: { details: Record<string, unknown> }) => (result.details.gentleAgents as { taskId: string }).taskId;
5850
+ const finish = async (child: FakeChild, id: string) => {
5851
+ child.emit({ type: "agent_end", messages: [{ role: "assistant", content: [{ type: "text", text: "done" }] }] });
5852
+ child.emit({ type: "agent_settled" });
5853
+ for (let attempt = 0; attempt < 40; attempt++) {
5854
+ const status = await h.tools.get("subagent_status")!.execute("status", { task_id: id }, undefined, undefined, ctx);
5855
+ if ((status.details.gentleAgents as { status?: string } | undefined)?.status === TASK_STATUS.COMPLETED) return;
5856
+ await tick();
5857
+ }
5858
+ assert.fail(`task ${id} never completed`);
5859
+ };
5860
+ try {
5861
+ const app = taskId(await run("gentle-ai-worker", scoped("src/app.ts")));
5862
+ const other = taskId(await run("gentle-ai-worker", scoped("`src/other.ts`")));
5863
+ await tick();
5864
+ assert.equal(runtime.children.length, 2, "disjoint writers run concurrently");
5865
+ await assert.rejects(run("gentle-ai-worker", scoped("src/*.ts")), (error: Error) => {
5866
+ assert.match(error.message, new RegExp(`task ${app}`));
5867
+ assert.match(error.message, new RegExp(`task ${other}`));
5868
+ assert.match(error.message, /`src\/\*\.ts` overlaps `src\/app\.ts`/);
5869
+ return true;
5870
+ });
5871
+ await run("explore", "Map src/app.ts and src/other.ts");
5872
+ await tick();
5873
+ assert.equal(runtime.children.length, 3, "read-only agents are never blocked by live writers");
5874
+ await finish(runtime.children[0], app);
5875
+ // The continuation inherits src/app.ts and is admitted again only while no
5876
+ // live writer claims an overlapping entry.
5877
+ await assert.rejects(run("gentle-ai-worker", scoped("src/**")), new RegExp(`task ${other}`), "src/** still overlaps the live src/other.ts writer");
5878
+ const blocking = taskId(await run("gentle-ai-worker", scoped("src/app.ts")));
5879
+ await assert.rejects(h.tools.get("subagent_continue")!.execute("follow", { task_id: app, prompt: "Continue.", mode: "background" }, undefined, undefined, ctx), new RegExp(`task ${blocking}`));
5880
+ await finish(runtime.children[3], blocking);
5881
+ await h.tools.get("subagent_continue")!.execute("follow", { task_id: app, prompt: "Continue.", mode: "background" }, undefined, undefined, ctx);
5882
+ await tick();
5883
+ assert.equal(runtime.children.length, 5, "the continuation is admitted once its surfaces are free");
5884
+ } finally {
5885
+ await h.fire("session_shutdown", ctx);
5886
+ rmSync(profile, TEST_DIR_REMOVAL);
5887
+ }
5888
+ });
5889
+
5890
+ // Second verify A1: writers claim surfaces under the canonical worktree root,
5891
+ // so a writer spawned in the session's subdirectory cwd and one sent to the
5892
+ // worktree root through workspace_root are compared.
5893
+ test("a subdirectory session cwd and workspace_root of the same worktree share one writer key", async () => {
5894
+ const h = fakePi();
5895
+ const runtime = deps();
5896
+ const profile = mkdtempSync(join(tmpdir(), "gentle-agents-writer-root-"));
5897
+ mkdirSync(join(profile, "agents"), { recursive: true });
5898
+ writeFileSync(join(profile, "agents", "gentle-ai-worker.md"), readFileSync(new URL("../assets/agents/gentle-ai-worker.md", import.meta.url)));
5899
+ writeFileSync(join(profile, "subagents.json"), JSON.stringify({ max_concurrency: 5, model_profiles: { "gentle-ai-worker": { model: "openai/gpt-4o", effort: "high" } } }));
5900
+ const sub = join(cwd, "sub");
5901
+ mkdirSync(sub, { recursive: true });
5902
+ // Git semantics: any path inside the project resolves to the project root.
5903
+ const resolveWorktree = (path: string, base: string) => {
5904
+ const target = resolve(base, path);
5905
+ return { root: target === cwd || target.startsWith(`${cwd}${sep}`) ? cwd : target, commonDir: "/fixture/common" };
5906
+ };
5907
+ const env: NodeJS.ProcessEnv = {};
5908
+ gentleAgents(h.pi, env, { ...runtime.deps, resolveWorktree, env, agentHome: profile });
5909
+ const { ctx } = fakeContext();
5910
+ Object.assign(ctx, { cwd: sub, sessionManager: { getSessionId: () => "s1", getCwd: () => sub, getEntries: () => [], getBranch: () => [] } });
5911
+ await h.fire("session_start", ctx);
5912
+ const task = "Write it.\n\n## Allowed edit surfaces\nsrc/app.ts\n\n## Return\nReport";
5913
+ try {
5914
+ const first = await h.tools.get("subagent_run")!.execute("run", { agent: "gentle-ai-worker", task, mode: "background" }, undefined, undefined, ctx);
5915
+ const firstId = (first.details.gentleAgents as { taskId: string }).taskId;
5916
+ await assert.rejects(h.tools.get("subagent_run")!.execute("run", { agent: "gentle-ai-worker", task, workspace_root: cwd, mode: "background" }, undefined, undefined, ctx), new RegExp(`task ${firstId}`));
5917
+ } finally {
5918
+ await h.fire("session_shutdown", ctx);
5919
+ rmSync(profile, TEST_DIR_REMOVAL);
5920
+ }
5921
+ });
5922
+
5923
+ // Background jobs share the subagent parent delivery router: the exit notice
5924
+ // is stored and woken like an idle completion, or steered into a running turn.
5925
+ function fakeJobShell() {
5926
+ const runs: Array<{ command: string; onData(data: Buffer): void; signal?: AbortSignal; exit(code: number): void }> = [];
5927
+ const shell = () => ({
5928
+ operations: {
5929
+ exec: (command: string, _cwd: string, options: { onData(data: Buffer): void; signal?: AbortSignal }) => new Promise<{ exitCode: number | null }>((done, fail) => {
5930
+ options.signal?.addEventListener("abort", () => fail(new Error("aborted")), { once: true });
5931
+ runs.push({ command, onData: options.onData, signal: options.signal, exit: (code) => done({ exitCode: code }) });
5932
+ }),
5933
+ },
5934
+ });
5935
+ const dir = mkdtempSync(join(tmpdir(), "gentle-jobs-agents-"));
5936
+ return { runs, shell, dir, cleanup: () => rmSync(dir, TEST_DIR_REMOVAL) };
5937
+ }
5938
+ // A job settles only after its log file closes, which takes real I/O turns.
5939
+ const jobIo = () => new Promise((done) => setTimeout(done, 50));
5940
+ const toolText = (result: { content: Array<{ text?: string }> }) => result.content.map((part) => part.text ?? "").join("\n");
5941
+
5942
+ test("standalone bash sleep is blocked only while background work is active (#1903)", async () => {
5943
+ const { pi, tools, fire, sent } = fakePi();
5944
+ const jobs = fakeJobShell();
5945
+ gentleAgents(pi, {}, { ...deps().deps, jobShell: jobs.shell, jobOutputDir: () => jobs.dir });
5946
+ const { ctx } = fakeContext();
5947
+ const call = async (toolName: string, command: string) =>
5948
+ (await fire("tool_call", ctx, { toolCallId: "t", toolName, input: { command } })).find((result) => result !== undefined) as { block?: boolean; reason?: string } | undefined;
5949
+ try {
5950
+ await fire("session_start", ctx);
5951
+ // Without background work, sleep is ordinary shell use.
5952
+ assert.equal(await call("bash", "sleep 10"), undefined);
5953
+
5954
+ await tools.get("bash_background")!.execute("b1", { command: "gh run watch 42 --exit-status", label: "CI" }, undefined, undefined, ctx);
5955
+ for (const command of ["sleep 10", " sleep 2m ", "sleep 0.5;", "sleep 5 && sleep 5"]) {
5956
+ const blocked = await call("bash", command);
5957
+ assert.equal(blocked?.block, true, command);
5958
+ assert.match(blocked!.reason!, /background work is active/);
5959
+ assert.match(blocked!.reason!, /End the turn/);
5960
+ }
5961
+ // Real wait conditions, mixed commands and the sanctioned background tools stay allowed.
5962
+ for (const command of ["until curl -s x; do sleep 1; done", "sleep 5 && gh run view 42", "for i in 1 2; do sleep 1; echo $i; done", "sleep $N"]) {
5963
+ assert.equal(await call("bash", command), undefined, command);
5964
+ }
5965
+ assert.equal(await call("bash_background", "sleep 100"), undefined);
5966
+ assert.equal(await call("monitor", "sleep 100"), undefined);
5967
+
5968
+ jobs.runs[0]!.exit(0);
5969
+ await eventually(() => sent.some((entry) => entry.message.customType === "gentle-jobs.notice"), "the job must settle before sleep is allowed again");
5970
+ assert.equal(await call("bash", "sleep 10"), undefined, "sleep is allowed again once background work settles");
5971
+ } finally {
5972
+ await fire("session_shutdown", ctx);
5973
+ jobs.cleanup();
5974
+ }
5975
+ });
5976
+
5977
+ test("bash_background returns at once, and an idle parent gets one stored exit notice and one wake", async () => {
5978
+ const { pi, tools, fire, sent, userMessages, delivery, renderers } = fakePi();
5979
+ const jobs = fakeJobShell();
5980
+ gentleAgents(pi, {}, { ...deps().deps, jobShell: jobs.shell, jobOutputDir: () => jobs.dir });
5981
+ const { ctx } = fakeContext();
5982
+ try {
5983
+ await fire("session_start", ctx);
5984
+ const started = toolText(await tools.get("bash_background")!.execute("b1", { command: "gh run watch 42 --exit-status", label: "CI" }, undefined, undefined, ctx));
5985
+ assert.match(started, /job-1/);
5986
+ assert.ok(started.includes(join(jobs.dir, "job-1.log")), "the output file path is returned");
5987
+ assert.match(started, /notified once/i);
5988
+ assert.equal(jobs.runs[0]!.command, "gh run watch 42 --exit-status");
5989
+ assert.equal(sent.length, 0, "nothing reaches the parent while the job runs");
5990
+ jobs.runs[0]!.onData(Buffer.from("check build: fail\n"));
5991
+ jobs.runs[0]!.exit(1);
5992
+ await eventually(
5993
+ () => sent.some((entry) => entry.message.customType === "gentle-jobs.notice") && userMessages.length > 0,
5994
+ "the closed job log must deliver its exit notice and wake before assertions",
5995
+ );
5996
+ const notices = sent.filter((entry) => entry.message.customType === "gentle-jobs.notice");
5997
+ assert.equal(notices.length, 1, "the exit is reported exactly once");
5998
+ assert.deepEqual(notices[0]!.options, { triggerTurn: false }, "an idle parent stores the notice without a direct turn");
5999
+ const content = String(notices[0]!.message.content);
6000
+ for (const expected of [/job-1/, /"CI"/, /exited with code 1/, /gh run watch 42 --exit-status/, /check build: fail/, /job-1\.log/]) assert.match(content, expected);
6001
+ assert.equal(userMessages.length, 1, "the idle parent is woken exactly once");
6002
+ assert.deepEqual(delivery, ["custom:gentle-jobs.notice", "user"], "the notice is stored before the wake");
6003
+ assert.match(renderers.get("gentle-jobs.notice")!(notices[0]!.message, { expanded: true }, plainTheme).render(70).map(stripAnsi).join("\n"), /exited with code 1/);
6004
+ await fire("turn_end", ctx);
6005
+ await fire("agent_settled", ctx);
6006
+ assert.equal(sent.length, 1, "later boundaries never replay the notice");
6007
+ assert.equal(userMessages.length, 1, "later boundaries never repeat the wake");
6008
+ } finally {
6009
+ await fire("session_shutdown", ctx);
6010
+ jobs.cleanup();
6011
+ }
6012
+ });
6013
+
6014
+ test("a busy parent gets the exit notice steered into its run at the next turn boundary", async () => {
6015
+ const { pi, tools, fire, sent, userMessages } = fakePi();
6016
+ const jobs = fakeJobShell();
6017
+ gentleAgents(pi, {}, { ...deps().deps, jobShell: jobs.shell, jobOutputDir: () => jobs.dir });
6018
+ const { ctx } = fakeContext();
6019
+ try {
6020
+ await fire("session_start", ctx);
6021
+ await fire("agent_start", ctx);
6022
+ await tools.get("bash_background")!.execute("b1", { command: "make build" }, undefined, undefined, ctx);
6023
+ jobs.runs[0]!.exit(0);
6024
+ await jobIo();
6025
+ assert.equal(sent.length, 0, "a busy parent is not interrupted mid-tool-call");
6026
+ await fire("turn_end", ctx);
6027
+ assert.equal(sent.length, 1);
6028
+ assert.deepEqual(sent[0]!.options, { deliverAs: "steer", triggerTurn: true });
6029
+ assert.match(String(sent[0]!.message.content), /job-1 \("make build"\) exited with code 0/);
6030
+ assert.equal(userMessages.length, 0, "a running parent needs no wake");
6031
+ } finally {
6032
+ await fire("session_shutdown", ctx);
6033
+ jobs.cleanup();
6034
+ }
6035
+ });
6036
+
6037
+ test("job_list and job_stop cover this session's jobs; stopped jobs send no notice and shutdown stops the rest", async () => {
6038
+ const { pi, tools, fire, sent } = fakePi();
6039
+ const jobs = fakeJobShell();
6040
+ gentleAgents(pi, {}, { ...deps().deps, jobShell: jobs.shell, jobOutputDir: () => jobs.dir });
6041
+ const { ctx } = fakeContext();
6042
+ try {
6043
+ await fire("session_start", ctx);
6044
+ assert.match(toolText(await tools.get("job_list")!.execute("l0", {}, undefined, undefined, ctx)), /No background jobs/);
6045
+ await tools.get("bash_background")!.execute("b1", { command: "sleep 100", label: "long" }, undefined, undefined, ctx);
6046
+ await tools.get("bash_background")!.execute("b2", { command: "npm run dev" }, undefined, undefined, ctx);
6047
+ const listed = toolText(await tools.get("job_list")!.execute("l1", {}, undefined, undefined, ctx));
6048
+ assert.match(listed, /job-1 · running · long/);
6049
+ assert.match(listed, /job-2 · running · npm run dev/);
6050
+ assert.match(toolText(await tools.get("job_stop")!.execute("s1", { job_id: "job-1" }, undefined, undefined, ctx)), /Stopped job-1/);
6051
+ assert.equal(jobs.runs[0]!.signal?.aborted, true, "the job's process tree is killed");
6052
+ await assert.rejects(async () => tools.get("job_stop")!.execute("s2", { job_id: "job-9" }, undefined, undefined, ctx), /No background job job-9 in this session/);
6053
+ await jobIo();
6054
+ assert.equal(sent.length, 0, "a stopped job sends no exit notice");
6055
+ assert.match(toolText(await tools.get("job_list")!.execute("l2", {}, undefined, undefined, ctx)), /job-1 · stopped · long/);
6056
+ await fire("session_shutdown", ctx);
6057
+ assert.equal(jobs.runs[1]!.signal?.aborted, true, "session shutdown stops every running job");
6058
+ await jobIo();
6059
+ assert.equal(sent.length, 0);
6060
+ } finally {
6061
+ jobs.cleanup();
6062
+ }
6063
+ });
6064
+
6065
+ test("/gentle:jobs opens this session's jobs overlay, stops the selected job, and the footer counts running jobs", async () => {
6066
+ const { pi, tools, commands, fire, sent } = fakePi();
6067
+ const jobs = fakeJobShell();
6068
+ gentleAgents(pi, {}, { ...deps().deps, jobShell: jobs.shell, jobOutputDir: () => jobs.dir });
6069
+ const { ctx, overlays } = fakeContext();
6070
+ const statuses: Array<string | undefined> = [];
6071
+ const snapshots: Array<{ sessionId: string; snapshot: { jobs: Array<{ id: string; label: string; startedAt: number }> } }> = [];
6072
+ const unsubscribe = pi.events.on("gentle-ai:jobs-sidebar", (value) => { snapshots.push(value as typeof snapshots[number]); });
6073
+ Object.assign(ctx.ui, { setStatus: (key: string, value: string | undefined) => { if (key === "gentle-jobs") statuses.push(value); } });
6074
+ try {
6075
+ await fire("session_start", ctx);
6076
+ await tools.get("bash_background")!.execute("b1", { command: "gh run watch 42 --exit-status", label: "CI" }, undefined, undefined, ctx);
6077
+ assert.equal(statuses.at(-1), "⧗ 1 job");
6078
+ assert.equal(snapshots.at(-1)?.sessionId, ctx.sessionManager.getSessionId());
6079
+ assert.deepEqual(snapshots.at(-1)?.snapshot.jobs.map(({ id, label }) => ({ id, label })), [{ id: "job-1", label: "CI" }]);
6080
+ const opened = commands.get("gentle:jobs")!.handler("", ctx);
6081
+ await tick();
6082
+ const view = overlays.at(-1)!;
6083
+ const screen = view.render(100).map(stripAnsi).join("\n");
6084
+ assert.match(screen, /Jobs · 1 running · 0 finished/);
6085
+ assert.match(screen, /gh run watch 42 --exit-status/);
6086
+ view.handleInput("s");
6087
+ assert.equal(jobs.runs[0]!.signal?.aborted, true, "s stops the selected job");
6088
+ assert.equal(statuses.at(-1), undefined, "the footer count clears when nothing runs");
6089
+ assert.deepEqual(snapshots.at(-1)?.snapshot.jobs, [], "the Status descriptions clear when nothing runs");
6090
+ await jobIo();
6091
+ const notices = sent.filter((entry) => entry.message.customType === "gentle-jobs.notice");
6092
+ assert.equal(notices.length, 1, "the agent was told it would be notified, so a human stop is reported once");
6093
+ assert.match(String(notices[0]!.message.content), /job-1 \("CI"\) was stopped by the user/);
6094
+ view.handleInput("q");
6095
+ await opened;
6096
+ } finally {
6097
+ unsubscribe();
6098
+ await fire("session_shutdown", ctx);
6099
+ jobs.cleanup();
6100
+ }
6101
+ });
6102
+
6103
+ test("a job exit notice whose forwarding throws while the parent is idle is retried after the bounded grace", async () => {
6104
+ const { pi, tools, fire, sent, userMessages } = fakePi();
6105
+ const harness = deps();
6106
+ const timers = recordTimers(harness.deps);
6107
+ const jobs = fakeJobShell();
6108
+ gentleAgents(pi, {}, { ...harness.deps, jobShell: jobs.shell, jobOutputDir: () => jobs.dir });
6109
+ const { ctx } = fakeContext();
6110
+ try {
6111
+ await fire("session_start", ctx);
6112
+ await tools.get("bash_background")!.execute("b1", { command: "make ci" }, undefined, undefined, ctx);
6113
+ const sendMessage = pi.sendMessage;
6114
+ Object.assign(pi, { sendMessage: () => { throw new Error("host busy"); } });
6115
+ jobs.runs[0]!.exit(0);
6116
+ await jobIo();
6117
+ assert.equal(sent.length, 0);
6118
+ assert.equal(userMessages.length, 0);
6119
+ Object.assign(pi, { sendMessage });
6120
+ // No turn boundary is coming for an idle parent, so the retry is a timer.
6121
+ assert.equal(timers.run(PARENT_WAKE_GRACE_MS), 1, "one bounded retry flush is armed");
6122
+ await tick();
6123
+ const notices = sent.filter((entry) => entry.message.customType === "gentle-jobs.notice");
6124
+ assert.equal(notices.length, 1, "the requeued notice reaches the idle parent");
6125
+ assert.match(String(notices[0]!.message.content), /job-1 \("make ci"\) exited with code 0/);
6126
+ assert.equal(userMessages.length, 1, "and the idle parent is woken for it");
6127
+ assert.equal(timers.run(PARENT_WAKE_GRACE_MS), 1);
6128
+ await tick();
6129
+ assert.equal(sent.length, 1, "a successful retry never delivers the notice twice");
6130
+ } finally {
6131
+ await fire("session_shutdown", ctx);
6132
+ jobs.cleanup();
6133
+ }
6134
+ });
6135
+
6136
+ for (const boundary of ["session_compact", "session_compact_failed"] as const) {
6137
+ test(`a parent compacting outside an agent run holds a job exit notice until ${boundary}, then wakes it`, async () => {
6138
+ const { pi, tools, fire, sent, userMessages, delivery, setIdle } = fakePi();
6139
+ const harness = deps();
6140
+ const timers = recordTimers(harness.deps);
6141
+ const jobs = fakeJobShell();
6142
+ gentleAgents(pi, {}, { ...harness.deps, jobShell: jobs.shell, jobOutputDir: () => jobs.dir });
6143
+ const { ctx } = fakeContext();
6144
+ try {
6145
+ await fire("session_start", ctx);
6146
+ await tools.get("bash_background")!.execute("b1", { command: "make ci" }, undefined, undefined, ctx);
6147
+ setIdle(false);
6148
+ jobs.runs[0]!.exit(1);
6149
+ await jobIo();
6150
+ assert.equal(sent.length, 0, "no direct custom-message turn starts while the parent compacts");
6151
+ assert.equal(userMessages.length, 0, "no wake is sent while the parent compacts");
6152
+ await fire(boundary, ctx);
6153
+ assert.equal(sent.length, 0, "the boundary handler runs before Pi leaves the compacting state");
6154
+ setIdle(true);
6155
+ assert.equal(timers.run(0), 1, "one deferred flush is scheduled for the compaction boundary");
6156
+ await tick();
6157
+ assert.deepEqual(sent.map((entry) => entry.options), [{ triggerTurn: false }], "the held notice is stored without a direct turn");
6158
+ assert.deepEqual(delivery, ["custom:gentle-jobs.notice", "user"], "one wake follows the held notice");
6159
+ } finally {
6160
+ await fire("session_shutdown", ctx);
6161
+ jobs.cleanup();
6162
+ }
6163
+ });
6164
+ }
6165
+
6166
+ test("session shutdown removes the default background job log directory", async () => {
6167
+ const { pi, tools, fire } = fakePi();
6168
+ const jobs = fakeJobShell();
6169
+ gentleAgents(pi, {}, { ...deps().deps, jobShell: jobs.shell });
6170
+ const { ctx } = fakeContext();
6171
+ try {
6172
+ await fire("session_start", ctx);
6173
+ const started = toolText(await tools.get("bash_background")!.execute("b1", { command: "sleep 100" }, undefined, undefined, ctx));
6174
+ const outputPath = /Output: (.+)$/m.exec(started)![1]!;
6175
+ assert.ok(existsSync(dirname(outputPath)), "the job log directory exists while the session runs");
6176
+ await fire("session_shutdown", ctx);
6177
+ assert.equal(existsSync(dirname(outputPath)), false, "the job log directory is removed with the session");
6178
+ } finally {
6179
+ jobs.cleanup();
6180
+ }
6181
+ });
6182
+
6183
+ test("session shutdown never hangs on a job whose process ignores the stop", { timeout: 5000 }, async () => {
6184
+ const { pi, tools, fire } = fakePi();
6185
+ const dir = mkdtempSync(join(tmpdir(), "gentle-jobs-stuck-"));
6186
+ // A process that never exits, even after its abort signal.
6187
+ const stuck = () => ({ operations: { exec: () => new Promise<{ exitCode: number | null }>(() => {}) } });
6188
+ const schedule: AgentsDeps["schedule"] = (fn, ms) => { const timer = setTimeout(fn, Math.min(ms, 10)); timer.unref(); return () => clearTimeout(timer); };
6189
+ gentleAgents(pi, {}, { ...deps().deps, schedule, jobShell: stuck });
6190
+ const { ctx } = fakeContext();
6191
+ try {
6192
+ await fire("session_start", ctx);
6193
+ await tools.get("bash_background")!.execute("b1", { command: "sleep 100" }, undefined, undefined, ctx);
6194
+ await fire("session_shutdown", ctx);
6195
+ } finally {
6196
+ rmSync(dir, TEST_DIR_REMOVAL);
6197
+ }
6198
+ });
6199
+
6200
+ // A monitor reports output lines while it runs, through the same router.
6201
+ test("monitor delivers line events to an idle parent with one wake, and reports its end with the event count", async () => {
6202
+ const { pi, tools, fire, sent, userMessages, renderers } = fakePi();
6203
+ const harness = deps();
6204
+ const timers = recordTimers(harness.deps);
6205
+ const jobs = fakeJobShell();
6206
+ gentleAgents(pi, {}, { ...harness.deps, jobShell: jobs.shell, jobOutputDir: () => jobs.dir });
6207
+ const { ctx } = fakeContext();
6208
+ try {
6209
+ await fire("session_start", ctx);
6210
+ const started = toolText(await tools.get("monitor")!.execute("m1", { command: "gh run watch 7", label: "CI checks", timeout_seconds: 900 }, undefined, undefined, ctx));
6211
+ assert.match(started, /Started monitor job-1 \("CI checks"\)/);
6212
+ assert.match(started, /900s/);
6213
+ jobs.runs[0]!.onData(Buffer.from("lint: pass\nunit: fail\n"));
6214
+ assert.equal(sent.length, 0, "lines wait for the batch window");
6215
+ assert.equal(timers.run(200), 1);
6216
+ await tick();
6217
+ const events = sent.filter((entry) => entry.message.customType === "gentle-jobs.notice");
6218
+ assert.equal(events.length, 1);
6219
+ assert.deepEqual(events[0]!.options, { triggerTurn: false });
6220
+ assert.match(String(events[0]!.message.content), /Monitor job-1 \("CI checks"\) reported 2 new lines:\nlint: pass\nunit: fail/);
6221
+ assert.equal(userMessages.length, 1, "the idle parent is woken for the events");
6222
+ assert.match(renderers.get("gentle-jobs.notice")!(events[0]!.message, { expanded: true }, plainTheme).render(70).map(stripAnsi).join("\n"), /unit: fail/);
6223
+ jobs.runs[0]!.onData(Buffer.from("e2e: pass\n"));
6224
+ jobs.runs[0]!.exit(1);
6225
+ await jobIo();
6226
+ const contents = sent.filter((entry) => entry.message.customType === "gentle-jobs.notice").map((entry) => String(entry.message.content));
6227
+ assert.equal(contents.length, 3, "pending lines are delivered before the end notice");
6228
+ assert.match(contents[1]!, /reported 1 new line:\ne2e: pass/);
6229
+ assert.match(contents[2]!, /Monitor job-1 \("CI checks"\) exited with code 1 after .* 3 events\./);
6230
+ } finally {
6231
+ await fire("session_shutdown", ctx);
6232
+ jobs.cleanup();
6233
+ }
6234
+ });
6235
+
6236
+ test("monitor events wait for a busy parent's turn boundary and coalesce into one notice", async () => {
6237
+ const { pi, tools, fire, sent } = fakePi();
6238
+ const harness = deps();
6239
+ const timers = recordTimers(harness.deps);
6240
+ const jobs = fakeJobShell();
6241
+ gentleAgents(pi, {}, { ...harness.deps, jobShell: jobs.shell, jobOutputDir: () => jobs.dir });
6242
+ const { ctx } = fakeContext();
6243
+ try {
6244
+ await fire("session_start", ctx);
6245
+ await fire("agent_start", ctx);
6246
+ await tools.get("monitor")!.execute("m1", { command: "tail -f log", timeout_seconds: 60 }, undefined, undefined, ctx);
6247
+ jobs.runs[0]!.onData(Buffer.from("ERROR a\n"));
6248
+ timers.run(200);
6249
+ jobs.runs[0]!.onData(Buffer.from("ERROR b\n"));
6250
+ timers.run(200);
6251
+ assert.equal(sent.length, 0, "a busy parent is not interrupted mid-tool-call");
6252
+ await fire("turn_end", ctx);
6253
+ assert.equal(sent.length, 1, "both batches arrive as one notice");
6254
+ assert.deepEqual(sent[0]!.options, { deliverAs: "steer", triggerTurn: true });
6255
+ assert.match(String(sent[0]!.message.content), /reported 2 new lines:\nERROR a\nERROR b/);
6256
+ // job_stop ends the monitor without any further notice.
6257
+ assert.match(toolText(await tools.get("job_stop")!.execute("s1", { job_id: "job-1" }, undefined, undefined, ctx)), /Stopped job-1/);
6258
+ jobs.runs[0]!.onData(Buffer.from("ERROR c\n"));
6259
+ timers.run(200);
6260
+ timers.run(60_000);
6261
+ await jobIo();
6262
+ await fire("turn_end", ctx);
6263
+ assert.equal(sent.length, 1, "a stopped monitor reports nothing more");
6264
+ } finally {
6265
+ await fire("session_shutdown", ctx);
6266
+ jobs.cleanup();
6267
+ }
6268
+ });
6269
+
6270
+ test("monitor rejects a missing or out-of-range timeout before starting anything", async () => {
6271
+ const { pi, tools, fire } = fakePi();
6272
+ const jobs = fakeJobShell();
6273
+ gentleAgents(pi, {}, { ...deps().deps, jobShell: jobs.shell, jobOutputDir: () => jobs.dir });
6274
+ const { ctx } = fakeContext();
6275
+ try {
6276
+ await fire("session_start", ctx);
6277
+ for (const params of [{ command: "x" }, { command: "x", timeout_seconds: 0 }, { command: "x", timeout_seconds: 3600 }]) {
6278
+ await assert.rejects(async () => tools.get("monitor")!.execute("m", params, undefined, undefined, ctx), /timeout_seconds must be a whole number from 1 to 1800/);
6279
+ }
6280
+ assert.equal(jobs.runs.length, 0);
6281
+ } finally {
6282
+ await fire("session_shutdown", ctx);
6283
+ jobs.cleanup();
6284
+ }
6285
+ });
6286
+
6287
+ test("events from two interleaved monitors coalesce per monitor while the parent is busy", async () => {
6288
+ const { pi, tools, fire, sent } = fakePi();
6289
+ const harness = deps();
6290
+ const timers = recordTimers(harness.deps);
6291
+ const jobs = fakeJobShell();
6292
+ gentleAgents(pi, {}, { ...harness.deps, jobShell: jobs.shell, jobOutputDir: () => jobs.dir });
6293
+ const { ctx } = fakeContext();
6294
+ try {
6295
+ await fire("session_start", ctx);
6296
+ await fire("agent_start", ctx);
6297
+ await tools.get("monitor")!.execute("m1", { command: "watch a", label: "A", timeout_seconds: 60 }, undefined, undefined, ctx);
6298
+ await tools.get("monitor")!.execute("m2", { command: "watch b", label: "B", timeout_seconds: 60 }, undefined, undefined, ctx);
6299
+ for (const round of [1, 2, 3]) {
6300
+ jobs.runs[0]!.onData(Buffer.from(`a${round}\n`));
6301
+ jobs.runs[1]!.onData(Buffer.from(`b${round}\n`));
6302
+ timers.run(200);
6303
+ }
6304
+ await fire("turn_end", ctx);
6305
+ const contents = sent.map((entry) => String(entry.message.content));
6306
+ assert.equal(contents.length, 2, "one notice per monitor, not one per batch");
6307
+ assert.match(contents[0]!, /\("A"\) reported 3 new lines:\na1\na2\na3/);
6308
+ assert.match(contents[1]!, /\("B"\) reported 3 new lines:\nb1\nb2\nb3/);
6309
+ } finally {
6310
+ await fire("session_shutdown", ctx);
6311
+ jobs.cleanup();
6312
+ }
6313
+ });
6314
+
6315
+ test("a human stop of a monitor from /gentle:jobs delivers its pending lines, then one stop notice, then nothing", async () => {
6316
+ const { pi, tools, commands, fire, sent } = fakePi();
6317
+ const harness = deps();
6318
+ const timers = recordTimers(harness.deps);
6319
+ const jobs = fakeJobShell();
6320
+ gentleAgents(pi, {}, { ...harness.deps, jobShell: jobs.shell, jobOutputDir: () => jobs.dir });
6321
+ const { ctx, overlays } = fakeContext();
6322
+ try {
6323
+ await fire("session_start", ctx);
6324
+ await fire("agent_start", ctx);
6325
+ await tools.get("monitor")!.execute("m1", { command: "tail -f log", label: "log", timeout_seconds: 60 }, undefined, undefined, ctx);
6326
+ jobs.runs[0]!.onData(Buffer.from("ERROR seen\n"));
6327
+ const opened = commands.get("gentle:jobs")!.handler("", ctx);
6328
+ await tick();
6329
+ overlays.at(-1)!.handleInput("s");
6330
+ overlays.at(-1)!.handleInput("q");
6331
+ await opened;
6332
+ assert.equal(jobs.runs[0]!.signal?.aborted, true);
6333
+ jobs.runs[0]!.onData(Buffer.from("ERROR after stop\n"));
6334
+ timers.run(200);
6335
+ timers.run(60_000);
6336
+ await jobIo();
6337
+ await fire("turn_end", ctx);
6338
+ const contents = sent.map((entry) => String(entry.message.content));
6339
+ assert.equal(contents.length, 2, `notices: ${JSON.stringify(contents)}`);
6340
+ assert.match(contents[0]!, /reported 1 new line:\nERROR seen/);
6341
+ assert.match(contents[1]!, /Monitor job-1 \("log"\) was stopped by the user after .*, 1 event\./);
6342
+ } finally {
6343
+ await fire("session_shutdown", ctx);
6344
+ jobs.cleanup();
6345
+ }
6346
+ });