@blackbelt-technology/pi-agent-dashboard 0.10.0 → 0.11.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 (255) hide show
  1. package/AGENTS.md +2 -2
  2. package/README.md +47 -6
  3. package/docs/architecture.md +1369 -63
  4. package/package.json +14 -9
  5. package/packages/extension/package.json +5 -3
  6. package/packages/extension/src/bridge-handlers/dispatch.ts +57 -3
  7. package/packages/extension/src/bridge-handlers/instance.ts +10 -1
  8. package/packages/extension/src/bridge-handlers/lifecycle.ts +65 -26
  9. package/packages/extension/src/bridge-ticket-client.ts +61 -7
  10. package/packages/extension/src/bridge-tls-checks.ts +79 -0
  11. package/packages/extension/src/bridge.ts +41 -28
  12. package/packages/extension/src/canvas-tool.ts +2 -0
  13. package/packages/extension/src/command-handler.ts +80 -6
  14. package/packages/extension/src/connect-target.ts +23 -0
  15. package/packages/extension/src/connection.ts +30 -7
  16. package/packages/extension/src/dashboard-http-origin.ts +88 -0
  17. package/packages/extension/src/dev-build.ts +11 -1
  18. package/packages/extension/src/git-link-builder.ts +11 -2
  19. package/packages/extension/src/inbound-limits.ts +138 -0
  20. package/packages/extension/src/local-token-header.ts +77 -6
  21. package/packages/extension/src/model-refresh.ts +69 -0
  22. package/packages/extension/src/pinned-endpoint.ts +44 -0
  23. package/packages/extension/src/project-trust-live.ts +143 -0
  24. package/packages/extension/src/project-trust.ts +159 -20
  25. package/packages/extension/src/provider-register.ts +59 -18
  26. package/packages/extension/src/remote-registration-gate.ts +21 -21
  27. package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
  28. package/packages/extension/src/role-model-tools.ts +47 -6
  29. package/packages/extension/src/server-auto-start.ts +1 -1
  30. package/packages/extension/src/server-proof-probe.ts +117 -0
  31. package/packages/extension/src/session-sync.ts +42 -12
  32. package/packages/extension/src/vault-delivery.ts +11 -1
  33. package/packages/server/package.json +8 -8
  34. package/packages/server/src/access/access-grants.ts +61 -8
  35. package/packages/server/src/access/access-health.ts +10 -0
  36. package/packages/server/src/access/access-plane.ts +5 -1
  37. package/packages/server/src/access/containment-gate.ts +55 -17
  38. package/packages/server/src/access/cwd-verdict.ts +3 -3
  39. package/packages/server/src/access/pi-trust-live.ts +244 -0
  40. package/packages/server/src/access/pi-trust-mirror-service.ts +44 -11
  41. package/packages/server/src/access/planes.ts +106 -1
  42. package/packages/server/src/access/preview-egress-store.ts +153 -0
  43. package/packages/server/src/access/prompt-channel.ts +5 -0
  44. package/packages/server/src/access/provisioning-wiring.ts +113 -0
  45. package/packages/server/src/access/provisioning.ts +763 -0
  46. package/packages/server/src/access/yolo-session.ts +54 -2
  47. package/packages/server/src/acp-bridge/acp-session-adapter.ts +8 -3
  48. package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
  49. package/packages/server/src/auth/audit-log.ts +80 -0
  50. package/packages/server/src/auth/auth-plugin.ts +44 -25
  51. package/packages/server/src/auth/auth.ts +24 -4
  52. package/packages/server/src/auth/bearer-auth.ts +52 -12
  53. package/packages/server/src/auth/cors-origin.ts +76 -29
  54. package/packages/server/src/auth/csp-report-paths.ts +31 -0
  55. package/packages/server/src/auth/csp-report-sink.ts +302 -0
  56. package/packages/server/src/auth/csp-report-store.ts +406 -0
  57. package/packages/server/src/auth/csp.ts +105 -9
  58. package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
  59. package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
  60. package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
  61. package/packages/server/src/auth/local-proof.ts +69 -18
  62. package/packages/server/src/auth/localhost-guard.ts +48 -10
  63. package/packages/server/src/auth/nav-intent.ts +72 -0
  64. package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
  65. package/packages/server/src/auth/passkey/passkey-pages.ts +17 -81
  66. package/packages/server/src/auth/passkey/passkey-routes.ts +8 -0
  67. package/packages/server/src/auth/pi-legacy-credentials.ts +3 -0
  68. package/packages/server/src/auth/plugin-server-trust.ts +29 -0
  69. package/packages/server/src/auth/plugin-trust-store.ts +103 -0
  70. package/packages/server/src/auth/proven-tls.ts +45 -0
  71. package/packages/server/src/auth/provider-auth-storage.ts +6 -1
  72. package/packages/server/src/auth/radius-mcp.ts +1 -1
  73. package/packages/server/src/auth/request-principal.ts +32 -0
  74. package/packages/server/src/auth/secret-rotation.ts +246 -0
  75. package/packages/server/src/auth/secure-origin.ts +56 -0
  76. package/packages/server/src/auth/serve-app-host.ts +111 -11
  77. package/packages/server/src/auth/ws-ticket.ts +39 -1
  78. package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
  79. package/packages/server/src/browser-handlers/directory-handler.ts +23 -0
  80. package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
  81. package/packages/server/src/browser-handlers/handler-context.ts +25 -2
  82. package/packages/server/src/browser-handlers/session-action-handler.ts +9 -1
  83. package/packages/server/src/browser-handlers/subscription-handler.ts +100 -2
  84. package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
  85. package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
  86. package/packages/server/src/cli.ts +210 -39
  87. package/packages/server/src/config-api.ts +23 -1
  88. package/packages/server/src/config-snapshot.ts +48 -1
  89. package/packages/server/src/directory-service.ts +160 -54
  90. package/packages/server/src/event-wiring.ts +143 -108
  91. package/packages/server/src/git-worktree/git-operations.ts +44 -10
  92. package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
  93. package/packages/server/src/git-worktree/ref-arg.ts +39 -0
  94. package/packages/server/src/git-worktree/worktree-init-trust.ts +43 -1
  95. package/packages/server/src/identity/http-road-classification.ts +13 -1
  96. package/packages/server/src/identity/ws-message-scope.ts +1 -0
  97. package/packages/server/src/identity/ws-road-classification.ts +1 -0
  98. package/packages/server/src/known-server-moves.ts +36 -15
  99. package/packages/server/src/lib/browse-roots.ts +118 -17
  100. package/packages/server/src/lib/client-dist.ts +36 -21
  101. package/packages/server/src/lib/dashboard-state-guard.ts +230 -0
  102. package/packages/server/src/lib/diagram-render.ts +4 -6
  103. package/packages/server/src/lib/eml.ts +3 -8
  104. package/packages/server/src/lib/file-cwd-admission.ts +145 -0
  105. package/packages/server/src/lib/grep-worker.ts +23 -0
  106. package/packages/server/src/lib/grep.ts +93 -7
  107. package/packages/server/src/lib/index-html.ts +81 -0
  108. package/packages/server/src/lib/office-preview.ts +2 -3
  109. package/packages/server/src/lib/path-containment.ts +7 -0
  110. package/packages/server/src/lib/resolve-file-mention.ts +11 -9
  111. package/packages/server/src/lib/route-admission.ts +80 -0
  112. package/packages/server/src/lib/writable-md-target.ts +4 -0
  113. package/packages/server/src/lifecycle/recovery-server.ts +65 -18
  114. package/packages/server/src/live-server/capability-redact.ts +15 -0
  115. package/packages/server/src/live-server/live-browser-gate.ts +22 -0
  116. package/packages/server/src/live-server/live-capability.ts +224 -17
  117. package/packages/server/src/live-server/live-csp-report.ts +63 -0
  118. package/packages/server/src/live-server/live-csp.ts +93 -0
  119. package/packages/server/src/live-server/live-egress.ts +435 -0
  120. package/packages/server/src/live-server/live-exposure.ts +149 -0
  121. package/packages/server/src/live-server/live-log.ts +21 -0
  122. package/packages/server/src/live-server/live-origin-scan.ts +298 -0
  123. package/packages/server/src/live-server/live-server-manager.ts +209 -33
  124. package/packages/server/src/live-server/live-server-proxy.ts +162 -17
  125. package/packages/server/src/live-server/live-static.ts +228 -0
  126. package/packages/server/src/openspec/dependencies-file.ts +122 -0
  127. package/packages/server/src/openspec/openspec-change-watcher.ts +3 -1
  128. package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
  129. package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +72 -26
  130. package/packages/server/src/openspec/openspec-poll-worker-pool.ts +48 -12
  131. package/packages/server/src/openspec/openspec-poll-worker.ts +95 -9
  132. package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
  133. package/packages/server/src/openspec/workflow-schema.ts +141 -267
  134. package/packages/server/src/package/npm-search-proxy.ts +5 -2
  135. package/packages/server/src/package/provider-probe.ts +8 -2
  136. package/packages/server/src/pairing/browser-gateway.ts +188 -12
  137. package/packages/server/src/pairing/device-token-services.ts +26 -0
  138. package/packages/server/src/pairing/paired-devices.ts +335 -22
  139. package/packages/server/src/pairing/pairing.ts +34 -4
  140. package/packages/server/src/pairing/socket-locality.ts +26 -0
  141. package/packages/server/src/persistence/preferences-store.ts +9 -0
  142. package/packages/server/src/pi/bridge-channel.ts +33 -0
  143. package/packages/server/src/pi/bridge-upgrade-auth.ts +18 -3
  144. package/packages/server/src/pi/gateway-listeners.ts +9 -3
  145. package/packages/server/src/pi/host-project-trust.ts +14 -6
  146. package/packages/server/src/pi/pi-gateway.ts +191 -21
  147. package/packages/server/src/pi/resource-toggle-trust.ts +1 -1
  148. package/packages/server/src/plugin-discovery-wiring.ts +142 -0
  149. package/packages/server/src/plugin-event-seam.ts +116 -4
  150. package/packages/server/src/plugin-runtime-clients.ts +89 -0
  151. package/packages/server/src/routes/access-routes.ts +159 -9
  152. package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
  153. package/packages/server/src/routes/canvas-types-routes.ts +20 -6
  154. package/packages/server/src/routes/csp-violations-routes.ts +162 -0
  155. package/packages/server/src/routes/file-routes.ts +329 -209
  156. package/packages/server/src/routes/file-write-binary-routes.ts +77 -20
  157. package/packages/server/src/routes/folder-project-routes.ts +18 -12
  158. package/packages/server/src/routes/git-routes.ts +319 -203
  159. package/packages/server/src/routes/grep-routes.ts +38 -14
  160. package/packages/server/src/routes/known-servers-routes.ts +189 -91
  161. package/packages/server/src/routes/live-server-routes.ts +378 -15
  162. package/packages/server/src/routes/local-proof-routes.ts +14 -0
  163. package/packages/server/src/routes/nav-intent-routes.ts +46 -0
  164. package/packages/server/src/routes/openspec-group-routes.ts +53 -44
  165. package/packages/server/src/routes/openspec-routes.ts +379 -28
  166. package/packages/server/src/routes/package-routes.ts +58 -10
  167. package/packages/server/src/routes/pairing-routes.ts +146 -10
  168. package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
  169. package/packages/server/src/routes/plugin-activation-routes.ts +59 -0
  170. package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
  171. package/packages/server/src/routes/provider-auth-routes.ts +15 -2
  172. package/packages/server/src/routes/resource-activation-routes.ts +18 -4
  173. package/packages/server/src/routes/session-routes.ts +51 -4
  174. package/packages/server/src/routes/system-routes.ts +84 -15
  175. package/packages/server/src/routes/ui-link-base.ts +88 -0
  176. package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
  177. package/packages/server/src/server.ts +648 -137
  178. package/packages/server/src/session/hydration-state.ts +148 -0
  179. package/packages/server/src/session/memory-session-manager.ts +7 -0
  180. package/packages/server/src/session/replay-exit-controller.ts +221 -0
  181. package/packages/server/src/session/retained-transcript.ts +9 -2
  182. package/packages/server/src/session/session-load-worker.ts +11 -2
  183. package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -9
  184. package/packages/server/src/terminal/terminal-manager.ts +54 -46
  185. package/packages/server/src/tls/tls-bridge-route.ts +61 -0
  186. package/packages/server/src/tls/tls-config-validation.ts +2 -0
  187. package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
  188. package/packages/server/src/vault/vault-delivery-hub.ts +155 -25
  189. package/packages/server/src/watch-files-handler.ts +66 -0
  190. package/packages/shared/package.json +1 -1
  191. package/packages/shared/src/browser-protocol.ts +148 -2
  192. package/packages/shared/src/canvas-declare.ts +27 -0
  193. package/packages/shared/src/config.ts +372 -53
  194. package/packages/shared/src/containment-guard.ts +35 -0
  195. package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +9 -0
  196. package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
  197. package/packages/shared/src/dashboard-plugin/file-handler.ts +2 -0
  198. package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
  199. package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
  200. package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
  201. package/packages/shared/src/dashboard-plugin/index.ts +2 -0
  202. package/packages/shared/src/dashboard-plugin/manifest-types.ts +54 -1
  203. package/packages/shared/src/dashboard-plugin/plugin-status.ts +54 -0
  204. package/packages/shared/src/dashboard-plugin/slot-props.ts +45 -3
  205. package/packages/shared/src/dashboard-plugin/slot-types.ts +8 -0
  206. package/packages/shared/src/dashboard-plugin/subagent-types.ts +219 -0
  207. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +28 -0
  208. package/packages/shared/src/display-prefs.ts +13 -0
  209. package/packages/shared/src/doctor-core.ts +94 -27
  210. package/packages/shared/src/live-server.ts +141 -0
  211. package/packages/shared/src/local-proof-signal.ts +16 -0
  212. package/packages/shared/src/loopback-host.ts +26 -0
  213. package/packages/shared/src/mcp/verb-tiers.generated.ts +178 -0
  214. package/packages/shared/src/mdns-discovery.ts +25 -6
  215. package/packages/shared/src/nav-intent.ts +29 -0
  216. package/packages/shared/src/openspec-dependencies.ts +760 -0
  217. package/packages/shared/src/openspec-poller.ts +3 -2
  218. package/packages/shared/src/pairing-knock-client.ts +44 -4
  219. package/packages/shared/src/pi-trust-live-query.ts +93 -0
  220. package/packages/shared/src/pi-trust-mirror-snapshot.ts +5 -7
  221. package/packages/shared/src/pi-trust-mirror-types.ts +36 -3
  222. package/packages/shared/src/pi-trust-mirror.ts +29 -3
  223. package/packages/shared/src/pi-trust-resource-digest.ts +255 -0
  224. package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
  225. package/packages/shared/src/platform/git-source.ts +88 -26
  226. package/packages/shared/src/platform/git.ts +14 -8
  227. package/packages/shared/src/platform/process.ts +48 -4
  228. package/packages/shared/src/platform/resolve-pi-shell.ts +76 -0
  229. package/packages/shared/src/platform/select-git-source.ts +7 -0
  230. package/packages/shared/src/plugin-route-cwd.ts +95 -0
  231. package/packages/shared/src/preview-egress.ts +138 -0
  232. package/packages/shared/src/project-root.ts +16 -0
  233. package/packages/shared/src/protocol.ts +40 -1
  234. package/packages/shared/src/recommended-extensions.ts +18 -0
  235. package/packages/shared/src/recovery-timing.ts +27 -0
  236. package/packages/shared/src/remote-credentials.ts +63 -0
  237. package/packages/shared/src/rest-api.ts +55 -8
  238. package/packages/shared/src/route-tiers.ts +55 -1
  239. package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
  240. package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
  241. package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
  242. package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
  243. package/packages/shared/src/safe-local-path.ts +24 -0
  244. package/packages/shared/src/sanitize-profiles.ts +98 -0
  245. package/packages/shared/src/server-launcher.ts +9 -1
  246. package/packages/shared/src/server-pinning.ts +55 -2
  247. package/packages/shared/src/server-routes.ts +462 -0
  248. package/packages/shared/src/session-ui-path.ts +11 -0
  249. package/packages/shared/src/tls-only-token.ts +16 -0
  250. package/packages/shared/src/tool-registry/definitions.ts +5 -5
  251. package/packages/shared/src/tool-registry/strategies.ts +12 -11
  252. package/packages/shared/src/types.ts +66 -0
  253. package/packages/shared/src/url-policy.ts +96 -0
  254. package/packages/shared/src/vault-delivery.ts +15 -0
  255. package/packages/shared/src/ws-message-tiers.ts +1 -0
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Prove a CANDIDATE server's identity before the bridge drops its established
3
+ * connection for it.
4
+ *
5
+ * A healthy `/api/health` answer is something any process on a loopback port
6
+ * can fake; only a holder of the local token can return a valid counter-proof.
7
+ * So the guarded migration performs the same upgrade handshake a real dial
8
+ * would — with this HOME's proof header — verifies the counter-proof on the
9
+ * upgrade response, and tears the probe socket down BEFORE `open`: no frame is
10
+ * ever sent, the bridge never registers, and the incumbent is untouched.
11
+ *
12
+ * Nothing to prove (remote endpoint, unix socket, no token, or the explicit
13
+ * opt-out) → ok. Refusal causes follow the dial path: no proof / wrong status →
14
+ * `server-proof-missing`; bad MAC or a stalled response → `server-proof-invalid`.
15
+ *
16
+ * See change: harden-bridge-inbound-and-discovery (D19).
17
+ */
18
+ import { WebSocket as WsWebSocket } from "ws";
19
+ import type { DialPlan, ServerProofFailure } from "./connection.js";
20
+ import { probeEndpointReachability } from "./instance-verification.js";
21
+ import { localCredentialPlan, proofFailureLogCause } from "./local-token-header.js";
22
+
23
+ export type ServerProofResult = { ok: true } | { ok: false; cause: ServerProofFailure };
24
+
25
+ export interface ServerProofProbeDeps {
26
+ /** Dial plan for the candidate (default: the real loopback plan). */
27
+ plan?: (endpoint: string) => Promise<DialPlan | undefined>;
28
+ /** `ws` client (injectable for tests). */
29
+ WebSocketImpl?: new (url: string, opts?: Record<string, unknown>) => any;
30
+ timeoutMs?: number;
31
+ }
32
+
33
+ const DEFAULT_TIMEOUT_MS = 3000;
34
+
35
+ export async function probeServerProof(candidateUrl: string, deps: ServerProofProbeDeps = {}): Promise<ServerProofResult> {
36
+ let plan: DialPlan | undefined;
37
+ try {
38
+ plan = await (deps.plan ?? ((u: string) => localCredentialPlan(u)))(candidateUrl);
39
+ } catch {
40
+ // Could not even open the proof-bound socket: nothing proved anything.
41
+ return { ok: false, cause: "server-proof-missing" };
42
+ }
43
+ if (!plan) return { ok: true };
44
+ const verify = plan.verifyUpgrade;
45
+ if (!verify) {
46
+ plan.dispose?.();
47
+ return { ok: true };
48
+ }
49
+
50
+ const WS = deps.WebSocketImpl ?? WsWebSocket;
51
+ return new Promise<ServerProofResult>((resolve) => {
52
+ let ws: any;
53
+ let settled = false;
54
+ const finish = (result: ServerProofResult): void => {
55
+ if (settled) return;
56
+ settled = true;
57
+ clearTimeout(timer);
58
+ try {
59
+ ws?.on?.("error", () => {}); // terminate() mid-handshake emits `error`
60
+ ws?.terminate?.();
61
+ } catch {
62
+ /* already torn down */
63
+ }
64
+ plan?.dispose?.();
65
+ resolve(result);
66
+ };
67
+ const timer = setTimeout(() => finish({ ok: false, cause: "server-proof-invalid" }), deps.timeoutMs ?? DEFAULT_TIMEOUT_MS);
68
+ timer.unref?.();
69
+ try {
70
+ const opts: Record<string, unknown> = {};
71
+ if (plan?.headers) opts.headers = plan.headers;
72
+ if (plan?.createConnection) opts.createConnection = plan.createConnection;
73
+ ws = new WS(candidateUrl, opts);
74
+ ws.on("upgrade", (res: { headers: Record<string, string | string[] | undefined> }) => {
75
+ let verdict: ReturnType<typeof verify>;
76
+ try {
77
+ verdict = verify(res);
78
+ } catch {
79
+ verdict = { ok: false, cause: "server-proof-invalid" };
80
+ }
81
+ finish(verdict);
82
+ });
83
+ // Anything that ends the handshake without a verified upgrade is a refusal.
84
+ ws.on("unexpected-response", () => finish({ ok: false, cause: "server-proof-missing" }));
85
+ ws.on("error", () => finish({ ok: false, cause: "server-proof-missing" }));
86
+ ws.on("close", () => finish({ ok: false, cause: "server-proof-missing" }));
87
+ } catch {
88
+ finish({ ok: false, cause: "server-proof-missing" });
89
+ }
90
+ });
91
+ }
92
+
93
+ /**
94
+ * The guarded migration's admission probe for a discovered candidate:
95
+ * reachable (`GET /api/health` → `{ok:true}`) AND able to prove its identity.
96
+ * A healthy answer alone never suffices. A refusal is logged with its named
97
+ * cause (`server_proof_missing` / `server_proof_invalid`) and keeps the
98
+ * established connection.
99
+ */
100
+ export async function verifyDiscoveredCandidate(input: {
101
+ healthUrl: string;
102
+ candidateUrl: string;
103
+ reachable?: (healthUrl: string) => Promise<boolean>;
104
+ probe?: ServerProofProbeDeps;
105
+ log?: (line: string) => void;
106
+ }): Promise<boolean> {
107
+ const reachable = input.reachable ?? ((healthUrl: string) => probeEndpointReachability({ healthUrl }));
108
+ if (!(await reachable(input.healthUrl))) return false;
109
+ const proof = await probeServerProof(input.candidateUrl, input.probe);
110
+ if (!proof.ok) {
111
+ (input.log ?? ((line: string) => console.error(line)))(
112
+ `[dashboard] server identity check failed (${proofFailureLogCause(proof.cause)}) at ${input.candidateUrl}`,
113
+ );
114
+ return false;
115
+ }
116
+ return true;
117
+ }
@@ -76,13 +76,40 @@ export function filterByEnabledModels<T extends { provider: string; id: string }
76
76
  }
