@piagent/platform 1.3.1 → 1.4.1
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.
- package/CHANGELOG.md +132 -0
- package/README.md +10 -4
- package/README.vi.md +27 -0
- package/architecture/layers.json +96 -1
- package/docs/README.md +1 -0
- package/docs/architecture.md +1 -0
- package/docs/authority-manifest.md +1 -0
- package/docs/auto-delegation-policy.md +1 -0
- package/docs/capability-packs.md +1 -0
- package/docs/command-reference-vietnamese.md +5 -4
- package/docs/context-engine.md +1 -0
- package/docs/context-window-policy.md +1 -0
- package/docs/distribution-standard.md +8 -7
- package/docs/en/architecture.md +13 -0
- package/docs/herdr-workflow.md +1 -0
- package/docs/languages.json +20 -4
- package/docs/mcp-and-tools.md +125 -9
- package/docs/memory-policy.md +1 -0
- package/docs/model-options.md +1 -0
- package/docs/oauth-providers.md +1 -0
- package/docs/operator-manual-vietnamese.md +15 -12
- package/docs/package-architecture-notes.md +1 -0
- package/docs/project-adapters.md +1 -0
- package/docs/project-onboarding.md +1 -0
- package/docs/publishing-for-teams.md +37 -0
- package/docs/quality-benchmark.md +1 -0
- package/docs/quickstart-vietnamese.md +3 -2
- package/docs/release-install-policy.md +22 -8
- package/docs/runtime-harness-standard.md +2 -1
- package/docs/runtime-policy-design.md +1 -0
- package/docs/runtime-quality-baseline.md +1 -0
- package/docs/security-redaction-benchmark.md +1 -0
- package/docs/security-threat-model.md +2 -1
- package/docs/subagent-orchestration-capabilities.md +1 -0
- package/docs/subagents-and-multiagent.md +1 -0
- package/docs/task-implementation-contract.md +12 -4
- package/docs/task-lifecycle-vietnamese.md +1 -0
- package/docs/team-onboarding.md +3 -2
- package/docs/third-party-neutrality.md +26 -0
- package/docs/usage-observability.md +71 -0
- package/docs/vercel-docs-site.md +1 -0
- package/docs/vi/architecture.md +13 -0
- package/docs/workflow-recipes.md +1 -0
- package/docs-site/architecture.html +5 -1
- package/docs-site/benchmark.html +5 -1
- package/docs-site/commands.html +5 -1
- package/docs-site/content/en/index.html +49 -0
- package/docs-site/content/en/runtime.html +13 -0
- package/docs-site/content/index.html +49 -0
- package/docs-site/content/runtime.html +28 -0
- package/docs-site/context-engine.html +5 -1
- package/docs-site/en/architecture.html +5 -1
- package/docs-site/en/benchmark.html +5 -1
- package/docs-site/en/commands.html +5 -1
- package/docs-site/en/context-engine.html +5 -1
- package/docs-site/en/index.html +54 -1
- package/docs-site/en/mcp-approval.html +5 -1
- package/docs-site/en/mcp-auth.html +5 -1
- package/docs-site/en/mcp-servers.html +5 -1
- package/docs-site/en/mcp.html +5 -1
- package/docs-site/en/permissions.html +5 -1
- package/docs-site/en/profiles.html +5 -1
- package/docs-site/en/quickstart.html +5 -1
- package/docs-site/en/runtime.html +18 -1
- package/docs-site/en/scope.html +5 -1
- package/docs-site/en/security.html +5 -1
- package/docs-site/en/team.html +5 -1
- package/docs-site/en/whats-new.html +5 -1
- package/docs-site/en/workflows.html +5 -1
- package/docs-site/index.html +54 -1
- package/docs-site/mcp-approval.html +5 -1
- package/docs-site/mcp-auth.html +5 -1
- package/docs-site/mcp-servers.html +5 -1
- package/docs-site/mcp.html +5 -1
- package/docs-site/permissions.html +5 -1
- package/docs-site/profiles.html +5 -1
- package/docs-site/quickstart.html +5 -1
- package/docs-site/runtime.html +33 -1
- package/docs-site/scope.html +5 -1
- package/docs-site/security.html +5 -1
- package/docs-site/team.html +5 -1
- package/docs-site/whats-new.html +5 -1
- package/docs-site/workflows.html +5 -1
- package/evals/fixtures/mutation-provenance-record.invalid.json +17 -0
- package/evals/fixtures/mutation-provenance-record.valid.json +27 -0
- package/evals/fixtures/piagent-webui/approval-v1.invalid.json +54 -0
- package/evals/fixtures/piagent-webui/approval-v1.valid.json +58 -0
- package/evals/fixtures/piagent-webui/attachment-v1.invalid.json +25 -0
- package/evals/fixtures/piagent-webui/attachment-v1.valid.json +25 -0
- package/evals/fixtures/piagent-webui/capabilities-v1.invalid.json +51 -0
- package/evals/fixtures/piagent-webui/capabilities-v1.valid.json +122 -0
- package/evals/fixtures/piagent-webui/commit-summary-v1.invalid.json +10 -0
- package/evals/fixtures/piagent-webui/commit-summary-v1.valid.json +25 -0
- package/evals/fixtures/piagent-webui/control-command-v1.invalid.json +37 -0
- package/evals/fixtures/piagent-webui/control-command-v1.valid.json +35 -0
- package/evals/fixtures/piagent-webui/diff-v1.invalid.json +13 -0
- package/evals/fixtures/piagent-webui/diff-v1.valid.json +141 -0
- package/evals/fixtures/piagent-webui/gateway-capabilities-v1.invalid.json +35 -0
- package/evals/fixtures/piagent-webui/gateway-capabilities-v1.valid.json +35 -0
- package/evals/fixtures/piagent-webui/gateway-protocol-v1.invalid.json +14 -0
- package/evals/fixtures/piagent-webui/gateway-protocol-v1.valid.json +14 -0
- package/evals/fixtures/piagent-webui/handoff-history-v1.invalid.json +16 -0
- package/evals/fixtures/piagent-webui/handoff-history-v1.valid.json +16 -0
- package/evals/fixtures/piagent-webui/model-catalog-v1.invalid.json +31 -0
- package/evals/fixtures/piagent-webui/model-catalog-v1.valid.json +43 -0
- package/evals/fixtures/piagent-webui/queue-v1.invalid.json +29 -0
- package/evals/fixtures/piagent-webui/queue-v1.valid.json +44 -0
- package/evals/fixtures/piagent-webui/recovery-history-v1.invalid.json +17 -0
- package/evals/fixtures/piagent-webui/recovery-history-v1.valid.json +20 -0
- package/evals/fixtures/piagent-webui/release-monitor-v1.invalid.json +12 -0
- package/evals/fixtures/piagent-webui/release-monitor-v1.valid.json +29 -0
- package/evals/fixtures/piagent-webui/review-state-v1.invalid.json +25 -0
- package/evals/fixtures/piagent-webui/review-state-v1.valid.json +38 -0
- package/evals/fixtures/piagent-webui/runtime-event-v2.invalid.json +49 -0
- package/evals/fixtures/piagent-webui/runtime-event-v2.valid.json +49 -0
- package/evals/fixtures/piagent-webui/session-catalog-v1.invalid.json +17 -0
- package/evals/fixtures/piagent-webui/session-catalog-v1.valid.json +58 -0
- package/evals/fixtures/piagent-webui/session-command-v1.invalid.json +19 -0
- package/evals/fixtures/piagent-webui/session-command-v1.valid.json +19 -0
- package/evals/fixtures/piagent-webui/snapshot-v1.invalid.json +5 -0
- package/evals/fixtures/piagent-webui/snapshot-v1.valid.json +191 -0
- package/evals/fixtures/piagent-webui/source-change-v1.invalid.json +57 -0
- package/evals/fixtures/piagent-webui/source-change-v1.valid.json +98 -0
- package/evals/fixtures/piagent-webui/source-mutation-v1.invalid.json +19 -0
- package/evals/fixtures/piagent-webui/source-mutation-v1.valid.json +38 -0
- package/evals/fixtures/piagent-webui/source-revert-v1.invalid.json +20 -0
- package/evals/fixtures/piagent-webui/source-revert-v1.valid.json +62 -0
- package/evals/fixtures/piagent-webui/subagent-tree-v1.invalid.json +26 -0
- package/evals/fixtures/piagent-webui/subagent-tree-v1.valid.json +39 -0
- package/evals/fixtures/piagent-webui/task-index-v1.invalid.json +15 -0
- package/evals/fixtures/piagent-webui/task-index-v1.valid.json +15 -0
- package/evals/fixtures/piagent-webui/task-timeline-v1.invalid.json +14 -0
- package/evals/fixtures/piagent-webui/task-timeline-v1.valid.json +16 -0
- package/evals/fixtures/piagent-webui/transcript-v1.invalid.json +35 -0
- package/evals/fixtures/piagent-webui/transcript-v1.valid.json +55 -0
- package/evals/fixtures/task-baseline-manifest.invalid.json +16 -0
- package/evals/fixtures/task-baseline-manifest.valid.json +41 -0
- package/evals/fixtures/verifier-file-snapshot.invalid.json +21 -0
- package/evals/fixtures/verifier-file-snapshot.valid.json +21 -0
- package/package.json +43 -4
- package/packages/piagent-core/README.md +3 -2
- package/packages/piagent-core/benchmark/benchmark-candidate.d.ts +1 -0
- package/packages/piagent-core/benchmark/benchmark-forensics.d.ts +1 -0
- package/packages/piagent-core/benchmark/benchmark-ledger.d.ts +4 -0
- package/packages/piagent-core/benchmark/benchmark-record-validation.d.ts +1 -0
- package/packages/piagent-core/benchmark/benchmark-runtime.d.ts +1 -0
- package/packages/piagent-core/capabilities/capability-core.js +2 -2
- package/packages/piagent-core/capabilities/capability-verification-cache.js +17 -7
- package/packages/piagent-core/capabilities/runtime-integrity.js +190 -0
- package/packages/piagent-core/extensions/piagent-guard.ts +80 -272
- package/packages/piagent-core/extensions/redaction-core.d.ts +2 -0
- package/packages/piagent-core/extensions/runtime-evidence.js +12 -1
- package/packages/piagent-core/extensions/shell-reach.ts +250 -0
- package/packages/piagent-core/extensions/task-journal.js +30 -1
- package/packages/piagent-core/extensions/task-state.js +33 -36
- package/packages/piagent-core/mcp/mcp-command-actions.js +1 -1
- package/packages/piagent-core/mcp/mcp-server-catalog.js +139 -9
- package/packages/piagent-core/package.json +1 -1
- package/packages/piagent-core/runtime/hooks/session-start-hook.ts +2 -2
- package/packages/piagent-core/runtime/hooks/tool-call-hook.ts +12 -2
- package/packages/piagent-core/runtime/hooks/tool-result-hook.ts +20 -19
- package/packages/piagent-core/runtime/hooks/tool-result-metadata.ts +13 -0
- package/packages/piagent-core/runtime/input/chat-images.ts +2 -2
- package/packages/piagent-core/runtime/inspection/activity-event-adapter.ts +94 -0
- package/packages/piagent-core/runtime/inspection/approval-broker.ts +318 -0
- package/packages/piagent-core/runtime/inspection/commit-summary-projection.ts +59 -0
- package/packages/piagent-core/runtime/inspection/context-telemetry-inspection.ts +37 -0
- package/packages/piagent-core/runtime/inspection/criteria-links.ts +295 -0
- package/packages/piagent-core/runtime/inspection/diff-projection.ts +499 -0
- package/packages/piagent-core/runtime/inspection/git-filter-safety.ts +38 -0
- package/packages/piagent-core/runtime/inspection/git-numstat-adapter.ts +71 -0
- package/packages/piagent-core/runtime/inspection/git-status-adapter.ts +493 -0
- package/packages/piagent-core/runtime/inspection/git-tree-adapter.ts +108 -0
- package/packages/piagent-core/runtime/inspection/mcp-control.ts +10 -0
- package/packages/piagent-core/runtime/inspection/mutation-provenance-contract.ts +131 -0
- package/packages/piagent-core/runtime/inspection/mutation-provenance-recorder.ts +48 -0
- package/packages/piagent-core/runtime/inspection/mutation-provenance-store.ts +161 -0
- package/packages/piagent-core/runtime/inspection/project-runtime-inspection.ts +36 -0
- package/packages/piagent-core/runtime/inspection/review-state-contract.ts +108 -0
- package/packages/piagent-core/runtime/inspection/review-state-projection.ts +93 -0
- package/packages/piagent-core/runtime/inspection/review-state-store.ts +112 -0
- package/packages/piagent-core/runtime/inspection/runtime-event-store.ts +262 -0
- package/packages/piagent-core/runtime/inspection/same-process-bridge-proof.ts +103 -0
- package/packages/piagent-core/runtime/inspection/source-change-projection.ts +471 -0
- package/packages/piagent-core/runtime/inspection/source-evidence-contract.ts +139 -0
- package/packages/piagent-core/runtime/inspection/source-evidence-store.ts +315 -0
- package/packages/piagent-core/runtime/inspection/source-handoff-store.ts +70 -0
- package/packages/piagent-core/runtime/inspection/source-inspection-plan.ts +34 -0
- package/packages/piagent-core/runtime/inspection/source-mutation-projection.ts +164 -0
- package/packages/piagent-core/runtime/inspection/source-mutation-store.ts +168 -0
- package/packages/piagent-core/runtime/inspection/source-open-target.ts +38 -0
- package/packages/piagent-core/runtime/inspection/source-revert-projection.ts +147 -0
- package/packages/piagent-core/runtime/inspection/task-baseline-start-capture.ts +22 -0
- package/packages/piagent-core/runtime/inspection/task-compaction-history.ts +160 -0
- package/packages/piagent-core/runtime/inspection/task-control-journal.ts +131 -0
- package/packages/piagent-core/runtime/inspection/task-handoff-history.ts +95 -0
- package/packages/piagent-core/runtime/inspection/task-provenance-projection.ts +60 -0
- package/packages/piagent-core/runtime/inspection/task-recovery-timeline.ts +88 -0
- package/packages/piagent-core/runtime/inspection/task-run-index.ts +87 -0
- package/packages/piagent-core/runtime/inspection/task-source-projection.ts +401 -0
- package/packages/piagent-core/runtime/inspection/task-subagent-tree.ts +101 -0
- package/packages/piagent-core/runtime/inspection/text-diff.ts +60 -0
- package/packages/piagent-core/runtime/inspection/verifier-snapshot-contract.ts +114 -0
- package/packages/piagent-core/runtime/inspection/verifier-snapshot-store.ts +189 -0
- package/packages/piagent-core/runtime/inspection/webui-snapshot.ts +320 -0
- package/packages/piagent-core/runtime/inspection/workspace-file-reader.ts +132 -0
- package/packages/piagent-core/runtime/inspection/workspace-source-projection.ts +96 -0
- package/packages/piagent-core/runtime/inspection/zero-turn-conformance.ts +175 -0
- package/packages/piagent-core/runtime/orchestration/owned-work-budget.ts +93 -6
- package/packages/piagent-core/runtime/policy/block-remedy.ts +139 -0
- package/packages/piagent-core/runtime/policy/source-index-transaction.ts +173 -0
- package/packages/piagent-core/runtime/policy/source-mutation-guard-binding.ts +42 -0
- package/packages/piagent-core/runtime/policy/source-mutation-guard.ts +184 -0
- package/packages/piagent-core/runtime/policy/source-worktree-transaction.ts +105 -0
- package/packages/piagent-core/runtime/product/activity-inspector-footer.ts +5 -3
- package/packages/piagent-core/runtime/product/activity-inspector.ts +85 -343
- package/packages/piagent-core/runtime/recovery/resume-state.ts +38 -1
- package/packages/piagent-core/runtime/registration/activity-inspector-command.ts +68 -14
- package/packages/piagent-core/runtime/registration/task-start-tool.ts +22 -27
- package/packages/piagent-core/runtime/session/model-authorship-state.ts +31 -3
- package/packages/piagent-core/runtime/session/runtime-state.ts +11 -1
- package/packages/piagent-core/runtime/session/token-economics.js +34 -0
- package/packages/piagent-core/runtime/tools/phase-tool-runtime.ts +2 -1
- package/packages/piagent-core/runtime/workflows/task-intake.ts +5 -0
- package/packages/piagent-core/security/sensitive-data.js +7 -0
- package/packages/piagent-webui/dist/client/assets/index-DwKCWbwd.css +1 -0
- package/packages/piagent-webui/dist/client/assets/index-bu7XpD9Q.js +172 -0
- package/packages/piagent-webui/dist/client/index.html +16 -0
- package/packages/piagent-webui/extension/attachment-store.ts +323 -0
- package/packages/piagent-webui/extension/held-message-queue.ts +311 -0
- package/packages/piagent-webui/extension/lifecycle-controller.ts +423 -0
- package/packages/piagent-webui/extension/lifecycle-event-adapter.ts +23 -0
- package/packages/piagent-webui/extension/piagent-webui.ts +470 -0
- package/packages/piagent-webui/extension/review-controller.ts +160 -0
- package/packages/piagent-webui/extension/same-session-bridge.ts +500 -0
- package/packages/piagent-webui/extension/session-options-controller.ts +281 -0
- package/packages/piagent-webui/extension/session-stream-adapter.ts +249 -0
- package/packages/piagent-webui/extension/source-mutation-controller.ts +215 -0
- package/packages/piagent-webui/extension/source-open-controller.ts +136 -0
- package/packages/piagent-webui/extension/source-revert-controller.ts +189 -0
- package/packages/piagent-webui/extension/terminal-session-adapter.ts +73 -0
- package/packages/piagent-webui/extension/vscode-handoff.ts +51 -0
- package/packages/piagent-webui/gateway/control-socket.ts +92 -0
- package/packages/piagent-webui/gateway/extension-authority.ts +47 -0
- package/packages/piagent-webui/gateway/gateway-events.ts +60 -0
- package/packages/piagent-webui/gateway/gateway-protocol-service.ts +64 -0
- package/packages/piagent-webui/gateway/gateway-service.ts +215 -0
- package/packages/piagent-webui/gateway/gateway-session-stream.ts +110 -0
- package/packages/piagent-webui/gateway/mcp-auth-broker.ts +158 -0
- package/packages/piagent-webui/gateway/native-project-picker.ts +29 -0
- package/packages/piagent-webui/gateway/pi-host.ts +41 -0
- package/packages/piagent-webui/gateway/profile-state.ts +1 -0
- package/packages/piagent-webui/gateway/project-registry.ts +108 -0
- package/packages/piagent-webui/gateway/provider-auth-broker.ts +172 -0
- package/packages/piagent-webui/gateway/session-catalog.ts +128 -0
- package/packages/piagent-webui/gateway/session-command-controller.ts +237 -0
- package/packages/piagent-webui/gateway/session-command-store.ts +224 -0
- package/packages/piagent-webui/gateway/session-inspection-registry.ts +239 -0
- package/packages/piagent-webui/gateway/session-lease-store.ts +1 -0
- package/packages/piagent-webui/gateway/session-metadata-store.ts +152 -0
- package/packages/piagent-webui/gateway/session-runtime-supervisor.ts +489 -0
- package/packages/piagent-webui/ownership/gateway-runtime-context.ts +8 -0
- package/packages/piagent-webui/ownership/profile-state.ts +117 -0
- package/packages/piagent-webui/ownership/session-lease-store.ts +329 -0
- package/packages/piagent-webui/ownership/session-refs.ts +8 -0
- package/packages/piagent-webui/package.json +33 -0
- package/packages/piagent-webui/server/README.md +4 -0
- package/packages/piagent-webui/server/benchmark-release-monitor.ts +230 -0
- package/packages/piagent-webui/server/core-inspection-provider.ts +403 -0
- package/packages/piagent-webui/server/gateway-websocket.ts +143 -0
- package/packages/piagent-webui/server/http-security.ts +27 -0
- package/packages/piagent-webui/server/ipc-read-model-client.ts +89 -0
- package/packages/piagent-webui/server/loopback-server.ts +368 -0
- package/packages/piagent-webui/server/read-model-provider.ts +37 -0
- package/packages/piagent-webui/server/read-only-router.ts +105 -0
- package/packages/piagent-webui/server/session-auth.ts +88 -0
- package/packages/piagent-webui/server/sidecar-main.ts +86 -0
- package/packages/piagent-webui/server/sse-hub.ts +76 -0
- package/packages/piagent-webui/server/static-bundle.ts +40 -0
- package/packages/piagent-webui/server/transcript-projection.ts +125 -0
- package/schemas/mutation-provenance-record.schema.json +100 -0
- package/schemas/piagent-webui/approval-v1.schema.json +654 -0
- package/schemas/piagent-webui/attachment-v1.schema.json +267 -0
- package/schemas/piagent-webui/capabilities-v1.schema.json +729 -0
- package/schemas/piagent-webui/catalog-v1.json +240 -0
- package/schemas/piagent-webui/commit-summary-v1.schema.json +63 -0
- package/schemas/piagent-webui/common-v1.schema.json +479 -0
- package/schemas/piagent-webui/control-command-v1.schema.json +1780 -0
- package/schemas/piagent-webui/diff-v1.schema.json +826 -0
- package/schemas/piagent-webui/gateway-capabilities-v1.schema.json +136 -0
- package/schemas/piagent-webui/gateway-protocol-v1.schema.json +456 -0
- package/schemas/piagent-webui/handoff-history-v1.schema.json +92 -0
- package/schemas/piagent-webui/model-catalog-v1.schema.json +95 -0
- package/schemas/piagent-webui/queue-v1.schema.json +99 -0
- package/schemas/piagent-webui/recovery-history-v1.schema.json +144 -0
- package/schemas/piagent-webui/release-monitor-v1.schema.json +173 -0
- package/schemas/piagent-webui/review-state-v1.schema.json +206 -0
- package/schemas/piagent-webui/runtime-event-v2.schema.json +5206 -0
- package/schemas/piagent-webui/session-catalog-v1.schema.json +222 -0
- package/schemas/piagent-webui/session-command-v1.schema.json +390 -0
- package/schemas/piagent-webui/snapshot-v1.schema.json +2622 -0
- package/schemas/piagent-webui/source-change-v1.schema.json +763 -0
- package/schemas/piagent-webui/source-mutation-v1.schema.json +96 -0
- package/schemas/piagent-webui/source-revert-v1.schema.json +130 -0
- package/schemas/piagent-webui/subagent-tree-v1.schema.json +88 -0
- package/schemas/piagent-webui/task-index-v1.schema.json +74 -0
- package/schemas/piagent-webui/task-timeline-v1.schema.json +49 -0
- package/schemas/piagent-webui/transcript-v1.schema.json +243 -0
- package/schemas/task-baseline-manifest.schema.json +122 -0
- package/schemas/verifier-file-snapshot.schema.json +81 -0
- package/scripts/build-docs-site.mjs +21 -1
- package/scripts/check-architecture.mjs +1 -0
- package/scripts/check-doc-languages.mjs +19 -2
- package/scripts/check-third-party-neutrality.mjs +43 -0
- package/scripts/explain-command.mjs +240 -0
- package/scripts/install-global.sh +105 -4
- package/scripts/mcp-manage.mjs +17 -4
- package/scripts/pi-session-stats.sh +10 -2
- package/scripts/piagent-cli.mjs +30 -3
- package/scripts/piagent-dashboard.mjs +261 -0
- package/scripts/piagent-webui-launcher.mjs +121 -0
- package/scripts/setup.sh +69 -33
- package/scripts/traffic-snapshot.mjs +214 -0
- package/scripts/typescript-loader.mjs +42 -1
- package/scripts/uninstall-global.sh +53 -2
- package/scripts/update-global.mjs +33 -1
- package/scripts/verify-local.sh +257 -0
- package/scripts/verify-release-identity.mjs +4 -1
- package/scripts/verify-translation-pairing.mjs +121 -0
|
@@ -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,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
|
+
}
|