@blackbelt-technology/pi-agent-dashboard 0.10.0 → 0.12.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 (474) hide show
  1. package/AGENTS.md +4 -2
  2. package/README.md +64 -18
  3. package/docs/architecture.md +2325 -270
  4. package/package.json +36 -20
  5. package/packages/extension/package.json +18 -9
  6. package/packages/extension/src/bridge-context.ts +6 -0
  7. package/packages/extension/src/bridge-handlers/dispatch.ts +109 -70
  8. package/packages/extension/src/bridge-handlers/forwarders.ts +19 -42
  9. package/packages/extension/src/bridge-handlers/instance.ts +31 -13
  10. package/packages/extension/src/bridge-handlers/lifecycle.ts +149 -66
  11. package/packages/extension/src/bridge-shutdown.ts +44 -0
  12. package/packages/extension/src/bridge-ticket-client.ts +61 -7
  13. package/packages/extension/src/bridge-tls-checks.ts +79 -0
  14. package/packages/extension/src/bridge.ts +309 -284
  15. package/packages/extension/src/canvas-tool.ts +2 -0
  16. package/packages/extension/src/command-handler.ts +106 -37
  17. package/packages/extension/src/connect-target.ts +23 -0
  18. package/packages/extension/src/connection.ts +153 -38
  19. package/packages/extension/src/credential-guard.ts +300 -0
  20. package/packages/extension/src/custom-entry-forward.ts +27 -18
  21. package/packages/extension/src/dashboard-http-origin.ts +88 -0
  22. package/packages/extension/src/default-model-apply.ts +83 -0
  23. package/packages/extension/src/dev-build.ts +11 -1
  24. package/packages/extension/src/flow-event-wiring.ts +19 -95
  25. package/packages/extension/src/followup-drain.ts +19 -5
  26. package/packages/extension/src/git-link-builder.ts +11 -2
  27. package/packages/extension/src/inbound-limits.ts +138 -0
  28. package/packages/extension/src/local-token-header.ts +77 -6
  29. package/packages/extension/src/model-refresh.ts +69 -0
  30. package/packages/extension/src/path-gate/decide.ts +68 -5
  31. package/packages/extension/src/path-gate/handler.ts +16 -8
  32. package/packages/extension/src/path-gate/index.ts +2 -2
  33. package/packages/extension/src/path-gate/roots.ts +15 -3
  34. package/packages/extension/src/path-gate/suppression.ts +3 -0
  35. package/packages/extension/src/pi-env.d.ts +8 -1
  36. package/packages/extension/src/pi-retry-settings.ts +11 -2
  37. package/packages/extension/src/pinned-endpoint.ts +44 -0
  38. package/packages/extension/src/plugin-event-forward-registry.ts +90 -14
  39. package/packages/extension/src/preview-path-link.ts +151 -0
  40. package/packages/extension/src/project-init/scaffold.ts +98 -35
  41. package/packages/extension/src/project-trust-live.ts +143 -0
  42. package/packages/extension/src/project-trust.ts +178 -30
  43. package/packages/extension/src/provider-model-cache.ts +118 -0
  44. package/packages/extension/src/provider-register.ts +487 -46
  45. package/packages/extension/src/remote-registration-gate.ts +21 -21
  46. package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
  47. package/packages/extension/src/retry-tracker.ts +90 -7
  48. package/packages/extension/src/role-manager.ts +4 -2
  49. package/packages/extension/src/role-model-tools.ts +68 -10
  50. package/packages/extension/src/server-auto-start.ts +69 -3
  51. package/packages/extension/src/server-launcher.ts +26 -8
  52. package/packages/extension/src/server-proof-probe.ts +117 -0
  53. package/packages/extension/src/session-sync.ts +53 -24
  54. package/packages/extension/src/spawn-new-session.ts +22 -0
  55. package/packages/extension/src/steer-buffer.ts +164 -0
  56. package/packages/extension/src/stream-forward-buffer.ts +64 -15
  57. package/packages/extension/src/sudo-askpass/config-reader.ts +32 -0
  58. package/packages/extension/src/sudo-askpass/controller.ts +405 -0
  59. package/packages/extension/src/sudo-askpass/helper-script.ts +69 -0
  60. package/packages/extension/src/sudo-askpass/in-flight.ts +79 -0
  61. package/packages/extension/src/sudo-askpass/index.ts +11 -0
  62. package/packages/extension/src/sudo-askpass/install.ts +143 -0
  63. package/packages/extension/src/sudo-askpass/password-cache.ts +118 -0
  64. package/packages/extension/src/sudo-askpass/prompt-text.ts +55 -0
  65. package/packages/extension/src/sudo-askpass/protocol.ts +18 -0
  66. package/packages/extension/src/sudo-askpass/sudo-mask-registry.ts +52 -0
  67. package/packages/extension/src/terminal-reload.ts +19 -5
  68. package/packages/extension/src/tool-update-filter-registry.ts +210 -0
  69. package/packages/extension/src/vault-delivery.ts +11 -1
  70. package/packages/extension/src/vault-redaction.ts +4 -3
  71. package/packages/server/package.json +17 -14
  72. package/packages/server/src/access/access-denials.ts +8 -0
  73. package/packages/server/src/access/access-grants.ts +303 -64
  74. package/packages/server/src/access/access-health.ts +10 -0
  75. package/packages/server/src/access/access-plane.ts +12 -1
  76. package/packages/server/src/access/containment-gate.ts +113 -30
  77. package/packages/server/src/access/cwd-verdict.ts +3 -3
  78. package/packages/server/src/access/denial-hold.ts +3 -0
  79. package/packages/server/src/access/grant-coordinator.ts +17 -1
  80. package/packages/server/src/access/named-grant.ts +3 -0
  81. package/packages/server/src/access/pending-grant-registry.ts +32 -5
  82. package/packages/server/src/access/pi-trust-live.ts +244 -0
  83. package/packages/server/src/access/pi-trust-mirror-service.ts +50 -11
  84. package/packages/server/src/access/planes.ts +107 -1
  85. package/packages/server/src/access/preview-egress-store.ts +153 -0
  86. package/packages/server/src/access/prompt-channel.ts +5 -0
  87. package/packages/server/src/access/provisioning-wiring.ts +113 -0
  88. package/packages/server/src/access/provisioning.ts +763 -0
  89. package/packages/server/src/access/verified-read.ts +24 -7
  90. package/packages/server/src/access/yolo-session.ts +54 -2
  91. package/packages/server/src/acp-bridge/acp-session-adapter.ts +18 -5
  92. package/packages/server/src/acp-bridge/server-requests.ts +10 -4
  93. package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
  94. package/packages/server/src/auth/audit-log.ts +108 -0
  95. package/packages/server/src/auth/auth-plugin.ts +230 -38
  96. package/packages/server/src/auth/auth.ts +104 -4
  97. package/packages/server/src/auth/bearer-auth.ts +52 -12
  98. package/packages/server/src/auth/bridge-ticket-eligibility.ts +53 -10
  99. package/packages/server/src/auth/cors-origin.ts +90 -30
  100. package/packages/server/src/auth/credential-envelope.ts +233 -0
  101. package/packages/server/src/auth/credential-key-worker.d.mts +16 -0
  102. package/packages/server/src/auth/credential-key-worker.mjs +108 -0
  103. package/packages/server/src/auth/credential-key.ts +479 -0
  104. package/packages/server/src/auth/credential-migration.ts +162 -0
  105. package/packages/server/src/auth/csp-report-paths.ts +26 -0
  106. package/packages/server/src/auth/csp-report-sink.ts +302 -0
  107. package/packages/server/src/auth/csp-report-store.ts +406 -0
  108. package/packages/server/src/auth/csp.ts +145 -11
  109. package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
  110. package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
  111. package/packages/server/src/auth/device-proof.ts +202 -0
  112. package/packages/server/src/auth/duplicate-cookie-gate.ts +271 -0
  113. package/packages/server/src/auth/host-admission.ts +7 -0
  114. package/packages/server/src/auth/host-gate.ts +13 -2
  115. package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
  116. package/packages/server/src/auth/local-proof.ts +69 -18
  117. package/packages/server/src/auth/localhost-guard.ts +98 -33
  118. package/packages/server/src/auth/locked-json-file.ts +68 -6
  119. package/packages/server/src/auth/models-json-store.ts +269 -0
  120. package/packages/server/src/auth/mutation-origin-gate.ts +5 -2
  121. package/packages/server/src/auth/nav-intent.ts +72 -0
  122. package/packages/server/src/auth/node-guard.ts +36 -49
  123. package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
  124. package/packages/server/src/auth/passkey/passkey-pages.ts +17 -81
  125. package/packages/server/src/auth/passkey/passkey-routes.ts +8 -0
  126. package/packages/server/src/auth/pi-legacy-credentials.ts +3 -0
  127. package/packages/server/src/auth/plugin-credential-store.ts +81 -10
  128. package/packages/server/src/auth/plugin-server-trust.ts +29 -0
  129. package/packages/server/src/auth/plugin-trust-store.ts +103 -0
  130. package/packages/server/src/auth/proven-tls.ts +45 -0
  131. package/packages/server/src/auth/provider-auth-storage.ts +214 -12
  132. package/packages/server/src/auth/provider-block-checks.ts +321 -0
  133. package/packages/server/src/auth/provider-host-detect.ts +151 -0
  134. package/packages/server/src/auth/provider-key-file.ts +71 -0
  135. package/packages/server/src/auth/provider-readiness.ts +91 -0
  136. package/packages/server/src/auth/radius-mcp.ts +1 -1
  137. package/packages/server/src/auth/request-principal.ts +32 -0
  138. package/packages/server/src/auth/route-tier-gate.ts +3 -2
  139. package/packages/server/src/auth/secret-rotation.ts +246 -0
  140. package/packages/server/src/auth/secure-origin.ts +56 -0
  141. package/packages/server/src/auth/serve-app-host.ts +111 -11
  142. package/packages/server/src/auth/vertex-key-check.ts +140 -0
  143. package/packages/server/src/auth/ws-ticket.ts +40 -2
  144. package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
  145. package/packages/server/src/browse.ts +73 -20
  146. package/packages/server/src/browser-handlers/acp-guard.ts +1 -4
  147. package/packages/server/src/browser-handlers/directory-handler.ts +34 -24
  148. package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
  149. package/packages/server/src/browser-handlers/handler-context.ts +25 -2
  150. package/packages/server/src/browser-handlers/session-action-handler.ts +167 -63
  151. package/packages/server/src/browser-handlers/spawn-choice.ts +138 -1
  152. package/packages/server/src/browser-handlers/subscription-handler.ts +146 -3
  153. package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
  154. package/packages/server/src/build-plugin-send-prompt.ts +18 -0
  155. package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
  156. package/packages/server/src/cli/credentials-command.ts +555 -0
  157. package/packages/server/src/cli.ts +229 -53
  158. package/packages/server/src/config-api.ts +53 -35
  159. package/packages/server/src/config-snapshot.ts +197 -1
  160. package/packages/server/src/directory-service.ts +193 -68
  161. package/packages/server/src/embed-lifecycle/idle-reaper.ts +13 -3
  162. package/packages/server/src/event-wiring.ts +322 -207
  163. package/packages/server/src/git-worktree/ensure-worktree.ts +185 -0
  164. package/packages/server/src/git-worktree/git-operations.ts +45 -11
  165. package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
  166. package/packages/server/src/git-worktree/ref-arg.ts +39 -0
  167. package/packages/server/src/git-worktree/repo-lock.ts +42 -0
  168. package/packages/server/src/git-worktree/start-worktree-init.ts +151 -0
  169. package/packages/server/src/git-worktree/worktree-init-trust.ts +43 -1
  170. package/packages/server/src/git-worktree/worktree-init.ts +5 -1
  171. package/packages/server/src/identity/http-road-classification.ts +18 -2
  172. package/packages/server/src/identity/identity-floor.ts +5 -2
  173. package/packages/server/src/identity/ws-message-scope.ts +11 -3
  174. package/packages/server/src/identity/ws-road-classification.ts +3 -1
  175. package/packages/server/src/known-server-moves.ts +36 -15
  176. package/packages/server/src/lib/browse-roots.ts +129 -17
  177. package/packages/server/src/lib/client-dist.ts +36 -21
  178. package/packages/server/src/lib/content-disposition.ts +20 -0
  179. package/packages/server/src/lib/dashboard-state-guard.ts +513 -0
  180. package/packages/server/src/lib/diagram-render.ts +4 -6
  181. package/packages/server/src/lib/eml.ts +5 -10
  182. package/packages/server/src/lib/file-cwd-admission.ts +145 -0
  183. package/packages/server/src/lib/frame-policy-probe.ts +308 -0
  184. package/packages/server/src/lib/frame-policy-test-seam.ts +99 -0
  185. package/packages/server/src/lib/frame-policy-verdict.ts +125 -0
  186. package/packages/server/src/lib/grep-worker.ts +23 -0
  187. package/packages/server/src/lib/grep.ts +96 -7
  188. package/packages/server/src/lib/index-html.ts +81 -0
  189. package/packages/server/src/lib/mention-fuzzy-index.ts +263 -0
  190. package/packages/server/src/lib/office-preview.ts +49 -13
  191. package/packages/server/src/lib/path-containment.ts +50 -10
  192. package/packages/server/src/lib/resolve-file-mention.ts +234 -40
  193. package/packages/server/src/lib/resolve-mentions-batch.ts +143 -0
  194. package/packages/server/src/lib/route-admission.ts +80 -0
  195. package/packages/server/src/lib/writable-handler-target.ts +4 -0
  196. package/packages/server/src/lib/writable-md-target.ts +26 -0
  197. package/packages/server/src/lifecycle/boot-parent-liveness.ts +10 -25
  198. package/packages/server/src/lifecycle/credential-exit-barrier.ts +207 -0
  199. package/packages/server/src/lifecycle/exit-signal.ts +43 -0
  200. package/packages/server/src/lifecycle/recovery-server.ts +65 -18
  201. package/packages/server/src/live-server/capability-redact.ts +31 -0
  202. package/packages/server/src/live-server/live-browser-gate.ts +22 -0
  203. package/packages/server/src/live-server/live-capability.ts +615 -44
  204. package/packages/server/src/live-server/live-csp-report.ts +63 -0
  205. package/packages/server/src/live-server/live-csp.ts +141 -0
  206. package/packages/server/src/live-server/live-egress.ts +435 -0
  207. package/packages/server/src/live-server/live-exposure.ts +149 -0
  208. package/packages/server/src/live-server/live-log.ts +25 -0
  209. package/packages/server/src/live-server/live-origin-scan.ts +298 -0
  210. package/packages/server/src/live-server/live-server-manager.ts +220 -33
  211. package/packages/server/src/live-server/live-server-proxy.ts +411 -50
  212. package/packages/server/src/live-server/live-static.ts +231 -0
  213. package/packages/server/src/live-server/preview-dispatch.ts +286 -0
  214. package/packages/server/src/live-server/preview-observe.ts +53 -0
  215. package/packages/server/src/live-server/preview-origin.ts +182 -0
  216. package/packages/server/src/live-server/preview-path-bridge.ts +70 -0
  217. package/packages/server/src/live-server/preview-path-store.ts +420 -0
  218. package/packages/server/src/live-server/preview-path.ts +40 -0
  219. package/packages/server/src/live-server/preview-pool.ts +385 -0
  220. package/packages/server/src/live-server/preview-preflight.ts +41 -0
  221. package/packages/server/src/live-server/preview-reserve.ts +44 -0
  222. package/packages/server/src/live-server/preview-tier.ts +217 -0
  223. package/packages/server/src/live-server/preview-viewers.ts +54 -0
  224. package/packages/server/src/live-server/preview-ws-registry.ts +43 -0
  225. package/packages/server/src/model-proxy/custom-provider-discovery.ts +4 -2
  226. package/packages/server/src/model-proxy/internal-auth-storage.ts +5 -1
  227. package/packages/server/src/model-proxy/internal-registry.ts +283 -21
  228. package/packages/server/src/model-proxy/models-block-apply.ts +291 -0
  229. package/packages/server/src/model-proxy/pi-models-validator.ts +164 -0
  230. package/packages/server/src/model-proxy/registry-singleton.ts +44 -9
  231. package/packages/server/src/model-proxy/server-model-runtime.ts +17 -0
  232. package/packages/server/src/openspec/dependencies-file.ts +122 -0
  233. package/packages/server/src/openspec/openspec-change-watcher.ts +3 -1
  234. package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
  235. package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +72 -26
  236. package/packages/server/src/openspec/openspec-poll-worker-pool.ts +48 -12
  237. package/packages/server/src/openspec/openspec-poll-worker.ts +95 -9
  238. package/packages/server/src/openspec/readiness.ts +1 -1
  239. package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
  240. package/packages/server/src/openspec/workflow-schema.ts +141 -267
  241. package/packages/server/src/package/npm-search-proxy.ts +5 -2
  242. package/packages/server/src/package/provider-probe.ts +202 -7
  243. package/packages/server/src/pairing/browser-gateway.ts +325 -51
  244. package/packages/server/src/pairing/device-key-intake.ts +120 -0
  245. package/packages/server/src/pairing/device-token-services.ts +26 -0
  246. package/packages/server/src/pairing/paired-devices.ts +702 -27
  247. package/packages/server/src/pairing/pairing.ts +103 -11
  248. package/packages/server/src/pairing/{subagent-resync-routing.ts → resync-requester-registry.ts} +6 -10
  249. package/packages/server/src/pairing/socket-locality.ts +26 -0
  250. package/packages/server/src/pairing/ws-tier-gate.ts +74 -0
  251. package/packages/server/src/pending/pending-attach-registry.ts +15 -0
  252. package/packages/server/src/pending/pending-initial-prompt-registry.ts +15 -0
  253. package/packages/server/src/persistence/memory-event-store.ts +251 -296
  254. package/packages/server/src/persistence/preferences-store.ts +61 -2
  255. package/packages/server/src/pi/bridge-channel.ts +33 -0
  256. package/packages/server/src/pi/bridge-contention.ts +84 -2
  257. package/packages/server/src/pi/bridge-upgrade-auth.ts +18 -3
  258. package/packages/server/src/pi/gateway-listeners.ts +9 -3
  259. package/packages/server/src/pi/host-project-trust.ts +29 -15
  260. package/packages/server/src/pi/pi-gateway.ts +398 -41
  261. package/packages/server/src/pi/provisional-registration.ts +4 -1
  262. package/packages/server/src/pi/resource-toggle-trust.ts +18 -7
  263. package/packages/server/src/pi-agent-settings.ts +95 -301
  264. package/packages/server/src/pi-default-remirror.ts +89 -0
  265. package/packages/server/src/plugin-append-event.ts +35 -0
  266. package/packages/server/src/plugin-discovery-wiring.ts +142 -0
  267. package/packages/server/src/plugin-entry-stats.ts +61 -0
  268. package/packages/server/src/plugin-event-seam.ts +116 -4
  269. package/packages/server/src/plugin-local-request.ts +207 -0
  270. package/packages/server/src/plugin-ownership.ts +111 -0
  271. package/packages/server/src/plugin-policy-registry.ts +297 -0
  272. package/packages/server/src/plugin-request-lane.ts +92 -16
  273. package/packages/server/src/plugin-runtime-clients.ts +89 -0
  274. package/packages/server/src/preferences-relay.ts +20 -0
  275. package/packages/server/src/project-seed.ts +347 -0
  276. package/packages/server/src/push/push-transports/webhook-url.ts +8 -5
  277. package/packages/server/src/questions/question-store.ts +3 -2
  278. package/packages/server/src/routes/access-routes.ts +182 -15
  279. package/packages/server/src/routes/acme-routes.ts +14 -4
  280. package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
  281. package/packages/server/src/routes/canvas-types-routes.ts +20 -6
  282. package/packages/server/src/routes/csp-violations-routes.ts +162 -0
  283. package/packages/server/src/routes/file-routes.ts +640 -279
  284. package/packages/server/src/routes/file-write-binary-routes.ts +97 -24
  285. package/packages/server/src/routes/folder-project-routes.ts +18 -12
  286. package/packages/server/src/routes/frame-policy-routes.ts +215 -0
  287. package/packages/server/src/routes/git-routes.ts +340 -273
  288. package/packages/server/src/routes/grep-routes.ts +64 -14
  289. package/packages/server/src/routes/known-servers-routes.ts +189 -91
  290. package/packages/server/src/routes/live-server-routes.ts +572 -15
  291. package/packages/server/src/routes/local-proof-routes.ts +14 -0
  292. package/packages/server/src/routes/models-introspection-routes.ts +1 -1
  293. package/packages/server/src/routes/nav-intent-routes.ts +46 -0
  294. package/packages/server/src/routes/openspec-group-routes.ts +53 -44
  295. package/packages/server/src/routes/openspec-routes.ts +396 -31
  296. package/packages/server/src/routes/package-routes.ts +58 -10
  297. package/packages/server/src/routes/pairing-routes.ts +342 -17
  298. package/packages/server/src/routes/pi-settings-routes.ts +2 -0
  299. package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
  300. package/packages/server/src/routes/plugin-activation-routes.ts +59 -0
  301. package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
  302. package/packages/server/src/routes/preferences-auto-name-routes.ts +5 -2
  303. package/packages/server/src/routes/preferences-claude-compat-routes.ts +49 -0
  304. package/packages/server/src/routes/provider-auth-routes.ts +181 -10
  305. package/packages/server/src/routes/provider-override-routes.ts +158 -0
  306. package/packages/server/src/routes/provider-routes.ts +348 -86
  307. package/packages/server/src/routes/resource-activation-routes.ts +18 -4
  308. package/packages/server/src/routes/session-routes.ts +75 -25
  309. package/packages/server/src/routes/system-routes.ts +169 -52
  310. package/packages/server/src/routes/ui-link-base.ts +88 -0
  311. package/packages/server/src/rpc-keeper/keeper-manager.ts +196 -25
  312. package/packages/server/src/rpc-keeper/keeper.cjs +37 -23
  313. package/packages/server/src/runtime-overlay/extension-reload.ts +16 -10
  314. package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
  315. package/packages/server/src/runtime-overlay/runtime-stager.ts +4 -2
  316. package/packages/server/src/server.ts +1139 -291
  317. package/packages/server/src/services/cli-service.ts +59 -10
  318. package/packages/server/src/services/secrets-resolver.ts +46 -30
  319. package/packages/server/src/session/custom-event-group-annotation.ts +3 -3
  320. package/packages/server/src/session/custom-event-group-resolver.ts +10 -5
  321. package/packages/server/src/session/death-reason.ts +11 -7
  322. package/packages/server/src/session/event-status-extraction.ts +5 -1
  323. package/packages/server/src/session/hydration-state.ts +148 -0
  324. package/packages/server/src/session/memory-session-manager.ts +31 -2
  325. package/packages/server/src/session/open-tool-calls.ts +81 -47
  326. package/packages/server/src/session/pid-target.ts +127 -0
  327. package/packages/server/src/session/replay-compaction.ts +18 -5
  328. package/packages/server/src/session/replay-exit-controller.ts +221 -0
  329. package/packages/server/src/session/retained-transcript.ts +9 -2
  330. package/packages/server/src/session/seed-discovered-history.ts +85 -0
  331. package/packages/server/src/session/server-pid-context.ts +14 -0
  332. package/packages/server/src/session/session-api.ts +78 -29
  333. package/packages/server/src/session/session-archive.ts +7 -0
  334. package/packages/server/src/session/session-bootstrap.ts +9 -54
  335. package/packages/server/src/session/session-load-worker-pool.ts +11 -1
  336. package/packages/server/src/session/session-load-worker.ts +32 -4
  337. package/packages/server/src/spawn-process/abort-spawned-run.ts +28 -9
  338. package/packages/server/src/spawn-process/acp-spawn.ts +8 -2
  339. package/packages/server/src/spawn-process/headless-pid-registry.ts +393 -77
  340. package/packages/server/src/spawn-process/link-register.ts +42 -0
  341. package/packages/server/src/spawn-process/plugin-spawn-choice.ts +48 -0
  342. package/packages/server/src/spawn-process/plugin-spawn-worktree.ts +290 -0
  343. package/packages/server/src/spawn-process/process-classifier.ts +8 -3
  344. package/packages/server/src/spawn-process/process-manager.ts +61 -6
  345. package/packages/server/src/spawn-process/restored-identity.ts +112 -0
  346. package/packages/server/src/spawn-process/session-terminator.ts +179 -18
  347. package/packages/server/src/spawn-process/spawn-env-contributors.ts +2 -1
  348. package/packages/server/src/spawn-process/spawn-failure-log.ts +9 -0
  349. package/packages/server/src/spawn-process/spawn-register-watchdog.ts +44 -19
  350. package/packages/server/src/sudo-credential/relay.ts +337 -0
  351. package/packages/server/src/terminal/terminal-gateway.ts +10 -0
  352. package/packages/server/src/terminal/terminal-manager.ts +54 -46
  353. package/packages/server/src/tls/sources/acme/credentials.ts +3 -2
  354. package/packages/server/src/tls/sources/acme/runtime.ts +2 -1
  355. package/packages/server/src/tls/tls-bridge-route.ts +61 -0
  356. package/packages/server/src/tls/tls-config-validation.ts +2 -0
  357. package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
  358. package/packages/server/src/vault/vault-delivery-hub.ts +172 -26
  359. package/packages/server/src/vault/vault-routes.ts +9 -2
  360. package/packages/server/src/vault/vault-store.ts +87 -24
  361. package/packages/server/src/watch-files-handler.ts +66 -0
  362. package/packages/server/vendor/xlsx/LICENSE +201 -0
  363. package/packages/server/vendor/xlsx/PROVENANCE.json +13 -0
  364. package/packages/server/vendor/xlsx/xlsx.d.mts +1065 -0
  365. package/packages/server/vendor/xlsx/xlsx.mjs +28228 -0
  366. package/packages/shared/package.json +4 -2
  367. package/packages/shared/src/agent-credential-files.ts +32 -0
  368. package/packages/shared/src/browser-protocol.ts +285 -59
  369. package/packages/shared/src/canvas-declare.ts +27 -0
  370. package/packages/shared/src/canvas-detect.ts +1 -1
  371. package/packages/shared/src/canvas-types.ts +2 -2
  372. package/packages/shared/src/config.ts +443 -187
  373. package/packages/shared/src/containment-guard.ts +45 -0
  374. package/packages/shared/src/credential-encryption.ts +87 -0
  375. package/packages/shared/src/custom-event-groups.ts +2 -0
  376. package/packages/shared/src/dashboard-plugin/claude-compat.ts +159 -0
  377. package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
  378. package/packages/shared/src/dashboard-plugin/file-handler.ts +2 -0
  379. package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
  380. package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
  381. package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
  382. package/packages/shared/src/dashboard-plugin/index.ts +2 -0
  383. package/packages/shared/src/dashboard-plugin/manifest-types.ts +100 -1
  384. package/packages/shared/src/dashboard-plugin/plugin-status.ts +58 -3
  385. package/packages/shared/src/dashboard-plugin/replay-entry-types.ts +46 -0
  386. package/packages/shared/src/dashboard-plugin/slot-props.ts +47 -3
  387. package/packages/shared/src/dashboard-plugin/slot-types.ts +9 -1
  388. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +39 -3
  389. package/packages/shared/src/device-key-proof.ts +309 -0
  390. package/packages/shared/src/display-prefs.ts +13 -0
  391. package/packages/shared/src/doctor-core.ts +94 -27
  392. package/packages/shared/src/event-forward-declaration.ts +85 -12
  393. package/packages/shared/src/forbidden-subjects.ts +126 -14
  394. package/packages/shared/src/heap-limits.ts +0 -30
  395. package/packages/shared/src/host-admission.ts +2 -1
  396. package/packages/shared/src/index.ts +7 -6
  397. package/packages/shared/src/live-server.ts +161 -0
  398. package/packages/shared/src/local-proof-signal.ts +16 -0
  399. package/packages/shared/src/loopback-host.ts +26 -0
  400. package/packages/shared/src/mcp/verb-tiers.generated.ts +176 -0
  401. package/packages/shared/src/mdns-discovery.ts +25 -6
  402. package/packages/shared/src/models-json-reader.ts +41 -0
  403. package/packages/shared/src/nav-intent.ts +29 -0
  404. package/packages/shared/src/network-denial-signal.ts +15 -0
  405. package/packages/shared/src/node-version.ts +63 -60
  406. package/packages/shared/src/openspec-dependencies.ts +760 -0
  407. package/packages/shared/src/openspec-poller.ts +3 -2
  408. package/packages/shared/src/pairing-knock-client.ts +135 -11
  409. package/packages/shared/src/pi-agent-settings-lock.ts +311 -0
  410. package/packages/shared/src/pi-path-compare.ts +31 -0
  411. package/packages/shared/src/pi-settings-schema.ts +52 -9
  412. package/packages/shared/src/pi-trust-live-query.ts +93 -0
  413. package/packages/shared/src/pi-trust-mirror-snapshot.ts +21 -11
  414. package/packages/shared/src/pi-trust-mirror-types.ts +38 -3
  415. package/packages/shared/src/pi-trust-mirror.ts +47 -11
  416. package/packages/shared/src/pi-trust-resource-digest.ts +261 -0
  417. package/packages/shared/src/pid-namespace.ts +86 -0
  418. package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
  419. package/packages/shared/src/platform/git-source.ts +88 -26
  420. package/packages/shared/src/platform/git.ts +14 -8
  421. package/packages/shared/src/platform/native-ts-register.mjs +1 -1
  422. package/packages/shared/src/platform/process.ts +452 -5
  423. package/packages/shared/src/platform/resolve-pi-shell.ts +105 -0
  424. package/packages/shared/src/platform/select-git-source.ts +7 -0
  425. package/packages/shared/src/platform/spawn-runtime.ts +193 -7
  426. package/packages/shared/src/plugin-route-cwd.ts +95 -0
  427. package/packages/shared/src/preview-egress.ts +192 -0
  428. package/packages/shared/src/preview-origins.ts +398 -0
  429. package/packages/shared/src/project-root.ts +16 -0
  430. package/packages/shared/src/prompt-answer.ts +9 -5
  431. package/packages/shared/src/protocol.ts +187 -86
  432. package/packages/shared/src/provider-env-catalog.ts +413 -0
  433. package/packages/shared/src/provider-overrides.ts +112 -0
  434. package/packages/shared/src/question-types.ts +6 -0
  435. package/packages/shared/src/recommended-extensions.ts +97 -26
  436. package/packages/shared/src/recovery-timing.ts +27 -0
  437. package/packages/shared/src/remote-credentials.ts +63 -0
  438. package/packages/shared/src/renderer-by-ext.ts +5 -2
  439. package/packages/shared/src/rest-api.ts +148 -11
  440. package/packages/shared/src/role-schema.ts +24 -0
  441. package/packages/shared/src/route-tiers.ts +149 -4
  442. package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
  443. package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
  444. package/packages/shared/src/runtime-overlay/compat.ts +70 -6
  445. package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
  446. package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
  447. package/packages/shared/src/safe-local-path.ts +24 -0
  448. package/packages/shared/src/sanitize-profiles.ts +98 -0
  449. package/packages/shared/src/secret-patterns.ts +49 -0
  450. package/packages/shared/src/server-launcher.ts +9 -1
  451. package/packages/shared/src/server-pinning.ts +55 -2
  452. package/packages/shared/src/server-routes.ts +462 -0
  453. package/packages/shared/src/session-ui-path.ts +11 -0
  454. package/packages/shared/src/source-matching.ts +2 -2
  455. package/packages/shared/src/state-replay.ts +40 -24
  456. package/packages/shared/src/sudo-credential.ts +71 -0
  457. package/packages/shared/src/tls-only-token.ts +16 -0
  458. package/packages/shared/src/tool-path-resolve.ts +16 -1
  459. package/packages/shared/src/tool-registry/definitions.ts +5 -5
  460. package/packages/shared/src/tool-registry/strategies.ts +13 -12
  461. package/packages/shared/src/tool-workdir.ts +56 -0
  462. package/packages/shared/src/trusted-types-mode.ts +72 -0
  463. package/packages/shared/src/types.ts +134 -109
  464. package/packages/shared/src/url-policy.ts +96 -0
  465. package/packages/shared/src/vault-delivery.ts +15 -0
  466. package/packages/shared/src/vertex-regions.ts +81 -0
  467. package/packages/shared/src/ws-message-tiers.ts +11 -3
  468. package/packages/extension/src/subagent-fanout-admission.ts +0 -234
  469. package/packages/extension/src/subagent-forward-sites.ts +0 -69
  470. package/packages/extension/src/subagent-frame-buffer.ts +0 -245
  471. package/packages/extension/src/subagent-frame-strip.ts +0 -109
  472. package/packages/extension/src/subagent-saturation.ts +0 -196
  473. package/packages/extension/src/subagent-tick-throttle.ts +0 -252
  474. package/packages/shared/src/anthropic-messages-source.ts +0 -8
@@ -53,7 +53,7 @@ Node.js HTTP + WebSocket server that:
53
53
  - Serves the built web client as static files (production) or proxies to Vite dev server (dev mode)
54
54
  - Writes per-session `.meta.json` sidecar files with dashboard state and cached stats
55
55
  - Exposes REST API for session management, event content fetch, pinned directories, and file reading
56
- - Provides session control REST endpoints (`/api/session/:id/*`) wrapping WebSocket-only operations (prompt, abort, spawn, resume, rename, hide, flow-control, model, thinking-level, attach/detach-proposal) — see `src/server/session-api.ts`
56
+ - Provides session control REST endpoints (`/api/session/:id/*`) wrapping WebSocket-only operations (prompt, abort, spawn, resume, rename, hide, model, thinking-level, attach/detach-proposal) — see `src/server/session-api.ts`
57
57
 
58
58
  **Bind model.** HTTP listener + pi gateway WS listener bind `127.0.0.1` by default. Loopback removes socket from wire.
59
59
 
@@ -106,6 +106,7 @@ React-based responsive web UI that:
106
106
  - Shows all active sessions organized by directory, with pinned directories always visible at the top
107
107
  - Renders chat messages with markdown, syntax highlighting, streaming, and a small raw-HTML pass that strips React-only `ref` attributes before render
108
108
  - Persists scroll position per session — switching sessions restores exact scroll position if locked, or scrolls to bottom if following
109
+ - Animates live arrivals, paces streamed text, glides follow-scroll; `chatMotion` pref (rollback: `PATCH /api/preferences/display {"chatMotion":false}`). Full ref: [`chat-motion.md`](chat-motion.md)
109
110
  - Displays collapsed tool call steps with lazy-loaded content and elapsed time badges
110
111
  - Shows live ticking elapsed counters on running operations (thinking, tool calls) and final duration on completed ones
111
112
  - Provides command autocomplete with `/` prefix
@@ -329,18 +330,17 @@ See change: add-acp-session-driver.
329
330
  - `registerEventBusForwarding`. `packages/extension/src/flow-event-wiring.ts`.
330
331
  - ONE `pi.events.on(channel, ...)` subscription per declared channel.
331
332
  - `on()` observes every emitter.
332
- - Declared set = keys of `FLOW_EVENT_MAP` + `SUBAGENT_EVENT_MAP` + optional `extraMaps` (currently none passed).
333
+ - Declared set = plugin-declared channels via `extraMaps`. Core maps removed (`FLOW_EVENT_MAP`, `SUBAGENT_EVENT_MAP`).
333
334
  - Channel list IS the contract. Undeclared channel -> never forwarded.
334
335
  - New channel -> new map entry. Identity entry when no rename wanted.
335
336
  - Retired: wildcard forwarding of any unknown channel. Unimplementable without an emit intercept.
336
337
 
337
338
  **Forward gates.** `forwardBusEvent`, same file.
338
339
 
339
- - Subagent channel -> forward only when `sessionReady && isActive() && connection.isConnected`.
340
- - Else buffer latest-wins per agent in `SubagentFrameBuffer`. Flushed on re-register / reconnect.
341
- - Other declared channel -> forward when `sessionReady && isActive()`.
340
+ - Plugin `latest`-group channel -> buffered latest-wins in `StreamForwardBuffer` while not forwardable. Flushed on re-register / reconnect.
341
+ - Declared channel -> forward when `sessionReady && isActive()`.
342
342
  - Forwarding failure never propagates to the emitter.
343
- - Forwarding failure drops that live frame. Nothing re-sends it. Subagent frames are the exception (buffered).
343
+ - Forwarding failure drops that live frame. Nothing re-sends it. `latest`-group frames are the exception (buffered).
344
344
 
345
345
  **Teardown.** dispose returned by `registerEventBusForwarding`.
346
346
 
@@ -362,6 +362,9 @@ See change: add-acp-session-driver.
362
362
  **Validation.** `validateDeclaration` — untrusted input.
363
363
  - Channel regex requires `:`. Caps: 32 channels/plugin, 256 total.
364
364
  - Rejected: `RESERVED_EVENT_TYPES`, channel already in core `EVENT_BUS_MAP`. First owner wins on conflict (counted).
365
+ - `RESERVED_EVENT_TYPES` no longer lists `flow_*`.
366
+ - `as`-type owner index: declaration whose `as` type owned by another `pluginId` → rejected, counted in `pluginEventForward.conflicts`. Same plugin may map two channels to one `as`. Source `packages/extension/src/plugin-event-forward-registry.ts`.
367
+ - Optional `replayEntryTypes: string[]` (plugin's persisted custom-entry types). Registry exposes `replayEntryTypes()`. Live bridge excludes those types from generic custom-entry forwarding and replays them on reconnect.
365
368
  - `pluginId`/key regex-validated. Key value string or finite number ≤128 chars, else delivered live-only.
366
369
 
367
370
  **Delivery.**
@@ -369,6 +372,30 @@ See change: add-acp-session-driver.
369
372
  - `latest` — keep newest per key until ready.
370
373
  - `stream` — keep all, in order, never coalesced.
371
374
 
375
+ **Example consumer: flows.** Flow catalog rides this path. Replaces core `flows_list` / `getFlowsList` / `FlowInfo` (removed). See change: flows-dock-chip-and-panel-actions.
376
+ - Declares `dashboard-flows:catalog` → `as: flow_catalog`, `delivery: latest`, `key: catalogKey`. Source: `packages/flows-plugin/src/bridge/flow-catalog-publisher.ts`.
377
+ - Payload: `{ catalogKey: "catalog", flows: [{ name, description, source, taskRequired }] }`.
378
+ - Probe: `flow:list-flows` (`flow-probe.ts`). Unanswered → no publish. Answered `[]` → publish empty catalog.
379
+ - Debounce 300 ms. Triggers: `session_start`, `flow:(un)register-(flows|agents)-dir`, `flow:rediscover`, `flow:complete`, publisher attach, server ask `dashboard-flows:report-files`.
380
+ - `report-files` with `{rediscover:true}` → pi-flows rediscovers before publish.
381
+ - Plugin server `packages/flows-plugin/src/server/flow-catalog.ts`:
382
+ - `ctx.onEvent` `flow_catalog` → `stateStore.setFlows`.
383
+ - Handles `plugin_action` `flow.request-catalog` (per-session ask limit, default 2 s).
384
+ - Sibling rediscover ask when known catalog changes.
385
+ - Server-start re-ask: 5 s interval × 60 s.
386
+ - Client `useFlowCatalog`: re-asks every 5 s, max 12 per view, while catalog unknown.
387
+ - Timings: flows plugin settings (`configSchema`).
388
+
389
+ **Example consumer: flow runs.**
390
+ - Flows bridge `packages/flows-plugin/src/bridge/flow-event-forward.ts` (`FLOW_RUN_CHANNELS`) declares 16 pi-flows channels.
391
+ - Step channels (`agent-*`, `subagent-tool-*` → `flow_tool_*`, `assistant-text`, `thinking-text`, `loop-iteration`, `decision` → `flow_decision`) `stream`, keyed `stepId`.
392
+ - `flow:flow-started` / `flow:complete` `stream`, keyed `flowName`.
393
+ - `flow:question` / `flow:answer` `stream`, keyed `stepId` (→ `flow_question` / `flow_answer`). See "Flow parent mailbox".
394
+ - `flow:ask-session-result` `live` (→ `flow_ask_session_result`).
395
+ - `summary-*` `live`.
396
+ - Core `FLOW_EVENT_MAP` and `SUBAGENT_EVENT_MAP` removed. Channels plugin-declared (`packages/extension/src/flow-event-wiring.ts`).
397
+ - Flows disabled → no flow events forwarded.
398
+
372
399
  **Retention.** `StreamForwardBuffer` (`packages/extension/src/stream-forward-buffer.ts`).
373
400
  - One buffer keyed by (pluginId, key value) — cross-channel order (delta vs entry) survives.
374
401
  - ≤2000 msgs or 2MiB per key; 64-key budget shared by latest+stream across plugins, drop-oldest, counted.
@@ -399,182 +426,100 @@ See change: add-acp-session-driver.
399
426
  **Second consumer.** `packages/roles-plugin/src/bridge/index.ts`.
400
427
  - `before_agent_start` appends one `toolGuidelines.Agent` bullet. Prefer `model:"@role"`, ≤12 configured roles. Only when Agent tool selected.
401
428
 
402
- ### Subagent Timeline Push/Pull Split (change: reduce-subagent-details-payload)
403
-
404
- **Why thin ticks.**
405
-
406
- - Producer builds ONE `snapshotDetails()` object.
407
- - Feeds BOTH carriers: `subagents:*` EventBus frame + pi-core `tool_execution_update`.
408
- - `entries[]` append-only → tick size grows linearly with run length.
409
- - Long run = fat intermediate ticks.
410
- - Solution: strip timeline from intermediate ticks.
411
- - Push terminal frame fat.
412
- - Pull full timeline on demand.
413
-
414
- **Strip module.**
415
-
416
- - File: `packages/extension/src/subagent-frame-strip.ts`.
417
- - Exports `stripSubagentEntries`, `stripForForward`, `NON_TERMINAL_STATUSES`.
418
- - Strips `details.entries` on FORWARD path when frame status `queued` or `running`.
419
-
420
- **Allowlist, never negation.**
421
-
422
- - `NON_TERMINAL_STATUSES` = explicit allowlist.
423
- - Never `!terminal`.
424
- - `AgentStatus` also has `stopped`; negation would strip it and lose that run's timeline.
425
- - `stopped` counts as terminal: never stripped.
426
-
427
- **Strip clones.**
428
-
429
- - Strip CLONES data.
430
- - `SubagentFrameBuffer` retains frames BY REFERENCE.
431
- - Mutating strip would corrupt the pull source.
432
- - Fat snapshot survives intact for resync.
433
-
434
- **Call-site allowlist.**
435
-
436
- - Strip applied at explicit call sites.
437
- - NEVER inside `sendEventForward`.
438
- - Sites: EventBus forward path (`flow-event-wiring.ts` `forwardBusEvent`).
439
- - Sites: buffered-frame flush + resync reply (`packages/extension/src/subagent-forward-sites.ts` — `flushBufferedSubagentFrames` strips, `serveSubagentResync` does NOT).
440
- - Sites: `tool_execution_update` carrier in `bridge.ts`.
441
- - Strip inside `sendEventForward` would strip the resync reply.
442
- - EventBus-only strip would leak every frame drained by the buffer.
429
+ ### Generic commands-changed seam (change: update-flows-plugin)
443
430
 
444
- **Terminal frames never stripped.**
431
+ - Bus channel `dashboard:commands-changed` (`COMMANDS_CHANGED_CHANNEL`, `packages/shared/src/event-forward-declaration.ts`). Payload ignored.
432
+ - Core bridge: `registerCommandsChangedListener` (`packages/extension/src/flow-event-wiring.ts`), wired from `bridge-handlers/lifecycle.ts`. Resends `commands_list`.
433
+ - Flows bridge emits it on `flow:rediscover` / `flow:complete`. Replaces former core listeners.
445
434
 
446
- - `completed`/`failed`/`aborted`/`stopped`/`error` forward full.
447
- - Terminal frame = durable record behind `tool_execution_end` backfill.
448
- - Second independent terminal guard: `stripForForward(data, channel)` never strips when `channel` in `TERMINAL_CHANNELS` (`subagents:completed`, `subagents:failed`).
449
- - Guard fires regardless of `details.status`.
450
- - Both signals must be wrong to lose a timeline.
435
+ ### Plugin entry replay (change: update-flows-plugin)
451
436
 
452
- **Full-snapshot invariant preserved.**
437
+ - Manifest field `pi-dashboard-plugin.replayEntryTypes: string[]` (flows: `["flow-event"]`). Lenient: malformed → contributes nothing.
438
+ - `packages/shared/src/dashboard-plugin/replay-entry-types.ts`: `normalizeReplayEntryTypes`, `computeReplayEntryTypes` → `{ replay (enabled plugins), hidden (every declaring plugin) }`.
439
+ - Server `packages/server/src/plugin-entry-stats.ts`: provider set at boot from discovered manifests (5 s cache).
440
+ - Session load (`session-load-worker-pool.ts` → `session-load-worker.ts`) passes sets to `replayEntriesAsEvents`. OFFLINE sessions replay from manifests, not a live bridge.
441
+ - `packages/shared/src/state-replay.ts`:
442
+ - `opts.replayEntryTypes` replays `{ seq, eventType, data }` records, seq-sorted, verbatim. Extra fields (`flowRunId`) ignored. Malformed skipped.
443
+ - `opts.hiddenEntryTypes` keeps disabled plugins' entries off every generic path. No replay.
444
+ - Core names no entry type.
445
+ - Live bridge: `custom-entry-forward.ts` excludes declared types.
446
+ - Client reducer `lib/plugins/plugin-entry-types.ts` (seeded in `App.tsx` from bundled registry) refuses generic rows.
447
+ - Server `CustomEventGroupResolver` never groups them.
448
+ - KNOWN BLOCKER: pi flushes custom entries only after first assistant message.
449
+ - `/api/health` `pluginEntries`: `declaredReplayTypes`, `replayedPluginEntries`, `rejectedPluginActions`.
453
450
 
454
- - Every frame still an idempotent FULL snapshot.
455
- - Latest-supersedes.
456
- - No delta encoding.
457
- - No wire key.
458
- - No version negotiation.
459
- - No producer change.
460
- - Dropped thin tick leaves no permanent hole.
451
+ ### Subagent delivery via plugin seams (change: move-subagents-to-plugin)
461
452
 
462
- **Pull path.**
453
+ Replaces the core thin-tick push/pull split (change: reduce-subagent-details-payload). Core names no subagent contract.
463
454
 
464
- - Client requests `subagent_resync_request`.
465
- - Bridge answers from retained fat snapshot as synthetic `subagents:started` frame.
455
+ **Boundary.**
466
456
 
467
- **Server resync locator.**
457
+ - Core carries no `subagents:*` channel, event map, frame buffer, strip, or resync frame.
458
+ - Enforced by `scripts/check-subagent-boundary.mjs`. Runs in `npm test`.
459
+ - Deleted from core: `SUBAGENT_EVENT_MAP`, `SubagentFrameBuffer`, `subagent-frame-strip.ts`, `subagent-forward-sites.ts`, `subagent_resync_request`, `useSubagentResyncCadence.ts`, `PI_DASHBOARD_SUBAGENT_STRIP`, tick throttle.
460
+ - Deleted e2e: tick-throttle, pull-measurements, thin-tick-liveness, pull-under-load specs.
468
461
 
469
- - `locateSubagentTimeline` (`packages/server/src/persistence/memory-event-store.ts`) now also matches `subagent_*` eventTypes carrying `details.entries`.
470
- - Before: resync reply fell to generic pass.
471
- - Before: any array > 20 items became string `"[array truncated]"`.
472
- - Before: reducer rendered no timeline.
473
- - Head-tail budget now applies: head + `⋯ N steps hidden ⋯` sentinel + tail.
474
- - `DEFAULT_MAX_EVENT_DATA_SIZE` = 262144.
462
+ **Generic seams.**
475
463
 
476
- **Open-inspector liveness.**
464
+ - Ownership: plugin manifest declares owned channels/event types. Server sends `plugin_ownership` table (`packages/server/src/plugin-ownership.ts`).
465
+ - Buffer: `StreamForwardBuffer` supports `latest` `group` + per-plugin `maxKeys`. Latest-wins per group key.
466
+ - Tool-update filter: bridge event `dashboard:register-tool-update-filter`. Registry `packages/extension/src/tool-update-filter-registry.ts`. Plugin filters `tool_execution_update` carrier.
467
+ - Server policies: `ctx.registerStorePolicy`, `registerDeliveryPolicy`, `registerReplayCarry`, `onSessionStatusEnded`, `appendEvent`. Registry `packages/server/src/plugin-policy-registry.ts`. Runtime types `packages/dashboard-plugin-runtime/src/server/plugin-policies.ts`.
468
+ - Replay carry: server sends `plugin_event_carry` frame after `history_window`, before first `event_replay`.
469
+ - Client state: `SessionState.pluginState` + `useSessionPluginState`. Reducer finalizer lookup `findFinalizerForEventType`.
470
+ - Version gate: manifest `requires.piExtensionVersions`. Subagents plugin `>=0.7.0`. Unmet range → `missingRequirements` → shown by shell plugin surfaces (Settings → Plugins, plugin settings page, Add-ons issues). Plugin renders no notice, reads no status.
477
471
 
478
- - File: `packages/client/src/hooks/useSubagentResyncCadence.ts`.
479
- - Mounted detail view re-fires `subagent_resync_request` on backoff cadence.
480
- - Base 2000 ms, doubles per idle tick, ceiling 30000 ms, resets on entry growth.
481
- - ONE timer per subagent → inline inspector + popout do not double-fire.
482
- - No `emptyTimeline` precondition on this trigger (open-time trigger keeps it).
472
+ **Subagents plugin implementations.**
483
473
 
484
- **Requester-scoped delivery.**
485
-
486
- - Request carries `requestId`.
487
- - Bridge echoes it on reply as `__resyncRequestId`.
488
- - Server routes reply to that one connection (`packages/server/src/pairing/subagent-resync-routing.ts`, `ResyncRequesterRegistry`, TTL 30000 ms).
489
- - Unknown/expired token falls back to normal broadcast.
490
-
491
- **Counters.**
492
-
493
- - `storeTrim.subagentTicks` / `subagentTickBytes` / `subagentFatTicks` / `subagentTickFatBytes` on `/api/health` (additive).
494
- - Bridge `SubagentFrameStats.resyncCadence` counts pull-loop requests.
495
-
496
- **Rollback. PARTIAL, not total.**
497
-
498
- - One flag: `PI_DASHBOARD_SUBAGENT_STRIP=0` forwards unstripped.
499
- - Flag disables STRIPPING ONLY.
500
- - Wire payload returns to pre-change shape: intermediate ticks fat again.
501
- - These stay ACTIVE under the flag: `locateSubagentTimeline` `subagent_*` gate.
502
- - Stay active: resync cadence in `useSubagentResyncCadence.ts`.
503
- - Stay active: requester-scoped routing (`requestId` / `__resyncRequestId`).
504
- - Stay active: additive `storeTrim` subagent-tick counters.
505
- - Each of those is additive or a bug fix. None depends on the strip.
506
- - No producer, protocol, or store rollback exists to do.
507
-
508
- **Known regression, stated deliberately.**
509
-
510
- - Run dying with NO terminal frame (crash/kill) leaves only thin ticks in store.
511
- - Recovery needs a LIVE bridge with agent still in the 64-slot `SubagentFrameBuffer`.
512
- - Evicted or post-reset agents answer `resyncNoop`.
513
- - Client keeps its last rendered state.
514
-
515
- ### Subagent Fan-out Admission (change: bound-subagent-fanout-under-host-pressure)
516
-
517
- **Problem.**
474
+ - `packages/subagents-plugin/src/bridge/index.ts` — forward channels, latest-wins buffer, tool-update filter, registry reconcile on `subagents:list`.
475
+ - `server/store-policy.ts` — store trim/keep rules for subagent events.
476
+ - `server/delivery-policy.ts` — per-connection delivery rules.
477
+ - `server/session-end-heal.ts` — `onSessionStatusEnded` heal of non-terminal agents.
478
+ - `server/replay-carry.ts` — `plugin_event_carry` payload for reconnect.
479
+ - `client/pluginState.ts` — plugin-owned reducer state in `SessionState.pluginState`.
518
480
 
519
- - Wide `Agent` fan-out on loaded host stalls parent event loop.
520
- - 13/14 census sessions died with unanswered fan-out as final transcript entry.
521
- - Stall triggers `hostPressure` unresponsive verdict; host reaps parent process.
481
+ **Invariants kept.**
522
482
 
523
- **Registration and ordering.**
483
+ - Every frame = idempotent FULL snapshot. Latest-supersedes.
484
+ - Terminal frames (`completed`/`failed`/`aborted`/`stopped`/`error`) never stripped.
485
+ - Dropped intermediate tick leaves no permanent hole.
524
486
 
525
- - Bridge registers admission gate on `tool_call` (`packages/extension/src/subagent-fanout-admission.ts`).
526
- - Registered AFTER pass-through forwarder in `bridge.ts`.
527
- - `runner.emitToolCall` stops at first `{block: true}` handler.
528
- - Earlier registration starves forwarder; dashboard misses `tool_call` while seeing `tool_execution_end`. Order load-bearing.
487
+ ### Subagent concurrency and stop (change: subagent-queue-visibility)
529
488
 
530
- **Concurrency bound.**
489
+ **Ownership.** Producer `@blackbelt-technology/pi-dashboard-subagents` >= 0.6.0 owns the one concurrency limit (`maxConcurrent`). Dashboard holds no `tool_call` admission gate. Excess `Agent` calls queue, never refused.
531
490
 
532
- - Bound measures in-flight concurrency per session, not batch width.
533
- - Platform drops assistant message before extension sees `tool_call`; batch size and batch identity unknowable.
534
- - In-flight counter increments at admission, not execution.
535
- - Siblings preflight sequentially before any executes; execution-time counter reads zero across whole batch.
536
- - Synchronous reject-only decision. Gate never awaits child; awaiting deadlocks preflight sequence.
491
+ **Setting.**
537
492
 
538
- **Configuration.**
493
+ - UI: Settings → Plugins → Subagents, field "Max parallel subagents" (`/settings/plugins/subagents`).
494
+ - Default `4`. Clamp `0`–`64`. `0` = unlimited.
495
+ - Live: applies within ~1 s, incl. waiting subagents.
539
496
 
540
- - Default cap: `DEFAULT_MAX_CONCURRENT_SUBAGENTS = 2` (`packages/shared/src/config.ts`).
541
- - Config key: `maxConcurrentSubagents`.
542
- - Value `0` disables gate (rollback).
543
- - Absent value resolves to active default (2).
544
- - Malformed non-integer or negative value resolves to `Infinity` (fail-open).
497
+ **Config mirror.**
545
498
 
546
- **Resource saturation.**
499
+ - `packages/subagents-plugin/src/server/index.ts` mirrors value to `~/.pi/agent/extensions/pi-dashboard-subagents/config.json`.
500
+ - Startup reconcile clamps file value.
501
+ - Write-through only when explicit and different from value producer runs.
547
502
 
548
- - Saturation narrows effective cap to 1 (never 0); saturated session still makes progress.
549
- - Private sampler: `subagent-saturation.ts`.
550
- - Dedicated `monitorEventLoopDelay` over fixed 5 s window plus own CPU baseline.
551
- - Never reads `collectMetrics()`: destructive read resets 15 s heartbeat histogram, corrupting crash telemetry.
552
- - Separates process domain (`process.cpuUsage()`, event loop delay) from machine domain (`os.loadavg()`).
553
- - Hysteresis: enter at threshold, exit only when all metrics fall below 80 % of threshold (`SATURATION_EXIT_RATIO = 0.8`).
503
+ **Heap coupling.**
554
504
 
555
- **Permit release.**
505
+ - `subagentHeapBudget(maxOldSpaceMb, maxConcurrent)` (`packages/shared/src/heap-limits.ts`) warns on plugin field.
506
+ - Warns when `floor(mb/(n+1)) < 100`; `0` warns under ceiling.
507
+ - Reads `GET /api/plugins/subagents/limits` → `{heapCeilingMb}`.
556
508
 
557
- - Releases permit on `tool_execution_end`.
558
- - Fires on normal, blocked, and aborted execution paths.
559
- - Never releases on `tool_result`: aborted call (Esc) skips result hook, leaking permits and starving session.
509
+ **Removed.**
560
510
 
561
- **Refusal semantics.**
511
+ - Admission config keys removed from `packages/shared/src/config.ts`. Leftover keys in `config.json` ignored.
512
+ - Automatic narrowing to 1 under host saturation removed. Constrained hosts lower the limit by hand.
513
+ - Old `subagent-admission-refused` entries resolve to `diagnostics` custom-event group (hidden by default).
562
514
 
563
- - Refusal returns `{block: true, reason}`.
564
- - Produces real errored tool result; renders terminal card with actionable retry reason.
565
- - Never sets `terminate`: refusal means re-issue later, not session abort.
515
+ **Per-subagent stop.**
566
516
 
567
- **Observability and durability.**
568
-
569
- - Refusal writes durable session entry `subagent-admission-refused` via `pi.appendEntry`. Survives process reap.
570
- - Admissions skip disk writes to protect hot path.
571
- - Live counters on `ProcessMetrics`: `fanoutAdmitted`, `fanoutRefused`, `fanoutSaturationRefused`.
572
-
573
- **Scope boundary.**
574
-
575
- - Gate runs per gated session, not per host process.
576
- - Subagent sessions skip bridge initialization via re-entry guard.
577
- - Grandchildren and `flow_agents` run ungated.
517
+ - Route `POST /api/plugins/subagents/stop`, body `{sessionId, agentId}`.
518
+ - Authority: `ctx.identity?.hasOperateAuthority` else `403`.
519
+ - Ids 1–128 chars, no control chars, else `400`. Unknown session `404`.
520
+ - Emits fixed `subagents:stop {agentId}` via `ctx.emitEventToSession`. Manifest `emits: ["subagents:stop"]`. Emit returns `false` → `503`.
521
+ - Behind `ctx.networkGuard`. Each request logs `stop request session=… agent=… outcome=…`.
522
+ - No fallback to session abort.
578
523
 
579
524
  ### Retry Lifecycle (change: retry-forever-with-stop-control)
580
525
 
@@ -582,10 +527,14 @@ Pi owns the retry loop. Dashboard configures + observes + renders it. Attempts f
582
527
 
583
528
  **1. Retry ownership & settings.**
584
529
 
585
- - Pi `RetrySettings` = `{ enabled, maxRetries, baseDelayMs, provider: {timeoutMs, maxRetries, maxRetryDelayMs} }`.
586
- - Session-layer delay = `baseDelayMs * 2^(attempt-1)`. Uncapped. No ceiling.
530
+ - Pi `RetrySettings` = `{ enabled, maxRetries, baseDelayMs, maxAgentDelayMs, provider: {timeoutMs, maxRetries, maxRetryDelayMs} }`.
531
+ - Session-layer delay = pi-ai `retryDelayMs`: `min(baseDelayMs * 2^max(0,attempt-1), maxAgentDelayMs ?? 60000)`.
532
+ - Unsafe product saturates to `MAX_SAFE_INTEGER`. Capped.
533
+ - Present since pi-ai 1.3.0 (extension peer floor). Call site: pi `AgentSession._prepareRetry`.
534
+ - Hidden cap made raised `baseDelayMs` look ignored past the cap. Old dashboard countdown used uncapped copy → showed e.g. 1382 s while pi slept 60 s. Fixed by change fix-retry-delay-cap.
587
535
  - `retry.maxDelayMs` REMOVED from session layer. pi migrates to `retry.provider.maxRetryDelayMs` (different layer, different semantics).
588
- - Overshoot consequence: next attempt lands ~2x elapsed. Scale-invariant. Tuning `baseDelayMs` shifts which attempt lands where, never the ratio.
536
+ - Overshoot consequence: next attempt lands ~2x elapsed. Holds only below the cap. Once `base*2^(n-1) > maxAgentDelayMs` every wait = cap (constant).
537
+ - Scale-invariant below cap. Tuning `baseDelayMs` shifts which attempt lands where, never the ratio.
589
538
  - Dashboard runs NO retry loop. Raising `retry.maxRetries` is the whole "retry forever" mechanism.
590
539
  - `resume mode:"continue"` cannot re-drive live turn (refused `resume.already_active`). For ended session resolves to `pi --session <file>` which reopens IDLE + drives no turn. No re-drive mechanism exists — none needed, since pi never settles turn while budget remains.
591
540
 
@@ -596,18 +545,25 @@ Pi owns the retry loop. Dashboard configures + observes + renders it. Attempts f
596
545
  - New rules: error `message_end` records pending error text → emits nothing. Error `agent_end` = attempt over + another coming → emits `auto_retry_start` + `auto_retry_waiting` (carries `attempt`, `delayMs`, `nextAttemptAt`), does NOT clear chain. `agent_settled` = SOLE terminal → emits `auto_retry_end`, clears chain.
597
546
  - Waiting signal suppressed once `attempt >= maxAttempts`.
598
547
  - `agent_settled` carries NO `messages` (verified pi 0.81.1/0.83), so tracker remembers terminal disposition via `lastEndWasError` at `agent_end`.
599
- - `-1` sentinels REMOVED. `maxAttempts` / `delayMs` sourced read-only from pi settings via `packages/extension/src/pi-retry-settings.ts` (defaults 3 / 2000; unreadable → `delayMs: 0` → surface renders elapsed-only).
548
+ - `-1` sentinels REMOVED. `maxAttempts` / `delayMs` sourced read-only from pi settings via `packages/extension/src/pi-retry-settings.ts` (defaults 3 / 2000 / cap 60000).
549
+ - `pi-retry-settings.ts` reads `retry.maxAgentDelayMs` (any finite number; project overrides global).
550
+ - `delayMs` from pi-ai `retryDelayMs` installed via `installPiAiDelayFn(tracker)` (fire-and-forget dynamic import, rejection swallowed); else local mirror `cappedDelay`.
551
+ - Guard in `delayFor`: base `<=0` or attempt `<1` → 0.
552
+ - fn throw / non-number / non-finite → `cappedDelay`.
553
+ - Final negative or non-finite → 0 (elapsed-only).
554
+ - Parity test `packages/extension/src/__tests__/retry-delay-parity.test.ts` asserts mirror == pi-ai across grid.
600
555
  - pi 0.83 exposes retry lifecycle events to RPC/SDK consumers ONLY. ExtensionAPI has no `auto_retry_*` and nothing on EventBus. `willRetry` in 0.83 is compaction-only (`session_before_compact`/`session_compact`). Bridge is extension → must observe-synthesize.
601
- - Native `agent_settled` guaranteed at the 1.3.0 lockstep floor (`piCompatibility.minimum == recommended == 1.3.0`). Bridge consumes the native settle unconditionally — no version gate, no floor-pi synthesis. Floor-pi synthesis module `packages/extension/src/agent-settled.ts` DELETED. `agent_settled` remains the SOLE terminal retry signal. See change: update-pi-core-0-85-adopt-apis.
556
+ - Native `agent_settled` guaranteed at the 1.7.0 lockstep floor (`piCompatibility.minimum == recommended == 1.7.0`). Bridge consumes the native settle unconditionally — no version gate, no floor-pi synthesis. Floor-pi synthesis module `packages/extension/src/agent-settled.ts` DELETED. `agent_settled` remains the SOLE terminal retry signal. See change: update-pi-core-0-85-adopt-apis, update-pi-core-1-7-adopt-apis.
602
557
  - Bridge follow-up drain (`bridgeFollowUp`) triggers on `agent_settled`, not `agent_end`. Forwarder schedules `drainFollowupQueue()` via `setTimeout(0)`; pi clears run-active before `agent_settled`, so `isIdle()` is true. No retry loop: a false `isIdle()` returns, the next `agent_settled` drains. Gate sequence: `packages/extension/src/followup-drain.ts`. See change: update-pi-core-1-3-adopt-apis.
603
558
 
604
559
  **3. Settings write + reload-on-save** (`packages/server/src/pi-agent-settings.ts`).
605
560
 
606
- - Reads/writes all SIX native fields: `retry.{enabled,maxRetries,baseDelayMs}` + `retry.provider.{timeoutMs,maxRetries,maxRetryDelayMs}` in GLOBAL `~/.pi/agent/settings.json`. Blank `provider.timeoutMs` OMITTED on write (never `0`/`null`).
561
+ - Reads/writes all SEVEN native fields: `retry.{enabled,maxRetries,baseDelayMs,maxAgentDelayMs}` (`maxAgentDelayMs` default 60000) + `retry.provider.{timeoutMs,maxRetries,maxRetryDelayMs}` in GLOBAL `~/.pi/agent/settings.json`. Blank `provider.timeoutMs` OMITTED on write (never `0`/`null`).
607
562
  - Write is MERGE-PRESERVING: every other key survives, including `retry.provider.*`.
608
563
  - Project `<cwd>/.pi/settings.json` NEVER written.
609
564
  - Distinct from `config-api.ts`, which writes dashboard's own `~/.pi/dashboard/config.json`.
610
- - Validation: `maxRetries` non-negative integer; `baseDelayMs` positive integer. Invalid → nothing written.
565
+ - Validation: `maxRetries` non-negative integer; `baseDelayMs` positive integer; `maxAgentDelayMs` non-negative integer (0 = no wait, legal). Invalid → nothing written.
566
+ - Preview `computeSchedule(maxRetries, base, cap)` in `packages/client/src/components/settings/RetrySettingsSection.tsx` uses capped curve. O(1) past cap (closed-form remainder). `retry-cap-notice` names first capped attempt.
611
567
  - No UI cap on `maxRetries`; long tail WARNED, never capped.
612
568
  - REST: `GET/PUT /api/pi-retry` (`packages/server/src/routes/pi-retry-routes.ts`), auth-gated by same network guard as `/api/config`.
613
569
  - pi reads settings only at session construction. Write alone inert for running sessions.
@@ -615,7 +571,7 @@ Pi owns the retry loop. Dashboard configures + observes + renders it. Attempts f
615
571
  - Target set = `reloadTargetSessionIds` = `piGateway.getConnectedSessionIds()` ∪ `headlessPidRegistry.listSessions()`.
616
572
  - Connected-only set missed headless sessions with dead bridge WS. See change: fix-out-of-band-reload.
617
573
  - Failed write reloads nothing.
618
- - **UI placement + save.** Editor renders on Settings **Sessions** tab (NOT Providers). Reason: 3 fields (`enabled`, `maxRetries`, `baseDelayMs`) turn-level not provider-scoped; observable effect on session (waiting / attempt n / countdown / Stop). Sibling turn-lifecycle settings co-located.
574
+ - **UI placement + save.** Editor renders on Settings **Sessions** tab (NOT Providers). Reason: 4 fields (`enabled`, `maxRetries`, `baseDelayMs`, `maxAgentDelayMs`) turn-level not provider-scoped; observable effect on session (waiting / attempt n / countdown / Stop). Sibling turn-lifecycle settings co-located.
619
575
  - Enclosing section titled "Retry".
620
576
  - NO private Save button. Registers with panel unified-Save draft registry via `useSettingsDraftSource({id:"pi-retry", page:"sessions", isDirty, commit, reset})`. See change: unify-settings-save-contract.
621
577
  - Consequences: one Save commits every dirty store. Sessions nav shows per-page dirty dot. Leave guard offers Save / Discard / Cancel.
@@ -754,6 +710,8 @@ Status-based dispatch rests on invariant: `register()` is only path to non-ended
754
710
 
755
711
  **Health.** `/api/health#droppedFrames` counters `statusReconcileQueued` (entries recorded owed) + `statusReconcileSent` (reconcile frames re-sent) count every registry kind. No new `/api/health` field. Accepted health-counter shift: shed reorders move from `droppedFrames.total` to `coalescedState`. `/api/health#socketBufferOccupancy` = `{ max, p95, msAboveThreshold }` over browser-socket `bufferedAmount`; typed-zero fallback `EMPTY_SOCKET_BUFFER_OCCUPANCY`. Sampled at the send-decision sites, which already read `bufferedAmount` for the shed predicate — **not** on a timer. A periodic sampler was implemented first and rejected: it breaks the "zero timers on an unsaturated socket" invariant (`browser-gateway-critical-frames` P3/E9). Time-above-threshold uses a per-socket entry/exit span (`occupancyAboveSince`); the hot exit branch is gated on `size > 0`.
756
712
 
713
+ **Subagent end / liveness frames are deferred, not shed** (change: fix-background-subagent-ghost-rows). `deferKeyOfEvent(msg)` keys `subagent_completed` / `subagent_failed` (real end `subagent_end:<sid>:<id>`, heal `subagent_heal:<sid>:<id>`), `subagent_stop_result` (`subagent_stop_result:<sid>:<agentId>`) and `subagent_registry_snapshot` (`subagent_registry_snapshot:<sid>`); no string id → no key → shed. `frameClassOf` is unchanged (still `transcript`). Healthy socket → full frame. Where `sendTo` would shed, a bounded projection (`projectDeferredSubagentFrame`: no timeline, `result`/`error` ≤ 8 KB, `deferredProjection:true`) goes to `sendState` under its key. Counted `/api/health#droppedFrames.deferredSubagentFrames` (also under `serverToBrowser`) — not a drop. The client replay persister never caches a `deferredProjection` event.
714
+
757
715
  **`msAboveThreshold` is OBSERVATION-based, not continuous wall-clock.** Sampling happens at send decisions, so a crossing that starts and ends between two decisions is never observed, and a reported duration is bounded by the samples that delimit it. `getSocketBufferOccupancy()` adds spans still open at read time (else an in-progress stall reports 0), and SETTLES a span whose socket has since drained or closed — without that, an event-driven sampler leaves such a span open forever and it grows on every health read (unbounded over-report). Settling deletes the entry, so a later exit cannot accrue it twice.
758
716
 
759
717
  **Test-only injector.** `POST /api/test/force-shed { enabled }` forces transcript-class frames to shed while leaving `bufferedAmount` untouched. Registered ONLY under `PI_E2E_FORCE_SHED=1` (set in `docker/compose.test.yml`, never a real image); still `networkGuard`-gated. Returns the effective state, so an unflagged server reports refusal instead of a silent no-op. Exists because real saturation is a browser failing to drain its own socket, which Playwright cannot induce. Drives `tests/e2e/status-reconcile.spec.ts`.
@@ -774,6 +732,37 @@ On browser connect, gateway emits ONE `sessions_snapshot { sessions, orders, end
774
732
 
775
733
  See change: `fix-connect-snapshot-frame-loss`.
776
734
 
735
+ ### Session route resolution + deep links (change: add-session-ui-deep-links-for-agents)
736
+
737
+ Agents open `/session/:id[/diff|/editor]` with any id form. Client resolves to canonical held id.
738
+
739
+ - **Raw param.** Route `:id` stays RAW. `useSessionRouteResolution` (`packages/client/src/hooks/useSessionRouteResolution.ts`) resolves synchronously during render. `selectedId` in `App.tsx` = canonical id (`undefined` while pending / not found). Status: `none|pending|ok|ambiguous|notFound|vanished`.
740
+ - **Matching.** `resolveSessionRouteId` (`lib/session/resolve-session-route-id.ts`): raw exact wins; else case-insensitive exact; else unique prefix ≥ 8 chars (`MIN_SESSION_PREFIX`). Several prefix hits → `ambiguous` (candidate links). < 8 chars → `none`. Returned id = held live-cased id.
741
+ - **Prefix verification.** Prefix-only match commits only after this connection's `GET /api/sessions?id=` lookup merged. Prefix unique among held ids can be ambiguous across owner-visible registry (older ended sessions outside snapshot window). Merge → `ambiguous` (candidate links). Status `pending` meanwhile. Lookup network / 5xx failure → fall back to held match. Full id or case-only difference commits without lookup.
742
+ - **Canonical URL.** `useCanonicalRouteUrl` navigates with `replace` to canonical id. Keeps suffix + query.
743
+ - **Snapshot window gap.** Snapshot holds non-ended + newest ended only (see Sessions snapshot window). Older ended arrive via `sessions_page`. Miss after snapshot → one `GET /api/sessions?id=<routeId>` per route id per connection (`lib/api/sessions-lookup-api.ts`).
744
+ - **Server filter.** Single-valued `id`. Case-insensitive exact or prefix ≥ 8 chars. Applied after `filterOwned`. Array `id` → 400.
745
+ - **Merge.** Lookup rows merge into `sessions` Map ONLY. Stripped of `notifyLog`, `uiUrl`, `diffUrl`. Order map, `endedTotals`, paging untouched.
746
+ - **`lookupOnlyIds`.** Tracks merged ids. Excluded from held-ended count (`heldEndedByGroup`) until `sessions_page_result` delivers them or snapshot clears the set.
747
+ - **Reconnect / server switch.** `snapshotGeneration` resets to 0. Resolved id sticky per route visit → open session never blanks.
748
+ - **Stale lookup replies.** Connection epoch bumps every time snapshot gate flips (snapshot lands; reconnect / server switch resets `snapshotGeneration` to 0). Lookup started in one epoch discarded if epoch changed before reply. Reply from server A never merges into server B `sessions` / `lookupOnlyIds`.
749
+ - **Vanished.** Was held, lookup returns empty (archived while viewing, or switch to server lacking it) → `useVanishedRedirect` does `navigate("/", { replace: true })` once.
750
+ - **Never existed.** Inline `SessionNotFound` (`data-testid="session-not-found"`). No redirect — agent must see evidence.
751
+ - **Pending.** `session-resolving` placeholder.
752
+ - **Lookup errors.** 401/403 → auth-loss path (`loginRedirectFor`). Network / 5xx → `notFound` + retry.
753
+ - **`ShellContent`.** Takes `sessionRoute` prop. Ignored when `frozen`.
754
+
755
+ **Deep-link URLs.** `GET /api/sessions` rows carry `uiUrl` / `diffUrl` (`SessionListItem`, `packages/shared/src/rest-api.ts`; helper `sessionUiPath`, `packages/shared/src/session-ui-path.ts`).
756
+
757
+ - Base from `resolveRequestUiBase` (`packages/server/src/routes/ui-link-base.ts`).
758
+ - Order: configured origin (public bases, live tunnels, `auth.redirectBaseUrl`) whose hostname matches first `X-Forwarded-Host`, then `Host`; else admitted `Host`; else `http://localhost:<port>`.
759
+ - `X-Forwarded-Host` only selects among configured origins. Never mints one.
760
+ - `trustProxy` stays off.
761
+ - zrok public share forwards `Host: <share>.shares.zrok.io`. No `X-Forwarded-Host`. `X-Forwarded-Proto: https`.
762
+ - Agent panes append `?embed=1` (see `docs/embedding-chat-view.md`).
763
+
764
+ See change: `add-session-ui-deep-links-for-agents`.
765
+
777
766
  ### Notify Flow (`ctx.ui.notify` → browser, split from prompt_request)
778
767
 
779
768
  Change: `split-notify-from-prompt-request`. `ctx.ui.notify` used to ship over `prompt_request`. Every consumer treated it as an unanswered ask → `trackPromptRequest` → `currentTool="ask_user"` re-armed on every quiescent moment → permanent "Needs you", false unread, `questionFirst` reorder, and a session the embed-lifecycle reaper could never reclaim. Now a dedicated `notify` message type end to end.
@@ -954,8 +943,50 @@ pi-flows runs multi-agent workflows in-process. Subagent sessions use `SessionMa
954
943
  5. React renders `FlowDashboard` (sticky card grid above ChatView), `FlowAgentDetail` (replaces chat), `FlowSummary` (post-completion). Component code lives in `packages/flows-plugin/src/client/` and is imported by the shell via `@blackbelt-technology/pi-dashboard-flows-plugin/client`. Slot-consumer-based mounting is tracked as the follow-up change `migrate-flows-jsx-to-slots`; the current shell imports the components directly. See change: extract-flows-as-plugin.
955
944
 
956
945
  **Flow controls (browser → pi-flows):**
957
- - Abort: browser sends `flow_control { action: "abort" }` → server → bridge → `pi.events.emit("flow:abort")` → `flowManager.abort()`
958
- - Autonomous toggle: browser sends `flow_control { action: "toggle_autonomous" }` → same path → `setAutonomousMode()`
946
+ - Flow commands: `plugin_action { pluginId: "flows", action }`, action ∈ `flow.abort | flow.ask-session | flow.dismiss-summary | flow.run | flow.delete | flow.set-edit-mode`. Handled in `packages/flows-plugin/src/server/flow-control.ts`.
947
+ - REST: `POST /api/plugins/flows/control` (operate authority + network guard). ACP session → 409 `unsupported_for_acp`.
948
+ - MCP tool: `flows_control`.
949
+ - Probe channel for models: `models:get-available`.
950
+ - Flow types (`FlowState` etc.) live in `packages/flows-plugin/src/types.ts`, not shared.
951
+
952
+ **Flow actions UI (flows-dock-chip-and-panel-actions):**
953
+ - `FLOWS` chip: `composer-context-group` claim.
954
+ - Panel headers (`FlowDashboard`, `FlowSummary`): Run again / Open flow… / Edit….
955
+ - Panels default collapsed.
956
+ - Session actions menu: New flow… / "Turn on edit mode for this project" only for flowless sessions.
957
+ - Shared logic: `useFlowActions(session)` + `<FlowActionDialogs>`.
958
+ - Flow list source: `useFlowCatalog(sessionId)` → `flow_catalog` (see Plugin-declared event forwarding).
959
+
960
+ **Agent `flow_open` tool (add-flow-open-tool):**
961
+ - Bridge `packages/flows-plugin/src/bridge/flow-open-tool.ts` registers pi tool `flow_open` via `pi.registerTool`.
962
+ - Loads only where flows plugin bridge loads. pi-flows unchanged.
963
+ - Params: exactly one of `flow` (catalog `<ns>:<name>`, runnable) or `path` (flow.yaml/flow.yml or dir directly containing one; view-only). Else `refused/invalid-arguments`.
964
+ - `promptGuidelines`: call `flow_open` after writing/editing/inspecting a flow.
965
+ - Bridge tracks active `runId`: `flow:flow-started` sets; `flow:complete` same `runId` clears; `session_start` resets. Active run → local `refused/flow-running`.
966
+ - Relative `path` resolved vs tool ctx cwd.
967
+ - Lane `requestPluginServer("flows","flow/open")`. Lane error or missing seam → `refused/unavailable`. Never throws.
968
+ - Server `packages/flows-plugin/src/server/flow-open.ts` `registerFlowOpen`: lane `hubLocalOnly`. Session id from lane meta only.
969
+ - `flow`: lookup `stateStore` catalog. Miss → `requestCatalog(sid,{rediscover:true})`, retried while cooldown-suppressed, poll 100 ms up to 1.5 s → else `unknown-flow`.
970
+ - `path` admission (`locateFlowPath`): resolve vs session cwd → realpath → dir ⇒ direct `flow.yaml|flow.yml` → regular file ≤ `MAX_FILE_BYTES` (1 MiB) → confined to `realpath(cwd)` (cwd `/` handled). Refusals `path-not-allowed` / `not-a-flow`.
971
+ - No content read before admission. Then read via host `readFileGuarded` (absent → `unavailable`).
972
+ - Dir without direct flow → `candidates` (≤20, cwd-relative). Walk: lstat BFS depth ≤6, skip `node_modules`/`.git`, no symlink follow. Walk visits ≤2000 dirs.
973
+ - Dir pick: first regular `flow.yaml`, else `flow.yml`. Definition must carry `steps` array, else `not-a-flow`.
974
+ - Path equal to catalog definition (canonical; catalog `source` resolved vs cwd) → opens as catalog flow (runnable).
975
+ - Path-opened flow files → `FlowFileRegistry.open()` (shared `flowFileRegistry`): def + code handlers + reported agents it names, each confined to cwd.
976
+ - Registry entries survive `report()`. Dropped on session end.
977
+ - Each `/api/plugins/flows/file` read re-realpaths (must be unchanged + inside cwd) else 403. Host routes unchanged.
978
+ - Delivery: broadcast `flows_open {sessionId, requestId, attachment{name, source, viewOnly, baselineStartedAt: Date.now()}}`.
979
+ - `baselineStartedAt` = call accept time, stamped before catalog rediscovery wait.
980
+ - `frameClassOf` classes it `state`, key `flows_open:<sessionId>:<requestId>` (never shed; never coalesced; each pin acked). Owner-scoped where identity enforced.
981
+ - Client `FlowOpenListener` (`shell-headless` claim): stores attachment per device (`flow-attach-store`).
982
+ - Client expands panel (`setFlowCollapsed(sid,["dashboard"],false)`). Sends `flows_open_ack {sessionId, requestId}` (tier `observe`, session-owned). Dedupe 128 requestIds.
983
+ - Server counts acks per ws over fixed 1.5 s window (pending map ≤ 64) → `shown {acks, name, path, viewOnly}` or `no-viewer`.
984
+ - Full pending map → new call `refused/rate-limited`; never evicts an open window.
985
+ - Rate limit 10 calls / 10 s per session (cleared on session end) → `rate-limited`.
986
+ - One `logger.info` per call: `flow_open session=<id> kind=<flow|path> outcome=<…> reason=<…> acks=<n>`. Never file content.
987
+ - View-only panel: no Run, no Edit…. Label "view only - not registered".
988
+ - View-only definition fetched with `fetchFlowFile(..., {noHostFallback:true})`.
989
+ - Load error adds "ask the agent to open it again" hint + Close.
959
990
 
960
991
  ### Extension UI System (Phases 1 + 2 shipped)
961
992
 
@@ -1073,7 +1104,7 @@ sequenceDiagram
1073
1104
 
1074
1105
  **Relationship to existing capabilities:**
1075
1106
  - `interactive-ui-dialogs` / `ui-proxy` / PromptBus — handle one-shot `ctx.ui.*` dialogs (request/response, awaited). The extension-ui-system handles persistent push-based descriptors (no awaiting). Orthogonal mechanisms; both ship.
1076
- - `extension-ui-forwarding` (per-channel declared-set forwarding) — bridge forwards via one `pi.events.on` subscription per declared channel (`registerEventBusForwarding`). Channels: core `FLOW_EVENT_MAP` / `SUBAGENT_EVENT_MAP` + plugin-declared via `dashboard:register-event-forward`. RPC probe channels (`flow:list-flows`, `roles:*`, `model:resolve`, `ui:list-modules`…) kept out of core map; plugin declarations naming one not rejected. No `emit` wrapper. The new system is the *declarative* path for UI specifically. No authored spec — file removed (0-byte placeholder since initial commit). See change: repair-corrupted-main-specs. See change: skip-rpc-probes-in-event-forwarder.
1107
+ - `extension-ui-forwarding` (per-channel declared-set forwarding) — bridge forwards via one `pi.events.on` subscription per declared channel (`registerEventBusForwarding`). Channels: plugin-declared (no core map) via `dashboard:register-event-forward`. RPC probe channels (`flow:list-flows`, `roles:*`, `model:resolve`, `ui:list-modules`…) kept out of core map; plugin declarations naming one not rejected. No `emit` wrapper. The new system is the *declarative* path for UI specifically. No authored spec — file removed (0-byte placeholder since initial commit). See change: repair-corrupted-main-specs. See change: skip-rpc-probes-in-event-forwarder.
1077
1108
  - pi-flows: in Phase 3 pi-flows itself adopts the system to surface registered workflows (breadcrumb), gates, and cards (agent-metric) for any flow-using extension automatically.
1078
1109
 
1079
1110
  **No-dashboard fallback:** When no bridge is connected, `ui:list-modules` is never emitted; extension listeners are dormant; slash commands fall back to existing text-output behavior. Extensions remain pi-runnable in pure-pi mode without code changes.
@@ -1097,9 +1128,47 @@ First-party slots (React, possibly also descriptor):
1097
1128
  - `content-view` — full-screen content area (replaces every conditional branch in `App.tsx` for `ArchiveBrowserView`, `SpecsBrowserView`, `OpenSpecPreview`, `FlowAgentDetail`, `FlowArchitectDetail`, `MarkdownPreviewView`, `FileDiffView`, `FlowYamlPreview`). Descriptor variant reuses `management-modal`.
1098
1129
  - `content-header-sticky` — sticky element above content-view (replaces sticky `FlowArchitect`/`FlowDashboard`). Descriptor variant reuses `breadcrumb`.
1099
1130
  - `content-inline-footer` — inline element below content-view (replaces `FlowSummary`). React-only.
1100
- - `composer-context-group` — labelled read-only context groups inside the chat composer's session-action strip (`ComposerSessionActions`), after the Git group, before the Status group. Multiplicity `many`, tier `react-only`, claim `{ component }`, context props `{ session, pluginContext }`. Outside the Status group's streaming `<fieldset disabled>` — stays visible mid-run. Runtime exports `ComposerContextGroupSlot` + primitive `ComposerContextGroup` (keeps signature, delegates to `ToolbarGroup` variant `info`). First claimant: quota plugin's `QuotaWidget`. See change: move-quota-to-context-strip; redesign-composer-session-strip.
1131
+ - `composer-context-group` — labelled read-only context groups inside the composer dock's Context lane (`ContextLane.tsx`), ahead of the Status group. Formerly the session-action strip (`ComposerSessionActions`). Multiplicity `many`, tier `react-only`, claim `{ component }`, context props `{ session, pluginContext }`. Outside the Status group's streaming `<fieldset disabled>` — never working-gated, stays live mid-run. Runtime exports `ComposerContextGroupSlot` + primitive `ComposerContextGroup` (keeps signature, delegates to `ToolbarGroup` variant `info`). First claimant: quota plugin's `QuotaWidget`. See change: move-quota-to-context-strip; redesign-composer-session-strip; add-composer-dock.
1132
+ - `composer-dock-process-group` — group of running-work rows inside the composer dock's Processes lane, before core Commands + Background groups. Multiplicity `many`, tier `react-only`, claim `{ component }`, session-scoped (predicate input = `DashboardSession`). Props `{ session, pluginContext, mode: "summary"|"rows", reportSummary(summary: ProcessGroupSummary | null) }`. `ProcessGroupSummary = { count: number; noun: string }`. `summary` mode: always mounted while session bound, renders `null`, only reports; adds no DOM/focus/timer. `rows` mode: mounted only while lane body shown, renders `ComposerDockRow`s, never reports. `noun` printed verbatim after `count` — claim agrees noun with count (`subagent` / `subagents`). `null` or `count ≤ 0` = nothing runs. Dock keeps `Map<claimKey, summary>`, drops entry on unmount. Runtime exports `ComposerDockProcessGroupSlot({ session, mode, onReport?, wrapClaim? })` + primitive `ComposerDockRow` (`packages/dashboard-plugin-runtime/src/ComposerDockRow.tsx`: 32 px row, 16 px icon box, truncation, action targets ≥24 px / ≥44 px below `md`, elapsed from `startedAt` in leaf `DockRowElapsed` owning its 1 s tick). First claimant: subagents plugin `SubagentDockGroup` (`packages/subagents-plugin/src/client/SubagentDockGroup.tsx`; Open → `/session/:sid/subagent/:aid`; status `created` → `pending`; dedupes by `state.id`). Additive: `PLUGIN_HOST_API_VERSION` 1.0.0 → 1.1.0. See change: add-composer-dock.
1133
+
1134
+ **Composer stack (`ComposerDock`):** one dock above one composer card replaces the old stack (`composer-context-strip`, `StatusBar`, `QueuePanel`, `YoloComposerStrip`). `ComposerSessionActions` strip superseded — its OpenSpec + Git content split into lanes (paragraph below kept for `ToolbarGroup` primitive details).
1135
+
1136
+ ```mermaid
1137
+ flowchart TB
1138
+ CV["ChatView (shrinkable)"] --> SB["SessionBanner (fixed)"]
1139
+ SB --> AN["composer-stack-anchor (fixed, content-height chip slot)"]
1140
+ AN --> DK
1141
+ subgraph DK["composer-dock (shrinkable)"]
1142
+ direction TB
1143
+ SC["composer-dock-scroll: Processes · Changes · OpenSpec · Queue · Context"]
1144
+ YF["YOLO footer (flex-none, h-8)"]
1145
+ end
1146
+ DK --> CI["CommandInput card: textarea + one toolbar row"]
1147
+ ```
1101
1148
 
1102
- **Composer session-action strip (`ComposerSessionActions`):** host groups (OpenSpec, Git, Status) + plugin `composer-context-group` contributions render through one primitive `ToolbarGroup({ label, variant: "actions"|"info", testId?, labelTestId?, contentAs?: "div"|"fieldset", contentProps?, className? })` (`packages/dashboard-plugin-runtime/src/slot-consumers.tsx`). Renders `<div data-group role="group" aria-labelledby>` + label `<span id>` (`useId`) + content element carrying `data-group-content`. `actions` variant: solid outline, `--bg-tertiary` fill, label segment on `--bg-surface`, hairlines between direct children, children ≥24 px targets. `info` variant: dashed outline, no fill (read-only readouts). Label test id = `labelTestId ?? (testId ? `${testId}-label` : undefined)` — never `undefined-label`. a11y contract change: every claimant becomes a named `role="group"` region; contributions drop own chip borders (quota plugin did). Host containers `composer-{openspec,git,status}-container`; legacy ids `composer-{openspec,git,status}-group-label`, `composer-git-group`, `composer-status-group` kept (Status content is `<fieldset disabled={working}>`). `packages/client/src/index.css`: `[data-group]:has(> [data-group-content]:empty) { display:none }` hides empty group (e.g. all badge claims render null). See change: redesign-composer-session-strip.
1149
+ - `composer-stack-anchor` = canvas chip slot (`shrink-0 mx-5`, 0 px while no chip). `CanvasDriver` portals chip tray into it while live composer + chat pane visible. No live composer or `full` editor mode → fixed bottom-right overlay fallback. See change: fix-chat-transcript-layout.
1150
+
1151
+ - Sibling of `CommandInput`, never inside it. Mounted by `ComposerDockHost.tsx` (hook boundary for `App.tsx`; also `DirectoryHomeView.tsx`). Visual join CSS only: `mx-5` inset (8px inside card edges, drawer look), `-mb-6 pb-6` tucks bottom edge 12px under card; `composer-root` drops its full-width `border-t` while dock visible (index.css sibling rule). team-app `ChatPane` embeds `CommandInput` bare: no dock.
1152
+ - Nothing renders for `readOnly` (archived) views or when no lane and no YOLO footer.
1153
+ - Files (`packages/client/src/components/chat/`): `ComposerDock.tsx` (layout, accordion render, compact mode, YOLO footer, live region), `composer-dock-model.ts` (`DockLane`, `DockLaneKey`, `DOCK_LANE_ORDER`, `useDockAccordion`), `useComposerDockLanes.ts` (builds Changes/OpenSpec/Queue/Context lanes), `ProcessesLane.tsx` + `ProcessesLaneBody.tsx` (built into dock), `ChangesLane.tsx`, `QueueLane.tsx`, `ContextLane.tsx`, `useDockCompactMode.ts`.
1154
+ - Lane order fixed: Processes, Changes, OpenSpec, Queue, Context. Lane renders only with content. Lane = `DockLane { key, label, icon, title, meta, summary, summaryText, actions, renderBody, expandable, live }`.
1155
+ - Accordion: one `openLane: DockLaneKey | null`, controlled by `App.tsx` via `useDockAccordion(selectedId)`. Resets to `null` on every session bind. At most one lane open. Nothing auto-expands; nothing persisted.
1156
+ - Row layout (composer column ≥ 32.5rem): each lane `role="group"`; expandable header = one stretched disclosure button (`aria-expanded`/`aria-controls`); actions siblings of it, never nested.
1157
+ - Compact mode (< 32.5rem = 520 px at 16 px root, `DOCK_COMPACT_REM`): one sticky chip per lane, every lane incl. Context + unattached OpenSpec; chip opens sheet below chips. Width via `ResizeObserver` on composer column (`bottom` stack), not dock → no feedback loop. Flip evaluated ≤ once per animation frame; exact at threshold, no hysteresis; width 0 never flips. `openLane` survives flip; focus moves to chip/toggle only if it was inside open lane.
1158
+ - Scroll: lanes in `composer-dock-scroll` (`min-h-0 overflow-y-auto`). YOLO footer `flex-none` outside it: never collapsed, never chip, never scrolled away. Dock shrinks before transcript.
1159
+ - Live region: one sr-only polite `role="status"`, sibling of lanes, never ancestor of YOLO footer. Announces count strings only. Elapsed clocks tick in leaves outside it.
1160
+ - Processes lane: subagents via `composer-dock-process-group` slot (summary + rows mounts); Commands from `useInflightBashTools` (Show → scroll to tool card; includes bash nested in `Agent` calls); Background from `DashboardSession.processes` (Kill → `kill_process { pgid }`, SIGTERM to group). Header count = core counts + claim summaries. Turn stops only via composer Stop.
1161
+ - Changes lane: header = Git worktree identity + worktree actions (`GitIdentity`, `WorktreeActionsMenu`) + `N files +A −D` + Review. Renders when `session.gitWorktree` set or diff lists files. Body lists session-owned in-cwd files from `GET /api/session-diff`; out-of-cwd entries listed apart, no diff link, outside count. Server cap `MAX_FILES = 200` → header shows `200+`.
1162
+ - `useDockDiff(sessionId, { working, dirtyCount, expanded })` (`packages/client/src/hooks/useDockDiff.ts`) wraps `useSessionDiff`. Triggers: first load; working→idle falling edge (`isComposerWorking`); `gitStatus.dirtyCount` change while idle; lane expand; Retry. Coalescing: ≤ 1 request in flight; trigger during request or inside window sets one pending flag; never dropped. `DOCK_DIFF_WINDOW_MS` 2000 min gap between starts. `DOCK_DIFF_SETTLE_MS` 1000 delay for turn-end/dirty triggers → same-second signals = one request. Back-off: request slower than `DOCK_DIFF_SLOW_MS` 300 ms doubles gap (2 s → 4 → 8, cap 30 s); fast request resets.
1163
+ - OpenSpec lane: `ComposerSessionActions.tsx` split, not rewritten; keeps readiness gate, attach flow, traceable archived/missing attachments (`showTrace`), single primary action, working-state rules. Title = attached change name + task count. Open proposal / Refresh / Detach in `⋯`. Expand → next open tasks via `fetchTasks(cwd, change)`.
1164
+ - Queue lane: embeds `QueuePanel` cycler (`embedded` prop hides own subtitle + clear-all; Clear all in lane header). Context lane: `composer-context-group` claims (never gated) + Status group (`<fieldset disabled={working}>`, keeps working gate).
1165
+ - YOLO footer: former `YoloComposerStrip`, height `YOLO_FOOTER_HEIGHT` = 32 px (`h-8`), `whitespace-nowrap`, sentence ellipsized. Test id `yolo-composer-strip` kept.
1166
+ - Composer card: one toolbar row (`composer-settings-row`). `+` = only fold host (absorbs Terminal; no `⋯` overflow). `Steer ▾` dropdown, folds into `+` below 420 px (`@[26.25rem]`). Working status word via `workingStatusLabel` (`packages/client/src/lib/chat/working-status.ts`; `StatusBar.tsx` deleted). One merged `model · thinking` chip wrapping `ModelSelector`. Round send/stop button at toolbar end, token fills only. Fold thresholds `@[55rem]`/`@[40rem]`/`@[26.25rem]`.
1167
+ - Pane height budget (`packages/client/src/lib/layout/chat-pane-row-class.ts`, `CHAT_PANE_ROW_TABLE`): `composer-context-strip`, `status-bar`, `queue-panel` entries removed. Added `composer-dock` (shrinkable, weight `DOCK_WEIGHT` 1, floor = `YOLO_FOOTER_HEIGHT` 32 + `DOCK_LANE_HEADER_FLOOR` 41 = 73, bound 32) and `composer-dock:footer-only` (YOLO, no lanes; floor 33, bound 32). App picks key by state. `chat-pane-row-completeness.test.ts` asserts `floor > bound` per entry and every rendered row listed.
1168
+ - Test ids: surviving ids kept; removed `composer-context-strip`, `status-bar`, `composer-session-actions`, composer `overflow-button`/`overflow-menu`; new dock root `composer-dock`.
1169
+ - No server, bridge protocol or persisted-data change. Rollback = revert client + shared slot decl + runtime + subagents plugin together; remove plugin claim before slot (validator rejects unknown slot id). See change: add-composer-dock.
1170
+
1171
+ **Composer session-action strip (`ComposerSessionActions`, superseded by `ComposerDock`; `ToolbarGroup` primitive still used by lanes):** host groups (OpenSpec, Git, Status) + plugin `composer-context-group` contributions render through one primitive `ToolbarGroup({ label, variant: "actions"|"info", testId?, labelTestId?, contentAs?: "div"|"fieldset", contentProps?, className? })` (`packages/dashboard-plugin-runtime/src/slot-consumers.tsx`). Renders `<div data-group role="group" aria-labelledby>` + label `<span id>` (`useId`) + content element carrying `data-group-content`. `actions` variant: solid outline, `--bg-tertiary` fill, label segment on `--bg-surface`, hairlines between direct children, children ≥24 px targets. `info` variant: dashed outline, no fill (read-only readouts). Label test id = `labelTestId ?? (testId ? `${testId}-label` : undefined)` — never `undefined-label`. a11y contract change: every claimant becomes a named `role="group"` region; contributions drop own chip borders (quota plugin did). Host containers `composer-{openspec,git,status}-container`; legacy ids `composer-{openspec,git,status}-group-label`, `composer-git-group`, `composer-status-group` kept (Status content is `<fieldset disabled={working}>`). `packages/client/src/index.css`: `[data-group]:has(> [data-group-content]:empty) { display:none }` hides empty group (e.g. all badge claims render null). See change: redesign-composer-session-strip.
1103
1172
  - `anchored-popover` — popover anchored to a triggering UI element (replaces `TasksPopover`).
1104
1173
  - `command-route` — maps a slash command or URL route to a `content-view` (replaces today's hand-wired routing in `App.tsx`).
1105
1174
  - `settings-section` — a section in the Settings page (replaces today's hardcoded `Background polling (OpenSpec)` section). React for first-party plugins; descriptor (RJSF/UiField) for third-party extensions.
@@ -1192,7 +1261,7 @@ Authoring rules: [`plugin-seams.md`](plugin-seams.md#lazy-claim-modules-module).
1192
1261
 
1193
1262
  **Bundled-by-default plugins:** The plugin loader treats all plugins identically (same manifest, same discovery, same `enabled` flag, same failure isolation). What distinguishes "bundled-by-default" plugins (initial set: `git-plugin`) is purely operational — the build pipeline always includes them in `packages/`. Their absence is a deliberate user opt-out, not a normal state. OpenSpec, Flows, and Subagents plugins are bundled in standard builds but their absence is a normal use case (e.g. a workspace without OpenSpec).
1194
1263
 
1195
- **Future Work — external plugin discovery:** Phase 1 scans `packages/*/package.json` only. The manifest format (`pi-dashboard-plugin` field in any `package.json`) is intentionally **format-compatible with arbitrary npm packages**, which unblocks an eventual progression where stable plugins can be PR'd into upstream packages (e.g. `pi-dashboard-subagents/dashboard/`) and discovered from `node_modules`. The deferred work (trust model, SemVer pinning of the plugin context API, build integration with `node_modules` paths) is documented in `dashboard-plugin-architecture/design.md` §"Future Work: external plugin discovery".
1264
+ **External plugin discovery (shipped):** `decouple-plugins-from-core` adds the `settings.json#packages[]` discovery source, manifest `hostApi` pinning, operator trust, and runtime-delivered clients. See "Plugin Discovery, Trust and Runtime Delivery" below and `docs/runtime-plugin-clients.md`.
1196
1265
 
1197
1266
  #### JSX slot wrappers and `??` fallback chains — anti-pattern
1198
1267
 
@@ -1224,7 +1293,7 @@ Dual-write contract. `registerPluginBridge` writes BOTH locations in `~/.pi/agen
1224
1293
  - `packages[]` — user-visible package list. pi-coding-agent reads only this.
1225
1294
  - `_dashboardManagedPackages` — ownership map. Tracks which `packages[]` entries owned by dashboard vs user. Prevents clobbering user-added entries.
1226
1295
 
1227
- pi-coding-agent ignores `dashboardPluginBridges` entirely. Bridge extensions invisible to pi until written to `packages[]`. Symptom of single-write bug: plugin bridge loaded by dashboard but never invoked by pi runtime; `/api/flows-anthropic-bridge/status` reports "no sessions reporting".
1296
+ pi-coding-agent ignores `dashboardPluginBridges` entirely. Bridge extensions invisible to pi until written to `packages[]`. Symptom of single-write bug: plugin bridge loaded by dashboard but never invoked by pi runtime; Symptom: bridge status reports "no sessions reporting".
1228
1297
 
1229
1298
  Reconciliation: one-shot `reconcilePluginBridgePackages` runs at server start. Replays current plugin manifests through `ensurePackageEntry` for every claim with a `bridge` entry. Drops dangling managed entries via `removePackageEntry` when manifest gone. Atomic settings write (tmp + rename).
1230
1299
 
@@ -1254,7 +1323,7 @@ All producers hash deterministic manifest serialization via `pluginRegistryHash(
1254
1323
 
1255
1324
  **Served-artifact build declaration (`pi-dashboard-build.json`):**
1256
1325
  Production Vite build writes `packages/client/dist/pi-dashboard-build.json`:
1257
- - Schema: `{ schemaVersion: 1, pluginRegistryHash: "<sha256>", fixturePolicy: "excluded" | "included" }`.
1326
+ - Schema: `{ schemaVersion: 1, pluginRegistryHash: "<sha256>", fixturePolicy: "excluded" | "included", bundledPluginIds?: string[] }`. `bundledPluginIds` = sorted ids of plugins the build bundled (additive; decides bundled-vs-runtime on every host — see "Plugin Discovery, Trust and Runtime Delivery").
1258
1327
  - Byte-reproducible: no timestamps, no host paths. Dev/HMR emits nothing.
1259
1328
  - SDK: `build-declaration-sdk.ts` + `build-metadata.ts` in `dashboard-plugin-runtime`.
1260
1329
 
@@ -1327,6 +1396,110 @@ Client banner flow: `PluginStalenessBanner` fetches `/api/health` on mount. Comp
1327
1396
 
1328
1397
  See change: `add-served-build-coherence-and-hash-parity`.
1329
1398
 
1399
+ #### Plugin Discovery, Trust and Runtime Delivery (`decouple-plugins-from-core`)
1400
+
1401
+ Plugins separable from core. Core imports no plugin. Plugin client reaches stock dashboard at runtime. Detail: `docs/runtime-plugin-clients.md`, `docs/plugin-seams.md`, `docs/publishing-plugins.md`, `docs/plugin-ui-primitives.md`.
1402
+
1403
+ **Discovery sources.** `discoverPlugins()` (`packages/dashboard-plugin-runtime/src/server/loader.ts`). `source` on `DiscoveredPlugin` + `PluginStatus`.
1404
+
1405
+ | Priority | `source` | Location |
1406
+ |---|---|---|
1407
+ | 1 | `workspace` | `<repo>/packages` |
1408
+ | 2 | `installed` | `~/.pi/dashboard/plugins` |
1409
+ | 3 | `bundled` | `resources/plugins` (Electron) |
1410
+ | 4 | `pi-package` | `~/.pi/agent/settings.json#packages[]` via `listPiPackages({scope:"user"})` (`packages/shared/src/pi-package-resolver.ts`) |
1411
+ | report only | `local-detected` | `<cwd>/.pi/settings.json#packages[]` of active sessions |
1412
+
1413
+ - `pi-package` entries: package dirs carrying a manifest. Files + manifest-less dirs skipped silently. Missing install paths invisible. `npm root -g` memoized once per process.
1414
+ - Exception to priority: id ∈ served build's `bundledPluginIds` → build's own copy wins (`workspace` if a copy exists, else `bundled`, else plain priority), both halves.
1415
+ - Discovery cache keyed by effective root set + digest of `bundledPluginIds` (absent → fixed "undeclared" key). Server reads declaration (`readBuildDeclaration`, `client-dist.ts`) at startup + on every refresh, before any discovery call.
1416
+ - Vite build-time call (explicit `repoRoot`) scans only workspace. No declaration. Unaffected.
1417
+
1418
+ **One row per id (shadowing).** Losing duplicate → winner's `shadowed: {source, packageDir}[]`. Logged at warn. Never loaded. No second `loaded:false` row. `PluginsSection` renders `shadowed` as sub-line.
1419
+
1420
+ **Local-scope detection** (`local-scope-detector.ts`).
1421
+ - Per active-session cwd: `listPiPackages({scope:"project", cwd})` entries with plugin manifest → row `source: "local-detected"`, `loaded: false`, `enabled: false`, error "Local-scope plugins are not loaded in this release. Install globally with --scope global to enable."
1422
+ - Same id already has a row → local copy goes to that row's `shadowed[]`.
1423
+ - Server entry, bridge, claims, client never loaded.
1424
+ - Rerun: each discovery refresh, session registers a new cwd, after each successful local-scope package op, on session end (prunes rows no active session has).
1425
+ - `plugins_changed` on session end only when the detected set changed.
1426
+
1427
+ **Refresh on completion.** Hook: package-operation completion listener (`setCompleteListener`, `packages/server/src/server.ts`), not `package-routes.ts` (routes return 202 before completion). Wiring: `packages/server/src/plugin-discovery-wiring.ts`. Implementation: `plugin-refresh.ts` `refreshPluginDiscovery()`.
1428
+
1429
+ ```mermaid
1430
+ flowchart TD
1431
+ OP["package op completes"] --> SC{"success?"}
1432
+ SC -- no --> NOP["no refresh"]
1433
+ SC -- "yes, scope local" --> LOC["rerun local-scope detection"]
1434
+ SC -- "yes, scope global/user" --> R1["re-read served declaration"]
1435
+ R1 --> R2["clear discovery cache + content-hash stat cache"]
1436
+ R2 --> R3["discoverPlugins()"]
1437
+ R3 --> R4["flag changed/vanished loaded plugins restartRequired"]
1438
+ R4 --> R5["additive loadServerEntries: NEW ids only; hostApi-gated; pi-package server-trust-gated"]
1439
+ R5 --> LOC
1440
+ LOC --> R6["probe refresh + status store update"]
1441
+ R6 --> BC["ONE plugins_changed {plugins: PluginStatus[]} broadcast"]
1442
+ ```
1443
+
1444
+ - Calls coalesce: refresh requested while one runs → exactly one follow-up.
1445
+ - Server entry throwing during refresh → `loaded:false` + error, broadcast, refresh continues.
1446
+ - Server entries load additively. Loaded plugin changed/vanished → `restartRequired: true`. Routes + handlers stay until restart.
1447
+ - Hot-added entry registering Fastify routes: refused (`FST_ERR_INSTANCE_ALREADY_LISTENING`). Recorded `loaded:false`, `restartRequired:true`, `HOT_ROUTE_RESTART_ERROR`.
1448
+ - Re-enable of discovered plugin whose server entry never loaded → restart.
1449
+ - Terminal `pi install` NOT visible live: only dashboard installs (Packages tab / `POST /api/packages/install`) reach the listener. Appears after dashboard restart. `pi-resources-watcher.ts` not wired to discovery.
1450
+ - `POST /api/plugins/:id/toggle` keeps contract (dependency graph, 409, cascade). Also broadcasts one `plugins_changed`.
1451
+
1452
+ **`plugins_changed`.** WS message `{type: "plugins_changed", plugins: PluginStatus[]}` (`packages/shared/src/browser-protocol.ts`). Emitted after refresh, toggle, trust write, local detection change. Client re-fetches runtime listing, recomputes enabled set, feeds `pluginAvailability`.
1453
+
1454
+ **Status shape (additive).** `PluginStatus.{source, shadowed, restartRequired, hostApi, client, serveApp}` (`packages/shared/src/dashboard-plugin/plugin-status.ts`).
1455
+ - `/api/health.plugins[]`: unauthenticated, tunnel-reachable → path- and hash-free subset only (`source`, `restartRequired`, `hostApi`, `client.delivery`, `client.refusedReason`, `serveApp`).
1456
+ - Paths, `client.sha256`, `shadowed[].packageDir`, `local-detected` rows → guarded `GET /api/plugins` + `plugins_changed` only.
1457
+
1458
+ **Host API version gate.** `PLUGIN_HOST_API_VERSION` (`packages/shared/src/dashboard-plugin/host-api.ts`) vs manifest `hostApi` caret range. Checked at discovery for BOTH halves.
1459
+ - `workspace`/`bundled`: warn only.
1460
+ - `installed`/`pi-package`: refuse server entry (error `host-api`) + client (`refused`, `host-api`).
1461
+ - Required for `pi-package` + `clientBundle` plugins.
1462
+
1463
+ **Trust defaults.**
1464
+
1465
+ | Thing | Default | Opt-in |
1466
+ |---|---|---|
1467
+ | `workspace` / `bundled` / `installed` server entry | loads (as before) | n/a |
1468
+ | `pi-package` server entry + bridge | DENIED (`server-untrusted`) | local `POST /api/plugins/:id/trust {server:true}` |
1469
+ | Runtime client (`clientBundle`) | refused (`untrusted`) | local `POST /api/plugins/:id/trust {sha256}`, pinned to content hash |
1470
+ | `serveApp` mount | trusted if bundled ∨ in `auth.trustedPlugins` ∨ in legacy `auth.capabilityRoutePlugins` | edit list; restart-effective |
1471
+ | `local-detected` | never loaded | install globally |
1472
+
1473
+ - `isServeAppTrusted` (`packages/server/src/auth/serve-app-host.ts`): bundled = source ∈ {`workspace`,`bundled`,`installed`} + realpath containment + basename in `piDashboard.bundledPlugins`. Basename alone no longer trusts. `pi-package` + `local-detected` never bundled.
1474
+ - `auth.trustedPlugins: {id, clientSha256?, server?}[]` written only by trust endpoints (`plugin-trust-store.ts`). `PUT /api/config` cannot write it.
1475
+ - Grant needs `operate` + genuinely local. Revoke needs `operate`. Tiers in `packages/shared/src/route-tiers.ts`.
1476
+
1477
+ **Runtime delivery pipeline.**
1478
+
1479
+ ```mermaid
1480
+ flowchart LR
1481
+ DECL["pi-dashboard-build.json bundledPluginIds"] --> ADM["admission: not bundled, enabled, deps loaded, hostApi ok, trusted + pin"]
1482
+ DISC["discoverPlugins"] --> ADM
1483
+ TRUST["auth.trustedPlugins"] --> ADM
1484
+ ADM --> LIST["GET /api/plugins/runtime-clients"]
1485
+ ADM --> ASSETS["GET /plugin-assets/id/sha/*"]
1486
+ IDX["sendIndexWithImportMap: / and /index.html"] --> MAP["importmap -> /host/*.js shims"]
1487
+ LIST --> LOADER["runtime-plugin-loader.ts"]
1488
+ ASSETS --> LOADER
1489
+ MAP --> LOADER
1490
+ LOADER --> REG["claims, i18n, routes, reducers, eventTypes owners, bumpSlotClaimsVersion"]
1491
+ ```
1492
+
1493
+ - Server pieces: `packages/dashboard-plugin-runtime/src/server/{runtime-client-registry,runtime-client-listing,plugin-assets-route,confined-static}.ts`, `packages/server/src/{plugin-runtime-clients,lib/index-html}.ts`, `routes/plugin-runtime-client-routes.ts`.
1494
+ - Client pieces: `packages/client/src/lib/plugins/runtime-plugin-loader.ts`, `packages/client/src/host-shims/*`.
1495
+ - Remote-server mode (`getApiBase()` non-empty) + Vite `--dev` page: loader does nothing.
1496
+
1497
+ **Core/plugin boundary.** `npm run check:plugin-boundary` (`scripts/check-plugin-boundary.mjs`, ratcheting `scripts/plugin-boundary-allowlist.json`, vitest wrapper). Plugin set from manifests. Flow-literal check: string literals starting `flow:` / `flow_` / `flow-` or containing `pi-flows` in non-test `packages/{extension,server,shared,client}/src` fail unless in allowlist `literalRows`. Shared contracts + `packages/mcp-core` in `docs/plugin-seams.md`.
1498
+
1499
+ **Absent-owner UX.** Manifest `eventTypes` → one group row per owned event type; availability decided at render time by `pluginAvailability`. Subagent state written by subagents-plugin slice + finalizers; generic heals in core. See `docs/plugin-seams.md`.
1500
+
1501
+ See change: decouple-plugins-from-core.
1502
+
1330
1503
  #### Plugin Activation UI
1331
1504
 
1332
1505
  Settings ▸ Plugins tab lists every discovered plugin (enabled or not) with display name, description, enable/disable toggle, missing-requirement chips, inline Install affordances.
@@ -1489,6 +1662,168 @@ Automation plugin = `packages/automation-plugin/`. Schedule-triggered background
1489
1662
  - Not a sandbox. Shell/MCP tools not path-checked. List them in `deniedTools`.
1490
1663
  - See change: add-path-containment-guard-extension.
1491
1664
 
1665
+ ### Plugin Spawn Worktree (`add-plugin-spawn-worktree`)
1666
+
1667
+ - `ServerPluginContext.spawnSession(opts)` gains optional `opts.worktree?: { branch; base?; ifExists: "reuse"|"fail"; attachChange? }`.
1668
+ - Honoured only with `mode: "worktree"`. Types: `packages/dashboard-plugin-runtime/src/server/server-context.ts`.
1669
+ - Bare `mode: "worktree"` (no block) → legacy local fallback: runs in `cwd`, warning logged.
1670
+ - Older host ignores block too. Caller treats success without `PluginSpawnResult.worktreePath` as "not in a worktree".
1671
+ - Trusted plugins only (`manifest.priority <= 100`). Same gate as `spawnSession`.
1672
+ - Hook body: `packages/server/src/spawn-process/plugin-spawn-worktree.ts` (`createPluginSpawnHook(deps)`). `server.ts` wires real deps.
1673
+ - Git step: `ensureWorktree` in `packages/server/src/git-worktree/ensure-worktree.ts`. Never throws.
1674
+ - Result: `{ok,path,branch,created}` | `{ok:false,code,message}`.
1675
+
1676
+ `ensureWorktree` order:
1677
+
1678
+ 1. Known-folder admission (`admitRouteCwd`, same set as `POST /api/git/worktree`).
1679
+ 2. Main-checkout resolve → `not_git`.
1680
+ 3. Branch validation: `isValidRefArg`, `git check-ref-format --branch`, `@{` rejected, derived path under `<main>/.worktrees/`.
1681
+ 4. Per-repo lock.
1682
+ 5. Resolution.
1683
+
1684
+ Resolution:
1685
+
1686
+ - Registered worktree for branch → reuse (`created:false`). `ifExists:"fail"` → `exists`.
1687
+ - Stale registration (dir gone) → `git worktree prune` once.
1688
+ - Main checkout, or path outside `.worktrees/` → `branch_in_use`.
1689
+ - No registration:
1690
+ - local branch → checkout.
1691
+ - only `origin/<branch>` → `addWorktree({base:"origin/<branch>", newBranch})`.
1692
+ - else fork `base ?? resolveDefaultBase` (verified; fail `base_not_found`).
1693
+ - `base` ignored when branch or worktree exists.
1694
+
1695
+ Lock:
1696
+
1697
+ - `withRepoLock(repoLockKey(cwd))` in `git-worktree/repo-lock.ts`.
1698
+ - Key = realpath of git common dir.
1699
+ - `POST /api/git/worktree` takes same lock. Responses unchanged.
1700
+
1701
+ cwd-policy:
1702
+
1703
+ - Hook `checkTarget` compares `cwdPolicyRegistry.resolve(worktreePath)` vs `resolve(opts.cwd)` before any git write.
1704
+ - Differ → `policy_mismatch`.
1705
+
1706
+ Init:
1707
+
1708
+ - `autoInitWorktreeOnSpawn` on → hook calls `startWorktreeInit(cwd,{skipIfRunning:true})` before filing intents. Awaits it.
1709
+ - `startWorktreeInit` in `git-worktree/start-worktree-init.ts`. Also used by `POST /api/git/worktree/init`.
1710
+ - Failed → `init_failed`. No spawn. Worktree kept.
1711
+ - Untrusted hook → never run. Spawn proceeds. Init stays pending.
1712
+ - `already_running` → `awaitInitRun` polls registry.
1713
+ - Server-side trigger. Browser-side twin: `auto-init-worktree.ts`.
1714
+
1715
+ After success, every cwd-keyed step uses worktree path:
1716
+
1717
+ - `pendingInitialPromptRegistry`.
1718
+ - `pendingAttachRegistry` (`attachChange`, kebab-case `^[a-z0-9][a-z0-9-]{0,99}$`). Withdrawn on spawn failure.
1719
+ - Full queue → `warning: "attach queue full; session not attached"`.
1720
+ - `spawnPiSession` / `spawnAcpSession`.
1721
+ - `armSpawnWatchdog`.
1722
+ - Headless PID registry.
1723
+ - No `gitWorktreeBase` written (dialog-only per `git-context`).
1724
+
1725
+ Failure:
1726
+
1727
+ - `success:false`. Nothing spawned, nothing queued. Never falls back to local.
1728
+ - Codes (`PluginSpawnWorktreeCode`): `invalid_block`, `not_git`, `admission_unavailable` (retryable), `branch_invalid`, `exists`, `base_not_found`, `branch_in_use`, `policy_mismatch`, `init_failed`, `git_failed`.
1729
+
1730
+ Log per worktree spawn:
1731
+
1732
+ - `[plugin-spawn] worktree <created|reused|failed> plugin=<id> branch=<json> code=<code>`.
1733
+
1734
+ - See change: add-plugin-spawn-worktree.
1735
+
1736
+ ### Agent Teams Plugin (`add-agent-teams-core`)
1737
+
1738
+ Package `packages/agent-teams-plugin/` (`@blackbelt-technology/pi-dashboard-agent-teams-plugin`). Plugin id `agent-teams` (NOT `team`; `packages/team-plugin` = unrelated persona product). Manifest `priority: 100`. `emits: [agent-teams:mail, agent-teams:team_closed]`.
1739
+
1740
+ - Entries:
1741
+ - bridge (`src/bridge/index.ts`): pi extension per session. CC-named tools. Mail → `pi.sendMessage` custom message (`customType` from `customTypeForKind`: `agent-teams-mail` default, `-idle`, `-notice`). Idle report on `agent_settled`. Teammate guards (`guard.ts`, `shell-guard.ts`).
1742
+ - server (`src/server/index.ts`): server-owned team store, `<dataDir>/teams/<id>.json` (`persistence.ts`). Request lane (`lane.ts`). Teammate spawn (`driver.ts`). Read REST routes (`routes.ts`).
1743
+ - client (`src/client/index.tsx`): eager exports only (`catalog`, `TeamBadge`, `isTeamSession`). UI claims lazy; see Team view below.
1744
+ - Lead + teammates = pi sessions. One team per lead session. No nested teams.
1745
+ - Server store = single source of truth: members, task list, mail log.
1746
+ - Lead-only tools: `TeamCreate`, `TeammateSpawn`, `TeamDelete`, `ShutdownRequest`, broadcast, urgent mail.
1747
+ - Teammate tool set = `TEAM_TOOLS_BY_ROLE.member` (`shared/protocol.ts`).
1748
+ - Task list: sequential ids, synchronous claim, `owner` field, auto-unblock, self-claim on `agent_settled`.
1749
+ - Mail: direct + broadcast. Queued for busy/spawning/disconnected recipients. `urgent` interrupts.
1750
+ - Teammate spawn: `spawnSession` (session mode). Spawn prompt sent as `spawn_prompt` mail after bind + guarded `hello`. No `initialPrompt`.
1751
+ - Caps (`configSchema.json`): `maxTeammates` 5 (1–10), `maxActiveTeams` 3, `maxTasks` 50, `maxMessageChars` 8000, `maxResultChars` 4000, `maxFinalTextChars` 2000, `mailRatePerMin` 6, `pairExchangeLimit` 10.
1752
+ - Security inventory: `docs/security/plugins-client-electron.md` (A2 + bundled table), `tool-call-guards.md`, `websocket-and-bridge.md`.
1753
+ - Seams used: `docs/plugin-seams.md` § Consumer: agent-teams.
1754
+ - See change: add-agent-teams-core
1755
+
1756
+ ### Agent Teams Team view (`add-agent-teams-ui`)
1757
+
1758
+ Team view, mail cards, tool renderers, session badge: same plugin `agent-teams`. Owner rule + control tiers: [`security/plugins-client-electron.md`](security/plugins-client-electron.md) row A2.
1759
+
1760
+ - Claims (`package.json` `pluginMeta.claims`):
1761
+ - `session-card-badge` → `TeamBadge` (eager, predicate `isTeamSession`).
1762
+ - `shell-overlay-route` → `TeamViewClaim` (lazy `src/client/TeamView.tsx`), path `/session/:sessionId/team`, `parentPath` `/session/:sessionId`, `presentation: content`.
1763
+ - `custom-entry-renderer` → `MailEntryCard` for `agent-teams-mail`, `-idle`, `-notice`.
1764
+ - `tool-renderer` ×11 → `TeamLifecycleToolRenderer` (TeamCreate, TeammateSpawn, TeamStatus, TeamDelete), `TeamMessageToolRenderer` (SendMessage), `TeamTaskToolRenderer` (TaskCreate/List/Get/Update), `TeamShutdownToolRenderer` (ShutdownRequest, ShutdownResponse).
1765
+ - Route `/session/:sessionId/team`: lead or teammate session id. Resolves via `GET /api/plugins/agent-teams/teams?sessionId=<id>`. Pick order: live over closed, then latest change, then smaller id.
1766
+ - Layout: header, then `Members · Tasks · Messages` tabs on every width (APG roving tabindex; ←/→ wrap; Home/End).
1767
+ - Members: table ≥ `sm` (640 px), stacked cards below. Stop button: busy ∧ `viewerCanControl` ∧ team not `closing`/`closed`.
1768
+ - Tasks: Pending · In progress · Completed sections ≥ `lg` (1024 px); grouped collapsible list below. Completed folded by default. Read-only.
1769
+ - Messages: mail log (`MessageLog`).
1770
+ - Header: `Shut down team` iff `viewerCanControl` ∧ status ∈ {`starting`, `active`, `orphaned`}. Confirm via `ui:confirm-dialog`.
1771
+ - States: loading skeleton (`aria-busy`); `team-none` (unknown and invisible share copy); `team-not-found` (only after resolved 404); `team-error` + retry; stale notice over kept snapshot; closed banner.
1772
+
1773
+ Live-state protocol:
1774
+
1775
+ - Snapshot `GET /api/plugins/agent-teams/teams/:id` → `TeamUiSnapshot` = core `TeamSnapshot` + `epoch` + `viewerCanControl`.
1776
+ - `epoch`: `randomBytes(8)` hex, minted per server start (`server/epoch.ts`). Epoch change ⇒ refetch.
1777
+ - ETag strong `"<epoch>:<rev>"` (`:ro` suffix for a viewer without control); `Cache-Control: private, no-cache`, `Vary: authorization, cookie`. `If-None-Match` exact match ⇒ `304`, no body.
1778
+ - Frame `plugin_event`: `pluginId: agent-teams`, `sessionId: <lead>`, `eventType: agent-teams:changed`, `data: {teamId, epoch, rev, closed?}`. Content-free: ids + rev only.
1779
+ - Server coalesce (`server/ui-bridge.ts`): ≤1 frame per team per `CHANGED_COALESCE_MS` (1000), leading + trailing. Close = last frame, `closed: true`.
1780
+ - Client refetch (`client/teams-store.ts`): single-flight, conditional (`If-None-Match`).
1781
+ - First use: immediate. Other triggers (frame, reconnect, tab visible): 500 ms debounce, 2000 ms max-wait.
1782
+ - 60 s safety timer while visible. Hidden tab defers fetch.
1783
+ - Frame stale iff epoch differs or `rev` greater. Frame during in-flight request ⇒ one follow-up.
1784
+ - Failure keeps snapshot + stale flag. Retry 1 s, 2 s, 4 s, then 30 s.
1785
+ - 429 honours `Retry-After` (delta-seconds or HTTP-date), clamped 1–120 s. No trigger shortens a wait.
1786
+ - Control POST (`stopMember`, `shutdownTeam`): client timeout 15 s, then refetch truth. Never auto-retried.
1787
+ - Lead stamp (`server/ui-bridge.ts`): `assignSessionRef(lead, {"agent-teams-lead": {teamId}})`; clear `{teamId: null}`. Written on diff only. Teammates keep core pluginRef key `agent-teams`.
1788
+
1789
+ Access + controls:
1790
+
1791
+ - `Team.owner` = `ownerKeyOf({iss, sub})` = `JSON.stringify([iss, sub])`. Set at create from host `principalOwner`; set at bind if unset.
1792
+ - `setRouteVisibility(canViewTeam)` at start. Registration failure ⇒ plugin refuses to start.
1793
+ - Invisible or unknown ⇒ `404 {"error":"not_found"}`, never 403. Hook throw or >1000 ms (`ROUTE_VISIBILITY_TIMEOUT_MS`) ⇒ fail closed.
1794
+ - Owner rule (`server/access.ts`): enforcement off ⇒ allow; no principal ⇒ deny; `urn:pi-dashboard:local-operator` ⇒ allow; else `team.owner === ownerKeyOf(principal)`; no owner ⇒ operator only.
1795
+ - `viewerCanControl` = owner rule only. Credential tier enforced by host gate (403).
1796
+ - `POST /api/plugins/agent-teams/teams/:id/members/:name/stop` (tier `control`, `route-tiers.ts:451`): 200 `{aborted:true}`; 409 `not_busy` / `not_connected`.
1797
+ - `POST /api/plugins/agent-teams/teams/:id/shutdown` (tier `control`, `route-tiers.ts:452`): 202 `{closing:true}`; 409 `team_closed`.
1798
+ - `?sessionId=`: 400 `bad_session_id` when repeated, `sessionId[]`, empty, NUL, or >128 chars.
1799
+ - Limits: read 8/s burst 16; POST writes 2/s burst 5. 429 ⇒ `rate_limited`.
1800
+ - See change: add-agent-teams-ui.
1801
+
1802
+ ### Agent Teams templates, hooks, plan approval (`add-agent-teams-templates-hooks`)
1803
+
1804
+ Same plugin `agent-teams`. Additive over core seams (`registerOpGate`, `registerDispatchEligibility`, `registerSpawnContributor`, `registerMailKind`, `Team.overrides`, `Member.hold`). Full guide: [`agent-teams.md`](agent-teams.md). Security: [`security/agent-teams-hooks-and-plans.md`](security/agent-teams-hooks-and-plans.md).
1805
+
1806
+ ```mermaid
1807
+ flowchart LR
1808
+ T["templates.ts<br/>user + project(trusted)"] --> S["start.ts team.start"]
1809
+ C["bridge /agent-team"] -->|lane| S
1810
+ D["Start team dialog"] -->|"POST teams/start"| S
1811
+ A["agents.ts .pi/agents"] --> R["spawn-resolve.ts"]
1812
+ S --> CORE["core createTeam · bindLead · spawnMember"]
1813
+ R --> CORE
1814
+ H["hooks.ts"] -->|registerOpGate| CORE
1815
+ P["plans.ts"] -->|eligibility · mail kinds| CORE
1816
+ ```
1817
+
1818
+ - Template = markdown + YAML frontmatter. Sources `user` (`<piAgentDir>/teams/`), `project` (`<cwd>/.pi/teams/`, needs `host.isProjectTrusted`). Vars `{{goal}}`, `{{cwd}}` only.
1819
+ - Start: `/agent-team start|templates` (bridge, current session becomes lead) or `POST /api/plugins/agent-teams/teams/start` (server spawns lead, deadline `leadBindDeadline`, `closeReason: lead_spawn_failed`). Template snapshot persisted on team; frozen.
1820
+ - Teammate types: `.pi/agents/<Name>.md` re-implemented reader (`agents.ts`). Precedence + ceiling + plan floor in `spawn-resolve.ts`.
1821
+ - Hooks `TeammateIdle|TaskCreated|TaskCompleted`: op gates, exit 0 allow / 2 block / other allow (fail-open), one `opGateBudgetMs` (12 s) deadline, concurrency 2/team 4/global, `hookMaxRetries` 3. TOFU `<dataDir>/hook-trust.json` keyed `realpath(cwd)`+sha256. Frozen at start.
1822
+ - Plan approval: `planning → pending → approved`. `PlanSubmit` / `PlanDecision` tools + `plan-decision` route. Layers: spawn tool list, `setActiveTools` narrowing, `tool_call` backstop (`bridge/plan-mode.ts`).
1823
+ - Config: `maxTemplateBytes`, `hookTimeoutMs`, `hookMaxRetries`, `planMaxChars`, `planModeTools`.
1824
+ - Routes: GET `templates`, GET `teams/:id/plans` (observe); POST `teams/start`, POST `…/members/:name/plan-decision`, POST/DELETE `hook-trust` (operate).
1825
+ - See change: add-agent-teams-templates-hooks.
1826
+
1492
1827
  ### Plugin Session Lifecycle Declarations (`hide-chat-gateway-sessions`)
1493
1828
 
1494
1829
  `ServerPluginContext.spawnSession` accepts `PluginSpawnOptions.lifecycle: PluginSessionLifecycle` (`packages/dashboard-plugin-runtime/src/server/server-context.ts`). Owning plugin declares per-session lifecycle decisions; core reads the flags, never the plugin name.
@@ -1719,20 +2054,42 @@ pi/openspec/tsx are regular npm dependencies of `@blackbelt-technology/pi-dashbo
1719
2054
 
1720
2055
  `launchSource` (returned by `/api/health`) is `"electron" | "standalone" | "bridge"`, derived from `DASHBOARD_STARTER`. Client uses it via `useLaunchSource()` to hide pi-core update UI on Electron (immutable bundle has no writable target).
1721
2056
 
1722
- Compatibility skew helpers in `pi-version-skew.ts` (`readPiCompatibility`, `readCurrentPiVersion`, `computeCompatibility`) survive as pure helpers. The pinned range is `minimum: "1.3.0"`, `recommended: "1.3.0"`, `maximum: null` (lockstep — one supported pi means no conditional code paths on that artifact). `piCompatibility` unchanged: a `@earendil-works/pi-coding-agent` range, a DIFFERENT artifact from the pi-ai pin below.
2057
+ Compatibility skew helpers in `pi-version-skew.ts` (`readPiCompatibility`, `readCurrentPiVersion`, `computeCompatibility`) survive as pure helpers. The pinned range is `minimum: "1.7.0"`, `recommended: "1.7.0"`, `maximum: null` (lockstep — one supported pi means no conditional code paths on that artifact). `piCompatibility` unchanged: a `@earendil-works/pi-coding-agent` range, a DIFFERENT artifact from the pi-ai pin below.
1723
2058
 
1724
2059
  1.1.0 adds: `tool_execution_end.durationMs` preferred for tool row duration; `samplingParamsByThinkingLevel` passthrough; `GET /api/provider-auth/legacy-provider-ids` (`azure-openai-responses` -> `azure` rename scan). See change: update-pi-core-1-1-adopt-apis.
1725
2060
 
1726
2061
  1.3.0 adds: follow-up drain on `agent_settled` (see `### Retry Lifecycle`). Single-bang `!cmd` output sent via `pi.sendUserMessage(msg, {deliverAs: "followUp"})`. Retry turn `before_agent_start` `messageType: "custom"` (pi ≥ 1.2.0) → gets session-context fragment, kb doctrine, role guidelines, untrusted-content guideline, team skill filter; also runs compaction check + `nextTurn` prelude. Typed setting `sessionShareDestination` (`auto`|`gist`|`radius`, default `auto`). Lockstep floor → 1.3.0. Dropped `@earendil-works/chord`. See change: update-pi-core-1-3-adopt-apis.
1727
2062
 
2063
+ 1.5.0 adds: `decidePiTrust` order = recorded pi entry → implicit (no trust-requiring resources) → dashboard trust (over `never`) → `defaultProjectTrust`. Trust-file keys matched like pi `pathsEqual` (`packages/shared/src/pi-path-compare.ts`). Tool-argument validation = `@earendil-works/pi-schema`. Typed PATCH accepts exactly `"disabled"` for `httpIdleTimeoutMs` / `websocketConnectTimeoutMs`; form shows stored `"disabled"` as `0`. `extensionChangelogVersions` read-only managed key. Windows shell replica names pi 1.5.0 (see Windows section). `mcp.json` reads strip one leading UTF-8 BOM. `!`/`!!`/slash-exec `bash_output.exitCode` = pi `ExecResult.code` (was always 0). Lockstep floor → 1.5.0. See change: update-pi-core-1-5-adopt-apis.
2064
+
1728
2065
  **Below-floor session signal.** Replaces per-feature pi version gates. Bridge `sendPiVersionIfChanged` (`packages/extension/src/model-tracker.ts`) reads the running pi argv-anchored via `readRunningPiVersion` and sends `pi_version_update`; server runs `computePiBelowFloor(version, serverPiMinimum())` (`packages/server/src/pi/pi-version-skew.ts`) → sets `DashboardSession.piBelowFloor: { minimum } | null`; client `PiBelowFloorWarning` renders on `SessionCard` + `SessionHeader`. Unknown or unparseable version → no flag. `minimum` sourced from `piCompatibility.minimum`. See change: update-pi-core-1-0-adopt-apis.
1729
2066
 
1730
- **pi-ai generation window.** Legacy generation REMOVED — the dashboard supports ONE **pi-ai** generation (pi >= 1.3.0). Supported range `>=1.3.0` (root `package.json` + `packages/extension/package.json` peerDependencies). Root devDependency pin `^1.3.0`. The server streams through pi-coding-agent's own **`ModelRuntime`** (ONE server runtime — see `### Single model runtime`), which owns module shape (factory API only), transcript normalization (`normalizeContext` before dispatch, else systemPrompt + tools drop silently) and OAuth relocation (`dist/oauth.js` is a TYPE-ONLY stub, never consulted; real loaders at `dist/auth/oauth/*.js`, a path NOT in the package `exports` map). `packages/extension/src/bridge.ts` streams through pi's own `ctx.modelRegistry.streamSimple`. The `packages/shared/src/piai-compat/` seam (`adaptPiAi`), its `api-table.ts` / `NON_TEXT_LAZY_FILES` helpers and `packages/shared/src/test-support/piai-factory-fixture.ts` are DELETED.
2067
+ **pi-ai generation window.** Legacy generation REMOVED — the dashboard supports ONE **pi-ai** generation (pi >= 1.7.0). Supported range `>=1.7.0` (root `package.json` + `packages/extension/package.json` peerDependencies). Root devDependency pin `^1.7.0`. The server streams through pi-coding-agent's own **`ModelRuntime`** (ONE server runtime — see `### Single model runtime`), which owns module shape (factory API only), transcript normalization (`normalizeContext` before dispatch, else systemPrompt + tools drop silently) and OAuth relocation (`dist/oauth.js` is a TYPE-ONLY stub, never consulted; real loaders at `dist/auth/oauth/*.js`, a path NOT in the package `exports` map). `packages/extension/src/bridge.ts` streams through pi's own `ctx.modelRegistry.streamSimple`. The `packages/shared/src/piai-compat/` seam (`adaptPiAi`), its `api-table.ts` / `NON_TEXT_LAZY_FILES` helpers and `packages/shared/src/test-support/piai-factory-fixture.ts` are DELETED.
1731
2068
 
1732
2069
  See change: collapse-model-proxy-onto-modelruntime.
1733
2070
 
1734
2071
  **Host project-trust service.** `packages/server/src/server.ts` registers `host.isProjectTrusted(cwd)` (awaited at boot) next to `host.knownFolderCwds`, plus `host.projectTrustSource` and `host.piTrustCoverInteractive`. `packages/server/src/pi/host-project-trust.ts` `createHostProjectTrustService` / `loadHostProjectTrustService` run shared `decidePiTrust` (pi's own rule + dashboard mirror; see Pi trust mirror). `coveringDashboardEntry` finds covering entry. Honours `PI_CODING_AGENT_DIR`. Pi core unresolvable → one log line (not silent untrusted). Legacy `createHostProjectTrust({recordedDecision, defaultProjectTrust})` kept for compat only; not the decision path. `mcp-client` injects it as `isProjectTrusted` so folder MCP rows load the project layer only in trusted folders. See change: migrate-mcp-to-pi-builtin, mirror-dashboard-trust-to-pi.
1735
2072
 
2073
+ **Host local-request service.** `packages/server/src/plugin-local-request.ts` `host.localRequest({method, url, body?, timeoutMs?})`. Registered in `packages/server/src/server.ts` beside `host.resolveCwdPolicy`. Registry key const `HOST_LOCAL_REQUEST_KEY`.
2074
+ - Why: credential-less `fastify.inject` writes refused `local_proof_required` under `requireLocalProof=true` (default). Proof = endpoint-bound HMAC over connection local addr+port, method+target, ts, nonce. Cannot mint for `inject` (no socket).
2075
+ - How: real loopback HTTP fetch to server's own listener. Header `X-Pi-Local-Proof` minted per request from in-process local token (same helper as CLI `pi-dashboard api`: `httpProofHeaders`, `localDialHost`). Route runs every normal guard (host gate, network guard, credential verify + replay cache, route-tier gate). Real client, no bypass.
2076
+ - Allowlist FIXED in source, exact pathnames, not registrant-configurable (any plugin can `consume` it; configurable list would let first consumer widen all). Only `query`-flagged entry takes query string.
2077
+
2078
+ | Method | Path |
2079
+ |---|---|
2080
+ | POST | `/api/git/worktree` |
2081
+ | POST | `/api/git/worktree/init` |
2082
+ | POST | `/api/git/worktree/orphan-cleanup` |
2083
+ | GET | `/api/openspec/tasks` (query allowed) |
2084
+ | POST | `/api/openspec/tasks/toggle` |
2085
+
2086
+ - Caps: request body 256 KiB (`LOCAL_REQUEST_MAX_BODY_BYTES`), response 4 MiB (`LOCAL_REQUEST_MAX_RESPONSE_BYTES`), timeout default 60 s, max 300 s.
2087
+ - No caller headers, host, or credential. Plugin never sees token or proof. Proof single-use, bound to one method + target + endpoint.
2088
+ - Result: `{ok:true, statusCode, body}` (route 4xx guard refusal still `ok:true`) or `{ok:false, code}`. Codes: `invalid_request`, `path_not_allowed`, `body_too_large`, `response_too_large`, `timeout`, `unavailable`, `unreachable`. No message echoes URL, header, proof. Nothing logged.
2089
+ - Consumer: agent-teams OpenSpec profiles, `packages/agent-teams-plugin/src/server/openspec/inject.ts` (`createInject`). Prefers service; falls back to loopback `fastify.inject` (no credential) on older host — strict `requireLocalProof` then answers 401/403, caller never retries.
2090
+ - Add route = edit allowlist in `plugin-local-request.ts`, in review, next to route-tier table.
2091
+ - See [agent-teams.md](agent-teams.md) § OpenSpec profiles. See change: add-agent-teams-openspec.
2092
+
1736
2093
  #### Legacy `~/.pi-dashboard/` advisory
1737
2094
 
1738
2095
  Pre-R3 builds installed pi/openspec/tsx into `~/.pi-dashboard/node_modules/` at runtime. R3 leaves that directory untouched. `detectLegacyManagedDir({ homedir })` in `packages/shared/src/legacy-managed-dir.ts` returns `{present, path, pkgCount, sizeMb}`. Doctor surfaces a warning-severity row "Legacy install directory" with a `rm -rf <path>` suggestion. Server `cli.ts` logs the path once at startup after the `[bootstrap] ready` line. Repo-lint `no-managed-dir-reference.test.ts` blocks any new write into the legacy directory from `packages/electron/src/lib/`, `packages/server/src/`, or `packages/shared/src/` outside the explicit allowlist.
@@ -1808,6 +2165,22 @@ The Stop button supports two-click escalation for stuck sessions:
1808
2165
 
1809
2166
  The bridge includes `process.pid` in `session_register` so the server can kill the process. The server also force-closes the bridge WebSocket and uses the headless PID registry as a fallback. If no PID is available, only the WebSocket is closed.
1810
2167
 
2168
+ ### Bridge shutdown fallback
2169
+
2170
+ Bridge `shutdown` handler (`packages/extension/src/bridge.ts`) → `runBridgeShutdown(inst.cachedCtx)` (`packages/extension/src/bridge-shutdown.ts`).
2171
+ - Calls `ctx.shutdown()` first. Errors swallowed (stale ctx must not skip fallback).
2172
+ - Arms unref'd `process.exit(0)` fallback after `BRIDGE_SHUTDOWN_FALLBACK_MS` = 5000 (was 500).
2173
+ - Why: pi >=1.5.1 exits itself when idle. Its `dispose()` waits for credential write (single-use OAuth refresh token already replaced by provider). Early exit loses rotated token.
2174
+ - Callers: server `{type:"shutdown"}` WS msg, `/quit`, `/exit`.
2175
+ - See change: `update-pi-core-1-6-adopt-apis` (spec `bridge-extension`).
2176
+
2177
+ Residual risks (not fixed; server side tracked by follow-up `settle-server-credential-writes-on-exit`, `ModelRuntime.settleCredentialWrites`):
2178
+ - Windows: `killProcess` = `taskkill /F`. Busy session gets no clean dispose.
2179
+ - POSIX: SIGKILL 2 s after SIGTERM can cut dispose or credential write that runs longer.
2180
+ - Idle tmux (interactive) session: clean shutdown starts at once. pi unregisters signal handlers when it stops TUI (`interactive-mode.js` `stop()`). Ladder SIGTERM 1.5 s later ends dispose still waiting on credential write.
2181
+ - Headless: registry rung spends up to 2 s before grace + final escalation. 5 s fallback can fire before ladder's last SIGKILL. Process ends either way.
2182
+ - Keeper-hosted pi with unlinked PID: ended by keeper SIGKILL (`rpc-keeper-sidecar`). Skips dispose.
2183
+
1811
2184
  ### Platform-routed kill paths
1812
2185
  All process termination across the codebase goes through `packages/shared/src/platform/process.ts`. No code outside that module may call `process.kill(...)` directly — enforcement is handled by `packages/shared/src/__tests__/no-direct-process-kill.test.ts`, a repo-level lint that scans every `.ts` file under `packages/*/src/` and fails CI if a direct call slips in. The three canonical helpers are:
1813
2186
 
@@ -2043,9 +2416,9 @@ The shared `<RichDiff>` component is also consumed by `DiffPanel` (Path A / chan
2043
2416
  - Work through PromptBus — `TuiFlowIOAdapter` calls `ctx.ui.select/confirm/input` which the bridge routes through the bus to registered adapters (dashboard, TUI, or custom)
2044
2417
 
2045
2418
  **Flow launcher:**
2046
- - Available flows detected from session commands list (heuristic: `source: "extension"`, excluding management commands)
2047
- - Launch dispatched as `send_prompt` with `/<flow-name> <task>`
2048
- - Commands list auto-refreshed on `flow:rediscover` and `flow:complete` events
2419
+ - Flow list: plugin-owned catalog `flow_catalog` (`useFlowCatalog`). Core holds no flow list.
2420
+ - Launch dispatched as `send_prompt` with `/<flow-name> <task>`.
2421
+ - Typed `/<flow-name>` runs pi-flows' registered command via extension dispatch. No bridge fast-path.
2049
2422
 
2050
2423
  **pi-flows local patches required** (upstream report prepared):
2051
2424
  - `EventEmitObserver`: 5 missing methods added (flow-started, agent-started, agent-complete, assistant-text, thinking-text)
@@ -2104,7 +2477,7 @@ flowchart TD
2104
2477
 
2105
2478
  **Feedback contract** — exactly one terminal `command_feedback` per reload, `command` field always `/reload`.
2106
2479
 
2107
- **Bridge side** — terminal-hosted path only; ladder step 2 wins for dashboard-spawned sessions. `BridgeCommandOptions.reload` = `terminalReload.reload` (`createTerminalReload`, `packages/extension/src/terminal-reload.ts`). `ExtensionContext` has no `reload()`; only a command handler's `ExtensionCommandContext` does. So `reload()` self-dispatches `pi.sendUserMessage("/__dashboard_reload <token>", {expandPromptTemplates: true})` — pi runs `_tryExecuteExtensionCommand`, hands handler FRESH command ctx → `ctx.reload()`. No TUI bootstrap. Nothing callable captured — works every reload (retired captured-fn-on-`globalThis` path was single-use, stale ctx after first reload). No pi version gate (`update-pi-core-1-0-adopt-apis`): `supportsInProcessCommandDispatch` and `NO_RELOAD_PATH_REASON` retired — the check could never fail on a supported pi (1.3.0 floor). `BridgeCommandOptions.reload` returns `ReloadOutcome` (`{ok:true, handedOff:true}` | `{ok:false, reason}`). See change: fix-terminal-session-dashboard-reload.
2480
+ **Bridge side** — terminal-hosted path only; ladder step 2 wins for dashboard-spawned sessions. `BridgeCommandOptions.reload` = `terminalReload.reload` (`createTerminalReload`, `packages/extension/src/terminal-reload.ts`). `ExtensionContext` has no `reload()`; only a command handler's `ExtensionCommandContext` does. So `reload()` self-dispatches `pi.sendUserMessage("/__dashboard_reload <token>", {expandPromptTemplates: true})` — pi runs `_tryExecuteExtensionCommand`, hands handler FRESH command ctx → `ctx.reload()`. No TUI bootstrap. Nothing callable captured — works every reload (retired captured-fn-on-`globalThis` path was single-use, stale ctx after first reload). No pi version gate (`update-pi-core-1-0-adopt-apis`): `supportsInProcessCommandDispatch` and `NO_RELOAD_PATH_REASON` retired — the check could never fail on a supported pi (1.7.0 floor). `BridgeCommandOptions.reload` returns `ReloadOutcome` (`{ok:true, handedOff:true}` | `{ok:false, reason}`). See change: fix-terminal-session-dashboard-reload, update-pi-core-1-7-adopt-apis.
2108
2481
 
2109
2482
  **Token handshake** — slot `process.__pi_dashboard_pending_reload__ = {token, sessionId, state, armedAt}`. State `armed → started → delivered | expired`. Transitions compare-and-set — requesting instance `error` and reloaded instance `completed` mutually exclusive. `START_TIMEOUT_MS` = 5000, `FINISH_TIMEOUT_MS` = 60000, both measured from `armedAt`.
2110
2483
 
@@ -2146,7 +2519,7 @@ Primitive: `useAsyncAction(fn, opts)` in `packages/client/src/hooks/useAsyncActi
2146
2519
 
2147
2520
  Two completion modes:
2148
2521
 
2149
- - `confirm:"http"` (default, fast ops): pending ends when `fetch()` settles. TunnelButton connect/disconnect, ProviderAuthSection sign-out/remove-key.
2522
+ - `confirm:"http"` (default, fast ops): pending ends when `fetch()` settles. Remote access dialog (opened from the connection menu) connect/disconnect, ProviderAuthSection sign-out/remove-key.
2150
2523
  - `confirm:"ws"` (slow ops): pending holds after HTTP ack until correlated `ServerToBrowserMessage` matches `opts.confirmEvent(msg, requestId)`. `opts.confirmTimeoutMs` (default 15000ms) fallback clears pending + info toast. Never stuck-spins.
2151
2524
 
2152
2525
  Correlation contract: client generates requestId, sends in REST body, registers WS handler on `run()` BEFORE fn fires (race-free). Server echoes requestId into completion broadcast.
@@ -2217,7 +2590,7 @@ Opt-in grammar + spell + writing-improvement check for composer draft. LLM-only
2217
2590
  - Offset-safe `applyAll()` / `accept()` / `dismiss()`.
2218
2591
 
2219
2592
  **UI.** Grammar panel mounts in two places:
2220
- - Composer draft (main chat): `packages/client/src/components/chat/GrammarPanel.tsx` renders above composer (sibling to `QueuePanel` in `App.tsx`).
2593
+ - Composer draft (main chat): `packages/client/src/components/chat/GrammarPanel.tsx` renders above composer (sibling above the composer dock in `App.tsx`).
2221
2594
  - Explore/New Change dialogs: `ComposerPanelSlot` in draft editors (explorers, change filer).
2222
2595
  - Diff-highlighted corrections + summary. Per-suggestion Accept/Dismiss + Apply-all button.
2223
2596
  - `CommandInput.tsx` Check toolbar button + ⌘G shortcut (`onGrammarCheck` prop). Same panel renders both surfaces.
@@ -2311,7 +2684,7 @@ Run-configuring surfaces, all five now paired:
2311
2684
  - Settings → Sessions → Default Model — `packages/client/src/components/settings/SettingsPanel.tsx`, persists `config.defaultThinkingLevel`
2312
2685
  - OpenSpec run-config row — `packages/client/src/components/openspec/useOpenSpecRunConfigRow.tsx`
2313
2686
  - Roles → assign model to `@role` — `packages/roles-plugin/src/RolesSettingsSection.tsx`
2314
- - Automation → Create, direct-model branch — `packages/automation-plugin/src/client/CreateAutomationDialog.tsx`
2687
+ - Automation → Create/edit, direct-model branch ("Runs as" group) — `packages/automation-plugin/src/client/AutomationEditor.tsx`, rendered inline by `AutomationBoard.tsx` (editing card or `automation-draft` card)
2315
2688
 
2316
2689
  Reference-listing surfaces, deliberately excluded: Model Proxy preferred-models list and Model Proxy alias→model table, both in `packages/client/src/components/settings/ModelProxySection.tsx`.
2317
2690
 
@@ -2666,6 +3039,23 @@ See change: add-git-checkout-root-resolver.
2666
3039
  - origin `live` = latest ACCEPTED non-empty `commands_list` (`SessionCommandRegistry.getEntry().receivedAt`) among sessions with `piGateway.isSessionConnected` and cwd EXACTLY equal (trailing sep stripped + `canonicalPath`); else `scan` (enabled skills as `skill:<n>`, prompts as `<n>`); else `none`.
2667
3040
  - Each command carries `scope` folder|global (path in `local.*` / local-scope packages / under `<cwd>/.pi`, else global). Impl `packages/server/src/pi/folder-commands.ts`.
2668
3041
  - Spawn choices: `spawn_session` / `send_prompt` / `resume_session` gain optional `model`, `thinkingLevel`. Validator `packages/server/src/browser-handlers/spawn-choice.ts` (`validateSpawnChoice`, `resolveResumeChoice`): model `provider/id` ≤200 chars, charset-restricted, no empty/dash-led segment; `:<level>` suffix split only when no `thinkingLevel` field; thinkingLevel ∈ `THINKING_LEVELS`; invalid → dropped + `console.warn`.
3042
+ - Spawn-choice resolver: `resolveSpawnChoice(input, {defaultModel, readRoles})` in `packages/server/src/browser-handlers/spawn-choice.ts`. One resolver for all spawn roads: WS `spawn_session`, REST `POST /api/session/spawn`, plugin `spawnSession` hook (+ MCP `spawn_session`), bridge `spawn_new_session`. Returns `{choice, warnings}`. Never throws.
3043
+ - `model` accepts `provider/id`, `provider/id:<level>`, `@role`, `@role:<level>`. `@role` resolved ONCE at spawn via `readRoleConfigFromDisk()` (`~/.pi/agent/providers.json#roles`) + `resolveModelRef`. Roles file read only for `@` refs. Spawned session keeps concrete model. No role following.
3044
+ - Role level precedence: `thinkingLevel` field > ref `:<level>` suffix > role-assigned level. Level never appended to `--model`. Literal refs keep `validateSpawnChoice` rules. Thinking-only choice pairs with `config.defaultModel`. Empty string = absent. `agent` + model/thinking → empty choice + warning.
3045
+ - Road policy:
3046
+ - REST strict → `400` before any side effect (owner token, queued intents, spawn).
3047
+ - WS lenient → drop + `console.warn` + `spawn_result.choiceWarning` (client warning toast; bus `SpawnOptions.onWarning`).
3048
+ - Plugin hook lenient → `PluginSpawnResult.warning`. Literal `model` passes through verbatim (`mapPluginSpawnOptions`, `packages/server/src/spawn-process/plugin-spawn-choice.ts`). `agent` + `model`/`thinkingLevel` rejected (`validatePluginAcpSpawn`).
3049
+ - Bridge log-only.
3050
+ - Bridge inheritance: `buildSpawnNewSessionMessage` (`packages/extension/src/spawn-new-session.ts`) adds current `model` + `thinkingLevel` to `spawn_new_session`. Unknown model or throw → plain frame.
3051
+ - Pending registries (`pending-attach-registry.ts`, `pending-initial-prompt-registry.ts`) gain `withdraw(cwd, value)`: removes NEWEST matching entry. Failed WS / REST / plugin spawn withdraws only its own intents.
3052
+ - Web client:
3053
+ - Per-folder memory `packages/client/src/lib/spawn/spawn-choice-memory.ts`: localStorage `pi-dashboard:spawn-choice:<cwd>`, `{model?, thinkingLevel?}`, `@role` stored verbatim.
3054
+ - `getEffectiveSpawnChoice` = remembered ?? Settings default, per field. Settings defaults mirrored by App via `setSpawnDefaults`.
3055
+ - Chip `packages/client/src/components/spawn/SpawnChoiceChip.tsx` (ModelSelector + Role tab + `default` entries) in `WorktreeSpawnDialog` (`modelChoice="show"|"hidden"`) and `AgentSpawnPicker` menu (chevron always rendered).
3056
+ - Quick spawns (folder button, OpenSpec board via `useAgentAwareSpawn`, Initialize project) use effective choice when agent is pi.
3057
+ - Sibling spawn copies source `model`/`thinkingLevel` (`siblingSpawnOpts`, `lib/spawn/spawn-opts.ts`).
3058
+ - See change: add-spawn-model-choice.
2669
3059
  - Thinking-only spawn → config `defaultModel` so bridge default thinking cannot override. `SessionFlags.thinking` → `--thinking`; `--model`/`--thinking` on fresh + `continue` argv; fork keeps parent model; tmux pane escapes each token (`shellEscape`).
2670
3060
  - Ended-session composer (`useEndedSessionComposer`): folder command list + catalogue models replace absent bridge lists. Folder list kept until live `commands_list` arrives (no empty flash).
2671
3061
  - Model/thinking pick stored client-side per session; sent on resuming `send_prompt`/`resume_session` (continue only; applied to that resume's `spawnPiSession`, never via cwd-keyed `pendingResumeRegistry`); dropped once session no longer ended.
@@ -2863,7 +3253,7 @@ One server-derived per-cwd readiness state gates every OpenSpec affordance — f
2863
3253
 
2864
3254
  **Reconfiguration re-broadcast.** `reconfigurePolling` diffs readiness-affecting keys (`enabled`, `optOutDirectories`, `offerInitialization`) against the previous config; poll-tuning writes (interval, concurrency, jitter, worker flag) never trigger a readiness broadcast. `optOutDirectories` membership change re-broadcasts only the affected cwds; `enabled`/`offerInitialization` change re-broadcasts every cached cwd.
2865
3255
 
2866
- **`hasOpenSpecSkills`.** Stat `<configRoot>/.pi/skills/openspec-explore/`. Config root via `resolveConfigRoot` (git-worktree/git-operations.ts): a worktree answers from its main checkout, because `.pi/skills/openspec-*` is gitignored and never checks out into a worktree. Root resolution memoized per cwd (stat-pass budget, P4); unresolvable → fall back to the cwd.
3256
+ **`hasOpenSpecSkills`.** Stat `<configRoot>/.pi/skills/openspec-explore/`, then `<configRoot>/.agents/skills/openspec-explore/`. Legacy first, short-circuit (common case 1 stat). Either layout → `true`. `.agents/skills/` = committed shared layout. Config root only, no ancestor walk. Config root via `resolveConfigRoot` (git-worktree/git-operations.ts): worktree answers from main checkout, because `.pi/skills/openspec-*` is gitignored and never checks out into a worktree. Root memoized per cwd (P4); `null` re-probed after 60s TTL. Unresolvable (`null`) root → `false`, NOT cwd fallback (probing cwd adopts stray tree). Presence recomputed every poll in `finalizeOpenSpecData` (not carried from unchanged-`openspec/` gate), so relocation/removal shows next poll. Source: packages/server/src/directory-service.ts `hasOpenSpecSkillsFor`.
2867
3257
 
2868
3258
  **Config keys** (`OpenSpecPollConfig`): `openspec.optOutDirectories: string[]` (default `[]`; pathKey-normalized at parse, trailing-slash spellings collapse to one entry), `openspec.offerInitialization: boolean` (default `true`; `false` suppresses only the ABSENT offer — `BROKEN`/`STALE`/`READY` unaffected; distinct from `openspec.enabled`, which disables the feature). Both writable via `PUT /api/config` partial `{ openspec: {...} }` — deep-merged, every other key preserved.
2869
3259
 
@@ -2940,7 +3330,7 @@ See change: widen-containment-to-resolved-checkout (was: git-root-file-containme
2940
3330
 
2941
3331
  ### Filesystem Browser (PathPicker)
2942
3332
 
2943
- The dashboard's reusable directory chooser (`PathPicker`) is backed by three localhost-only endpoints:
3333
+ The dashboard's reusable directory chooser (`PathPicker`) is backed by three endpoints (full picker for local callers; remote callers confined, see Remote confinement below):
2944
3334
 
2945
3335
  - `GET /api/browse?path=<dir>&q=<query>&detect=<0|1>` — lists subdirectories of `<dir>` (or `$HOME` when omitted). By default this is a single-`readdir` enumeration with no per-entry filesystem probes; `isGit` / `isPi` are absent from each `BrowseEntry`. Pass `detect=1` (only the literal string `"1"` is truthy) to opt into eager `.git` / `.pi` classification on every entry — useful for skill recipes that consumed the legacy shape. When `q` is non-empty, entries are case-insensitive substring-filtered and ranked:
2946
3336
  - **Tier 0** exact match → **Tier 1** prefix → **Tier 2** word-boundary substring (after `-`, `_`, `.`, space, `/`) → **Tier 3** plain substring.
@@ -2959,6 +3349,70 @@ If a debounced query is still pending when Enter fires, the client flushes it sy
2959
3349
 
2960
3350
  New folders can be created from two entry points — a footer **+ New folder** button (inline name entry), or an inline **+ Create "<name>" here** row shown when the typed partial has no exact match. The create-here row is suppressed if the parsed parent differs from the last-successfully-fetched directory (prevents creating inside a stale parent after a mid-path typo). On success the picker refetches and descends into the new directory.
2961
3351
 
3352
+ #### Remote confinement (change: harden-server-capability-bounds)
3353
+
3354
+ `/api/browse`, `/api/browse/flags`, `/api/browse/mkdir` confine non-local callers. Local callers (`isLocallyTrusted` true) unchanged: full picker.
3355
+
3356
+ - Not genuinely local = tunnel, LAN, relayed loopback with forwarding header. Confined to shared roots.
3357
+ - Shared roots = `$HOME` + pinned dirs + session cwds + workspace folders + worktree-init trust roots + project-scope access-grant subjects.
3358
+ - Compare by realpath. Symlink escape refused.
3359
+ - Forbidden: `/`, `$HOME` itself as pinned root, system roots, ancestors of those, `~/.ssh`, `~/.pi`. `~/.pi` subtree refused even under `$HOME`.
3360
+ - Outside roots → 403 `path outside allowed roots`.
3361
+ - Listing: `confined: true`; `parent: null` at root top.
3362
+ - Flags: any outside path → 403 whole request.
3363
+ - mkdir: parent outside → 403 before any write.
3364
+ - Remote sockets cannot widen roots. `pin_directory`, `add_folder_to_workspace`, `move_folder_to_workspace` outside roots dropped. Server sends `folder_refused {path, reason: outside_allowed_roots}`. Client toast: "Ask the host to pin it".
3365
+ - Locality bit stamped per socket once at `/ws` upgrade. Unstamped = remote.
3366
+ - Docker: host browser hits container via port mapping = non-loopback peer. Confined to container `$HOME` + auto-pinned `PI_WORKSPACES`. Recovery actions refused there; use `docker compose restart` / `docker exec`. Set `browse.confineRemote: false` to lift it.
3367
+ - Residual: marker-less relay (`ssh -R`, no forwarding headers) looks loopback = local unless `requireLocalProof: false` (opt-out). Default on: refused without proof.
3368
+ - Operator opt-out: `config.json` `browse.confineRemote` (default `true`). Only explicit `false` disables. Read at server start (restart to apply). Off → remote callers browse / mkdir / pin like local callers. Used by the Docker e2e harness (browser = remote peer via port mapping; specs pin per-test dirs outside `$HOME`); harness env `PI_E2E_BROWSE_CONFINEMENT=1` keeps it on. Shipping installs stay confined.
3369
+ - Threat model: guards observe-tier remote viewer. Caller that may spawn session/terminal already has FS reach.
3370
+ - Shell output over tunnel (change: harden-bridge-inbound-and-discovery): `!` / `!!` / exec-template bash output (`bash_output`, `packages/extension/src/command-handler.ts`) reaches every tunnel viewer by design.
3371
+ - Only credential-vault values masked (`packages/extension/src/vault-redaction.ts`). No pattern redaction of secrets in output.
3372
+ - Operator rule: no secrets printed by shell commands on a tunneled session.
3373
+
3374
+ #### Bridge inbound bounds (change: harden-bridge-inbound-and-discovery)
3375
+
3376
+ Bridge caps per-unit-time work that server or bridge-socket holder can trigger. Limiter: `packages/extension/src/inbound-limits.ts`.
3377
+
3378
+ - `PI_DASHBOARD_BRIDGE_MAX_BASH` = max concurrent `!` / `!!` / exec-template bash per session. Default `4`.
3379
+ - `PI_DASHBOARD_BRIDGE_PROMPT_RATE` = `<burst>/<refillPerSec>`. One token bucket per bridge process. Default `30/10`.
3380
+ - Prompt bucket shared by: `send_prompt`, `retry_session`, `git_commit_draft`, flows `flow.run`, `plugin_emit_event`, `promote_followup_entry`.
3381
+ - Valid values: positive integers only. Invalid (`0`, negative, non-integer, empty) → default + one log line per process per variable. `0` ≠ unlimited.
3382
+ - Bucket survives WS reconnect and `/reload` (per bridge process). Keyed on process-global shared state (`inst.shared`), not the connection: a per-connection key let the server refill it via `send_prompt /reload`.
3383
+ - Refusal visible: inline `command_feedback` error in chat. Never silent drop.
3384
+ - Bash refusal text: `bash concurrency limit reached (N in flight per session)`.
3385
+ - Prompt refusal text: `inbound command rate limit reached (burst B, refill R/s)`.
3386
+ - `server_restarting.quiesceMs` normalized in `ConnectionManager.pauseAutoStart` (`packages/extension/src/connection.ts`): invalid / ≤0 ignored; fraction rounded up; capped at `MAX_QUIESCE_MS` = `120000` (`packages/shared/src/recovery-timing.ts`). Later pause never shortens active one.
3387
+
3388
+ #### Bridge loopback counter-proof (change: harden-bridge-inbound-and-discovery)
3389
+
3390
+ - Bridge holding local token (`~/.pi/dashboard/local/token`) requires server counter-proof on EVERY loopback dial (`ws:` and `wss:`): configured endpoint, auto-start, discovered mDNS advert, retarget, reconnect. `ws+unix:` exempt.
3391
+ - Independent of `PI_DASHBOARD_REQUIRE_SERVER_PROOF`.
3392
+ - Refusal: no register, no session data. Log cause `server_proof_missing` (no proof) or `server_proof_invalid` (bad MAC / timeout). Then backoff.
3393
+ - Opt-out: `PI_DASHBOARD_ALLOW_UNPROVEN_LOCAL_SERVER=1` (exactly `1`). Logged each dial. Needed for same-host server older than 0.10.0.
3394
+ - Same-user rogue process out of scope (can read token).
3395
+ - Device bearer (`PI_DASHBOARD_TOKEN`) sent only to pinned endpoint: configured, or pin-store `lastEndpoint`. Canonical host:port equality. Lone pin is no fallback.
3396
+ - Discovered host → log `bridge ticket unpinned_discovered_host`. No request sent.
3397
+
3398
+ #### Git remote credentials (change: harden-bridge-inbound-and-discovery)
3399
+
3400
+ - Bridge strips userinfo from remotes before building links and before `vault_sync_request.origin`: http(s) all userinfo; ssh:// password only. Hub strips again.
3401
+ - Unparseable remote with userinfo → no origin, no links.
3402
+
3403
+ #### Recovery server lockdown (change: harden-server-capability-bounds)
3404
+
3405
+ `recovery-server.ts` serves recovery page when main server fails. Imports node built-ins only.
3406
+
3407
+ - Binds `config.host` (default `127.0.0.1`). Never all interfaces unless operator sets `bindHost`.
3408
+ - `GET /` and `GET /api/health` stay open.
3409
+ - `POST /api/recovery/retry|reinstall` admitted iff either:
3410
+ - local token: `x-pi-local-token`, timing-safe compare; or
3411
+ - loopback peer AND none of 8 forwarding headers (`x-forwarded-for`, `x-forwarded-host`, `x-forwarded-proto`, `x-real-ip`, `forwarded`, `via`, `x-forwarded-server`, `x-forwarded-port`) AND loopback `Host` AND `Origin` absent or same host:port as `Host` (default port stripped; `Origin: null` refused).
3412
+ - Else 403 `text/plain` with remedy. Page shows it in `role=alert` callout. Buttons stay enabled.
3413
+ - One log line per refusal: route only, no token.
3414
+ - Residual: `ssh -R` rewriting `Host` to localhost and sending no `Origin` passes.
3415
+
2962
3416
  ### Pi Resources Browser
2963
3417
 
2964
3418
  The dashboard can display pi extensions, skills, and prompts installed for each workspace. The server-side scanner (`pi-resource-scanner.ts`) discovers resources from three sources:
@@ -3171,6 +3625,47 @@ File-open surfaces: internal Monaco pane and preview overlay only.
3171
3625
 
3172
3626
  v2–v4 follow-on (pin-to-split, create-file, edit-with-conflicts) deferred to separate proposals.
3173
3627
 
3628
+ ### Editor pane chrome
3629
+
3630
+ Client only. No API change. Code: `packages/client/src/components/editor-pane/`. See change: scope-anchor-editor-pane-controls.
3631
+
3632
+ Pane bar (`EditorPane.tsx`): `tree-toggle` (Files, labelled) · `EditorTabs` tablist (`min-w-0 overflow-x-auto`) · `new-tab-menu-toggle` (`+`) · spacer · `tab-search-toggle` (`⌄`) · `editor-pane-close` (✕). Tablist is the only flexible item.
3633
+
3634
+ Document bar (`DocumentBar.tsx`, `doc-bar`):
3635
+ - file tab: `doc-breadcrumb` · mode switcher (`file-mode-*`, `FileModeSwitcher`) · Reload · `tab-open-in-app` · `tab-reveal-in-file-manager` · `doc-more-menu` (`⋯`).
3636
+ - url tab: `tab-open-in-browser`.
3637
+ - diff / live / terminal / plugin tab: title line only.
3638
+ - no tab: bar hidden.
3639
+ - Open + Reveal gated on `systemOpen`. Reveal label from `/api/health` `platform`: Finder / Explorer / file manager.
3640
+ - Breadcrumb folder segment: expand-only reveal (`expandTreeRoots {relPaths}`), `railView="files"`, `setTreeVisible(true)`. Leaf opens `⋯`: Show in file tree, Copy full/relative/file name. Outside-cwd file: no relative copy, no show-in-tree.
3641
+ - Narrow (`ResizeObserver`, `width < 640`): Open + Reveal move into `⋯` (first items, each test id once). Ancestors → `…`.
3642
+
3643
+ `+` menu (`NewTabMenu.tsx`, session panes): Terminal (`new-terminal-launch`), Live preview (`live-preview-launch`), Open file… (`open-file-launch`).
3644
+
3645
+ Search = rail view. Session panes only (`hasFileSearch`, true when provider has `onFilenameSearch`).
3646
+ - State: `railView: "files" | "search"`, `searchMode: "filenames" | "contents"`. Reset on `sessionId` change.
3647
+ - Rail switch: `rail-view-files` / `editor-search-toggle`. Rail visible = `treeVisible || railView === "search"`.
3648
+ - Cmd/Ctrl-P filenames, Cmd/Ctrl-Shift-F contents. Same key closes. Other key switches mode. Esc closes view only when focus inside rail.
3649
+ - Only persisted value: `treeVisible`; search never writes it. Folder panes: no Search view, no `open-file-launch`, Cmd-P not intercepted.
3650
+
3651
+ Bulk close:
3652
+ - Reducer `closeTabs {paths}` (path-keyed, unknown ignored). Single close: `reduceCloseTab`.
3653
+ - `handlerCloseRisk(tab, remaining, lookups, {unknownIsRisky})` → `"unsaved" | null` (`file-handler/close-risk.ts`). Shared by `guardTabClose` (`unknownIsRisky: true`) and `planBulkClose`.
3654
+ - `planBulkClose(openFiles, targetPaths, lookups)` → `{ targets, risky }`. `risky` = deduped `{ kind, id | key, reason, tabPaths[] }`.
3655
+ - Unknown dirty state: silent in bulk, prompts in single close. Single terminal close: silent.
3656
+ - Risky set non-empty → `BulkCloseConfirm` (`bulk-close-confirm`): Cancel (focused) · Close all but these N · Close all & discard. Empty → closes without asking.
3657
+ - Runner closes open menus first, recomputes plan on confirm. `paneOverlayOpen` makes Cmd/Ctrl-W no-op.
3658
+ - Tab context menu `tab-context-menu`: Close · Close other tabs · Close tabs to the right · Close all tabs · Show in file tree · Copy path. Opens on right-click, ContextMenu key, Shift+F10.
3659
+
3660
+ Search tabs (`TabSearchPopover.tsx`, input `tab-search-input`):
3661
+ - `matchTabs` (`lib/layout/match-tabs.ts`). Haystack = display label + location (never raw path prefix).
3662
+ - Token AND. Fold per code point: NFD, strip U+0300–U+036F, lower-case. Index map keeps highlight ranges. `ß` `ø` `ł` match only themselves. Order = tab-strip order; first match preselected.
3663
+ - ↑ ↓ move · Enter activate · Esc close, refocus `⌄` · Delete/Backspace on empty field closes selected (single-close path).
3664
+ - Footer: empty query → `Close all but the active tab`; query → `Close N matching tabs` (same confirm).
3665
+ - No match: Enter opens rail Search prefilled (`{ query, nonce }`) when `hasFileSearch`; else `No open tab matches`.
3666
+
3667
+ Menus (`+`, document `⋯`, tab context): `Popover` + `role=menu` + `ActionList`. Keys in `menu-keys.ts`: ↑ ↓ wrap, Home/End, Enter/Space, Esc closes + refocuses trigger, disabled items skipped, first item focused on open.
3668
+
3174
3669
  ### Split editor workspace
3175
3670
 
3176
3671
  `SplitWorkspaceProvider` lifts split state + editor-pane state per session.
@@ -3221,6 +3716,231 @@ Shell overlays dispatch by route match (see Shell overlay routing). Mutual exclu
3221
3716
 
3222
3717
  Plugin content-view claims (flows-plugin) still predicate-driven via SlotRegistry. See change `overlay-url-routing`.
3223
3718
 
3719
+ ### Live Preview: Static Targets, Exposure, Egress (change: improve-canvas-html-and-url-ux)
3720
+
3721
+ Source: `packages/server/src/live-server/` (`live-static.ts`, `live-csp.ts`, `live-exposure.ts`, `live-browser-gate.ts`, `live-egress.ts`, `live-csp-report.ts`, `live-origin-scan.ts`, `live-capability.ts`), `packages/server/src/access/planes.ts`, `packages/shared/src/live-server.ts`, `packages/shared/src/preview-egress.ts`. Design: `openspec/changes/improve-canvas-html-and-url-ux/design.md` (D1-D10).
3722
+
3723
+ #### Target kinds
3724
+ - `port`: proxied loopback `host:port`. Persisted only when `addedBy:"user"`. Preset (agent declare, confirm-chip tap) in memory, ≤16/session LRU. Rejects dashboard listen ports.
3725
+ - `static`: `{cwd, root}` via `POST /api/live-server/start-static`. In memory, keyed `(cwd, root)`, ≤32/session LRU.
3726
+ - Eviction: LRU. Evicted target tokens revoked. "Use" = register or accepted request.
3727
+
3728
+ #### Static roots and servable files (D2)
3729
+ - In cwd: nearest ancestor (inclusive, ≤ cwd) with `index.html` or `package.json`. None → file dir. No whole-cwd fallback.
3730
+ - Granted file outside cwd: root = file dir. Per-request gate limits to grant.
3731
+ - Extension allowlist (`STATIC_WEB_EXTENSIONS`): html htm css js mjs json svg png jpg jpeg gif webp avif ico woff woff2 ttf otf mp4 webm ogg mp3 wav m4a. No `.map`, `.txt`.
3732
+ - 404: dot / `.git` / `node_modules` segments, forbidden subjects, `isCredentialName` names.
3733
+ - Realpath containment. `%2e`/`%2f` decoded once, re-checked. Symlink escape → 404.
3734
+ - Single `Range` → 206. Headers: `Cache-Control: no-store`, `nosniff`, `Referrer-Policy: no-referrer`.
3735
+ - Every request re-runs `gateFilePath(cwd, <real path>)`. Revoked grant or pin applies next request.
3736
+
3737
+ #### Capability URL and policy (D1, D4)
3738
+ - Mint: `POST /api/live-server/:id/capability` → `/live/<id>/~c/<token>/`. Body `{egress:"open"|"restricted", scripts:boolean, runScripts?:true}`.
3739
+ - Fail-closed: absent/invalid `egress` → `restricted`. Absent `scripts` → `false`.
3740
+ - Policy stored on token. Never read from request path, query or header.
3741
+ - Idle / max: port 30 min / 12 h; static 10 min / 2 h (`CAPABILITY_*_MS`).
3742
+ - `POST /api/live-server/:id/touch {tokenId}` every 5 min while viewer mounted + visible.
3743
+ - Token reused only when (target, policy, exposure epoch, viewer) unchanged.
3744
+ - Logs: `redactCapability` → `/~c/<redacted>`.
3745
+
3746
+ #### Response isolation (D3)
3747
+ | Mode | Frame `sandbox` | Response CSP |
3748
+ |---|---|---|
3749
+ | open, scripts | `allow-scripts allow-forms allow-popups allow-downloads` | `sandbox …; object-src 'none'; frame-ancestors 'self'` |
3750
+ | restricted, scripts | `allow-scripts allow-forms` | `sandbox …` + egress directives |
3751
+ | scripts off | empty | `sandbox` (+ egress directives if restricted) |
3752
+ - Applies to port AND static targets on every capability response (`buildLiveCsp`).
3753
+ - Our CSP appended to upstream CSP. Upstream never stripped. Browser enforces intersection.
3754
+ - Restricted: `default-src 'none'`; `script-src` / `style-src` = `<P> 'unsafe-inline'` (+ `'unsafe-eval'` with scripts) + `<G>`; `connect-src <P> <G>`; `form-action 'none'`; `base-uri 'none'`; `frame-src 'none'`; `object-src 'none'`; `worker-src <P> blob:`; `manifest-src 'none'`; `frame-ancestors 'self'`; `report-uri` only (no `report-to`, no `Reporting-Endpoints`).
3755
+ - `<P>` = prefix from validated `Host`. Never `'self'`. Never dashboard origin.
3756
+ - `<G>` = project grants ∪ viewer allow-once set.
3757
+
3758
+ #### Exposure policy (D5)
3759
+ - `exposed` if ANY: bind host not loopback (unparseable → exposed); `collectEndpoints()` non-empty (tunnel, `publicBaseUrls`, TLS); forwarding-header request seen since start (sticky); `liveServer.previewExposure: "exposed"` in `config.json`. Else `local-only`.
3760
+ - Same-host relay adding no header (`ssh -L`, socat) is undetectable. Operators set `previewExposure`. Residual.
3761
+ - `GET /api/live-server/policy` (observe) → `{exposure, epoch, promptingEnabled}`.
3762
+ - Epoch bumps on every change. Change to `exposed`: revoke restricted scripts-on `local-only` tokens; broadcast `preview_exposure_changed {epoch}`; viewers re-mint without scripts within 2 s.
3763
+ - Scripts on restricted mint: `local-only` → allowed. `exposed` → refused unless `runScripts:true` (viewer "Run scripts" only).
3764
+ - Frames cannot mint: opaque origin, CORS rejects `null`, no token on `/api`. Client-asserted marker is safe.
3765
+ - Local-minted token accepted only from genuinely-local requests.
3766
+ - Residual: remote operator open with scripts → token valid to expiry. Documented in viewer tooltip.
3767
+ - Provenance: operator open → `open`. Agent / undeclared → `restricted`. Confirm-chip tap → restricted preset (consents to connect, not egress).
3768
+ - Agent-declared loopback URL never auto-opened. Routed to confirm chip.
3769
+
3770
+ #### Browser-capability rule (D10)
3771
+ - `isBrowserOriginated(headers)`: `Origin: null` or any `Sec-Fetch-*` header.
3772
+ - Browser-originated `/live/` HTTP or WS upgrade without valid capability → 404 (`live-server-proxy.ts`).
3773
+ - Non-browser local callers (curl, `fastify.inject`) keep admission for port targets.
3774
+ - Static targets: never reachable without capability, by any caller.
3775
+
3776
+ ```mermaid
3777
+ flowchart TD
3778
+ A["Request /live/:id/…"] --> B{"Browser-originated?<br/>Origin null or Sec-Fetch-*"}
3779
+ B -- yes --> C{"Valid capability?<br/>/~c/token/"}
3780
+ C -- no --> X["404"]
3781
+ C -- yes --> K{"Target kind"}
3782
+ B -- no --> D{"Capability present?"}
3783
+ D -- yes --> K
3784
+ D -- no --> E{"Port target admitted?<br/>static never"}
3785
+ E -- no --> X
3786
+ E -- yes --> P["Proxy upstream<br/>no capability CSP"]
3787
+ K -- port --> Q["Proxy upstream<br/>CSP from token policy"]
3788
+ K -- static --> G{"gateFilePath(cwd, real path)<br/>per request"}
3789
+ G -- denied --> X
3790
+ G -- ok --> S["serveStatic<br/>CSP from token policy"]
3791
+ ```
3792
+
3793
+ #### Preview egress plane (D6, D7)
3794
+ - Origin scan (`live-origin-scan.ts`): HTML ≤ 2 MiB (`SCAN_MAX_HTML_BYTES`) + same-root CSS. Reads `src`, `srcset`, `poster`, `data`, `<link href>`, `@import`. Plain `<a href>` ignored.
3795
+ - Output `{source:"markup"}`. Truncation → `scanIncomplete`. Root-absolute refs → `rootAbsolute`.
3796
+ - Runtime reports: `POST /live/<id>/~c/<token>/__pi/csp-report` (`CSP_REPORT_SUBPATH`). Types `application/csp-report`, `application/reports+json`.
3797
+ - Limits: body ≤ 64 KiB (413), 20/s and 600/h per token (429). Reads `blocked-uri` only.
3798
+ - Runtime reports best-effort. Page may forge → labelled "reported by this page", allow-once only.
3799
+ - Blocked set per token ≤ 64 (`MAX_BLOCKED_ORIGINS`). Eviction drops runtime entries first.
3800
+ - `GET /api/live-server/:id/egress?token=` and `POST /api/live-server/:id/allow-once {tokenId, origin}`: control tier. Minting principal only.
3801
+ - Allow-once keyed by client `viewerId` (per tab), ≤ 32.
3802
+ - Grant = deferred plane `preview-egress` (`planes.ts`). `allow-always` / `deny`. Never YOLO-eligible.
3803
+ - "Allow for this project" (operator click) → deferred registry entry → standard dialog. Prompting off (default) → Allow once only.
3804
+ - Subject: `canonicalHttpsOrigin` (https only, no userinfo, punycode, default port elided).
3805
+ - Ungrantable (`isUngrantableEgressOrigin`): non-https, `localhost`, loopback / private / link-local / CGNAT / ULA IP literals, single-label, `.local` `.internal` `.lan` `.home.arpa`, IPv4-embedding labels, dashboard origins.
3806
+ - Grant-time DNS: 3 s (`EGRESS_DNS_TIMEOUT_MS`). Private / loopback / fail → "Could not verify this origin; try again". Later rebinding = residual.
3807
+ - Store: `~/.pi/dashboard/preview-egress.json` `{[projectKey]: string[]}` via `auth/locked-json-file.ts`. Override `PI_PREVIEW_EGRESS_STORE`.
3808
+ - `projectKey` = canonical subject of git common root, else cwd.
3809
+
3810
+ #### Capability origins and tiers (change: serve-live-previews-on-capability-origin)
3811
+
3812
+ Source: `packages/server/src/live-server/` (`preview-origin.ts`, `preview-dispatch.ts`, `preview-pool.ts`, `preview-preflight.ts`, `preview-path-store.ts`, `preview-reserve.ts`, `preview-viewers.ts`, `preview-path-bridge.ts`, `live-server-proxy.ts`, `live-capability.ts`), `packages/server/src/auth/duplicate-cookie-gate.ts`, `packages/shared/src/preview-origins.ts`, `packages/server/src/routes/live-server-routes.ts`.
3813
+
3814
+ Config: `liveServer.previewOrigins` = `{ enabled, wildcard: {suffix, forHosts[], scheme?}, portPool: "a-b", ipDnsSuffix }`.
3815
+
3816
+ ##### Mint negotiation
3817
+ - Client `POST /api/live-server/:id/capability` with `accept: ["origin","preview"]`.
3818
+ - No or invalid `accept` ⇒ legacy path.
3819
+ - Response: `{tier, origin?, path, base?, expiresAt, tokenId, policy}`.
3820
+ - Client validates shape. Refuses `origin` equal to dashboard origin.
3821
+
3822
+ ##### Tier table
3823
+ First match wins. Tier input = RAW `Host` header + socket peer. Never `request.protocol`.
3824
+
3825
+ | Tier | Match | Origin | Path |
3826
+ |---|---|---|---|
3827
+ | 1 | Host `localhost` / `127.0.0.1`; peer loopback; no forwarding header; no TLS | `http://<label>.localhost:<port>` | `/` |
3828
+ | 2 | Host ∈ `wildcard.forHosts` | `<scheme>://<label>.<suffix>[:port]` | `/` |
3829
+ | 3 | login session principal; IPv4 Host the bind answers; pool port free | `http://<ip>:<poolPort>` | `/?k=<one-shot secret>` |
3830
+ | 4 | IPv4 Host; `ipDnsSuffix` set | `http://<label>.<a-b-c-d>.<suffix>[:port]` | `/` |
3831
+ | 5 | no earlier tier matches (incl. IPv6 Host, pool full) | dashboard origin | `/preview/<pid>/` |
3832
+ | legacy | no/invalid `accept`; or `enabled:false` | dashboard origin | `/live/<id>/~c/<token>/` |
3833
+
3834
+ ##### Tier 1
3835
+ - Same-host reverse proxy adding no forwarding header looks like local browser. Pinned limitation.
3836
+ - Fix: proxy sends `X-Forwarded-For`, or set `enabled:false`.
3837
+
3838
+ ##### Tier 2
3839
+ - Warns when `suffix` shares parent domain with a `forHosts` entry (cookie tossing).
3840
+
3841
+ ##### Tier 3 (port pool)
3842
+ - `portPool` `"a-b"`: ≤100 ports, all ≥1024. Excludes dashboard, gateway, TLS, model-proxy ports.
3843
+ - Invalid value ⇒ tier 3 off. Logged once.
3844
+ - Eligible principal: login session cookie `pi_dash_token` (`Path=/`) only.
3845
+ - One plain-HTTP listener per live capability, lowest free pool port. `EADDRINUSE` ⇒ skip next port.
3846
+ - ≤8 listeners per principal. Pool full ⇒ tier 4/5 with log `pool exhausted`. Never an error.
3847
+ - Listener released on every capability deletion: expiry, revoke, eviction, config change, shutdown.
3848
+ - Pool ports in `ownPorts`. No target may point at them. Forbidden to mock site.
3849
+ - Opt-in in Docker: see `docker/README.md` § Live previews.
3850
+
3851
+ Pool-port request pipeline (in order, first failure stops):
3852
+ 1. Fixed Host binding. Else `403`.
3853
+ 2. Minting session cookie matches. Else `404`.
3854
+ 3. One-shot `?k=` hop: sets host-only `pi_dash_pool_<port>` (`HttpOnly; SameSite=Strict; Path=/`), then redirects to clean URL. `to` must be single-slash root-relative, no `\` or control chars, ≤2048; else `/`.
3855
+ 4. Later requests: cookie `pi_dash_pool_<port>` required. Else `404`.
3856
+ 5. `Origin` present ⇒ must equal entry origin. Else `404` (upgrades `403`).
3857
+
3858
+ ##### Tier 4
3859
+ - `ipDnsSuffix` (e.g. `sslip.io`). IPv4 Host only.
3860
+
3861
+ ##### Tier 5 (`/preview/<pid>/`)
3862
+ - `pid` = 22 chars. One current pid per port target. Shared by all holders. Policy = narrowest holder.
3863
+ - Mint within last 20 min of lifetime ⇒ new pid, `restartRequired`.
3864
+ - Bounds: 32 pids per principal, 256 total.
3865
+ - Opaque origin: sandbox without `allow-same-origin`.
3866
+ - Full path forwarded upstream.
3867
+ - CORS: `Access-Control-Allow-Origin: null` for opaque origin. `OPTIONS` preflight answered for valid pid.
3868
+ - Authorised by pid, not dashboard auth.
3869
+ - WS upgrades on `/preview/<pid>/...` supported.
3870
+ - Pid drop (revoke, expiry, target removed, disabled) closes its tracked WS and in-flight responses (`preview-ws-registry.ts`; `server.ts` `previewWs.closePid`).
3871
+ - Tiers 1-5: `Referrer-Policy: no-referrer` replaces any upstream value. Legacy: only when app set none.
3872
+ - Tier 5 root-absolute `Location` rewritten into `/preview/<pid>/…`.
3873
+ - Dead or reset upstream on `/preview/` ⇒ `502 {"error":"bad_gateway"}`. Timeout ⇒ `504 {"error":"gateway_timeout"}`.
3874
+ - Residual: client abort does not destroy upstream HTTP request (`@fastify/reply-from`; same on `/live/`). Proxy timeout bounds it.
3875
+
3876
+ ##### Tier-5 base reservation
3877
+ - `POST /api/live-server/preview-path {port}|{targetId}` (control) ⇒ `{path:"/preview/<pid>/", expiresAt, tier5Viewers:true}`.
3878
+ - No tier-5-capable browser ⇒ `{path:null, tier5Viewers:false}`. Nothing reserved.
3879
+ - Browser announces `live_preview_accept`. Counted only if its upgrade Host classifies to tier 5.
3880
+ - `DELETE /api/live-server/preview-path/:pid` releases UNBOUND reservation. Reserver only.
3881
+ - Limits: 8 per principal, 64 total.
3882
+ - TTL: 10 min from creation; 12 h while port target exists.
3883
+ - Adopted by next control-tier tier-5 mint for that port. Unadopted pid unknown to everyone.
3884
+ - Agent path: bridge `preview_path_request` / `preview_path_result` / `preview_path_release`.
3885
+ - Tier 1-4 mint of port with live pid ⇒ `base:"/preview/<pid>/"`.
3886
+ - `serve_mock_site{base?}`: explicit base allowlist `^/([A-Za-z0-9._~-]+/)+$`, ≤256. Else neutral event `mock-site:base-reservation` (2 s wait, then root).
3887
+
3888
+ ##### Dispatch
3889
+ - Preview-shaped Host (`label.localhost`, wildcard suffix, IP-DNS suffix) ⇒ route-less `previewApp` (second Fastify instance).
3890
+ - `previewApp` never reaches host gate, CORS, cookie auth, `/api`, `/ws`, SPA, plugin routes.
3891
+ - Refusal: identical `403 {"error":"host_not_allowed"}`.
3892
+ - Dead upstream: `502`. Dispatcher failure: `503`. Never falls through to dashboard.
3893
+ - Preview WS upgrades handled before host gate.
3894
+
3895
+ ##### Duplicate-cookie gate
3896
+ - Repeated `pi_dash_*` cookie name ⇒ `400` (JSON or static HTML by `Accept`).
3897
+ - Response expires the name at every path (self-heal).
3898
+ - Set-Cookie expiry lines capped at 8 KiB total (`EXPIRY_MAX_BYTES`, `fitExpiryBudget`). `/`, `/api/`, `/auth/` kept first. Keeps 400 head under Node 16 KiB header limit.
3899
+ - Applies to WS upgrades.
3900
+ - Repeated `pi_dash_token` / `pi_dash_pool_*` ⇒ counts as missing credential.
3901
+ - `previewApp` exempt.
3902
+
3903
+ ##### CSP
3904
+ - Capability responses: CSP built from entry, never request.
3905
+ - Tiers 1-4: `allow-same-origin` + exact `frame-ancestors`.
3906
+ - Tier 5: path-scoped `frame-src`. No `frame-ancestors` (T11 fallback: Chromium blocks same-pid nested panes under `'self'`; sandboxed parent is opaque).
3907
+ - Tier 5 sandbox CSP still forces opaque origin. Pid is the capability.
3908
+ - Legacy: `frame-ancestors 'self'`.
3909
+ - Dashboard `frame-src` built per request from Host: `http://*.localhost`, wildcard suffix, `http://<host>:*` for pool.
3910
+ - `/preview/` skips dashboard baseline CSP (same as `/live/`).
3911
+
3912
+ ##### Rollback
3913
+ - `liveServer.previewOrigins.enabled: false` ⇒ every mint returns legacy path.
3914
+ - Existing origin-bound capabilities revoked at next sweep, reason `disabled`.
3915
+ - Boot log: `[live-preview] tiers: 1, 3(8100-8199), 5`.
3916
+
3917
+ ##### Client guards (D6(b), cookie reset)
3918
+ - Dashboard doc framed by live frame (`data-pi-live-frame`) or cross-origin parent (`frameElement === null`): no boot, no render, no boot-time API calls.
3919
+ - Source: `lib/live-preview/frame-guard.ts` `isDashboardBootBlocked`; `main.tsx`; `lib/boot/client-boot.ts`.
3920
+ - After each live-frame `load`: readable `contentWindow.location.href` ⇒ frame `about:blank` + "Preview navigated to the dashboard; blocked." until Reload.
3921
+ - Source: `components/editor-pane/live/LiveFrame.tsx`, `LiveFrameParts.tsx`.
3922
+ - Same-origin `/api/*` 400 `duplicate_dashboard_cookie` ⇒ tier 2/3 frames blank to `about:blank` + "A preview reset dashboard cookies; reopen it to continue."
3923
+ - Tier 1 untouched. Nothing auto-reopens. Reload / Reopen re-mints.
3924
+ - Source: `lib/live-preview/cookie-reset.ts`.
3925
+
3926
+ ##### Browser tests (live preview)
3927
+ - `npm run test:e2e:live-preview` ⇒ `playwright.live-preview.config.ts`. Specs: `tests/e2e/live-preview/`. Guide: `tests/e2e/live-preview/README.md`.
3928
+ - Host-run isolated dashboard (global-setup, `HOME=<tmp>`, tiers 1/2/3/5). Not docker harness.
3929
+ - Projects: `chromium`, `firefox`, `chromium-resolver`.
3930
+ - `chromium-resolver`: `*.resolver.spec.ts` only. `--host-resolver-rules` maps `*.preview.test`, `dash.test`, `dash5.test` → `127.0.0.1`.
3931
+ - Docker-harness tier-5 / legacy spec: `tests/e2e/live-preview-harness-tiers.spec.ts`.
3932
+
3933
+ ##### Observability (redacted)
3934
+ - `[live-preview] mint tier= target= h= via= peerLocal= reason=`
3935
+ - `[live-preview] pool bind|release|exhausted`
3936
+ - `[live-preview] reserve port= session= h=`
3937
+ - `[live-preview] pid dropped reason=holder-revoked|expired|target-removed|adoption-refused`
3938
+ - `[live-preview] refuse h= reason=` (one per `h` per 60 s)
3939
+ - `[live-preview] admit h= tier=` (first per entry)
3940
+ - `h` = first 8 hex of `sha256(secret)`. Never label, pid, token.
3941
+
3942
+ See change: serve-live-previews-on-capability-origin.
3943
+
3224
3944
  ### Network Access Control
3225
3945
 
3226
3946
  One universal network guard plus the auth plugin. Universal guard runs whether or not auth is configured.
@@ -3261,6 +3981,8 @@ Both views are load-bearing because the router and the guard disagree about dot-
3261
3981
 
3262
3982
  **Denial contract.** `403` with body `{ success: false, error: "network_not_allowed", reason, hint }` — clients branch on `error`. Recorded in the buffer behind `GET /api/tunnel/block-events`, which powers the "Trust this network?" prompt. Logged as `[network-guard] denied reason=… path=… ip=…` — path + socket-peer IP + reason only; no body, no token.
3263
3983
 
3984
+ **Second denial surface: `/api/health`.** Health is a public exception, so the guard never refuses it. Health answers `200` carrying `networkAccess: { error: "network_not_allowed", hint }` — present iff `evaluateNetworkPass` (`packages/server/src/auth/localhost-guard.ts`) would refuse THIS caller and `localProof: "required"` not already reported (localProof wins). Constant value: no mode, no list, no address. Presence = caller's own admission only. No block event, no grant prompt, no telemetry — health never reaches `sendNetworkDenied`. Verdict reads admission list through 1 s TTL memo (≤1 config `statSync`/s); local / token / authenticated callers short-circuit first. Constants: `packages/shared/src/network-denial-signal.ts`. Client `useNetworkDenied` maps the field to denial → banner offers Request access, not Offline. See change: surface-network-denial-on-health.
3985
+
3264
3986
  **Second port.** Optional model-proxy second-port Fastify instance runs ONLY the proxy gate, no universal guard. Safe solely because it binds `127.0.0.1` (asserted by `packages/server/src/__tests__/model-proxy-second-port.test.ts`). If that bind ever becomes configurable, install the universal guard there too.
3265
3987
 
3266
3988
  **Namespace-coverage test.** `packages/server/src/__tests__/network-guard-namespace-coverage.test.ts` enumerates the real route table with plugin routes loaded. Fails if any non-static/non-`/auth`/non-public route sits outside the guarded namespaces or the enumerated independently-authenticated set (`/mcp`).
@@ -3285,25 +4007,53 @@ Both honor same matching logic. Both work independently of whether `auth.provide
3285
4007
 
3286
4008
  Hardens five residual trust / credential-boundary weaknesses from audit. Each mitigates a confirmed finding; none is a standalone RCE.
3287
4009
 
3288
- **Strict local proof (`requireLocalProof`).** Top-level config key, default `false`, read live per request — toggling needs no restart. Off = bare loopback (loopback peer, no forwarding header) stays trusted exactly as today. On = the network guard admits a bare-loopback request only on `observe`-tier `/api/*` REST reads (the `isObserveApiRequest` exception in `localhost-guard.ts`). Everything else needs PROOF, one of:
3289
- - `pi_dash_local` httpOnly `SameSite=Strict` cookie, 30 d, value `HMAC(localToken, "pi-dashboard/local-proof/v1")` — rotating the local token invalidates every proof cookie;
3290
- - `X-Pi-Local-Token` header;
3291
- - authenticated principal (`request.isAuthenticated`).
4010
+ **Strict local proof (`requireLocalProof`).** Top-level config key, default `true` (change `close-container-loopback-impersonation`). Missing or non-boolean value → `true`; server logs one warning per distinct raw value (`liveRequireLocalProof`, `packages/server/src/config-snapshot.ts`). Only explicit boolean `false` opts out. Read live from `config.json` per request — toggling needs no restart. Default on = the network guard admits a bare-loopback request (loopback peer, no forwarding header) only on `observe`-tier REST reads (`isObserveApiRequest` in `localhost-guard.ts`) and `/v1/*` (`packages/shared/src/route-tiers.ts`). Everything else needs PROOF, one of:
4011
+ - `pi_dash_local` httpOnly `SameSite=Strict` cookie (format below);
4012
+ - `X-Pi-Local-Proof` header (CLI, bridge);
4013
+ - desktop app (Electron loads `/auth/local-proof`);
4014
+ - signed-in or paired principal (`request.isAuthenticated`).
3292
4015
 
3293
4016
  Gated surfaces: `control` / `operate` REST routes, browser WS (`/ws`, `/ws/terminal/*`, `/live/*`), plugin-registered WS scopes (`isPluginScopePeerLocal`), bridge-ticket mint (`decideBridgeTicketMint`), and the route-tier exemption (`tierRefusalFor`). A `127.0.0.1` entry in `trustedNetworks` / `auth.bypassHosts` no longer re-admits a relay under strict — `isTrustedSource` refuses a loopback-range peer without proof.
3294
4017
 
3295
- **Why it exists.** A header-injecting tunnel (zrok) presents as loopback but carries `X-Forwarded-*`, so it already fails `isGenuinelyLocal`. A marker-less relay (`ssh -R`, `socat`) terminates on `127.0.0.1` and injects NO forwarding header — indistinguishable from a same-host browser, so it inherits full unauthenticated access to code-exec routes. Enable `requireLocalProof` when such a relay is used; only zrok-class tunnels are safe without it.
4018
+ ```mermaid
4019
+ flowchart TD
4020
+ R["Bare-loopback request<br/>(loopback peer, no X-Forwarded-*)"] --> O{"requireLocalProof<br/>explicit false?"}
4021
+ O -- yes --> T["Trusted (opt-out, legacy)"]
4022
+ O -- no --> V{"observe-tier REST<br/>or /v1/*?"}
4023
+ V -- yes --> A["Admit"]
4024
+ V -- no --> P{"Proof present?<br/>cookie / X-Pi-Local-Proof /<br/>principal"}
4025
+ P -- yes --> A
4026
+ P -- no --> D["403 network_not_allowed<br/>reason local_proof_required"]
4027
+ ```
4028
+
4029
+ **Why it exists.** A header-injecting tunnel (zrok) presents as loopback but carries `X-Forwarded-*`, so it already fails `isGenuinelyLocal`. A marker-less relay (`ssh -R`, `socat`) terminates on `127.0.0.1` and injects NO forwarding header — indistinguishable from a same-host browser, so it inherits full unauthenticated access to code-exec routes. Default on closes this. Opt-out (`false`) re-opens it; only zrok-class tunnels stay safe under opt-out.
4030
+
4031
+ **Denial.** Under strict, a proof-less bare-loopback denial is `403 { success: false, error: "network_not_allowed", reason: "local_proof_required", hint: … }` — same `error` literal as every other network denial, so clients keep branching on `error`; `reason` carries the strict-mode signal and `hint` names `pi-dashboard open`. `GET /api/health` adds `localProof: "required"` only for a bare-loopback caller without proof. Client `useNetworkDenied` probes on `offline` + `auth_required` and shows a banner with copyable `pi-dashboard open`. `/auth/login` shows the same remedy instead of single-provider auto-redirect. Signed-in loopback tab admitted on observe routes: session cookie tagged before the strict observe return (`packages/server/src/auth/auth-plugin.ts`).
4032
+
4033
+ **Bootstrap.** `pi-dashboard open [--print]` mints a one-time code (`POST /api/local-proof`, `X-Pi-Local-Token` only, 60 s TTL, single use via `LocalProofCodeStore`) and opens `/auth/local-proof?code=…`, which redeems it, sets the `pi_dash_local` cookie, and redirects `/`. Electron always loads that URL. Server not running → `open` exits `1` ("server not running"). Bootstrap routes register regardless of the flag. `pi-dashboard login --local` (break-glass) prints a link through `/auth/local-proof?code=…&next=/?pi_local=<code>` so a plain tab authorizes first.
4034
+
4035
+ **Forwarded loopback.** `ssh -L`, VS Code port forward, WSL arrive as bare loopback. Run `pi-dashboard open --print` on the server; open the printed URL through a SAME-PORT forward (cookie is port-bound).
4036
+
4037
+ **`pi_dash_local` cookie.** Format `id.issuedAt.lastUse.port.HMAC`, `HMAC` keyed `k_local = HMAC(localToken, "pi-dashboard/local-proof/v1")`. Bound to issuing listener `port` (`packages/server/src/auth/local-proof.ts`). Idle expiry 12 h. Re-signed on use when last refresh > 1 h old. Absolute cap 30 d. Rotating local token invalidates all cookies. Accepted residual: browsers send the cookie to every `localhost:<port>` site, so a local web app can capture and replay it to the same port within the idle window. Follow-up: dedicated loopback host.
4038
+
4039
+ **Opt-out.** `requireLocalProof: false` re-exposes the control plane to every container on the host: a container reaching host `127.0.0.1` (Docker Desktop `host.docker.internal`, `--network host`, `ssh -R`, `socat`) looks like bare loopback. See change: close-container-loopback-impersonation.
3296
4040
 
3297
- **Denial.** Under strict, a proof-less bare-loopback denial is `403 { success: false, error: "network_not_allowed", reason: "local_proof_required", hint: … }` — same `error` literal as every other network denial, so clients keep branching on `error`; `reason` carries the strict-mode signal and `hint` names `pi-dashboard open`.
4041
+ **One-time secret rotation.** `rotateSecretsOnce()` (`packages/server/src/auth/secret-rotation.ts`) runs at start of `createServer`. Claims `~/.pi/dashboard/local/rotation.lock` (exclusive link; stale after 30 s or dead pid; wait cap 35 s). If `local/rotation-epoch` < `REQUIRED_ROTATION_EPOCH` (=1): writes new 0600 `local/token` and new `auth.secret` (`writeConfigFileSecure`), then epoch file last. Effect: everyone signs in once; proof cookies reissued. Failure fails CLOSED: exit 1 before listening, one log line naming step + lock + epoch paths. Upgrade: stop every dashboard instance first (older instance on same HOME keeps old token until restart). No rollback needed; delete `local/rotation-epoch` only to force another rotation.
3298
4042
 
3299
- **Bootstrap.** `pi-dashboard open [--print]` mints a one-time code (`POST /api/local-proof`, `X-Pi-Local-Token` only, 60 s TTL, single use via `LocalProofCodeStore`) and opens `/auth/local-proof?code=…`, which redeems it, sets the `pi_dash_local` cookie, and redirects `/`. Electron always loads that URL. Server not running → `open` exits `1` ("server not running"). Bootstrap routes register regardless of the flag, so `open` works before strict is toggled.
4043
+ **Dashboard state guard** (`packages/server/src/lib/dashboard-state-guard.ts`). Always refused, every caller, every mode, not undone by opt-out: `~/.pi/dashboard/local/**` and `identity.key` (post-open fstat dev/ino recheck defeats symlink swap). Trust-gated: rest of `~/.pi/dashboard/` (`config.json` holds auth HMAC secret), refused unless caller locally trusted now or logged in (paired-device bearer not enough). Covers `/api/file*`, `/api/session-file`, `/api/file/write*`, `/api/grep`, mention resolve, open-in-system, reveal, live static gates. Unproven local caller's containment miss is prompt-ineligible (no operator access prompt).
4044
+
4045
+ **`pi-dashboard api <METHOD> <path> [--data <json>] [--port n]`** (`cmdApi`, `packages/server/src/cli.ts`). Mints fresh proof per request; dials loopback address literal; no redirect follow. Path: single leading `/`, no `#`, no control chars. Exit `0` on 2xx (body → stdout), `1` other status (body → stderr), `2` usage error or server not running. Unknown subcommand → exit 2 + usage. Older binaries without `api` fall through to foreground start: require the first release shipping `api`. Slash-command exec templates get env `PI_DASHBOARD_CLI` (absolute, shell-quoted): `eval "$PI_DASHBOARD_CLI" api GET /api/config`.
4046
+
4047
+ **Browser relay tickets.** `cdpUrl` and extension `mcpRelayUrl` carry single-use `?ticket=` (32 random bytes base64url, 60 s TTL, bound to guid + role `ext`|`cdp`, consumed by first presenting dial, in-memory, digest-only, never logged). Pass whole `cdpUrl` to `agent-browser connect`; dropped client needs fresh `browser_connect`. Plugin WS scopes may set `peerCredential: "plugin"` (skips only strict proof; host/origin/locality still enforced). Spike: `openspec/changes/close-container-loopback-impersonation/relay-ticket-spike.md`.
4048
+
4049
+ **Accepted residuals.** Observe-tier reads open to containers: transcripts, session lists, files inside session cwds and under `~/.pi` outside the dashboard dir (e.g. `~/.pi/agent/auth.json`); `$HOME`-cwd session also exposes `~/.ssh`. `/v1/*` spend. Live capability URLs (`/live/<token>/…`) judged without proof (Electron "Open in browser" needs it): a capability URL leaked into a transcript lets a container open that preview. A container that MOUNTS `~/.pi` or `$HOME` can read the token: NEVER mount `~/.pi/dashboard` into a container. Bridge gateway loopback grace + recovery server unchanged (out of scope).
3300
4050
 
3301
4051
  **Trade-offs (stated, not implied).**
3302
4052
  - `/v1/*` model proxy keeps bare-loopback admission even under strict: local pi processes call it, and a marker-less relay can spend model credentials but cannot execute code.
3303
4053
  - `/api/health` posture disclosure unchanged.
3304
- - A raw `curl -X POST` to `control` / `operate` routes from this host needs `X-Pi-Local-Token` (token at `~/.pi/dashboard/local/token`). `npm run reload` and the CLI `restart` already send it.
4054
+ - Raw `curl` to `control` / `operate` routes from this host is refused (`403 local_proof_required`). Use `pi-dashboard api <METHOD> <path>`. `npm run reload` and the CLI `restart` already send proof.
3305
4055
 
3306
- **Pairing approval never honors bare loopback (any mode).** `createApprovalGuard` on `POST /api/pair/approve` and `/api/pair/approve-pending` admits only a login session, a valid proof cookie, or `X-Pi-Local-Token`; a device bearer is refused first, and Host admission still applies. Default-off strict does not exempt it. A hand-typed `http://localhost:8000` on an auth-off install must use `pi-dashboard open` or Electron to approve; the dialog shows the hint.
4056
+ **Pairing approval never honors bare loopback (any mode).** `createApprovalGuard` on `POST /api/pair/approve` and `/api/pair/approve-pending` admits only a login session, a valid proof cookie, or `X-Pi-Local-Token`; a device bearer is refused first, and Host admission still applies. Applies in every `requireLocalProof` mode, including opt-out. A hand-typed `http://localhost:8000` on an auth-off install must use `pi-dashboard open` or Electron to approve; the dialog shows the hint.
3307
4057
 
3308
4058
  **Credential + trust hardening in the same change.**
3309
4059
  - Login OAuth state carried in a signed `pi_dash_oauth_state` cookie, verified before code exchange; `returnUrl` restricted to same-origin relative paths (closes CSRF + open redirect).
@@ -3336,7 +4086,7 @@ Durable dashboard trust counts as trusted project for pi sessions on SAME machin
3336
4086
  | `folderWorkspaces` | Folder workspaces. |
3337
4087
  | `accessGrants` | Project-root subjects only. Default OFF. |
3338
4088
 
3339
- NOT counted: server-lifetime trust (session worktree trust, session access grants, YOLO), KB source trust. Deferred follow-up: server-lifetime trust; bridges on other machines.
4089
+ NOT counted in snapshot: server-lifetime trust (session worktree trust, session access grants, YOLO), KB source trust. Server-lifetime trust + remote bridges now served by live query (see Live trust query).
3340
4090
 
3341
4091
  **Matching.**
3342
4092
  - Key form `piTrustKey` = `realpathSync(path.resolve)`. No Unicode-space normalisation. Source: `packages/shared/src/pi-trust-mirror.ts`.
@@ -3344,35 +4094,45 @@ NOT counted: server-lifetime trust (session worktree trust, session access grant
3344
4094
  - Identity: canonical path + `dev` + `ino` (+ `birthtimeMs` when recorded). Entry applies only on identity match.
3345
4095
  - Identity mismatch → fail closed. Other machine, re-created folder, moved folder.
3346
4096
 
3347
- **Deny rules** `mirrorDenyRules`. Separate from grant-subject `forbidden-subjects` (unchanged).
4097
+ **Deny rules** `mirrorDenyRules`. Builds on grant-subject `forbidden-subjects` (`grant.sensitive`), wider since change: harden-agent-tool-guards (D7).
3348
4098
  - Exact: `/`, `$HOME`, ancestors of `$HOME`, system dirs, broad parents (`/Users /home /Volumes /private /var/tmp /mnt /media`; win: drive root, `C:\Users`).
3349
- - Subtree: `~/.ssh ~/.pi ~/.aws ~/.gnupg ~/.kube ~/.docker`, OS temp (`os.tmpdir`, `/tmp`, `/private/tmp`), `~/.cache`, `~/Downloads`.
4099
+ - Subtree: every grant-subject sensitive subject (`~/.ssh`, `~/.pi`, `~/.aws`, `~/.config/gh`, `~/.gnupg`, `~/.kube`, `~/.docker`, `~/.netrc`, browser user-data roots) + OS temp (`os.tmpdir`, `/tmp`, `/private/tmp`), `~/.cache`, `~/Downloads`.
3350
4100
 
3351
4101
  **Decision order** `decidePiTrust` (shared by bridge, `host.isProjectTrusted`, toggle gate). First match wins.
3352
4102
 
3353
4103
  ```mermaid
3354
4104
  flowchart TD
3355
- A["project_trust / host.isProjectTrusted(cwd)"] --> B{"trust-requiring resources?"}
3356
- B -- no --> R0["trusted: implicit"]
3357
- B -- yes --> C{"pi recorded entry?"}
4105
+ A["project_trust / host.isProjectTrusted(cwd)"] --> C{"pi recorded entry?"}
3358
4106
  C -- "true / false" --> R1["pi decision wins"]
3359
- C -- none --> D{"mirror on AND covering entry?"}
4107
+ C -- none --> B{"trust-requiring resources?"}
4108
+ B -- no --> R0["trusted: implicit"]
4109
+ B -- yes --> D{"mirror on AND covering entry?"}
3360
4110
  D -- yes --> R2["trusted: dashboard source"]
3361
4111
  D -- no --> R3["defaultProjectTrust"]
3362
4112
  ```
3363
4113
 
4114
+ - Order = pi 1.5 (`project-trust.js:22-23`). See change: update-pi-core-1-5-adopt-apis.
3364
4115
  - `--approve` / `--no-approve` applied by pi first.
3365
4116
  - `--no-extensions`: bridge never decides.
3366
4117
  - `pi mcp list` reads only `trust.json`.
3367
4118
  - Dashboard trust overrides `defaultProjectTrust`, INCLUDING `never`.
3368
4119
  - Recorded pi entry (true or false, nearest ancestor) beats dashboard trust.
4120
+ - Trust-file keys compared like pi `pathsEqual` (`packages/shared/src/pi-path-compare.ts`: `piPathComparisonKey`, `piPathsEqual`, `nativePathApi`). Resolved; lower-cased on win32.
3369
4121
 
3370
4122
  **Bridge** `decideBridgeProjectTrust` (`packages/extension/src/project-trust.ts`).
3371
- - No server round trip.
4123
+ - No server round trip on snapshot step. Live query only on snapshot miss (see Live trust query).
3372
4124
  - Per event: reads `config.json`, `trust.json` (lockless; BOM stripped; null = absent; bad shape/parse = undecided `store-unreadable`), snapshot.
3373
4125
  - Returns `{trusted:"yes", remember:false}` or undecided.
3374
4126
  - Dashboard-spawned headless sessions consult mirror always. Other sessions only if `coverInteractive`.
3375
- - Reason codes logged when withheld: `forbidden-folder`, `recorded-entry`, `identity-mismatch`, `hook-changed`, `not-project-root`, `source-off`, `source-not-installed`, `choice-unreadable`, `store-unreadable`, `not-covered-session`.
4127
+ - **Activation cwd: no unconditional `yes`** (change: harden-agent-tool-guards D3). Activation cwd decided like any other cwd: recorded pi entry → snapshot mirror → live query. Auto-trusted only when dashboard trust covers it (pinned folder, workspace folder, covered grant, YOLO root via live query).
4128
+ - Nothing covers the activation cwd → `withheld("not-covered")`; pi decides (`trust.json`, then `defaultProjectTrust`; RPC has no prompt, `ask` = untrusted).
4129
+ - Road-independent: UI, MCP `spawn_session`, REST, WS, automation, goal, `/new`, worktree. No spawner cooperation, no flag, no state.
4130
+ - Forbidden/temporary activation folder (`/private/tmp`, `~/Downloads`, `~/.cache`, `$HOME`) → logs `forbidden-folder`. Never trusted **by the dashboard mirror**: no dashboard source covers a forbidden folder, bridge never returns `yes`.
4131
+ - pi still decides there: `piStoreBlocks` returns `recorded-entry` for a recorded pi entry; with none, bridge returns `undecided` → pi applies `trust.json`, then `defaultProjectTrust` (incl. `always`).
4132
+ - `piTrustMirror.enabled:false` also disables it (bridge returns undecided, pi decides).
4133
+ - Remedy for lost project `.pi/` resources: pin the folder, add it to a workspace, or `/trust` in a terminal pi.
4134
+ - Reason codes logged when withheld: `forbidden-folder`, `recorded-entry`, `identity-mismatch`, `hook-changed`, `not-project-root`, `source-off`, `source-not-installed`, `choice-unreadable`, `store-unreadable`, `not-covered-session`, `not-covered`, `identity-weak` + 7 `live-*` (see Live trust query).
4135
+ - Recorded-entry lookup `nearestRecordedEntry` (`packages/shared/src/pi-trust-mirror-snapshot.ts`) matches keys via `piPathsEqual`. Withholds yes for `/r/` or Windows case-different refusal.
3376
4136
  - p95 < 20 ms (1,000 entries, 20-deep cwd).
3377
4137
  - Spawn token: `PI_DASHBOARD_SPAWN_TOKEN` read + removed from env at bridge activation (`packages/extension/src/spawn-token.ts`). Process-global until first `session_register`. Agent-started nested pi never counts as dashboard-spawned.
3378
4138
 
@@ -3394,15 +4154,16 @@ flowchart TD
3394
4154
 
3395
4155
  **UI.**
3396
4156
  - Settings → Access → "Pi trust from the dashboard" (`packages/client/src/components/settings/PiTrustMirrorSection.tsx`): switches, effective list, per-entry choice, ignored rows (reason + label), pi `trust.json` entries + agent dir, disclosures.
3397
- - Disclosures: precedence over `defaultProjectTrust` (incl `never`); scope; `--no-approve` / `--no-extensions` / pi CLI not covered; activation-cwd rule.
4157
+ - Disclosures: precedence over `defaultProjectTrust` (incl `never`); scope; `--no-approve` / `--no-extensions` / pi CLI not covered; no activation auto-trust outside dashboard trust.
3398
4158
  - Folder page banner: pi / dashboard (source + folder; "dashboard sessions, not terminal pi" unless `coverInteractive`) / neither (links Settings → Access).
3399
4159
 
3400
4160
  **Breaking bridge behaviour.** NOT reverted by `enabled:false`.
3401
- - (a) Recorded pi entry beats activation-cwd auto-trust.
3402
- - (b) Activation-cwd auto-trust no longer applies in forbidden/temporary folders (logged).
3403
- - (c) Spawn token removed from env at activation (see Bridge).
4161
+ - (a) Recorded pi entry beats dashboard trust.
4162
+ - (b) No unconditional activation-cwd `yes` (harden-agent-tool-guards D3): a dashboard spawn in a folder dashboard trust does not cover gets `undecided` (`not-covered`) and pi decides.
4163
+ - (c) Bridge `yes` withheld in forbidden/temporary folders (logged `forbidden-folder`): dashboard trust never covers them, pi decides.
4164
+ - (d) Spawn token removed from env at activation (see Bridge).
3404
4165
 
3405
- **Rollback.** `piTrustMirror.enabled: false`. Bridge reads config live. Works with server down. Does not revert (a)-(c).
4166
+ **Rollback.** `piTrustMirror.enabled: false`. Bridge reads config live. Works with server down. Does not revert (a)-(d).
3406
4167
 
3407
4168
  **Security residuals.**
3408
4169
  - Hook trust widened to full project trust for the subtree. Checkbox text states it.
@@ -3412,6 +4173,130 @@ flowchart TD
3412
4173
 
3413
4174
  See change: mirror-dashboard-trust-to-pi.
3414
4175
 
4176
+ #### Live trust query (change: mirror-dashboard-trust-live-remote)
4177
+
4178
+ Extends mirror to server-lifetime trust + remote bridges. Live entries never written to disk. Snapshot carries count only. Bridge asks server on snapshot miss.
4179
+
4180
+ ```mermaid
4181
+ sequenceDiagram
4182
+ participant P as pi project_trust
4183
+ participant B as bridge decideBridgeProjectTrust
4184
+ participant S as server POST /api/pi-trust/query
4185
+ P->>B: project_trust(cwd)
4186
+ B->>B: store, recorded entry, snapshot cover (activation cwd = any cwd)
4187
+ Note over B: snapshot miss, ask conditions hold
4188
+ B->>S: { cwd } + local proof OR Bearer PI_DASHBOARD_TOKEN
4189
+ S->>S: auth, rate limit, cap 8 KiB, deny rules, cover lookup
4190
+ alt local requester
4191
+ S-->>B: { covered, key, sourceKind, dev, ino, birthtimeMs? }
4192
+ B->>B: identityMatches vs own stat
4193
+ else paired device
4194
+ S-->>B: { covered, salt, digest }
4195
+ B->>B: trustResourceManifest + HMAC, compare digests
4196
+ end
4197
+ B-->>P: trusted yes (remember false) OR undecided + reason code
4198
+ ```
4199
+
4200
+ **Route.** `POST /api/pi-trust/query` body `{cwd}`. Source: `packages/server/src/routes/pi-trust-query-routes.ts`. Path const `PI_TRUST_QUERY_PATH` (`packages/shared/src/pi-trust-live-query.ts`).
4201
+ - `ROUTE_TIERS` tier `operate` (same as `POST /api/ws-ticket`). Registered in `http-road-classification.ts`. Not PRE_AUTH.
4202
+ - Body cap 8 KiB → 413. Bad `cwd` (relative, NUL, length) → 400, never 500.
4203
+ - Server re-canonicalises: `piTrustKey(cwd) !== cwd` → not covered.
4204
+ - Handler order: auth → rate limit → body → switches + deny rules → cover lookup → proof → YOLO liveness re-check.
4205
+
4206
+ **Admission.**
4207
+ - Local = loopback + no forwarding headers + VERIFIED endpoint-bound `X-Pi-Local-Proof` (`kind === "proof"`). Shared `isLoopbackHost`.
4208
+ - Remote = paired device bearer at `operate`.
4209
+ - Refused: raw legacy local token, browser login cookie, trusted-network admission.
4210
+ - Proof binds method + path, not body. `cwd` = unauthenticated input.
4211
+
4212
+ **When bridge asks** (all must hold):
4213
+ - `enabled` ∧ `liveQuery` in `config.json`.
4214
+ - session allowed by `coverInteractive` rule.
4215
+ - no recorded pi entry.
4216
+ - `!isMirrorDenied(cwd)`.
4217
+ - snapshot gives no cover (any reason, incl `identity-mismatch`).
4218
+ - `liveCount > 0` ∨ remote bridge (non-loopback endpoint + `PI_DASHBOARD_TOKEN`).
4219
+
4220
+ Bridge `decideBridgeProjectTrust` now async. Snapshot step stays sync (p95 < 20 ms). Handler never throws: every path resolves `{trusted:"undecided"}` on failure.
4221
+
4222
+ **Live sources** (`piTrustMirror.sources.*`, in-memory, listed by provider in mirror service):
4223
+
4224
+ | Source | Covers | Lifetime |
4225
+ |---|---|---|
4226
+ | worktree-init session trust | `listSessionTrust()`, hook hash re-checked | until server restart |
4227
+ | session access grants | project-root subjects, `scope==="session"` | until server restart |
4228
+ | `yolo` (default ON) | roots of `yolo.status()` | scoped: until expiry. env activation: while server runs. unscoped: never |
4229
+
4230
+ - Identity `{dev, ino, birthtimeMs?}` recorded at entry creation, in-memory map keyed `<source>\0<key>`. Unstatable folder never counts.
4231
+ - Fixed listener gaps: session branches of `recordTrust`/`revokeTrust`/`recordGrant`/`revokeGrant` notify. `YoloController.setChangeListener` + unref'd expiry timer.
4232
+ - Snapshot field `liveCount` only. Never paths or identities. Boot writes `0`. Rewritten only when count changes, synchronously in the changing action. Failed rewrite logged, action succeeds. Reader treats missing/invalid as 0. Snapshot `version` stays 1.
4233
+ - Stale count = extra or missed query, never wrong yes.
4234
+ - Server consumers (`host.isProjectTrusted`, `projectTrustSource`, MCP view) run `decidePiTrust` over durable + live entries, no folder proof.
4235
+ - Server host predicate (`packages/server/src/pi/host-project-trust.ts`) reads recorded pi entry for EVERY folder. Dashboard trust + `defaultProjectTrust` read only when folder has trust-requiring resources and nothing recorded. Unreadable store / lock held → undecided (untrusted).
4236
+ - Toggle gate own-folder check (`packages/server/src/pi/resource-toggle-trust.ts`) uses `piPathsEqual`. Digest user-skills exclusion (`packages/shared/src/pi-trust-resource-digest.ts`) uses it too.
4237
+
4238
+ **Proofs.**
4239
+ - Local: recorded `dev`+`ino`[+`birthtimeMs`]. Bridge compares via `identityMatches`. Re-created folder → `identity-mismatch`.
4240
+ - Remote: `{covered:true, salt, digest}`. No source kind, no identity. Salt 16 random bytes.
4241
+ - `digest = HMAC-SHA256(salt, "pi-trust-live/v1\n" + cwdKey + "\n" + manifest)`. cwd key binds answer to path.
4242
+ - `manifest` = sorted entries of pi's trust-requiring resources: cwd `.pi/{settings.json,mcp.json,extensions,skills,prompts,themes,SYSTEM.md,APPEND_SYSTEM.md}` (recursive, label `c/<rel>`) + `<d>/.agents/skills` for cwd and each ancestor except `~/.agents/skills` (label `a<k>/<rel>`, `k`=levels above cwd).
4243
+ - Entry: file → `label\0f\0sha256(content)`. Dir → `label\0d`. Other type → null.
4244
+ - Shared fn `trustResourceManifest(cwd, {home, signal})` in `packages/shared/src/pi-trust-resource-digest.ts`. Async `fs/promises`, `AbortSignal`, one read per file.
4245
+ - Fail-closed → null → `identity-weak`: empty set, any symlink, `.pi/settings.json` unparseable/unknown ref shape/refs outside set (`packages` entry, ext/skill path outside), >1,000 files, >16 MiB, read failure.
4246
+ - Bridge compares two non-null digests only. Unequal → `identity-mismatch`.
4247
+ - Resource-name list = literal (pi does not export it). Golden test `packages/shared/src/__tests__/pi-trust-resource-golden.test.ts` asserts equality with installed pi `trust-manager.js` + `hasTrustRequiringProjectResources` parity.
4248
+
4249
+ **One deadline** `piTrustMirror.liveQueryTimeoutMs`.
4250
+ - Default 300 ms local / 1000 ms remote. Clamp 50–1000. Non-finite → default. Resolver `effectiveLiveQueryTimeoutMs` (`packages/shared/src/config.ts`).
4251
+ - Bounds request + proof. `Promise.race([work, deadline→live-timeout])`. `AbortController` per call aborts `fetch` (`redirect:"error"`) + every `fs/promises` read.
4252
+ - After race: `inst.isActive()` re-check. Stale instance → undecided.
4253
+
4254
+ **Reason codes** (`MirrorWithheldReason`, `packages/shared/src/pi-trust-mirror-types.ts`; 19, labels in `MIRROR_WITHHELD_LABELS`):
4255
+ - Parent (7): `forbidden-folder`, `not-project-root`, `hook-changed`, `source-off`, `source-not-installed`, `identity-mismatch`, `choice-unreadable`.
4256
+ - Bridge (5): `recorded-entry`, `store-unreadable`, `not-covered-session`, `not-covered`, `identity-weak`.
4257
+ - `not-covered` = bridge log only (label "no dashboard trust source covers this folder"); never an Access-page ignored row, no source produced the folder.
4258
+ - Live (7): `live-timeout`, `live-unreachable`, `live-refused`, `live-unsupported`, `live-rate-limited`, `live-not-covered`, `live-error`.
4259
+
4260
+ | Outcome | Code |
4261
+ |---|---|
4262
+ | connection refused | `live-unreachable` |
4263
+ | 401 / 403 | `live-refused` |
4264
+ | 404 (old server) | `live-unsupported` |
4265
+ | 429 | `live-rate-limited` |
4266
+ | abort / deadline | `live-timeout` |
4267
+ | answer `covered:false` | `live-not-covered` |
4268
+ | 5xx, redirect, malformed body, covered answer missing proof fields | `live-error` |
4269
+
4270
+ **Rate limits.**
4271
+ - Fixed window 10 s. 20 queries per paired device. 200 for `local` requester.
4272
+ - Proof permits: 4 global, 1 per device. Excess → 429. One log line per window. Control chars stripped from logged `cwd`/device.
4273
+ - Local identity answers take no permit.
4274
+ - No manifest cache (staleness in security decision).
4275
+
4276
+ **Health.** `/api/health` `piTrustMirror.live` = `{covered, notCovered, refused, rateLimited, budgetMissed}`. Same disclosure gate as access-grant health block (`access-health.ts`). Server-side only. `budgetMissed` = handling time > server `liveQueryTimeoutMs` for requester class. Bridge logs own reason codes. Remote bridge with shorter timeout can log `live-timeout` while server counts `covered`.
4277
+
4278
+ **Settings + rollback.**
4279
+ - `piTrustMirror.liveQuery` (default `true`), `liveQueryTimeoutMs`, `sources.yolo` (default `true`).
4280
+ - `liveQuery=false`: no queries. Bridge reads `config.json`, works with server down.
4281
+ - `sources.yolo=false`: YOLO roots stop counting. Other live sources stay.
4282
+ - `enabled=false`: everything off.
4283
+ - Old bridge never queries. New bridge + old server → 404 → `live-unsupported` → undecided.
4284
+ - Nothing live persisted.
4285
+
4286
+ **Residuals.**
4287
+ - YOLO default ON widens YOLO from file access to project-code execution in its roots. Disclosed at activation + Access page. Unscoped YOLO never counts. Deny rules apply.
4288
+ - npm packages named in `.pi/settings.json` bound by reference, not fetched bytes.
4289
+ - Marker-less relay (`ssh -R`, `socat`) + shared home can look local. Needs same-user access + dev+ino(+birth) match. Accepted.
4290
+ - `ssh -L` tunnel + shared home: loopback → classed local → `identity-mismatch`, fail-closed. Dial non-loopback endpoint with device token.
4291
+ - Symlinked (pnpm-style) trees, >1,000 files, >16 MiB → no remote trust (`identity-weak`).
4292
+ - Benign `.pi/settings.json` edit on one side drops remote trust.
4293
+ - Local-rate-limit key shared by all local pi. 200/10 s sized for fleet spawns.
4294
+ - Snapshot step sync: hung mount blocks before live deadline starts (parent residual).
4295
+ - Non-goal: no path mapping between machines. Canonical paths must be equal.
4296
+ - Non-goal: no defence against malicious bridge. Bridge decides only for own pi process.
4297
+
4298
+ See change: mirror-dashboard-trust-live-remote.
4299
+
3415
4300
  ### Access Grants and Denial Remedies (change: add-access-grants-and-review)
3416
4301
 
3417
4302
  Companion to **Network Access Control** above. That section's universal `onRequest` guard is the network plane; this one is the filesystem plane. Both turn a terminal refusal into a remedy an operator can accept. Network plane: `403 network_not_allowed` → `BlockEventBuffer` → "Trust this network". Filesystem plane: a containment refusal → `denialId` → **grant** → next read admitted, no restart. The guard above is not re-explained here; see it for the network plane.
@@ -3448,6 +4333,21 @@ The rejected alternative, `within(realpath(resolved), realpath(grant))`, was a *
3448
4333
 
3449
4334
  **The store.** `packages/server/src/access/access-grants.ts`. Persisted at `~/.pi/dashboard/access-grants.json` (`PI_ACCESS_GRANTS_STORE` overrides; schema `{ version: 1, grants }`). One grant carries `subject` (realpath), `scope` (`"session"` — in-memory until server restart — or `"project"` — persisted), `grantedAt`, `origin` (the session whose denial produced it), and optional `widenedFrom` (the denied subject when the grant came from an offered ancestor). Invariants: absent/malformed store → empty, never throws; **cap 200 per scope**, oldest-`grantedAt` evicted within that scope only (a union cap would let an ephemeral session grant delete a persisted project grant); writes atomic (temp + rename) so a crash mid-write cannot truncate the store into its own malformed→empty rule; a failed write is non-fatal — the subject stays ungranted, the failure is logged **and returned to the caller** so the UI cannot claim a grant that does not exist. Recorded grants are audited (`[access-grant] granted subject=… scope=… site=… denialId=…`).
3450
4335
 
4336
+ **Write-mode grants** (change: fix-file-link-editor-routing, D2). Out-of-cwd text-doc save (`POST /api/file/write`) needs write grant. Read grant never admits write.
4337
+
4338
+ - `AccessGrant.mode?: "read" | "write"`. Absent = read. Store stays `version: 1`; rollback-safe (old build reads entry as read grant).
4339
+ - `loadFromDisk` fail-closed: `mode` other than exact `"write"` → read.
4340
+ - One entry per `(subject, scope, mode)`. Write grant = second entry beside read grant. Revocable independently.
4341
+ - `grantedSubjects()` unchanged, includes write entries (write ⊃ read). `grantedWriteSubjects()` = `mode:"write"` only.
4342
+ - Write evaluation: `evaluateContainment(..., {action:"write"})`. Skips layer ② (`checkoutAnchors`): checkout roots never admit write. Grant layer uses write subjects only.
4343
+ - Denial side field = `action: "read" | "write"` (`PathDenial`, `DenialFacts`, `PendingGrant`). Not `mode`: `mode` already names held/deferred prompt plane.
4344
+ - Pending registry key = `plane \0 action \0 subject`. Read + write denial for same dir = separate entries.
4345
+ - Grant mode derived server-side from recorded denial/prompt `action`. Never from client field. `grant_response` carries verdict + rung only.
4346
+ - `allow-once` = transient real-path grant for this request, write predicate, never persisted. `performAtomicMdWrite` re-realpath must equal gated realpath, else refuse.
4347
+ - YOLO: write hold = filesystem-plane denial → auto allow-once, only within YOLO roots (default root = session cwd → outside write still prompts). No persisted grant.
4348
+ - Prompt before existence: nonexistent outside doc prompts, then `404`. Stat-first = existence oracle, refused.
4349
+ - Access page: write row shows "Write" badge. `DELETE /api/access/grants` optional `mode`; last-entry removal only un-mirrors pi-trust.
4350
+
3451
4351
  `"session"` scope means the **server process**, not the pi session whose denial produced it (design D17): one grant widens the grant layer for every session and every connected client; `origin` is what the Access tab shows.
3452
4352
 
3453
4353
  **Read-once, cost-bounded on the hot path** (design D16). The store is loaded into memory once and invalidated on write; the containment path never reads the store synchronously. `isAllowed` is async by explicit design (one caller stalling would block every request), so a sync read on that path would regress it. With an empty store the predicate short-circuits with zero syscalls — that is what makes "empty store is byte-identical to today" true of **cost** as well as outcome. When grants exist, evaluation is a linear scan of distinct subjects with one `realpath` on the request side; `grep-routes.ts` awaits the predicate per match, so N matches x 200 grants x a `realpath` is the worst case the cap alone does not bound. `GET /api/access/store-stats` exposes the load count so a test can prove the hot path never re-reads the store. Rollback consequence: deleting the store file changes nothing until the process restarts — the supported rollback is **revoke through the Access tab** (which invalidates the in-memory set), or delete-then-restart.
@@ -3485,7 +4385,7 @@ Bridge-side companion to **Access-Grant Prompts and YOLO** and **Access Grants a
3485
4385
 
3486
4386
  **Approve, not sandbox.** Gate asks operator when a covered tool leaves its roots. Does **not** confine: `bash`, `grep`, `find`, `ls`, custom and MCP tools are not covered (shell strings are not reliably parseable). UI copy must not call it a sandbox or confinement. Agent runs as the operator's user and can write `access-grants.json` itself; nothing here defends against a hostile local process.
3487
4387
 
3488
- **Where it lives** (design D1). Pure decision module `packages/extension/src/path-gate/` (`decidePathAccess`, plus `resolve.ts`, `roots.ts`, `grant-cache.ts`, `suppression.ts`, `grant-link.ts`, `handler.ts`, `index.ts`). Registered in `bridge.ts` as its own `tool_call` handler **after** the fan-out admission handler (`fanoutAdmission.onToolCall`), **not** wrapped in the fail-open `safe(...)`. Own `try/catch` maps any internal error — including a throwing `ctx.cwd` getter after session teardown — to `{ block: true, reason }`. In-root calls take no round-trip.
4388
+ **Where it lives** (design D1). Pure decision module `packages/extension/src/path-gate/` (`decidePathAccess`, plus `resolve.ts`, `roots.ts`, `grant-cache.ts`, `suppression.ts`, `grant-link.ts`, `handler.ts`, `index.ts`). Registered in `bridge.ts` as its own `tool_call` handler, **not** wrapped in the fail-open `safe(...)`. Own `try/catch` maps any internal error — including a throwing `ctx.cwd` getter after session teardown — to `{ block: true, reason }`. In-root calls take no round-trip.
3489
4389
 
3490
4390
  **Gated tools.** `read`, `write`, `edit` only, matched by name.
3491
4391
 
@@ -3640,7 +4540,7 @@ YOLO requires `hostGate.mode === "enforce"` and a HELD-eligible denial; there is
3640
4540
 
3641
4541
  An operator's explicit `deny` on a YOLO-eligible plane or the `agent-path` surface is remembered in the **refusal ledger** (`access/refusal-ledger.ts`, `access-refusals.json`, `PI_ACCESS_REFUSALS_STORE` overrides the path) — durable, cleared only by the operator — so a later YOLO session refuses that subject (`refused-by-prior-refusal`) instead of auto-allowing it. Auto-answers are logged `(no human answered)` and kept in a bounded in-memory history. Store conventions mirror `access-grants.json`: atomic temp+rename, missing/malformed = empty, a failed write leaves the cache unchanged.
3642
4542
 
3643
- **Opt-in and env vars** (D10). Prompting ships behind `accessGrants.promptEnabled` (**default `false`**). `PI_DASHBOARD_DISABLE_GRANT_PROMPT=1` is the kill switch — it engages only on the exact value `1` (`isGrantPromptKilled`). Both suppress *prompting only*: existing grants stay in force and denials still land in the pending list. The no-audience rule is necessary but not sufficient for automation — Playwright E2E runs with a browser connected, so CI relies on the env var. `PI_DASHBOARD_GRANT_YOLO` (`parseYoloEnv`) takes one plain absolute path, a JSON array of absolute paths for several, or the literal `unscoped`; anything else (`1`, `true`, relative, `[]`, malformed JSON, `UNSCOPED`) is `invalid` and leaves YOLO inactive.
4543
+ **Opt-in and env vars** (D10). Prompting is gated by `accessGrants.promptEnabled` (**default `true`** since D16 of `add-access-provisioning`; was `false`. Absent key = on; explicit `false` is kept). `PI_DASHBOARD_DISABLE_GRANT_PROMPT=1` is the kill switch — it engages only on the exact value `1` (`isGrantPromptKilled`). Both suppress *prompting only*: existing grants stay in force and denials still land in the pending list. The no-audience rule is necessary but not sufficient for automation — Playwright E2E runs with a browser connected, so CI relies on the env var. `PI_DASHBOARD_GRANT_YOLO` (`parseYoloEnv`) takes one plain absolute path, a JSON array of absolute paths for several, or the literal `unscoped`; anything else (`1`, `true`, relative, `[]`, malformed JSON, `UNSCOPED`) is `invalid` and leaves YOLO inactive.
3644
4544
 
3645
4545
  **REST** (`packages/server/src/routes/access-prompt-routes.ts`):
3646
4546
 
@@ -3653,6 +4553,108 @@ Access-page mutations (`POST /api/access/prompts/:promptId`, `POST`/`DELETE /api
3653
4553
 
3654
4554
  **Coverage.** Browser E2E `tests/e2e/access-grant-dialog.spec.ts`; clean-install VM smoke `qa/tests/36-access-grant-dialog.sh`.
3655
4555
 
4556
+ ### Access provisioning (change: add-access-provisioning)
4557
+
4558
+ Companion to **Access-Grant Prompts and YOLO** above. Denial dialogs ask one subject at a time, after a denial. Provisioning asks once, up front: agent submits a project's declared folder needs, operator approves per line, approved lines become persisted grants.
4559
+
4560
+ Design: `openspec/changes/add-access-provisioning/design.md` (D1–D16).
4561
+
4562
+ **Flow.**
4563
+ - Agent runs skill `project-access` (`packages/extension/.pi/skills/project-access/SKILL.md`, beside `project-init`). Modes: `map` (read-only), `suggest` (drafts profile, writes after `ask_user` confirm), `provision` (submit + poll).
4564
+ - Profile `.pi/access.json`: `{ version: 1, folders: [{path, why}], remote: ("lan"|"internet"|"device")[] }`. Optional. Only the skill reads it. Server never reads it. Unknown `version` → skill refuses.
4565
+ - Skill calls `POST /api/access/provision`. Route validates, classifies, records pending request, delivers `provision_request`. Route writes no grant, no config.
4566
+ - Operator answers per line in `ProvisionPromptDialog` (`packages/client/src/components/access-grant/`). Answer settles request. Settle writes grants.
4567
+ - Skill polls `GET /api/access/provision/:id` until terminal. 404 (server restart) → reported "unknown".
4568
+
4569
+ ```mermaid
4570
+ flowchart TD
4571
+ S["skill project-access: POST /api/access/provision"] --> L{"eligibility ladder (D7)"}
4572
+ L -->|fail| X["refused: 503 / 409; nothing recorded"]
4573
+ L -->|pass| V["validate root (D8) + classify lines (D4) + bounds (D6)"]
4574
+ V -->|fail| X
4575
+ V --> R[("provisioning registry (in memory)")]
4576
+ R --> O["provision_request to operator sockets only"]
4577
+ O --> A{"provision_response / POST :id/settle"}
4578
+ A -->|no live capability| DR["dropped + counted; request stays pending"]
4579
+ A -->|capability held| RS["re-check ladder + root; re-verify lines; one sync write section"]
4580
+ RS --> G["recordGrant(via: provision, evict: false)"]
4581
+ O -.->|terminal transition| DM["provision_dismiss to all tabs"]
4582
+ ```
4583
+
4584
+ **Registry.** `packages/server/src/access/provisioning.ts` (`ProvisioningRegistry`; `create` / `get` / `settle` / `dismiss` / `dismissAll` / `expire` / `list` / `stats`; `now` injected). Wiring `access/provisioning-wiring.ts`: operator-socket delivery, expiry timer, `provision_dismiss`, capability-gated `onResponse`. Own registry, not an access plane (D1): one record, N lines, one dialog. Never touches `PendingGrantRegistry`. Never consults YOLO. Memory only; restart loses pending requests, grants already written stay.
4585
+
4586
+ **Routes** (`packages/server/src/routes/access-routes.ts`; all `networkGuard`).
4587
+ - `POST /api/access/provision` — create. Operate tier.
4588
+ - `GET /api/access/provision` — list pending. Observe tier.
4589
+ - `GET /api/access/provision/:id` — status + per-line outcome. Pending or last 50 ended.
4590
+ - `POST /api/access/provision/:id/settle` — answer. Needs `isPromptEligible(request)`, else 403 `no-capability`.
4591
+ - `POST /api/access/provision/dismiss-all` — dismiss every pending. Needs `isPromptEligible(request)`. Counts as dismissal per request; starts each root's cooldown.
4592
+
4593
+ **WS messages** (`packages/shared/src/browser-protocol.ts`).
4594
+ - `provision_request` — server → browser. Carries lines + classification. Sent only to operator sockets.
4595
+ - `provision_response` — browser → server. `{requestId, lines: [{lineId, verdict: "approve"|"reject", piTrust?}]}`. Omitted line = reject. Tier `operate` (`ws-message-tiers.ts`).
4596
+ - `provision_dismiss` — server → browser. Sent on every terminal transition. Closes dialog in other tabs.
4597
+
4598
+ **Capability-targeted delivery + settle** (D2/D3).
4599
+ - Operator socket = holds live prompt capability AND operate tier. New gateway send helper; not `broadcastToAll`. `no-operator` counts the same set.
4600
+ - `provision_response` settles only if `holdsLiveCapability(ws)` (`pairing/browser-gateway.ts`). Backed by `WeakMap<WebSocket, grantSocketId>` filled at capability issue, cleared at release, checked against live channel table in `prompt-channel.ts`. Capability A never authorises socket B. Failing message dropped + counted (`droppedResponses`).
4601
+ - HTTP settle needs `isPromptEligible(request)`. Client already attaches `X-Pi-Grant-Channel` to same-origin `/api/*` (`grant-channel.ts`). Access page needs no allowlist change.
4602
+ - Dialog close sends `provision_response` with every line rejected. Same gate.
4603
+ - Plain operate-tier request from agent (no capability) cannot settle.
4604
+ - Settle re-checks ladder. Now failing → answer refused; request stays pending until TTL.
4605
+ - Terminal transitions first-wins. Later answer → 409 `already-settled`.
4606
+
4607
+ **Eligibility ladder** (D7; coupled to `accessGrants.promptEnabled`). Creation refused in order:
4608
+ 1. `PI_DASHBOARD_DISABLE_GRANT_PROMPT=1` → 503 `disabled`.
4609
+ 2. `accessGrants.promptEnabled === false` → 409 `prompting-disabled`.
4610
+ 3. host gate `report` mode → 409 `report-mode`.
4611
+ 4. `promptChannelCount() === 0` → 409 `no-operator`.
4612
+
4613
+ Same ladder gates settle. One switch covers every dialog.
4614
+
4615
+ **Project root** (D8). `projectRoot` absolute, exists, directory, holds `.git` or `.pi`, not ungrantable. Real path = pending key + grant `origin`. Agent can create `.git` anywhere it can write → origin is a *claimed* label. UI says "requested for `<path>`", never "belongs to".
4616
+
4617
+ **Line classification** (D4; first match wins). Expand (absolute, `~/`, project-relative) → `invalid` | real path + must be directory → `missing` (file line is `missing`, never grants parent) → `forbidden` (`isUngrantableSubject`) → `sensitive` (D5a) → `in-root` → `covered` (persisted grant admits) → `grantable`. Same real path collapses; first `why` kept. Only `grantable` approvable. `why` capped 200 chars, control chars stripped, rendered as React text only, JSON-quoted in logs.
4618
+
4619
+ **Bounds** (D6; `PROVISION_*` constants).
4620
+
4621
+ | Bound | Value | On breach |
4622
+ |---|---|---|
4623
+ | Lines per request | 32 | 400 `too-many-lines` |
4624
+ | Pending per project root | 1 | 409 `pending-exists` + existing id |
4625
+ | Pending total | 4 | 429 `capacity` |
4626
+ | Creations per project root | 1 / 60 s | 429 `rate-limited` + retry-after |
4627
+ | Cooldown after request ended with no approved line | 5 min per root | 429 `cooldown` |
4628
+ | Creations total | 3 / 10 min | 429 `rate-limited` |
4629
+ | Request TTL | 10 min | `expired`; nothing granted |
4630
+
4631
+ Residual: per-root limits do not bind an agent that creates `.git` in fresh directories. Global limit still allows 18 dialogs/hour; rotating agent can hold all 4 slots → legitimate requests get `429 capacity`. Mitigation: Access page lists every pending request with claimed root; "Dismiss all pending". Block-by-requester = follow-up.
4632
+
4633
+ **Approval** (D5). Settle runs two phases.
4634
+ - Async: re-check ladder, re-validate root (fail → every approved line `refused`, `root-changed`), re-classify approved lines.
4635
+ - Sync, no `await`: `realpathSync` each approved line vs shown real path. Mismatch or no longer `grantable` → `changed` / `refused` before any write. Count net-new subjects; `persisted + net-new > 200` → every approved line `refused` (`capacity`). Else `recordGrant({subject, scope: "project", via: "provision", origin, evict: false})` per line. Write failure → `failed`; later lines still run.
4636
+ - Node runs sync section uninterleaved: no other grant write in this server process lands between compare, capacity check, writes. Home lock is advisory; other-process writers not serialised (they can write the file directly anyway).
4637
+ - Outcomes: `granted`, `rejected`, `changed`, `refused`, `failed`, `handed-off`.
4638
+
4639
+ **Provisioned grants are never evicted.** `enforceCap` skips `via: "provision"`. Denial-path write at the 200 cap evicts oldest *non-provisioned* grant. All 200 provisioned → denial-path write refused like any failed write. Eviction logs `[access-grants] evicted subject= via=`. "Permanent" = until operator revokes on the Access page. Grants are machine-wide by folder (`scope: "project"` = persisted, not per-project); dialog copy says so.
4640
+
4641
+ **Credential-folder refusal** (D5a). `forbiddenGrantSubjects().sensitive` covers only `~/.ssh`, `~/.pi`. Provisioning also classifies `sensitive` any line at, below, **or an ancestor of** `~/.aws`, `~/.gnupg`, `~/.kube`, `~/.docker`, macOS `~/Library/Keychains` (grant admits whole subtree; `~/Library` would admit `Keychains`). Known gap, not closed here: denial path can still grant these folders and ancestors, no warning. Follow-up.
4642
+
4643
+ **pi trust per line** (D9). `grantable` line whose real path holds `.git` or `.pi` shows `PiTrustCheckbox`, unchecked by default, with consequence statement. Approved project-root line with omitted `piTrust` → `false` (explicit choice always stored). Applied only to lines ending `granted`, via `mirror.setChoice("accessGrants", subject, piTrust)`.
4644
+
4645
+ **Remote goals** (D10). `remote` entries render as "Open Remote access" actions naming the wizard task (lan → "Allow devices on my network"; internet → "Share over the internet"; device → "Let a phone or laptop in"). Action opens `RemoteAccessDialog` on its landing. Outcome `handed-off`. Provisioning writes nothing remote.
4646
+
4647
+ **Observability** (D14). Logs `[access-provision] created|settled|dismissed|expired|refused id= project=<json> lines= approved= reason=`; dropped response `[access-provision] response-dropped reason=no-capability`; per-grant `[access-grant] persisted … via=provision`. `/api/health` `accessGrants.provisioning = {pending, created, approved, rejected, dismissed, expired, refused, droppedResponses}` (cumulative except `pending`; additive, optional) via `snapshotAccessGrantHealth` (`access/access-health.ts`).
4648
+
4649
+ **Stated trust limit** (D11, operator decision A). Consent + audit on the honest path. **Not containment.** Approval proves a capability-holding connection answered, nothing more. Local process running as operator (incl. agent `bash`) can: write `access-grants.json` directly; create `.git` to claim a root; forge a browser-shaped WS to obtain a capability and settle its own request; already settle denial prompts via `POST /api/access/prompts/:promptId` (no capability check). What it does stop: *casual* self-approval via plain operate-tier request. Dialog, skill and docs state this. Operator-presence proof (passkey user verification) = follow-up.
4650
+
4651
+ **Reversal of archived D12/D15** (`add-access-grants-and-review`; design D15 here).
4652
+ - D12 "Access tab reviews and revokes, never creates": *kept* — no free-form add control anywhere. *Revised* — Access page may answer a pending provisioning request it lists; same per-line verdict as dialog.
4653
+ - D15 "grant names only a subject a recorded denial named": *kept* — forbidden subjects on stored value, real-path subjects, authentication, no cross-origin. *Replaced for this path only* — binding becomes "line operator approved on a capability-holding connection, re-verified at approval".
4654
+ - Rationale: D15 protects callers that cannot see the denial. Provisioning protects the same property (operator saw this exact real path) through the dialog. Stricter than denial path in two ways: credential folders refused (D5a); settle requires capability (D3).
4655
+
4656
+ **Default flip** (D16). `accessGrants.promptEnabled` default `true`; explicit value kept; no config migration. Denial dialogs now appear on default installs with host gate `enforce` and an operator browser open. Automation sets `PI_DASHBOARD_DISABLE_GRANT_PROMPT=1`. Agent path gate does not read `promptEnabled` (own `agentPathGate` switch). Rollback: revert change; provisioned grants stay ordinary revocable grants.
4657
+
3656
4658
  ### Plugin cwd admission (change: harden-plugin-cwd-admission)
3657
4659
 
3658
4660
  Plugin route `cwd` gate. Async tri-state (`admitCwd`, `packages/shared/src/cwd-guard.ts`): `admit{token}` | `refuse` | `indeterminate{failedProbes, elapsedMs}`.
@@ -3684,6 +4686,59 @@ flowchart TD
3684
4686
  G -->|refuse| F
3685
4687
  ```
3686
4688
 
4689
+ ### Core cwd admission (git / openspec routes)
4690
+
4691
+ Git routes + caller-`cwd` openspec routes admit via `admitRouteCwd` (`packages/server/src/lib/route-admission.ts`) → shared `admitCwd` (`packages/shared/src/cwd-guard.ts`). Same tri-state as plugin cwd admission (above).
4692
+
4693
+ - Route branches `admissionAllows(admission, cwd)` on RAW request value (same var passed to `admitRouteCwd`).
4694
+ - Git ops run on `token.canonCwd`.
4695
+ - Openspec ops + keys keep raw `cwd`. Guard sanitizes the variable itself.
4696
+ - Known set = `listKnownFolderCwds` (session cwds ∪ pinned dirs, unfiltered). Same fn behind `host.knownFolderCwds`.
4697
+ - Openspec fallbacks (`knownCwds()[0]`, `update {all}`) unchanged, not admitted.
4698
+
4699
+ Admitted: known cwd; subdirs + linked worktrees of known main checkout.
4700
+ Refused: sibling worktree of known worktree; main checkout of known worktree; child repo of pinned non-repo folder; symlink to unknown; regular file (`checkoutRootsClassifiedAsync` reads `spawn ENOTDIR` as `none` → refuse; Windows errno may differ → 503).
4701
+
4702
+ Gated openspec writes (`init`, `workflow-schema`, dependencies GET/PUT): admit first, then exact `knownInitTargets` membership + opt-out (raw + canonical) + global-dir exclusion. Refusal bodies unchanged.
4703
+
4704
+ Codes:
4705
+
4706
+ | Condition | Status | Body |
4707
+ |---|---|---|
4708
+ | git refuse | 400 | `code: cwd_unknown` |
4709
+ | ungated openspec refuse | 403 | `code: cwd_unknown`, `reason`, `hint` |
4710
+ | indeterminate | 503 + `Retry-After: 1` | `success:false`, `code` = `error` = `cwd-admission-unavailable`, `message`, `retryAfterMs:1000` |
4711
+ | non-portable `change` segment | 400 | `code: invalid_name` |
4712
+ | git cwd missing / not dir (admitted only) | 400 | `code: cwd_invalid` |
4713
+ | folder-project | 503 | own body `{error, message, retryAfterMs}`, no `code` |
4714
+
4715
+ `remove-batch`: items admitted sequentially, memo per raw cwd. Whole-batch budget 10 s; per-admission deadline `min(3000, remaining)`. Budget spent → only direct matches decided, rest `cwd-admission-unavailable`. Per-item codes (`cwd_unknown` / `cwd_invalid` / `cwd-admission-unavailable`). Envelope 200, no `Retry-After`. Classification memo keyed by `token.canonCwd`.
4716
+
4717
+ Token: released on `reply.raw` close (git + openspec helpers); `finally` in `remove-batch` and folder-project.
4718
+
4719
+ Client: text via `err.cwd_unknown`, `err.cwd_admission_unavailable`, `err.invalid_name`. `fetchWorktreeInitStatus` reports `cwdUnknown`. Post-spawn auto-init (`autoInitWorktreeOnSpawn` ON) re-probes every 500 ms, up to 10 s, on `cwd_unknown`. MCP server plugin tools surface refusals as tool errors.
4720
+
4721
+ ```mermaid
4722
+ flowchart TD
4723
+ R["request cwd (raw)"] --> A["admitRouteCwd"]
4724
+ A --> D{"admitCwd decision"}
4725
+ D -->|"admit"| B{"admissionAllows(adm, cwd)"}
4726
+ B -->|"true"| OK["200 path: git on token.canonCwd, openspec on raw cwd"]
4727
+ B -->|"false"| RF["refuse"]
4728
+ D -->|"refuse"| RF
4729
+ D -->|"indeterminate"| IND["503 cwd-admission-unavailable, Retry-After 1"]
4730
+ RF -->|"git"| E400["400 cwd_unknown"]
4731
+ RF -->|"ungated openspec"| E403["403 cwd_unknown"]
4732
+ RF -->|"gated openspec"| EG["today's refusal body"]
4733
+ ```
4734
+
4735
+ Latency (`evidence/latency.md`, 84 known folders, direct match):
4736
+
4737
+ - `git status`: +0.66 ms p50 / +1.48 ms p99 (gate ≤2 / ≤15). `openspec tasks`: +0.30 ms p50 / +0.36 ms p99.
4738
+ - Derivation path: 0 indeterminate / 200; p99 < 0.5 s.
4739
+
4740
+ See change: core-cwd-admission.
4741
+
3687
4742
  ### OAuth Authentication Flow
3688
4743
 
3689
4744
  Optional OAuth2 authentication protects the dashboard when accessed remotely.
@@ -3943,6 +4998,37 @@ sequenceDiagram
3943
4998
 
3944
4999
  `request-access` remedy on `operate_required`: present iff no credential + knock pre-switch gates pass (`knockPeerGate`). Discloses only `host_not_admitted` | `knock_not_lan`. Never reads `acceptLanRequests`. See `docs/credential-vault.md` §10. See change: add-request-access-remedy.
3945
5000
 
5001
+ #### Route delegation and pair action (change: group-servers-by-identity)
5002
+
5003
+ Identity challenge is public and separate from access check:
5004
+
5005
+ - `POST /api/pair/challenge {nonce}` → `{fingerprint, publicKey, signature, v}`. Public (`PUBLIC_PAIRING_PREFIXES`, `pairing-routes.ts`). Answers where `/api/health` returns `403 network_not_allowed`.
5006
+ - Proof: Node `proveServerIdentity` (`packages/shared/src/server-pinning.ts`); browser `challengeIdentity` (`packages/client/src/lib/pairing/pair-protocol.ts`).
5007
+
5008
+ Delegation (D7):
5009
+
5010
+ - `POST /api/pair/poll` `approved` answer → `{status, token, routes}`. `routes` = `reachableUrls()` filtered to `https:`, origin-normalised (`httpsOrigins`, `pairing-routes.ts`). `wss://` and `PI_E2E_SEED` loopback `http` stay in QR `urls`, never in `routes`.
5011
+ - `routes` only on the one `approved` answer carrying the one-shot token. Never on `pending` / `rejected` / `unknown`, `/api/pair/challenge`, or TXT.
5012
+ - Receiver validates (`validateDeliveredRoutes`): `https`, origin only, DNS name (no IP literal, `localhost`, `*.local`), ≤ 8 routes, host ≤ 253 chars.
5013
+ - Receiver stores only after challenge at that origin proves pinned `F` (`recordDeliveredRoutes`, `packages/electron/src/lib/delivered-routes.ts`). Source `pairing`.
5014
+ - Browser ignores `routes`: no own store for them. Electron keyring keeps ≤ 3 delivered (`MAX_DELIVERED_STORED`), then 5-host cap, https first.
5015
+
5016
+ Pair action per row (`pairAction`, `packages/shared/src/server-routes.ts`; hook `use-pair-action.ts`):
5017
+
5018
+ - Browser, on-link route: "Request access…" → `window.open("http://<host>:<port>/pair?request", "_blank", "noopener")`. URL via `buildRequestPageUrl`; refused unless it round-trips. No fp check (Electron only).
5019
+ - Browser, otherwise: "Pair with code…" → pasted payload; local check payload `id` = entry `F`; new tab `<https origin>/pair#<payload>`. Landing runs `challengeIdentity` before redeem.
5020
+ - Electron, no `F`, on-link route discovered: "Verify and request access…" (TOFU compare).
5021
+ - Electron, on-link route discovered or in keyring: "Request access…" → `piDashboard.openServerWindow({host, port})`. Connecting window proves identity first.
5022
+ - Otherwise: "Pair with code…".
5023
+ - Knock refusals: `knock_disabled` → remedy text; `knock_not_lan` → "Pair with code instead"; `knock_pending`, `knock_busy` unchanged.
5024
+
5025
+ Electron bridges (main window only, local-origin gate):
5026
+
5027
+ - `piDashboard.listServers()` → `servers:list`. Renderer-safe state (`pairedRow`, `discovered`); no bearer.
5028
+ - `piDashboard.pairWithCode({fingerprint})` → `servers:pair-with-code` → `serverWindows.pairWithCode(fp)` → Connecting window code mode. Pasted text travels only on `servers:submit-code` from the connecting window.
5029
+ - In-app redeem (`packages/electron/src/lib/pairing-code-client.ts`): decode; payload `F` ≠ pin → no request; prove first payload `https` URL that proves pin; `POST /api/pair/redeem`; poll for approval (compare code shown in Connecting window only); bearer → keyring (`safeStorage` rules); routes validated + proven.
5030
+ - Pasted text, pairing code, bearer never reach dashboard page or logs.
5031
+
3946
5032
  #### Bearer device auth — D5/D7
3947
5033
 
3948
5034
  Approval mints long-lived opaque bearer token. Registry `~/.pi/dashboard/paired-devices.json` (0600). Stores only SHA-256 hash. Revoke = row delete (Settings → Security → Paired Devices). Auth branch: `Authorization: Bearer` (REST) feeds existing `request.isAuthenticated` — one OR branch, registered before OAuth plugin. Modules `paired-devices.ts`, `bearer-auth.ts`.
@@ -3959,7 +5045,7 @@ Windows credential ACLs now OBSERVED, not assumed. `chmod` no-op on Windows —
3959
5045
 
3960
5046
  #### CORS default
3961
5047
 
3962
- `https://pi-dashboard.dev` built-in allowed origin, beside `*.share.zrok.io`. CORS (origin-keyed) distinct from auth (bearer). Config `cors.allowedOrigins` extends.
5048
+ `https://pi-dashboard.dev` built-in allowed origin. CORS (origin-keyed) distinct from auth (bearer). Config `cors.allowedOrigins` extends. zrok wildcard NOT default — opt-in `cors.allowZrokWildcard`. See § CORS. See change: harden-cors-and-csp-reporting.
3963
5049
 
3964
5050
  #### Versioned protocol — D9
3965
5051
 
@@ -3977,6 +5063,49 @@ Approval: operator types numeric confirm code shown on device → `POST /api/pai
3977
5063
 
3978
5064
  Gate: `reachableUrls()` (`packages/server/src/pairing.ts`) read-time filter (D4/D14) advertises only secure `wss`/`https` endpoints. Keeps `urls[]` secure. `createPayload()` returns null when no reachable url → route returns `{success:false,error:"no_reachable_endpoint"}` (HTTP 200).
3979
5065
 
5066
+ ### Device keys and the mutual device check (change: device-key-mutual-check)
5067
+
5068
+ Paired device proves possession of its own key. One key per server fingerprint. Check is mutual: device proves the server first, signs second.
5069
+
5070
+ ```mermaid
5071
+ sequenceDiagram
5072
+ participant C as Client
5073
+ participant S as Server (route)
5074
+ C->>S: POST /api/pair/challenge {nonce}
5075
+ S-->>C: {fingerprint, publicKey, signature, deviceNonce}
5076
+ Note over C: verify signature + fingerprint vs pin or advert
5077
+ alt route not proven
5078
+ Note over C: stop — no proof to this route
5079
+ else route proven
5080
+ C->>S: POST /api/pair/device-status {deviceNonce, pub, sig}
5081
+ S-->>C: {status: paired|expired|unknown|revoked, tier?, scope?}
5082
+ end
5083
+ Note over S: any failure → {status:"unverified"} at HTTP 200
5084
+ ```
5085
+
5086
+ - Step 1 — `POST /api/pair/challenge {nonce}` reply gains `deviceNonce`: 32 random bytes, base64url (43 chars). Store single-use, 60 s TTL, bound 10 000 entries, oldest evicted. Carries no secret.
5087
+ - Client verifies step 1 against pin or advertised fingerprint FIRST. Unproven route → stop, no proof sent.
5088
+ - Step 2 — `POST /api/pair/device-status {deviceNonce, pub, sig}`. `sig` = Ed25519 over `pi-devcheck/v2\n<fp>\n<deviceNonce>`. `pub` = raw 32-byte key, unpadded base64url (43), not SPKI; `sig` 64 bytes (86). Charset + length checked before decode. Nonce consumed on first presentation, so no client timestamp.
5089
+ - Reply `{status: paired|expired|unknown|revoked, tier?, scope?}`. Full paired key → `tier` + `scope:"full"`. Companion → `scope:"status-only"`, no tier. `expired` / `revoked` → neither. `revoked` decided first, wins over `expired`.
5090
+ - `expired` reuses the per-row judgement that refuses a bearer `401 bearer_expired` (`currentVerdict`, `packages/server/src/pairing/paired-devices.ts`), never a copy of the expiry arithmetic.
5091
+ - Every failure — bad signature, malformed field, unknown / expired / consumed nonce, rate-limited peer — answers `{status:"unverified"}` at HTTP 200. Discloses only the caller's own key status.
5092
+ - Limit 60/min per peer address, sliding window, invalid attempts counted. Limiter map bound 1024 peers, oldest evicted. Step 1 never limited.
5093
+ - Route public (`PUBLIC_PAIRING_PREFIXES`), tier `observe` like the challenge. Not a prefix of `/api/pair/device-key` — auth hook matches `startsWith`.
5094
+ - Proof, key bind, keyed knock go ONLY to the route that proved the pin in that selection. Electron `http:` route → the address literal that proved it, never the host name or a sibling literal. `https:` → proven host name.
5095
+ - Key per fingerprint: browser `packages/client/src/lib/pairing/device-key.ts` — non-extractable WebCrypto key in IndexedDB, secure contexts only. Electron main `packages/electron/src/lib/device-key.ts`, private part under `safeStorage` (`server-keyring.ts`). Shell `packages/shell/src/lib/device-key.ts` — IndexedDB.
5096
+ - Created only when pairing starts (Request access, Pair with code, Pair again). Listing creates nothing.
5097
+ - Registered at approval: knock / redeem body carries `deviceKey: {deviceNonce, pub, sig}`, `sig` over `pi-devbind/v1`. Held on `PendingDevice`, passed to `registry.add` — deny / expiry / lockout leaves nothing behind.
5098
+ - Later bind: `POST /api/pair/device-key {deviceNonce, pub, sig}` with the device's own credential (`authVia === "device"`). `400` bad proof, `401` no credential, `409` key held by another row, tier `observe`. One primary key per row; replaces the old one.
5099
+ - Uniqueness: one public key across primary + companion keys of active and revoked rows. Duplicate at approval → pairing proceeds keyless; duplicate at bind → `409`.
5100
+ - Companion key: `#companion=<pub>.<ts>.<sig>&from=<origin>` fragment, `sig` over `pi-companion/v1`, `ts` ±300 s. Status-only, accepted nowhere else. Opt-in, unticked at approval, max 4 per device.
5101
+ - Revoke is a state. Whole row (hash, tier, keys, companions, expiry fields) moves to `~/.pi/dashboard/revoked-devices.json` (0600) plus `revokedAt` / `revokedBy`. Revoked written FIRST, then active removed; id in both files → revoked wins.
5102
+ - Undo restores hash, tier, keys, companions, expiry fields unchanged — never extends expiry, never restarts the grace window. Purge at 90 d (`REVOKED_RETENTION_MS`) or Delete now.
5103
+ - Unreadable revoked file → set aside as `revoked-devices.corrupt-<time>.json`, empty list, `warning` on `GET /api/paired-devices/revoked`.
5104
+ - `registry.onRevoked(listener)` → browser gateway + pi gateway close matching sockets, code `4401`, reason `device revoked`. `verify()` scans active rows only, so REST, device-session, ws-ticket, bridge mint need no change.
5105
+ - Rollback-safe: older builds ignore the second file, degrade to "revoke = delete". Only Undo is lost.
5106
+ - Discard rule: no device-status answer discards anything — `unknown`, `expired`, `revoked` all keep credential and key. Only a refused credential at a proven route (`401`, incl. `401 bearer_expired`; refused cookie exchange) discards credential + key together.
5107
+ - Shared helpers: `packages/shared/src/device-key-proof.ts` — message builders, validators, `deviceRowState`. Server verifier `packages/server/src/auth/device-proof.ts`.
5108
+
3980
5109
  ### Built-in TLS listener (change: add-tailscale-cert-tls)
3981
5110
 
3982
5111
  Optional second `https.Server`. Off by default (`tls.enabled: false`). Serves the SAME Fastify app as the main listener.
@@ -4216,6 +5345,23 @@ The web client includes a Settings panel (gear icon in sidebar header → `/sett
4216
5345
  4. Server preserves `***` secrets (doesn't overwrite real values), writes to disk, and applies runtime-safe changes
4217
5346
  5. Port/piPort changes flag `restartRequired` in the response
4218
5347
 
5348
+ ### Sidebar header grouping
5349
+ - Header = Tailwind `@container`. Row 1 `flex-wrap` (wraps, never clips).
5350
+ - Icon buttons (Discord, Appearance, Focus, Settings, row-2 filter funnel) share one recipe: HEADER_ICON_BTN + HEADER_ICON_SIZE in packages/client/src/components/primitives/header-icon-button.ts. 28 px box (size-7 rounded-md), 18 px glyph, --text-secondary, --bg-hover fill on hover/aria-expanded, selected-chip look on aria-pressed. Core-only. Named exceptions in ui-contract.md row "icon button (header)".
5351
+ - Row 1 left: logo · Discord (`discord-btn`) · divider · Appearance (`ThemePicker`, `theme-picker-trigger`) · Focus (`focus-toggle-btn`).
5352
+ - Appearance dropdown: trigger glyph mdiBrightness6. 300 px @container panel (usePopoverFlip clamps to viewport). "Mode" heading + segmented ThemeToggle (icon + label Light/System/Dark). "Palette" heading + scrolling grid-cols-2 palette grid (theme-palette-grid; 1 column when panel < 254 px). Active palette = aria-pressed + selected-chip fill, no check glyph. Only the grid scrolls on short viewport.
5353
+ - Row 1 right: open-questions pill (`QuestionStack`) · update badge · connection chip (`connection-chip`, `ServerSelector`) · Settings (`settings-btn`).
5354
+ - Electron RuntimeUpdateBadge glyph-only in header; version in title/aria-label.
5355
+ - Connection chip: server-kind glyph (connection-chip-glyph; mdiLaptop local, mdiServerNetwork remote; offline = mdiLaptopOff / mdiServerNetworkOff form in --accent-red-text, carries connection-chip-offline-glyph) with aria-hidden top-right status dot badge · server name (max-w-24, max-w-40 from header container 480 px; hidden < 400 px) · offline word (>= 480 px) · remote-access tone glyph (internet/partial/failed) · waiting-device badge (tunnel-btn-badge) · chevron (hidden < 400 px). Collapsed chip 32 px. Kind from currentServerKind(entry, host) in ServerSelector.tsx. title = "{server}: switch server".
5356
+ - Chip menu: servers · "Manage servers…" · Access group.
5357
+ - Access group: Remote access (`tunnel-btn`, opens `RemoteAccessDialog`) · Install as app (`install-btn`, only when installable).
5358
+ - `useRemoteAccessIndicator` (hooks): tunnel-status poll, reachability, pending-pairing count, saved-run resume. Called once in `App.tsx`.
5359
+ - `App` hosts lazy `RemoteAccessDialog`.
5360
+ - `TunnelButton` and `InstallButton` deleted.
5361
+ - Row 2: one scoped search box. Scope toggle Sessions|Folders. Inactive query = chip with switch + clear buttons.
5362
+ - Filter funnel (`filter-funnel-btn`) opens popover. Badge counts Include archive + Show hidden.
5363
+ - Layout floors: common state (quiet remote access, update count < 10) one line at >= 280 px sidebar. With tunnel on or 2-digit count, right group wraps at ~280-300 px, never clips. Worst state, short server name, one line at >= 400 px.
5364
+
4219
5365
  ### Reconnection Flow
4220
5366
  1. Browser reconnects with `subscribe` message including `lastSeq`
4221
5367
  2. Server compacts the in-memory window via `compactEventsForReplay`, then replays missed events in async batches of 200 (`REPLAY_BATCH_SIZE`) with backpressure handling
@@ -4337,10 +5483,10 @@ See change: `lazy-load-session-history`, `add-tail-only-replay-window`.
4337
5483
  ### Bridge Reconnection (State Reset)
4338
5484
  When a bridge extension reconnects (e.g., after `pnpm run reload` or network recovery):
4339
5485
  1. Bridge sends `session_register` with `eventCount` to re-register the session
4340
- 2. Server checks `canSkipWipe`: if the bridge's `eventCount` matches the server's `lastEntryCount` and events exist in the store, the wipe is skipped (fast reconnect path)
4341
- 3. **Full replay path** (`canSkipWipe = false`): Server clears the in-memory event store, broadcasts `session_state_reset` to browsers, stores replayed events, and sends them as `event_replay` batch after `replay_complete`
4342
- 4. **Skip replay path** (`canSkipWipe = true`): Server keeps existing events in the store, marks the session in `skipReplayInsert` set so replayed events are NOT re-inserted (preventing exponential duplication). Status updates are still processed for session state accuracy. After `replay_complete`, the `event_replay` batch is skipped since browsers already have the events.
4343
- 5. Bridge replays full session history as individual `event_forward` messages
5486
+ 2. Server checks skip-wipe fingerprint (see Event Broadcast During Replay): `eventCount` + `leafEntryId` match, store intact → wipe skipped (fast reconnect path). Old bridge (no leaf) always wipes.
5487
+ 3. **Full replay path** (wipe): Server clears the in-memory event store, broadcasts `session_state_reset` to browsers, stores replayed events, and sends them as `event_replay` batch after `replay_complete`
5488
+ 4. **Skip replay path** (no wipe): Server keeps existing events in the store. Replayed marked events are NOT inserted (preventing exponential duplication). Status updates are still processed for session state accuracy. After `replay_complete`, the `event_replay` batch is skipped since browsers already have the events.
5489
+ 5. Bridge replays full session history as individual `event_forward` messages, each marked `replay: true`
4344
5490
  6. Bridge sends `replay_complete` to signal replay is done
4345
5491
  7. If the agent is currently mid-turn (bridge tracks `isAgentStreaming` flag in persistent `BridgeState`), a synthetic `agent_start` event is sent after `replay_complete` so the session card shows "Thinking…" instead of "Waiting for input"
4346
5492
  8. Server clears the replaying flag, broadcasts the final accumulated session status
@@ -4348,7 +5494,7 @@ When a bridge extension reconnects (e.g., after `pnpm run reload` or network rec
4348
5494
 
4349
5495
  Without the `session_state_reset` message (full replay path), replayed events would duplicate existing messages in the browser's accumulated state.
4350
5496
 
4351
- **Replay status suppression**: During step 5, replayed events like `agent_start`/`agent_end` would normally trigger rapid `session_updated` broadcasts (e.g., `status: "streaming"` → `status: "idle"` for each turn), causing visible flicker on session cards. The server suppresses these status broadcasts while replaying, accumulating them in the session manager. Only the final status is broadcast after `replay_complete`. A 5-second safety timeout ensures the flag is cleared even if `replay_complete` never arrives (e.g., older bridge versions).
5497
+ **Replay status suppression**: During step 5, replayed events like `agent_start`/`agent_end` would normally trigger rapid `session_updated` broadcasts (e.g., `status: "streaming"` → `status: "idle"` for each turn), causing visible flicker on session cards. The server suppresses these status broadcasts while replaying, accumulating them in the session manager. Only the final status is broadcast after `replay_complete`. Fallback for unmarked (older) bridges: idle exit after 5s with no bridge message, or cap exit after 60s (see Event Broadcast During Replay). `replay_complete` never arriving no longer leaves the flag set.
4352
5498
 
4353
5499
  **Agent streaming state recovery**: The bridge tracks `isAgentStreaming` in process-level `BridgeState` (survives reload). Set `true` on `agent_start`, `false` on `agent_end`/`session_shutdown`. Since the replay doesn't include `agent_start`/`agent_end` events, the session status would otherwise stay "active" (displayed as "Waiting for input") when the agent is mid-turn during reconnect.
4354
5500
 
@@ -4575,11 +5721,87 @@ When a browser subscribes to a session whose events have been evicted from memor
4575
5721
  5. If the session file is missing or corrupt, server sends `dataUnavailable: true`
4576
5722
  6. Concurrent loads for the same session are deduplicated
4577
5723
 
4578
- ### Flows Refresh Deduplication
4579
- When a session sends `flows_list`, the server notifies other sessions in the same cwd to rediscover flows. To prevent infinite loops (A→refresh B→B sends flows→refresh A→...), a per-session 5-second cooldown (`recentFlowsRefresh` set) suppresses duplicate refresh requests.
5724
+ ### Flow Catalog Refresh (replaces Flows Refresh Deduplication)
5725
+ `flows_list` and `request_flows_refresh` removed. Catalog refresh runs through plugin channel `dashboard-flows:catalog` (see Plugin-declared event forwarding). Sibling rediscover ask fires only when a known catalog changes. Former `recentFlowsRefresh` 5 s cooldown no longer exists.
5726
+
5727
+ ### Event Broadcast During Replay (change: fix-large-session-resume-replay, #928/#929)
5728
+
5729
+ **Replay marking (bridge).**
5730
+ - Bridge sets `replay: true` on every replayed `event_forward`. Sites: `replaySessionEntries` (`packages/extension/src/session-sync.ts`); ACP event-log replay (`packages/server/src/acp-bridge/acp-session-adapter.ts`).
5731
+ - Live forwards never marked.
5732
+ - Field optional: `EventForwardMessage.replay?: true` (`packages/shared/src/protocol.ts`). Old server ignores it.
5733
+
5734
+ **Classification (server).** `isReplayedForward(sessionId, msg)` in `packages/server/src/event-wiring.ts`:
5735
+ `msg.replay === true || replayingSessions.has(sessionId)`.
5736
+ - Marked event never live: no broadcast, unread, push, `lastActivityAt`, card order, OpenSpec detection.
5737
+ - Marked event after exit → controller `reopen` → next exit flushes it.
5738
+ - Skipped replay: marked events never inserted until next register.
5739
+
5740
+ **Replay mode owner.** `packages/server/src/session/replay-exit-controller.ts`, one per session.
5741
+ - API: `begin`, `touch`, `reopen`, `complete`, `release`.
5742
+ - State: flush epoch, `flushPending`, waiter registry.
5743
+
5744
+ ```mermaid
5745
+ stateDiagram-v2
5746
+ [*] --> Replaying: session_register (begin)
5747
+ Replaying --> Exit: replay_complete (complete)
5748
+ Replaying --> Exit: 5s idle, unmarked bridge (idle)
5749
+ Replaying --> Exit: 60s cap, unmarked bridge (cap)
5750
+ Replaying --> Exit: unregister
5751
+ Exit --> Flush: flushPending
5752
+ Flush --> [*]: isLast true
5753
+ Exit --> [*]: no pending flush
5754
+ ```
4580
5755
 
4581
- ### Event Broadcast During Replay
4582
- During bridge session replay (while `replayingSessions` set contains the session), `event_forward` messages are stored but NOT broadcast individually to browser subscribers. Instead, when `replay_complete` arrives (or the 5s safety timeout fires), the server sends all accumulated events as a single `event_replay` batch to subscribers. This prevents per-event serialization overhead during replay while still delivering the full history to browsers.
5756
+ **Fallback exits (unmarked old bridges only).**
5757
+ - `idle`: no processed bridge message of any type for `REPLAY_IDLE_MS` (5000).
5758
+ - `idle` re-check runs via one `setImmediate`, so queued input handled first. Busy server does not force idle exit.
5759
+ - `cap`: `REPLAY_CAP_MS` (60000) after register.
5760
+ - One timer set per session. Each new register cancels old set.
5761
+ - Test seam: `createServer({ replayTimings: { idleMs, capMs, keepaliveMs } })`.
5762
+
5763
+ **Exit (`exitReplay(sessionId, cause)`).** Single implementation.
5764
+ - Causes: `complete | idle | cap | unregister`.
5765
+ - Log: `[replay] exit <id> cause=<cause>`. `warn` level for `idle` / `cap`.
5766
+ - Work, fixed order:
5767
+ 1. clear OpenSpec phase/change.
5768
+ 2. reconcile + recompute prompts (not on `unregister`).
5769
+ 3. one `session_updated` broadcast.
5770
+ 4. windowed flush when `flushPending`.
5771
+ - Late `replay_complete` after `idle` / `cap` exit = no-op.
5772
+
5773
+ **Pending proposal.**
5774
+ - Bridge replay neither raises nor clears `pendingReplaceProposal`.
5775
+ - `register()` carries `pendingReplaceProposal` + `rejectedReplaceProposals` across re-register (`packages/server/src/session/memory-session-manager.ts`).
5776
+
5777
+ **Windowed abortable flush.** `BrowserGateway.replayStoreToSubscribers(sessionId, isStale)` (`packages/server/src/pairing/browser-gateway.ts`). Per WebSocket subscriber:
5778
+ - Exactly one `session_state_reset`.
5779
+ - Store windowed like subscribe-time full replay: `sendEventBatches` with `maxReplayEvents`, `history_window` when window applies.
5780
+ - Ends `isLast: true`. Empty store → terminal empty batch.
5781
+ - In-process subscribers: one full `event_replay`.
5782
+ - `isStale` polled before each batch. Re-register / unregister → flush stops, socket unmuted, no catch-up.
5783
+ - `flushPending` stays set until flush completes → next exit sends full flush even after skipped register.
5784
+
5785
+ **Skip-wipe fingerprint.**
5786
+ - `session_register` (`SessionRegisterMessage`) carries `eventCount`, optional `leafEntryId`, `liveTailOpen`.
5787
+ - Skip wipe only when `leafEntryId` valid (string, 1–128 chars) AND one of:
5788
+ - bridge-learned: `eventCount` + leaf match previous register.
5789
+ - hydration-learned: cold hydration recorded `{entryCount, leafEntryId, storeMaxSeq}` (`packages/server/src/session/hydration-state.ts`); needs `liveTailOpen === false` and unchanged store.
5790
+ - Old bridge (no leaf) always wipes.
5791
+ - Log: `[replay] register <id> skipWipe=<bool> reason=<...>`.
5792
+ - `LoadResult` carries `entryCount` + `leafEntryId` (`session-load-worker.ts`, `directory-service.ts`).
5793
+
5794
+ **Register supersedes cold hydration.**
5795
+ - `session_register` bumps per-session generation (`hydration-state.ts`) → calls `directoryService.cancelLoad`.
5796
+ - Subscription handler drops hydration result whose generation changed before insert; stops its fan-out.
5797
+ - Subscribe during bridge replay, store empty: no cold load (works without `sessionFile`).
5798
+ - Immediate `event_replay{events:[],isLast:false}`.
5799
+ - Keepalive every `keepaliveMs` (10000 default) until exit flush.
5800
+ - Keepalive stops before terminal batch.
5801
+
5802
+ **Mixed versions.**
5803
+ - New server + old bridge: timer fallback + full wipe.
5804
+ - Old server + new bridge: extra fields ignored.
4583
5805
 
4584
5806
  ### Per-message entry id stamping (live vs replay)
4585
5807
 
@@ -4625,6 +5847,69 @@ flowchart LR
4625
5847
  List --> Fold["Archive (N) fold"]
4626
5848
  ```
4627
5849
 
5850
+ ## Mid-turn prompt queue (steer + follow-up)
5851
+
5852
+ - Follow-ups: bridge-owned `bridgeFollowUp` (`packages/extension/src/followup-buffer.ts`).
5853
+ - pi never sees held follow-ups until `drainOneFollowup` (`followup-drain.ts`) ships one per `agent_settled` as fresh prompt.
5854
+ - Steers: bridge holds dashboard steers sent while streaming in `inst.bridgeSteer` (`packages/extension/src/steer-buffer.ts`, `createSteerBuffer(instanceNonce)`).
5855
+ - Steer ids `<nonce>:<seq>`; entries `{id,text,images?,promptId?}`.
5856
+ - Steer buffer: cap 20 + byte ceiling 32 MiB, same as follow-ups, accounted independently.
5857
+ - `admitSteer` validates images. Refusal → `command_feedback` for `send_prompt`.
5858
+ - Routing (`command-handler.ts` passthrough + `bridge.ts` `sessionPrompt` fallback):
5859
+ - flags `bufferFollowUp` / `bufferSteer`.
5860
+ - streaming steer → steer buffer, no pi call, `prompt_received` ack without `promptId`.
5861
+ - idle steer → direct `pi.sendUserMessage`.
5862
+ - Hand-off: `handOffHeldSteers` (`bridge-handlers/lifecycle.ts`) runs inside awaited `turn_end` handler, `outcome === "completed"` only.
5863
+ - pi awaits extension `turn_end` handlers before `getSteeringMessages()` (`pi-agent-core` `agent-loop.js`).
5864
+ - Hand-off takes oldest (`steeringMode` `"one-at-a-time"`, default) or all (`"all"`).
5865
+ - Hand-off removes entries + emits `queue_update` synchronously BEFORE sends.
5866
+ - Hand-off per entry: `pi.sendUserMessage(content,{deliverAs:"steer"})` → `prompt_received{fresh:false,promptId}` → one macrotask yield.
5867
+ - After hand-off: not cancellable. Bubble gone. pi renders user message.
5868
+ - Settle drain: `drainOneFollowup` ships oldest held steer BEFORE follow-ups, one per `agent_settled`, same gates, acks `promptId`.
5869
+ - Settle drain covers steer after last turn and aborted/error runs.
5870
+ - Cancel: browser → server → bridge `remove_steering_entry{sessionId,id}` / `clear_steering_entries{sessionId}`.
5871
+ - Cancel handlers: `bridge-handlers/dispatch.ts`. No pi call.
5872
+ - Unknown id → `command_feedback` "Steer already sent or cancelled".
5873
+ - Server relay: `session-action-handler.ts` `handleRemoveSteeringEntry` / `handleClearSteeringEntries`.
5874
+ - ACP sessions ignore cancel (`acp-bridge/server-requests.ts`).
5875
+ - `clear_steering_queue` stays deleted (pi exposes no queue removal).
5876
+ - Wire: `queue_update.steering` / `pendingQueues.steering` = `(SteerEntryView | string)[]`.
5877
+ - `SteerEntryView{id,text,imageCount}`.
5878
+ - Plain strings = legacy bridges (one release), no cancel.
5879
+ - `message_start` matcher touches follow-ups only.
5880
+ - Re-announce `queue_update` (empty included) on:
5881
+ - register: `lifecycle.ts`, after `sessionReady = true`.
5882
+ - re-register: `bridge.ts` `onReconnect`, after `sendStateSync`.
5883
+ - Trade-off: held steers live in bridge memory. Bridge reload mid-turn drops them.
5884
+ - Client: `PendingSteerCard.tsx`.
5885
+ - ✕ `pending-steer-cancel-<id>`.
5886
+ - image badge.
5887
+ - `PendingSteerClearAll` from 2 entries.
5888
+ - no confirmation.
5889
+
5890
+ ```mermaid
5891
+ sequenceDiagram
5892
+ participant D as Dashboard
5893
+ participant S as Server
5894
+ participant B as Bridge
5895
+ participant P as pi
5896
+ D->>S: send_prompt (streaming, steer)
5897
+ S->>B: send_prompt
5898
+ B->>B: held in inst.bridgeSteer (cancellable)
5899
+ B-->>S: prompt_received (no promptId)
5900
+ B-->>S: queue_update
5901
+ Note over B,P: turn_end (outcome completed)
5902
+ B->>B: handOffHeldSteers: remove + queue_update
5903
+ B->>P: sendUserMessage(deliverAs steer)
5904
+ B-->>S: prompt_received{fresh:false,promptId}
5905
+ Note over B: cancel path
5906
+ D->>S: remove_steering_entry{id}
5907
+ S->>B: remove_steering_entry{sessionId,id}
5908
+ B->>B: drop entry (no pi call)
5909
+ B-->>S: queue_update
5910
+ S-->>D: queue_update
5911
+ ```
5912
+
4628
5913
  ## Persistence
4629
5914
 
4630
5915
  | Data | Storage | Details |
@@ -4799,7 +6084,7 @@ The client can connect/disconnect the tunnel via `POST /api/tunnel-connect` and
4799
6084
 
4800
6085
  **Reserved/persistent URLs (v2 namespaces+names).** Config keys `tunnel.zrok.reservedName` + `tunnel.zrok.persistent` (default false). Mint name: `zrok2 create name -n public <name>` (reuse-on-exists for same account; taken-by-other → warn + ephemeral). Share: `zrok2 share public --headless -n public:<name> localhost:<port>` → stable `<name>.shares.zrok.io`. Release: `zrok2 delete name <name>` invoked only by explicit forget (see below). Reserved name SURVIVES disconnect/restart; released ONLY by `POST /api/tunnel-disconnect {forget:true}`. Ephemeral (no name, default persistent=false) yields rotating `*.shares.zrok.io` URL. Legacy v1 `tunnel.reservedToken` preserved on read (downgrade) but IGNORED by v2 provider — never promoted to reservedName.
4801
6086
 
4802
- **URL format + CORS.** v2 emits bare `<t>.shares.zrok.io` (plural, no scheme); provider prepends `https://`. urlRegex anchored so `*.shares.zrok.io.attacker.com` NOT matched as zrok host. CORS allows `*.shares.zrok.io`.
6087
+ **URL format + CORS.** v2 emits bare `<t>.shares.zrok.io` (plural, no scheme); provider prepends `https://`. urlRegex anchored so `*.shares.zrok.io.attacker.com` NOT matched as zrok host. CORS allows the live dashboard tunnel origin always; `*.shares.zrok.io` wildcard only with opt-in `cors.allowZrokWildcard: true` (see § CORS).
4803
6088
 
4804
6089
  **Doctor + version check.** "zrok API reachable" probes `api-v2.zrok.io` (or enrolled env `api_endpoint`). NEW check "zrok version compatible" warns when major < 2 (v1 = 0.4.x) — real root-cause detector for field 500s.
4805
6090
 
@@ -4830,8 +6115,19 @@ The Fastify CORS callback in `server.ts` allows:
4830
6115
  - Same-origin navigations (no `Origin` header).
4831
6116
  - `localhost`, `127.0.0.1`, `[::1]` on any port.
4832
6117
  - The currently-active zrok tunnel URL (looked up dynamically via `getTunnelUrl()` so URL rotation picks up without a restart).
4833
- - Any `*.share.zrok.io` host (covers stale tabs, new reservations, and the brief window before `activeTunnelUrl` is populated on startup).
6118
+ - Every live tunnel origin (`getLiveTunnelOrigins()`, any provider; includes the live zrok URL).
6119
+ - Any `*.share.zrok.io` / `*.shares.zrok.io` host — **opt-in only**, `cors.allowZrokWildcard: true`. Default `false`.
6120
+ - Neutral shell `https://pi-dashboard.dev`.
4834
6121
  - Explicitly-configured `corsAllowedOrigins` from config.
6122
+ - Origin host in a trusted network.
6123
+
6124
+ **Zrok wildcard is opt-in.** `cors.allowZrokWildcard` — boolean, only literal `true` enables (parser: `=== true`; default `false`; `packages/shared/src/config.ts`). Read live via `liveCorsAllowZrokWildcard()` (`config-snapshot.ts`) through `corsOpts()`. Branch test in `classifyCorsOrigin` is `allowZrokWildcard === true`. Live dashboard tunnel always allowed via branches 4 / 4b, never via wildcard. Admission (WS + REST gate) never consults the wildcard. Reason: zrok shares free + self-service; stranger share is likely same-site to victim tunnel.
6125
+
6126
+ **Canonical compare.** `canonicalOrigin(raw)` in `auth/cors-origin.ts`: lowercase scheme + host, default port elided, ONE trailing hostname dot stripped, path/query dropped. Returns `null` for padded input, control chars, non-http(s), bad port. Used on both sides of the tunnel branches (4, 4b) and in `isSameOriginByHost`. `https://X.share.zrok.io.` equals dotless form — matches host admission. Padded / control-char origins denied. Throwing `getTunnelUrl` / `getLiveTunnelOrigins` getters = no live tunnels (never a 500). Live reload parity: `cors.allowZrokWildcard` and `cors.allowedOrigins` both applied on edit, no restart.
6127
+
6128
+ **Stale second zrok frontend.** Page on zrok A calling server on zrok B loses CORS after upgrade. Escape hatch: set `cors.allowZrokWildcard: true` in `~/.pi/dashboard/config.json`. Rollback = same key.
6129
+
6130
+ See change: harden-cors-and-csp-reporting (D6, D7).
4835
6131
 
4836
6132
  On a mismatch the callback returns `cb(null, false)` — **not** `cb(new Error(…), false)`. The `Error` form causes `@fastify/cors` to surface the error as HTTP 500 on every asset response, which is exactly what caused the long-running “zrok returns 500 on assets” debugging saga: Vite emits `<script type="module" crossorigin>` entry tags, which per HTML spec browsers always fetch in CORS mode (even same-origin), so the tunnel URL appearing in `Origin` is unavoidable. Returning `cb(null, false)` simply omits CORS headers; the browser enforces same-origin policy on its own. CORS answers READ-authority only (may this origin see the response); ADMISSION — may this origin open a socket or mutate state — is decided by the next subsection.
4837
6133
 
@@ -4842,7 +6138,7 @@ Issue #625. CORS hides a response, never blocks the request. Gate blocks the act
4842
6138
  **Shared decision** — `packages/server/src/auth/cors-origin.ts`, `isOriginAdmitted(origin, hostHeader, opts)` = `isCorsOriginAllowed` plus 2 deltas.
4843
6139
 
4844
6140
  - Delta 1, Host match: Origin `host[:port]` equals request `Host` → admit. Both normalized with `new URL()`; origin scheme applied to Host so default ports elide. Covers mDNS `http://mac.local:8000` + plain-LAN pages. `isBypassedHost` matches IP literals only; without this rule hostname-addressed clients 403.
4845
- - Delta 2, no zrok wildcard: `isCorsOriginAllowed` gains `allowZrokWildcard` — default `true` for CORS, `false` for admission. `*.share.zrok.io` / `*.shares.zrok.io` skipped for admission. Zrok shares are free + self-service, so a stranger share is likely same-site to the victim tunnel. Dashboard-run tunnels are live tunnel origins, still admitted.
6141
+ - Delta 2, no zrok wildcard: `isCorsOriginAllowed` gains `allowZrokWildcard` — default `false` for CORS (opt-in config `cors.allowZrokWildcard`) and always `false` for admission. `*.share.zrok.io` / `*.shares.zrok.io` skipped for admission. Zrok shares are free + self-service, so a stranger share is likely same-site to the victim tunnel. Dashboard-run tunnels are live tunnel origins, still admitted.
4846
6142
  - Absent `Origin` → admit. Bridge, `pi-dashboard` CLI, `curl`, skill send none. Browsers cannot omit it. Empty `""`, whitespace-padded, malformed → deny.
4847
6143
 
4848
6144
  **WebSocket gate** — `server.ts`, `fastify.server.on("upgrade")`, `isWsOriginTrusted(origin, host, scope, corsOpts())`.
@@ -4865,7 +6161,7 @@ Issue #625. CORS hides a response, never blocks the request. Gate blocks the act
4865
6161
 
4866
6162
  **Logs** — `[ws-gate] rejected upgrade origin=… scope=… peer=…`; `[csrf-gate] rejected <method> <path> origin=…`; `[pi-gateway] … browser-origin`. Fields are attacker-controlled; `sanitizeHeaderForLog` strips control chars, caps 256.
4867
6163
 
4868
- **Escape hatch** — a hand-run `zrok share public` (not the dashboard tunnel feature) needs its origin in `cors.allowedOrigins` (`~/.pi/dashboard/config.json`).
6164
+ **Escape hatch** — a hand-run `zrok share public` (not the dashboard tunnel feature) needs its origin in `cors.allowedOrigins` (`~/.pi/dashboard/config.json`). `cors.allowZrokWildcard: true` widens CORS reads only; admission still refuses the wildcard.
4869
6165
 
4870
6166
  ### Host Admission Gate
4871
6167
 
@@ -5049,25 +6345,23 @@ pi extensions + plugin bridges still load under pi's jiti (separate process).
5049
6345
 
5050
6346
  Both server-launch call sites (`packages/server/src/cli.ts` and `packages/extension/src/server-launcher.ts`) capture **both** stdout and stderr into `~/.pi/dashboard/server.log`. The CLI uses `stdio: ["ignore", logFd, logFd]` on its direct `spawn()` call; the bridge uses `spawnDetached({ stdoutFd: logFd, logFd })`. Without this parity, crash diagnostics from jiti / Fastify / ajv-compiler that reach stdout would be invisible via the bridge path while remaining visible via the CLI path. See change: `fix-bridge-autostart-diagnostics`.
5051
6347
 
5052
- #### CJS preload for Fastify (nodejs/node#58515 mitigation)
5053
-
5054
- Every server-spawn call site injects `--require <preload-fastify.cjs>` BEFORE `--import <native-loader>` in the child's argv, as long as the resolver `resolvePreloadFastifyPath()` in `packages/shared/src/platform/preload-fastify.ts` finds the preload file. The order matters: Node processes `--require` before `--import`, so the preload runs through Node's **legacy synchronous CJS loader** (which predates and bypasses the ESM→CJS translator). The preload synchronously `require()`s `@fastify/ajv-compiler/standalone`, `@fastify/ajv-compiler`, and `fastify` — populating `require.cache` with those modules in `kEvaluated` state.
6348
+ #### CJS preload for Fastify (removed)
5055
6349
 
5056
- When the native loader's ESM hook later resolves an `import "fastify"`, Node's translator finds the modules already cached and short-circuits — it never enters the recursive require chain that triggers the `Unexpected module status 3` assertion on Node 22.0.0–22.18.x / 24.1.0–24.2.x.
5057
-
5058
- This is a **race-independent fix**: it doesn't try to close the timing window, it removes the racy code path from the execution trace. All four spawn sites (CLI daemon, bridge auto-start, Electron, restart orchestrator) share the resolver and the same injection pattern. See change: `preload-fastify-cjs`.
6350
+ The `--require preload-fastify.cjs` injection no longer exists. `preload-fastify.cjs` and `resolvePreloadFastifyPath()` are deleted; spawn argv carries no `--require`. The #58515 `Unexpected module status 3` assertion affects Node 22.0.0–22.18.x and 24.1.0–24.2.x only — all below the Node 26 server floor. See change: `raise-node-floor-to-26`.
5059
6351
 
5060
6352
  #### Node-version preflight
5061
6353
 
5062
- Single source of truth: `packages/shared/src/node-version.ts`. Exports `MIN_SUPPORTED_NODE` (`"22.19.0"`), `meetsFloor(version, floor)`, `isAffectedNode(version)`, `isOutOfEnginesRange(version)`, `isUsableNodeVersion(version)`, `isAtOrAboveEnginesCap(version)`. Version predicates live solely here — single module, no platform-split checker.
6354
+ Single source of truth: `packages/shared/src/node-version.ts`. Exports `MIN_SERVER_NODE` (`"26.0.0"`), `MIN_PI_SPAWN_NODE` (`"22.19.0"`), `SERVER_ENGINES_RANGE` (`">=26.0.0 <27"`), `meetsFloor(version, floor)`, `isAffectedNode(version)`, `isOutOfEnginesRange(version)`, `isUsableNodeVersion(version)`, `isAtOrAboveEnginesCap(version)`. Version predicates live solely here — single module, no platform-split checker.
5063
6355
 
5064
- Floor `22.19.0`. Affected ranges: `22.0.0–22.18.x` + `24.1.0–24.2.x` ([nodejs/node#58515](https://github.com/nodejs/node/issues/58515) — ESM loader assertion when Fastify's `@fastify/ajv-compiler` requires CJS modules). Engines cap `<27` bounds the dashboard's tested range; cap excess accepted, flagged.
6356
+ - Server floor `26.0.0`; range `>=26.0.0 <27`. Cap `<27` bounds tested range; cap excess flagged, not refused by the server guard.
6357
+ - `isUsableNodeVersion` = clean semver AND `!isOutOfEnginesRange`. No separate #58515 check.
6358
+ - `isAffectedNode` ([nodejs/node#58515](https://github.com/nodejs/node/issues/58515); `22.0.0–22.18.x` + `24.1.0–24.2.x`) used only by the pi-session spawn-ladder gate. Pi itself keeps `>=22.19.0`.
5065
6359
 
5066
- Startup guard refuses bad Node: `packages/server/src/auth/node-guard.ts` `assertNodeVersionSupported()` runs pre-boot; exits(1) when `isAffectedNode` or `isOutOfEnginesRange` — server never starts (since change `bump-pi-compat-to-0-75`).
6360
+ Startup guard: `packages/server/src/auth/node-guard.ts` `assertNodeVersionSupported()` checks `isOutOfEnginesRange` only; exits(1) on failure. `buildEnginesRangeMessage` prints `Required: >=26.0.0 <27`, `nvm install 26 && nvm use 26`, `brew install node`. Managed hint printed only when `<managedDir>/node/.version` marker meets the range (marker read, no spawn). The former #58515 startup check and `buildNodeUpgradeMessage` are removed.
5067
6361
 
5068
- Consumers: startup guard; Electron `lib/dependency-detector.ts` `isUsableNodeVersion` filter on detected system Node; spawn-runtime gate `evaluateVersionGate` (pi floor + affected-range check per candidate, cap excess passes with `capExceeded`).
6362
+ Consumers: startup guard; Electron `lib/dependency-detector.ts` `detectSystemNode` (accept-set Node 26 only, via `isUsableNodeVersion`); server spawn via `resolveServerRuntime()` (below); pi-session spawn-runtime gate `evaluateVersionGate`.
5069
6363
 
5070
- Root `package.json` declares `"engines": { "node": ">=22.19.0 <27" }`; `packages/server/package.json` `"node": ">=22.19.0"` as npm-level advisories.
6364
+ Root `package.json` declares `"engines": { "node": ">=26.0.0 <27" }`; `packages/server/package.json` `"node": ">=26.0.0"`.
5071
6365
 
5072
6366
  #### Spawn runtime resolution
5073
6367
 
@@ -5080,7 +6374,7 @@ Four rungs, first hit wins:
5080
6374
  3. User Node — login-shell first on Electron arm, PATH first on terminal arms (`npm`/`docker`); then version-manager fs probe (`~/.nvm/alias/default`), no shell.
5081
6375
  4. Managed `<managedDir>/node`; else bundled; else `process.execPath` — terminal rung, never fails.
5082
6376
 
5083
- Gate (`evaluateVersionGate`): pass pi engines floor + not nodejs/node#58515-affected; cap excess (`isAtOrAboveEnginesCap`, `<27`) accepted, flagged `capExceeded`. Floor read from spawned pi copy engines; fallback `MIN_SUPPORTED_NODE`.
6377
+ Gate (`evaluateVersionGate`): pass pi engines floor + not nodejs/node#58515-affected; cap excess (`isAtOrAboveEnginesCap`, `<27`) accepted, flagged `capExceeded`. Floor read from spawned pi copy engines; fallback `MIN_PI_SPAWN_NODE`.
5084
6378
 
5085
6379
  Publication: `runtime.resolved` written to `~/.pi/dashboard/config.json` every server start (`packages/server/src/runtime-publication.ts::publishResolvedRuntime`). Diagnostic-only; override never written. `pi-dashboard runtime` CLI subcommand prints resolved runtime.
5086
6380
 
@@ -5088,6 +6382,59 @@ Spawn-time re-validation (`packages/server/src/runtime-resolution.ts`): boot-tim
5088
6382
 
5089
6383
  Doctor rows: resolved runtime (+ rung/via), ABI mismatch, legacy `~/.pi-dashboard/` dir orphan test. Home split: `~/.pi/dashboard/` = user config + published runtime state; `~/.pi-dashboard/` = machine-managed runtime, managed node_modules, logs.
5090
6384
 
6385
+ #### Server spawn runtime resolution (`resolveServerRuntime`)
6386
+
6387
+ Resolves the Node binary that runs the dashboard **server**. Separate from the pi-session ladder above. Gate = `SERVER_ENGINES_RANGE` (`>=26.0.0 <27`). Source: `packages/shared/src/platform/spawn-runtime.ts`.
6388
+
6389
+ Order, first in-range hit wins:
6390
+
6391
+ 1. `runtime.override` (`~/.pi/dashboard/config.json`).
6392
+ 2. First `node` on PATH.
6393
+ 3. Version-manager defaults: nvm `alias/default`, volta, asdf, mise, fnm.
6394
+ 4. Managed `<managedDir>/node`.
6395
+ 5. Starter's own runtime (`ownRuntime`; version from running process, never probed).
6396
+
6397
+ ```mermaid
6398
+ flowchart TD
6399
+ S([resolveServerRuntime]) --> O{override in range?}
6400
+ O -- yes --> R([resolved])
6401
+ O -- no --> P{PATH node in range?}
6402
+ P -- yes --> R
6403
+ P -- no --> V{version-manager default in range?}
6404
+ V -- yes --> R
6405
+ V -- no --> M{managed node in range?}
6406
+ M -- yes --> R
6407
+ M -- no --> W{own runtime in range?}
6408
+ W -- yes --> R
6409
+ W -- no --> X([resolved false + trail])
6410
+ ```
6411
+
6412
+ Properties:
6413
+
6414
+ - Not total: no match → `{resolved:false, range, trail}`.
6415
+ - No shell ever run. nvm without `alias/default` is not found.
6416
+ - ≤1 `--version` probe per distinct path (`execFile`).
6417
+ - `describeServerRuntimeTrail()` formats trail for logs.
6418
+
6419
+ #### Bridge auto-start runtime + refusal
6420
+
6421
+ Source: `packages/extension/src/server-auto-start.ts`. Inside the single-flight lock:
6422
+
6423
+ - Resolves server Node via `resolveServerRuntime()`. Skipped when dashboard already answers.
6424
+ - Resolved: logs `server runtime: <path> <version> via <step>` (`appendAutoStartLog`); passes `nodeBin` to `launchServer` (`packages/extension/src/server-launcher.ts`).
6425
+ - Unresolved: re-probe port (attach if up, silent). Else logs `[auto-start] refused: no Node satisfying >=26.0.0 <27 ...; candidates: ...` and shows one `ui.notify` warning per session (range, pi's Node version, install Node 26 or desktop app, `~/.pi/dashboard/server.log` path).
6426
+
6427
+ #### Electron server Node pick
6428
+
6429
+ Source: `packages/electron/src/lib/pick-node.ts`. Order:
6430
+
6431
+ 1. Bundled Node (`BUNDLED_NODE_VERSION` v26.13.0; `BUNDLED_NODE_MAJOR` 26).
6432
+ 2. System Node — pre-resolved by `launch-source.ts` via `resolveServerRuntime({ownRuntime:null})`, only when bundled Node missing.
6433
+ 3. Electron executable with `ELECTRON_RUN_AS_NODE=1` — only if embedded Node (`process.versions.node`) in range. Electron 44 embeds 24.22.0 → never qualifies.
6434
+ 4. `unavailable` — `launch-source` throws `pick.reason`; no `launchDashboardServer` call; `requestServerLaunch` → `{kind:"failed"}`.
6435
+
6436
+ Electron dev / localLink launches need Node 26 on PATH or in a version manager.
6437
+
5091
6438
  #### AppImage CLI self-recursion guard (Linux power-user mode)
5092
6439
 
5093
6440
  Electron's power-user launch path (`ensureServer()` → `detectPiDashboardCli()` → `launchViaCli()`) prefers already-installed `pi-dashboard` CLI on PATH. On Linux **AppImage** builds, AppImage runtime prepends its squashfs mount dir (e.g. `/tmp/.mount_PI-Das.../`) to `PATH` of Electron child. Mount contains binary literally named `pi-dashboard` because `forge.config.ts` declares `packagerConfig.executableName: "pi-dashboard"` for branding consistency. Without guard, `which pi-dashboard` returns AppImage's own launcher first; `launchViaCli()` spawns Electron app recursively as if it were dashboard CLI; recursive child silently ignores `start --port 8000`, never opens dashboard port, `waitForReady` polls until 15s deadline expires — user sees indefinite loading screen.
@@ -5132,9 +6479,13 @@ Electron-bound presentation concerns (tray icons, menu template, dock behavior,
5132
6479
 
5133
6480
  ### Windows runtime dependencies (git + bash)
5134
6481
 
5135
- On Windows agent needs `git.exe` + POSIX shell. git backs repo ops; `pi.exec("sh")` backs `!`/`!!` bang commands. macOS/Linux ship both system-wide; Windows-only problem.
6482
+ On Windows agent needs `git.exe` + bash. git backs repo ops. bash backs agent `bash` tool, `!`/`!!` bang commands, `!cmd` config values. Pi resolves bash itself (`getShellConfig()`, pi-coding-agent 1.5.0). Dashboard never calls `pi.exec("sh")`. macOS/Linux ship both system-wide; Windows-only problem.
5136
6483
 
5137
- Installers embed dugite-native (git 2.53.0 + GNU bash as `usr/bin/sh.exe`). Config key `windowsGitSource`: `"auto"`\|`"host"`\|`"bundled"`, default `"auto"`.
6484
+ Shell replica `packages/shared/src/platform/resolve-pi-shell.ts` (names pi 1.5.0). `isWslLauncherBash(p, env)` SystemRoot-aware: launcher = `<SystemRoot>\System32|Sysnative\bash.exe`. Non-drive-absolute SystemRoot → not launcher. Fixed `<drive>:\Windows\…` regex used only when SystemRoot unset. Existence check = `accessSync(F_OK)`.
6485
+
6486
+ Installers embed dugite-native (git 2.53.0.windows.4). Bundle ships GNU bash only as `usr/bin/sh.exe`. Config key `windowsGitSource`: `"auto"`\|`"host"`\|`"bundled"`, default `"auto"`.
6487
+
6488
+ Bundled bash copy: `ensureBundledBashExe` (`packages/electron/scripts/lib/ensure-bundled-bash-exe.mjs`) byte-copies `usr/bin/sh.exe` → `usr/bin/bash.exe`. `sh.exe` kept. Throws if `sh.exe` missing. MSYS bash picks `posix off` from argv[0] `bash` (`posix on` for `sh`). Cost: +~2.5 MB per Windows artifact. See change: fix-windows-bundled-bash-exe.
5138
6489
 
5139
6490
  - `auto` → host when git+bash both on PATH, else bundled (atomic).
5140
6491
  - `host` → host, bundled fallback + Doctor error.
@@ -5142,13 +6493,59 @@ Installers embed dugite-native (git 2.53.0 + GNU bash as `usr/bin/sh.exe`). Conf
5142
6493
 
5143
6494
  `selectGitSource()` decides. Cached process-lifetime (`git-source.ts`); invalidated on `/api/restart` (fresh process) + config-write.
5144
6495
 
5145
- `ensureBundledGitOnPath()` prepends `resources/git/{cmd,usr/bin,<libdir>/bin}` to PATH (after `ensureWindowsSystemPath`, lands before System32). Sets `GIT_EXEC_PATH` + `SSL_CERT_FILE`. `<libdir>` = `mingw64` (x64) / `clangarm64` (arm64).
6496
+ `ensureBundledGitOnPath()` prepends to PATH (after `ensureWindowsSystemPath`, lands before System32). Sets `GIT_EXEC_PATH` + `SSL_CERT_FILE`. `<libdir>` = `mingw64` (x64) / `clangarm64` (arm64).
6497
+
6498
+ - `windowsBashSource: "bundled"` (default) → prepends `resources/git/{cmd,usr/bin,<libdir>/bin}`. pi picks bundled `bash.exe` only if no Git for Windows under `%ProgramFiles%` / `%ProgramFiles(x86)%`.
6499
+ - `windowsBashSource: "host"` → prepends `resources/git/{cmd,<libdir>/bin}`. Appends `usr/bin` LAST. pi picks host's first `bash.exe` on PATH only if no Git for Windows under `%ProgramFiles%` / `%ProgramFiles(x86)%`.
6500
+ - Both modes: installed Git for Windows `bash.exe` in `%ProgramFiles%\Git\bin` wins over PATH (pi step 2 precedes `where bash.exe`). `windowsBashSource` only orders PATH; it does not override that check.
6501
+ - Mode applies only while active git source is bundled. Windows-only.
5146
6502
 
5147
6503
  Hooked into `ToolResolver.buildSpawnEnv` (covers server-launcher + process-manager) and `terminal-manager` PTY env separately (PTY bypasses `buildSpawnEnv`).
5148
6504
 
5149
- Build-time: `download-git-windows.mjs` runs in `bundle-server.mjs`, SHA-256 fail-closed, GO/NO-GO.
6505
+ Build-time: `download-git-windows.mjs` runs in `bundle-server.mjs`, SHA-256 fail-closed, calls `ensureBundledBashExe`. GO/NO-GO in `bundle-server.mjs` + `assert-runnable-bundle.mjs` requires `usr/bin/bash.exe`.
6506
+
6507
+ PATH semantics: bundled entries lead (except `usr/bin` under `windowsBashSource: "host"`). Takes effect for newly spawned sessions only (existing children keep old PATH). No-op on macOS/Linux.
6508
+
6509
+ **Pi bash resolution** (`getShellConfig()`, never `sh.exe`, never `pi.exec("sh")`). Order:
6510
+
6511
+ 1. pi `shellPath` setting (bash tool + `!` only; not `!cmd`).
6512
+ 2. `%ProgramFiles%\Git\bin\bash.exe`, then `%ProgramFiles(x86)%\Git\bin\bash.exe`.
6513
+ 3. First `where bash.exe` hit.
6514
+ 4. Else throw `No bash shell found`.
6515
+
6516
+ First `where` hit `C:\Windows\System32\bash.exe` (WSL launcher):
6517
+
6518
+ - No WSL distro → `no installed distributions` failure.
6519
+ - Distro present → commands run inside Linux.
6520
+
6521
+ Dashboard never writes pi `shellPath`. Git for Windows in `%ProgramFiles%` wins regardless of `windowsBashSource`.
6522
+
6523
+ **`windowsBashSource`** (`"bundled"` default \| `"host"`). Setter `setWindowsBashSourceSetting` (`packages/shared/src/platform/git-source.ts`). Seeded at startup by `seedWindowsSourceSettings()` (`packages/server/src/config-api.ts`). UI: Settings → Sessions → Worktrees → "Bash for agent commands" (beside "Git & Bash source"). PATCH `/api/config` applies live to new sessions/terminals, no restart. Persists.
5150
6524
 
5151
- PATH semantics: bundled entries lead. Takes effect for newly spawned sessions only (existing children keep old PATH). No-op on macOS/Linux.
6525
+ Side effects:
6526
+
6527
+ - `bundled`: every child resolving `bash` by name (pi, dashboard terminal `bash`, `#!/usr/bin/env bash` git hooks) gets bundled bash. WSL-distro users who got WSL bash before now get bundled Windows bash unless `host`.
6528
+ - `host`: MSYS tools in `usr/bin` (`find`, `sort`) shadowed by System32 tools for children. No host `bash.exe` on PATH → falls back to bundled bash. Bundled git still works incl. `#!/bin/sh` hooks.
6529
+
6530
+ **Diagnostics.** `resolvePiShell({env, exists})` (`packages/shared/src/platform/resolve-pi-shell.ts`) replicates pi order over augmented spawn env. `/api/health` `gitSource` = `{ setting, source, gitPath, gitVersion, shellPath, bashSetting, shellIsWslLauncher }` (null on macOS/Linux). `shellPath` = bash pi would resolve, never `sh.exe`.
6531
+
6532
+ Doctor "bash source" row:
6533
+
6534
+ - No shell → warning `doctor.no_posix_shell`.
6535
+ - WSL launcher, `bashSetting` ≠ `host` → warning `doctor.bash_is_wsl_launcher`.
6536
+ - WSL launcher, `host` → ok "requires an installed WSL distro".
6537
+
6538
+ Residuals: process cwd searched first by `where.exe`. User pi `shellPath` wins for bash tool/`!`.
6539
+
6540
+ **Build gate.** `packages/electron/scripts/assert-bundled-bash-resolvable.mjs`, step "Assert pi resolves bundled bash" in `.github/workflows/_electron-build.yml` (win32 full-bundle legs):
6541
+
6542
+ - Loads SHIPPED pi `getShellConfig` + shipped shared helpers.
6543
+ - `ProgramFiles*` → empty dir. Stub host `bash.exe` on PATH.
6544
+ - Bundled mode → expects `usr\bin\bash.exe`. Host mode → expects stub.
6545
+ - Exec checks (`posix off`, git commit through `#!/bin/sh` hook) only when target arch == runner arch. win32-arm64 = resolution-only.
6546
+ - Re-verify on pi version bump.
6547
+
6548
+ See change: fix-windows-bundled-bash-exe.
5152
6549
 
5153
6550
  ### Session spawn dispatch
5154
6551
 
@@ -5176,6 +6573,13 @@ Per-session keeper process owns pi's stdin pipe. Keeper forwards verbatim to pi'
5176
6573
 
5177
6574
  Keeper outlives dashboard server restarts. Replaced Unix `tail -f /dev/null | pi` wrapper and Windows direct-stdin pipe. Uniform durability across Unix and Windows.
5178
6575
 
6576
+ Keeper logging off by default. Settings > Developer toggle `keeperLog.capturePiOutput` (default `false`) gates ALL keeper log output.
6577
+ - Off: no `keeper-<id>.log`, no `keeper-launch-<id>.log`. `log()` no-op. Rotation not armed. PID sidecars (`.pid`, `.pi-pid`) still written.
6578
+ - On: lifecycle lines + pi stdout/stderr → `keeper-<id>.log` (in-place rotation at `keeperLog.maxBytes`); keeper startup stderr → `keeper-launch-<id>.log`.
6579
+ - Server sets `PI_KEEPER_CAPTURE_PI_OUTPUT=1` from config only. Deletes inherited value (case-insensitive) when off. Inherited env cannot enable.
6580
+ - Read at spawn: applies to new sessions only. Running keepers keep prior behavior.
6581
+ - Server closes launch-log fd after spawn.
6582
+
5179
6583
  Three-process topology + dual-channel boundary:
5180
6584
 
5181
6585
  ```mermaid
@@ -5293,42 +6697,84 @@ The dashboard uses mDNS (via `bonjour-service`) for zero-config server discovery
5293
6697
 
5294
6698
  ### Known Servers
5295
6699
  - Users can persist remote servers in `config.json` via `knownServers: KnownServer[]`
5296
- - Each entry has `host`, `port`, optional `label`, `addedAt` timestamp, optional `fingerprint` (`sha256:` prefix, pinned, see Identity pinning)
5297
- - REST API: `GET /api/known-servers` (list + `canManage`, `networkGuard`), `POST`/`DELETE /api/known-servers` (operator-only), `POST /api/known-servers/accept-move` (operator), `POST /api/known-servers/probe` (operator), `POST /api/discover-servers` for on-demand mDNS scan
6700
+ - Entry = one server instance, keyed by `fingerprint` (`sha256:` prefix, pinned). Shape `{fingerprint?, label?, addedAt, routes[], host, port}`. `host`/`port` mirror primary route (first `http` route, else first route). See Routes and identity grouping.
6701
+ - REST API: `GET /api/known-servers` (list + `canManage`, `networkGuard`; entries carry `routes[]`), `POST /api/known-servers {host, port, scheme?, label?, fingerprint?}` (attach route, operator-only), `DELETE /api/known-servers` by `{host, port, scheme?}` (route; entry removed with its last route) or `{fingerprint}` (whole entry), `POST /api/known-servers/accept-move` (operator), `POST /api/known-servers/probe {host, port, scheme?}` (operator), `POST /api/discover-servers` for on-demand mDNS scan
5298
6702
  - Mutations and probe are operator-only: `preHandler: [networkGuard, operatorGuard]`. Network-trusted browsers can list entries but not change them. Breaking, see release note.
5299
6703
  - Localhost is always implicitly available (not stored)
5300
6704
  - The data model is extensible for future key exchange / auth tokens
5301
6705
 
5302
6706
  ### Known-server identity pinning (change: stabilize-mdns-server-identity)
5303
- - Uniqueness key: `(fingerprint, port)`. `parseKnownServers` (`packages/shared/src/config.ts`) passes `sha256:` fingerprints through; duplicates merged on load, first entry wins, later hosts dropped (logged).
6707
+ - Uniqueness: per `http` route `(fingerprint, port)`; https routes join oldest entry holding F. `parseKnownServers` (`packages/shared/src/config.ts`) passes `sha256:` fingerprints through; legacy `{host, port}` reads as one route (`https` on port 443, else `http`); duplicate entries merged on load, first stored wins.
5304
6708
  - Proof: `proveServerIdentity(baseUrl, {timeoutMs})` (`packages/shared/src/server-pinning.ts`). Fresh nonce → `POST /api/pair/challenge`. `redirect: "manual"`. Response read with 4 KiB cap. Fingerprint recomputed from presented key. Signature verified.
5305
6709
  - `challengePinnedServer` unchanged (remote-registration gate relies on it).
5306
6710
  - Pin written only after proof. Two paths: operator add; backfill (operator probe reports `reachable` for unpinned entry).
5307
- - Add: proof runs outside write queue. Queued write re-reads config and re-validates.
5308
- - Proven `F`, no conflict → pinned.
5309
- - `F` held by other entry at same port, holder's stored address still proves `F` → `409 already_known {host, port}`. Nothing written.
5310
- - `F` held, holder's stored address no longer proves `F` → holder host updated → `{updated: true}`. Label replaced only when non-empty label supplied. `addedAt` kept.
5311
- - Target pinned to `G ≠ F` → `409 identity_changed {expected, proven}`.
6711
+ - Add: challenge over route scheme runs outside write queue. `scheme` allowlist `http`|`https` (else `400 invalid_scheme`). Queued write re-reads config and re-validates.
6712
+ - Proven `F` → route attached per grouping rule. No `409 already_known`, no holder re-probe.
6713
+ - Route already stored → label refresh / pin → `{success: true}`.
6714
+ - New route attached to existing entry → `{updated: true}`. New entry → `{success: true}`.
6715
+ - Route stored under pin `G ≠ F` → `409 identity_changed {expected, proven}`.
6716
+ - Label replaced only when non-empty label supplied. `addedAt` kept.
5312
6717
  - Add never clears or replaces a pin. Failed challenge keeps existing pin.
5313
- - Backfill: proven `F` pinned at stored address. Existing `(F, port)` holder → merged into verified entry (label kept when verified entry has none), other entry removed, dropped host logged.
6718
+ - Backfill: proven `F` pinned at primary route (own scheme). Existing `(F, port)` holder → merged into verified entry (survivor keeps routes, gains other's missing routes; label kept when verified entry has none), other entry removed, dropped host logged.
5314
6719
  - All known-server writes (add, delete, backfill, accept-move) → one module-level serialized queue (`known-servers-routes.ts`). Challenges run before enqueue. Each write aborts if target entry gone.
5315
6720
 
6721
+ ### Routes and identity grouping (change: group-servers-by-identity)
6722
+
6723
+ - Entry = one server instance. Key = fingerprint `F`. Route = address proven to be `F`.
6724
+ - Route item: `{host, port, scheme: "http"|"https", source: "saved"|"mdns"|"pairing"}`. Pure helpers in `packages/shared/src/server-routes.ts` (server, client, Electron): `classifyRoute`, `groupRoutes`, `findAttachTarget`, `rankRoutes`, `pairAction`, `buildRequestPageUrl`, `validateDeliveredRoutes`, `originToRoute`. Constants: `SIMILAR_LATENCY_MS = 50`, `MAX_DELIVERED_ROUTES = 8`.
6725
+ - Route kind derived, never stored: `loopback` (127/8, `::1`, `localhost`); `lan` (RFC1918, CGNAT 100.64/10, link-local, `fc00::/7`, `fe80::/10`, internal names); `mdns` (`*.local`); `tunnel` (https under `zrok.io`); else `public`. Kind picks label and pair action only.
6726
+ - Grouping (`findAttachTarget`): proven route joins entry holding `F` when route is `https`, or entry has no `http` route, or entry has `http` route on same port. Else new entry with same `F`, labelled "same identity as …". Two `http` ports = two rows.
6727
+ - https route joins oldest entry holding `F` (stored list order).
6728
+ - Unpinned entry: single route, keyed `host:port` until proof.
6729
+ - Merge, same identity: on load first stored wins; on backfill proven entry wins. Survivor keeps routes, gains missing routes, keeps or takes label.
6730
+ - Host normalised (`normalizeHost`): lower-case, one trailing dot removed, brackets and zone id stripped, IPv4-mapped IPv6 as IPv4.
6731
+ - Route proof, two concurrent calls per route:
6732
+ - identity challenge (`POST /api/pair/challenge`, route scheme): proof + latency.
6733
+ - `GET /api/health`: access. `403 network_not_allowed` → "Network not allowed". A `200` carrying `networkAccess.error` means same denial but this checker ignores it (`server-route-check.ts` unchanged; `surface-network-denial-on-health` design D6).
6734
+
6735
+ | Challenge | Health | Route state |
6736
+ | --- | --- | --- |
6737
+ | proves `F` | ok | proven, usable |
6738
+ | proves `F` | `403 network_not_allowed` | proven, network not allowed |
6739
+ | proves `F′ ≠ F` | any | refused: different identity; no credential sent |
6740
+ | bad signature / bad key | any | refused: invalid identity proof |
6741
+ | non-200 or no `publicKey`/`signature` | ok | can't prove identity (older server) |
6742
+ | transport failure | n/a | unreachable |
6743
+
6744
+ - Server proof scheme-aware: `proveServerIdentity("<scheme>://host:port")`. Normal TLS verification, `redirect: "manual"`, 2 s, 4 KiB body cap.
6745
+ - Browser proof: `challengeIdentity` (`packages/client/src/lib/pairing/pair-protocol.ts`), same CORS and mixed-content limits as health. Blocked routes explained by server probe.
6746
+ - Concurrency: at most 6 route checks in flight; 2 s each.
6747
+ - mDNS advert `fp` unauthenticated: picks display group only. Route used only after proof of that `F`.
6748
+ - Best route, `rankRoutes(routes, {credentialed})`, proven routes only:
6749
+ - `credentialed: false` (list marker, browser switch): https wins when `https − http ≤ 50 ms` (inclusive); else lowest latency.
6750
+ - `credentialed: true` (Electron open that sends stored bearer): stored https, then stored http, then discovered https, then discovered. First proven wins; latency ignored. Prevents bearer downgrade to cleartext.
6751
+
6752
+ ```mermaid
6753
+ flowchart TD
6754
+ R["proven routes"] --> C{"credentialed?"}
6755
+ C -- "no" --> L["fastest http, fastest https"]
6756
+ L --> G{"https − http ≤ 50 ms?"}
6757
+ G -- "yes" --> HS["https"]
6758
+ G -- "no" --> F["lowest latency"]
6759
+ C -- "yes" --> O["stored https, then stored http, then discovered https, then discovered; first proven, no latency"]
6760
+ ```
6761
+
5316
6762
  ### Move suggestions (change: stabilize-mdns-server-identity)
5317
6763
  - Trigger: `up` / `srv-update` / refresh sweep for peer whose `(fp, port)` matches pinned entry at different host.
5318
6764
  - Rate: one challenge per `(fp, port)` per `MOVE_CHALLENGE_INTERVAL_MS` (60 s).
5319
- - Stored address still proves `F` → no action.
6765
+ - Primary route still proves `F` → no action.
5320
6766
  - Else challenge peer address only if on-link (inside a subnet of a local interface, or IPv6 prefix match) and not loopback / link-local / unspecified / multicast. Else skip, logged `move-skipped`.
5321
6767
  - Proof → in-memory suggestion `{entry, host, port, verifiedAt}`. Not persisted. Fn: `known-server-moves.ts`.
5322
6768
  - `GET /api/known-servers` returns `movedTo` per entry.
5323
6769
  - Dropped when: stored address proves `F` again; peer disappears; not re-verified within `MOVE_SUGGESTION_TTL_MS` (10 min).
5324
6770
  - Advert alone never writes config.
5325
- - Accept: `POST /api/known-servers/accept-move {host, port}` (operator). Re-verifies: stored address fails + suggested address proves `F`. Rewrites host/port; label, `fingerprint`, `addedAt` kept.
6771
+ - Accept: `POST /api/known-servers/accept-move {host, port}` (operator). Re-verifies: primary route fails + suggested address proves `F`. Rewrites primary route `host`/`port` (scheme `http`); other routes, label, `fingerprint`, `addedAt` kept.
5326
6772
  - Logs: `[known-servers] move-suggested|move-withdrawn|move-skipped fp=<short> <old> -> <new>`; accept logs `[known-servers] moved fp=<short> <old> -> <new>`. `<short>` = fingerprint without `sha256:`, 16 chars.
5327
6773
 
5328
6774
  ### Operator probe (change: stabilize-mdns-server-identity)
5329
- - `POST /api/known-servers/probe {host, port}` (operator). Refuses unless `normalizeHostKey(host):port` matches persisted entry.
5330
- - Order: DNS lookup first (own budget `PROBE_DNS_TIMEOUT_MS`), then `GET http://<formatHostPort>/api/health` (`redirect: "manual"`, `PROBE_HTTP_TIMEOUT_MS`). Separate budgets: slow negative `.local` lookup ≠ HTTP timeout.
5331
- - One in-flight probe per entry.
6775
+ - `POST /api/known-servers/probe {host, port, scheme?}` (operator). Refuses unless `normalizeHostKey(host):port` + scheme matches a stored route.
6776
+ - Order: DNS lookup first (own budget `PROBE_DNS_TIMEOUT_MS`), then `GET <scheme>://<formatHostPort>/api/health` (`redirect: "manual"`, `PROBE_HTTP_TIMEOUT_MS`). Separate budgets: slow negative `.local` lookup ≠ HTTP timeout.
6777
+ - One in-flight probe per route. On `reachable`, challenge over same route adds `fingerprint`. Result carries `scheme`.
5332
6778
  - States:
5333
6779
  - `name-not-resolved`: `ENOTFOUND` / `EAI_NONAME`.
5334
6780
  - `timeout`: DNS timeout, `EAI_AGAIN`, HTTP `AbortError` / `TimeoutError`.
@@ -5338,7 +6784,7 @@ The dashboard uses mDNS (via `bonjour-service`) for zero-config server discovery
5338
6784
 
5339
6785
  ### Server Selector UI
5340
6786
  - The header dropdown shows persisted known servers (from config) plus localhost, not raw mDNS results
5341
- - Each entry shows label (or hostname), host:port, Local/Remote badge, and availability status
6787
+ - Each row is one identity: label (or hostname), best route `host:port`, Local/Remote badge, availability status. Routes listed per row with kind and proof state (`ServerRouteTable.tsx`, `server-route-chips.tsx`).
5342
6788
  - **Probe lifecycle**: availability is probed via `/api/health` **only when the dropdown opens** — once per open. No mount probe, no timer, no probing while the dropdown is closed. Current-server status is derived from the live WebSocket state, not a separate probe.
5343
6789
  - **Unreachable entries** are rendered with `opacity-50`, `cursor-not-allowed`, and the `disabled` attribute set; clicks are no-ops. To re-probe, close and reopen the dropdown. The transactional switch (below) still protects against races between the last probe and a click on a reachable entry.
5344
6790
  - Last-used server persisted in `localStorage` (`pi-dashboard-last-server`) — **only after** a successful switch (see transactional switching below).
@@ -5380,9 +6826,8 @@ An `inFlightSwitchKey` ref guards against duplicate clicks; the clicked dropdown
5380
6826
  `ConnectionStatusBanner` (`packages/client/src/components/ConnectionStatusBanner.tsx`) mounts above `<MobileShell>`. It shows "Disconnected from &lt;host&gt;. Retrying…" when the active WebSocket has been non-`OPEN` for more than 3 seconds continuously. The threshold is implemented via `setTimeout` cleared on any return-to-`OPEN` or unmount, so brief reconnects (laptop sleep, wifi hiccup) never flash the banner. During an in-flight staging switch the banner is suppressed — the live socket is still open, so no disconnection has actually occurred.
5381
6827
 
5382
6828
  ### Server Management (Settings Panel)
5383
- - **Known Servers section**: lists persisted servers with remove buttons and an inline add form (host, port, label)
5384
- - **Network Discovery section**: "Scan network" triggers `POST /api/discover-servers`, shows results with "Add" button that prompts for a label
5385
- - Already-known servers show "Already added" badge in discovery results
6829
+ - **Servers section** (`ServersTab` → `KnownServersSection`): one merged section, saved + discovered servers, one row per identity. Replaces separate Known Servers and Network Discovery sections. Per-row pair action (see Routes and identity grouping; Route delegation and pair action).
6830
+ - Add form takes host, port, scheme, label. Scan triggers `POST /api/discover-servers`.
5386
6831
  - Electron loading page shows known servers as fallback when primary server is unreachable
5387
6832
 
5388
6833
  ## Bridge↔Server Connection — transport & identity (designed)
@@ -5562,7 +7007,7 @@ See change: add-radius-provider-login (D5, D6).
5562
7007
 
5563
7008
  **Non-goal.** Model proxy has no Radius OAuth refresh loader.
5564
7009
 
5565
- **Dependency pin.** The server imports only `@earendil-works/pi-coding-agent` (`await import(...)`, public index `ModelRuntime`), never `@earendil-works/pi-ai` and never either package's `dist/` (both unreachable — export maps / hoisted `1.3.0`). Binding to the pi-ai copy pi-coding-agent was built against gives version parity by construction. Six governed pins move together: `packages/server/package.json` dep `^1.3.0`, `piCompatibility.minimum`, `piCompatibility.recommended`, the `pnpm-workspace.yaml` override, `docker/Dockerfile`, and `scripts/verify-release-deps.mjs` `minVersion` (`checkPiPinCoherence`). Every `@earendil-works` peer is `>=1.3.0` (optional, no upper bound); every `@earendil-works` devDependency is `^1.3.0`; `pnpm-workspace.yaml` overrides pin `pi-coding-agent`, `pi-ai`, `pi-tui`. See changes: update-pi-core-1-0-adopt-apis, update-pi-core-1-1-adopt-apis, update-pi-core-1-3-adopt-apis; floor moved to 1.1.0 in update-pi-core-1-1-adopt-apis, to 1.3.0 in update-pi-core-1-3-adopt-apis.
7010
+ **Dependency pin.** The server imports only `@earendil-works/pi-coding-agent` (`await import(...)`, public index `ModelRuntime`), never `@earendil-works/pi-ai` and never either package's `dist/` (both unreachable — export maps / hoisted `1.7.0`). Binding to the pi-ai copy pi-coding-agent was built against gives version parity by construction. Six governed pins move together: `packages/server/package.json` dep `^1.7.0`, `piCompatibility.minimum`, `piCompatibility.recommended`, the `pnpm-workspace.yaml` override, `docker/Dockerfile`, and `scripts/verify-release-deps.mjs` `minVersion` (`checkPiPinCoherence`). Every `@earendil-works` peer is `>=1.7.0` (optional, no upper bound); every `@earendil-works` devDependency is `^1.7.0`; `pnpm-workspace.yaml` overrides pin `pi-coding-agent`, `pi-ai`, `pi-tui`. See changes: update-pi-core-1-0-adopt-apis, update-pi-core-1-1-adopt-apis, update-pi-core-1-3-adopt-apis; floor moved to 1.1.0 in update-pi-core-1-1-adopt-apis, to 1.3.0 in update-pi-core-1-3-adopt-apis, to 1.5.0 in update-pi-core-1-5-adopt-apis.
5566
7011
 
5567
7012
  **Routes** (`packages/server/src/routes/provider-auth-routes.ts`):
5568
7013
 
@@ -5630,6 +7075,109 @@ The endpoint resolves `$ENV_VAR` references and the `***` REDACTED sentinel (for
5630
7075
  | `src/client/components/settings/ProviderAuthSection.tsx` | Settings UI component |
5631
7076
  | `src/client/components/settings/RadiusMcpOffer.tsx` | Inline Radius MCP offer shown after a completed `radius` sign-in |
5632
7077
 
7078
+ ### Provider advanced settings
7079
+
7080
+ Edit opens `ProviderEditDialog.tsx` (panes in `ProviderAdvancedPanes.tsx`). Shared `PaneShell` = title + Back footer. Change: `add-provider-advanced-settings`.
7081
+
7082
+ Panes:
7083
+ - Main: per-kind content (sign-in facts, `ProviderEnvFields`, custom-endpoint fields + Test).
7084
+ - Advanced (collapsed): Endpoint, Models (→ one model), Edit as JSON, Add another `<name>` (copies).
7085
+ - Title `<provider> - <pane>`. One draft of whole block. Save writes once. Disabled until draft changes.
7086
+ - Endpoint/Models/JSON read-only when `writable:false`. Reasons: `provider_overrides.has_comments`, `.set_by_extension`, `.unreadable`, `.legacy_shape`, `.invalid_before`.
7087
+
7088
+ #### Two stores
7089
+
7090
+ ```mermaid
7091
+ flowchart LR
7092
+ D[ProviderEditDialog] -->|built-in / models.json-only| O["/api/provider-overrides/:provider"]
7093
+ D -->|custom endpoint / copy| P["/api/providers/:name"]
7094
+ O --> M[(agentDir/models.json providers.id)]
7095
+ P --> J[(providers.json providers.id.block)]
7096
+ ```
7097
+
7098
+ | Provider | Block lives in | Routes |
7099
+ |---|---|---|
7100
+ | pi built-in, or only in `models.json` | `models.json` `providers.<id>` | `GET`/`PUT /api/provider-overrides/:provider` |
7101
+ | custom endpoint, copy | `providers.json#providers.<id>.block` | `GET`/`PATCH /api/providers/:name` |
7102
+
7103
+ - `GET /api/providers/:name` (`operate`): entry, `block` masked, `revision`.
7104
+ - `PUT /api/provider-overrides/:provider` on `providers.json` id → 409 `owned_by_providers_json`.
7105
+ - Unknown id, no `models.json` block → 404.
7106
+ - Extension-set models: bridge reports `modelsSetByExtension: true` on `providers_list` catalogue entry. GET → `writable:false, reason:"provider_overrides.set_by_extension"`. PUT → 409 same code.
7107
+ - Split API-key row id `<id>-api` resolves to pi provider `<id>` on override routes (`provider-override-routes.ts`).
7108
+ - `PUT /api/providers` carries `block`, `copyOf`, unknown keys through unchanged.
7109
+ - `PATCH /api/providers/:name` keeps stored `block`/`copyOf` when omitted. Accepts `revision`; stale → 409 `stale_revision`. No `revision` → last-write-wins.
7110
+ - `block` may not hold `baseUrl`/`apiKey`/`api` → `block_field_owned_by_entry`.
7111
+
7112
+ #### `models.json` writer (`auth/models-json-store.ts`, `auth/provider-block-checks.ts`)
7113
+
7114
+ - Lock: `acquireLock(path, 2000, …)` from `locked-json-file.ts`. Held >2 s → 503 `provider_overrides.locked`.
7115
+ - Read, replace one key under `providers`, write tmp next to realpath, validate, rename. Symlink + mode kept. New file `0600`.
7116
+ - Tmp/rename I/O error → 500 `provider_overrides.write_failed`. Tmp deleted. `models.json` byte-identical.
7117
+ - Normalise: empty `headers`/`modelOverrides`/`models`/`compat` removed. Block with no fields → key deleted.
7118
+ - Revision: GET returns hash of stored block. PUT re-checks under lock before rename. Residual: unlocked hand edit between check and rename lost.
7119
+ - Refusals before write: `unreadable` (pi can't parse; `/* */` too), `has_comments` (`//` outside strings), `legacy_shape` (no `providers` object), `invalid_before` (file already fails pi).
7120
+ - Trailing commas + BOM not comments. Rewrite drops them. Values kept, formatting not.
7121
+ - Validation (two layers):
7122
+ - pi `ModelConfig.load(<tmp>)`, imported by resolved path `<pi>/dist/core/model-config.js` (`model-proxy/pi-models-validator.ts`).
7123
+ - Composer rules (dashboard fn): block needs ≥1 of `baseUrl`/`headers`/`compat`/`modelOverrides`/`models`; added model needs `baseUrl` somewhere. Parity test runs pi composer on same fixtures.
7124
+ - Import failure → fail closed, 503 `validator_missing`. Test pins path.
7125
+ - Other refusals (nothing written): body >256 KiB (262144) → 413 `too_large`; 400 `prototype_key`, `duplicate_model_id`, `orphan_mask`, `userinfo_refused`, `command_refused`, `RECURSIVE_PROXY` (self-pointing `baseUrl`). Codes under `provider_overrides.`; `PATCH` block path uses `providers.`.
7126
+ - After write: `refreshModelRegistry()` + `credentials_updated` (no `refreshProviders`). Sessions `ModelRegistry.refresh()` reload `models.json`.
7127
+ - Logs: provider, outcome, code. Never values.
7128
+
7129
+ #### Masking value classes
7130
+
7131
+ Follows pi resolver (`resolve-config-value`):
7132
+ - `!…` → command.
7133
+ - Unescaped `$NAME` / `${NAME}` → reference. `$$`, `$!` escape.
7134
+ - Else → literal.
7135
+
7136
+ Rules:
7137
+ - Literal `apiKey`, header values (any depth), `baseUrl` userinfo, `baseUrl` query values → masked `ENV_MASK_MARKER`.
7138
+ - Restore keys: provider header by case-insensitive name; model header by (model id, name); `modelOverrides` header by (model id, name); userinfo/query by (path, part/param).
7139
+ - Orphan marker → `orphan_mask`.
7140
+ - References + commands shown as text.
7141
+ - New/changed command from browser → `command_refused`. Unchanged kept.
7142
+ - Userinfo refused only when new/changed.
7143
+ - `ENV_MASK_MARKER` accepted only inside `block` + override routes. Legacy `***` stays on `GET /api/providers` `apiKey`.
7144
+
7145
+ #### Server hybrid apply (`model-proxy/models-block-apply.ts`, `internal-registry.ts`)
7146
+
7147
+ Runtime keeps `modelsPath: null`. Shared reader parses like pi (BOM, comments, trailing commas). On each registry refresh:
7148
+ 1. Auth-side (`baseUrl`, `headers`, `authHeader`, `apiKey`) → `runtime.registerProvider(id, …)` for built-ins with block. pi composer applies in `getAuth`. OAuth kept. Removed block → unregister to bare built-in.
7149
+ 2. Model-side (`baseUrl`, `compat`, `modelOverrides`, `models[]`) → dashboard applies to built-in model copies in `getAllModels()`. Pi order: `models[]` entry replaces same id, overrides last. Feeds `/api/models` + `streamSimple` object.
7150
+ 3. `!command` value: server never runs it. Applied without value. Credential falls back to stored. Dependent models excluded, reason `command_value`.
7151
+ 4. Block fails both checks → skipped (bare built-in) + registry error.
7152
+ - `GET /api/models` excludes credentials + `headers`.
7153
+ - `radius-override.ts` keeps precedence.
7154
+ - `$NAME` resolves in server env. Session resolves in session env. May differ. Row warning reflects server.
7155
+
7156
+ #### Copies
7157
+
7158
+ - Offered for built-ins whose sign-in = API key only (incl. key command).
7159
+ - Id `<base>-<slug(name)>`. Empty slug refused. Collision with any registry id refused on create only.
7160
+ - `copyOf` immutable.
7161
+ - Entry in `providers.json`; row `<base> · <name>`, `custom: true`.
7162
+ - Bridge (`extension/src/provider-register.ts`): skips discovery. Models = base effective models from session `ModelRegistry`, `baseUrl`+`headers` stripped. Config = base `models.json` block (`baseUrl`, `headers`, `authHeader`) overlaid by copy `block`. `compat`/`modelOverrides` merged per model. `name` set at registration.
7163
+ - Key: copy's own `apiKey`, else `ModelRegistry.getApiKeyForProvider(base)`. Server: `auth.json[base]` + server env.
7164
+ - Shared key = command → server excludes (`command_value`). Row warning "Server can't use `<base>`'s key command". Sessions still work.
7165
+ - Snapshot (`lastRegistered`/`entriesEqual`): `baseUrl`, `apiKey`, `api`, hash of `block`, `copyOf`, copy fingerprint (resolved key hash + base block hash + base model ids). Copies re-register on `credentials_updated` + `ModelRegistry.refresh()`.
7166
+ - Discovery, catalogue cache, `provider-probe` skip `copyOf`. `POST /api/providers/:name/refresh` on copy → 400 `copy_has_no_discovery`.
7167
+
7168
+ #### Vertex Project / Region
7169
+
7170
+ API-key method gets `Project` + `Region` fields (`shared/src/vertex-regions.ts`, `provider-overrides.ts`). Not env vars. Write `baseUrl`.
7171
+ - Project regex `^[a-z][a-z0-9-]{4,28}[a-z0-9]$`. Invalid → inline error, Save disabled.
7172
+ - Region: `global` | pinned list | Other (`^[a-z]+-[a-z]+[0-9]+$`). Disabled until Project set. No `us`/`eu`.
7173
+ - `global` → `https://aiplatform.googleapis.com/v1/projects/<p>/locations/global`.
7174
+ - Else → `https://<r>-aiplatform.googleapis.com/v1/projects/<p>/locations/<r>`.
7175
+ - Forms parse back. Other `baseUrl` → fields disabled ("Endpoint URL set under Advanced").
7176
+ - Built-in Vertex → override write. Copy → `block.baseUrl` via `PATCH`.
7177
+ - Save order (built-in): `baseUrl` first, then credential. `baseUrl` refused → nothing written; offer Save key without region. Credential refused → restore previous `baseUrl`. Restore fails → report both, Open Endpoint action.
7178
+ - Method switch / key removal removes Vertex-form `baseUrl` in same save. Refused → save refused.
7179
+ - Key check (`vertex-key-check.ts`): runs only when effective `baseUrl` empty or Vertex-form. `countTokens` under that `baseUrl`. Other host → `not_checked` (key never sent to custom host). 401/403/timeout/network/404 → failed. Else ok.
7180
+
5633
7181
  ## Terminal Emulator
5634
7182
 
5635
7183
  The dashboard includes a browser-based terminal emulator for direct shell access.
@@ -5739,7 +7287,7 @@ See FAQ: How do I clean up stale entries from settings.json?
5739
7287
 
5740
7288
  ### Bundled first-party extensions (Electron installer)
5741
7289
 
5742
- The Electron installer can optionally ship a curated subset of recommended pi extensions inside `resources/bundled-extensions/<id>/` so first-run works with zero network access. The set is declared by `BUNDLED_EXTENSION_IDS` in `packages/shared/src/recommended-extensions.ts` (currently `pi-anthropic-messages`, `pi-flows`) — a strict subset of `RECOMMENDED_EXTENSIONS`, enforced by a unit test.
7290
+ The Electron installer can optionally ship a curated subset of recommended pi extensions inside `resources/bundled-extensions/<id>/` so first-run works with zero network access. The set is declared by `BUNDLED_EXTENSION_IDS` in `packages/shared/src/recommended-extensions.ts` (currently `pi-flows`) — a strict subset of `RECOMMENDED_EXTENSIONS`, enforced by a unit test.
5743
7291
 
5744
7292
  **Build time** (`packages/electron/scripts/bundle-recommended-extensions.sh`): gated on `BUNDLE_RECOMMENDED_EXTENSIONS=1` (set in `.github/workflows/publish.yml`, unset everywhere else). Clones each id shallow, records the commit SHA to `.bundled-sha`, validates the SPDX identifier against a fixed allowlist (MIT, Apache-2.0, BSD-2-Clause, BSD-3-Clause, ISC), and fails the build if the combined bundle exceeds 15 MB. `forge.config.ts` conditionally appends `./resources/bundled-extensions` to `extraResource` when the directory exists.
5745
7293
 
@@ -5780,12 +7328,35 @@ Inline `!!` ephemeral cards (`InlineTerminalCard`) unchanged, excluded from tabs
5780
7328
 
5781
7329
  See change: terminals-in-tabbed-panes.
5782
7330
 
7331
+ ### Terminal Caps and Orphan Reaping (change: harden-server-capability-bounds)
7332
+
7333
+ `TerminalManager` bounds live PTYs. Config block `terminals` in `config.json`:
7334
+
7335
+ | Key | Default | Meaning |
7336
+ |-----|---------|---------|
7337
+ | `maxConcurrent` | 32 | Global live PTY cap. Tab + inline both count. |
7338
+ | `maxPerOwner` | 16 | Per `{iss,sub}` owner. Only while identity plane stamps owners. Ownerless PTYs count global only. |
7339
+ | `inlineOrphanTtlMs` | 600000 | Inline PTY TTL with no client attached. |
7340
+
7341
+ - Each value integer >= 1, else default + one warn line.
7342
+ - Restart server to apply.
7343
+ - Refused spawn starts nothing. Requesting socket gets `terminal_limit_reached {scope: global|owner, limit, cwd, inline}`. UI shows dismissible notice.
7344
+ - Tab terminals never reaped on idleness.
7345
+ - Inline (ephemeral) PTY: clock starts at spawn, restarts at last detach. Expiry kills PTY. Transcript tombstone kept.
7346
+
5783
7347
  ### Known Servers Configuration
5784
7348
 
5785
7349
  ```json
5786
7350
  {
5787
7351
  "knownServers": [
5788
- { "host": "office-mac.local", "port": 8000, "label": "Office Mac", "addedAt": "2024-01-15T10:30:00Z" },
7352
+ {
7353
+ "host": "office-mac.local", "port": 8000, "label": "Office Mac", "addedAt": "2024-01-15T10:30:00Z",
7354
+ "fingerprint": "sha256:<43 chars>",
7355
+ "routes": [
7356
+ { "host": "office-mac.local", "port": 8000, "scheme": "http", "source": "saved" },
7357
+ { "host": "office.example.ts.net", "port": 443, "scheme": "https", "source": "pairing" }
7358
+ ]
7359
+ },
5789
7360
  { "host": "build-server", "port": 8000, "addedAt": "2024-01-20T14:00:00Z" }
5790
7361
  ]
5791
7362
  }
@@ -5793,6 +7364,10 @@ See change: terminals-in-tabbed-panes.
5793
7364
 
5794
7365
  Managed via REST API (`/api/known-servers`) or Settings panel. Localhost is always implicit.
5795
7366
 
7367
+ - `routes[]` item: `{host, port, scheme, source}`. Kind derived, never stored.
7368
+ - Legacy entry (no `routes`) reads as one route. Startup never rewrites file; first mutation writes `routes[]` + mirror. One log line.
7369
+ - Rollback: previous build reads `host`/`port` mirror only; drops `routes` on its next write. Secondary routes lost (re-learned via mDNS / pairing). `https` route read back as `http`; legacy port-443 entries read as `https` again on re-upgrade. No entry lost.
7370
+
5796
7371
  ## Bundled Skill: pi-dashboard
5797
7372
 
5798
7373
  The `.pi/skills/pi-dashboard/` directory is both a local project skill (discovered by pi from `.pi/skills/`) and shipped with the npm package (discovered via `pi.skills` in `package.json`). This means any pi session in the dashboard project or any project that installs the dashboard package gets access to the skill.
@@ -5809,9 +7384,9 @@ The `.pi/skills/pi-dashboard/` directory is both a local project skill (discover
5809
7384
  | `POST /api/session/:id/rename` | Rename a session |
5810
7385
  | `POST /api/session/:id/hide` | Hide session |
5811
7386
  | `POST /api/session/:id/unhide` | Unhide session |
5812
- | `POST /api/session/spawn` | Spawn new session in a directory |
7387
+ | `POST /api/session/spawn` | Spawn new session in a directory. Body `{cwd, agent?, model?, thinkingLevel?, initialPrompt?, attachProposal?}`; `@role` resolved once; invalid choice → 400 (before side effects) |
5813
7388
  | `POST /api/session/:id/resume` | Resume or fork ended session |
5814
- | `POST /api/session/:id/flow-control` | Abort flow or toggle autonomous |
7389
+ | `POST /api/plugins/flows/control` | Flow controls (abort, ask-session, run, delete, edit mode). Operate authority + network guard; ACP → 409 `unsupported_for_acp` |
5815
7390
  | `POST /api/session/:id/model` | Set provider + model |
5816
7391
  | `POST /api/session/:id/thinking-level` | Set thinking level |
5817
7392
  | `POST /api/session/:id/attach-proposal` | Attach OpenSpec change |
@@ -6112,12 +7687,14 @@ See change: repair-corrupted-main-specs.
6112
7687
 
6113
7688
  ## OpenSpec workflow schema (`pi-spec-driven`)
6114
7689
 
6115
- Dashboard-managed project schema. Base: OpenSpec built-in `spec-driven` + patch set (`CURRENT_PATCH = 1`). Opt-in per project. Never enabled on existing projects by default.
7690
+ Dashboard-managed project schema. Base: OpenSpec built-in `spec-driven` + patch set (`CURRENT_PATCH = 2`). Opt-in per project. Never enabled on existing projects by default.
6116
7691
 
6117
7692
  Code:
6118
7693
  - `packages/server/src/openspec/workflow-schema.ts` — generation, stamp, state table, write guard, actions.
6119
7694
  - `packages/server/src/routes/openspec-routes.ts` — `POST /api/openspec/workflow-schema`, init chain.
6120
- - `packages/server/src/directory-service.ts` — `workflowSchemaStatusFor` (poll status).
7695
+ - `packages/server/src/openspec/workflow-schema-status.ts` — worker-safe fs-only status (`computeSchemaStatus`, `inspectSchema`, stamp parse/compare, `fingerprintDir`, config + change enumeration). No CLI/semaphore imports.
7696
+ - `packages/server/src/openspec/openspec-poll-worker.ts` + `openspec-poll-worker-pool.ts` — `schemaStatus` request kind: `{cwd, localVersion, packageSchemasDir, userSchemasDir}` → `{status, validateFingerprint?}`.
7697
+ - `packages/server/src/directory-service.ts` — `requestSchemaStatus` enqueues it.
6121
7698
  - `packages/shared/src/types.ts` — `WorkflowSchemaGenerated`, `OpenSpecWorkflowSchemaStatus`.
6122
7699
  - `packages/shared/src/openspec-poller.ts`, `.pi/skills/openspec-shared/scripts/effective-status.sh` — R-rule skip.
6123
7700
 
@@ -6246,11 +7823,40 @@ Remove sees only local working tree. Unmerged branches pinning `pi-spec-driven`
6246
7823
 
6247
7824
  `OpenSpecData.workflowSchema?: OpenSpecWorkflowSchemaStatus` = `{ configured, generated, missing, unpinnedChanges, affectedChanges }`.
6248
7825
  - Attached only to successful-poll payloads. Failure payload carries no schema status (`hasWorkflowSchemaStatus(readiness)` gate in `directory-service.ts`).
6249
- - Computed on the MAIN thread, not the poll worker. `workflowSchemaStatusFor` (`directory-service.ts`) runs concurrently with the CLI spawn in `pollOne`, attached at finalize. Async fs reads only.
6250
- - Only `newer` / `conflict` `schema validate` spawns. Routed through the shared spawn semaphore; memoized by (cwd, fingerprint, CLI version).
7826
+ - Computed by poll worker `schemaStatus` request. See Poll status below.
7827
+ - Only `newer` / `conflict` spawn `schema validate`. Main thread, shared spawn semaphore, memoized.
6251
7828
  - Readiness untouched. Missing schema dir → per-change `Unknown schema` errors, not `STALE`. `STALE` would disable every OpenSpec control on session cards.
6252
7829
  - Settings section: `/settings/openspec#workflow-schema` (`OpenSpecWorkflowSchemaSection.tsx`). Folder-section chip only links there.
6253
7830
 
7831
+ ### Poll status
7832
+
7833
+ ```mermaid
7834
+ sequenceDiagram
7835
+ participant M as main
7836
+ participant W as poll worker
7837
+ M->>W: schemaStatus {cwd, localVersion, packageSchemasDir, userSchemasDir}
7838
+ W-->>M: {status, validateFingerprint?}
7839
+ opt newer / conflict
7840
+ M->>M: openspec schema validate pi-spec-driven (semaphore, memoized)
7841
+ end
7842
+ ```
7843
+
7844
+ - Computed by worker `schemaStatus` request on EVERY tick, gate hit included.
7845
+ - Gate does not track: CLI version, `config.yml`, user/package schema dirs, fallback `list` path.
7846
+ - Enqueued once per tick:
7847
+ - status-all path: right after `pool.probe`.
7848
+ - fallback `list` path: before `list` spawn.
7849
+ - `build` never waits on it. Only finalize awaits.
7850
+ - Stamp compare decided from stamp alone.
7851
+ - Whole-dir fingerprint only for `newer` / `conflict`. `.openspec.yaml` reads bounded (16).
7852
+ - `newer` / `conflict`: worker returns `validateFingerprint`. Main runs `openspec schema validate pi-spec-driven` via shared semaphore. Memoized by (cwd, fingerprint, CLI version). Failure → `incompatible`.
7853
+ - Worker error / timeout / disabled → in-process fallback `schemaStatusImpl`.
7854
+ - Both fail → `workflowSchema` key omitted for tick. Logged once per failure run per cwd.
7855
+ - `finalizeOpenSpecData` never carries previous tick's `workflowSchema`.
7856
+ - One spawn semaphore: `DirectoryService.semaphore` shared with REST route (`server.ts` passes as `spawnSemaphore`). `reconfigurePolling` resize applies to both.
7857
+
7858
+ See change: move-workflow-schema-status-to-poll-worker.
7859
+
6254
7860
  ### REST endpoint
6255
7861
 
6256
7862
  `POST /api/openspec/workflow-schema`. Body: `{ cwd, action, confirm?, pinTo?, changes?, previousDefault? }`. `action` ∈ `enable | disable | update | adopt | pin | remove`.
@@ -6276,6 +7882,176 @@ Design-evidence promotion (R1 split files, R2 `design/` dir, R3 no design + task
6276
7882
  - Skills: `.pi/skills/openspec-shared/scripts/effective-status.sh` — `jq -r '.schemaName'` gate on `openspec status --change <name> --json`.
6277
7883
  - Other schemas: rules unchanged. Fallback `list` path (no `schemaName`): keeps promoting.
6278
7884
 
7885
+ ## OpenSpec change dependencies (`add-openspec-change-dependencies`)
7886
+
7887
+ Per-change execution order. Declared + inferred edges → graph → cycle/unknown validation → waves. Pure parser in shared; server builds inputs; client renders chips, dialog, "Execution order" board mode.
7888
+
7889
+ Code:
7890
+ - `packages/shared/src/openspec-dependencies.ts` — pure: `parse`, `scanProposal`, `scanDelta`, `computeDependencyGraph`, `serializeDependencies`.
7891
+ - `packages/shared/src/types.ts` — `ChangeDependencies`, `DependencyEdge`, `DependencyIssue`; `OpenSpecChange.dependencies`.
7892
+ - `packages/server/src/openspec/openspec-dependency-inputs.ts` — per-file + per-change parse cache; `computeDependencies`.
7893
+ - `packages/server/src/openspec/openspec-poll-worker.ts` — `buildFromStatusAll` calls `computeDependencies` (worker and in-process identical).
7894
+ - `packages/server/src/openspec/dependencies-file.ts` — read/write helper for `dependencies.yaml`.
7895
+ - `packages/server/src/routes/openspec-routes.ts` — `GET`/`PUT /api/openspec/dependencies`.
7896
+ - `packages/client/src/components/openspec/DependencyChips.tsx`, `DependenciesDialog.tsx`.
7897
+ - `packages/client/src/lib/openspec/openspec-dependencies-view.ts` (pure helpers), `openspec-dependencies-api.ts` (fetch).
7898
+ - `.pi/skills/ship-it/scripts/openspec-deps-gate.ts` — ship-it step 1.5 gate.
7899
+
7900
+ Spec: `openspec/specs/openspec-change-dependencies/spec.md`. Archived change: `openspec/changes/archive/2026-10-21-add-openspec-change-dependencies/`. See change: add-openspec-change-dependencies.
7901
+
7902
+ ### Pipeline
7903
+
7904
+ ```mermaid
7905
+ flowchart LR
7906
+ DECL["declared: dependencies.yaml"] --> MERGE
7907
+ L1["L1: proposal labelled lines + prose refs"] --> MERGE
7908
+ L23["L2 capability birth / L3 shared capability"] --> MERGE
7909
+ MERGE["merge per ordered pair (blocked, blocker)"] --> RES["resolve: open / satisfied / unknown"]
7910
+ RES --> VAL["validate: cycle check x2"]
7911
+ VAL --> WAVE["waves: Kahn over open edges"]
7912
+ WAVE --> OUT["OpenSpecChange.dependencies"]
7913
+ ```
7914
+
7915
+ ### File: `openspec/changes/<name>/dependencies.yaml`
7916
+
7917
+ Keys:
7918
+ - `blocked_by: [name | {change, reason?}]`.
7919
+ - `not_blocked_by: [name]`.
7920
+ - `related: [name]`.
7921
+
7922
+ Rules:
7923
+ - Unknown top-level key → `invalid-file`.
7924
+ - Bad name → `invalid-file`. Name grammar `/^[a-z0-9]+(?:-[a-z0-9]+)*$/` (OpenSpec change-id).
7925
+ - `reason` > 500 chars → `invalid-file`. Alias → `invalid-file`.
7926
+ - File > 64 KiB → `invalid-file`. Symlink / non-regular file → `invalid-file`.
7927
+ - Empty file or empty key → no deps (not an error).
7928
+ - Parse: `yaml` `failsafe` schema + `maxAliasCount: 0`.
7929
+ - Reader `readDependenciesFile`: `lstat` regular-file check, read ≤ 64 KiB + 1, `O_NOFOLLOW`.
7930
+ - Only `blocked_by` stored. `blocks` always computed (inverse).
7931
+
7932
+ ### Inference layers
7933
+
7934
+ - Declared edges: from `dependencies.yaml`. Highest precedence.
7935
+ - L1 proposal text: labelled lines `Blocked by` / `Depends on` / `Builds on` / `Blocks`.
7936
+ - List item or paragraph. Optional bold + parenthetical. Value after `:` or as backticked token. Continuation lines allowed.
7937
+ - `Blocks on` is NOT a label.
7938
+ - Fenced code blocks skipped.
7939
+ - Self, unknown, and archived-under-`Blocks` ignored.
7940
+ - Other backticked active change names in prose → `related`. Never blocking.
7941
+ - L2 capability birth: capability with no `openspec/specs/<cap>/spec.md` is unborn.
7942
+ - Sole ADDED-only birther blocks every other change that has a delta header.
7943
+ - ≥ 2 birthers → `duplicate-capability` warning. No edge.
7944
+ - L3 shared capability: `overlaps` edge. Undirected. Never blocking.
7945
+
7946
+ ### Merge
7947
+
7948
+ - Key: `(blocked, blocker)`.
7949
+ - Precedence: declared > inferred-text > inferred-capability.
7950
+ - `not_blocked_by` suppresses any edge for that pair.
7951
+ - Name in both `blocked_by` and `not_blocked_by` → `conflicting-entry` warning. `not_blocked_by` wins.
7952
+
7953
+ ### Resolution
7954
+
7955
+ | Blocker state | Result |
7956
+ |---|---|
7957
+ | active change dir `openspec/changes/<name>/` | open |
7958
+ | archive dir exactly `<YYYY-MM-DD>-<name>` | satisfied |
7959
+ | `<date>-SHELVED-<name>` | NOT satisfied |
7960
+ | unknown, in declared `blocked_by` | `unknown-change` warning |
7961
+ | unknown, inferred | silent |
7962
+ | self | `self-reference` error |
7963
+
7964
+ ### Validation
7965
+
7966
+ - Errors: `invalid-file`, `self-reference`, `cycle` (declared-only).
7967
+ - Warnings: `cycle` (inferred edge involved), `blocked-by-cycle`, `unknown-change`, `conflicting-entry`, `duplicate-capability`.
7968
+ - Cycle path: shortest cycle through smallest-named SCC member. Lexicographic tie-break. Format `a → b → a`.
7969
+
7970
+ ### Waves
7971
+
7972
+ - Kahn over open edges among active changes.
7973
+ - Wave 1 = no open blockers.
7974
+ - Cycle members + their dependents → `wave: null`.
7975
+
7976
+ ### Tracked paths (poll gate + watcher)
7977
+
7978
+ - Per-change `dependencies.yaml` in gate probe + watcher filter.
7979
+ - cwd-level: `changes/archive/`, `openspec/specs/`, `openspec/specs/<cap>/spec.md` for capability ids of previous build (`DirCache.allCapIds`).
7980
+ - `allCapIds === null` → gate never skips.
7981
+ - Capability set change → re-stamp cwd mtime.
7982
+
7983
+ ### Schema patch v2
7984
+
7985
+ - `CURRENT_PATCH = 2` in `packages/server/src/openspec/workflow-schema-status.ts` (`workflow-schema.ts` re-exports it).
7986
+ - Inserts artifact `dependencies` before `tasks`. Generates `dependencies.yaml` from `templates/dependencies.yaml`. Requires `[proposal, specs]`.
7987
+ - `tasks.requires = [specs, design, dependencies]`.
7988
+ - Anchor must be exactly `[specs, design]`. Otherwise generation aborts.
7989
+ - Patch-1 stamp → `generated: outdated`. Only explicit Update regenerates.
7990
+ - Undeclared change stays `PLANNING`. Board shows "Declare dependencies" hint, artifact letter `L`.
7991
+ - `OpenSpecData.workflowSchema.undeclaredChanges`: `affectedChanges` members without regular `dependencies.yaml`. Lstat only; symlink or dir counts as undeclared. Sorted.
7992
+ - Computed each poll tick by `listUndeclared` in `packages/server/src/openspec/workflow-schema-status.ts`. Worker-safe. Reads bounded by `mapLimit` 16.
7993
+ - Consumed by Settings → OpenSpec Update confirmation (patch 2): count of affected changes returning to `PLANNING`. Update applies patch v2 only on explicit action; enable never regenerates.
7994
+
7995
+ ### REST
7996
+
7997
+ `GET /api/openspec/dependencies?cwd=&change=` (tier `observe`) → `{dependencies, declared, declaredError, file}`.
7998
+
7999
+ `PUT /api/openspec/dependencies` (tier `control`). Body: `{cwd, change, blockedBy, notBlockedBy, related, expected}`.
8000
+
8001
+ Both `networkGuard`.
8002
+
8003
+ Gate order and codes:
8004
+ 1. `400` `invalid-request`.
8005
+ 2. `403` `cwd-not-tracked`.
8006
+ 3. `403` `openspec-disabled`.
8007
+ 4. `403` `opted-out`.
8008
+ 5. `404` `no-openspec-dir`.
8009
+ 6. `409` `status-all-unsupported`.
8010
+ 7. `503` `pending`.
8011
+ 8. `404` `unknown-change`.
8012
+
8013
+ PUT after gate:
8014
+ 1. `writeGuard` → `403` `write-refused`.
8015
+ 2. Shared per-cwd lock `inFlightInits` → `409` `locked`.
8016
+ 3. `expected` precondition (mtime + size) → `409` `modified`.
8017
+ 4. YAML serializer → temp file → `rename` (replace) or `link` (create, no replace).
8018
+
8019
+ Log event: `openspec.dependencies`.
8020
+
8021
+ MCP tools: `get_openspec_dependencies`, `openspec_dependencies`.
8022
+
8023
+ ### Client
8024
+
8025
+ - `DependencyChips` + `DependenciesDialog` (edit `blocked_by` / `not_blocked_by` / `related`).
8026
+ - Chips visible when default schema is `pi-spec-driven` or any change `hasFile`.
8027
+ - Board toggle "Execution order": sorts columns by wave. Within-column reorder off. Cross-column drop appends.
8028
+
8029
+ ### ship-it gate
8030
+
8031
+ `.pi/skills/ship-it/scripts/openspec-deps-gate.ts --change <name>` (step 1.5).
8032
+
8033
+ - Online: `GET` per request, 5 s timeout. 503 retried ≤ 3× at 2 s.
8034
+ - Offline fallback: shared parser. Cycles and inferred edges NOT checked.
8035
+ - Open blockers archived on `origin/develop` count satisfied.
8036
+ - Output JSON: `{status: ok|warn|blocked, mode, blockers[{change,state,source}], issues, notes}`.
8037
+ - Errors → block via `SHIP_IT_BLOCKED.md`. Open blockers → warn.
8038
+
8039
+ ### Cost
8040
+
8041
+ - Debug line: `[openspec-deps] changes=N edges declared=.. inferred-text=.. inferred-capability=.. issues error=.. warning=.. ms=..`. Shown when `DEBUG` matches `openspec-poll`.
8042
+ - Budget: < 20 ms median for 100 changes after one input edit.
8043
+ - Caches: per-file (path + mtime + size); per-change keyed by gate probe mtime.
8044
+ - Measured (#P2, macOS 26.4, Apple M5 Pro, this repo, 85 active changes):
8045
+ - cold first run: 73 ms (cold fs cache) / 24 ms (warm fs cache).
8046
+ - warm, nothing changed: 2.0 ms.
8047
+ - one input touched: 2.3 ms.
8048
+ - Windows 11 QA VM: pending (manual-only row P2).
8049
+
8050
+ ### Compat / rollback
8051
+
8052
+ - Additive. No migration.
8053
+ - Rollback: revert commit. Leftover `dependencies.yaml` files inert.
8054
+
6279
8055
  ## Electron Server Lifecycle
6280
8056
 
6281
8057
  Paired remote dashboards open in per-server Electron windows (own origin, device cookie): see [electron-server-windows.md](./electron-server-windows.md).
@@ -6530,6 +8306,10 @@ See change: require-git-on-boot.
6530
8306
 
6531
8307
  Package manager: **pnpm**, pinned to `pnpm@11.15.1` via root `package.json` `packageManager` field + `corepack enable`.
6532
8308
 
8309
+ - Node 25+ ships no `corepack`. Node 26 = required runtime/dev Node.
8310
+ - Docker: `ARG COREPACK_VERSION=0.36.0`; `npm install -g "corepack@${COREPACK_VERSION}"` then `corepack enable`.
8311
+ - Dev setup: `npm install -g corepack && corepack enable`.
8312
+
6533
8313
  Scope: pnpm drives ALL dev, CI, Docker, and build work. `npm` survives ONLY in locations listed below.
6534
8314
 
6535
8315
  Lockfile: Single committed lockfile = `pnpm-lock.yaml`. Old `package-lock.json` removed.
@@ -6558,10 +8338,15 @@ Configuration lives in `pnpm-workspace.yaml` (NOT `package.json` `pnpm.*` — ya
6558
8338
 
6559
8339
  1. `npm publish --provenance` in `publish.yml` — OIDC Trusted Publishing. Needs no npm-installed tree. `publish` job upgrades to `npm@latest` only for OIDC ≥11.5.1 floor.
6560
8340
  2. Column C runtime `npm install` on END-USER machines: `pi-core-updater.ts`, `pi-core-checker.ts`, `recovery-server.ts`, electron `update-checker.ts`.
6561
- 3. `bundle-server.mjs` internal `npm install --omit=dev` for electron bundle.
6562
- 4. `deploy-site.yml` `site/` job (separate `site/package-lock.json`; `site/` NOT a pnpm workspace member).
8341
+ 3. `bundle-server.mjs` internal npm for electron bundle runtime tree:
8342
+ - `npm install --omit=dev` (floating mode, default).
8343
+ - `npm pack @blackbelt-technology/pi-dashboard-server@X` (`fetchPublishedLock`, release-lock mode).
8344
+ - `npm ci --omit=dev --allow-remote=all` on rebased `package-lock.json` (release-lock mode).
8345
+ 4. Runtime-lock generation: `scripts/generate-runtime-lock.mjs` (publish + nightly). Rebase check: `scripts/lint-runtime-lock.mjs --version X`.
8346
+ 5. `deploy-site.yml` `site/` job (separate `site/package-lock.json`; `site/` NOT a pnpm workspace member).
6563
8347
 
6564
8348
  See change: adopt-pnpm-for-dev-ci.
8349
+ See change: pin-electron-bundle-dependency-tree.
6565
8350
 
6566
8351
  ## Doctor Diagnostics
6567
8352
 
@@ -6861,6 +8646,52 @@ Caps (caps.ts): `maxActiveEmbedSessionsPerVisitor` + `maxActiveEmbedSessionsGlob
6861
8646
 
6862
8647
  See change: add-embed-session-lifecycle.
6863
8648
 
8649
+ ## Flow parent mailbox
8650
+
8651
+ pi-flows 0.11+ steps ask questions to a parent. Dashboard shows them in flow panel. Change: `adopt-flow-parent-mailbox`.
8652
+
8653
+ **Events (bridge → server → client).**
8654
+ - `flow:question` → `flow_question`. `stream`, keyed `stepId`.
8655
+ - `flow:answer` → `flow_answer`. `stream`, keyed `stepId`.
8656
+ - `flow:ask-session-result` → `flow_ask_session_result`. `live`.
8657
+ - Declared in `packages/flows-plugin/src/bridge/flow-event-forward.ts` (`FLOW_RUN_CHANNELS`).
8658
+
8659
+ **Reducer.**
8660
+ - `FlowState.questions` keyed by `question_id`.
8661
+ - First close wins (answer or cancel). Later closes ignored.
8662
+ - Run end closes leftover open questions as `cancel`.
8663
+
8664
+ **UI.**
8665
+ - Asking step node: purple, `?` marker.
8666
+ - Agent card: Question block. Button "Ask session".
8667
+ - Whole run waiting on a question → run-level waiting state.
8668
+
8669
+ **Ask session path.**
8670
+ ```mermaid
8671
+ sequenceDiagram
8672
+ participant C as Client
8673
+ participant S as Server (flows plugin)
8674
+ participant B as Bridge
8675
+ participant F as pi-flows
8676
+ C->>S: plugin_action flow.ask-session {questionId, requestId?}
8677
+ S->>B: emit flow:ask-session {question_id, requestId?}
8678
+ B->>F: flow:ask-session
8679
+ F-->>B: flow:ask-session-result
8680
+ F->>F: post flow:ask follow-up into session
8681
+ ```
8682
+ - Payload `questionId` 1-64 chars `[A-Za-z0-9_-]`; `requestId` same charset.
8683
+ - Repeat per (sessionId, questionId) within 30 s → throttled. REST 429 `{ code: "throttled" }`.
8684
+ - REST twin: `POST /api/plugins/flows/control { sessionId, action: "flow.ask-session", questionId, requestId? }`. Operate authority.
8685
+
8686
+ **Run attach.**
8687
+ - `flow.run` relays `notifyParent: true`. Dashboard-started runs attached; steps can ask parent session.
8688
+ - Automations stay detached.
8689
+
8690
+ **Removed.**
8691
+ - PromptBus `FlowQuestionAdapter`. Flow questions no longer enter PromptBus / chat stream.
8692
+ - AUTO (autonomous mode): pi-flows 0.12 dropped it. `flow.toggle-autonomous`, `/dashboard:flow-auto` gone.
8693
+ - `autonomousMode` key in `providers.json` preserved as unknown key (`dashboard-roles-ownership`).
8694
+
6864
8695
  ## Question stack (open prompts → one global list)
6865
8696
 
6866
8697
  One list of every open PromptBus prompt the caller may see. Client: header pill, panel, dialog. Server: `question-store` keyed by `(sessionId, promptId)`. Change: add-pending-question-stack.
@@ -7062,6 +8893,33 @@ Result render emits leaf heading, not breadcrumb, plus `(+N more sections)`. Ful
7062
8893
 
7063
8894
  Path-only fetch (`getChunk` without `headingPath`) returns first chunk plus `suppressedSections` count. Never a silent 1-of-N slice.
7064
8895
 
8896
+ - `kb_get` tool + `kb get` CLI share `resolveFetch` / `renderFetch` / `buildFetchRoots` (`packages/kb/src/fetch-resolve.ts`).
8897
+ - Roots = `store.listRoots()` (`SELECT DISTINCT root FROM chunks`). Remote git/https roots included.
8898
+ - NOT `resolvedSources[0]`. Old bug: ~88% sections unfetchable in 9-root KB (issue #1114).
8899
+ - Path readings:
8900
+ - literal in every root.
8901
+ - id-qualified `<source-id>:<path>`. Longest id wins. Ids with `:` round-trip.
8902
+ - dir-qualified `<relDir>/<path>`. `relDir` = `relative(cwd, dir)`, `/`-normalized, filesystem roots only.
8903
+ - Dedup by (root, path).
8904
+ - 1 reading → hit.
8905
+ - 0 → `(not found: <arg>)`. Unresolved path only.
8906
+ - >1 → `(ambiguous: <arg> is indexed in N sources — pass one of:)` + sorted `<source-id>:<path>` candidates. No body. Details `{found:false, candidates:N}`.
8907
+ - Section: `getChunkBySection(root, path, section)` (`packages/kb/src/sqlite-store.ts`).
8908
+ - Exact `heading_path` first.
8909
+ - Else (no ` > ` in arg) last-heading suffix match.
8910
+ - Several distinct heading paths → ambiguous section candidate list.
8911
+ - `getChunk` exact semantics unchanged.
8912
+ - No match in a resolved file → `section-missing` result. Render `(section not found: <section> in <arg> — sections:)` + ≤50 distinct body heading paths (rowid order, `:meta` chunk excluded) + `(+K more section[s])` when K > 0. Empty list → `(section not found: <section> in <arg> — no sections)`. `found:false`. Paths via required `FetchStore.getChunks(root, path)`. See change: fix-kb-parent-link-and-section-miss.
8913
+ - Source classification (`classifyRef`, `packages/kb/src/sources.ts`):
8914
+ - `ssh://` → `git`.
8915
+ - GitHub repo ref (`[https://]github.com/<o>/<r>` + optional `.git`, `@<ref>`, `/tree/<ref>`) → `git` (regex `GITHUB_REPO`). Cloned as `https://github.com/<o>/<r>` (`.git` kept if given). Revision from `@ref`/`/tree/<ref>`. `pin` wins. No auto-subdir.
8916
+ - Other `github.com/...` paths, raw, `/blob/`, `/archive/` → `https`.
8917
+ - https plain fetch: `assertIndexableBody` rejects HTML body or file name without configured extension (`ResolveCtx.extensions`, default `DEFAULTS.extensions`, case-insensitive). Runs before cache swap → old cache + `.fetched` marker survive.
8918
+ - Error names URL. `/blob/` → raw URL hint. Else `kind: "git"` hint.
8919
+ - Remote sources still index via `kb index` CLI only. Extension auto-reindex walks filesystem `resolvedSources`.
8920
+
8921
+ See change: fix-kb-get-roots-and-guard.
8922
+
7065
8923
  #### DOX doctrine injection (`doctrine` config)
7066
8924
 
7067
8925
  Config group `doctrine: { "inject": "kb" | "off", "write": boolean }`. Layered project `.pi/dashboard/knowledge_base.json` → global `~/.pi/dashboard/knowledge_base.json` → defaults. Deep-merged one level, same as `readDiscipline` / `ranking`. Defaults `{ inject: "kb", write: false }`. Validation: `inject` ∈ {`kb`,`off`}; `write` boolean.
@@ -7113,12 +8971,16 @@ Settings page `packages/kb-plugin/src/client/KbSettingsPanel.tsx`. Add via `KbSo
7113
8971
 
7114
8972
  `reindexAll` (`packages/kb-plugin/src/server/kb-routes.ts`) walks `cfg.allSourceSpecs` — all kinds (filesystem/git/https/npm) via engine resolvers. Each source isolated: failure → `error` outcome, job `jobStatus:"error"`, `lastError` `"N source(s) failed: …"` (≤500 chars); untrusted → skipped, job stays idle; failed/skipped source keeps prior chunks. `git`/`https` resolution async (`execFile`, 120 s timeout) — never blocks server event loop. Reindex gate = saved `allSourceSpecs.length > 0`.
7115
8973
 
8974
+ Worker: job runs in `worker_threads` worker `reindex-worker.mjs` (`reindex-runner.ts`, core `reindex-core.ts`). Kill-switch `PI_DASHBOARD_KB_REINDEX_WORKER=0` → in-process. Read per job. Worker load failure before ready → in-process fallback. Crash after ready → job fails. Cancel → `cancel` msg, `terminate()` after `REINDEX_CANCEL_GRACE_MS` (5 s). Batch loop yields after `INDEX_BATCH_MAX_MS` (50 ms). One `[kb-plugin] reindex mode=worker|inprocess … outcome=…` log line per job.
8975
+
7116
8976
  Trust = TOFU, global. Store `~/.pi/dashboard/kb-source-trust.json`, keyed sha256 of `{kind,ref,subdir,pin}`. One grant covers identical spec in every folder. Revoke under Access → `DELETE /api/kb/source-trust`. Grant path: UI trust dialog (`Trust & add` / `Add without trusting` / `Cancel`) → `PUT /api/kb/config` `trustRefs`, or `POST /api/kb/source-trust {ref}`. Server records SAVED spec matched by exact `ref` (404 none, 409 duplicate refs, 400 filesystem, 500 persist failure). `untrustedRefs` in PUT response lists grants that failed. Trust-store write atomic (`tmp`+rename); `recordTrust` returns boolean. Fetch-side SSRF/zip-slip guards from change `harden-untrusted-content-ingestion` (`net-guard.ts`, `archive-guard.ts`).
7117
8977
 
7118
8978
  ### KB source & search routes
7119
8979
 
7120
8980
  - `GET /api/kb/sources?cwd=` — per-source kind, files, trusted, outside, last outcome.
7121
8981
  - `GET /api/kb/search?cwd=&q=&limit=&docType=` — read-only test search over SAVED index. Opens existing store only — no init, no migrate, no create. `q` 1–512, `limit` 1–50 (default 10), `docType` `doc|agents|source-md`. No reindex, no verdicts. Stale schema → `needsReindex:true`.
8982
+ - `POST /api/kb/reindex/cancel?cwd=` — operator tier. Asks running job to stop. `200 {cancelled:true|false}`. Shares reindex admission. Job still `running` in `/stats` until settled. Repeat during grace → `cancelled:true`, no second stop.
8983
+ - `GET /api/kb/stats?cwd=` — adds transient `progress {root,done,total}` while running.
7122
8984
 
7123
8985
  All cwd-guarded (`isAllowedCwd`).
7124
8986
 
@@ -7270,7 +9132,7 @@ Residuals:
7270
9132
  - NAT / published-port callers (docker): `binding-mismatch`. BREAKING for `pi-dashboard login --local|open|token create` through a published port. Run inside container or log in.
7271
9133
 
7272
9134
  Deploy + rollback:
7273
- - Order: restart server FIRST (`curl -X POST http://localhost:8000/api/restart`), THEN `npm run reload`.
9135
+ - Order: restart server FIRST (`pi-dashboard api POST /api/restart`; dev checkout: `npx tsx .pi/skills/implement/scripts/restart-server.ts`), THEN `npm run reload`.
7274
9136
  - Reverse order: proof-only bridges hit pre-proof server → refused / quarantined.
7275
9137
  - Rollback: revert server. Marked sessions quarantine (`server-proof-missing`) → restart those sessions.
7276
9138
 
@@ -7691,3 +9553,196 @@ flowchart LR
7691
9553
  - Revert change. Delete `~/.pi/dashboard/role-bindings.json` (optional).
7692
9554
  - Targets keep last concrete value.
7693
9555
  - Grammar `llm.role` configs fall back to "pick a model".
9556
+
9557
+ ## Client sink hardening (Trusted Types, URL policy, navigation intents)
9558
+
9559
+ ### Trusted Types mode
9560
+ - Modes: `off|report|enforce`. Default `report`.
9561
+ - Resolution order: env `PI_DASHBOARD_TRUSTED_TYPES` → config `security.trustedTypes` (`~/.pi/dashboard/config.json`) → default.
9562
+ - Default → `off` iff `PI_DASHBOARD_CSP=off`, else `report`.
9563
+ - "Set" source = not `undefined` and not whitespace-only string. First set source decides.
9564
+ - Value trimmed + lowercased. `off|report|enforce` → itself.
9565
+ - Other set value (typo, number, object) → `report` + one startup warning naming source (`env`|`config`). Never logs raw value.
9566
+ - Every set source validated, incl. env shadowing valid config. Mirrors `hostGate.mode` no-lockout convention.
9567
+ - Resolver: `packages/shared/src/trusted-types-mode.ts` `resolveTrustedTypesMode({env,config,cspMode})` → `{mode,source,warnings}`; `recognizeTrustedTypesMode(raw)`.
9568
+ - `packages/server/src/auth/csp.ts` re-exports resolver. Old `(raw, cspMode)` signature removed.
9569
+ - `registerCsp` appends `require-trusted-types-for 'script'` to baseline header when modes match. Else sets other header kind with directive alone.
9570
+ - Add-if-absent per header kind. `/live/` skipped. `serveApp` mounts keep own enforcing policy.
9571
+ - Server injects `<meta name="pi-trusted-types" content="<mode>">` into index.html (`lib/index-html.ts`).
9572
+ - `server.ts` resolves once at startup (`loadConfig().security?.trustedTypes`). Logs each warning once (`[csp] Trusted Types: …`). Same mode → `registerCsp` + `createIndexHtmlSender`.
9573
+ - `createIndexHtmlSender` option `trustedTypesMode` required (no `report` fallback). Document meta always equals header mode.
9574
+ - Dev: `trustedTypesDevPlugin` in `packages/client/trusted-types-dev-plugin.ts` (imported by `packages/client/vite.config.ts`). Uses same shared resolver. Reads config file. States same mode as server.
9575
+ - Config API: `PUT /api/config` deep-merges `security`. `trustedTypes: null` deletes key (emptied `security` removed). Restart flagged only when normalized value changes.
9576
+ - `GET /api/config` adds computed, never-persisted `trustedTypesEnvOverride` (recognized env value or `null`). Stripped on write.
9577
+ - UI: Settings → Security → Trusted Types select (`TrustedTypesSection.tsx`): Default / Enforce / Report only / Off. Env override → read-only text `Set by PI_DASHBOARD_TRUSTED_TYPES: <mode>`. Change needs server restart.
9578
+ - Rollback / opt-in: config key, Settings, or env + restart.
9579
+ - Missing meta → client treats as `report`.
9580
+
9581
+ ### Client policies
9582
+ - File: `packages/client/src/lib/security/trusted-types.ts`. Registered before first render (`lib/boot/client-boot.ts` `bootClient`).
9583
+ - `pi-sanitized-html`: profiles from `packages/shared/src/sanitize-profiles.ts` (same configs as server sanitizers).
9584
+ - No mermaid parse policy. MermaidBlock colorize runs on sanitized DOM: DOMPurify `RETURN_DOM` (mermaid profile) → tint → XML serialize. No string parse of unsanitized output. Final `sanitizeMermaidSvg` + `pi-sanitized-html` still run before injection.
9585
+ - `pi-worker-url`: `/sw.js`, `/assets/<file>.m?js`.
9586
+ - `default`: mode-aware.
9587
+ - report: pass-through + count.
9588
+ - enforce: sanitize, `createScript` → null, script-URL allowlist.
9589
+ - Team app: `pi-static-svg` in `packages/team-app/src/ui/trusted-static-svg.ts`.
9590
+
9591
+ ### Violation channel
9592
+ - Client batches `securitypolicyviolation` events + default hits every 30 s and on `pagehide`.
9593
+ - Dedupe key: directive/sink/source. Cap ≤ 50 keys + `overflow`. No samples. Source without query/fragment.
9594
+ - `POST /api/csp-violations`: network guard, 8 KiB cap, per-principal burst 3 / 12 per min → 429, counters only, LRU 500.
9595
+ - `GET /api/csp-violations` (operate tier): returns counters.
9596
+ - Unrelated to live-preview `/__pi/csp-report`.
9597
+ - Shadow aggregate: `shadow: {<outcome>: n}` per report. Outside 50-key cap and `overflow`. Report mode only.
9598
+ - Shadow totals clamp 1,000,000 per report. Remainder carried to next report.
9599
+ - Totals-only report sent when shadow totals non-empty.
9600
+ - Totals subtracted on 2xx. Kept on failure except 400: discarded + 1 `shadow-error` added.
9601
+ - Body priority: violations → default hits → per-source `trusted-types-shadow` detail.
9602
+ - Body ≤ 7,168 B. Every `source` cut to 512 UTF-16 units.
9603
+ - `pagehide` keepalive send not retried. Residual: last ≤ 30 s lost.
9604
+ - Server `parseReport`: `shadow` non-object or bad known count → 400. Unknown keys ignored.
9605
+ - Server after schema + limiter: `recordShadow` → persisted `ttShadow`. Never `record()`.
9606
+ - Shadow detail: own in-memory LRU 500. Never evicts violation keys.
9607
+ - See change: add-trusted-types-shadow-enforce.
9608
+
9609
+ ### URL policy
9610
+ - `packages/shared/src/url-policy.ts` `classifyUrl(raw, origin|null)` → `internal|loopback|external|mailto|blocked`.
9611
+ - Chokepoints in `packages/dashboard-plugin-runtime/src/safe-navigation.tsx` (plugin SDK, host API 1.2.0): `SafeLink`, `openExternalUrl`, `assignLocation`, `useSafeNavigation`.
9612
+ - Re-used by `packages/client/src/lib/nav/safe-navigation.tsx`.
9613
+ - Electron `isAllowedExternalUrl` delegates to `classifyUrl`.
9614
+ - CI guard: `scripts/check-client-sinks.mjs` (ci.yml step + ship-it 4.4). Rejects raw nav / html / script sinks.
9615
+ - Exemption: `// client-sinks: allow — <reason>`.
9616
+
9617
+ ### Navigation intents
9618
+ - `POST /api/nav-intent` mints `ni = b64url(e).b64url(HMAC-SHA256(key, principal\0kind\0target\0e))`. TTL 600 s. Per-process key (restart invalidates).
9619
+ - `POST /api/nav-intent/verify` → `{ok}`. Constant-time compare.
9620
+ - Route-backed overlays (`/folder/:cwd/view?path=`, `/pi-view?url=`):
9621
+ - verified `ni` → operator provenance (≤ 2 s pending, then agent on failure).
9622
+ - no `ni` → agent provenance (restricted egress).
9623
+ - Minted only from operator Expand on operator-provenance `PreviewCard`. Modifier / middle clicks and agent cards never mint.
9624
+ - `returnTo` / `returnUrl` not intent-gated.
9625
+
9626
+ ### OIDC discovery
9627
+ - `packages/client-utils/src/identity/login-flow.ts` rejects non-`https:` discovery endpoints (loopback `http:` allowed).
9628
+ - Throws `LoginFlowError("discovery-failed")` before any navigation or token request.
9629
+
9630
+ ### Electron bundled pages
9631
+ - `src/renderer/{doctor,remote-connect,connecting}.html`, `resources/loading.html`.
9632
+ - Meta CSP `require-trusted-types-for 'script'` from day one. Not governed by env knob.
9633
+
9634
+ See change: harden-client-sinks.
9635
+
9636
+ ## Baseline CSP: strict policy + report sink (S3b)
9637
+
9638
+ Two policies, one sink, persisted counter. Default mode stays `report`; nothing breaks by default. Code: `packages/server/src/auth/{csp,csp-report-paths,csp-report-sink,csp-report-store}.ts`.
9639
+
9640
+ ### Modes (`PI_DASHBOARD_CSP`)
9641
+
9642
+ | Mode | Headers |
9643
+ |---|---|
9644
+ | `report` (default) | `baseline` Report-Only → `/__pi/csp-report/baseline` AND `strict` Report-Only → `/__pi/csp-report/strict` |
9645
+ | `enforce` (explicit opt-in) | `strict` ENFORCED → `/__pi/csp-report/strict`. `baseline` NOT emitted. |
9646
+ | `off` | no baseline or strict header |
9647
+ | any, Vite `--dev` (per proxied response) | baseline only (legacy `script-src`), enforcing under `enforce`. No strict header. No report destination. Dev never feeds strict counter. |
9648
+
9649
+ - Strict = baseline with `script-src 'self' 'nonce-<n>'`. No `'unsafe-inline'`, no `'unsafe-eval'`. Enforced only under explicit `enforce`.
9650
+ - Every emitted policy carries `report-uri /__pi/csp-report/<label>` ONLY.
9651
+ - No `report-to` directive. No `Reporting-Endpoints` header. `cspReportEndpointName` removed from `csp-report-paths.ts`.
9652
+ - Live preview same (`buildLiveCsp`): `report-uri /live/<id>/~c/<token>/__pi/csp-report` only.
9653
+ - Why: Chromium 157 / Firefox 153 never delivered `report-to` + `Reporting-Endpoints` reports on plain http. `report-to` suppresses `report-uri` in Chromium. Prod counters stayed 0.
9654
+ - Residual: `report-uri` deprecated in CSP3. Tripwire = Chromium-only `tests/e2e/csp-report-delivery.spec.ts`. Safari / Firefox need a manual canary.
9655
+ - Route-level per-response policies (`/api/file/raw` sandbox, `ctx.serveApp` mounts, `/live/`) untouched by mode.
9656
+ - Release note: explicit `enforce` now enforces the STRICT policy (before: baseline). Existing `enforce` deployments see it.
9657
+
9658
+ ### Trusted Types interaction
9659
+
9660
+ - TT follows resolved mode (env `PI_DASHBOARD_TRUSTED_TYPES` → config `security.trustedTypes` → default), independent of CSP mode (see § Client sink hardening).
9661
+ - Matching modes append `require-trusted-types-for 'script'`: `report` → baseline Report-Only header; `enforce` → strict enforcing header. Reports go to that header's label.
9662
+ - Differing modes → other header kind carries TT directive alone, labelled `trusted-types` → `/__pi/csp-report/trusted-types`.
9663
+ - TT violations count in `require-trusted-types-for` bucket. Never in strict `script-src*` measure.
9664
+ - Client counters `/api/csp-violations` (in-memory, harden-client-sinks) untouched. Distinct namespace.
9665
+
9666
+ #### Shadow enforce (report mode)
9667
+
9668
+ - Runs only in `default` policy, `report` mode (`packages/client/src/lib/security/trusted-types.ts`). `off` / `enforce`: no shadow work.
9669
+ - Returns input unchanged. Output and `defaultHit` counts unchanged. Never throws into sink.
9670
+ - Outcomes (`SHADOW_OUTCOMES`): `would-block-script`, `would-block-script-url`, `would-alter-html`, `would-throw-html`, `not-evaluated`, `shadow-error`.
9671
+ - `would-block-script`: every report-mode `createScript` call.
9672
+ - `would-block-script-url`: `createScriptURL` failing `isAllowedScriptUrl`.
9673
+ - `inShadow` flag: nested `default` call returns input, counts nothing.
9674
+ - HTML tag-free input (no `<`): no outcome, no work.
9675
+ - HTML uses separate `DOMPurify(window)` instance. Shared instance untouched.
9676
+ - Parse policy `pi-shadow-parse`: module-private, never exported, never a document sink.
9677
+ - Shared `enforceProfileFor(s)` picks profile for both enforce and classifier.
9678
+ - Pass 1: enforce profile. `removed > 0` → `would-alter-html`.
9679
+ - Pass 2: only if pass 1 clean and input leads with `style|link|meta|title|base|script|noscript|template`. `FORCE_BODY`. Output differs → `would-alter-html`.
9680
+ - Throw in `assertPurify` or pass 1 → `would-throw-html`. Other throw → `shadow-error`.
9681
+ - Memo: exact-string LRU. 512 entries / 4 Mi UTF-16 units.
9682
+ - Budget per 30 s window: 200 classifications / 2 Mi UTF-16 units / 50 ms (`performance.now()`).
9683
+ - Over budget: `not-evaluated` once per distinct input per window. Not memoized.
9684
+ - Perf gate: report-mode variant of `tests/e2e/trusted-types-perf.spec.ts`. Median of 5 runs ≤ 20 ms.
9685
+
9686
+ #### Shadow persistence, health and flip gate
9687
+
9688
+ - Store: `ttShadow: {since, counts: {<outcome>: {count, firstSeen, lastSeen}}}` in `csp-reports.json`. `version` stays `1`.
9689
+ - `ttShadow.since` renewed on: fresh store; missing block (older-server rewrite after rollback); malformed block (1 warning, core kept, no `.corrupt`).
9690
+ - `POST /api/csp-reports/reset`: zeroes `ttShadow`, sets its `since` to core `since`.
9691
+ - In-memory per-source shadow rows not cleared by reset. Split view until restart.
9692
+ - Crash loses ≤ 5 s of shadow counts.
9693
+ - Health: `cspReports.ttShadow` = `{since, <6 outcome counts>}`. Flat. Zeros included. No per-key timestamps. Absent = server predates change.
9694
+ - Flip gate (`enforce-trusted-types-default`): evidence valid only from `ttShadow.since`.
9695
+ - Flip gate: `not-evaluated` and `shadow-error` = 0.
9696
+ - Flip gate: `would-alter-html` = 0 necessary, not sufficient. Visual spec under enforce stays a gate.
9697
+ - See change: add-trusted-types-shadow-enforce.
9698
+
9699
+ ### Nonce lifecycle
9700
+
9701
+ - `cspNonceFor(reply)`: 16 random bytes base64, minted per HTML response, memoized per reply. `onSend` hook reads it.
9702
+ - Import map `<script type="importmap">` gets same nonce (`injectImportMap`, `sendIndexWithImportMap` in `server.ts`).
9703
+ - Non-HTML responses: strict header without nonce.
9704
+ - Passkey pages (`auth/passkey/passkey-pages.ts`): no inline script. Static same-origin assets `/auth/passkey/*.js|css`. Per-request data in non-executable `<script type="application/json" id="pk-data">` island. No nonce needed.
9705
+ - Plugin bundles load via same-origin `import()` → covered by `'self'`. `blob:` / `data:` stay forbidden.
9706
+ - pdf.js: client sets `isEvalSupported:false` → no `new Function` probe report.
9707
+
9708
+ ### Report sink
9709
+
9710
+ `POST /__pi/csp-report/:policy`, `:policy` ∈ `baseline|strict|trusted-types`.
9711
+
9712
+ - Mounted at root, OUTSIDE guard jurisdiction (`/api`, `/v1`, `/editor`, `/live`). Mutation-origin gate does not apply.
9713
+ - Public to OAuth gate (`auth-plugin.ts` skip beside `/api/health`). Signed-out pages (login, passkey) can report.
9714
+ - Host admission gate still applies.
9715
+ - Live sink `/live/<id>/__pi/csp-report` separate, unchanged.
9716
+ - Refusal precedence: 404 (bad label) → 405 (`Allow: POST`) → 429 → 415 → 413 / 408 / 400.
9717
+ - Content-Type `application/csp-report` | `application/reports+json`, else 415.
9718
+ - Own byte-counting body read. Cap 8 KiB, chunked included → 413. Independent of `content-length`, `bodyLimit`, parser order.
9719
+ - Body read deadline 5 s → 408.
9720
+ - Empty / malformed / non-report / content-encoded body → 400, uncounted.
9721
+ - Limiter: per socket peer, token bucket capacity 20, refill 1 token/s. Every request consumes one token (Reporting API batch too). Loopback NOT exempt (global `@fastify/rate-limit` allow-lists loopback → would exempt all tunnel traffic). Excess → 429.
9722
+ - Accepted → 204, empty body. No response reflects input. Raw reports never logged or stored.
9723
+ - Log: throttled `[csp] violation policy=<label> directive=<x>`.
9724
+ - Limiter / size cap / deadline refusals bump persisted `dropped`.
9725
+ - Tunnel users share peer `127.0.0.1` → flood can push real reports into `dropped`. Sink = signal, not access control.
9726
+
9727
+ ### Counter store
9728
+
9729
+ - File `~/.pi/dashboard/csp-reports.json`, mode 0600, tmp-file + rename.
9730
+ - Debounced write 5 s (`FLUSH_DEBOUNCE_MS`). Flush on server close. Write failure never throws.
9731
+ - Key `policy × effective-directive`. Fixed directive allow-set, else `other`.
9732
+ - Bounded document-path breakdown (path only, top 20 per policy, rest `other`). Persisted, never in health.
9733
+ - Fields: counts, `dropped`, `since`, `firstSeen`/`lastSeen`.
9734
+ - Corrupt at boot → moved to `csp-reports.json.corrupt`, counting restarts at zero, new `since`.
9735
+ - Reset: `POST /api/csp-reports/reset` (operate tier, `packages/shared/src/route-tiers.ts`) or delete file while server stopped. Both set new `since`, zero `dropped`.
9736
+ - Health: `GET /api/health` carries `cspReports` `{since, dropped, counts}` ONLY when `canDiscloseAccessPosture(request)` passes (same predicate as `accessGrants`). Else block omitted. Health never refuses.
9737
+ - Predicate ignores `requireLocalProof`: bare loopback caller sees block. Accepted — counts only.
9738
+ - Counter inflation fails safe: forged reports can only delay flip, never hide real violation.
9739
+
9740
+ ### Rollout / rollback
9741
+
9742
+ - Default `report`. Release adds sink + dual Report-Only. No page breaks.
9743
+ - `enforce` = strict, opt-in.
9744
+ - Rollback: `PI_DASHBOARD_CSP=report` or `off` + server restart.
9745
+ - Follow-up `enforce-strict-csp-default` owns soak + default flip. Exit gate: ≥ 14 d window, zero strict `script-src*` violations, `dropped == 0`, ≥ 1 release shipped, enforce-lane E2E green. Inspect directive / document breakdown before flip.
9746
+ - E2E lanes: see `docs/faq.md` § "CSP enforce + OAuth real-gate E2E lanes".
9747
+
9748
+ See change: harden-cors-and-csp-reporting (D8, D9, D10), fix-csp-report-delivery.