77
77
  }
78
78
 
79
+ /**
80
+ * Branch fingerprint carried on `session_register`: `eventCount` (branch length)
81
+ * and `leafEntryId` (id of its last entry). With `liveTailOpen` it lets the
82
+ * server skip the wipe when it already holds this exact branch. Never throws.
83
+ * See change: fix-large-session-resume-replay (D5, D7).
84
+ */
85
+ export function branchFingerprint(
86
+ sessionManager: { getBranch?: () => Array<{ id?: unknown }> } | undefined,
87
+ ): { eventCount?: number; leafEntryId?: string } {
88
+ try {
89
+ const entries = sessionManager?.getBranch?.();
90
+ if (!entries) return {};
91
+ const last = entries.length > 0 ? entries[entries.length - 1].id : undefined;
92
+ return {
93
+ eventCount: entries.length,
94
+ ...(typeof last === "string" && last.length > 0 ? { leafEntryId: last } : {}),
95
+ };
96
+ } catch {
97
+ return {};
98
+ }
99
+ }
100
+
79
101
  /**
80
102
  * Send full state sync to the server (session_register, commands, flows, models).
81
103
  * Called on initial connect and reconnect.
104
+ *
105
+ * `opts.liveTailOpen` is computed ONCE by the caller and shared with the replay
106
+ * that follows, so the register and the replay agree.
107
+ * See change: fix-large-session-resume-replay (D7).
82
108
  */
