@piagent/platform 1.3.0 → 1.4.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 (304) hide show
  1. package/CHANGELOG.md +56 -3
  2. package/README.md +3 -3
  3. package/architecture/layers.json +96 -1
  4. package/docs/README.md +1 -0
  5. package/docs/architecture.md +1 -0
  6. package/docs/authority-manifest.md +1 -0
  7. package/docs/auto-delegation-policy.md +1 -0
  8. package/docs/capability-packs.md +10 -2
  9. package/docs/command-reference-vietnamese.md +5 -4
  10. package/docs/context-engine.md +1 -0
  11. package/docs/context-window-policy.md +1 -0
  12. package/docs/distribution-standard.md +8 -7
  13. package/docs/herdr-workflow.md +1 -0
  14. package/docs/mcp-and-tools.md +14 -9
  15. package/docs/memory-policy.md +1 -0
  16. package/docs/model-options.md +1 -0
  17. package/docs/oauth-providers.md +1 -0
  18. package/docs/operator-manual-vietnamese.md +15 -12
  19. package/docs/package-architecture-notes.md +1 -0
  20. package/docs/project-adapters.md +1 -0
  21. package/docs/project-onboarding.md +1 -0
  22. package/docs/publishing-for-teams.md +1 -0
  23. package/docs/quality-benchmark.md +1 -0
  24. package/docs/quickstart-vietnamese.md +3 -2
  25. package/docs/release-install-policy.md +11 -7
  26. package/docs/runtime-harness-standard.md +1 -0
  27. package/docs/runtime-policy-design.md +1 -0
  28. package/docs/runtime-quality-baseline.md +1 -0
  29. package/docs/security-redaction-benchmark.md +1 -0
  30. package/docs/security-threat-model.md +2 -1
  31. package/docs/subagent-orchestration-capabilities.md +1 -0
  32. package/docs/subagents-and-multiagent.md +1 -0
  33. package/docs/task-implementation-contract.md +1 -0
  34. package/docs/task-lifecycle-vietnamese.md +1 -0
  35. package/docs/team-onboarding.md +3 -2
  36. package/docs/third-party-neutrality.md +26 -0
  37. package/docs/usage-observability.md +1 -0
  38. package/docs/vercel-docs-site.md +1 -0
  39. package/docs/workflow-recipes.md +1 -0
  40. package/docs-site/architecture.html +1 -1
  41. package/docs-site/benchmark.html +1 -1
  42. package/docs-site/commands.html +1 -1
  43. package/docs-site/context-engine.html +1 -1
  44. package/docs-site/en/architecture.html +1 -1
  45. package/docs-site/en/benchmark.html +1 -1
  46. package/docs-site/en/commands.html +1 -1
  47. package/docs-site/en/context-engine.html +1 -1
  48. package/docs-site/en/index.html +1 -1
  49. package/docs-site/en/mcp-approval.html +1 -1
  50. package/docs-site/en/mcp-auth.html +1 -1
  51. package/docs-site/en/mcp-servers.html +1 -1
  52. package/docs-site/en/mcp.html +1 -1
  53. package/docs-site/en/permissions.html +1 -1
  54. package/docs-site/en/profiles.html +1 -1
  55. package/docs-site/en/quickstart.html +1 -1
  56. package/docs-site/en/runtime.html +1 -1
  57. package/docs-site/en/scope.html +1 -1
  58. package/docs-site/en/security.html +1 -1
  59. package/docs-site/en/team.html +1 -1
  60. package/docs-site/en/whats-new.html +1 -1
  61. package/docs-site/en/workflows.html +1 -1
  62. package/docs-site/index.html +1 -1
  63. package/docs-site/mcp-approval.html +1 -1
  64. package/docs-site/mcp-auth.html +1 -1
  65. package/docs-site/mcp-servers.html +1 -1
  66. package/docs-site/mcp.html +1 -1
  67. package/docs-site/permissions.html +1 -1
  68. package/docs-site/profiles.html +1 -1
  69. package/docs-site/quickstart.html +1 -1
  70. package/docs-site/runtime.html +1 -1
  71. package/docs-site/scope.html +1 -1
  72. package/docs-site/security.html +1 -1
  73. package/docs-site/team.html +1 -1
  74. package/docs-site/whats-new.html +1 -1
  75. package/docs-site/workflows.html +1 -1
  76. package/evals/fixtures/mutation-provenance-record.invalid.json +17 -0
  77. package/evals/fixtures/mutation-provenance-record.valid.json +27 -0
  78. package/evals/fixtures/piagent-webui/approval-v1.invalid.json +54 -0
  79. package/evals/fixtures/piagent-webui/approval-v1.valid.json +58 -0
  80. package/evals/fixtures/piagent-webui/attachment-v1.invalid.json +25 -0
  81. package/evals/fixtures/piagent-webui/attachment-v1.valid.json +25 -0
  82. package/evals/fixtures/piagent-webui/capabilities-v1.invalid.json +51 -0
  83. package/evals/fixtures/piagent-webui/capabilities-v1.valid.json +122 -0
  84. package/evals/fixtures/piagent-webui/commit-summary-v1.invalid.json +10 -0
  85. package/evals/fixtures/piagent-webui/commit-summary-v1.valid.json +25 -0
  86. package/evals/fixtures/piagent-webui/control-command-v1.invalid.json +37 -0
  87. package/evals/fixtures/piagent-webui/control-command-v1.valid.json +35 -0
  88. package/evals/fixtures/piagent-webui/diff-v1.invalid.json +13 -0
  89. package/evals/fixtures/piagent-webui/diff-v1.valid.json +141 -0
  90. package/evals/fixtures/piagent-webui/gateway-capabilities-v1.invalid.json +35 -0
  91. package/evals/fixtures/piagent-webui/gateway-capabilities-v1.valid.json +35 -0
  92. package/evals/fixtures/piagent-webui/gateway-protocol-v1.invalid.json +14 -0
  93. package/evals/fixtures/piagent-webui/gateway-protocol-v1.valid.json +14 -0
  94. package/evals/fixtures/piagent-webui/handoff-history-v1.invalid.json +16 -0
  95. package/evals/fixtures/piagent-webui/handoff-history-v1.valid.json +16 -0
  96. package/evals/fixtures/piagent-webui/model-catalog-v1.invalid.json +31 -0
  97. package/evals/fixtures/piagent-webui/model-catalog-v1.valid.json +43 -0
  98. package/evals/fixtures/piagent-webui/queue-v1.invalid.json +29 -0
  99. package/evals/fixtures/piagent-webui/queue-v1.valid.json +44 -0
  100. package/evals/fixtures/piagent-webui/recovery-history-v1.invalid.json +17 -0
  101. package/evals/fixtures/piagent-webui/recovery-history-v1.valid.json +20 -0
  102. package/evals/fixtures/piagent-webui/release-monitor-v1.invalid.json +12 -0
  103. package/evals/fixtures/piagent-webui/release-monitor-v1.valid.json +29 -0
  104. package/evals/fixtures/piagent-webui/review-state-v1.invalid.json +25 -0
  105. package/evals/fixtures/piagent-webui/review-state-v1.valid.json +38 -0
  106. package/evals/fixtures/piagent-webui/runtime-event-v2.invalid.json +49 -0
  107. package/evals/fixtures/piagent-webui/runtime-event-v2.valid.json +49 -0
  108. package/evals/fixtures/piagent-webui/session-catalog-v1.invalid.json +17 -0
  109. package/evals/fixtures/piagent-webui/session-catalog-v1.valid.json +58 -0
  110. package/evals/fixtures/piagent-webui/session-command-v1.invalid.json +19 -0
  111. package/evals/fixtures/piagent-webui/session-command-v1.valid.json +19 -0
  112. package/evals/fixtures/piagent-webui/snapshot-v1.invalid.json +5 -0
  113. package/evals/fixtures/piagent-webui/snapshot-v1.valid.json +191 -0
  114. package/evals/fixtures/piagent-webui/source-change-v1.invalid.json +57 -0
  115. package/evals/fixtures/piagent-webui/source-change-v1.valid.json +98 -0
  116. package/evals/fixtures/piagent-webui/source-mutation-v1.invalid.json +19 -0
  117. package/evals/fixtures/piagent-webui/source-mutation-v1.valid.json +38 -0
  118. package/evals/fixtures/piagent-webui/source-revert-v1.invalid.json +20 -0
  119. package/evals/fixtures/piagent-webui/source-revert-v1.valid.json +62 -0
  120. package/evals/fixtures/piagent-webui/subagent-tree-v1.invalid.json +26 -0
  121. package/evals/fixtures/piagent-webui/subagent-tree-v1.valid.json +39 -0
  122. package/evals/fixtures/piagent-webui/task-index-v1.invalid.json +15 -0
  123. package/evals/fixtures/piagent-webui/task-index-v1.valid.json +15 -0
  124. package/evals/fixtures/piagent-webui/task-timeline-v1.invalid.json +14 -0
  125. package/evals/fixtures/piagent-webui/task-timeline-v1.valid.json +16 -0
  126. package/evals/fixtures/piagent-webui/transcript-v1.invalid.json +35 -0
  127. package/evals/fixtures/piagent-webui/transcript-v1.valid.json +55 -0
  128. package/evals/fixtures/task-baseline-manifest.invalid.json +16 -0
  129. package/evals/fixtures/task-baseline-manifest.valid.json +41 -0
  130. package/evals/fixtures/verifier-file-snapshot.invalid.json +21 -0
  131. package/evals/fixtures/verifier-file-snapshot.valid.json +21 -0
  132. package/package.json +30 -3
  133. package/packages/piagent-core/benchmark/benchmark-candidate.d.ts +1 -0
  134. package/packages/piagent-core/benchmark/benchmark-forensics.d.ts +1 -0
  135. package/packages/piagent-core/benchmark/benchmark-ledger.d.ts +4 -0
  136. package/packages/piagent-core/benchmark/benchmark-record-validation.d.ts +1 -0
  137. package/packages/piagent-core/benchmark/benchmark-runtime.d.ts +1 -0
  138. package/packages/piagent-core/capabilities/capability-core.js +2 -2
  139. package/packages/piagent-core/capabilities/capability-verification-cache.js +280 -0
  140. package/packages/piagent-core/capabilities/runtime-integrity.js +153 -1
  141. package/packages/piagent-core/extensions/document-intake.ts +24 -10
  142. package/packages/piagent-core/extensions/piagent-guard.ts +90 -73
  143. package/packages/piagent-core/extensions/redaction-core.d.ts +2 -0
  144. package/packages/piagent-core/extensions/state-retention.js +77 -44
  145. package/packages/piagent-core/extensions/task-journal.js +30 -1
  146. package/packages/piagent-core/extensions/task-state.js +33 -36
  147. package/packages/piagent-core/mcp/mcp-server-catalog.js +5 -5
  148. package/packages/piagent-core/package.json +1 -1
  149. package/packages/piagent-core/runtime/hooks/session-start-hook.ts +2 -2
  150. package/packages/piagent-core/runtime/hooks/tool-call-hook.ts +5 -2
  151. package/packages/piagent-core/runtime/hooks/tool-result-hook.ts +20 -19
  152. package/packages/piagent-core/runtime/hooks/tool-result-metadata.ts +13 -0
  153. package/packages/piagent-core/runtime/input/chat-images.ts +2 -2
  154. package/packages/piagent-core/runtime/inspection/activity-event-adapter.ts +94 -0
  155. package/packages/piagent-core/runtime/inspection/approval-broker.ts +318 -0
  156. package/packages/piagent-core/runtime/inspection/commit-summary-projection.ts +59 -0
  157. package/packages/piagent-core/runtime/inspection/context-telemetry-inspection.ts +37 -0
  158. package/packages/piagent-core/runtime/inspection/criteria-links.ts +295 -0
  159. package/packages/piagent-core/runtime/inspection/diff-projection.ts +499 -0
  160. package/packages/piagent-core/runtime/inspection/git-filter-safety.ts +38 -0
  161. package/packages/piagent-core/runtime/inspection/git-numstat-adapter.ts +71 -0
  162. package/packages/piagent-core/runtime/inspection/git-status-adapter.ts +493 -0
  163. package/packages/piagent-core/runtime/inspection/git-tree-adapter.ts +108 -0
  164. package/packages/piagent-core/runtime/inspection/mcp-control.ts +10 -0
  165. package/packages/piagent-core/runtime/inspection/mutation-provenance-contract.ts +131 -0
  166. package/packages/piagent-core/runtime/inspection/mutation-provenance-recorder.ts +48 -0
  167. package/packages/piagent-core/runtime/inspection/mutation-provenance-store.ts +161 -0
  168. package/packages/piagent-core/runtime/inspection/project-runtime-inspection.ts +36 -0
  169. package/packages/piagent-core/runtime/inspection/review-state-contract.ts +108 -0
  170. package/packages/piagent-core/runtime/inspection/review-state-projection.ts +93 -0
  171. package/packages/piagent-core/runtime/inspection/review-state-store.ts +112 -0
  172. package/packages/piagent-core/runtime/inspection/runtime-event-store.ts +262 -0
  173. package/packages/piagent-core/runtime/inspection/same-process-bridge-proof.ts +103 -0
  174. package/packages/piagent-core/runtime/inspection/source-change-projection.ts +471 -0
  175. package/packages/piagent-core/runtime/inspection/source-evidence-contract.ts +139 -0
  176. package/packages/piagent-core/runtime/inspection/source-evidence-store.ts +315 -0
  177. package/packages/piagent-core/runtime/inspection/source-handoff-store.ts +70 -0
  178. package/packages/piagent-core/runtime/inspection/source-inspection-plan.ts +34 -0
  179. package/packages/piagent-core/runtime/inspection/source-mutation-projection.ts +164 -0
  180. package/packages/piagent-core/runtime/inspection/source-mutation-store.ts +168 -0
  181. package/packages/piagent-core/runtime/inspection/source-open-target.ts +38 -0
  182. package/packages/piagent-core/runtime/inspection/source-revert-projection.ts +147 -0
  183. package/packages/piagent-core/runtime/inspection/task-baseline-start-capture.ts +22 -0
  184. package/packages/piagent-core/runtime/inspection/task-compaction-history.ts +160 -0
  185. package/packages/piagent-core/runtime/inspection/task-control-journal.ts +131 -0
  186. package/packages/piagent-core/runtime/inspection/task-handoff-history.ts +95 -0
  187. package/packages/piagent-core/runtime/inspection/task-provenance-projection.ts +60 -0
  188. package/packages/piagent-core/runtime/inspection/task-recovery-timeline.ts +88 -0
  189. package/packages/piagent-core/runtime/inspection/task-run-index.ts +87 -0
  190. package/packages/piagent-core/runtime/inspection/task-source-projection.ts +401 -0
  191. package/packages/piagent-core/runtime/inspection/task-subagent-tree.ts +101 -0
  192. package/packages/piagent-core/runtime/inspection/text-diff.ts +60 -0
  193. package/packages/piagent-core/runtime/inspection/verifier-snapshot-contract.ts +114 -0
  194. package/packages/piagent-core/runtime/inspection/verifier-snapshot-store.ts +189 -0
  195. package/packages/piagent-core/runtime/inspection/webui-snapshot.ts +320 -0
  196. package/packages/piagent-core/runtime/inspection/workspace-file-reader.ts +132 -0
  197. package/packages/piagent-core/runtime/inspection/workspace-source-projection.ts +96 -0
  198. package/packages/piagent-core/runtime/inspection/zero-turn-conformance.ts +175 -0
  199. package/packages/piagent-core/runtime/orchestration/owned-work-budget.ts +68 -4
  200. package/packages/piagent-core/runtime/policy/source-index-transaction.ts +173 -0
  201. package/packages/piagent-core/runtime/policy/source-mutation-guard-binding.ts +42 -0
  202. package/packages/piagent-core/runtime/policy/source-mutation-guard.ts +184 -0
  203. package/packages/piagent-core/runtime/policy/source-worktree-transaction.ts +105 -0
  204. package/packages/piagent-core/runtime/product/activity-inspector-footer.ts +5 -3
  205. package/packages/piagent-core/runtime/product/activity-inspector.ts +85 -343
  206. package/packages/piagent-core/runtime/recovery/resume-state.ts +38 -1
  207. package/packages/piagent-core/runtime/registration/activity-inspector-command.ts +68 -14
  208. package/packages/piagent-core/runtime/registration/task-start-tool.ts +13 -14
  209. package/packages/piagent-core/runtime/session/model-authorship-state.ts +31 -3
  210. package/packages/piagent-core/runtime/session/runtime-state.ts +11 -1
  211. package/packages/piagent-webui/dist/client/assets/index-DjMntaK5.js +172 -0
  212. package/packages/piagent-webui/dist/client/assets/index-DwKCWbwd.css +1 -0
  213. package/packages/piagent-webui/dist/client/index.html +16 -0
  214. package/packages/piagent-webui/extension/attachment-store.ts +323 -0
  215. package/packages/piagent-webui/extension/held-message-queue.ts +311 -0
  216. package/packages/piagent-webui/extension/lifecycle-controller.ts +408 -0
  217. package/packages/piagent-webui/extension/lifecycle-event-adapter.ts +23 -0
  218. package/packages/piagent-webui/extension/piagent-webui.ts +470 -0
  219. package/packages/piagent-webui/extension/review-controller.ts +160 -0
  220. package/packages/piagent-webui/extension/same-session-bridge.ts +500 -0
  221. package/packages/piagent-webui/extension/session-options-controller.ts +281 -0
  222. package/packages/piagent-webui/extension/session-stream-adapter.ts +249 -0
  223. package/packages/piagent-webui/extension/source-mutation-controller.ts +215 -0
  224. package/packages/piagent-webui/extension/source-open-controller.ts +136 -0
  225. package/packages/piagent-webui/extension/source-revert-controller.ts +189 -0
  226. package/packages/piagent-webui/extension/terminal-session-adapter.ts +73 -0
  227. package/packages/piagent-webui/extension/vscode-handoff.ts +51 -0
  228. package/packages/piagent-webui/gateway/control-socket.ts +92 -0
  229. package/packages/piagent-webui/gateway/gateway-events.ts +60 -0
  230. package/packages/piagent-webui/gateway/gateway-protocol-service.ts +64 -0
  231. package/packages/piagent-webui/gateway/gateway-service.ts +215 -0
  232. package/packages/piagent-webui/gateway/gateway-session-stream.ts +110 -0
  233. package/packages/piagent-webui/gateway/mcp-auth-broker.ts +158 -0
  234. package/packages/piagent-webui/gateway/native-project-picker.ts +29 -0
  235. package/packages/piagent-webui/gateway/pi-host.ts +41 -0
  236. package/packages/piagent-webui/gateway/profile-state.ts +1 -0
  237. package/packages/piagent-webui/gateway/project-registry.ts +108 -0
  238. package/packages/piagent-webui/gateway/provider-auth-broker.ts +172 -0
  239. package/packages/piagent-webui/gateway/session-catalog.ts +128 -0
  240. package/packages/piagent-webui/gateway/session-command-controller.ts +237 -0
  241. package/packages/piagent-webui/gateway/session-command-store.ts +224 -0
  242. package/packages/piagent-webui/gateway/session-inspection-registry.ts +204 -0
  243. package/packages/piagent-webui/gateway/session-lease-store.ts +1 -0
  244. package/packages/piagent-webui/gateway/session-metadata-store.ts +152 -0
  245. package/packages/piagent-webui/gateway/session-runtime-supervisor.ts +485 -0
  246. package/packages/piagent-webui/ownership/gateway-runtime-context.ts +8 -0
  247. package/packages/piagent-webui/ownership/profile-state.ts +117 -0
  248. package/packages/piagent-webui/ownership/session-lease-store.ts +329 -0
  249. package/packages/piagent-webui/ownership/session-refs.ts +8 -0
  250. package/packages/piagent-webui/package.json +33 -0
  251. package/packages/piagent-webui/server/README.md +4 -0
  252. package/packages/piagent-webui/server/benchmark-release-monitor.ts +230 -0
  253. package/packages/piagent-webui/server/core-inspection-provider.ts +403 -0
  254. package/packages/piagent-webui/server/gateway-websocket.ts +143 -0
  255. package/packages/piagent-webui/server/http-security.ts +27 -0
  256. package/packages/piagent-webui/server/ipc-read-model-client.ts +89 -0
  257. package/packages/piagent-webui/server/loopback-server.ts +368 -0
  258. package/packages/piagent-webui/server/read-model-provider.ts +37 -0
  259. package/packages/piagent-webui/server/read-only-router.ts +105 -0
  260. package/packages/piagent-webui/server/session-auth.ts +88 -0
  261. package/packages/piagent-webui/server/sidecar-main.ts +86 -0
  262. package/packages/piagent-webui/server/sse-hub.ts +76 -0
  263. package/packages/piagent-webui/server/static-bundle.ts +40 -0
  264. package/packages/piagent-webui/server/transcript-projection.ts +110 -0
  265. package/schemas/mutation-provenance-record.schema.json +100 -0
  266. package/schemas/piagent-webui/approval-v1.schema.json +654 -0
  267. package/schemas/piagent-webui/attachment-v1.schema.json +267 -0
  268. package/schemas/piagent-webui/capabilities-v1.schema.json +729 -0
  269. package/schemas/piagent-webui/catalog-v1.json +240 -0
  270. package/schemas/piagent-webui/commit-summary-v1.schema.json +63 -0
  271. package/schemas/piagent-webui/common-v1.schema.json +479 -0
  272. package/schemas/piagent-webui/control-command-v1.schema.json +1780 -0
  273. package/schemas/piagent-webui/diff-v1.schema.json +826 -0
  274. package/schemas/piagent-webui/gateway-capabilities-v1.schema.json +136 -0
  275. package/schemas/piagent-webui/gateway-protocol-v1.schema.json +456 -0
  276. package/schemas/piagent-webui/handoff-history-v1.schema.json +92 -0
  277. package/schemas/piagent-webui/model-catalog-v1.schema.json +95 -0
  278. package/schemas/piagent-webui/queue-v1.schema.json +99 -0
  279. package/schemas/piagent-webui/recovery-history-v1.schema.json +144 -0
  280. package/schemas/piagent-webui/release-monitor-v1.schema.json +173 -0
  281. package/schemas/piagent-webui/review-state-v1.schema.json +206 -0
  282. package/schemas/piagent-webui/runtime-event-v2.schema.json +5206 -0
  283. package/schemas/piagent-webui/session-catalog-v1.schema.json +222 -0
  284. package/schemas/piagent-webui/session-command-v1.schema.json +390 -0
  285. package/schemas/piagent-webui/snapshot-v1.schema.json +2622 -0
  286. package/schemas/piagent-webui/source-change-v1.schema.json +763 -0
  287. package/schemas/piagent-webui/source-mutation-v1.schema.json +96 -0
  288. package/schemas/piagent-webui/source-revert-v1.schema.json +130 -0
  289. package/schemas/piagent-webui/subagent-tree-v1.schema.json +88 -0
  290. package/schemas/piagent-webui/task-index-v1.schema.json +74 -0
  291. package/schemas/piagent-webui/task-timeline-v1.schema.json +49 -0
  292. package/schemas/piagent-webui/transcript-v1.schema.json +243 -0
  293. package/schemas/task-baseline-manifest.schema.json +122 -0
  294. package/schemas/verifier-file-snapshot.schema.json +81 -0
  295. package/scripts/check-architecture.mjs +1 -0
  296. package/scripts/check-doc-languages.mjs +19 -2
  297. package/scripts/check-third-party-neutrality.mjs +43 -0
  298. package/scripts/install-global.sh +1 -1
  299. package/scripts/piagent-cli.mjs +17 -3
  300. package/scripts/piagent-dashboard.mjs +208 -0
  301. package/scripts/piagent-webui-launcher.mjs +121 -0
  302. package/scripts/typescript-loader.mjs +26 -1
  303. package/scripts/verify-local.sh +253 -0
  304. package/scripts/verify-release-identity.mjs +4 -1
