@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
@@ -127,9 +127,10 @@ export function buildOpenSpecData(
127
127
  typeof statusResult?.isComplete === "boolean" ? statusResult.isComplete : undefined;
128
128
 
129
129
  // Re-derive isComplete from post-override artifacts. Promote false→true
130
- // only when every artifact is done; never demote CLI true.
130
+ // only when every artifact is done or skipped (a declared absence, as in
131
+ // deriveArtifactStatus); never demote CLI true.
131
132
  let isComplete = cliIsComplete;
132
- if (artifacts.length > 0 && artifacts.every((a) => a.status === "done")) {
133
+ if (artifacts.length > 0 && artifacts.every((a) => a.status === "done" || a.status === "skipped")) {
133
134
  isComplete = true;
134
135
  }
135
136
 
@@ -23,11 +23,23 @@
23
23
 
24
24
  import { truncateUtf8 } from "./display-name.js";
25
25
  import { isKnockRefusal, type KnockRefusal } from "./pairing-knock.js";
26
+ import { validateDeliveredRoutes } from "./server-routes.js";
26
27
 
27
28
  export type KnockRefusalReason = KnockRefusal | "untrusted origin" | "unsupported_media_type" | "unknown";
28
29
 
29
30
  export type KnockOutcome =
30
- | { status: "approved"; token: string; fingerprint: string }
31
+ | {
32
+ status: "approved";
33
+ token: string;
34
+ fingerprint: string;
35
+ /**
36
+ * `https` origins the server delivered with the approval, already validated
37
+ * (`validateDeliveredRoutes`); absent when none survived. NOT yet proven at
38
+ * the fingerprint — only a client with its own store may keep one, and only after it proves.
39
+ * See change: group-servers-by-identity (D7).
40
+ */
41
+ routes?: string[];
42
+ }
31
43
  | { status: "identity_mismatch"; expected: string; proven: string | null; stage: "challenge" | "response" }
32
44
  | { status: "refused"; reason: KnockRefusalReason; retryAfter?: number; httpStatus: number }
33
45
  | { status: "rejected" }
@@ -196,6 +208,30 @@ export async function sendKnock(
196
208
  return pollForOutcome(baseUrl, data.pendingId, expiresAt, provenFingerprint, hooks);
197
209
  }
198
210
 
211
+ /**
212
+ * Redeem step for a one-time pairing code (`POST /api/pair/redeem`) at an address whose identity
213
+ * is already proven, then poll for the operator's approval like a knock. The redeem answer
214
+ * carries no fingerprint and no expiry: the proof is the one done at this same origin, and the
215
+ * poll loop is bounded by the server ending the request (any non-`pending` status is terminal)
216
+ * and by {@link MAX_KNOCK_LIFETIME_MS}. A refused redeem is `refused` (`reason` `unknown`; the
217
+ * caller maps `httpStatus`). The code is never echoed into an outcome.
218
+ * See change: group-servers-by-identity (D8).
219
+ */
220
+ export async function redeemPairingCode(
221
+ baseUrl: string,
222
+ provenFingerprint: string,
223
+ code: string,
224
+ hooks: KnockHooks = {},
225
+ ): Promise<KnockOutcome> {
226
+ const redeemed = await post<{ pendingId: string; confirmCode: string }>(baseUrl, "/api/pair/redeem", { code }, hooks.redirect);
227
+ const data = redeemed.json.data;
228
+ if (!redeemed.json.success || !data) return refusal(redeemed.status, redeemed.json);
229
+ if (!/^\d{8}$/.test(String(data.confirmCode)) || typeof data.pendingId !== "string") return refusal(redeemed.status, {});
230
+ const expiresAt = (hooks.now ?? Date.now)() + MAX_KNOCK_LIFETIME_MS;
231
+ hooks.onWaiting?.({ pendingId: data.pendingId, confirmCode: data.confirmCode, expiresAt });
232
+ return pollForOutcome(baseUrl, data.pendingId, expiresAt, provenFingerprint, hooks);
233
+ }
234
+
199
235
  /** Prove-then-knock for callers that do not pause between the two steps. */
200
236
  export async function knockServerWith(
201
237
  prove: ProveFn,
@@ -210,7 +246,8 @@ export async function knockServerWith(
210
246
  return sendKnock(baseUrl, proof.fingerprint, name, hooks);
211
247
  }
212
248
 
213
- type PollEnvelope = Awaited<ReturnType<typeof post<{ status: string; token?: string }>>>;
249
+ type PollData = { status: string; token?: string; routes?: unknown };
250
+ type PollEnvelope = Awaited<ReturnType<typeof post<PollData>>>;
214
251
 
215
252
  /** One poll request; a transport failure is returned, not thrown, so the loop can decide. */
216
253
  async function tryPoll(
@@ -219,7 +256,7 @@ async function tryPoll(
219
256
  redirect?: RequestRedirect,
220
257
  ): Promise<{ ok: true; poll: PollEnvelope } | { ok: false; error: unknown }> {
221
258
  try {
222
- return { ok: true, poll: await post<{ status: string; token?: string }>(baseUrl, "/api/pair/poll", { pendingId }, redirect) };
259
+ return { ok: true, poll: await post<PollData>(baseUrl, "/api/pair/poll", { pendingId }, redirect) };
223
260
  } catch (error) {
224
261
  return { ok: false, error };
225
262
  }
@@ -228,7 +265,10 @@ async function tryPoll(
228
265
  /** A terminal outcome for one poll answer, or null while the request is still pending and unexpired. */
229
266
  function classifyPoll(poll: PollEnvelope, fingerprint: string, elapsed: boolean): KnockOutcome | null {
230
267
  const p = poll.json.data;
231
- if (p?.status === "approved" && typeof p.token === "string" && p.token.length > 0 && p.token.length <= MAX_TOKEN_CHARS) return { status: "approved", token: p.token, fingerprint };
268
+ if (p?.status === "approved" && typeof p.token === "string" && p.token.length > 0 && p.token.length <= MAX_TOKEN_CHARS) {
269
+ const routes = validateDeliveredRoutes(p.routes);
270
+ return { status: "approved", token: p.token, fingerprint, ...(routes.length > 0 ? { routes } : {}) };
271
+ }
232
272
  if (p?.status === "rejected") return { status: "rejected" };
233
273
  return !poll.json.success || p?.status !== "pending" || elapsed ? { status: "expired" } : null;
234
274
  }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Browser-safe wire types + validators for the live trust query
3
+ * (`POST /api/pi-trust/query`). No Node imports.
4
+ *
5
+ * A covered answer has two shapes, by requester class:
6
+ * - local (genuinely local proof): the covering folder, its source kind and
7
+ * the folder identity recorded when the live entry was created;
8
+ * - remote (paired device): only `{covered, salt, digest}` — never the source
9
+ * kind or an identity.
10
+ *
11
+ * See change: mirror-dashboard-trust-live-remote (D1, D4, D5).
12
+ */
13
+ import type { MirrorSourceKind } from "./pi-trust-mirror-types.js";
14
+
15
+ /** Body cap (bytes) and cwd cap (characters) of a live query. */
16
+ export const PI_TRUST_QUERY_MAX_BODY_BYTES = 8192;
17
+ export const PI_TRUST_QUERY_MAX_CWD = 4096;
18
+
19
+ export const PI_TRUST_QUERY_PATH = "/api/pi-trust/query";
20
+
21
+ export interface PiTrustLiveQueryRequest {
22
+ cwd: string;
23
+ }
24
+
25
+ export type PiTrustLiveQueryBodyCheck =
26
+ | { ok: true; cwd: string }
27
+ | { ok: false; status: 400 | 413; error: string };
28
+
29
+ /**
30
+ * Validate a parsed query body: an object with a string `cwd` that is absolute,
31
+ * NUL-free and at most 4,096 characters. The byte cap is the caller's (it needs
32
+ * the raw length). Never throws.
33
+ */
34
+ export function validatePiTrustQueryBody(body: unknown, rawBytes?: number): PiTrustLiveQueryBodyCheck {
35
+ if (typeof rawBytes === "number" && rawBytes > PI_TRUST_QUERY_MAX_BODY_BYTES) {
36
+ return { ok: false, status: 413, error: "body too large" };
37
+ }
38
+ if (!body || typeof body !== "object" || Array.isArray(body)) return { ok: false, status: 400, error: "malformed body" };
39
+ const cwd = (body as { cwd?: unknown }).cwd;
40
+ if (typeof cwd !== "string" || cwd.length === 0) return { ok: false, status: 400, error: "cwd required" };
41
+ if (cwd.length > PI_TRUST_QUERY_MAX_CWD) return { ok: false, status: 400, error: "cwd too long" };
42
+ if (cwd.includes("\0")) return { ok: false, status: 400, error: "cwd malformed" };
43
+ if (!(cwd.startsWith("/") || /^[A-Za-z]:[\\/]/.test(cwd) || cwd.startsWith("\\\\"))) {
44
+ return { ok: false, status: 400, error: "cwd must be absolute" };
45
+ }
46
+ return { ok: true, cwd };
47
+ }
48
+
49
+ export type PiTrustLiveAnswer =
50
+ | { covered: false }
51
+ | { covered: true; salt: string; digest: string }
52
+ | {
53
+ covered: true;
54
+ key: string;
55
+ sourceKind: MirrorSourceKind;
56
+ dev: string;
57
+ ino: string;
58
+ birthtimeMs?: number;
59
+ };
60
+
61
+ export type PiTrustLiveCovered = Exclude<PiTrustLiveAnswer, { covered: false }>;
62
+
63
+ export function isRemoteLiveAnswer(a: PiTrustLiveCovered): a is Extract<PiTrustLiveCovered, { salt: string }> {
64
+ return "salt" in a;
65
+ }
66
+
67
+ /** Strictly parse an answer body; anything that is not one of the three shapes is `null`. */
68
+ export function parsePiTrustLiveAnswer(body: unknown): PiTrustLiveAnswer | null {
69
+ if (!body || typeof body !== "object" || Array.isArray(body)) return null;
70
+ const b = body as Record<string, unknown>;
71
+ if (b.covered === false) return { covered: false };
72
+ if (b.covered !== true) return null;
73
+ if (typeof b.salt === "string" && typeof b.digest === "string" && b.salt && b.digest) {
74
+ return { covered: true, salt: b.salt, digest: b.digest };
75
+ }
76
+ if (
77
+ typeof b.key === "string" &&
78
+ typeof b.sourceKind === "string" &&
79
+ typeof b.dev === "string" &&
80
+ typeof b.ino === "string" &&
81
+ (b.birthtimeMs === undefined || typeof b.birthtimeMs === "number")
82
+ ) {
83
+ return {
84
+ covered: true,
85
+ key: b.key,
86
+ sourceKind: b.sourceKind as MirrorSourceKind,
87
+ dev: b.dev,
88
+ ino: b.ino,
89
+ ...(typeof b.birthtimeMs === "number" ? { birthtimeMs: b.birthtimeMs } : {}),
90
+ };
91
+ }
92
+ return null;
93
+ }
@@ -20,6 +20,7 @@ import {
20
20
  statFolderIdentity,
21
21
  } from "./pi-trust-mirror.js";
22
22
  import type { MirrorWithheldReason, PiTrustSnapshot, PiTrustSnapshotEntry } from "./pi-trust-mirror-types.js";
23
+ import { hasProjectRootMarker } from "./project-root.js";
23
24
  import { hookDefHash, normalizeHook } from "./worktree-init-hook.js";
24
25
 
25
26
  /** `~/.pi/dashboard/pi-trust-mirror.json` — server-written, bridge-read. */
@@ -57,7 +58,9 @@ export function readPiTrustMirrorSnapshot(file: string = piTrustMirrorSnapshotPa
57
58
  if (!parsed || typeof parsed !== "object") return null;
58
59
  const p = parsed as Record<string, unknown>;
59
60
  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
+ const live = p.liveCount;
62
+ const liveCount = typeof live === "number" && Number.isInteger(live) && live >= 0 ? live : 0;
63
+ return { version: 1, generation: p.generation, entries: p.entries.filter(validEntry), liveCount };
61
64
  } catch {
62
65
  return null;
63
66
  }
@@ -122,12 +125,7 @@ export function currentHookHash(configRoot: string): string | null {
122
125
  }
123
126
 
124
127
  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
- }
128
+ return isCanonicalAbsolutePath(dir) && hasProjectRootMarker(dir);
131
129
  }
132
130
 
133
131
  export type SnapshotCoverage =
@@ -3,8 +3,11 @@
3
3
  * See change: mirror-dashboard-trust-to-pi.
4
4
  */
5
5
 
6
- /** Durable trust source ids (mirrors `PiTrustMirrorSourceId` in config). */
7
- export type MirrorSourceKind = "worktreeInit" | "workflow" | "pinned" | "folderWorkspaces" | "accessGrants";
6
+ /**
7
+ * Trust source ids (mirrors `PiTrustMirrorSourceId` in config). `yolo` is
8
+ * live-only: it never appears in the snapshot.
9
+ */
10
+ export type MirrorSourceKind = "worktreeInit" | "workflow" | "pinned" | "folderWorkspaces" | "accessGrants" | "yolo";
8
11
 
9
12
  /** Why an entry does not confer pi trust (Access page + bridge log vocabulary). */
10
13
  export type MirrorIgnoreReason =
@@ -21,7 +24,15 @@ export type MirrorWithheldReason =
21
24
  | MirrorIgnoreReason
22
25
  | "recorded-entry"
23
26
  | "store-unreadable"
24
- | "not-covered-session";
27
+ | "not-covered-session"
28
+ | "identity-weak"
29
+ | "live-timeout"
30
+ | "live-unreachable"
31
+ | "live-refused"
32
+ | "live-unsupported"
33
+ | "live-rate-limited"
34
+ | "live-not-covered"
35
+ | "live-error";
25
36
 
26
37
  /** Readable label per ignore reason (Access page). */
27
38
  export const MIRROR_REASON_LABELS: Record<MirrorIgnoreReason, string> = {
@@ -34,6 +45,22 @@ export const MIRROR_REASON_LABELS: Record<MirrorIgnoreReason, string> = {
34
45
  "choice-unreadable": "per-entry choices unreadable",
35
46
  };
36
47
 
48
+ /** Readable label per bridge reason code (Access page legend; a code from a bridge log can be looked up). */
49
+ export const MIRROR_WITHHELD_LABELS: Record<MirrorWithheldReason, string> = {
50
+ ...MIRROR_REASON_LABELS,
51
+ "recorded-entry": "pi already has a recorded decision for this folder",
52
+ "store-unreadable": "pi's trust store could not be read",
53
+ "not-covered-session": "dashboard trust does not cover this session kind",
54
+ "identity-weak": "folder proof unavailable (empty, symlinked, referenced code outside it, or too large)",
55
+ "live-timeout": "live query did not finish within the time budget",
56
+ "live-unreachable": "dashboard server could not be reached",
57
+ "live-refused": "dashboard server refused the live query",
58
+ "live-unsupported": "dashboard server does not offer the live query",
59
+ "live-rate-limited": "dashboard server rate-limited the live query",
60
+ "live-not-covered": "dashboard server does not trust this folder right now",
61
+ "live-error": "live query failed or returned an unusable answer",
62
+ };
63
+
37
64
  /** One durable entry in `~/.pi/dashboard/pi-trust-mirror.json`. */
38
65
  export interface PiTrustSnapshotEntry {
39
66
  /** Canonical folder path in pi's trust-store key form. */
@@ -54,4 +81,10 @@ export interface PiTrustSnapshot {
54
81
  /** Strictly increases on every rewrite. */
55
82
  generation: number;
56
83
  entries: PiTrustSnapshotEntry[];
84
+ /**
85
+ * How many server-lifetime (live) entries count right now. A count only —
86
+ * never a path or identity (live trust is memory-only). Readers treat a
87
+ * missing or invalid value as 0.
88
+ */
89
+ liveCount: number;
57
90
  }
@@ -14,6 +14,7 @@
14
14
  * See change: mirror-dashboard-trust-to-pi.
15
15
  */
16
16
  import * as fs from "node:fs";
17
+ import * as fsp from "node:fs/promises";
17
18
  import os from "node:os";
18
19
  import path from "node:path";
19
20
  import type { PiTrustMirrorSourceId } from "./config.js";
@@ -230,7 +231,7 @@ export type DefaultProjectTrust = "always" | "never" | "ask";
230
231
  export type PiTrustSource =
231
232
  | { kind: "implicit" }
232
233
  | { kind: "recorded"; path: string }
233
- | { kind: "dashboard"; sourceKind: MirrorSourceKind; entry: string }
234
+ | { kind: "dashboard"; sourceKind: MirrorSourceKind; entry: string; lifetime?: string }
234
235
  | { kind: "default"; value: DefaultProjectTrust };
235
236
 
236
237
  export interface PiTrustDecision {
@@ -244,7 +245,7 @@ export interface DecidePiTrustInput {
244
245
  /** pi's nearest recorded entry (true OR false), or null. */
245
246
  recordedEntry: { path: string; decision: boolean } | null;
246
247
  /** The counted dashboard entry covering the cwd, or null. */
247
- mirrorEntry: { sourceKind: MirrorSourceKind; key: string } | null;
248
+ mirrorEntry: { sourceKind: MirrorSourceKind; key: string; lifetime?: string } | null;
248
249
  /** `piTrustMirror.enabled`. */
249
250
  mirrorEnabled: boolean;
250
251
  piDefault: DefaultProjectTrust;
@@ -263,7 +264,12 @@ export function decidePiTrust(input: DecidePiTrustInput): PiTrustDecision {
263
264
  if (input.mirrorEnabled && input.mirrorEntry) {
264
265
  return {
265
266
  trusted: true,
266
- source: { kind: "dashboard", sourceKind: input.mirrorEntry.sourceKind, entry: input.mirrorEntry.key },
267
+ source: {
268
+ kind: "dashboard",
269
+ sourceKind: input.mirrorEntry.sourceKind,
270
+ entry: input.mirrorEntry.key,
271
+ ...(input.mirrorEntry.lifetime ? { lifetime: input.mirrorEntry.lifetime } : {}),
272
+ },
267
273
  };
268
274
  }
269
275
  return { trusted: input.piDefault === "always", source: { kind: "default", value: input.piDefault } };
@@ -276,6 +282,7 @@ export const MIRROR_SOURCE_LABELS: Record<MirrorSourceKind, string> = {
276
282
  pinned: "pinned folder",
277
283
  folderWorkspaces: "folder workspace",
278
284
  accessGrants: "access grant",
285
+ yolo: "YOLO session",
279
286
  };
280
287
 
281
288
  // ── Covering entry + identity ─────────────────────────────────────────────
@@ -316,6 +323,25 @@ export function statFolderIdentity(dir: string): FolderIdentity | null {
316
323
  }
317
324
  }
318
325
 
326
+ /**
327
+ * `statFolderIdentity` on `fs/promises`, for the bridge's bounded live step (a hung
328
+ * mount must not block the event loop past the deadline). Honours `signal`:
329
+ * aborted → `null`. Same shape and rules as the sync form.
330
+ */
331
+ export async function statFolderIdentityAsync(dir: string, signal?: AbortSignal): Promise<FolderIdentity | null> {
332
+ if (!isCanonicalAbsolutePath(dir) || signal?.aborted) return null;
333
+ try {
334
+ const st = await fsp.stat(dir, { bigint: true });
335
+ if (signal?.aborted) return null;
336
+ const identity: FolderIdentity = { dev: st.dev.toString(), ino: st.ino.toString() };
337
+ const birth = Number(st.birthtimeMs);
338
+ if (Number.isFinite(birth) && birth > 0 && st.birthtimeMs !== st.ctimeMs) identity.birthtimeMs = birth;
339
+ return identity;
340
+ } catch {
341
+ return null;
342
+ }
343
+ }
344
+
319
345
  /** Observed identity equals the entry's: dev + ino, and birth time when the entry recorded one. */
320
346
  export function identityMatches(
321
347
  entry: { dev: string; ino: string; birthtimeMs?: number },
@@ -0,0 +1,255 @@
1
+ /**
2
+ * Content proof for REMOTE live trust answers: a salted digest of exactly what
3
+ * pi's project-trust gate protects for a cwd.
4
+ *
5
+ * pi decides "does this folder need trust" from `<cwd>/.pi/{settings.json,
6
+ * mcp.json, extensions, skills, prompts, themes, SYSTEM.md, APPEND_SYSTEM.md}`
7
+ * plus `<d>/.agents/skills` for the cwd and every ancestor (except the user's own
8
+ * `~/.agents/skills`). `trustResourceManifest` lists every entry under that set
9
+ * (files by content hash, directories by name) and the answer binds it to the
10
+ * cwd key with an HMAC over a fresh salt. Two sides trust only on equality of two
11
+ * computed digests, so a different folder at the same path (or a copy that
12
+ * differs in `.pi/mcp.json`) never inherits trust.
13
+ *
14
+ * Fail-closed → `null`: empty set, any symlink / non-regular entry, a read
15
+ * failure, a cap (1,000 entries / 16 MiB), unparseable or unrecognised
16
+ * `.pi/settings.json` references, or references to code outside the set.
17
+ * Async (`fs/promises`) with an AbortSignal checked after every awaited read, so
18
+ * the bridge's single deadline can stop the walk.
19
+ *
20
+ * Node-only. See change: mirror-dashboard-trust-live-remote (D5).
21
+ */
22
+ import { createHash, createHmac, randomBytes } from "node:crypto";
23
+ import * as fsp from "node:fs/promises";
24
+ import path from "node:path";
25
+
26
+ /**
27
+ * pi does not export its own list (`TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES`),
28
+ * so ours is a literal, pinned to pi's by a golden test.
29
+ */
30
+ export const TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES: readonly string[] = [
31
+ "settings.json",
32
+ "mcp.json",
33
+ "extensions",
34
+ "skills",
35
+ "prompts",
36
+ "themes",
37
+ "SYSTEM.md",
38
+ "APPEND_SYSTEM.md",
39
+ ];
40
+
41
+ /** `.pi` subtrees a settings reference may legitimately point into (all hashed recursively). */
42
+ const CODE_SUBTREES = ["extensions", "skills", "prompts", "themes"] as const;
43
+
44
+ export const TRUST_RESOURCE_MAX_ENTRIES = 1000;
45
+ export const TRUST_RESOURCE_MAX_BYTES = 16 * 1024 * 1024;
46
+
47
+ const DIGEST_DOMAIN = "pi-trust-live/v1";
48
+
49
+ class FailClosed extends Error {}
50
+
51
+ interface Walk {
52
+ entries: Array<{ label: string; line: string }>;
53
+ bytes: number;
54
+ signal?: AbortSignal;
55
+ }
56
+
57
+ function checkAbort(w: Walk): void {
58
+ if (w.signal?.aborted) throw new FailClosed("aborted");
59
+ }
60
+
61
+ function addEntry(w: Walk, label: string, line: string): void {
62
+ if (w.entries.length >= TRUST_RESOURCE_MAX_ENTRIES) throw new FailClosed("too many entries");
63
+ w.entries.push({ label, line });
64
+ }
65
+
66
+ async function lstatOrNull(p: string, w: Walk): Promise<import("node:fs").Stats | null> {
67
+ try {
68
+ const st = await fsp.lstat(p);
69
+ checkAbort(w);
70
+ return st;
71
+ } catch (err) {
72
+ checkAbort(w);
73
+ if ((err as NodeJS.ErrnoException)?.code === "ENOENT" || (err as NodeJS.ErrnoException)?.code === "ENOTDIR") return null;
74
+ throw new FailClosed("stat failed");
75
+ }
76
+ }
77
+
78
+ async function addDirectory(w: Walk, abs: string, label: string): Promise<void> {
79
+ addEntry(w, label, `${label}\0d`);
80
+ // Iterate (not `readdir`): a directory of millions of names stops at the entry cap
81
+ // instead of being listed into memory first.
82
+ let handle: import("node:fs").Dir;
83
+ try {
84
+ handle = await fsp.opendir(abs);
85
+ } catch {
86
+ throw new FailClosed("readdir failed");
87
+ }
88
+ try {
89
+ for await (const ent of handle) {
90
+ checkAbort(w);
91
+ await addTree(w, path.join(abs, ent.name), `${label}/${ent.name}`);
92
+ }
93
+ } catch (err) {
94
+ if (err instanceof FailClosed) throw err;
95
+ throw new FailClosed("readdir failed");
96
+ } finally {
97
+ await handle.close().catch(() => undefined);
98
+ }
99
+ checkAbort(w);
100
+ }
101
+
102
+ async function addFile(w: Walk, abs: string, label: string, size: number): Promise<void> {
103
+ if (w.bytes + size > TRUST_RESOURCE_MAX_BYTES) throw new FailClosed("too large");
104
+ w.bytes += size;
105
+ let buf: Buffer;
106
+ try {
107
+ buf = await fsp.readFile(abs, w.signal ? { signal: w.signal } : undefined);
108
+ } catch {
109
+ throw new FailClosed("read failed");
110
+ }
111
+ checkAbort(w);
112
+ addEntry(w, label, `${label}\0f\0${createHash("sha256").update(buf).digest("hex")}`);
113
+ }
114
+
115
+ /** Add `abs` (labelled `label`) and, for a directory, everything below it. */
116
+ async function addTree(w: Walk, abs: string, label: string): Promise<boolean> {
117
+ const st = await lstatOrNull(abs, w);
118
+ if (!st) return false;
119
+ if (st.isSymbolicLink()) throw new FailClosed("symlink");
120
+ if (st.isDirectory()) await addDirectory(w, abs, label);
121
+ else if (st.isFile()) await addFile(w, abs, label, st.size);
122
+ else throw new FailClosed("special file");
123
+ return true;
124
+ }
125
+
126
+ function withinOrEqual(child: string, parent: string): boolean {
127
+ const rel = path.relative(parent, child);
128
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
129
+ }
130
+
131
+ /** One settings reference: optional include/exclude marker, optional glob tail; must resolve inside `roots`. */
132
+ function referenceInside(item: unknown, piDir: string, roots: readonly string[]): boolean {
133
+ if (typeof item !== "string") return false;
134
+ let ref = item;
135
+ if (ref.startsWith("!") || ref.startsWith("+") || ref.startsWith("-")) ref = ref.slice(1);
136
+ const glob = ref.search(/[*?[{]/);
137
+ if (glob >= 0) ref = ref.slice(0, ref.lastIndexOf("/", glob) + 1) || ".";
138
+ const resolved = path.resolve(piDir, ref);
139
+ return roots.some((r) => withinOrEqual(resolved, r));
140
+ }
141
+
142
+ async function readSettings(w: Walk, file: string): Promise<Record<string, unknown>> {
143
+ let parsed: unknown;
144
+ try {
145
+ parsed = JSON.parse(await fsp.readFile(file, "utf8"));
146
+ } catch {
147
+ throw new FailClosed("settings unparseable");
148
+ }
149
+ checkAbort(w);
150
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new FailClosed("settings shape");
151
+ return parsed as Record<string, unknown>;
152
+ }
153
+
154
+ /**
155
+ * `.pi/settings.json` may point pi at code. Every reference must stay inside the
156
+ * hashed subtrees; `packages` (fetched by pi) and any shape we do not recognise
157
+ * fail closed.
158
+ */
159
+ async function checkSettingsRefs(w: Walk, piDir: string): Promise<void> {
160
+ const file = path.join(piDir, "settings.json");
161
+ if (!(await lstatOrNull(file, w))) return;
162
+ const obj = await readSettings(w, file);
163
+ if ("packages" in obj && (!Array.isArray(obj.packages) || obj.packages.length > 0)) {
164
+ throw new FailClosed("packages referenced");
165
+ }
166
+ const roots = CODE_SUBTREES.map((n) => path.join(piDir, n));
167
+ for (const key of CODE_SUBTREES) {
168
+ if (!(key in obj)) continue;
169
+ const list = obj[key];
170
+ if (!Array.isArray(list)) throw new FailClosed("reference shape");
171
+ if (!list.every((item) => referenceInside(item, piDir, roots))) throw new FailClosed("reference outside set");
172
+ }
173
+ }
174
+
175
+ function compareCodePoints(a: string, b: string): number {
176
+ const ai = Array.from(a);
177
+ const bi = Array.from(b);
178
+ const n = Math.min(ai.length, bi.length);
179
+ for (let i = 0; i < n; i += 1) {
180
+ const x = ai[i].codePointAt(0) as number;
181
+ const y = bi[i].codePointAt(0) as number;
182
+ if (x !== y) return x - y;
183
+ }
184
+ return ai.length - bi.length;
185
+ }
186
+
187
+ async function realOrSelf(p: string): Promise<string> {
188
+ try {
189
+ return await fsp.realpath(p);
190
+ } catch {
191
+ return path.resolve(p);
192
+ }
193
+ }
194
+
195
+ /** `<cwd>/.pi/<resource>` for every name pi's gate protects (a symlinked `.pi` fails closed). */
196
+ async function collectPiResources(w: Walk, cwd: string): Promise<void> {
197
+ const piDir = path.join(cwd, ".pi");
198
+ const piStat = await lstatOrNull(piDir, w);
199
+ if (!piStat) return;
200
+ if (piStat.isSymbolicLink()) throw new FailClosed("symlink");
201
+ if (!piStat.isDirectory()) return;
202
+ await checkSettingsRefs(w, piDir);
203
+ for (const name of TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES) {
204
+ await addTree(w, path.join(piDir, name), `c/${name}`);
205
+ }
206
+ }
207
+
208
+ /** `<d>/.agents/skills` for the cwd and every ancestor, except the user's own. */
209
+ async function collectAgentSkills(w: Walk, cwd: string, userSkills: string): Promise<void> {
210
+ for (let dir = cwd, k = 0; ; k += 1) {
211
+ const agents = path.join(dir, ".agents");
212
+ const agentsStat = await lstatOrNull(agents, w);
213
+ if (agentsStat?.isSymbolicLink()) throw new FailClosed("symlink");
214
+ const skills = path.join(agents, "skills");
215
+ if (skills !== userSkills && agentsStat) await addTree(w, skills, `a${k}`);
216
+ const parent = path.dirname(dir);
217
+ if (parent === dir) return;
218
+ dir = parent;
219
+ }
220
+ }
221
+
222
+ /**
223
+ * The manifest of pi's trust-requiring resources for `cwd` (a canonical key), or
224
+ * `null` when the set is empty or cannot be bound. `home` is this side's own home
225
+ * (its `.agents/skills` is the user's, excluded).
226
+ */
227
+ export async function trustResourceManifest(
228
+ cwd: string,
229
+ opts: { home: string; signal?: AbortSignal },
230
+ ): Promise<string | null> {
231
+ const w: Walk = { entries: [], bytes: 0, signal: opts.signal };
232
+ try {
233
+ checkAbort(w);
234
+ const userSkills = path.join(await realOrSelf(opts.home), ".agents", "skills");
235
+ checkAbort(w);
236
+ await collectPiResources(w, cwd);
237
+ await collectAgentSkills(w, cwd, userSkills);
238
+ if (w.entries.length === 0) return null;
239
+ w.entries.sort((a, b) => compareCodePoints(a.label, b.label));
240
+ return w.entries.map((e) => e.line).join("\n");
241
+ } catch {
242
+ // FailClosed or anything unexpected: no binding, no trust.
243
+ return null;
244
+ }
245
+ }
246
+
247
+ /** 16 random bytes, hex. Fresh per answer. */
248
+ export function newTrustSalt(): string {
249
+ return randomBytes(16).toString("hex");
250
+ }
251
+
252
+ /** `HMAC-SHA256(salt, "pi-trust-live/v1\n" + cwdKey + "\n" + manifest)`, hex. */
253
+ export function trustResourceDigest(salt: string, cwdKey: string, manifest: string): string {
254
+ return createHmac("sha256", salt).update(`${DIGEST_DOMAIN}\n${cwdKey}\n${manifest}`).digest("hex");
255
+ }