83
109
  export function sendStateSync(
84
110
  bc: BridgeContext,
85
111
  getFlowsList: () => FlowInfo[],
112
+ opts?: { liveTailOpen?: boolean },
86
113
  ): void {
87
114
  const model = getCurrentModelString(bc);
88
115
  const thinkingLevel = (bc.pi as any).getThinkingLevel?.() ?? undefined;
@@ -93,12 +120,8 @@ export function sendStateSync(
93
120
  const sessionDir = bc.lastSessionDir ?? bc.cachedCtx?.sessionManager?.getSessionDir?.() ?? undefined;
94
121
  const firstMessage = extractFirstMessage(bc.cachedCtx);
95
122
 
96
- // Include eventCount so server can skip event wipe on reconnect
97
- let eventCount: number | undefined;
98
- try {
99
- const entries = bc.cachedCtx?.sessionManager?.getBranch?.();
100
- if (entries) eventCount = entries.length;
101
- } catch { /* ignore */ }
123
+ // Include eventCount (+ leaf id, liveTailOpen) so server can skip event wipe on reconnect
124
+ const { eventCount, leafEntryId } = branchFingerprint(bc.cachedCtx?.sessionManager);
102
125
 
103
126
  // Tag the very first sendStateSync after process boot as "spawn";
104
127
  // every subsequent invocation (driven by WebSocket reconnect after a
@@ -140,8 +163,12 @@ export function sendStateSync(
140
163
  sessionDir,
141
164
  firstMessage,
142
165
  eventCount,
166
+ ...(leafEntryId !== undefined ? { leafEntryId } : {}),
167
+ ...(opts?.liveTailOpen !== undefined ? { liveTailOpen: opts.liveTailOpen } : {}),
143
168
  pid: process.pid,
144
169
  registerReason,
170
+ // See change: prove-vault-bridge-tls (D7).
171
+ ...(bc.connection.certValidation ? { certValidation: "enforced" as const } : {}),
145
172
  // Tri-state git-repo signal computed synchronously (no git_info_update
146
173
  // arrival race). See change: gate-session-worktree-button-on-git.
147
174
  isGitRepo: detectIsGitRepo(process.cwd()),
@@ -214,7 +241,9 @@ export function replaySessionEntries(bc: BridgeContext, opts?: { liveTailOpen?:
214
241
  if (!entries || entries.length === 0) return;
215
242
  const events = replayEntriesAsEvents(bc.sessionId, entries, undefined, opts);
216
243
  for (const msg of events) {
217
- bc.connection.send(msg);
244
+ // Mark every replayed forward so the server never treats it as live,
245
+ // whatever its replay timers say. See change: fix-large-session-resume-replay (D1).
246
+ bc.connection.send({ ...msg, replay: true });
218
247
  }
219
248
  } catch { /* ignore */ }
220
249
  }
@@ -252,11 +281,7 @@ export function handleSessionChange(
252
281
 
253
282
  // Include eventCount for consistency (session switch/fork changes sessionId,
254
283
  // so the server will wipe regardless, but include for completeness)
255
- let eventCount: number | undefined;
256
- try {
257
- const entries = ctx.sessionManager?.getBranch?.();
258
- if (entries) eventCount = entries.length;
259
- } catch { /* ignore */ }
284
+ const { eventCount, leafEntryId } = branchFingerprint(ctx.sessionManager);
260
285
 
261
286
  // handleSessionChange always mints a fresh sessionId (new/fork/resume),
262
287
  // so registerReason is unconditionally "spawn" — even after the bridge
@@ -283,8 +308,13 @@ export function handleSessionChange(
283
308
  ...(dashboardSpawned ? { dashboardSpawned: true } : {}),
284
309
  firstMessage,
285
310
  eventCount,
311
+ ...(leafEntryId !== undefined ? { leafEntryId } : {}),
312
+ // The switch path never leaves the tail open (see replaySessionEntries below).
313
+ liveTailOpen: false,
286
314
  pid: process.pid,
287
315
  registerReason: "spawn",
316
+ // See change: prove-vault-bridge-tls (D7).
317
+ ...(bc.connection.certValidation ? { certValidation: "enforced" as const } : {}),
288
318
  // See change: gate-session-worktree-button-on-git.
289
319
  isGitRepo: detectIsGitRepo(cwd),
290
320
  ...(usageSeed ? { usageSeed } : {}),
@@ -32,6 +32,7 @@
32
32
  import { createHash } from "node:crypto";
33
33
  import { realpathAsync, remoteUrlOrAsync } from "@blackbelt-technology/pi-dashboard-shared/platform/git.js";
34
34
  import type { VaultReportMessage, VaultSnapshotMessage, VaultSyncRequestMessage } from "@blackbelt-technology/pi-dashboard-shared/protocol.js";
35
+ import { remoteForWire } from "@blackbelt-technology/pi-dashboard-shared/remote-credentials.js";
35
36
  import {
36
37
  clampVaultGraceHours,
37
38
  isDeliverableEnvName,
@@ -96,6 +97,11 @@ export interface VaultDeliveryDeps {
96
97
  /** Resolve the session cwd to its real path and raw origin. Undefined = unusable. */
97
98
  resolveProject?: (cwd: string) => Promise<VaultProject | undefined>;
98
99
  identityTimeoutMs?: number;
100
+ /**
101
+ * `"enforced"` while the connection carries the TLS checks (read per sync); declared
102
+ * on `vault_sync_request`. See change: prove-vault-bridge-tls (D7).
103
+ */
104
+ certValidation?: () => "enforced" | undefined;
99
105
  log?: (line: string) => void;
100
106
  }
101
107
 
@@ -265,14 +271,18 @@ export function createVaultDelivery(deps: VaultDeliveryDeps): VaultDelivery {
265
271
 
266
272
  const sendSync = (reason: VaultSyncRequestMessage["reason"], project: VaultProject | undefined): void => {
267
273
  if (!supported) return;
274
+ // Raw origin, userinfo-stripped, never normalized; unparseable-with-userinfo
275
+ // → undefined → no origin sent. See change: harden-bridge-inbound-and-discovery (D18).
276
+ const origin = project?.origin ? remoteForWire(project.origin) : undefined;
268
277
  try {
269
278
  deps.send({
270
279
  type: "vault_sync_request",
271
280
  sessionId: deps.sessionId(),
272
281
  ...(project ? { cwd: project.dir } : {}),
273
- ...(project?.origin ? { origin: project.origin } : {}),
282
+ ...(origin ? { origin } : {}),
274
283
  tracked: [...registry.tracked.keys()],
275
284
  reason,
285
+ ...(deps.certValidation?.() === "enforced" ? { certValidation: "enforced" as const } : {}),
276
286
  });
277
287
  } catch { /* the next connect re-syncs */ }
278
288
  };
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-dashboard-server",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Dashboard server for monitoring and interacting with pi agent sessions",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -71,11 +71,11 @@
71
71
  },
72
72
  "dependencies": {
73
73
  "@agentclientprotocol/sdk": "~1.8.0",
74
- "@blackbelt-technology/dashboard-plugin-runtime": "^0.10.0",
75
- "@blackbelt-technology/pi-dashboard-document-converter": "^0.10.0",
76
- "@blackbelt-technology/pi-dashboard-extension": "^0.10.0",
77
- "@blackbelt-technology/pi-dashboard-mcp-client-plugin": "^0.10.0",
78
- "@blackbelt-technology/pi-dashboard-shared": "^0.10.0",
74
+ "@blackbelt-technology/dashboard-plugin-runtime": "^0.11.0",
75
+ "@blackbelt-technology/pi-dashboard-document-converter": "^0.11.0",
76
+ "@blackbelt-technology/pi-dashboard-extension": "^0.11.0",
77
+ "@blackbelt-technology/pi-dashboard-mcp-core": "^0.11.0",
78
+ "@blackbelt-technology/pi-dashboard-shared": "^0.11.0",
79
79
  "@earendil-works/pi-coding-agent": "^1.3.0",
80
80
  "@fastify/compress": "^9.2.0",
81
81
  "@fastify/cookie": "^11.0.2",
@@ -117,8 +117,8 @@
117
117
  "koffi": "^3.3.3"
118
118
  },
119
119
  "devDependencies": {
120
- "@blackbelt-technology/pi-dashboard-mcp-server-plugin": "^0.10.0",
121
- "@blackbelt-technology/pi-path-containment-guard": "^0.10.0",
120
+ "@blackbelt-technology/pi-dashboard-mcp-server-plugin": "^0.11.0",
121
+ "@blackbelt-technology/pi-path-containment-guard": "^0.11.0",
122
122
  "@types/diff": "^7.0.0",
123
123
  "@types/jsonwebtoken": "^9.0.9",
124
124
  "@types/mailparser": "^3.4.6",
@@ -61,9 +61,29 @@ function notifyGrantsChanged(): void {
61
61
  }
62
62
  }
63
63
 
64
+ /**
65
+ * Notified SYNCHRONOUSLY when the in-memory session grants change. Separate from
66
+ * {@link setGrantsChangedListener} (persisted writes only). Feeds the pi-trust
67
+ * live count. See change: mirror-dashboard-trust-live-remote.
68
+ */
69
+ let sessionGrantsChanged: (() => void) | undefined;
70
+ export function setSessionGrantsChangedListener(fn: (() => void) | undefined): void {
71
+ sessionGrantsChanged = fn;
72
+ }
73
+ function notifySessionGrantsChanged(): void {
74
+ try {
75
+ sessionGrantsChanged?.();
76
+ } catch {
77
+ /* a listener never fails a grant */
78
+ }
79
+ }
80
+
64
81
  /** `session` = in-memory, until server restart. `project` = persisted JSON. */
65
82
  export type GrantScope = "session" | "project";
66
83
 
84
+ /** Which write path produced a grant (absent = the Access page's grant route). */
85
+ type GrantVia = "prompt" | "agent-prompt" | "provision";
86
+
67
87
  /** One grant. Session-scoped grants carry the SAME four fields (D17) — not a bare Set. */
68
88
  export interface AccessGrant {
69
89
  /** Directory, realpath'd at grant time (D2). */
@@ -79,11 +99,13 @@ export interface AccessGrant {
79
99
  */
80
100
  widenedFrom?: string;
81
101
  /**
102
+ * `"provision"` = an operator approved a line of a project's provisioning request
103
+ * (change: add-access-provisioning); such a grant is never an eviction victim.
82
104
  * `"prompt"` when an operator's allow-always answer to an access prompt wrote
83
105
  * this grant (change: add-access-grant-dialog, task 8.2). Absent = the Access
84
106
  * page's grant route. Optional and additive: older builds spread it through.
85
107
  */
86
- via?: "prompt" | "agent-prompt";
108
+ via?: GrantVia;
87
109
  }
88
110
 
89
111
  /** D10: fixed cap, per scope. */
@@ -193,6 +215,8 @@ function loadFromDisk(): AccessGrant[] {
193
215
  // The cap is a property of the STORE, not of the write path: a hand-edited or
194
216
  // hostile file with 100k grants would otherwise be admitted in full, growing
195
217
  // the hot path's Set per request and memory without bound.
218
+ // Load does not spare provisioned grants: the bound wins, so a hostile file
219
+ // full of `via: "provision"` entries still cannot grow the Set.
196
220
  enforceCap(valid, "project");
197
221
  return valid;
198
222
  }
@@ -260,21 +284,36 @@ export function grantedSubjects(): string[] {
260
284
  * already in the file could make it sort oldest, and evicting it would let
261
285
  * `recordGrant` return `ok: true` for a grant that was never persisted: the UI
262
286
  * would claim a grant that does not exist, the exact failure D11 forbids.
287
+ *
288
+ * `spareProvisioned` — `via: "provision"` grants are never victims (change:
289
+ * add-access-provisioning, D5). Returns `false` and mutates nothing when the
290
+ * excess cannot be fully evicted (`evict: false`, or every candidate spared).
291
+ * Every eviction is logged.
263
292
  */
264
- function enforceCap(grants: AccessGrant[], scope: GrantScope, protect?: AccessGrant): void {
293
+ function enforceCap(
294
+ grants: AccessGrant[],
295
+ scope: GrantScope,
296
+ opts: { protect?: AccessGrant; evict?: boolean; spareProvisioned?: boolean } = {},
297
+ ): boolean {
265
298
  const inScope = grants.filter((g) => g.scope === scope);
266
- if (inScope.length <= GRANT_CAP_PER_SCOPE) return;
299
+ if (inScope.length <= GRANT_CAP_PER_SCOPE) return true;
300
+ if (opts.evict === false) return false;
267
301
  const excess = inScope.length - GRANT_CAP_PER_SCOPE;
268
302
  const evictOrder = inScope
269
- .filter((g) => g !== protect)
303
+ .filter((g) => g !== opts.protect && !(opts.spareProvisioned && g.via === "provision"))
270
304
  .map((g, i) => ({ g, i }))
271
305
  .sort((a, b) => a.g.grantedAt - b.g.grantedAt || a.i - b.i)
272
306
  .slice(0, excess)
273
307
  .map((x) => x.g);
308
+ if (evictOrder.length < excess) return false;
274
309
  const doomed = new Set(evictOrder);
275
310
  for (let i = grants.length - 1; i >= 0; i -= 1) {
276
311
  if (doomed.has(grants[i])) grants.splice(i, 1);
277
312
  }
313
+ for (const g of evictOrder) {
314
+ console.warn(`[access-grants] evicted subject=${JSON.stringify(g.subject)} via=${g.via ?? "none"}`);
315
+ }
316
+ return true;
278
317
  }
279
318
 
280
319
  /** Atomic write: temp file in the same directory, then rename (D11). */
@@ -306,7 +345,12 @@ export interface RecordGrantInput {
306
345
  origin?: string;
307
346
  /** Set when the subject came from the denial's offered-ancestor ladder. */
308
347
  widenedFrom?: string;
309
- via?: "prompt" | "agent-prompt";
348
+ via?: GrantVia;
349
+ /**
350
+ * `false` = refuse with `{ok:false, error:"capacity"}` at the cap instead of
351
+ * evicting the oldest grant (change: add-access-provisioning). Default `true`.
352
+ */
353
+ evict?: boolean;
310
354
  now?: number;
311
355
  }
312
356
 
@@ -319,7 +363,7 @@ export interface RecordGrantInput {
319
363
  * did not stick.
320
364
  */
321
365
  /** A grant with its optional provenance fields set only when present. */
322
- function buildGrant(base: AccessGrant, widenedFrom: string | undefined, via: "prompt" | "agent-prompt" | undefined): AccessGrant {
366
+ function buildGrant(base: AccessGrant, widenedFrom: string | undefined, via: GrantVia | undefined): AccessGrant {
323
367
  const grant: AccessGrant = { ...base };
324
368
  if (widenedFrom) grant.widenedFrom = widenedFrom;
325
369
  if (via) grant.via = via;
@@ -354,7 +398,11 @@ export function recordGrant(input: RecordGrantInput): RecordGrantResult {
354
398
  if (existing) return { ok: true, grant: existing };
355
399
  const grant = buildGrant({ subject, scope, grantedAt, origin }, widen, input.via);
356
400
  sessionGrants.push(grant);
357
- enforceCap(sessionGrants, "session", grant);
401
+ if (!enforceCap(sessionGrants, "session", { protect: grant, evict: input.evict, spareProvisioned: true })) {
402
+ sessionGrants.pop();
403
+ return { ok: false, error: "capacity" };
404
+ }
405
+ notifySessionGrantsChanged();
358
406
  return { ok: true, grant };
359
407
  }
360
408
 
@@ -363,7 +411,9 @@ export function recordGrant(input: RecordGrantInput): RecordGrantResult {
363
411
  if (existing) return { ok: true, grant: existing };
364
412
  const grant = buildGrant({ subject, scope, grantedAt, origin }, widen, input.via);
365
413
  grants.push(grant);
366
- enforceCap(grants, "project", grant);
414
+ if (!enforceCap(grants, "project", { protect: grant, evict: input.evict, spareProvisioned: true })) {
415
+ return { ok: false, error: "capacity" };
416
+ }
367
417
 
368
418
  const file: StoreFile = { version: 1, grants };
369
419
  try {
@@ -390,12 +440,15 @@ export function revokeGrant(subject: string, scope?: GrantScope): boolean {
390
440
  let removed = false;
391
441
 
392
442
  if (scope !== "project") {
443
+ let sessionRemoved = false;
393
444
  for (let i = sessionGrants.length - 1; i >= 0; i -= 1) {
394
445
  if (sessionGrants[i].subject === target) {
395
446
  sessionGrants.splice(i, 1);
396
447
  removed = true;
448
+ sessionRemoved = true;
397
449
  }
398
450
  }
451
+ if (sessionRemoved) notifySessionGrantsChanged();
399
452
  }
400
453
  if (scope === "session") return removed;
401
454
 
@@ -13,6 +13,7 @@
13
13
  import type { GrantCoordinator } from "./grant-coordinator.js";
14
14
  import type { GrantRegistryStats } from "./pending-grant-registry.js";
15
15
  import type { HostGateMode } from "./prompt-channel.js";
16
+ import type { ProvisionStats } from "./provisioning.js";
16
17
  import type { YoloController } from "./yolo-session.js";
17
18
 
18
19
  export interface AccessGrantHealth {
@@ -40,6 +41,12 @@ export interface AccessGrantHealth {
40
41
  };
41
42
  /** Remembered explicit refusals (the durable ledger). */
42
43
  refusals: number;
44
+ /**
45
+ * Access-provisioning counters (design D14): cumulative except `pending`.
46
+ * Additive and optional: absent when no reader is wired; readers ignore it.
47
+ * See change: add-access-provisioning.
48
+ */
49
+ provisioning?: ProvisionStats;
43
50
  }
44
51
 
45
52
  export interface AccessGrantHealthDeps {
@@ -50,6 +57,8 @@ export interface AccessGrantHealthDeps {
50
57
  killSwitch(): boolean;
51
58
  hostGateMode(): HostGateMode;
52
59
  operatorChannels(): number;
60
+ /** Provisioning registry stats; omit to leave `provisioning` out of the snapshot. */
61
+ provisioning?(): ProvisionStats;
53
62
  }
54
63
 
55
64
  export function snapshotAccessGrantHealth(deps: AccessGrantHealthDeps): AccessGrantHealth {
@@ -73,5 +82,6 @@ export function snapshotAccessGrantHealth(deps: AccessGrantHealthDeps): AccessGr
73
82
  refusedByPriorRefusal: totals.refusedByPriorRefusal,
74
83
  },
75
84
  refusals: deps.refusalCount(),
85
+ ...(deps.provisioning ? { provisioning: deps.provisioning() } : {}),
76
86
  };
77
87
  }
@@ -35,7 +35,11 @@ interface PlaneGrantRequest {
35
35
 
36
36
  type PlaneGrantResult =
37
37
  | { ok: true; store: string; widenedFrom?: string }
38
- | { ok: false; reason: "unnamed" | "forbidden" | "invalid-subject" | "write-failed"; error?: string };
38
+ | {
39
+ ok: false;
40
+ reason: "unnamed" | "forbidden" | "invalid-subject" | "write-failed" | "unverifiable";
41
+ error?: string;
42
+ };
39
43
 
40
44
  interface PlaneBase {
41
45
  readonly id: AccessPlaneId;
@@ -23,6 +23,8 @@
23
23
  */
24
24
 
25
25
  import { lstat } from "node:fs/promises";
26
+ import type { PathDecision } from "@blackbelt-technology/pi-dashboard-shared/containment-guard.js";
27
+ import { currentCallerUnproven, dashboardStateRefuses } from "../lib/dashboard-state-guard.js";
26
28
  import { isAllowed, isGrantAdmitted } from "../lib/path-containment.js";
27
29
  import { recordPathDenial } from "./access-denials.js";
28
30
  import { grantedSubjects } from "./access-grants.js";
@@ -63,10 +65,18 @@ async function remedySubject(resolved: string, kind: SubjectKind): Promise<strin
63
65
  }
64
66
  }
65
67
 
66
- export interface ContainmentDecision {
67
- allowed: boolean;
68
- /** True when the grant layer (not layers ①/②) admitted the path. */
69
- viaGrant: boolean;
68
+ /**
69
+ * A containment verdict bound to the exact path it decided (`resolved`). Branded in
70
+ * `@blackbelt-technology/pi-dashboard-shared/containment-guard.js`; this module is the ONLY
71
+ * place that builds one (see `decision`), so `containmentAllows(decision, resolved)` can only
72
+ * be true for the path that was actually evaluated.
73
+ * See change: codeql-file-containment-barrier.
74
+ */
75
+ export type ContainmentDecision = PathDecision;
76
+
77
+ /** The one constructor of a {@link ContainmentDecision}. */
78
+ function decision(resolved: string, allowed: boolean, viaGrant: boolean): ContainmentDecision {
79
+ return { allowed, viaGrant, resolved } as ContainmentDecision;
70
80
  }
71
81
 
72
82
  /** The additive remedy fields carried beside an unchanged `error` string. */
@@ -231,17 +241,22 @@ export async function evaluateContainment(
231
241
  quiet?: boolean;
232
242
  },
233
243
  ): Promise<ContainmentDecision & { remedy?: ContainmentRemedy }> {
244
+ // Dashboard secrets (token, identity key, config) are refused before anything else, with the
245
+ // plain refusal and NO remedy: nothing is recorded, so there is no `denialId` to turn into a
246
+ // grant, and no operator is asked. See change: close-container-loopback-impersonation (D8).
247
+ if (await dashboardStateRefuses(resolved)) return decision(resolved, false, false);
248
+
234
249
  // Layers ①/② first — untouched and still authoritative (design D1) — then the
235
250
  // grant layer, and only on a miss does the denial get recorded.
236
- let decision: ContainmentDecision;
251
+ let verdict: ContainmentDecision;
237
252
  if (await isAllowed(resolved, { anchors })) {
238
- decision = { allowed: true, viaGrant: false };
253
+ verdict = decision(resolved, true, false);
239
254
  } else if ((opts.allowGrant ?? true) && (await isGrantAdmitted(resolved, grantedSubjects()))) {
240
- decision = { allowed: true, viaGrant: true };
255
+ verdict = decision(resolved, true, true);
241
256
  } else {
242
- decision = { allowed: false, viaGrant: false };
257
+ verdict = decision(resolved, false, false);
243
258
  }
244
- if (decision.allowed) return decision;
259
+ if (verdict.allowed) return verdict;
245
260
 
246
261
  // A site that cannot be ADMITTED by a grant must not ORIGINATE one. Recording a
247
262
  // denial here would return a `denialId` the operator could accept, minting a
@@ -253,7 +268,7 @@ export async function evaluateContainment(
253
268
  // `denialBody` emits only the fields that are present. (Task 4.5, fresh cycle
254
269
  // round 1: `allowGrant: false` previously blocked admission but still minted a
255
270
  // remedy at `/api/open-in-system` and `/api/reveal-in-file-manager`.)
256
- if (opts.allowGrant === false) return decision;
271
+ if (opts.allowGrant === false) return verdict;
257
272
 
258
273
  // `subjectKind` decides what the remedy names — see `remedySubject`. The
259
274
  // default ("file") is right for the majority of sites (a refused file read);
@@ -275,7 +290,7 @@ export async function evaluateContainment(
275
290
 
276
291
  if (opts.quiet) {
277
292
  return {
278
- ...decision,
293
+ ...verdict,
279
294
  remedy: {
280
295
  reason: "Path is outside every containment anchor for this session.",
281
296
  hint: "Grant access to this directory from the denial's remedy, or open the file from a session rooted in it.",
@@ -302,14 +317,37 @@ export async function evaluateContainment(
302
317
 
303
318
  // Ask the operator, if this denial may be asked about (add-access-grant-dialog).
304
319
  // Any outcome other than an allow verdict leaves the denial exactly as above.
305
- const resolution = await holdDenial(
306
- { plane: "filesystem", rawSubject: entry.subject, ancestors, origin: opts.session ?? "unknown" },
307
- opts.hold,
308
- );
320
+ // A bare-loopback caller that only lacks proof is prompt-ineligible: refused at once, nothing
321
+ // queued, nobody asked (MODIFIED file-read-containment). See change: close-container-loopback-impersonation (D8).
322
+ const resolution: Resolution = currentCallerUnproven()
323
+ ? { kind: "deny", reason: "ineligible" }
324
+ : await holdDenial(
325
+ { plane: "filesystem", rawSubject: entry.subject, ancestors, origin: opts.session ?? "unknown" },
326
+ opts.hold,
327
+ );
309
328
  const reEvaluated = resolution.kind === "allow" && (await reEvaluate(resolved, anchors, resolution));
310
- if (reEvaluated) return { allowed: true, viaGrant: true };
329
+ if (reEvaluated) return decision(resolved, true, true);
311
330
  if (opts.disclosure) remedy.promptOutcome = outcomeFor(resolution, opts.hold !== undefined);
312
- return { ...decision, remedy };
331
+ return { ...verdict, remedy };
332
+ }
333
+
334
+ /**
335
+ * The decision of a PASSIVE site: one that filters or returns nothing instead of refusing with a
336
+ * body, and so never originates a denial (`grep-routes.ts` result filter, `resolve-file-mention.ts`,
337
+ * the raw-image pre-check in `file-routes.ts`). Layers ①/② first, then — only with `allowGrant` —
338
+ * the grant layer. No denial record, no hold, and no refusal of its own beyond what `isAllowed` / `isGrantAdmitted` already enforce (both refuse dashboard-state paths): exactly the
339
+ * `isAllowed` / `isGrantAdmitted` pair these sites called by hand before, now bound to the path.
340
+ * `grantSubjects` lets a loop hoist the store read (design D16: no N × store read per match).
341
+ * See change: codeql-file-containment-barrier.
342
+ */
343
+ export async function decidePassive(
344
+ resolved: string,
345
+ anchors: string[],
346
+ opts: { allowGrant: boolean; grantSubjects?: string[] },
347
+ ): Promise<ContainmentDecision> {
348
+ if (await isAllowed(resolved, { anchors })) return decision(resolved, true, false);
349
+ if (opts.allowGrant && (await isGrantAdmitted(resolved, opts.grantSubjects ?? grantedSubjects()))) return decision(resolved, true, true);
350
+ return decision(resolved, false, false);
313
351
  }
314
352
 
315
353
  /**
@@ -6,7 +6,7 @@
6
6
  * RE-EVALUATION, never a skip. The cwd's real path is re-resolved NOW and must
7
7
  * still equal the verdict subject (any verdict kind: a swapped symlink never rides a
8
8
  * stale answer onto another folder); existence and the `.git` / ungrantable rules are
9
- * re-applied; then membership of the live known-folder set (sessions ∪ pins) is compared
9
+ * re-applied; then membership of the live known-folder set (sessions ∪ pins ∪ workspace folders) is compared
10
10
  * canonically. An `allow-always` additionally re-runs the full guard when the caller
11
11
  * supplies one; an `allow-once` admits the single held request.
12
12
  *
@@ -38,7 +38,7 @@ import { isUngrantableSubject } from "./forbidden-subjects.js";
38
38
  import type { Resolution } from "./grant-coordinator.js";
39
39
 
40
40
  export interface VerdictDeps {
41
- /** LIVE known-folder set: session cwds ∪ pinned directories. */
41
+ /** LIVE known-folder set: session cwds ∪ pinned directories ∪ workspace folders. */
42
42
  known(): string[];
43
43
  /**
44
44
  * Full guard re-run for an `allow-always` that membership did not already
@@ -89,7 +89,7 @@ export async function resolveCwdVerdict(
89
89
  const canon = await confirmedSubject(cwd, resolution.subject, realpath);
90
90
  if (canon === null) return { kind: "refuse" };
91
91
 
92
- // Canonical membership against sessions ∪ pins, both sides: a session that
92
+ // Canonical membership against sessions ∪ pins ∪ workspace folders, both sides: a session that
93
93
  // registered for this cwd while the dialog was open admits too.
94
94
  const knownCanon = await canonKnownClassified(deps.known, deps.realpath);
95
95
  if (knownCanon.canon.includes(canon)) return admitIfUnchanged(cwd, canon, realpath);