@@ -0,0 +1,329 @@
1
+ import { createHmac, randomBytes } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+
5
+ const FILE_LIMIT = 256 * 1024; // Shared single-writer authority for Gateway and terminal runtimes.
6
+ const RECORD_LIMIT = 8 * 1024;
7
+ const ENTRY_LIMIT = 512;
8
+ const REF = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/;
9
+
10
+ type LeaseEvent = "acquired" | "released" | "recovery-required";
11
+ type MutationLock = { version: "piagent-session-lease-lock-v1"; pid: number; createdAt: string; nonce: string };
12
+ type LeaseRecord = {
13
+ version: "piagent-session-lease-v1";
14
+ sequence: number;
15
+ recordedAt: string;
16
+ sessionRef: string;
17
+ event: LeaseEvent;
18
+ ownerEpoch: string;
19
+ gatewayInstanceRef: string;
20
+ runtimeInstanceRef: string;
21
+ previousDigest: string | null;
22
+ reasonCode: string | null;
23
+ recordDigest: string;
24
+ };
25
+
26
+ export type SessionLeaseSnapshot = {
27
+ state: "released" | "gateway-owned" | "terminal-owned" | "recovery-required" | "unavailable";
28
+ ownerEpoch: string | null;
29
+ gatewayInstanceRef: string | null;
30
+ runtimeInstanceRef: string | null;
31
+ continuity: "exact" | "released" | "unknown";
32
+ revision: string | null;
33
+ reasonCode: string | null;
34
+ };
35
+
36
+ const TERMINAL_OWNER_PREFIX = "terminal_";
37
+
38
+ function terminalOwnerPid(value: string | null): number | null {
39
+ const match = value?.match(/^terminal_(\d+)_/), pid = Number(match?.[1]);
40
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
41
+ }
42
+
43
+ function gatewayOwnerPid(value: string | null): number | null {
44
+ const match = value?.match(/^gateway_(\d+)_/), pid = Number(match?.[1]);
45
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
46
+ }
47
+
48
+ function processAlive(pid: number): boolean {
49
+ try { process.kill(pid, 0); return true; }
50
+ catch (error) { return !(error && typeof error === "object" && "code" in error && error.code === "ESRCH"); }
51
+ }
52
+
53
+ function exactTimestamp(value: unknown): value is string {
54
+ return typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)
55
+ && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
56
+ }
57
+
58
+ function validRef(value: unknown): value is string { return typeof value === "string" && REF.test(value); }
59
+
60
+ function unsigned(record: LeaseRecord): Omit<LeaseRecord, "recordDigest"> {
61
+ const { recordDigest: _ignored, ...value } = record;
62
+ return value;
63
+ }
64
+
65
+ export class SessionLeaseStore {
66
+ readonly directory: string;
67
+ readonly #key: Buffer;
68
+
69
+ constructor(root: string, key: Buffer) {
70
+ this.directory = path.join(root, "leases");
71
+ this.#key = key;
72
+ fs.mkdirSync(this.directory, { recursive: true, mode: 0o700 });
73
+ const stat = fs.lstatSync(this.directory);
74
+ if (!stat.isDirectory() || stat.isSymbolicLink()
75
+ || (typeof process.getuid === "function" && stat.uid !== process.getuid())) throw new Error("session-lease-root-invalid");
76
+ fs.chmodSync(this.directory, 0o700);
77
+ }
78
+
79
+ #digest(namespace: string, value: unknown): string {
80
+ return `${namespace}_${createHmac("sha256", this.#key).update(JSON.stringify(value)).digest("hex")}`;
81
+ }
82
+
83
+ #file(sessionRef: string): string {
84
+ if (!validRef(sessionRef)) throw new Error("session-lease-ref-invalid");
85
+ return path.join(this.directory, `${this.#digest("lease-file", sessionRef).slice("lease-file_".length)}.jsonl`);
86
+ }
87
+
88
+ #lockFile(sessionRef: string): string {
89
+ return `${this.#file(sessionRef)}.lock`;
90
+ }
91
+
92
+ #reclaimDeadMutationLock(file: string): boolean {
93
+ let stat: fs.Stats;
94
+ try { stat = fs.lstatSync(file); } catch { return false; }
95
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1_024
96
+ || (typeof process.getuid === "function" && stat.uid !== process.getuid())) return false;
97
+ const descriptor = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
98
+ let value: unknown;
99
+ try {
100
+ const opened = fs.fstatSync(descriptor);
101
+ if (opened.dev !== stat.dev || opened.ino !== stat.ino || opened.size !== stat.size) return false;
102
+ value = JSON.parse(fs.readFileSync(descriptor, "utf8"));
103
+ } catch { return false; }
104
+ finally { fs.closeSync(descriptor); }
105
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
106
+ const lock = value as Partial<MutationLock>;
107
+ if (Object.keys(lock).length !== 4 || lock.version !== "piagent-session-lease-lock-v1"
108
+ || !Number.isSafeInteger(lock.pid) || Number(lock.pid) < 1 || !exactTimestamp(lock.createdAt)
109
+ || !validRef(lock.nonce) || processAlive(Number(lock.pid))) return false;
110
+ let current: fs.Stats;
111
+ try { current = fs.lstatSync(file); } catch { return false; }
112
+ if (current.dev !== stat.dev || current.ino !== stat.ino || !current.isFile() || current.isSymbolicLink()) return false;
113
+ try { fs.unlinkSync(file); return true; } catch { return false; }
114
+ }
115
+
116
+ #withMutationLock<T>(sessionRef: string, action: () => T): T {
117
+ const file = this.#lockFile(sessionRef);
118
+ let descriptor: number;
119
+ for (let attempt = 0; ; attempt += 1) {
120
+ try {
121
+ descriptor = fs.openSync(file, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL
122
+ | (fs.constants.O_NOFOLLOW ?? 0), 0o600);
123
+ break;
124
+ } catch (error) {
125
+ if (error && typeof error === "object" && "code" in error && error.code === "EEXIST") {
126
+ if (attempt === 0 && this.#reclaimDeadMutationLock(file)) continue;
127
+ throw new Error("session-lease-busy");
128
+ }
129
+ throw error;
130
+ }
131
+ }
132
+ try {
133
+ const lock: MutationLock = { version: "piagent-session-lease-lock-v1", pid: process.pid,
134
+ createdAt: new Date().toISOString(), nonce: `lock_${randomBytes(24).toString("base64url")}` };
135
+ fs.writeFileSync(descriptor, JSON.stringify(lock)); fs.fsyncSync(descriptor); fs.fchmodSync(descriptor, 0o600);
136
+ return action();
137
+ } finally {
138
+ fs.closeSync(descriptor);
139
+ try { fs.unlinkSync(file); } catch { /* a missing lock fails the next mutation closed through continuity checks */ }
140
+ }
141
+ }
142
+
143
+ #valid(record: unknown, sessionRef: string, index: number, previousDigest: string | null): record is LeaseRecord {
144
+ if (!record || typeof record !== "object" || Array.isArray(record)) return false;
145
+ const value = record as Partial<LeaseRecord>;
146
+ if (Object.keys(value).length !== 11 || !Object.keys(value).every((key) => ["version", "sequence", "recordedAt",
147
+ "sessionRef", "event", "ownerEpoch", "gatewayInstanceRef", "runtimeInstanceRef", "previousDigest", "reasonCode",
148
+ "recordDigest"].includes(key))) return false;
149
+ if (value.version !== "piagent-session-lease-v1" || value.sequence !== index + 1 || !exactTimestamp(value.recordedAt)
150
+ || value.sessionRef !== sessionRef || !["acquired", "released", "recovery-required"].includes(String(value.event))
151
+ || !validRef(value.ownerEpoch) || !validRef(value.gatewayInstanceRef) || !validRef(value.runtimeInstanceRef)
152
+ || value.previousDigest !== previousDigest || !validRef(value.recordDigest)
153
+ || !(value.reasonCode === null || validRef(value.reasonCode))) return false;
154
+ if (value.event === "recovery-required" ? value.reasonCode === null : value.reasonCode !== null) return false;
155
+ return value.recordDigest === this.#digest("lease-record", unsigned(value as LeaseRecord));
156
+ }
157
+
158
+ #read(sessionRef: string): LeaseRecord[] {
159
+ const file = this.#file(sessionRef);
160
+ let stat: fs.Stats;
161
+ try { stat = fs.lstatSync(file); } catch (error) {
162
+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return [];
163
+ throw error;
164
+ }
165
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > FILE_LIMIT) throw new Error("session-lease-file-invalid");
166
+ const descriptor = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
167
+ try {
168
+ const opened = fs.fstatSync(descriptor);
169
+ if (opened.dev !== stat.dev || opened.ino !== stat.ino || opened.size !== stat.size) throw new Error("session-lease-file-race");
170
+ const lines = fs.readFileSync(descriptor, "utf8").split("\n");
171
+ if (lines.at(-1) === "") lines.pop();
172
+ if (lines.length > ENTRY_LIMIT) throw new Error("session-lease-entry-limit");
173
+ const records: LeaseRecord[] = [];
174
+ for (const [index, line] of lines.entries()) {
175
+ if (!line || Buffer.byteLength(line) > RECORD_LIMIT) throw new Error("session-lease-record-limit");
176
+ let value: unknown;
177
+ try { value = JSON.parse(line); } catch { throw new Error("session-lease-record-invalid"); }
178
+ if (!this.#valid(value, sessionRef, index, records.at(-1)?.recordDigest ?? null)) throw new Error("session-lease-record-invalid");
179
+ records.push(value);
180
+ }
181
+ return records;
182
+ } finally { fs.closeSync(descriptor); }
183
+ }
184
+
185
+ #append(sessionRef: string, value: Omit<LeaseRecord, "version" | "sequence" | "previousDigest" | "recordDigest">): LeaseRecord {
186
+ const records = this.#read(sessionRef);
187
+ if (records.length >= ENTRY_LIMIT) throw new Error("session-lease-entry-limit");
188
+ const partial = {
189
+ version: "piagent-session-lease-v1" as const,
190
+ sequence: records.length + 1,
191
+ previousDigest: records.at(-1)?.recordDigest ?? null,
192
+ ...value
193
+ };
194
+ const record: LeaseRecord = { ...partial, recordDigest: this.#digest("lease-record", partial) };
195
+ const body = Buffer.from(`${JSON.stringify(record)}\n`);
196
+ if (body.length > RECORD_LIMIT) throw new Error("session-lease-record-limit");
197
+ const file = this.#file(sessionRef);
198
+ let stat: fs.Stats | null = null;
199
+ try { stat = fs.lstatSync(file); } catch { /* first record */ }
200
+ if (stat && (!stat.isFile() || stat.isSymbolicLink() || stat.size + body.length > FILE_LIMIT)) throw new Error("session-lease-file-invalid");
201
+ const descriptor = fs.openSync(file, fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_CREAT
202
+ | (fs.constants.O_NOFOLLOW ?? 0), 0o600);
203
+ try { fs.writeFileSync(descriptor, body); fs.fsyncSync(descriptor); }
204
+ finally { fs.closeSync(descriptor); }
205
+ fs.chmodSync(file, 0o600);
206
+ return record;
207
+ }
208
+
209
+ inspect(sessionRef: string): SessionLeaseSnapshot {
210
+ try {
211
+ const last = this.#read(sessionRef).at(-1);
212
+ if (!last || last.event === "released") return {
213
+ state: "released", ownerEpoch: null, gatewayInstanceRef: null, runtimeInstanceRef: null,
214
+ continuity: "released", revision: last?.recordDigest ?? this.#digest("lease-empty", sessionRef), reasonCode: null
215
+ };
216
+ return {
217
+ state: last.event === "acquired"
218
+ ? last.gatewayInstanceRef.startsWith(TERMINAL_OWNER_PREFIX) ? "terminal-owned" : "gateway-owned"
219
+ : "recovery-required",
220
+ ownerEpoch: last.ownerEpoch, gatewayInstanceRef: last.gatewayInstanceRef, runtimeInstanceRef: last.runtimeInstanceRef,
221
+ continuity: last.event === "acquired" ? "exact" : "unknown", revision: last.recordDigest,
222
+ reasonCode: last.reasonCode
223
+ };
224
+ } catch {
225
+ return { state: "unavailable", ownerEpoch: null, gatewayInstanceRef: null, runtimeInstanceRef: null,
226
+ continuity: "unknown", revision: null, reasonCode: "session-lease-unavailable" };
227
+ }
228
+ }
229
+
230
+ acquire(sessionRef: string, gatewayInstanceRef: string, runtimeInstanceRef: string, now = new Date()): SessionLeaseSnapshot {
231
+ if (!validRef(gatewayInstanceRef) || !validRef(runtimeInstanceRef) || !Number.isFinite(now.getTime())) throw new Error("session-lease-input-invalid");
232
+ if (gatewayInstanceRef.startsWith(TERMINAL_OWNER_PREFIX)) throw new Error("session-lease-input-invalid");
233
+ return this.#acquireOwner(sessionRef, gatewayInstanceRef, runtimeInstanceRef, now);
234
+ }
235
+
236
+ releaseDeadOwnerForExplicitRecovery(sessionRef: string, now = new Date()): SessionLeaseSnapshot {
237
+ if (!Number.isFinite(now.getTime())) throw new Error("session-lease-input-invalid");
238
+ return this.#withMutationLock(sessionRef, () => {
239
+ const current = this.inspect(sessionRef);
240
+ const pid = current.state === "terminal-owned" ? terminalOwnerPid(current.gatewayInstanceRef)
241
+ : current.state === "gateway-owned" ? gatewayOwnerPid(current.gatewayInstanceRef) : null;
242
+ if (!pid || processAlive(pid)) throw new Error("session-owner-not-proven-dead");
243
+ this.#append(sessionRef, { recordedAt: now.toISOString(), sessionRef, event: "recovery-required", ownerEpoch: current.ownerEpoch!,
244
+ gatewayInstanceRef: current.gatewayInstanceRef!, runtimeInstanceRef: current.runtimeInstanceRef!, reasonCode: "owner-process-exited" });
245
+ this.#append(sessionRef, { recordedAt: now.toISOString(), sessionRef, event: "released", ownerEpoch: current.ownerEpoch!,
246
+ gatewayInstanceRef: current.gatewayInstanceRef!, runtimeInstanceRef: current.runtimeInstanceRef!, reasonCode: null });
247
+ return this.inspect(sessionRef);
248
+ });
249
+ }
250
+
251
+ acquireTerminal(sessionRef: string, terminalInstanceRef: string, runtimeInstanceRef: string, now = new Date()): SessionLeaseSnapshot {
252
+ if (!terminalInstanceRef.startsWith(TERMINAL_OWNER_PREFIX)) throw new Error("session-lease-input-invalid");
253
+ if (!validRef(terminalInstanceRef) || !validRef(runtimeInstanceRef) || !Number.isFinite(now.getTime())) {
254
+ throw new Error("session-lease-input-invalid");
255
+ }
256
+ return this.#withMutationLock(sessionRef, () => {
257
+ const current = this.inspect(sessionRef), previousPid = terminalOwnerPid(current.gatewayInstanceRef);
258
+ if (current.state === "terminal-owned" && previousPid && !processAlive(previousPid)) {
259
+ this.#append(sessionRef, { recordedAt: now.toISOString(), sessionRef, event: "recovery-required",
260
+ ownerEpoch: current.ownerEpoch!, gatewayInstanceRef: current.gatewayInstanceRef!, runtimeInstanceRef: current.runtimeInstanceRef!,
261
+ reasonCode: "terminal-owner-process-exited" });
262
+ this.#append(sessionRef, { recordedAt: now.toISOString(), sessionRef, event: "released", ownerEpoch: current.ownerEpoch!,
263
+ gatewayInstanceRef: current.gatewayInstanceRef!, runtimeInstanceRef: current.runtimeInstanceRef!, reasonCode: null });
264
+ } else if (current.state !== "released") {
265
+ throw new Error(current.state === "recovery-required" ? "session-recovery-required" : "session-owner-conflict");
266
+ }
267
+ const ownerEpoch = `owner_${randomBytes(24).toString("base64url")}`;
268
+ this.#append(sessionRef, { recordedAt: now.toISOString(), sessionRef, event: "acquired", ownerEpoch,
269
+ gatewayInstanceRef: terminalInstanceRef, runtimeInstanceRef, reasonCode: null });
270
+ return this.inspect(sessionRef);
271
+ });
272
+ }
273
+
274
+ #acquireOwner(sessionRef: string, ownerInstanceRef: string, runtimeInstanceRef: string, now: Date): SessionLeaseSnapshot {
275
+ if (!validRef(ownerInstanceRef) || !validRef(runtimeInstanceRef) || !Number.isFinite(now.getTime())) throw new Error("session-lease-input-invalid");
276
+ return this.#withMutationLock(sessionRef, () => {
277
+ const current = this.inspect(sessionRef);
278
+ if (current.state === "unavailable") throw new Error(current.reasonCode ?? "session-lease-unavailable");
279
+ if (current.state !== "released") throw new Error(current.state === "recovery-required" ? "session-recovery-required" : "session-owner-conflict");
280
+ const ownerEpoch = `owner_${randomBytes(24).toString("base64url")}`;
281
+ this.#append(sessionRef, { recordedAt: now.toISOString(), sessionRef, event: "acquired", ownerEpoch,
282
+ gatewayInstanceRef: ownerInstanceRef, runtimeInstanceRef, reasonCode: null });
283
+ return this.inspect(sessionRef);
284
+ });
285
+ }
286
+
287
+ release(sessionRef: string, ownerEpoch: string, gatewayInstanceRef: string, runtimeInstanceRef: string, now = new Date()): SessionLeaseSnapshot {
288
+ if (gatewayInstanceRef.startsWith(TERMINAL_OWNER_PREFIX)) throw new Error("session-lease-input-invalid");
289
+ return this.#releaseOwner(sessionRef, ownerEpoch, gatewayInstanceRef, runtimeInstanceRef, "gateway-owned", now);
290
+ }
291
+
292
+ releaseTerminal(sessionRef: string, ownerEpoch: string, terminalInstanceRef: string, runtimeInstanceRef: string,
293
+ now = new Date()): SessionLeaseSnapshot {
294
+ if (!terminalInstanceRef.startsWith(TERMINAL_OWNER_PREFIX)) throw new Error("session-lease-input-invalid");
295
+ return this.#releaseOwner(sessionRef, ownerEpoch, terminalInstanceRef, runtimeInstanceRef, "terminal-owned", now);
296
+ }
297
+
298
+ #releaseOwner(sessionRef: string, ownerEpoch: string, ownerInstanceRef: string, runtimeInstanceRef: string,
299
+ expectedState: "gateway-owned" | "terminal-owned", now: Date): SessionLeaseSnapshot {
300
+ return this.#withMutationLock(sessionRef, () => {
301
+ const current = this.#matchingOwner(sessionRef, ownerEpoch, ownerInstanceRef, runtimeInstanceRef, expectedState, now);
302
+ this.#append(sessionRef, { recordedAt: now.toISOString(), sessionRef, event: "released", ownerEpoch: current.ownerEpoch!,
303
+ gatewayInstanceRef: current.gatewayInstanceRef!, runtimeInstanceRef: current.runtimeInstanceRef!, reasonCode: null });
304
+ return this.inspect(sessionRef);
305
+ });
306
+ }
307
+
308
+ requireRecovery(sessionRef: string, ownerEpoch: string, gatewayInstanceRef: string, runtimeInstanceRef: string,
309
+ reasonCode: string, now = new Date()): SessionLeaseSnapshot {
310
+ if (!validRef(reasonCode)) throw new Error("session-lease-reason-invalid");
311
+ return this.#withMutationLock(sessionRef, () => {
312
+ const current = this.#matchingOwner(sessionRef, ownerEpoch, gatewayInstanceRef, runtimeInstanceRef, "gateway-owned", now);
313
+ this.#append(sessionRef, { recordedAt: now.toISOString(), sessionRef, event: "recovery-required", ownerEpoch: current.ownerEpoch!,
314
+ gatewayInstanceRef: current.gatewayInstanceRef!, runtimeInstanceRef: current.runtimeInstanceRef!, reasonCode });
315
+ return this.inspect(sessionRef);
316
+ });
317
+ }
318
+
319
+ #matchingOwner(sessionRef: string, ownerEpoch: string, gatewayInstanceRef: string, runtimeInstanceRef: string,
320
+ expectedState: "gateway-owned" | "terminal-owned", now: Date): SessionLeaseSnapshot {
321
+ if (!validRef(ownerEpoch) || !validRef(gatewayInstanceRef) || !validRef(runtimeInstanceRef) || !Number.isFinite(now.getTime())) {
322
+ throw new Error("session-lease-input-invalid");
323
+ }
324
+ const current = this.inspect(sessionRef);
325
+ if (current.state !== expectedState || current.ownerEpoch !== ownerEpoch || current.gatewayInstanceRef !== gatewayInstanceRef
326
+ || current.runtimeInstanceRef !== runtimeInstanceRef) throw new Error("session-owner-conflict");
327
+ return current;
328
+ }
329
+ }
@@ -0,0 +1,8 @@
1
+ import { createHmac } from "node:crypto";
2
+
3
+ function ref(key: Buffer, namespace: string, value: string): string {
4
+ return `${namespace}_${createHmac("sha256", key).update(value).digest("base64url").slice(0, 43)}`;
5
+ }
6
+
7
+ export function sessionRefForPath(key: Buffer, sessionPath: string): string { return ref(key, "session", sessionPath); }
8
+ export function projectRefForCwd(key: Buffer, cwd: string): string { return ref(key, "project", cwd || "unknown"); }
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@piagent/webui",
3
+ "version": "0.0.0-private",
4
+ "private": true,
5
+ "type": "module",
6
+ "scripts": {
7
+ "generate:contracts": "node scripts/generate-contracts.mjs --write",
8
+ "check:contracts": "node scripts/generate-contracts.mjs --check",
9
+ "typecheck": "tsc -p tsconfig.json --noEmit",
10
+ "build": "npm run check:contracts && vite build",
11
+ "benchmark": "node benchmark/benchmark.mjs"
12
+ },
13
+ "dependencies": {
14
+ "@emotion/cache": "^11.14.0",
15
+ "@emotion/react": "^11.14.0",
16
+ "@emotion/styled": "^11.14.1",
17
+ "@mui/icons-material": "^9.3.1",
18
+ "@mui/material": "^9.3.1",
19
+ "react": "19.2.8",
20
+ "react-dom": "19.2.8"
21
+ },
22
+ "devDependencies": {
23
+ "@types/react": "19.2.18",
24
+ "@types/react-dom": "19.2.4",
25
+ "@vitejs/plugin-react": "6.0.5",
26
+ "json-schema-to-typescript": "15.0.4",
27
+ "typescript": "7.0.2",
28
+ "vite": "8.2.1"
29
+ },
30
+ "engines": {
31
+ "node": ">=22.19.0"
32
+ }
33
+ }
@@ -0,0 +1,4 @@
1
+ # Server boundary
2
+
3
+ The loopback server, bootstrap authentication and read-only routes begin in
4
+ WUI1-02. WUI1-01 intentionally contains no listener or route implementation.
@@ -0,0 +1,230 @@
1
+ import { createHash } from "node:crypto";
2
+ import { execFileSync } from "node:child_process";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+
7
+ import { validBenchmarkCandidateProvenance } from "../../piagent-core/benchmark/benchmark-candidate.js";
8
+ import { benchmarkCandidateProvenance } from "../../piagent-core/benchmark/benchmark-forensics.js";
9
+ import { assertBenchmarkLedgerBinding, inspectBenchmarkLedger, validateBenchmarkLedgerPrefix } from "../../piagent-core/benchmark/benchmark-ledger.js";
10
+ import { completedBenchmarkRecord } from "../../piagent-core/benchmark/benchmark-record-validation.js";
11
+ import { benchmarkGitEnvironment } from "../../piagent-core/benchmark/benchmark-runtime.js";
12
+ import { redactSensitiveText } from "../../piagent-core/extensions/redaction-core.js";
13
+
14
+ const MAX_RUNS = 20, MAX_DIRECTORIES = 100, MAX_DIRECTORY_ENTRIES = 5_000, MAX_JSON_BYTES = 32 * 1024 * 1024;
15
+ type Identity = { projectRef: string; runtimeInstanceId: string; sessionRef: string; taskId: string | null; taskRunId: string | null;
16
+ agentOperationId: null; toolCallId: null };
17
+
18
+ function opaque(prefix: string, value: string): string {
19
+ return `${prefix}.${createHash("sha256").update(`piagent-webui-release-monitor-v1\0${value}`).digest("hex").slice(0, 48)}`;
20
+ }
21
+ function timestamp(value: unknown): value is string {
22
+ return typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value)
23
+ && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
24
+ }
25
+ function text(value: unknown, maximum = 160): string | null {
26
+ const result = redactSensitiveText(String(value ?? "")).text.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
27
+ return result ? result.slice(0, maximum) : null;
28
+ }
29
+ function number(value: unknown): number | null { return Number.isFinite(value) ? Number(value) : null; }
30
+ function stableBytes(file: string, maximum = MAX_JSON_BYTES): Buffer {
31
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
32
+ try {
33
+ const before = fs.fstatSync(fd, { bigint: true });
34
+ if (!before.isFile() || before.size > BigInt(maximum)) throw new Error("monitor-file-invalid");
35
+ const bytes = fs.readFileSync(fd), after = fs.fstatSync(fd, { bigint: true });
36
+ const stableFields = ["dev", "ino", "mode", "size", "mtimeNs", "ctimeNs"] as const;
37
+ if (stableFields.some((field) => before[field] !== after[field])) throw new Error("monitor-file-changed");
38
+ return bytes;
39
+ } finally { fs.closeSync(fd); }
40
+ }
41
+ function json(file: string, maximum = MAX_JSON_BYTES): any { return JSON.parse(stableBytes(file, maximum).toString("utf8")); }
42
+ function safeDirectory(file: string): boolean { try { const stat = fs.lstatSync(file); return stat.isDirectory() && !stat.isSymbolicLink(); } catch { return false; } }
43
+ function boundedDirectories(root: string) {
44
+ const handle = fs.opendirSync(root), values: string[] = []; let truncated = false;
45
+ try {
46
+ while (values.length <= MAX_DIRECTORY_ENTRIES) {
47
+ const entry = handle.readSync(); if (!entry) break;
48
+ if (entry.isDirectory() && !entry.isSymbolicLink()) values.push(path.join(root, entry.name));
49
+ }
50
+ truncated = values.length > MAX_DIRECTORY_ENTRIES;
51
+ } finally { handle.closeSync(); }
52
+ return { values: values.slice(0, MAX_DIRECTORY_ENTRIES), truncated };
53
+ }
54
+ function git(cwd: string, args: string[]): string {
55
+ return execFileSync("git", ["-C", cwd, ...args], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024,
56
+ env: benchmarkGitEnvironment(), stdio: ["ignore", "pipe", "pipe"] }).trim();
57
+ }
58
+ function repository(cwd: string) {
59
+ const head = git(cwd, ["rev-parse", "HEAD"]), membership = new Map<string, boolean>();
60
+ const hasCommit = (commit: unknown) => {
61
+ if (typeof commit !== "string" || !/^[a-f0-9]{40,64}$/.test(commit)) return false;
62
+ const cached = membership.get(commit); if (cached !== undefined) return cached;
63
+ try { git(cwd, ["cat-file", "-e", `${commit}^{commit}`]); membership.set(commit, true); return true; }
64
+ catch { membership.set(commit, false); return false; }
65
+ };
66
+ return { head, hasCommit };
67
+ }
68
+ function rcCandidateDigest(cwd: string): string {
69
+ const raw = execFileSync("git", ["-C", cwd, "ls-files", "--cached", "--others", "--exclude-standard", "-z"], {
70
+ encoding: "buffer", maxBuffer: 64 * 1024 * 1024, env: benchmarkGitEnvironment(), stdio: ["ignore", "pipe", "pipe"]
71
+ });
72
+ const files = raw.toString("utf8").split("\0").filter(Boolean).sort();
73
+ if (files.length > 50_000) throw new Error("release-candidate-too-large");
74
+ const digest = createHash("sha256"); let total = 0;
75
+ for (const relative of files) {
76
+ if (!relative || relative.startsWith("/") || relative.split("/").includes("..")) throw new Error("release-candidate-path-invalid");
77
+ const absolute = path.join(cwd, relative), stat = fs.lstatSync(absolute);
78
+ const bytes = stat.isSymbolicLink() ? Buffer.from(fs.readlinkSync(absolute)) : stableBytes(absolute, 16 * 1024 * 1024);
79
+ total += bytes.length; if (total > 512 * 1024 * 1024) throw new Error("release-candidate-too-large");
80
+ digest.update(relative).update("\0").update(bytes).update("\0");
81
+ }
82
+ return digest.digest("hex");
83
+ }
84
+
85
+ function sourceBinding(cwd: string, provenance: any, commit: unknown, repo: ReturnType<typeof repository>, cache: { benchmark?: any }) {
86
+ if (validBenchmarkCandidateProvenance(provenance)) {
87
+ cache.benchmark ??= benchmarkCandidateProvenance(cwd);
88
+ if (cache.benchmark.contentDigest === provenance.contentDigest) return "current";
89
+ }
90
+ return repo.hasCommit(commit) ? "stale" : "unbound";
91
+ }
92
+ function ledger(runRoot: string, expected: any, records?: any[]): { records: any[]; binding: any } {
93
+ const inspected = inspectBenchmarkLedger(path.join(runRoot, "runs.jsonl"));
94
+ assertBenchmarkLedgerBinding(expected, inspected.binding, "WebUI benchmark ledger");
95
+ if (records && JSON.stringify(records) !== JSON.stringify(inspected.records)) throw new Error("benchmark-report-ledger-mismatch");
96
+ return inspected;
97
+ }
98
+ function scores(report: any) {
99
+ const value = report.surfaces?.piagent?.scores ?? {};
100
+ return { quality: number(value.quality), safety: number(value.safety), reliability: number(value.reliability),
101
+ workflow: number(value.workflow), efficiency: number(value.efficiency), overall: number(value.overall) };
102
+ }
103
+ function completeRun(cwd: string, runRoot: string, report: any, repo: ReturnType<typeof repository>, cache: { benchmark?: any }) {
104
+ if (report?.schemaVersion !== 2 || typeof report.runId !== "string" || report.runId.length > 160 || !timestamp(report.startedAt)
105
+ || !timestamp(report.completedAt) || typeof report.suite?.id !== "string" || !Array.isArray(report.runs)
106
+ || report.runs.length > 1_000 || report.runCount !== report.runs.length) throw new Error("benchmark-report-invalid");
107
+ const binding = sourceBinding(cwd, report.environment?.candidateProvenance, report.environment?.source?.commit, repo, cache);
108
+ if (binding === "unbound") return null;
109
+ if (report.runs.some((item: any) => !completedBenchmarkRecord(item) || item.runId !== report.runId)) throw new Error("benchmark-report-invalid");
110
+ ledger(runRoot, report.ledger, report.runs);
111
+ const gate = report.comparison?.productionGate ?? report.comparison?.suiteGate;
112
+ return { runRef: opaque("benchmark", report.runId), suiteId: text(report.suite.id, 80) ?? "unknown", lifecycle: "completed",
113
+ evidenceState: "complete", sourceState: binding, startedAt: report.startedAt, updatedAt: report.completedAt,
114
+ completedRuns: report.runCount, expectedRuns: report.runCount, verdict: text(report.verdict?.status, 100),
115
+ releaseGate: gate?.passed === true ? "passed" : gate?.passed === false ? "failed" : "not-applicable",
116
+ tokenClaimAllowed: typeof report.comparison?.tokenClaimAllowed === "boolean" ? report.comparison.tokenClaimAllowed : null,
117
+ claimTier: ["smoke", "public-regression", "capability", "private-holdout", "production-shadow"].includes(report.comparison?.claimEligibility?.achievedTier)
118
+ ? report.comparison.claimEligibility.achievedTier : "unknown", scores: scores(report) };
119
+ }
120
+ const MARKERS = [
121
+ ["paused.json", "paused", "pausedAt"], ["interrupted.json", "interrupted", "interruptedAt"],
122
+ ["stopped.json", "stopped", "stoppedAt"], ["aborted.json", "aborted", "abortedAt"]
123
+ ] as const;
124
+ function partialRun(cwd: string, runRoot: string, manifest: any, repo: ReturnType<typeof repository>, cache: { benchmark?: any }) {
125
+ if (manifest?.schemaVersion !== 1 || typeof manifest.runId !== "string" || !timestamp(manifest.startedAt)
126
+ || !Array.isArray(manifest.order) || manifest.order.length > 1_000) throw new Error("benchmark-manifest-invalid");
127
+ const binding = sourceBinding(cwd, manifest.candidateProvenance, manifest.sourceIdentity?.commit, repo, cache);
128
+ if (binding === "unbound") return null;
129
+ for (const [name, lifecycle, timeField] of MARKERS) {
130
+ const file = path.join(runRoot, name); if (!fs.existsSync(file)) continue;
131
+ const marker = json(file, 2 * 1024 * 1024);
132
+ if (marker?.schemaVersion !== 1 || marker.runId !== manifest.runId || !timestamp(marker[timeField])
133
+ || !Number.isInteger(marker.completedRuns) || !Number.isInteger(marker.expectedRuns) || marker.completedRuns < 0
134
+ || marker.expectedRuns < marker.completedRuns) throw new Error("benchmark-marker-invalid");
135
+ const inspected = ledger(runRoot, marker.ledger);
136
+ validateBenchmarkLedgerPrefix(inspected.records, manifest.order, completedBenchmarkRecord);
137
+ if (inspected.records.length !== marker.completedRuns || manifest.order.length !== marker.expectedRuns) throw new Error("benchmark-marker-count-mismatch");
138
+ return { runRef: opaque("benchmark", manifest.runId), suiteId: text(manifest.suite?.id, 80) ?? "unknown", lifecycle,
139
+ evidenceState: "partial", sourceState: binding, startedAt: manifest.startedAt, updatedAt: marker[timeField],
140
+ completedRuns: marker.completedRuns, expectedRuns: marker.expectedRuns, verdict: null, releaseGate: "unknown",
141
+ tokenClaimAllowed: null, claimTier: "unknown", scores: { quality: null, safety: null, reliability: null, workflow: null, efficiency: null, overall: null } };
142
+ }
143
+ const inspected = ledger(runRoot, manifest.ledger);
144
+ validateBenchmarkLedgerPrefix(inspected.records, manifest.order, completedBenchmarkRecord);
145
+ const lockPath = path.join(runRoot, ".benchmark-run.lock"); let live = false, updatedAt = manifest.startedAt;
146
+ if (fs.existsSync(lockPath)) {
147
+ const lock = json(lockPath, 16 * 1024);
148
+ if (lock?.schemaVersion !== 1 || lock.runId !== manifest.runId || !Number.isInteger(lock.pid) || lock.pid < 1
149
+ || lock.hostname !== os.hostname() || !timestamp(lock.acquiredAt)) throw new Error("benchmark-lock-invalid");
150
+ try { process.kill(lock.pid, 0); live = true; } catch { live = false; }
151
+ updatedAt = lock.acquiredAt;
152
+ }
153
+ return { runRef: opaque("benchmark", manifest.runId), suiteId: text(manifest.suite?.id, 80) ?? "unknown",
154
+ lifecycle: live ? "in-progress" : "incomplete", evidenceState: "partial", sourceState: binding,
155
+ startedAt: manifest.startedAt, updatedAt, completedRuns: inspected.records.length, expectedRuns: manifest.order.length,
156
+ verdict: null, releaseGate: "unknown", tokenClaimAllowed: null, claimTier: "unknown",
157
+ scores: { quality: null, safety: null, reliability: null, workflow: null, efficiency: null, overall: null } };
158
+ }
159
+ function benchmarkRuns(cwd: string, root: string, repo: ReturnType<typeof repository>) {
160
+ const warnings: Array<{ code: string; count: number; message: string }> = [], cache: { benchmark?: any } = {};
161
+ if (!safeDirectory(root)) return { state: "missing", runs: [], warnings, page: { total: 0, returned: 0, truncated: false } };
162
+ const bounded = boundedDirectories(root);
163
+ const allDirectories = bounded.values.filter(safeDirectory)
164
+ .map((directory) => ({ directory, modifiedAt: fs.statSync(directory).mtimeMs }))
165
+ .sort((a, b) => b.modifiedAt - a.modifiedAt);
166
+ const directories = allDirectories.slice(0, MAX_DIRECTORIES).map((item) => item.directory);
167
+ const runs: any[] = [], seenRuns = new Set<string>(); let corrupt = 0;
168
+ for (const runRoot of directories) {
169
+ if (runs.length >= MAX_RUNS) break;
170
+ try {
171
+ const reportPath = path.join(runRoot, "report.json"), manifestPath = path.join(runRoot, "run-manifest.json");
172
+ const value = fs.existsSync(reportPath) ? completeRun(cwd, runRoot, json(reportPath), repo, cache)
173
+ : fs.existsSync(manifestPath) ? partialRun(cwd, runRoot, json(manifestPath, 4 * 1024 * 1024), repo, cache) : null;
174
+ if (value) {
175
+ if (seenRuns.has(value.runRef)) corrupt += 1;
176
+ else { seenRuns.add(value.runRef); runs.push(value); }
177
+ }
178
+ } catch { corrupt += 1; }
179
+ }
180
+ if (corrupt) warnings.push({ code: "benchmark-evidence-corrupt", count: corrupt, message: `${corrupt} benchmark run(s) could not be validated.` });
181
+ if (allDirectories.length > MAX_DIRECTORIES || bounded.truncated) warnings.push({ code: "benchmark-directory-truncated",
182
+ count: Math.max(1, allDirectories.length - MAX_DIRECTORIES), message: "Older benchmark directories are outside the bounded inspection window." });
183
+ return { state: runs.length ? "ready" : corrupt ? "unavailable" : "missing", runs, warnings,
184
+ page: { total: allDirectories.length, returned: runs.length,
185
+ truncated: bounded.truncated || allDirectories.length > MAX_DIRECTORIES || runs.length >= MAX_RUNS } };
186
+ }
187
+
188
+ function releaseReadiness(cwd: string, file: string, repo: ReturnType<typeof repository>) {
189
+ if (!fs.existsSync(file)) return { state: "missing", reportRef: null, generatedAt: null, sourceState: "unknown", localSafeGate: "unknown",
190
+ rcAssembly: "unknown", beta: "unknown", gaRelease: "unknown", blockerCount: 0, blockers: [], authorization: { releaseCommit: false, tag: false, publish: false, push: false } };
191
+ try {
192
+ const report = json(file, 4 * 1024 * 1024), repository = report?.matrix?.repository, readiness = report?.readiness, authorization = report?.authorization;
193
+ if (report?.schemaVersion !== 1 || report.reportVersion !== "rc-local-readiness-v1" || !timestamp(report.generatedAt)
194
+ || !/^[a-f0-9]{40,64}$/.test(String(repository?.head ?? "")) || !/^[a-f0-9]{64}$/.test(String(repository?.candidateContentDigest ?? ""))
195
+ || !Array.isArray(readiness?.blockers) || readiness.blockers.length > 100
196
+ || ["releaseCommit", "tag", "publish", "push"].some((key) => authorization?.[key] !== false)) throw new Error("release-readiness-invalid");
197
+ const sourceState = repo.head === repository.head && rcCandidateDigest(cwd) === repository.candidateContentDigest ? "current" : "stale";
198
+ const blockers = readiness.blockers.slice(0, 8).map((item: unknown) => text(item, 240)).filter(Boolean);
199
+ return { state: sourceState === "current" ? "ready" : "stale", reportRef: opaque("release", `${report.generatedAt}\0${repository.candidateContentDigest}`),
200
+ generatedAt: report.generatedAt, sourceState, localSafeGate: ["passed", "failed"].includes(readiness.localSafeGate) ? readiness.localSafeGate : "unknown",
201
+ rcAssembly: text(readiness.rcAssembly, 100) ?? "unknown", beta: text(readiness.beta, 100) ?? "unknown", gaRelease: text(readiness.gaRelease, 100) ?? "unknown",
202
+ blockerCount: readiness.blockers.length, blockers,
203
+ authorization: { releaseCommit: false, tag: false, publish: false, push: false } };
204
+ } catch {
205
+ return { state: "unavailable", reportRef: null, generatedAt: null, sourceState: "unknown", localSafeGate: "unknown",
206
+ rcAssembly: "unknown", beta: "unknown", gaRelease: "unknown", blockerCount: 0, blockers: [], authorization: { releaseCommit: false, tag: false, publish: false, push: false } };
207
+ }
208
+ }
209
+
210
+ export function projectBenchmarkReleaseMonitor(input: { cwd: string; identity: Identity; generatedAt?: string; benchmarkRoot?: string; releaseReportPath?: string }) {
211
+ const generatedAt = input.generatedAt ?? new Date().toISOString();
212
+ try {
213
+ const repo = repository(input.cwd), root = input.benchmarkRoot ?? path.join(process.env.PI_CODING_AGENT_DIR || path.join(os.homedir(), ".pi", "agent"), "benchmarks", "piagent");
214
+ const releasePath = input.releaseReportPath ?? path.join(input.cwd, "plans", "codex-first-product", "evidence", "p7-local-readiness", "report.json");
215
+ const benchmark = benchmarkRuns(input.cwd, root, repo), release = releaseReadiness(input.cwd, releasePath, repo);
216
+ const revision = `release-monitor.${createHash("sha256").update(JSON.stringify({ benchmark, release })).digest("hex")}`;
217
+ const degraded = benchmark.state === "unavailable" || ["unavailable", "stale"].includes(release.state) || benchmark.warnings.length > 0;
218
+ return { schemaVersion: 1, version: "piagent-webui-release-monitor-v1", generatedAt, identity: structuredClone(input.identity),
219
+ state: "ready", monitorRevision: revision, benchmark, release,
220
+ actions: { runBenchmark: false, resumeBenchmark: false, releaseCommit: false, tag: false, publish: false, push: false },
221
+ health: degraded ? { state: "degraded", reasonCode: "monitor-evidence-incomplete", message: "Some local benchmark or release evidence is unavailable." }
222
+ : { state: "ok", reasonCode: null, message: null } };
223
+ } catch {
224
+ return { schemaVersion: 1, version: "piagent-webui-release-monitor-v1", generatedAt, identity: structuredClone(input.identity),
225
+ state: "unavailable", monitorRevision: null, benchmark: { state: "unavailable", runs: [], warnings: [], page: { total: 0, returned: 0, truncated: false } },
226
+ release: { state: "unavailable", reportRef: null, generatedAt: null, sourceState: "unknown", localSafeGate: "unknown", rcAssembly: "unknown", beta: "unknown", gaRelease: "unknown", blockerCount: 0, blockers: [], authorization: { releaseCommit: false, tag: false, publish: false, push: false } },
227
+ actions: { runBenchmark: false, resumeBenchmark: false, releaseCommit: false, tag: false, publish: false, push: false },
228
+ health: { state: "error", reasonCode: "release-monitor-unavailable", message: "Local benchmark and release evidence is unavailable." } };
229
+ }
230
+ }