@blackbelt-technology/pi-agent-dashboard 0.9.0 → 0.10.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 (439) hide show
  1. package/README.md +38 -5
  2. package/docs/architecture.md +1673 -75
  3. package/package.json +23 -15
  4. package/packages/extension/package.json +8 -8
  5. package/packages/extension/src/ask-user-tool.ts +65 -3
  6. package/packages/extension/src/auto-session-namer.ts +190 -50
  7. package/packages/extension/src/bridge-handlers/dispatch.ts +450 -0
  8. package/packages/extension/src/bridge-handlers/forwarders.ts +616 -0
  9. package/packages/extension/src/bridge-handlers/instance.ts +220 -0
  10. package/packages/extension/src/bridge-handlers/lifecycle.ts +1030 -0
  11. package/packages/extension/src/bridge-handlers/ui-prompt-patch.ts +198 -0
  12. package/packages/extension/src/bridge-identity-log.ts +45 -0
  13. package/packages/extension/src/bridge.ts +480 -2510
  14. package/packages/extension/src/command-handler.ts +180 -11
  15. package/packages/extension/src/connection.ts +265 -18
  16. package/packages/extension/src/dashboard-context-injector.ts +26 -47
  17. package/packages/extension/src/empty-actionable-guard.ts +8 -3
  18. package/packages/extension/src/flow-event-wiring.ts +1 -1
  19. package/packages/extension/src/followup-buffer.ts +1 -1
  20. package/packages/extension/src/followup-drain.ts +79 -0
  21. package/packages/extension/src/local-token-header.ts +161 -17
  22. package/packages/extension/src/message-update-coalescer.ts +3 -1
  23. package/packages/extension/src/model-refresh.ts +19 -0
  24. package/packages/extension/src/multiselect-list.ts +6 -2
  25. package/packages/extension/src/multiselect-polyfill.ts +2 -2
  26. package/packages/extension/src/openspec-cli-shim.ts +1 -1
  27. package/packages/extension/src/path-gate/decide.ts +15 -41
  28. package/packages/extension/src/path-gate/grant-cache.ts +3 -1
  29. package/packages/extension/src/path-gate/handler.ts +51 -2
  30. package/packages/extension/src/path-gate/index.ts +12 -1
  31. package/packages/extension/src/path-gate/resolve.ts +6 -124
  32. package/packages/extension/src/path-gate/roots.ts +4 -1
  33. package/packages/extension/src/path-gate/suppression.ts +4 -1
  34. package/packages/extension/src/path-gate/yolo-link.ts +104 -0
  35. package/packages/extension/src/plugin-event-forward-registry.ts +200 -0
  36. package/packages/extension/src/project-trust.ts +119 -25
  37. package/packages/extension/src/prompt-expander.ts +5 -1
  38. package/packages/extension/src/prompt-meta.ts +64 -0
  39. package/packages/extension/src/provider-register.ts +87 -20
  40. package/packages/extension/src/role-manager.ts +5 -4
  41. package/packages/extension/src/server-auto-start.ts +12 -5
  42. package/packages/extension/src/server-launcher.ts +11 -13
  43. package/packages/extension/src/session-move.ts +19 -0
  44. package/packages/extension/src/session-sync.ts +31 -38
  45. package/packages/extension/src/spawn-token.ts +46 -0
  46. package/packages/extension/src/stream-forward-buffer.ts +161 -0
  47. package/packages/extension/src/subagent-frame-buffer.ts +6 -2
  48. package/packages/extension/src/subagent-tick-throttle.ts +3 -1
  49. package/packages/extension/src/vault-delivery.ts +394 -0
  50. package/packages/extension/src/vault-forwarder.ts +128 -0
  51. package/packages/extension/src/vault-masker.ts +165 -0
  52. package/packages/extension/src/vault-redaction.ts +181 -0
  53. package/packages/extension/src/vcs-info.ts +5 -2
  54. package/packages/server/bin/pi-dashboard.mjs +26 -89
  55. package/packages/server/package.json +29 -15
  56. package/packages/server/src/access/access-grants.ts +18 -0
  57. package/packages/server/src/access/agent-confirm-registry.ts +31 -13
  58. package/packages/server/src/access/agent-grant.ts +1 -1
  59. package/packages/server/src/access/agent-yolo.ts +91 -0
  60. package/packages/server/src/access/containment-gate.ts +28 -1
  61. package/packages/server/src/access/cwd-admission-log.ts +46 -0
  62. package/packages/server/src/access/cwd-verdict.ts +144 -0
  63. package/packages/server/src/access/grant-coordinator.ts +3 -1
  64. package/packages/server/src/access/pi-trust-mirror-service.ts +374 -0
  65. package/packages/server/src/access/planes.ts +10 -1
  66. package/packages/server/src/access/refusal-ledger.ts +6 -6
  67. package/packages/server/src/access/yolo-session.ts +73 -12
  68. package/packages/server/src/acp-bridge/acp-connection.ts +225 -0
  69. package/packages/server/src/acp-bridge/acp-restore.ts +41 -0
  70. package/packages/server/src/acp-bridge/acp-session-adapter.ts +544 -0
  71. package/packages/server/src/acp-bridge/child-env.ts +73 -0
  72. package/packages/server/src/acp-bridge/event-log.ts +194 -0
  73. package/packages/server/src/acp-bridge/gateway-client.ts +136 -0
  74. package/packages/server/src/acp-bridge/local-bridge-socket.ts +67 -0
  75. package/packages/server/src/acp-bridge/local-host.ts +132 -0
  76. package/packages/server/src/acp-bridge/main.ts +118 -0
  77. package/packages/server/src/acp-bridge/models.ts +33 -0
  78. package/packages/server/src/acp-bridge/permission-bridge.ts +106 -0
  79. package/packages/server/src/acp-bridge/server-requests.ts +136 -0
  80. package/packages/server/src/acp-bridge/session-state.ts +127 -0
  81. package/packages/server/src/addons/addon-toggle-restore.ts +110 -0
  82. package/packages/server/src/addons/addons-catalog.ts +408 -0
  83. package/packages/server/src/addons/addons-folder-service.ts +347 -0
  84. package/packages/server/src/addons/addons-folder.ts +310 -0
  85. package/packages/server/src/addons/addons-service.ts +470 -0
  86. package/packages/server/src/addons/package-contents.ts +99 -0
  87. package/packages/server/src/addons/settings-entries.ts +120 -0
  88. package/packages/server/src/attachments/fit-worker-pool.ts +12 -17
  89. package/packages/server/src/auth/approval-refusal.ts +87 -0
  90. package/packages/server/src/auth/auth-plugin.ts +292 -79
  91. package/packages/server/src/auth/auth.ts +78 -7
  92. package/packages/server/src/auth/bearer-auth.ts +23 -1
  93. package/packages/server/src/auth/cors-origin.ts +10 -0
  94. package/packages/server/src/auth/csp.ts +6 -0
  95. package/packages/server/src/auth/host-admission.ts +26 -0
  96. package/packages/server/src/auth/host-gate.ts +6 -1
  97. package/packages/server/src/auth/local-credential.ts +258 -0
  98. package/packages/server/src/auth/local-proof.ts +7 -4
  99. package/packages/server/src/auth/local-token.ts +16 -0
  100. package/packages/server/src/auth/localhost-guard.ts +251 -8
  101. package/packages/server/src/auth/network-trust-telemetry.ts +126 -0
  102. package/packages/server/src/auth/node-guard.ts +43 -0
  103. package/packages/server/src/auth/operate-required.ts +126 -0
  104. package/packages/server/src/auth/passkey/challenge-store.ts +90 -0
  105. package/packages/server/src/auth/passkey/passkey-log.ts +34 -0
  106. package/packages/server/src/auth/passkey/passkey-pages.ts +173 -0
  107. package/packages/server/src/auth/passkey/passkey-routes.ts +224 -0
  108. package/packages/server/src/auth/passkey/passkey-service.ts +247 -0
  109. package/packages/server/src/auth/passkey/phone-signin.ts +211 -0
  110. package/packages/server/src/auth/passkey/requester.ts +83 -0
  111. package/packages/server/src/auth/passkey/rp-context.ts +98 -0
  112. package/packages/server/src/auth/passkey/user-directory.ts +348 -0
  113. package/packages/server/src/auth/pi-legacy-credentials.ts +321 -0
  114. package/packages/server/src/auth/provider-auth-registry.ts +35 -1
  115. package/packages/server/src/auth/provider-auth-storage.ts +55 -8
  116. package/packages/server/src/auth/radius-override.ts +13 -0
  117. package/packages/server/src/auth/route-tier-gate.ts +27 -11
  118. package/packages/server/src/auth/runtime-provider-catalogue.ts +107 -0
  119. package/packages/server/src/auth/scan-legacy-provider-ids.ts +80 -0
  120. package/packages/server/src/auth/serve-app-host.ts +97 -0
  121. package/packages/server/src/auth/trust-mode-boot.ts +93 -0
  122. package/packages/server/src/auth/trust-mode.ts +83 -0
  123. package/packages/server/src/auto-name-outcome-store.ts +4 -1
  124. package/packages/server/src/browse.ts +114 -2
  125. package/packages/server/src/browser-handlers/acp-guard.ts +79 -0
  126. package/packages/server/src/browser-handlers/directory-handler.ts +128 -6
  127. package/packages/server/src/browser-handlers/session-action-handler.ts +129 -62
  128. package/packages/server/src/browser-handlers/session-meta-handler.ts +16 -6
  129. package/packages/server/src/browser-handlers/spawn-choice.ts +99 -0
  130. package/packages/server/src/cli.ts +883 -97
  131. package/packages/server/src/config-api.ts +143 -1
  132. package/packages/server/src/config-snapshot.ts +5 -0
  133. package/packages/server/src/directory-service.ts +435 -32
  134. package/packages/server/src/embed-lifecycle/caps.ts +35 -4
  135. package/packages/server/src/embed-lifecycle/embed-lifecycle-controller.ts +45 -4
  136. package/packages/server/src/embed-lifecycle/idle-reaper.ts +195 -20
  137. package/packages/server/src/embed-lifecycle/lifecycle-metrics.ts +38 -0
  138. package/packages/server/src/embed-lifecycle/plugin-session-close.ts +123 -0
  139. package/packages/server/src/embed-lifecycle/quiescence.ts +29 -3
  140. package/packages/server/src/embed-lifecycle/reclaim-give-up.ts +54 -0
  141. package/packages/server/src/event-wiring.ts +208 -35
  142. package/packages/server/src/file-watch-manager.ts +187 -39
  143. package/packages/server/src/git-worktree/git-operations.ts +16 -5
  144. package/packages/server/src/git-worktree/worktree-init-trust.ts +48 -5
  145. package/packages/server/src/git-worktree/worktree-init.ts +7 -56
  146. package/packages/server/src/identity/host-resources.ts +3 -0
  147. package/packages/server/src/identity/http-road-classification.ts +18 -0
  148. package/packages/server/src/identity/identity-registration-tracker.ts +4 -1
  149. package/packages/server/src/identity/plugin-identity.ts +19 -0
  150. package/packages/server/src/identity/policy-registry.ts +4 -1
  151. package/packages/server/src/identity/resolver-registry.ts +12 -3
  152. package/packages/server/src/identity/ws-message-scope.ts +9 -0
  153. package/packages/server/src/identity/ws-road-classification.ts +9 -0
  154. package/packages/server/src/known-server-moves.ts +175 -0
  155. package/packages/server/src/lib/browse-roots.ts +36 -0
  156. package/packages/server/src/lib/digest-gate.ts +82 -0
  157. package/packages/server/src/lib/file-write-lock.ts +24 -0
  158. package/packages/server/src/lib/folder-project.ts +439 -0
  159. package/packages/server/src/lib/purify.ts +13 -5
  160. package/packages/server/src/lib/writable-handler-target.ts +66 -0
  161. package/packages/server/src/lib/writable-md-target.ts +12 -1
  162. package/packages/server/src/lifecycle/classify-dashboard-port.ts +134 -0
  163. package/packages/server/src/lifecycle/home-lock.ts +344 -130
  164. package/packages/server/src/lifecycle/home-rendezvous.ts +41 -11
  165. package/packages/server/src/lifecycle/recovery-server.ts +77 -1
  166. package/packages/server/src/lifecycle/stop-ownership.ts +97 -11
  167. package/packages/server/src/live-server/live-capability.ts +254 -0
  168. package/packages/server/src/live-server/live-server-proxy.ts +173 -26
  169. package/packages/server/src/metrics/eventloop-spike-metrics.ts +2 -2
  170. package/packages/server/src/model-proxy/internal-auth-storage.ts +27 -26
  171. package/packages/server/src/model-proxy/internal-registry.ts +6 -0
  172. package/packages/server/src/model-proxy/server-model-runtime.ts +6 -0
  173. package/packages/server/src/openspec/openspec-change-watcher.ts +109 -16
  174. package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +132 -0
  175. package/packages/server/src/openspec/openspec-poll-worker-pool.ts +90 -35
  176. package/packages/server/src/openspec/openspec-poll-worker.ts +200 -44
  177. package/packages/server/src/openspec/proposal-attach-naming.ts +5 -3
  178. package/packages/server/src/openspec/readiness.ts +9 -0
  179. package/packages/server/src/openspec/workflow-schema.ts +1128 -0
  180. package/packages/server/src/package/installed-package-enricher.ts +38 -3
  181. package/packages/server/src/package/package-health-scanner.ts +133 -0
  182. package/packages/server/src/package/package-manager-wrapper.ts +18 -2
  183. package/packages/server/src/package/provider-catalogue-cache.ts +17 -3
  184. package/packages/server/src/package/provider-probe.ts +5 -3
  185. package/packages/server/src/pairing/browser-gateway.ts +108 -8
  186. package/packages/server/src/pairing/knock-admission.ts +277 -0
  187. package/packages/server/src/pairing/pairing.ts +154 -27
  188. package/packages/server/src/pairing/subagent-resync-routing.ts +4 -1
  189. package/packages/server/src/pairing/ws-tier-gate.ts +34 -0
  190. package/packages/server/src/peer-servers.ts +77 -0
  191. package/packages/server/src/pending/pending-plugin-ref-registry.ts +57 -2
  192. package/packages/server/src/persistence/boot-state.ts +48 -1
  193. package/packages/server/src/persistence/memory-event-store.ts +216 -237
  194. package/packages/server/src/persistence/meta-persistence.ts +12 -1
  195. package/packages/server/src/persistence/preferences-store.ts +116 -7
  196. package/packages/server/src/pi/bridge-upgrade-auth.ts +32 -21
  197. package/packages/server/src/pi/folder-commands.ts +141 -0
  198. package/packages/server/src/pi/gateway-socket-bind.ts +9 -3
  199. package/packages/server/src/pi/gateway-transport-policy.ts +13 -0
  200. package/packages/server/src/pi/host-project-trust.ts +158 -33
  201. package/packages/server/src/pi/pi-gateway.ts +93 -9
  202. package/packages/server/src/pi/pi-resource-scanner.ts +15 -0
  203. package/packages/server/src/pi/resource-activation-toggle.ts +6 -0
  204. package/packages/server/src/pi/resource-toggle-trust.ts +34 -2
  205. package/packages/server/src/pi/session-skill-registry.ts +13 -3
  206. package/packages/server/src/pi/settings-write-lock.ts +32 -0
  207. package/packages/server/src/pi/trust-challenges.ts +38 -0
  208. package/packages/server/src/pi-agent-settings.ts +701 -100
  209. package/packages/server/src/pi-settings-themes.ts +104 -0
  210. package/packages/server/src/questions/brief-generator.ts +138 -0
  211. package/packages/server/src/questions/brief-model.ts +55 -0
  212. package/packages/server/src/questions/brief-policy.ts +36 -0
  213. package/packages/server/src/questions/brief-prompt.ts +92 -0
  214. package/packages/server/src/questions/brief-runtime.ts +50 -0
  215. package/packages/server/src/questions/question-answer.ts +55 -0
  216. package/packages/server/src/questions/question-broadcast.ts +106 -0
  217. package/packages/server/src/questions/question-files.ts +128 -0
  218. package/packages/server/src/questions/question-routes.ts +126 -0
  219. package/packages/server/src/questions/question-snapshot.ts +150 -0
  220. package/packages/server/src/questions/question-stack.ts +57 -0
  221. package/packages/server/src/questions/question-store.ts +477 -0
  222. package/packages/server/src/routes/access-prompt-routes.ts +5 -3
  223. package/packages/server/src/routes/access-routes.ts +123 -5
  224. package/packages/server/src/routes/acme-routes.ts +190 -0
  225. package/packages/server/src/routes/acp-routes.ts +16 -0
  226. package/packages/server/src/routes/addons-routes.ts +221 -0
  227. package/packages/server/src/routes/file-routes.ts +366 -75
  228. package/packages/server/src/routes/file-write-binary-routes.ts +473 -0
  229. package/packages/server/src/routes/folder-project-routes.ts +99 -0
  230. package/packages/server/src/routes/git-routes.ts +17 -2
  231. package/packages/server/src/routes/known-servers-routes.ts +333 -53
  232. package/packages/server/src/routes/live-server-routes.ts +72 -4
  233. package/packages/server/src/routes/local-proof-routes.ts +12 -7
  234. package/packages/server/src/routes/mermaid-repair-routes.ts +254 -0
  235. package/packages/server/src/routes/model-proxy-routes.ts +4 -2
  236. package/packages/server/src/routes/openspec-routes.ts +270 -40
  237. package/packages/server/src/routes/package-health-routes.ts +140 -0
  238. package/packages/server/src/routes/package-routes.ts +28 -1
  239. package/packages/server/src/routes/pairing-routes.ts +158 -24
  240. package/packages/server/src/routes/pi-retry-routes.ts +18 -2
  241. package/packages/server/src/routes/pi-settings-routes.ts +264 -0
  242. package/packages/server/src/routes/plugin-activation-routes.ts +87 -27
  243. package/packages/server/src/routes/provider-auth-routes.ts +22 -5
  244. package/packages/server/src/routes/provider-routes.ts +29 -0
  245. package/packages/server/src/routes/resource-activation-routes.ts +16 -32
  246. package/packages/server/src/routes/session-routes.ts +49 -5
  247. package/packages/server/src/routes/system-routes.ts +207 -23
  248. package/packages/server/src/routes/tls-routes.ts +55 -0
  249. package/packages/server/src/routes/user-routes.ts +192 -0
  250. package/packages/server/src/runtime-overlay/runtime-stager.ts +15 -2
  251. package/packages/server/src/runtime-overlay/runtime-update-checker.ts +11 -2
  252. package/packages/server/src/server.ts +919 -139
  253. package/packages/server/src/services/attached-driver.ts +175 -0
  254. package/packages/server/src/services/change-notifier.ts +55 -0
  255. package/packages/server/src/services/cli-service.ts +450 -0
  256. package/packages/server/src/services/command-runner.ts +92 -0
  257. package/packages/server/src/services/definitions-store.ts +121 -0
  258. package/packages/server/src/services/driver.ts +112 -0
  259. package/packages/server/src/services/health.ts +94 -0
  260. package/packages/server/src/services/leases.ts +117 -0
  261. package/packages/server/src/services/log-text.ts +97 -0
  262. package/packages/server/src/services/native-driver.ts +283 -0
  263. package/packages/server/src/services/oci-driver.ts +590 -0
  264. package/packages/server/src/services/output-capture.ts +183 -0
  265. package/packages/server/src/services/paths.ts +82 -0
  266. package/packages/server/src/services/ports.ts +26 -0
  267. package/packages/server/src/services/routes.ts +140 -0
  268. package/packages/server/src/services/runtime-detect.ts +108 -0
  269. package/packages/server/src/services/secret-delivery.ts +61 -0
  270. package/packages/server/src/services/secrets-resolver.ts +145 -0
  271. package/packages/server/src/services/secrets-store.ts +137 -0
  272. package/packages/server/src/services/service-manager.ts +1565 -0
  273. package/packages/server/src/services/start-record.ts +66 -0
  274. package/packages/server/src/services/state-machine.ts +241 -0
  275. package/packages/server/src/session/archive-sweeper.ts +92 -3
  276. package/packages/server/src/session/custom-event-group-matcher.ts +4 -3
  277. package/packages/server/src/session/in-flight-tool-calls.ts +74 -0
  278. package/packages/server/src/session/memory-session-manager.ts +53 -0
  279. package/packages/server/src/session/name-provenance.ts +102 -0
  280. package/packages/server/src/session/open-tool-calls.ts +15 -6
  281. package/packages/server/src/session/session-api.ts +47 -12
  282. package/packages/server/src/session/session-archive.ts +56 -4
  283. package/packages/server/src/session/session-diff-cache.ts +11 -4
  284. package/packages/server/src/session/session-load-worker-pool.ts +4 -3
  285. package/packages/server/src/session/session-scanner.ts +73 -3
  286. package/packages/server/src/session/session-to-meta.ts +15 -0
  287. package/packages/server/src/spawn-process/abort-spawned-run.ts +55 -0
  288. package/packages/server/src/spawn-process/acp-spawn.ts +131 -0
  289. package/packages/server/src/spawn-process/process-manager.ts +164 -30
  290. package/packages/server/src/spawn-process/restart-helper.ts +9 -8
  291. package/packages/server/src/spawn-process/server-pid.ts +16 -7
  292. package/packages/server/src/spawn-process/session-terminator.ts +218 -0
  293. package/packages/server/src/spawn-process/spawn-env-contributors.ts +159 -0
  294. package/packages/server/src/spawn-process/spawn-register-watchdog.ts +10 -1
  295. package/packages/server/src/terminal/terminal-manager.ts +67 -1
  296. package/packages/server/src/tls/cert-files.ts +228 -0
  297. package/packages/server/src/tls/cert-manager.ts +703 -0
  298. package/packages/server/src/tls/cert-store.ts +69 -0
  299. package/packages/server/src/tls/source-registry.ts +71 -0
  300. package/packages/server/src/tls/sources/acme/accounts.ts +76 -0
  301. package/packages/server/src/tls/sources/acme/acme-source.ts +508 -0
  302. package/packages/server/src/tls/sources/acme/config-projection.ts +34 -0
  303. package/packages/server/src/tls/sources/acme/credentials.ts +185 -0
  304. package/packages/server/src/tls/sources/acme/dns.ts +303 -0
  305. package/packages/server/src/tls/sources/acme/e2e-overrides.ts +49 -0
  306. package/packages/server/src/tls/sources/acme/entry.ts +180 -0
  307. package/packages/server/src/tls/sources/acme/gc.ts +78 -0
  308. package/packages/server/src/tls/sources/acme/runtime.ts +51 -0
  309. package/packages/server/src/tls/sources/acme/solvers/acme-dns.ts +154 -0
  310. package/packages/server/src/tls/sources/acme/solvers/cloudflare.ts +147 -0
  311. package/packages/server/src/tls/sources/acme/types.ts +72 -0
  312. package/packages/server/src/tls/sources/tailscale-cert.ts +172 -0
  313. package/packages/server/src/tls/tls-config-validation.ts +92 -0
  314. package/packages/server/src/tls/tls-listener.ts +351 -0
  315. package/packages/server/src/tls/types.ts +80 -0
  316. package/packages/server/src/tunnel/tunnel-block-events.ts +4 -1
  317. package/packages/server/src/tunnel/tunnel-core.ts +4 -1
  318. package/packages/server/src/tunnel/tunnel-endpoints.ts +4 -0
  319. package/packages/server/src/tunnel-providers/tailscale.ts +27 -6
  320. package/packages/server/src/vault/vault-bindings.ts +101 -0
  321. package/packages/server/src/vault/vault-delivery-hub.ts +294 -0
  322. package/packages/server/src/vault/vault-grants.ts +260 -0
  323. package/packages/server/src/vault/vault-import.ts +161 -0
  324. package/packages/server/src/vault/vault-permissions.ts +39 -0
  325. package/packages/server/src/vault/vault-plugin-read.ts +64 -0
  326. package/packages/server/src/vault/vault-projects.ts +156 -0
  327. package/packages/server/src/vault/vault-routes.ts +277 -0
  328. package/packages/server/src/vault/vault-store.ts +371 -0
  329. package/packages/shared/package.json +5 -2
  330. package/packages/shared/src/acp/acp-config.ts +123 -0
  331. package/packages/shared/src/acp/normalize-v1.ts +92 -0
  332. package/packages/shared/src/acp/paths.ts +36 -0
  333. package/packages/shared/src/acp/to-dashboard-events.ts +533 -0
  334. package/packages/shared/src/acp/update-model.ts +574 -0
  335. package/packages/shared/src/anthropic-messages-source.ts +8 -0
  336. package/packages/shared/src/bind-reachability.ts +21 -2
  337. package/packages/shared/src/boot-state.ts +6 -0
  338. package/packages/shared/src/browser-host-identity.ts +49 -0
  339. package/packages/shared/src/browser-host-ipc.ts +107 -0
  340. package/packages/shared/src/browser-protocol.ts +385 -71
  341. package/packages/shared/src/canonical-subject.ts +27 -2
  342. package/packages/shared/src/card-sections.ts +185 -1
  343. package/packages/shared/src/chrome-profiles.ts +188 -0
  344. package/packages/shared/src/config.ts +473 -26
  345. package/packages/shared/src/custom-event-groups.ts +5 -2
  346. package/packages/shared/src/cwd-guard.ts +381 -1
  347. package/packages/shared/src/dashboard-paths.ts +12 -0
  348. package/packages/shared/src/dashboard-plugin/editor-pane-tab.ts +26 -0
  349. package/packages/shared/src/dashboard-plugin/file-handler.ts +71 -0
  350. package/packages/shared/src/dashboard-plugin/index.ts +7 -3
  351. package/packages/shared/src/dashboard-plugin/manifest-types.ts +106 -2
  352. package/packages/shared/src/dashboard-plugin/project-identity.ts +42 -0
  353. package/packages/shared/src/dashboard-plugin/project-markers.ts +60 -0
  354. package/packages/shared/src/dashboard-plugin/slot-props.ts +95 -0
  355. package/packages/shared/src/dashboard-plugin/slot-types.ts +64 -4
  356. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +22 -3
  357. package/packages/shared/src/dashboard-starter.ts +30 -0
  358. package/packages/shared/src/display-name.ts +42 -0
  359. package/packages/shared/src/doctor-core.ts +25 -107
  360. package/packages/shared/src/enabled-models-match.ts +47 -0
  361. package/packages/shared/src/event-forward-declaration.ts +187 -0
  362. package/packages/shared/src/file-kind.ts +54 -2
  363. package/packages/shared/src/git-worktree-helpers.ts +8 -4
  364. package/packages/shared/src/grammar-types.ts +3 -1
  365. package/packages/shared/src/host-admission.ts +2 -1
  366. package/packages/shared/src/host-port.ts +34 -0
  367. package/packages/shared/src/launcher-origin.ts +26 -0
  368. package/packages/shared/src/local-credential-proof.ts +219 -0
  369. package/packages/shared/src/markup-repair/asciidoc.ts +130 -0
  370. package/packages/shared/src/markup-repair/types.ts +13 -0
  371. package/packages/shared/src/md-table-cell.ts +11 -0
  372. package/packages/shared/src/mdns-discovery.ts +392 -42
  373. package/packages/shared/src/models-json-reader.ts +6 -0
  374. package/packages/shared/src/openspec-design-evidence.ts +25 -1
  375. package/packages/shared/src/openspec-poller.ts +210 -9
  376. package/packages/shared/src/openspec-status-all.ts +393 -0
  377. package/packages/shared/src/operate-required.ts +29 -0
  378. package/packages/shared/src/pairing-knock-client.ts +261 -0
  379. package/packages/shared/src/pairing-knock.ts +71 -0
  380. package/packages/shared/src/pairing-refusal.ts +32 -0
  381. package/packages/shared/src/path-containment-guard-name.ts +8 -0
  382. package/packages/shared/src/pi-settings-keys.ts +9 -0
  383. package/packages/shared/src/pi-settings-schema.ts +285 -0
  384. package/packages/shared/src/pi-trust-mirror-snapshot.ts +200 -0
  385. package/packages/shared/src/pi-trust-mirror-types.ts +57 -0
  386. package/packages/shared/src/pi-trust-mirror.ts +328 -0
  387. package/packages/shared/src/platform/binary-lookup.ts +2 -194
  388. package/packages/shared/src/platform/git.ts +204 -4
  389. package/packages/shared/src/platform/native-ts-hooks.mjs +93 -40
  390. package/packages/shared/src/platform/native-ts-register.mjs +22 -10
  391. package/packages/shared/src/platform/native-ts-tier.d.mts +1 -0
  392. package/packages/shared/src/platform/native-ts-tier.mjs +17 -0
  393. package/packages/shared/src/platform/node-spawn.ts +1 -2
  394. package/packages/shared/src/platform/openspec.ts +129 -31
  395. package/packages/shared/src/platform/process-scan.ts +199 -1
  396. package/packages/shared/src/platform/process.ts +51 -0
  397. package/packages/shared/src/platform/runner.ts +46 -2
  398. package/packages/shared/src/platform/spawn-mechanism.ts +14 -2
  399. package/packages/shared/src/platform/ts-loader-select.d.mts +1 -7
  400. package/packages/shared/src/platform/ts-loader-select.mjs +14 -43
  401. package/packages/shared/src/plugin-bridge-register.ts +24 -1
  402. package/packages/shared/src/project-name.ts +42 -0
  403. package/packages/shared/src/prompt-answer.ts +183 -0
  404. package/packages/shared/src/protocol.ts +133 -8
  405. package/packages/shared/src/question-types.ts +73 -0
  406. package/packages/shared/src/recommended-extensions.ts +80 -23
  407. package/packages/shared/src/recovery-timing.ts +12 -0
  408. package/packages/shared/src/redaction.ts +50 -0
  409. package/packages/shared/src/rest-api.ts +484 -1
  410. package/packages/shared/src/role-config-disk.ts +23 -0
  411. package/packages/shared/src/role-schema.ts +79 -0
  412. package/packages/shared/src/route-tiers.ts +127 -0
  413. package/packages/shared/src/runtime-overlay/materialize-plugins.d.mts +17 -0
  414. package/packages/shared/src/runtime-overlay/materialize-plugins.mjs +119 -8
  415. package/packages/shared/src/server-identity.ts +51 -15
  416. package/packages/shared/src/server-launcher.ts +12 -33
  417. package/packages/shared/src/server-pinning.ts +81 -0
  418. package/packages/shared/src/services/offers.ts +114 -0
  419. package/packages/shared/src/services/schema.ts +628 -0
  420. package/packages/shared/src/services/status.ts +169 -0
  421. package/packages/shared/src/session-meta.ts +59 -2
  422. package/packages/shared/src/session-name.ts +8 -0
  423. package/packages/shared/src/skill-block-parser.ts +14 -0
  424. package/packages/shared/src/source-matching.ts +5 -1
  425. package/packages/shared/src/state-replay.ts +19 -0
  426. package/packages/shared/src/terminal-safe.ts +24 -0
  427. package/packages/shared/src/tls-status.ts +69 -0
  428. package/packages/shared/src/tool-path-resolve.ts +243 -0
  429. package/packages/shared/src/tool-registry/definitions.ts +26 -4
  430. package/packages/shared/src/tool-registry/index.ts +2 -2
  431. package/packages/shared/src/tool-registry/pi-tools.ts +32 -3
  432. package/packages/shared/src/tunnel-provider.ts +3 -2
  433. package/packages/shared/src/types.ts +104 -9
  434. package/packages/shared/src/vault-delivery.ts +73 -0
  435. package/packages/shared/src/vault-origin.ts +51 -0
  436. package/packages/shared/src/vault-project-key.ts +53 -0
  437. package/packages/shared/src/worktree-init-hook.ts +69 -0
  438. package/packages/shared/src/ws-message-tiers.ts +135 -0
  439. package/tsconfig.base.json +1 -0
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Snapshot + trust-store readers and the snapshot coverage check, shared by the
3
+ * bridge (`project_trust` handler — no server contact) and the server's
4
+ * `host.isProjectTrusted`, so both decide from the SAME bytes with the SAME rules.
5
+ *
6
+ * Everything here is read-only and non-throwing: any doubt yields "no coverage"
7
+ * or a reason code, never a throw and never trust. Nothing is cached across
8
+ * calls (bridge-decomposition rule: no module-level caches).
9
+ *
10
+ * See change: mirror-dashboard-trust-to-pi.
11
+ */
12
+ import * as fs from "node:fs";
13
+ import path from "node:path";
14
+ import { getDashboardConfigDir } from "./dashboard-paths.js";
15
+ import {
16
+ ancestorKeys,
17
+ identityMatches,
18
+ isCanonicalAbsolutePath,
19
+ piTrustKey,
20
+ statFolderIdentity,
21
+ } from "./pi-trust-mirror.js";
22
+ import type { MirrorWithheldReason, PiTrustSnapshot, PiTrustSnapshotEntry } from "./pi-trust-mirror-types.js";
23
+ import { hookDefHash, normalizeHook } from "./worktree-init-hook.js";
24
+
25
+ /** `~/.pi/dashboard/pi-trust-mirror.json` — server-written, bridge-read. */
26
+ export function piTrustMirrorSnapshotPath(): string {
27
+ return path.join(getDashboardConfigDir(), "pi-trust-mirror.json");
28
+ }
29
+
30
+ /** `~/.pi/dashboard/pi-trust-overrides.json` — per-entry "also trust in pi" choices. */
31
+ export function piTrustOverridesPath(): string {
32
+ return path.join(getDashboardConfigDir(), "pi-trust-overrides.json");
33
+ }
34
+
35
+ const SOURCE_KINDS = new Set(["worktreeInit", "workflow", "pinned", "folderWorkspaces", "accessGrants"]);
36
+
37
+ function validEntry(e: unknown): e is PiTrustSnapshotEntry {
38
+ if (!e || typeof e !== "object") return false;
39
+ const x = e as Record<string, unknown>;
40
+ return (
41
+ typeof x.key === "string" &&
42
+ path.isAbsolute(x.key) &&
43
+ typeof x.sourceKind === "string" &&
44
+ SOURCE_KINDS.has(x.sourceKind) &&
45
+ typeof x.dev === "string" &&
46
+ typeof x.ino === "string" &&
47
+ (x.birthtimeMs === undefined || typeof x.birthtimeMs === "number") &&
48
+ (x.configRoot === undefined || typeof x.configRoot === "string") &&
49
+ (x.hookHash === undefined || typeof x.hookHash === "string")
50
+ );
51
+ }
52
+
53
+ /** The snapshot, or `null` when absent, truncated, or not the expected shape. */
54
+ export function readPiTrustMirrorSnapshot(file: string = piTrustMirrorSnapshotPath()): PiTrustSnapshot | null {
55
+ try {
56
+ const parsed: unknown = JSON.parse(fs.readFileSync(file, "utf8"));
57
+ if (!parsed || typeof parsed !== "object") return null;
58
+ const p = parsed as Record<string, unknown>;
59
+ if (p.version !== 1 || typeof p.generation !== "number" || !Array.isArray(p.entries)) return null;
60
+ return { version: 1, generation: p.generation, entries: p.entries.filter(validEntry) };
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ export type PiTrustFileRead =
67
+ | { kind: "absent" }
68
+ | { kind: "unreadable" }
69
+ | { kind: "ok"; data: Record<string, boolean> };
70
+
71
+ /**
72
+ * pi's `trust.json` read WITHOUT its lock, with pi's own rules: a leading BOM is
73
+ * stripped, `null` values are absent, an absent file means nothing recorded, and
74
+ * any read/parse/shape failure (or a value other than true/false/null) is
75
+ * `unreadable`. Best-effort at read time — pi re-reads under its lock later.
76
+ */
77
+ export function readPiTrustFileLockless(agentDir: string): PiTrustFileRead {
78
+ const file = path.join(agentDir, "trust.json");
79
+ let raw: string;
80
+ try {
81
+ raw = fs.readFileSync(file, "utf8");
82
+ } catch (err) {
83
+ return (err as NodeJS.ErrnoException)?.code === "ENOENT" ? { kind: "absent" } : { kind: "unreadable" };
84
+ }
85
+ try {
86
+ const parsed: unknown = JSON.parse(raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw);
87
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return { kind: "unreadable" };
88
+ const data: Record<string, boolean> = {};
89
+ for (const [k, v] of Object.entries(parsed)) {
90
+ if (v === null) continue;
91
+ if (v !== true && v !== false) return { kind: "unreadable" };
92
+ data[k] = v;
93
+ }
94
+ return { kind: "ok", data };
95
+ } catch {
96
+ return { kind: "unreadable" };
97
+ }
98
+ }
99
+
100
+ /** pi's nearest recorded entry for `cwdKey` (walks `cwdKey` then its ancestors). */
101
+ export function nearestRecordedEntry(
102
+ data: Record<string, boolean>,
103
+ cwdKey: string,
104
+ ): { path: string; decision: boolean } | null {
105
+ for (const k of ancestorKeys(cwdKey)) {
106
+ const v = data[k];
107
+ if (v === true || v === false) return { path: k, decision: v };
108
+ }
109
+ return null;
110
+ }
111
+
112
+ /** Hash of the `worktreeInit` hook currently in `<configRoot>/.pi/settings.json`, or null. */
113
+ export function currentHookHash(configRoot: string): string | null {
114
+ try {
115
+ const parsed: unknown = JSON.parse(fs.readFileSync(path.join(configRoot, ".pi", "settings.json"), "utf8"));
116
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
117
+ const hook = normalizeHook((parsed as { worktreeInit?: unknown }).worktreeInit);
118
+ return hook ? hookDefHash(hook) : null;
119
+ } catch {
120
+ return null;
121
+ }
122
+ }
123
+
124
+ function isProjectRoot(dir: string): boolean {
125
+ if (!isCanonicalAbsolutePath(dir)) return false;
126
+ try {
127
+ return fs.existsSync(path.join(dir, ".git")) || fs.existsSync(path.join(dir, ".pi"));
128
+ } catch {
129
+ return false;
130
+ }
131
+ }
132
+
133
+ export type SnapshotCoverage =
134
+ | { covered: true; entry: PiTrustSnapshotEntry }
135
+ | { covered: false; reason?: MirrorWithheldReason };
136
+
137
+ /**
138
+ * Does a snapshot entry cover `cwd`? Walks the cwd key and its ancestors,
139
+ * nearest first; an entry applies only when its folder still has the recorded
140
+ * identity (dev + ino + birth time when recorded), a hook entry's hook still
141
+ * hashes to the recorded value, and an access-grant entry is still a project
142
+ * root. No entry at all → `{covered:false}` with no reason; the nearest
143
+ * rejected entry's reason is reported otherwise (for the bridge log).
144
+ */
145
+ export function coverSnapshot(
146
+ snapshot: PiTrustSnapshot | null,
147
+ cwdKey: string,
148
+ hooks: { currentHookHash?: (configRoot: string) => string | null } = {},
149
+ ): SnapshotCoverage {
150
+ if (!snapshot || snapshot.entries.length === 0) return { covered: false };
151
+ const byKey = groupByKey(snapshot.entries);
152
+ const hashOf = hooks.currentHookHash ?? currentHookHash;
153
+ let rejected: MirrorWithheldReason | undefined;
154
+ for (const k of ancestorKeys(cwdKey)) {
155
+ const list = byKey.get(k);
156
+ if (!list) continue;
157
+ const identity = statFolderIdentity(k);
158
+ for (const entry of list) {
159
+ const reason = entryRejection(entry, k, identity, hashOf);
160
+ if (!reason) return { covered: true, entry };
161
+ rejected ??= reason;
162
+ }
163
+ }
164
+ return { covered: false, ...(rejected ? { reason: rejected } : {}) };
165
+ }
166
+
167
+ function groupByKey(entries: readonly PiTrustSnapshotEntry[]): Map<string, PiTrustSnapshotEntry[]> {
168
+ const byKey = new Map<string, PiTrustSnapshotEntry[]>();
169
+ for (const e of entries) {
170
+ const list = byKey.get(e.key);
171
+ if (list) list.push(e);
172
+ else byKey.set(e.key, [e]);
173
+ }
174
+ return byKey;
175
+ }
176
+
177
+ /** Why a snapshot entry no longer applies at `folder`, or null when it still does. */
178
+ function entryRejection(
179
+ entry: PiTrustSnapshotEntry,
180
+ folder: string,
181
+ identity: ReturnType<typeof statFolderIdentity>,
182
+ hashOf: (configRoot: string) => string | null,
183
+ ): MirrorWithheldReason | null {
184
+ if (!identityMatches(entry, identity)) return "identity-mismatch";
185
+ if (entry.sourceKind === "worktreeInit" || entry.sourceKind === "workflow") {
186
+ const current = entry.configRoot ? hashOf(entry.configRoot) : null;
187
+ if (current === null || current !== entry.hookHash) return "hook-changed";
188
+ }
189
+ if (entry.sourceKind === "accessGrants" && !isProjectRoot(folder)) return "not-project-root";
190
+ return null;
191
+ }
192
+
193
+ /** `piTrustKey` that never throws: a bad/relative cwd yields `null`. */
194
+ export function safePiTrustKey(cwd: string, home: string): string | null {
195
+ try {
196
+ return piTrustKey(cwd, { home });
197
+ } catch {
198
+ return null;
199
+ }
200
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Browser-safe types for the dashboard-trust → pi mirror (no Node imports).
3
+ * See change: mirror-dashboard-trust-to-pi.
4
+ */
5
+
6
+ /** Durable trust source ids (mirrors `PiTrustMirrorSourceId` in config). */
7
+ export type MirrorSourceKind = "worktreeInit" | "workflow" | "pinned" | "folderWorkspaces" | "accessGrants";
8
+
9
+ /** Why an entry does not confer pi trust (Access page + bridge log vocabulary). */
10
+ export type MirrorIgnoreReason =
11
+ | "forbidden-folder"
12
+ | "not-project-root"
13
+ | "hook-changed"
14
+ | "source-off"
15
+ | "source-not-installed"
16
+ | "identity-mismatch"
17
+ | "choice-unreadable";
18
+
19
+ /** Every reason code the bridge may log when it withholds trust. */
20
+ export type MirrorWithheldReason =
21
+ | MirrorIgnoreReason
22
+ | "recorded-entry"
23
+ | "store-unreadable"
24
+ | "not-covered-session";
25
+
26
+ /** Readable label per ignore reason (Access page). */
27
+ export const MIRROR_REASON_LABELS: Record<MirrorIgnoreReason, string> = {
28
+ "forbidden-folder": "folder never mirrored (home, system, temp, secrets)",
29
+ "not-project-root": "not a project root (no .git or .pi)",
30
+ "hook-changed": "hook changed — re-approve",
31
+ "source-off": "source or entry opted out",
32
+ "source-not-installed": "source not installed",
33
+ "identity-mismatch": "folder changed since it was trusted",
34
+ "choice-unreadable": "per-entry choices unreadable",
35
+ };
36
+
37
+ /** One durable entry in `~/.pi/dashboard/pi-trust-mirror.json`. */
38
+ export interface PiTrustSnapshotEntry {
39
+ /** Canonical folder path in pi's trust-store key form. */
40
+ key: string;
41
+ sourceKind: MirrorSourceKind;
42
+ /** Device / inode as decimal strings (bigint-safe). */
43
+ dev: string;
44
+ ino: string;
45
+ /** Only when the filesystem reported one distinct from ctime at write time. */
46
+ birthtimeMs?: number;
47
+ /** worktreeInit/workflow: the configuration root whose hook is re-hashed. */
48
+ configRoot?: string;
49
+ hookHash?: string;
50
+ }
51
+
52
+ export interface PiTrustSnapshot {
53
+ version: 1;
54
+ /** Strictly increases on every rewrite. */
55
+ generation: number;
56
+ entries: PiTrustSnapshotEntry[];
57
+ }
@@ -0,0 +1,328 @@
1
+ /**
2
+ * Dashboard trust → pi `project_trust` mirror: the shared pure core.
3
+ *
4
+ * One folder decision (`decidePiTrust`) serves the bridge, `host.isProjectTrusted`
5
+ * and the toggle gate. `piTrustKey` reproduces pi's trust-store key form;
6
+ * `mirrorDenyRules` is a SEPARATE deny list from `forbidden-subjects` (it reuses
7
+ * its values read-only and never changes the grant-subject rules);
8
+ * `filterMirrorEntries` applies source/choice/deny/hook/project-root facts and
9
+ * explains every ignored entry with a reason code.
10
+ *
11
+ * Node-only (`node:fs`/`os`/`path`): the browser client imports the types from
12
+ * `pi-trust-mirror-types.ts` instead. Nothing here writes pi's `trust.json`.
13
+ *
14
+ * See change: mirror-dashboard-trust-to-pi.
15
+ */
16
+ import * as fs from "node:fs";
17
+ import os from "node:os";
18
+ import path from "node:path";
19
+ import type { PiTrustMirrorSourceId } from "./config.js";
20
+ import { forbiddenGrantSubjects, realpathNearestAncestor } from "./forbidden-subjects.js";
21
+ import type { MirrorIgnoreReason, MirrorSourceKind } from "./pi-trust-mirror-types.js";
22
+
23
+ export type { MirrorIgnoreReason, MirrorSourceKind, PiTrustSnapshot, PiTrustSnapshotEntry } from "./pi-trust-mirror-types.js";
24
+
25
+ // ── Key function ──────────────────────────────────────────────────────────
26
+
27
+ /**
28
+ * pi's trust-store key: `canonicalizePath(resolvePath(path))` with no options
29
+ * (no Unicode-space normalisation). `canonicalizePath` is `realpathSync` that
30
+ * returns the INPUT on failure (not nearest-ancestor), so a missing leaf keeps
31
+ * its lexical form. Tilde expands against the explicit `home`. Relative input
32
+ * throws — a bridge cwd must never silently resolve against `process.cwd()`.
33
+ */
34
+ export function piTrustKey(input: string, opts: { home: string }): string {
35
+ let p = input;
36
+ if (p === "~") p = opts.home;
37
+ else if (p.startsWith("~/") || (path.sep === "\\" && p.startsWith("~\\"))) p = path.join(opts.home, p.slice(2));
38
+ if (!path.isAbsolute(p)) throw new Error(`piTrustKey: relative path rejected: ${JSON.stringify(input)}`);
39
+ const resolved = path.resolve(p);
40
+ try {
41
+ return fs.realpathSync(resolved);
42
+ } catch {
43
+ return resolved;
44
+ }
45
+ }
46
+
47
+ /**
48
+ * True only for a canonical absolute path: no NUL, no `.`/`..` segments, already
49
+ * normalised. Snapshot keys and trust-store keys are always in this form, so
50
+ * anything else is refused before a filesystem probe rather than normalised.
51
+ */
52
+ export function isCanonicalAbsolutePath(p: unknown): p is string {
53
+ return (
54
+ typeof p === "string" &&
55
+ p.length > 0 &&
56
+ !p.includes("\0") &&
57
+ path.isAbsolute(p) &&
58
+ path.normalize(p) === p &&
59
+ !p.split(/[\\/]/).includes("..")
60
+ );
61
+ }
62
+
63
+ /** `key` itself, then each ancestor, up to the root. */
64
+ export function ancestorKeys(key: string): string[] {
65
+ const out: string[] = [];
66
+ let cur = key;
67
+ for (;;) {
68
+ out.push(cur);
69
+ const parent = path.dirname(cur);
70
+ if (parent === cur) return out;
71
+ cur = parent;
72
+ }
73
+ }
74
+
75
+ // ── Deny rules ────────────────────────────────────────────────────────────
76
+
77
+ export interface MirrorDenyEnv {
78
+ homedir?: string;
79
+ platform?: NodeJS.Platform;
80
+ env?: NodeJS.ProcessEnv;
81
+ }
82
+
83
+ export interface MirrorDenyRules {
84
+ /** Refused exactly (the folder itself, not its subtree). */
85
+ exact: string[];
86
+ /** Refused at and below. */
87
+ subtree: string[];
88
+ }
89
+
90
+ const POSIX_BROAD_PARENTS = ["/Users", "/home", "/Volumes", "/private", "/var/tmp", "/mnt", "/media"];
91
+
92
+ /**
93
+ * The mirror's own deny list (design D2). `exact`: the grant-subject `whole`
94
+ * list (`/`, `$HOME`, system dirs) + every ancestor of `$HOME` + platform broad
95
+ * parents. `subtree`: the grant-subject `sensitive` list (`~/.ssh`, `~/.pi`) +
96
+ * `~/.aws`, `~/.gnupg`, `~/.kube`, `~/.docker`, temp dirs, `~/.cache`,
97
+ * `~/Downloads`. All canonicalised (real paths).
98
+ */
99
+ export function mirrorDenyRules(env: MirrorDenyEnv = {}): MirrorDenyRules {
100
+ const home = env.homedir ?? os.homedir();
101
+ const platform = env.platform ?? process.platform;
102
+ const windows = platform === "win32";
103
+ const p = windows ? path.win32 : path.posix;
104
+ const canon = (x: string): string => realpathNearestAncestor(p.resolve(x));
105
+ const grant = forbiddenGrantSubjects({ homedir: home, platform, env: env.env });
106
+ const realHome = canon(home);
107
+
108
+ const exact = [...grant.whole];
109
+ for (let cur = p.dirname(realHome); ; cur = p.dirname(cur)) {
110
+ exact.push(cur);
111
+ if (p.dirname(cur) === cur) break;
112
+ }
113
+ if (windows) {
114
+ const vars = env.env ?? process.env;
115
+ exact.push(p.join(vars.SystemDrive ? `${vars.SystemDrive}\\` : "C:\\", "Users"));
116
+ } else {
117
+ exact.push(...POSIX_BROAD_PARENTS.map(canon));
118
+ }
119
+
120
+ const tmpdirs = windows ? [os.tmpdir()] : [os.tmpdir(), "/tmp", "/private/tmp"];
121
+ const subtree = [
122
+ ...grant.sensitive,
123
+ ...[".aws", ".gnupg", ".kube", ".docker", ".cache", "Downloads"].map((d) => canon(p.join(home, d))),
124
+ ...tmpdirs.map(canon),
125
+ ];
126
+ return { exact: [...new Set(exact)], subtree: [...new Set(subtree)] };
127
+ }
128
+
129
+ function samePathStr(a: string, b: string, windows: boolean): boolean {
130
+ return windows ? a.toLowerCase() === b.toLowerCase() : a === b;
131
+ }
132
+
133
+ /** True when `key` is forbidden as a mirror entry, or lies inside a forbidden subtree. */
134
+ export function isMirrorDenied(key: string, rules: MirrorDenyRules, platform: NodeJS.Platform = process.platform): boolean {
135
+ const windows = platform === "win32";
136
+ const p = windows ? path.win32 : path.posix;
137
+ const real = realpathNearestAncestor(p.resolve(key));
138
+ if (rules.exact.some((f) => samePathStr(real, f, windows))) return true;
139
+ return rules.subtree.some((root) => {
140
+ if (samePathStr(real, root, windows)) return true;
141
+ const rel = p.relative(root, real);
142
+ return rel !== "" && !rel.startsWith("..") && !p.isAbsolute(rel);
143
+ });
144
+ }
145
+
146
+ // ── Entries, settings, filter ─────────────────────────────────────────────
147
+
148
+ export interface MirrorSettings {
149
+ enabled: boolean;
150
+ coverInteractive: boolean;
151
+ sources: Record<PiTrustMirrorSourceId, boolean>;
152
+ }
153
+
154
+ /** A source entry as read from a durable store, with the per-decision facts resolved. */
155
+ export interface MirrorCandidate {
156
+ sourceKind: MirrorSourceKind;
157
+ /** pi trust-store key form (canonical absolute path). */
158
+ key: string;
159
+ /** Stored per-entry choice; `undefined` = follows the source default. */
160
+ choice?: boolean;
161
+ /** worktreeInit/workflow: recorded hash vs the hook currently in `configRoot`. */
162
+ hookState?: "current" | "changed" | "unreadable";
163
+ /** accessGrants: the subject currently contains `.git` or `.pi`. */
164
+ projectRoot?: boolean;
165
+ /** Pass-through payload (configRoot, hookHash, ...) the caller needs after filtering. */
166
+ meta?: Record<string, unknown>;
167
+ }
168
+
169
+ export interface MirrorFilterFacts {
170
+ /** False when the per-entry choices file exists but cannot be read. */
171
+ choicesReadable: boolean;
172
+ /** `false` for a source whose producer is not installed (workflow before add-project-workflows). */
173
+ installed?: Partial<Record<MirrorSourceKind, boolean>>;
174
+ deny?: MirrorDenyRules;
175
+ platform?: NodeJS.Platform;
176
+ home?: string;
177
+ }
178
+
179
+ export interface MirrorIgnored {
180
+ entry: MirrorCandidate;
181
+ reason: MirrorIgnoreReason;
182
+ }
183
+
184
+ export interface MirrorFilterResult {
185
+ counted: MirrorCandidate[];
186
+ ignored: MirrorIgnored[];
187
+ }
188
+
189
+ /**
190
+ * Split candidates into counted and ignored-with-reason. Precedence of reasons:
191
+ * not installed → unreadable choice → forbidden folder → hook → project root →
192
+ * source/choice. An entry counts iff (source on ∧ choice≠false) ∨ choice=true.
193
+ */
194
+ export function filterMirrorEntries(
195
+ candidates: readonly MirrorCandidate[],
196
+ settings: Pick<MirrorSettings, "sources">,
197
+ facts: MirrorFilterFacts,
198
+ ): MirrorFilterResult {
199
+ const deny = facts.deny ?? mirrorDenyRules({ homedir: facts.home, platform: facts.platform });
200
+ const counted: MirrorCandidate[] = [];
201
+ const ignored: MirrorIgnored[] = [];
202
+ for (const entry of candidates) {
203
+ const reason = ignoreReason(entry, settings, facts, deny);
204
+ if (reason) ignored.push({ entry, reason });
205
+ else counted.push(entry);
206
+ }
207
+ return { counted, ignored };
208
+ }
209
+
210
+ function ignoreReason(
211
+ entry: MirrorCandidate,
212
+ settings: Pick<MirrorSettings, "sources">,
213
+ facts: MirrorFilterFacts,
214
+ deny: MirrorDenyRules,
215
+ ): MirrorIgnoreReason | null {
216
+ if (facts.installed?.[entry.sourceKind] === false) return "source-not-installed";
217
+ if (!facts.choicesReadable) return "choice-unreadable";
218
+ if (isMirrorDenied(entry.key, deny, facts.platform)) return "forbidden-folder";
219
+ if (entry.hookState === "changed" || entry.hookState === "unreadable") return "hook-changed";
220
+ if (entry.sourceKind === "accessGrants" && entry.projectRoot !== true) return "not-project-root";
221
+ const sourceOn = settings.sources[entry.sourceKind] === true;
222
+ const wanted = entry.choice === true || (sourceOn && entry.choice !== false);
223
+ return wanted ? null : "source-off";
224
+ }
225
+
226
+ // ── The shared folder decision ────────────────────────────────────────────
227
+
228
+ export type DefaultProjectTrust = "always" | "never" | "ask";
229
+
230
+ export type PiTrustSource =
231
+ | { kind: "implicit" }
232
+ | { kind: "recorded"; path: string }
233
+ | { kind: "dashboard"; sourceKind: MirrorSourceKind; entry: string }
234
+ | { kind: "default"; value: DefaultProjectTrust };
235
+
236
+ export interface PiTrustDecision {
237
+ trusted: boolean;
238
+ source: PiTrustSource;
239
+ }
240
+
241
+ export interface DecidePiTrustInput {
242
+ /** pi's own `hasTrustRequiringProjectResources(cwd)`; `false` ⇒ implicitly trusted. */
243
+ hasTrustRequiringResources: boolean;
244
+ /** pi's nearest recorded entry (true OR false), or null. */
245
+ recordedEntry: { path: string; decision: boolean } | null;
246
+ /** The counted dashboard entry covering the cwd, or null. */
247
+ mirrorEntry: { sourceKind: MirrorSourceKind; key: string } | null;
248
+ /** `piTrustMirror.enabled`. */
249
+ mirrorEnabled: boolean;
250
+ piDefault: DefaultProjectTrust;
251
+ }
252
+
253
+ /**
254
+ * implicit → pi's recorded entry → dashboard trust (even over `never`) →
255
+ * `defaultProjectTrust`. Never writes anything. CLI `--approve/--no-approve`
256
+ * is pi's and outside this core.
257
+ */
258
+ export function decidePiTrust(input: DecidePiTrustInput): PiTrustDecision {
259
+ if (!input.hasTrustRequiringResources) return { trusted: true, source: { kind: "implicit" } };
260
+ if (input.recordedEntry) {
261
+ return { trusted: input.recordedEntry.decision, source: { kind: "recorded", path: input.recordedEntry.path } };
262
+ }
263
+ if (input.mirrorEnabled && input.mirrorEntry) {
264
+ return {
265
+ trusted: true,
266
+ source: { kind: "dashboard", sourceKind: input.mirrorEntry.sourceKind, entry: input.mirrorEntry.key },
267
+ };
268
+ }
269
+ return { trusted: input.piDefault === "always", source: { kind: "default", value: input.piDefault } };
270
+ }
271
+
272
+ /** Human label for a source kind (UI + toggle prompt). */
273
+ export const MIRROR_SOURCE_LABELS: Record<MirrorSourceKind, string> = {
274
+ worktreeInit: "worktree-init trust",
275
+ workflow: "workflow trust",
276
+ pinned: "pinned folder",
277
+ folderWorkspaces: "folder workspace",
278
+ accessGrants: "access grant",
279
+ };
280
+
281
+ // ── Covering entry + identity ─────────────────────────────────────────────
282
+
283
+ /** Nearest entry whose key equals the cwd key or an ancestor of it. */
284
+ export function findCoveringEntry<T extends { key: string }>(entries: readonly T[], cwdKey: string): T | null {
285
+ if (entries.length === 0) return null;
286
+ const byKey = new Map<string, T>();
287
+ for (const e of entries) if (!byKey.has(e.key)) byKey.set(e.key, e);
288
+ for (const k of ancestorKeys(cwdKey)) {
289
+ const hit = byKey.get(k);
290
+ if (hit) return hit;
291
+ }
292
+ return null;
293
+ }
294
+
295
+ export interface FolderIdentity {
296
+ dev: string;
297
+ ino: string;
298
+ birthtimeMs?: number;
299
+ }
300
+
301
+ /**
302
+ * Device + inode (as strings; bigint-safe) of `dir`, and its birth time only
303
+ * when the filesystem reported one distinct from the change time. `null` when
304
+ * the folder cannot be stat'ed.
305
+ */
306
+ export function statFolderIdentity(dir: string): FolderIdentity | null {
307
+ if (!isCanonicalAbsolutePath(dir)) return null;
308
+ try {
309
+ const st = fs.statSync(dir, { bigint: true });
310
+ const identity: FolderIdentity = { dev: st.dev.toString(), ino: st.ino.toString() };
311
+ const birth = Number(st.birthtimeMs);
312
+ if (Number.isFinite(birth) && birth > 0 && st.birthtimeMs !== st.ctimeMs) identity.birthtimeMs = birth;
313
+ return identity;
314
+ } catch {
315
+ return null;
316
+ }
317
+ }
318
+
319
+ /** Observed identity equals the entry's: dev + ino, and birth time when the entry recorded one. */
320
+ export function identityMatches(
321
+ entry: { dev: string; ino: string; birthtimeMs?: number },
322
+ observed: FolderIdentity | null,
323
+ ): boolean {
324
+ if (!observed) return false;
325
+ if (entry.dev !== observed.dev || entry.ino !== observed.ino) return false;
326
+ if (entry.birthtimeMs !== undefined && entry.birthtimeMs !== observed.birthtimeMs) return false;
327
+ return true;
328
+ }