@gpustack/loopwright 0.0.0-stage → 0.0.3
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/LICENSE +191 -0
- package/README.md +356 -2
- package/bin/loopwright.js +3 -0
- package/node_modules/@loopwright/agent-pi/dist/adapter-v2.d.ts +9 -0
- package/node_modules/@loopwright/agent-pi/dist/adapter-v2.js +122 -0
- package/node_modules/@loopwright/agent-pi/dist/adapter.d.ts +30 -0
- package/node_modules/@loopwright/agent-pi/dist/adapter.js +340 -0
- package/node_modules/@loopwright/agent-pi/dist/admission.d.ts +25 -0
- package/node_modules/@loopwright/agent-pi/dist/admission.js +65 -0
- package/node_modules/@loopwright/agent-pi/dist/artifacts.d.ts +15 -0
- package/node_modules/@loopwright/agent-pi/dist/artifacts.js +76 -0
- package/node_modules/@loopwright/agent-pi/dist/boundary.d.ts +18 -0
- package/node_modules/@loopwright/agent-pi/dist/boundary.js +113 -0
- package/node_modules/@loopwright/agent-pi/dist/broker-channel.d.ts +4 -0
- package/node_modules/@loopwright/agent-pi/dist/broker-channel.js +121 -0
- package/node_modules/@loopwright/agent-pi/dist/candidate.d.ts +96 -0
- package/node_modules/@loopwright/agent-pi/dist/candidate.js +1712 -0
- package/node_modules/@loopwright/agent-pi/dist/capture.d.ts +39 -0
- package/node_modules/@loopwright/agent-pi/dist/capture.js +146 -0
- package/node_modules/@loopwright/agent-pi/dist/cas.d.ts +51 -0
- package/node_modules/@loopwright/agent-pi/dist/cas.js +836 -0
- package/node_modules/@loopwright/agent-pi/dist/catalog-api.d.ts +3 -0
- package/node_modules/@loopwright/agent-pi/dist/catalog-api.js +2 -0
- package/node_modules/@loopwright/agent-pi/dist/catalog.d.ts +39 -0
- package/node_modules/@loopwright/agent-pi/dist/catalog.js +280 -0
- package/node_modules/@loopwright/agent-pi/dist/circuit-breaker-limits.d.ts +9 -0
- package/node_modules/@loopwright/agent-pi/dist/circuit-breaker-limits.js +12 -0
- package/node_modules/@loopwright/agent-pi/dist/containers.d.ts +29 -0
- package/node_modules/@loopwright/agent-pi/dist/containers.js +160 -0
- package/node_modules/@loopwright/agent-pi/dist/context.d.ts +56 -0
- package/node_modules/@loopwright/agent-pi/dist/context.js +351 -0
- package/node_modules/@loopwright/agent-pi/dist/daemon.d.ts +8 -0
- package/node_modules/@loopwright/agent-pi/dist/daemon.js +52 -0
- package/node_modules/@loopwright/agent-pi/dist/deadline.d.ts +6 -0
- package/node_modules/@loopwright/agent-pi/dist/deadline.js +18 -0
- package/node_modules/@loopwright/agent-pi/dist/decode-capture.d.ts +39 -0
- package/node_modules/@loopwright/agent-pi/dist/decode-capture.js +287 -0
- package/node_modules/@loopwright/agent-pi/dist/descriptor.d.ts +12 -0
- package/node_modules/@loopwright/agent-pi/dist/descriptor.js +17 -0
- package/node_modules/@loopwright/agent-pi/dist/docker-absence.d.ts +2 -0
- package/node_modules/@loopwright/agent-pi/dist/docker-absence.js +9 -0
- package/node_modules/@loopwright/agent-pi/dist/errors.d.ts +7 -0
- package/node_modules/@loopwright/agent-pi/dist/errors.js +19 -0
- package/node_modules/@loopwright/agent-pi/dist/event-sequence.d.ts +6 -0
- package/node_modules/@loopwright/agent-pi/dist/event-sequence.js +64 -0
- package/node_modules/@loopwright/agent-pi/dist/events.d.ts +19 -0
- package/node_modules/@loopwright/agent-pi/dist/events.js +132 -0
- package/node_modules/@loopwright/agent-pi/dist/execution-guard.d.ts +9 -0
- package/node_modules/@loopwright/agent-pi/dist/execution-guard.js +25 -0
- package/node_modules/@loopwright/agent-pi/dist/execution-lease.d.ts +24 -0
- package/node_modules/@loopwright/agent-pi/dist/execution-lease.js +316 -0
- package/node_modules/@loopwright/agent-pi/dist/execution.d.ts +32 -0
- package/node_modules/@loopwright/agent-pi/dist/execution.js +476 -0
- package/node_modules/@loopwright/agent-pi/dist/external-mcp.d.ts +87 -0
- package/node_modules/@loopwright/agent-pi/dist/external-mcp.js +526 -0
- package/node_modules/@loopwright/agent-pi/dist/factory-bootstrap.d.ts +15 -0
- package/node_modules/@loopwright/agent-pi/dist/factory-bootstrap.js +74 -0
- package/node_modules/@loopwright/agent-pi/dist/host-session.d.ts +51 -0
- package/node_modules/@loopwright/agent-pi/dist/host-session.js +2094 -0
- package/node_modules/@loopwright/agent-pi/dist/http-mcp.d.ts +32 -0
- package/node_modules/@loopwright/agent-pi/dist/http-mcp.js +353 -0
- package/node_modules/@loopwright/agent-pi/dist/index.d.ts +7 -0
- package/node_modules/@loopwright/agent-pi/dist/index.js +4 -0
- package/node_modules/@loopwright/agent-pi/dist/lifecycle.d.ts +13 -0
- package/node_modules/@loopwright/agent-pi/dist/lifecycle.js +11 -0
- package/node_modules/@loopwright/agent-pi/dist/mcp-process.d.ts +35 -0
- package/node_modules/@loopwright/agent-pi/dist/mcp-process.js +92 -0
- package/node_modules/@loopwright/agent-pi/dist/mcp-transport.d.ts +25 -0
- package/node_modules/@loopwright/agent-pi/dist/mcp-transport.js +63 -0
- package/node_modules/@loopwright/agent-pi/dist/mcp.d.ts +23 -0
- package/node_modules/@loopwright/agent-pi/dist/mcp.js +212 -0
- package/node_modules/@loopwright/agent-pi/dist/operation.d.ts +5 -0
- package/node_modules/@loopwright/agent-pi/dist/operation.js +28 -0
- package/node_modules/@loopwright/agent-pi/dist/policy-v2.d.ts +10 -0
- package/node_modules/@loopwright/agent-pi/dist/policy-v2.js +64 -0
- package/node_modules/@loopwright/agent-pi/dist/policy.d.ts +13 -0
- package/node_modules/@loopwright/agent-pi/dist/policy.js +260 -0
- package/node_modules/@loopwright/agent-pi/dist/preflight.d.ts +60 -0
- package/node_modules/@loopwright/agent-pi/dist/preflight.js +700 -0
- package/node_modules/@loopwright/agent-pi/dist/progress-summary.d.ts +1 -0
- package/node_modules/@loopwright/agent-pi/dist/progress-summary.js +119 -0
- package/node_modules/@loopwright/agent-pi/dist/protocol.d.ts +17 -0
- package/node_modules/@loopwright/agent-pi/dist/protocol.js +131 -0
- package/node_modules/@loopwright/agent-pi/dist/provider.d.ts +62 -0
- package/node_modules/@loopwright/agent-pi/dist/provider.js +217 -0
- package/node_modules/@loopwright/agent-pi/dist/receipt.d.ts +3 -0
- package/node_modules/@loopwright/agent-pi/dist/receipt.js +64 -0
- package/node_modules/@loopwright/agent-pi/dist/recovery.d.ts +6 -0
- package/node_modules/@loopwright/agent-pi/dist/recovery.js +188 -0
- package/node_modules/@loopwright/agent-pi/dist/resources.d.ts +13 -0
- package/node_modules/@loopwright/agent-pi/dist/resources.js +81 -0
- package/node_modules/@loopwright/agent-pi/dist/response.d.ts +20 -0
- package/node_modules/@loopwright/agent-pi/dist/response.js +259 -0
- package/node_modules/@loopwright/agent-pi/dist/runtime-profile.d.ts +6 -0
- package/node_modules/@loopwright/agent-pi/dist/runtime-profile.js +37 -0
- package/node_modules/@loopwright/agent-pi/dist/sdk-worker.d.ts +14 -0
- package/node_modules/@loopwright/agent-pi/dist/sdk-worker.js +633 -0
- package/node_modules/@loopwright/agent-pi/dist/sender.d.ts +46 -0
- package/node_modules/@loopwright/agent-pi/dist/sender.js +553 -0
- package/node_modules/@loopwright/agent-pi/dist/session-host.d.ts +21 -0
- package/node_modules/@loopwright/agent-pi/dist/session-host.js +315 -0
- package/node_modules/@loopwright/agent-pi/dist/snapshot-transfer.d.ts +14 -0
- package/node_modules/@loopwright/agent-pi/dist/snapshot-transfer.js +102 -0
- package/node_modules/@loopwright/agent-pi/dist/snapshot.d.ts +19 -0
- package/node_modules/@loopwright/agent-pi/dist/snapshot.js +121 -0
- package/node_modules/@loopwright/agent-pi/dist/tool-process.d.ts +32 -0
- package/node_modules/@loopwright/agent-pi/dist/tool-process.js +85 -0
- package/node_modules/@loopwright/agent-pi/dist/tool-worker.d.ts +2 -0
- package/node_modules/@loopwright/agent-pi/dist/tool-worker.js +105 -0
- package/node_modules/@loopwright/agent-pi/dist/tools.d.ts +36 -0
- package/node_modules/@loopwright/agent-pi/dist/tools.js +128 -0
- package/node_modules/@loopwright/agent-pi/dist/types-v2.d.ts +71 -0
- package/node_modules/@loopwright/agent-pi/dist/types-v2.js +1 -0
- package/node_modules/@loopwright/agent-pi/dist/types.d.ts +314 -0
- package/node_modules/@loopwright/agent-pi/dist/types.js +1 -0
- package/node_modules/@loopwright/agent-pi/dist/usage.d.ts +18 -0
- package/node_modules/@loopwright/agent-pi/dist/usage.js +314 -0
- package/node_modules/@loopwright/agent-pi/dist/workspace-mcp.d.ts +27 -0
- package/node_modules/@loopwright/agent-pi/dist/workspace-mcp.js +142 -0
- package/node_modules/@loopwright/agent-pi/package.json +24 -0
- package/node_modules/@loopwright/agent-pi/runtime/Dockerfile +8 -0
- package/node_modules/@loopwright/agent-pi/runtime/seccomp.json +1 -0
- package/node_modules/@loopwright/cli/dist/arguments.d.ts +19 -0
- package/node_modules/@loopwright/cli/dist/arguments.js +358 -0
- package/node_modules/@loopwright/cli/dist/closure.d.ts +93 -0
- package/node_modules/@loopwright/cli/dist/closure.js +230 -0
- package/node_modules/@loopwright/cli/dist/draft.d.ts +9 -0
- package/node_modules/@loopwright/cli/dist/draft.js +106 -0
- package/node_modules/@loopwright/cli/dist/failure-matrix.d.ts +9 -0
- package/node_modules/@loopwright/cli/dist/failure-matrix.js +701 -0
- package/node_modules/@loopwright/cli/dist/index.d.ts +6 -0
- package/node_modules/@loopwright/cli/dist/index.js +5 -0
- package/node_modules/@loopwright/cli/dist/main.d.ts +22 -0
- package/node_modules/@loopwright/cli/dist/main.js +1855 -0
- package/node_modules/@loopwright/cli/package.json +16 -0
- package/node_modules/@loopwright/controller/dist/acceptance.d.ts +43 -0
- package/node_modules/@loopwright/controller/dist/acceptance.js +446 -0
- package/node_modules/@loopwright/controller/dist/benchmark-gate.d.ts +273 -0
- package/node_modules/@loopwright/controller/dist/benchmark-gate.js +3147 -0
- package/node_modules/@loopwright/controller/dist/budget-observations.d.ts +25 -0
- package/node_modules/@loopwright/controller/dist/budget-observations.js +139 -0
- package/node_modules/@loopwright/controller/dist/bundle.d.ts +26 -0
- package/node_modules/@loopwright/controller/dist/bundle.js +64 -0
- package/node_modules/@loopwright/controller/dist/capture.d.ts +89 -0
- package/node_modules/@loopwright/controller/dist/capture.js +587 -0
- package/node_modules/@loopwright/controller/dist/compile.d.ts +3 -0
- package/node_modules/@loopwright/controller/dist/compile.js +402 -0
- package/node_modules/@loopwright/controller/dist/config.d.ts +22 -0
- package/node_modules/@loopwright/controller/dist/config.js +255 -0
- package/node_modules/@loopwright/controller/dist/controller.d.ts +177 -0
- package/node_modules/@loopwright/controller/dist/controller.js +2135 -0
- package/node_modules/@loopwright/controller/dist/credentials.d.ts +29 -0
- package/node_modules/@loopwright/controller/dist/credentials.js +189 -0
- package/node_modules/@loopwright/controller/dist/deadlines.d.ts +18 -0
- package/node_modules/@loopwright/controller/dist/deadlines.js +71 -0
- package/node_modules/@loopwright/controller/dist/errors.d.ts +27 -0
- package/node_modules/@loopwright/controller/dist/errors.js +41 -0
- package/node_modules/@loopwright/controller/dist/events.d.ts +52 -0
- package/node_modules/@loopwright/controller/dist/events.js +228 -0
- package/node_modules/@loopwright/controller/dist/files.d.ts +51 -0
- package/node_modules/@loopwright/controller/dist/files.js +386 -0
- package/node_modules/@loopwright/controller/dist/finalize.d.ts +25 -0
- package/node_modules/@loopwright/controller/dist/finalize.js +32 -0
- package/node_modules/@loopwright/controller/dist/gate.d.ts +84 -0
- package/node_modules/@loopwright/controller/dist/gate.js +640 -0
- package/node_modules/@loopwright/controller/dist/git-objects.d.ts +11 -0
- package/node_modules/@loopwright/controller/dist/git-objects.js +59 -0
- package/node_modules/@loopwright/controller/dist/git-reader.d.ts +17 -0
- package/node_modules/@loopwright/controller/dist/git-reader.js +40 -0
- package/node_modules/@loopwright/controller/dist/handlers.d.ts +6 -0
- package/node_modules/@loopwright/controller/dist/handlers.js +45 -0
- package/node_modules/@loopwright/controller/dist/handoff.d.ts +71 -0
- package/node_modules/@loopwright/controller/dist/handoff.js +554 -0
- package/node_modules/@loopwright/controller/dist/index.d.ts +41 -0
- package/node_modules/@loopwright/controller/dist/index.js +21 -0
- package/node_modules/@loopwright/controller/dist/inspect.d.ts +30 -0
- package/node_modules/@loopwright/controller/dist/inspect.js +372 -0
- package/node_modules/@loopwright/controller/dist/interpolation.d.ts +9 -0
- package/node_modules/@loopwright/controller/dist/interpolation.js +79 -0
- package/node_modules/@loopwright/controller/dist/ownership.d.ts +41 -0
- package/node_modules/@loopwright/controller/dist/ownership.js +666 -0
- package/node_modules/@loopwright/controller/dist/parser.d.ts +5 -0
- package/node_modules/@loopwright/controller/dist/parser.js +200 -0
- package/node_modules/@loopwright/controller/dist/progress.d.ts +41 -0
- package/node_modules/@loopwright/controller/dist/progress.js +904 -0
- package/node_modules/@loopwright/controller/dist/publication.d.ts +60 -0
- package/node_modules/@loopwright/controller/dist/publication.js +329 -0
- package/node_modules/@loopwright/controller/dist/reconcile.d.ts +26 -0
- package/node_modules/@loopwright/controller/dist/reconcile.js +1378 -0
- package/node_modules/@loopwright/controller/dist/recovery.d.ts +10 -0
- package/node_modules/@loopwright/controller/dist/recovery.js +315 -0
- package/node_modules/@loopwright/controller/dist/refusal-record.d.ts +43 -0
- package/node_modules/@loopwright/controller/dist/refusal-record.js +150 -0
- package/node_modules/@loopwright/controller/dist/registry.d.ts +6 -0
- package/node_modules/@loopwright/controller/dist/registry.js +374 -0
- package/node_modules/@loopwright/controller/dist/repair.d.ts +31 -0
- package/node_modules/@loopwright/controller/dist/repair.js +102 -0
- package/node_modules/@loopwright/controller/dist/report.d.ts +64 -0
- package/node_modules/@loopwright/controller/dist/report.js +596 -0
- package/node_modules/@loopwright/controller/dist/retained.d.ts +284 -0
- package/node_modules/@loopwright/controller/dist/retained.js +193 -0
- package/node_modules/@loopwright/controller/dist/rules.d.ts +31 -0
- package/node_modules/@loopwright/controller/dist/rules.js +110 -0
- package/node_modules/@loopwright/controller/dist/run-eval.d.ts +115 -0
- package/node_modules/@loopwright/controller/dist/run-eval.js +959 -0
- package/node_modules/@loopwright/controller/dist/scheduler.d.ts +10 -0
- package/node_modules/@loopwright/controller/dist/scheduler.js +41 -0
- package/node_modules/@loopwright/controller/dist/schema.d.ts +17 -0
- package/node_modules/@loopwright/controller/dist/schema.js +78 -0
- package/node_modules/@loopwright/controller/dist/source.d.ts +69 -0
- package/node_modules/@loopwright/controller/dist/source.js +872 -0
- package/node_modules/@loopwright/controller/dist/step.d.ts +38 -0
- package/node_modules/@loopwright/controller/dist/step.js +1776 -0
- package/node_modules/@loopwright/controller/dist/storage.d.ts +90 -0
- package/node_modules/@loopwright/controller/dist/storage.js +1345 -0
- package/node_modules/@loopwright/controller/dist/submission.d.ts +51 -0
- package/node_modules/@loopwright/controller/dist/submission.js +292 -0
- package/node_modules/@loopwright/controller/dist/types.d.ts +585 -0
- package/node_modules/@loopwright/controller/dist/types.js +9 -0
- package/node_modules/@loopwright/controller/dist/verification.d.ts +124 -0
- package/node_modules/@loopwright/controller/dist/verification.js +1308 -0
- package/node_modules/@loopwright/controller/dist/verifier-protocol.d.ts +105 -0
- package/node_modules/@loopwright/controller/dist/verifier-protocol.js +1312 -0
- package/node_modules/@loopwright/controller/dist/verifier-worker.d.ts +1 -0
- package/node_modules/@loopwright/controller/dist/verifier-worker.js +33 -0
- package/node_modules/@loopwright/controller/package.json +12 -0
- package/node_modules/@loopwright/core/dist/acceptance.d.ts +108 -0
- package/node_modules/@loopwright/core/dist/acceptance.js +327 -0
- package/node_modules/@loopwright/core/dist/artifacts.d.ts +63 -0
- package/node_modules/@loopwright/core/dist/artifacts.js +356 -0
- package/node_modules/@loopwright/core/dist/boundary.d.ts +21 -0
- package/node_modules/@loopwright/core/dist/boundary.js +484 -0
- package/node_modules/@loopwright/core/dist/contracts.d.ts +287 -0
- package/node_modules/@loopwright/core/dist/contracts.js +694 -0
- package/node_modules/@loopwright/core/dist/diagnostics.d.ts +21 -0
- package/node_modules/@loopwright/core/dist/diagnostics.js +51 -0
- package/node_modules/@loopwright/core/dist/evidence.d.ts +92 -0
- package/node_modules/@loopwright/core/dist/evidence.js +85 -0
- package/node_modules/@loopwright/core/dist/graph.d.ts +8 -0
- package/node_modules/@loopwright/core/dist/graph.js +44 -0
- package/node_modules/@loopwright/core/dist/identity.d.ts +162 -0
- package/node_modules/@loopwright/core/dist/identity.js +80 -0
- package/node_modules/@loopwright/core/dist/index.d.ts +30 -0
- package/node_modules/@loopwright/core/dist/index.js +39 -0
- package/node_modules/@loopwright/core/dist/limits.d.ts +99 -0
- package/node_modules/@loopwright/core/dist/limits.js +59 -0
- package/node_modules/@loopwright/core/dist/results.d.ts +161 -0
- package/node_modules/@loopwright/core/dist/results.js +98 -0
- package/node_modules/@loopwright/core/dist/scope.d.ts +13 -0
- package/node_modules/@loopwright/core/dist/scope.js +154 -0
- package/node_modules/@loopwright/core/dist/scrubber.d.ts +13 -0
- package/node_modules/@loopwright/core/dist/scrubber.js +63 -0
- package/node_modules/@loopwright/core/dist/usage.d.ts +68 -0
- package/node_modules/@loopwright/core/dist/usage.js +56 -0
- package/node_modules/@loopwright/core/package.json +12 -0
- package/node_modules/@loopwright/decisions/dist/benchmark.d.ts +23 -0
- package/node_modules/@loopwright/decisions/dist/benchmark.js +337 -0
- package/node_modules/@loopwright/decisions/dist/client.d.ts +74 -0
- package/node_modules/@loopwright/decisions/dist/client.js +292 -0
- package/node_modules/@loopwright/decisions/dist/index.d.ts +15 -0
- package/node_modules/@loopwright/decisions/dist/index.js +8 -0
- package/node_modules/@loopwright/decisions/dist/nodes.d.ts +63 -0
- package/node_modules/@loopwright/decisions/dist/nodes.js +282 -0
- package/node_modules/@loopwright/decisions/dist/primitives.d.ts +36 -0
- package/node_modules/@loopwright/decisions/dist/primitives.js +300 -0
- package/node_modules/@loopwright/decisions/dist/redaction.d.ts +23 -0
- package/node_modules/@loopwright/decisions/dist/redaction.js +146 -0
- package/node_modules/@loopwright/decisions/dist/router.d.ts +55 -0
- package/node_modules/@loopwright/decisions/dist/router.js +248 -0
- package/node_modules/@loopwright/decisions/dist/schema.d.ts +25 -0
- package/node_modules/@loopwright/decisions/dist/schema.js +536 -0
- package/node_modules/@loopwright/decisions/dist/types.d.ts +394 -0
- package/node_modules/@loopwright/decisions/dist/types.js +80 -0
- package/node_modules/@loopwright/decisions/package.json +12 -0
- package/node_modules/@loopwright/github-app/dist/action.d.ts +90 -0
- package/node_modules/@loopwright/github-app/dist/action.js +2429 -0
- package/node_modules/@loopwright/github-app/dist/config.d.ts +23 -0
- package/node_modules/@loopwright/github-app/dist/config.js +297 -0
- package/node_modules/@loopwright/github-app/dist/digests.d.ts +1 -0
- package/node_modules/@loopwright/github-app/dist/digests.js +1 -0
- package/node_modules/@loopwright/github-app/dist/index.d.ts +14 -0
- package/node_modules/@loopwright/github-app/dist/index.js +13 -0
- package/node_modules/@loopwright/github-app/dist/models-config.d.ts +1 -0
- package/node_modules/@loopwright/github-app/dist/models-config.js +1 -0
- package/node_modules/@loopwright/github-app/dist/output-format.d.ts +1 -0
- package/node_modules/@loopwright/github-app/dist/output-format.js +1 -0
- package/node_modules/@loopwright/github-app/dist/preflight.d.ts +1 -0
- package/node_modules/@loopwright/github-app/dist/preflight.js +1 -0
- package/node_modules/@loopwright/github-app/dist/publisher.d.ts +58 -0
- package/node_modules/@loopwright/github-app/dist/publisher.js +1368 -0
- package/node_modules/@loopwright/github-app/dist/qualification.d.ts +1 -0
- package/node_modules/@loopwright/github-app/dist/qualification.js +1 -0
- package/node_modules/@loopwright/github-app/dist/sandbox.d.ts +1 -0
- package/node_modules/@loopwright/github-app/dist/sandbox.js +1 -0
- package/node_modules/@loopwright/github-app/dist/schema.d.ts +1 -0
- package/node_modules/@loopwright/github-app/dist/schema.js +1 -0
- package/node_modules/@loopwright/github-app/dist/service.d.ts +52 -0
- package/node_modules/@loopwright/github-app/dist/service.js +1658 -0
- package/node_modules/@loopwright/github-app/dist/suite-pr-lookup.d.ts +90 -0
- package/node_modules/@loopwright/github-app/dist/suite-pr-lookup.js +392 -0
- package/node_modules/@loopwright/github-app/dist/taskpack.d.ts +1 -0
- package/node_modules/@loopwright/github-app/dist/taskpack.js +1 -0
- package/node_modules/@loopwright/github-app/dist/tenant-queue.d.ts +44 -0
- package/node_modules/@loopwright/github-app/dist/tenant-queue.js +423 -0
- package/node_modules/@loopwright/github-app/dist/token-broker.d.ts +50 -0
- package/node_modules/@loopwright/github-app/dist/token-broker.js +262 -0
- package/node_modules/@loopwright/github-app/dist/turnkey-memory.d.ts +35 -0
- package/node_modules/@loopwright/github-app/dist/turnkey-memory.js +1654 -0
- package/node_modules/@loopwright/github-app/dist/turnkey.d.ts +16 -0
- package/node_modules/@loopwright/github-app/dist/turnkey.js +34 -0
- package/node_modules/@loopwright/github-app/dist/types.d.ts +220 -0
- package/node_modules/@loopwright/github-app/dist/types.js +14 -0
- package/node_modules/@loopwright/github-app/dist/upstreams.d.ts +13 -0
- package/node_modules/@loopwright/github-app/dist/upstreams.js +65 -0
- package/node_modules/@loopwright/github-app/dist/webhook.d.ts +34 -0
- package/node_modules/@loopwright/github-app/dist/webhook.js +241 -0
- package/node_modules/@loopwright/github-app/dist/yaml.d.ts +1 -0
- package/node_modules/@loopwright/github-app/dist/yaml.js +1 -0
- package/node_modules/@loopwright/github-app/package.json +12 -0
- package/node_modules/@loopwright/hardware-runner/dist/config.d.ts +48 -0
- package/node_modules/@loopwright/hardware-runner/dist/config.js +719 -0
- package/node_modules/@loopwright/hardware-runner/dist/evaluator.d.ts +230 -0
- package/node_modules/@loopwright/hardware-runner/dist/evaluator.js +3178 -0
- package/node_modules/@loopwright/hardware-runner/dist/index.d.ts +13 -0
- package/node_modules/@loopwright/hardware-runner/dist/index.js +9 -0
- package/node_modules/@loopwright/hardware-runner/dist/provenance.d.ts +128 -0
- package/node_modules/@loopwright/hardware-runner/dist/provenance.js +1500 -0
- package/node_modules/@loopwright/hardware-runner/dist/queue.d.ts +81 -0
- package/node_modules/@loopwright/hardware-runner/dist/queue.js +1081 -0
- package/node_modules/@loopwright/hardware-runner/dist/relay-server.d.ts +13 -0
- package/node_modules/@loopwright/hardware-runner/dist/relay-server.js +2997 -0
- package/node_modules/@loopwright/hardware-runner/dist/types.d.ts +239 -0
- package/node_modules/@loopwright/hardware-runner/dist/types.js +12 -0
- package/node_modules/@loopwright/hardware-runner/dist/worker.d.ts +49 -0
- package/node_modules/@loopwright/hardware-runner/dist/worker.js +1648 -0
- package/node_modules/@loopwright/hardware-runner/package.json +12 -0
- package/node_modules/@loopwright/memory/dist/cas.d.ts +21 -0
- package/node_modules/@loopwright/memory/dist/cas.js +510 -0
- package/node_modules/@loopwright/memory/dist/compaction.d.ts +18 -0
- package/node_modules/@loopwright/memory/dist/compaction.js +110 -0
- package/node_modules/@loopwright/memory/dist/finalizer.d.ts +23 -0
- package/node_modules/@loopwright/memory/dist/finalizer.js +538 -0
- package/node_modules/@loopwright/memory/dist/index.d.ts +9 -0
- package/node_modules/@loopwright/memory/dist/index.js +8 -0
- package/node_modules/@loopwright/memory/dist/schema.d.ts +36 -0
- package/node_modules/@loopwright/memory/dist/schema.js +510 -0
- package/node_modules/@loopwright/memory/dist/selector.d.ts +7 -0
- package/node_modules/@loopwright/memory/dist/selector.js +157 -0
- package/node_modules/@loopwright/memory/dist/store.d.ts +51 -0
- package/node_modules/@loopwright/memory/dist/store.js +554 -0
- package/node_modules/@loopwright/memory/dist/types.d.ts +442 -0
- package/node_modules/@loopwright/memory/dist/types.js +8 -0
- package/node_modules/@loopwright/memory/dist/verifier.d.ts +5 -0
- package/node_modules/@loopwright/memory/dist/verifier.js +328 -0
- package/node_modules/@loopwright/memory/package.json +12 -0
- package/node_modules/@loopwright/state/dist/admission.d.ts +321 -0
- package/node_modules/@loopwright/state/dist/admission.js +199 -0
- package/node_modules/@loopwright/state/dist/boundary.d.ts +53 -0
- package/node_modules/@loopwright/state/dist/boundary.js +194 -0
- package/node_modules/@loopwright/state/dist/checkpoint.d.ts +16 -0
- package/node_modules/@loopwright/state/dist/checkpoint.js +84 -0
- package/node_modules/@loopwright/state/dist/clock.d.ts +8 -0
- package/node_modules/@loopwright/state/dist/clock.js +27 -0
- package/node_modules/@loopwright/state/dist/connection.d.ts +55 -0
- package/node_modules/@loopwright/state/dist/connection.js +391 -0
- package/node_modules/@loopwright/state/dist/errors.d.ts +13 -0
- package/node_modules/@loopwright/state/dist/errors.js +34 -0
- package/node_modules/@loopwright/state/dist/index.d.ts +3 -0
- package/node_modules/@loopwright/state/dist/index.js +1 -0
- package/node_modules/@loopwright/state/dist/journal.d.ts +119 -0
- package/node_modules/@loopwright/state/dist/journal.js +72 -0
- package/node_modules/@loopwright/state/dist/model.d.ts +40 -0
- package/node_modules/@loopwright/state/dist/model.js +58 -0
- package/node_modules/@loopwright/state/dist/ownership.d.ts +14 -0
- package/node_modules/@loopwright/state/dist/ownership.js +45 -0
- package/node_modules/@loopwright/state/dist/pages.d.ts +11 -0
- package/node_modules/@loopwright/state/dist/pages.js +41 -0
- package/node_modules/@loopwright/state/dist/receipts.d.ts +33 -0
- package/node_modules/@loopwright/state/dist/receipts.js +97 -0
- package/node_modules/@loopwright/state/dist/schema.d.ts +28 -0
- package/node_modules/@loopwright/state/dist/schema.js +41 -0
- package/node_modules/@loopwright/state/dist/settlement.d.ts +10 -0
- package/node_modules/@loopwright/state/dist/settlement.js +129 -0
- package/node_modules/@loopwright/state/dist/store.d.ts +52 -0
- package/node_modules/@loopwright/state/dist/store.js +100 -0
- package/node_modules/@loopwright/state/dist/types.d.ts +315 -0
- package/node_modules/@loopwright/state/dist/types.js +1 -0
- package/node_modules/@loopwright/state/package.json +12 -0
- package/node_modules/@loopwright/taskpack/dist/baseline-align.d.ts +195 -0
- package/node_modules/@loopwright/taskpack/dist/baseline-align.js +1847 -0
- package/node_modules/@loopwright/taskpack/dist/digests.d.ts +61 -0
- package/node_modules/@loopwright/taskpack/dist/digests.js +715 -0
- package/node_modules/@loopwright/taskpack/dist/index.d.ts +18 -0
- package/node_modules/@loopwright/taskpack/dist/index.js +17 -0
- package/node_modules/@loopwright/taskpack/dist/models-config.d.ts +112 -0
- package/node_modules/@loopwright/taskpack/dist/models-config.js +1026 -0
- package/node_modules/@loopwright/taskpack/dist/output-format.d.ts +28 -0
- package/node_modules/@loopwright/taskpack/dist/output-format.js +157 -0
- package/node_modules/@loopwright/taskpack/dist/preflight.d.ts +130 -0
- package/node_modules/@loopwright/taskpack/dist/preflight.js +1497 -0
- package/node_modules/@loopwright/taskpack/dist/qualification.d.ts +23 -0
- package/node_modules/@loopwright/taskpack/dist/qualification.js +120 -0
- package/node_modules/@loopwright/taskpack/dist/sandbox.d.ts +121 -0
- package/node_modules/@loopwright/taskpack/dist/sandbox.js +2642 -0
- package/node_modules/@loopwright/taskpack/dist/schema.d.ts +197 -0
- package/node_modules/@loopwright/taskpack/dist/schema.js +4189 -0
- package/node_modules/@loopwright/taskpack/dist/scrubber.d.ts +47 -0
- package/node_modules/@loopwright/taskpack/dist/scrubber.js +283 -0
- package/node_modules/@loopwright/taskpack/dist/suite.d.ts +124 -0
- package/node_modules/@loopwright/taskpack/dist/suite.js +3256 -0
- package/node_modules/@loopwright/taskpack/dist/taskpack.d.ts +154 -0
- package/node_modules/@loopwright/taskpack/dist/taskpack.js +3634 -0
- package/node_modules/@loopwright/taskpack/dist/turnkey-memory.d.ts +122 -0
- package/node_modules/@loopwright/taskpack/dist/turnkey-memory.js +483 -0
- package/node_modules/@loopwright/taskpack/dist/turnkey.d.ts +437 -0
- package/node_modules/@loopwright/taskpack/dist/turnkey.js +7335 -0
- package/node_modules/@loopwright/taskpack/dist/types.d.ts +1274 -0
- package/node_modules/@loopwright/taskpack/dist/types.js +99 -0
- package/node_modules/@loopwright/taskpack/dist/upstreams.d.ts +261 -0
- package/node_modules/@loopwright/taskpack/dist/upstreams.js +2242 -0
- package/node_modules/@loopwright/taskpack/dist/yaml.d.ts +18 -0
- package/node_modules/@loopwright/taskpack/dist/yaml.js +167 -0
- package/node_modules/@loopwright/taskpack/package.json +12 -0
- package/node_modules/@loopwright/taskpack-runner/dist/compile-taskpack.d.ts +137 -0
- package/node_modules/@loopwright/taskpack-runner/dist/compile-taskpack.js +474 -0
- package/node_modules/@loopwright/taskpack-runner/dist/corpus.d.ts +8 -0
- package/node_modules/@loopwright/taskpack-runner/dist/corpus.js +129 -0
- package/node_modules/@loopwright/taskpack-runner/dist/index.d.ts +13 -0
- package/node_modules/@loopwright/taskpack-runner/dist/index.js +7 -0
- package/node_modules/@loopwright/taskpack-runner/dist/intake.d.ts +149 -0
- package/node_modules/@loopwright/taskpack-runner/dist/intake.js +135 -0
- package/node_modules/@loopwright/taskpack-runner/dist/parity.d.ts +130 -0
- package/node_modules/@loopwright/taskpack-runner/dist/parity.js +927 -0
- package/node_modules/@loopwright/taskpack-runner/dist/python-bridge.d.ts +68 -0
- package/node_modules/@loopwright/taskpack-runner/dist/python-bridge.js +517 -0
- package/node_modules/@loopwright/taskpack-runner/dist/service.d.ts +149 -0
- package/node_modules/@loopwright/taskpack-runner/dist/service.js +1796 -0
- package/node_modules/@loopwright/taskpack-runner/dist/types.d.ts +29 -0
- package/node_modules/@loopwright/taskpack-runner/dist/types.js +11 -0
- package/node_modules/@loopwright/taskpack-runner/package.json +12 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/README.md +77 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/docs/support-records.md +57 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/docs/supported-runners.md +98 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/manifest.json +205 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/expand_matrix.sh +273 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/matrix.yaml +280 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/resolve_dockerfile.sh +24 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pyproject.toml +46 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/runtime_runner/runner.py.json +5270 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/discovery/legacy-support.md +86 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/github/service.py +401 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/proposals/analysis.json +95 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/proposals/ready.json +109 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_assemble.py +263 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_check_draft.py +333 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_checks.py +1099 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_discovery.py +817 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_proposal.py +658 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_publish.py +987 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_summary.py +107 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/agent.py +610 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/assemble.py +84 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/check_draft.py +94 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/checks.py +1002 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/discovery.py +789 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/model.py +557 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/progress.py +174 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/analysis.md +40 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/proposal.md +65 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/repair.md +17 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/proposal.py +903 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/publish.py +997 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/summary.py +131 -0
- package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/tool-versions.json +133 -0
- package/node_modules/package-lock.json +3025 -0
- package/package-lock.json +3025 -0
- package/package.json +52 -4
|
@@ -0,0 +1,3256 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { constants, existsSync } from 'node:fs';
|
|
4
|
+
import { lstat, open, readlink, realpath } from 'node:fs/promises';
|
|
5
|
+
import { extname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
import { LIMITS } from '@loopwright/core';
|
|
8
|
+
import { assertDigestLockfileVerified } from './digests.js';
|
|
9
|
+
import { collectControlRootSiblingPaths, collectGitHubSiblingPaths } from './sandbox.js';
|
|
10
|
+
import { collectManifestControlPlanePaths, effectiveProtectedPaths, headBranchPrefixesCollide, IDENTIFIER_PATTERN, isGitHubTriggerDeclared, normalizeRelativePath, parseTaskpackDocument, pathCoveredBy, pathCoveredByCaseInsensitive, validateRfc6901JsonPointer, validateTaskpackV2Manifest, writableOverlapsMandatoryProtected, } from './schema.js';
|
|
11
|
+
import { SecretScrubber } from './scrubber.js';
|
|
12
|
+
import { authorizeRepositoryActor, validateCommentGuidance, } from './taskpack.js';
|
|
13
|
+
import { DEFAULT_COMMENT_PREFIXES, DEFAULT_TASKPACK_SUITE_PATH, GITHUB_PROTECTED_AUTOMATION_PATHS, LOCAL_PROTECTED_AUTOMATION_PATHS, MAX_SUITE_DOMAINS, MAX_SUITE_STAGE_READINESS_PROBES, MAX_SUITE_STAGE_VERSION_BLOB_BYTES, MAX_SUITE_STAGES, REPOSITORY_FULL_NAME_PATTERN, SUITE_STAGE_READINESS_PROBE_KINDS, TASKPACK_COMMENT_COMMANDS, TASKPACK_MANIFEST_API_VERSION, TASKPACK_MANIFEST_BYTES, TASKPACK_SUITE_MANIFEST_BYTES, TaskpackError, } from './types.js';
|
|
14
|
+
import { buildCleanGitEnv, COMMIT_SHA_PATTERN, discoverTaskpackUpstreamsV2, extractBaselineVersionsFromDocument, extractJsonVersionPath, fetchBoundedText, findOpenManagedPullRequest, isPlainRecord, isPrereleaseVersionTag, MEMORY_PULL_REQUEST_BRANCH_PREFIX, resolveGitCommitSha, resolveGitExecutable, validateGitRemoteSource, } from './upstreams.js';
|
|
15
|
+
const execFileAsync = promisify(execFile);
|
|
16
|
+
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
17
|
+
const MAX_STRING = 8_192;
|
|
18
|
+
const MAX_SCHEDULE_KEYS = 32;
|
|
19
|
+
const MAX_MATRIX_ENTRIES = 16;
|
|
20
|
+
const SAFE_GIT_REF_PATTERN = /^[A-Za-z0-9_./@^~{}-]{1,256}$/;
|
|
21
|
+
const STRICT_SEMVER_CORE_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
|
|
22
|
+
function suiteInvalid(message, path) {
|
|
23
|
+
throw new TaskpackError('TASKPACK_MANIFEST_INVALID', message, path);
|
|
24
|
+
}
|
|
25
|
+
function isObjectRecord(value) {
|
|
26
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
27
|
+
return false;
|
|
28
|
+
const proto = Object.getPrototypeOf(value);
|
|
29
|
+
return proto === Object.prototype || proto === null;
|
|
30
|
+
}
|
|
31
|
+
function requireSuiteObject(value, path, fields) {
|
|
32
|
+
if (!isObjectRecord(value))
|
|
33
|
+
suiteInvalid('expected an object', path);
|
|
34
|
+
for (const key of Object.keys(value)) {
|
|
35
|
+
if (FORBIDDEN_KEYS.has(key) || !fields.includes(key)) {
|
|
36
|
+
suiteInvalid(`unknown field "${key}"`, path);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return value;
|
|
40
|
+
}
|
|
41
|
+
function requireSuiteString(value, path, min, max) {
|
|
42
|
+
if (typeof value !== 'string' || value.length < min || value.length > max) {
|
|
43
|
+
suiteInvalid(`expected a string of ${min}..${max} characters`, path);
|
|
44
|
+
}
|
|
45
|
+
if (/[\0\r\n]/.test(value))
|
|
46
|
+
suiteInvalid('string contains forbidden control characters', path);
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
function requireSuiteBoolean(value, path) {
|
|
50
|
+
if (typeof value !== 'boolean')
|
|
51
|
+
suiteInvalid('expected a boolean', path);
|
|
52
|
+
return value;
|
|
53
|
+
}
|
|
54
|
+
function requireSuiteIdentifier(value, path) {
|
|
55
|
+
const text = requireSuiteString(value, path, 1, 64);
|
|
56
|
+
if (!IDENTIFIER_PATTERN.test(text))
|
|
57
|
+
suiteInvalid('expected a lowercase identifier', path);
|
|
58
|
+
return text;
|
|
59
|
+
}
|
|
60
|
+
function requireSuiteLabel(value, path) {
|
|
61
|
+
const text = requireSuiteString(value, path, 1, 128);
|
|
62
|
+
if (/[\s\p{C}]/u.test(text))
|
|
63
|
+
suiteInvalid('expected a 1..128 character non-whitespace label', path);
|
|
64
|
+
return text;
|
|
65
|
+
}
|
|
66
|
+
function requireUniqueStringList(value, path, min, max, maxItemLen = MAX_STRING) {
|
|
67
|
+
if (!Array.isArray(value) || value.length < min || value.length > max) {
|
|
68
|
+
suiteInvalid(`expected an array of ${min}..${max} items`, path);
|
|
69
|
+
}
|
|
70
|
+
const seen = new Set();
|
|
71
|
+
return Object.freeze(value.map((item, idx) => {
|
|
72
|
+
const text = requireSuiteString(item, `${path}/${idx}`, 1, maxItemLen);
|
|
73
|
+
if (seen.has(text))
|
|
74
|
+
suiteInvalid(`duplicate entry "${text}"`, `${path}/${idx}`);
|
|
75
|
+
seen.add(text);
|
|
76
|
+
return text;
|
|
77
|
+
}));
|
|
78
|
+
}
|
|
79
|
+
function deriveControlRoot(relativeManifestPath) {
|
|
80
|
+
if (relativeManifestPath === undefined)
|
|
81
|
+
return '.loopwright';
|
|
82
|
+
const dir = posix.dirname(relativeManifestPath);
|
|
83
|
+
return dir === '.' || dir === '' ? '.loopwright' : dir;
|
|
84
|
+
}
|
|
85
|
+
function validateSuiteHttpSourceUrl(source, path, allowLoopbackHttp = false) {
|
|
86
|
+
if (/[\s]/.test(source))
|
|
87
|
+
suiteInvalid('http-json source must not contain whitespace', path);
|
|
88
|
+
let parsed;
|
|
89
|
+
try {
|
|
90
|
+
parsed = new URL(source);
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
suiteInvalid(`http-json source "${source}" is not a valid URL`, path);
|
|
94
|
+
}
|
|
95
|
+
if (parsed.username !== '' || parsed.password !== '' || parsed.hash !== '') {
|
|
96
|
+
suiteInvalid('http-json source must not embed credentials or fragments', path);
|
|
97
|
+
}
|
|
98
|
+
if (parsed.protocol === 'https:')
|
|
99
|
+
return;
|
|
100
|
+
if (allowLoopbackHttp && parsed.protocol === 'http:') {
|
|
101
|
+
const host = parsed.hostname.toLowerCase();
|
|
102
|
+
if (host === '127.0.0.1' || host === 'localhost' || host === '[::1]' || host === '::1')
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
suiteInvalid(allowLoopbackHttp
|
|
106
|
+
? 'http-json source must use https:// (or loopback http://)'
|
|
107
|
+
: 'http-json source must use https://', path);
|
|
108
|
+
}
|
|
109
|
+
function validateSuiteDomainMatrix(raw, path) {
|
|
110
|
+
if (Array.isArray(raw)) {
|
|
111
|
+
if (raw.length < 1 || raw.length > LIMITS.targets) {
|
|
112
|
+
suiteInvalid(`domain matrix array must contain 1..${LIMITS.targets} cells`, path);
|
|
113
|
+
}
|
|
114
|
+
const seenIds = new Set();
|
|
115
|
+
const cells = raw.map((item, idx) => {
|
|
116
|
+
const cPath = `${path}/${idx}`;
|
|
117
|
+
const cell = requireSuiteObject(item, cPath, ['id', 'platform', 'variant']);
|
|
118
|
+
const id = requireSuiteIdentifier(cell['id'], `${cPath}/id`);
|
|
119
|
+
if (seenIds.has(id))
|
|
120
|
+
suiteInvalid(`duplicate matrix cell id "${id}"`, `${cPath}/id`);
|
|
121
|
+
seenIds.add(id);
|
|
122
|
+
const platform = requireSuiteLabel(cell['platform'], `${cPath}/platform`);
|
|
123
|
+
const variant = requireSuiteLabel(cell['variant'], `${cPath}/variant`);
|
|
124
|
+
return Object.freeze({ id, platform, variant });
|
|
125
|
+
});
|
|
126
|
+
return Object.freeze(cells);
|
|
127
|
+
}
|
|
128
|
+
if (isObjectRecord(raw)) {
|
|
129
|
+
const keys = Object.keys(raw);
|
|
130
|
+
if (keys.length < 1 || keys.length > MAX_MATRIX_ENTRIES) {
|
|
131
|
+
suiteInvalid(`domain matrix object must contain 1..${MAX_MATRIX_ENTRIES} entries`, path);
|
|
132
|
+
}
|
|
133
|
+
const out = {};
|
|
134
|
+
for (const key of keys) {
|
|
135
|
+
const kPath = `${path}/${key}`;
|
|
136
|
+
if (FORBIDDEN_KEYS.has(key) || !/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(key)) {
|
|
137
|
+
suiteInvalid(`invalid matrix key "${key}"`, kPath);
|
|
138
|
+
}
|
|
139
|
+
const val = raw[key];
|
|
140
|
+
if (typeof val === 'string') {
|
|
141
|
+
out[key] = requireSuiteString(val, kPath, 1, 256);
|
|
142
|
+
}
|
|
143
|
+
else if (typeof val === 'boolean') {
|
|
144
|
+
out[key] = val;
|
|
145
|
+
}
|
|
146
|
+
else if (typeof val === 'number') {
|
|
147
|
+
if (!Number.isFinite(val) || Object.is(val, -0)) {
|
|
148
|
+
suiteInvalid('matrix numeric value must be finite and non-negative-zero', kPath);
|
|
149
|
+
}
|
|
150
|
+
out[key] = val;
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
suiteInvalid('matrix object values must be string, number, or boolean scalars', kPath);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return Object.freeze(out);
|
|
157
|
+
}
|
|
158
|
+
suiteInvalid('domain matrix must be an array of TargetMatrixCell entries or a scalar record', path);
|
|
159
|
+
}
|
|
160
|
+
function validateSuiteReadinessProbe(raw, path, domainIds, seenProbeIds, allowLoopbackHttp) {
|
|
161
|
+
const rec = requireSuiteObject(raw, path, [
|
|
162
|
+
'id', 'kind', 'source', 'versionFrom', 'expectedVersion', 'ref',
|
|
163
|
+
'tagPrefix', 'jsonPointer', 'versionPath', 'allowPrerelease',
|
|
164
|
+
]);
|
|
165
|
+
let probeId;
|
|
166
|
+
if (Object.hasOwn(rec, 'id') && rec['id'] !== undefined) {
|
|
167
|
+
probeId = requireSuiteIdentifier(rec['id'], `${path}/id`);
|
|
168
|
+
if (seenProbeIds.has(probeId))
|
|
169
|
+
suiteInvalid(`duplicate readiness probe id "${probeId}"`, `${path}/id`);
|
|
170
|
+
seenProbeIds.add(probeId);
|
|
171
|
+
}
|
|
172
|
+
const kindStr = requireSuiteString(rec['kind'], `${path}/kind`, 1, 32);
|
|
173
|
+
if (!SUITE_STAGE_READINESS_PROBE_KINDS.includes(kindStr)) {
|
|
174
|
+
suiteInvalid(`unsupported readiness probe kind "${kindStr}"`, `${path}/kind`);
|
|
175
|
+
}
|
|
176
|
+
const kind = kindStr;
|
|
177
|
+
const source = requireSuiteString(rec['source'], `${path}/source`, 1, 512);
|
|
178
|
+
if (kind === 'github-release') {
|
|
179
|
+
if (!REPOSITORY_FULL_NAME_PATTERN.test(source)) {
|
|
180
|
+
suiteInvalid(`github-release readiness probe source "${source}" must match owner/repo`, `${path}/source`);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
else if (kind === 'http-json') {
|
|
184
|
+
validateSuiteHttpSourceUrl(source, `${path}/source`, allowLoopbackHttp);
|
|
185
|
+
}
|
|
186
|
+
else if (source.startsWith('-')) {
|
|
187
|
+
suiteInvalid(`${kind} readiness probe source must not start with "-"`, `${path}/source`);
|
|
188
|
+
}
|
|
189
|
+
let versionFrom;
|
|
190
|
+
if (Object.hasOwn(rec, 'versionFrom') && rec['versionFrom'] !== undefined) {
|
|
191
|
+
const vfPath = `${path}/versionFrom`;
|
|
192
|
+
const vfRec = requireSuiteObject(rec['versionFrom'], vfPath, ['domain', 'path', 'jsonPointer']);
|
|
193
|
+
const vfDomain = requireSuiteIdentifier(vfRec['domain'], `${vfPath}/domain`);
|
|
194
|
+
if (!domainIds.has(vfDomain)) {
|
|
195
|
+
suiteInvalid(`versionFrom.domain "${vfDomain}" does not exist in spec.domains`, `${vfPath}/domain`);
|
|
196
|
+
}
|
|
197
|
+
const vfRelPath = normalizeRelativePath(vfRec['path'], `${vfPath}/path`);
|
|
198
|
+
let vfPointer;
|
|
199
|
+
if (Object.hasOwn(vfRec, 'jsonPointer') && vfRec['jsonPointer'] !== undefined) {
|
|
200
|
+
validateRfc6901JsonPointer(vfRec['jsonPointer'], `${vfPath}/jsonPointer`);
|
|
201
|
+
vfPointer = vfRec['jsonPointer'];
|
|
202
|
+
}
|
|
203
|
+
versionFrom = Object.freeze({
|
|
204
|
+
domain: vfDomain,
|
|
205
|
+
path: vfRelPath,
|
|
206
|
+
...(vfPointer !== undefined ? { jsonPointer: vfPointer } : {}),
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
let expectedVersion;
|
|
210
|
+
if (Object.hasOwn(rec, 'expectedVersion') && rec['expectedVersion'] !== undefined) {
|
|
211
|
+
if (versionFrom !== undefined) {
|
|
212
|
+
suiteInvalid('readiness probe cannot specify both versionFrom and expectedVersion', `${path}/expectedVersion`);
|
|
213
|
+
}
|
|
214
|
+
expectedVersion = requireSuiteString(rec['expectedVersion'], `${path}/expectedVersion`, 1, 256).trim();
|
|
215
|
+
if (expectedVersion.length === 0) {
|
|
216
|
+
suiteInvalid('expectedVersion must be non-empty', `${path}/expectedVersion`);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
let ref;
|
|
220
|
+
if (Object.hasOwn(rec, 'ref') && rec['ref'] !== undefined) {
|
|
221
|
+
ref = requireSuiteString(rec['ref'], `${path}/ref`, 1, 256);
|
|
222
|
+
if (!SAFE_GIT_REF_PATTERN.test(ref) || ref.startsWith('-')) {
|
|
223
|
+
suiteInvalid(`invalid git ref "${ref}"`, `${path}/ref`);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
let tagPrefix;
|
|
227
|
+
if (Object.hasOwn(rec, 'tagPrefix') && rec['tagPrefix'] !== undefined) {
|
|
228
|
+
tagPrefix = requireSuiteString(rec['tagPrefix'], `${path}/tagPrefix`, 1, 64);
|
|
229
|
+
if (/[\s]/.test(tagPrefix))
|
|
230
|
+
suiteInvalid('tagPrefix must not contain whitespace', `${path}/tagPrefix`);
|
|
231
|
+
}
|
|
232
|
+
let jsonPointer;
|
|
233
|
+
if (Object.hasOwn(rec, 'jsonPointer') && rec['jsonPointer'] !== undefined) {
|
|
234
|
+
if (kind !== 'http-json') {
|
|
235
|
+
suiteInvalid('jsonPointer is only supported on http-json readiness probes', `${path}/jsonPointer`);
|
|
236
|
+
}
|
|
237
|
+
validateRfc6901JsonPointer(rec['jsonPointer'], `${path}/jsonPointer`);
|
|
238
|
+
jsonPointer = rec['jsonPointer'];
|
|
239
|
+
}
|
|
240
|
+
let versionPath;
|
|
241
|
+
if (Object.hasOwn(rec, 'versionPath') && rec['versionPath'] !== undefined) {
|
|
242
|
+
if (kind !== 'http-json') {
|
|
243
|
+
suiteInvalid('versionPath is only supported on http-json readiness probes', `${path}/versionPath`);
|
|
244
|
+
}
|
|
245
|
+
if (jsonPointer !== undefined) {
|
|
246
|
+
suiteInvalid('http-json readiness probe cannot specify both jsonPointer and versionPath', `${path}/versionPath`);
|
|
247
|
+
}
|
|
248
|
+
versionPath = requireSuiteString(rec['versionPath'], `${path}/versionPath`, 1, 256);
|
|
249
|
+
for (const forbidden of FORBIDDEN_KEYS) {
|
|
250
|
+
const segRe = new RegExp(`(?:^|[.\\['"])${forbidden}(?:$|[.\\]'"])`);
|
|
251
|
+
if (segRe.test(versionPath)) {
|
|
252
|
+
suiteInvalid(`versionPath must not reference forbidden property "${forbidden}"`, `${path}/versionPath`);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
let allowPrerelease;
|
|
257
|
+
if (Object.hasOwn(rec, 'allowPrerelease') && rec['allowPrerelease'] !== undefined) {
|
|
258
|
+
allowPrerelease = requireSuiteBoolean(rec['allowPrerelease'], `${path}/allowPrerelease`);
|
|
259
|
+
}
|
|
260
|
+
return Object.freeze({
|
|
261
|
+
...(probeId !== undefined ? { id: probeId } : {}),
|
|
262
|
+
kind,
|
|
263
|
+
source,
|
|
264
|
+
...(versionFrom !== undefined ? { versionFrom } : {}),
|
|
265
|
+
...(expectedVersion !== undefined ? { expectedVersion } : {}),
|
|
266
|
+
...(ref !== undefined ? { ref } : {}),
|
|
267
|
+
...(tagPrefix !== undefined ? { tagPrefix } : {}),
|
|
268
|
+
...(jsonPointer !== undefined ? { jsonPointer } : {}),
|
|
269
|
+
...(versionPath !== undefined ? { versionPath } : {}),
|
|
270
|
+
...(allowPrerelease !== undefined ? { allowPrerelease } : {}),
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
function computeTopologicalStageOrder(stages) {
|
|
274
|
+
const byId = new Map(stages.map(s => [s.id, s]));
|
|
275
|
+
const state = new Map();
|
|
276
|
+
const order = [];
|
|
277
|
+
const visit = (id) => {
|
|
278
|
+
const cur = state.get(id) ?? 0;
|
|
279
|
+
if (cur === 2)
|
|
280
|
+
return;
|
|
281
|
+
if (cur === 1) {
|
|
282
|
+
suiteInvalid(`spec.stages contains a dependency cycle involving "${id}"`, '/spec/stages');
|
|
283
|
+
}
|
|
284
|
+
state.set(id, 1);
|
|
285
|
+
const stage = byId.get(id);
|
|
286
|
+
for (const dep of stage.dependsOn) {
|
|
287
|
+
visit(dep);
|
|
288
|
+
}
|
|
289
|
+
state.set(id, 2);
|
|
290
|
+
order.push(id);
|
|
291
|
+
};
|
|
292
|
+
for (const stage of stages) {
|
|
293
|
+
visit(stage.id);
|
|
294
|
+
}
|
|
295
|
+
return Object.freeze(order);
|
|
296
|
+
}
|
|
297
|
+
/** Validate a parsed `TaskpackSuite` object (including null-prototype records). */
|
|
298
|
+
export function validateTaskpackSuiteManifest(value, options = {}) {
|
|
299
|
+
const allowLoopbackHttp = options.allowLoopbackHttp === true;
|
|
300
|
+
const suitePath = options.suitePath !== undefined
|
|
301
|
+
? normalizeRelativePath(options.suitePath, '/')
|
|
302
|
+
: undefined;
|
|
303
|
+
const controlRoot = options.controlRoot !== undefined
|
|
304
|
+
? normalizeRelativePath(options.controlRoot, '/')
|
|
305
|
+
: deriveControlRoot(suitePath);
|
|
306
|
+
const root = requireSuiteObject(value, '/', ['apiVersion', 'kind', 'metadata', 'spec']);
|
|
307
|
+
if (root['apiVersion'] !== TASKPACK_MANIFEST_API_VERSION) {
|
|
308
|
+
suiteInvalid('unsupported apiVersion', '/apiVersion');
|
|
309
|
+
}
|
|
310
|
+
if (root['kind'] !== 'TaskpackSuite') {
|
|
311
|
+
suiteInvalid('kind must be TaskpackSuite', '/kind');
|
|
312
|
+
}
|
|
313
|
+
const metadata = requireSuiteObject(root['metadata'], '/metadata', ['name']);
|
|
314
|
+
const name = requireSuiteIdentifier(metadata['name'], '/metadata/name');
|
|
315
|
+
const spec = requireSuiteObject(root['spec'], '/spec', ['domains', 'stages']);
|
|
316
|
+
const rawDomains = spec['domains'];
|
|
317
|
+
if (!Array.isArray(rawDomains) || rawDomains.length < 1 || rawDomains.length > MAX_SUITE_DOMAINS) {
|
|
318
|
+
suiteInvalid(`spec.domains must contain 1..${MAX_SUITE_DOMAINS} entries`, '/spec/domains');
|
|
319
|
+
}
|
|
320
|
+
const domainIds = new Set();
|
|
321
|
+
const domainPaths = new Set();
|
|
322
|
+
const domains = rawDomains.map((item, idx) => {
|
|
323
|
+
const dPath = `/spec/domains/${idx}`;
|
|
324
|
+
const rawDomain = requireSuiteObject(item, dPath, ['id', 'taskpack', 'enabled', 'schedules', 'stage', 'matrix']);
|
|
325
|
+
const id = requireSuiteIdentifier(rawDomain['id'], `${dPath}/id`);
|
|
326
|
+
if (domainIds.has(id))
|
|
327
|
+
suiteInvalid(`duplicate domain id "${id}"`, `${dPath}/id`);
|
|
328
|
+
domainIds.add(id);
|
|
329
|
+
const rawTpPath = requireSuiteString(rawDomain['taskpack'], `${dPath}/taskpack`, 1, 1021);
|
|
330
|
+
const normalizedTpPath = normalizeRelativePath(posix.normalize(rawTpPath.replace(/\\/g, '/')), `${dPath}/taskpack`);
|
|
331
|
+
if (!/\.(?:yaml|yml|json)$/i.test(normalizedTpPath)) {
|
|
332
|
+
suiteInvalid('domain taskpack path must end in .yaml, .yml, or .json', `${dPath}/taskpack`);
|
|
333
|
+
}
|
|
334
|
+
if (suitePath !== undefined && normalizedTpPath === suitePath) {
|
|
335
|
+
suiteInvalid('domain taskpack path must not equal the suite manifest path', `${dPath}/taskpack`);
|
|
336
|
+
}
|
|
337
|
+
if (domainPaths.has(normalizedTpPath)) {
|
|
338
|
+
suiteInvalid(`duplicate domain taskpack path "${normalizedTpPath}"`, `${dPath}/taskpack`);
|
|
339
|
+
}
|
|
340
|
+
domainPaths.add(normalizedTpPath);
|
|
341
|
+
const enabled = Object.hasOwn(rawDomain, 'enabled') && rawDomain['enabled'] !== undefined
|
|
342
|
+
? requireSuiteBoolean(rawDomain['enabled'], `${dPath}/enabled`)
|
|
343
|
+
: true;
|
|
344
|
+
let schedules;
|
|
345
|
+
if (Object.hasOwn(rawDomain, 'schedules') && rawDomain['schedules'] !== undefined) {
|
|
346
|
+
schedules = requireUniqueStringList(rawDomain['schedules'], `${dPath}/schedules`, 0, MAX_SCHEDULE_KEYS, 128);
|
|
347
|
+
}
|
|
348
|
+
let stage;
|
|
349
|
+
if (Object.hasOwn(rawDomain, 'stage') && rawDomain['stage'] !== undefined) {
|
|
350
|
+
stage = requireSuiteIdentifier(rawDomain['stage'], `${dPath}/stage`);
|
|
351
|
+
}
|
|
352
|
+
let matrix;
|
|
353
|
+
if (Object.hasOwn(rawDomain, 'matrix') && rawDomain['matrix'] !== undefined) {
|
|
354
|
+
matrix = validateSuiteDomainMatrix(rawDomain['matrix'], `${dPath}/matrix`);
|
|
355
|
+
}
|
|
356
|
+
return Object.freeze({
|
|
357
|
+
id,
|
|
358
|
+
taskpack: normalizedTpPath,
|
|
359
|
+
enabled,
|
|
360
|
+
...(schedules !== undefined ? { schedules } : {}),
|
|
361
|
+
...(stage !== undefined ? { stage } : {}),
|
|
362
|
+
...(matrix !== undefined ? { matrix } : {}),
|
|
363
|
+
});
|
|
364
|
+
});
|
|
365
|
+
let stages = Object.freeze([]);
|
|
366
|
+
if (Object.hasOwn(spec, 'stages') && spec['stages'] !== undefined) {
|
|
367
|
+
const rawStages = spec['stages'];
|
|
368
|
+
if (!Array.isArray(rawStages) || rawStages.length > MAX_SUITE_STAGES) {
|
|
369
|
+
suiteInvalid(`spec.stages must contain 0..${MAX_SUITE_STAGES} entries`, '/spec/stages');
|
|
370
|
+
}
|
|
371
|
+
const seenStageIds = new Set();
|
|
372
|
+
const parsedStages = rawStages.map((item, idx) => {
|
|
373
|
+
const sPath = `/spec/stages/${idx}`;
|
|
374
|
+
const rawStage = requireSuiteObject(item, sPath, ['id', 'dependsOn', 'readiness']);
|
|
375
|
+
const id = requireSuiteIdentifier(rawStage['id'], `${sPath}/id`);
|
|
376
|
+
if (seenStageIds.has(id))
|
|
377
|
+
suiteInvalid(`duplicate stage id "${id}"`, `${sPath}/id`);
|
|
378
|
+
seenStageIds.add(id);
|
|
379
|
+
let dependsOn = Object.freeze([]);
|
|
380
|
+
if (Object.hasOwn(rawStage, 'dependsOn') && rawStage['dependsOn'] !== undefined) {
|
|
381
|
+
const deps = requireUniqueStringList(rawStage['dependsOn'], `${sPath}/dependsOn`, 0, MAX_SUITE_STAGES - 1, 64);
|
|
382
|
+
for (const [dIdx, dep] of deps.entries()) {
|
|
383
|
+
requireSuiteIdentifier(dep, `${sPath}/dependsOn/${dIdx}`);
|
|
384
|
+
}
|
|
385
|
+
dependsOn = deps;
|
|
386
|
+
}
|
|
387
|
+
let readiness = Object.freeze([]);
|
|
388
|
+
if (Object.hasOwn(rawStage, 'readiness') && rawStage['readiness'] !== undefined) {
|
|
389
|
+
const rawProbes = rawStage['readiness'];
|
|
390
|
+
if (!Array.isArray(rawProbes) || rawProbes.length > MAX_SUITE_STAGE_READINESS_PROBES) {
|
|
391
|
+
suiteInvalid(`stage readiness must contain 0..${MAX_SUITE_STAGE_READINESS_PROBES} probes`, `${sPath}/readiness`);
|
|
392
|
+
}
|
|
393
|
+
const seenProbeIds = new Set();
|
|
394
|
+
readiness = Object.freeze(rawProbes.map((probe, pIdx) => (validateSuiteReadinessProbe(probe, `${sPath}/readiness/${pIdx}`, domainIds, seenProbeIds, allowLoopbackHttp))));
|
|
395
|
+
}
|
|
396
|
+
return Object.freeze({ id, dependsOn, readiness });
|
|
397
|
+
});
|
|
398
|
+
for (const [idx, stage] of parsedStages.entries()) {
|
|
399
|
+
for (const [dIdx, depId] of stage.dependsOn.entries()) {
|
|
400
|
+
if (depId === stage.id) {
|
|
401
|
+
suiteInvalid(`stage "${stage.id}" cannot depend on itself`, `/spec/stages/${idx}/dependsOn/${dIdx}`);
|
|
402
|
+
}
|
|
403
|
+
if (!seenStageIds.has(depId)) {
|
|
404
|
+
suiteInvalid(`stage "${stage.id}" dependsOn unknown stage "${depId}"`, `/spec/stages/${idx}/dependsOn/${dIdx}`);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
computeTopologicalStageOrder(parsedStages);
|
|
409
|
+
stages = Object.freeze(parsedStages);
|
|
410
|
+
}
|
|
411
|
+
const stageIdSet = new Set(stages.map(s => s.id));
|
|
412
|
+
for (const [idx, domain] of domains.entries()) {
|
|
413
|
+
if (domain.stage !== undefined && !stageIdSet.has(domain.stage)) {
|
|
414
|
+
suiteInvalid(`domain "${domain.id}" references unknown stage "${domain.stage}"`, `/spec/domains/${idx}/stage`);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
const suiteManifest = {
|
|
418
|
+
apiVersion: TASKPACK_MANIFEST_API_VERSION,
|
|
419
|
+
kind: 'TaskpackSuite',
|
|
420
|
+
metadata: Object.freeze({ name }),
|
|
421
|
+
spec: Object.freeze({
|
|
422
|
+
domains: Object.freeze(domains),
|
|
423
|
+
stages,
|
|
424
|
+
}),
|
|
425
|
+
};
|
|
426
|
+
Object.defineProperty(suiteManifest, 'controlRoot', { value: controlRoot, enumerable: false });
|
|
427
|
+
if (suitePath !== undefined) {
|
|
428
|
+
Object.defineProperty(suiteManifest, 'suitePath', { value: suitePath, enumerable: false });
|
|
429
|
+
}
|
|
430
|
+
return Object.freeze(suiteManifest);
|
|
431
|
+
}
|
|
432
|
+
/** Parse YAML/JSON bytes and validate as a `TaskpackSuite` (`<= 65_536` bytes). */
|
|
433
|
+
export function parseTaskpackSuiteManifest(raw, options = {}) {
|
|
434
|
+
const bytes = typeof raw === 'string' ? Buffer.from(raw, 'utf8') : raw;
|
|
435
|
+
if (bytes.byteLength > TASKPACK_SUITE_MANIFEST_BYTES) {
|
|
436
|
+
throw new TaskpackError('TASKPACK_MANIFEST_INVALID', `suite manifest exceeds ${TASKPACK_SUITE_MANIFEST_BYTES} bytes`, '/');
|
|
437
|
+
}
|
|
438
|
+
const parsed = parseTaskpackDocument(bytes, options.format ?? 'yaml');
|
|
439
|
+
return validateTaskpackSuiteManifest(parsed, options);
|
|
440
|
+
}
|
|
441
|
+
// ---------------------------------------------------------------------------
|
|
442
|
+
// Safe file loading (O_NOFOLLOW, !isSymbolicLink, isFile, nlink === 1)
|
|
443
|
+
// ---------------------------------------------------------------------------
|
|
444
|
+
function isContainedInRoot(candidate, realRoot) {
|
|
445
|
+
if (candidate === realRoot)
|
|
446
|
+
return true;
|
|
447
|
+
const prefix = realRoot.endsWith(sep) ? realRoot : `${realRoot}${sep}`;
|
|
448
|
+
return candidate.startsWith(prefix);
|
|
449
|
+
}
|
|
450
|
+
async function resolveSafeRepositoryRoot(repositoryRoot) {
|
|
451
|
+
const resolvedRoot = resolve(repositoryRoot);
|
|
452
|
+
const st = await lstat(resolvedRoot).catch(() => null);
|
|
453
|
+
if (st === null || st.isSymbolicLink() || !st.isDirectory()) {
|
|
454
|
+
throw new TaskpackError('TASKPACK_MANIFEST_INVALID', 'repository root must be an existing non-symlink directory', '/');
|
|
455
|
+
}
|
|
456
|
+
const realRoot = await realpath(resolvedRoot).catch(() => {
|
|
457
|
+
throw new TaskpackError('TASKPACK_MANIFEST_INVALID', 'repository root cannot be resolved', '/');
|
|
458
|
+
});
|
|
459
|
+
return { resolvedRoot, realRoot };
|
|
460
|
+
}
|
|
461
|
+
async function resolveDarwinFdPath(fd) {
|
|
462
|
+
return new Promise(resolvePromise => {
|
|
463
|
+
let settled = false;
|
|
464
|
+
const finish = (value) => {
|
|
465
|
+
if (settled)
|
|
466
|
+
return;
|
|
467
|
+
settled = true;
|
|
468
|
+
resolvePromise(value);
|
|
469
|
+
};
|
|
470
|
+
let child;
|
|
471
|
+
try {
|
|
472
|
+
child = spawn('/usr/bin/perl', ['-e', 'open(my $fh, "<&=", 3) or exit 1; my $buf = "\\0" x 4096; fcntl($fh, 50, $buf) or exit 1; $buf =~ s/\\0.*//s; print $buf;'], {
|
|
473
|
+
stdio: ['ignore', 'pipe', 'ignore', fd],
|
|
474
|
+
env: { PATH: '/usr/bin:/bin' },
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
catch {
|
|
478
|
+
finish(null);
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
const chunks = [];
|
|
482
|
+
let total = 0;
|
|
483
|
+
const timer = setTimeout(() => {
|
|
484
|
+
child.kill('SIGKILL');
|
|
485
|
+
finish(null);
|
|
486
|
+
}, 5_000);
|
|
487
|
+
timer.unref?.();
|
|
488
|
+
child.stdout?.on('data', (chunk) => {
|
|
489
|
+
total += chunk.byteLength;
|
|
490
|
+
if (total > 4096) {
|
|
491
|
+
child.kill('SIGKILL');
|
|
492
|
+
clearTimeout(timer);
|
|
493
|
+
finish(null);
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
chunks.push(chunk);
|
|
497
|
+
});
|
|
498
|
+
child.on('error', () => {
|
|
499
|
+
clearTimeout(timer);
|
|
500
|
+
finish(null);
|
|
501
|
+
});
|
|
502
|
+
child.on('close', code => {
|
|
503
|
+
clearTimeout(timer);
|
|
504
|
+
if (code !== 0) {
|
|
505
|
+
finish(null);
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
const out = Buffer.concat(chunks, total).toString('utf8');
|
|
509
|
+
finish(out.length > 0 ? out : null);
|
|
510
|
+
});
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
async function readSafeControlFileUnderRoot(resolvedRoot, realRoot, relPath, maxBytes, diagPath) {
|
|
514
|
+
const normalized = normalizeRelativePath(relPath, diagPath);
|
|
515
|
+
const segments = normalized.split('/');
|
|
516
|
+
const parentDirs = [];
|
|
517
|
+
let cursor = resolvedRoot;
|
|
518
|
+
for (let i = 0; i < segments.length; i += 1) {
|
|
519
|
+
const seg = segments[i];
|
|
520
|
+
cursor = join(cursor, seg);
|
|
521
|
+
const st = await lstat(cursor).catch(() => null);
|
|
522
|
+
if (st === null) {
|
|
523
|
+
throw new TaskpackError('TASKPACK_MANIFEST_INVALID', `path "${normalized}" does not exist`, diagPath);
|
|
524
|
+
}
|
|
525
|
+
if (st.isSymbolicLink()) {
|
|
526
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `path "${normalized}" must not traverse or target symbolic links`, diagPath);
|
|
527
|
+
}
|
|
528
|
+
if (i < segments.length - 1) {
|
|
529
|
+
if (!st.isDirectory()) {
|
|
530
|
+
throw new TaskpackError('TASKPACK_MANIFEST_INVALID', `parent segment of "${normalized}" is not a directory`, diagPath);
|
|
531
|
+
}
|
|
532
|
+
parentDirs.push({ path: cursor, segment: seg, dev: st.dev, ino: st.ino });
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
const realFull = await realpath(cursor).catch(() => {
|
|
536
|
+
throw new TaskpackError('TASKPACK_MANIFEST_INVALID', `path "${normalized}" cannot be resolved`, diagPath);
|
|
537
|
+
});
|
|
538
|
+
if (!isContainedInRoot(realFull, realRoot)) {
|
|
539
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `path "${normalized}" escapes repository root`, diagPath);
|
|
540
|
+
}
|
|
541
|
+
const before = await lstat(cursor).catch((error) => {
|
|
542
|
+
if (error.code === 'ELOOP') {
|
|
543
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `symbolic link traversal is forbidden at "${normalized}"`, diagPath);
|
|
544
|
+
}
|
|
545
|
+
throw new TaskpackError('TASKPACK_MANIFEST_INVALID', `file "${normalized}" cannot be inspected`, diagPath);
|
|
546
|
+
});
|
|
547
|
+
if (before.isSymbolicLink()) {
|
|
548
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `file "${normalized}" must not be a symbolic link`, diagPath);
|
|
549
|
+
}
|
|
550
|
+
if (!before.isFile()) {
|
|
551
|
+
throw new TaskpackError('TASKPACK_MANIFEST_INVALID', `path "${normalized}" must be a regular file`, diagPath);
|
|
552
|
+
}
|
|
553
|
+
if (before.nlink !== 1) {
|
|
554
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `hardlinked file "${normalized}" (nlink=${before.nlink}) is forbidden`, diagPath);
|
|
555
|
+
}
|
|
556
|
+
if (before.size > maxBytes) {
|
|
557
|
+
throw new TaskpackError('TASKPACK_MANIFEST_INVALID', `file "${normalized}" exceeds ${maxBytes} bytes`, diagPath);
|
|
558
|
+
}
|
|
559
|
+
const noFollow = 'O_NOFOLLOW' in constants ? constants.O_NOFOLLOW : 0;
|
|
560
|
+
const oDirectory = 'O_DIRECTORY' in constants ? constants.O_DIRECTORY : 0;
|
|
561
|
+
const pinnedParentHandles = [];
|
|
562
|
+
let rootHandle;
|
|
563
|
+
let handle;
|
|
564
|
+
try {
|
|
565
|
+
if (process.platform === 'linux') {
|
|
566
|
+
rootHandle = await open(realRoot, constants.O_RDONLY | noFollow | oDirectory);
|
|
567
|
+
let currentDirFd = rootHandle.fd;
|
|
568
|
+
for (const parent of parentDirs) {
|
|
569
|
+
let dirHandle;
|
|
570
|
+
try {
|
|
571
|
+
dirHandle = await open(`/proc/self/fd/${currentDirFd}/${parent.segment}`, constants.O_RDONLY | noFollow | oDirectory);
|
|
572
|
+
}
|
|
573
|
+
catch (error) {
|
|
574
|
+
const code = error?.code;
|
|
575
|
+
if (code === 'ELOOP' || code === 'ENOTDIR') {
|
|
576
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `parent directory of "${normalized}" became a symbolic link`, diagPath);
|
|
577
|
+
}
|
|
578
|
+
throw new TaskpackError('TASKPACK_MANIFEST_INVALID', `parent directory of "${normalized}" could not be opened`, diagPath);
|
|
579
|
+
}
|
|
580
|
+
const dirInfo = await dirHandle.stat();
|
|
581
|
+
if (!dirInfo.isDirectory() || dirInfo.dev !== parent.dev || dirInfo.ino !== parent.ino) {
|
|
582
|
+
await dirHandle.close().catch(() => undefined);
|
|
583
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `parent directory of "${normalized}" changed identity before opening`, diagPath);
|
|
584
|
+
}
|
|
585
|
+
pinnedParentHandles.push({ handle: dirHandle, path: parent.path, dev: parent.dev, ino: parent.ino });
|
|
586
|
+
currentDirFd = dirHandle.fd;
|
|
587
|
+
}
|
|
588
|
+
const leafSegment = segments[segments.length - 1];
|
|
589
|
+
try {
|
|
590
|
+
handle = await open(`/proc/self/fd/${currentDirFd}/${leafSegment}`, constants.O_RDONLY | noFollow);
|
|
591
|
+
}
|
|
592
|
+
catch (error) {
|
|
593
|
+
const code = error?.code;
|
|
594
|
+
if (code === 'ELOOP') {
|
|
595
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `symbolic link detected while opening "${normalized}"`, diagPath);
|
|
596
|
+
}
|
|
597
|
+
throw new TaskpackError('TASKPACK_MANIFEST_INVALID', `file "${normalized}" could not be opened`, diagPath);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
else {
|
|
601
|
+
for (const parent of parentDirs) {
|
|
602
|
+
let dirHandle;
|
|
603
|
+
try {
|
|
604
|
+
dirHandle = await open(parent.path, constants.O_RDONLY | noFollow | oDirectory);
|
|
605
|
+
}
|
|
606
|
+
catch (error) {
|
|
607
|
+
const code = error?.code;
|
|
608
|
+
if (code === 'ELOOP' || code === 'ENOTDIR') {
|
|
609
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `parent directory of "${normalized}" became a symbolic link`, diagPath);
|
|
610
|
+
}
|
|
611
|
+
throw new TaskpackError('TASKPACK_MANIFEST_INVALID', `parent directory of "${normalized}" could not be opened`, diagPath);
|
|
612
|
+
}
|
|
613
|
+
const dirInfo = await dirHandle.stat();
|
|
614
|
+
if (!dirInfo.isDirectory() || dirInfo.dev !== parent.dev || dirInfo.ino !== parent.ino) {
|
|
615
|
+
await dirHandle.close().catch(() => undefined);
|
|
616
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `parent directory of "${normalized}" changed identity before opening`, diagPath);
|
|
617
|
+
}
|
|
618
|
+
pinnedParentHandles.push({ handle: dirHandle, path: parent.path, dev: parent.dev, ino: parent.ino });
|
|
619
|
+
}
|
|
620
|
+
try {
|
|
621
|
+
handle = await open(cursor, constants.O_RDONLY | noFollow);
|
|
622
|
+
}
|
|
623
|
+
catch (error) {
|
|
624
|
+
const code = error?.code;
|
|
625
|
+
if (code === 'ELOOP') {
|
|
626
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `symbolic link detected while opening "${normalized}"`, diagPath);
|
|
627
|
+
}
|
|
628
|
+
throw new TaskpackError('TASKPACK_MANIFEST_INVALID', `file "${normalized}" could not be opened`, diagPath);
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
const info = await handle.stat();
|
|
632
|
+
if (!info.isFile() || info.nlink !== 1 || info.dev !== before.dev || info.ino !== before.ino) {
|
|
633
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `file "${normalized}" identity or link count changed while opening`, diagPath);
|
|
634
|
+
}
|
|
635
|
+
if (info.size !== before.size || info.size > maxBytes) {
|
|
636
|
+
throw new TaskpackError('TASKPACK_MANIFEST_INVALID', `file "${normalized}" changed size while loading or exceeds ${maxBytes} bytes`, diagPath);
|
|
637
|
+
}
|
|
638
|
+
if (process.platform === 'linux') {
|
|
639
|
+
const fdResolvedPath = await readlink(`/proc/self/fd/${handle.fd}`).catch(() => null);
|
|
640
|
+
if (fdResolvedPath === null || fdResolvedPath !== realFull || !isContainedInRoot(fdResolvedPath, realRoot)) {
|
|
641
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `opened file descriptor for "${normalized}" resolved outside repository root`, diagPath);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
else if (process.platform === 'darwin') {
|
|
645
|
+
const fdResolvedPath = await resolveDarwinFdPath(handle.fd);
|
|
646
|
+
if (fdResolvedPath === null || fdResolvedPath !== realFull || !isContainedInRoot(fdResolvedPath, realRoot)) {
|
|
647
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `opened file descriptor for "${normalized}" resolved outside repository root`, diagPath);
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
for (const parent of pinnedParentHandles) {
|
|
651
|
+
const postParent = await lstat(parent.path).catch(() => null);
|
|
652
|
+
const postFdStat = await parent.handle.stat().catch(() => null);
|
|
653
|
+
if (postParent === null
|
|
654
|
+
|| postFdStat === null
|
|
655
|
+
|| postParent.isSymbolicLink()
|
|
656
|
+
|| !postParent.isDirectory()
|
|
657
|
+
|| postParent.dev !== parent.dev
|
|
658
|
+
|| postParent.ino !== parent.ino
|
|
659
|
+
|| postFdStat.dev !== parent.dev
|
|
660
|
+
|| postFdStat.ino !== parent.ino) {
|
|
661
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `parent directory of "${normalized}" changed identity or became a symbolic link while opening`, diagPath);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
const postReal = await realpath(cursor).catch(() => null);
|
|
665
|
+
const postLeaf = await lstat(cursor).catch(() => null);
|
|
666
|
+
if (postReal === null
|
|
667
|
+
|| postReal !== realFull
|
|
668
|
+
|| !isContainedInRoot(postReal, realRoot)
|
|
669
|
+
|| postLeaf === null
|
|
670
|
+
|| postLeaf.isSymbolicLink()
|
|
671
|
+
|| postLeaf.dev !== info.dev
|
|
672
|
+
|| postLeaf.ino !== info.ino) {
|
|
673
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `file "${normalized}" escaped repository root or changed identity during open`, diagPath);
|
|
674
|
+
}
|
|
675
|
+
const buf = Buffer.alloc(info.size + 1);
|
|
676
|
+
let size = 0;
|
|
677
|
+
while (size < buf.length) {
|
|
678
|
+
const read = await handle.read(buf, size, buf.length - size, size);
|
|
679
|
+
if (!read.bytesRead)
|
|
680
|
+
break;
|
|
681
|
+
size += read.bytesRead;
|
|
682
|
+
}
|
|
683
|
+
if (size !== info.size) {
|
|
684
|
+
throw new TaskpackError('TASKPACK_MANIFEST_INVALID', `file "${normalized}" mutated while loading`, diagPath);
|
|
685
|
+
}
|
|
686
|
+
const slice = buf.subarray(0, size);
|
|
687
|
+
const sha256 = createHash('sha256').update(slice).digest('hex');
|
|
688
|
+
return { bytes: slice, sha256 };
|
|
689
|
+
}
|
|
690
|
+
finally {
|
|
691
|
+
if (handle !== undefined) {
|
|
692
|
+
await handle.close().catch(() => undefined);
|
|
693
|
+
}
|
|
694
|
+
for (const parent of pinnedParentHandles.reverse()) {
|
|
695
|
+
await parent.handle.close().catch(() => undefined);
|
|
696
|
+
}
|
|
697
|
+
if (rootHandle !== undefined) {
|
|
698
|
+
await rootHandle.close().catch(() => undefined);
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
function resolveSuiteRelativePath(repositoryRoot, rawSuitePath) {
|
|
703
|
+
if (rawSuitePath === undefined || rawSuitePath.trim().length === 0) {
|
|
704
|
+
return DEFAULT_TASKPACK_SUITE_PATH;
|
|
705
|
+
}
|
|
706
|
+
const segments = rawSuitePath.split(/[\\/]/);
|
|
707
|
+
if (segments.includes('..')) {
|
|
708
|
+
suiteInvalid('suite path must not contain ".." traversal', '/');
|
|
709
|
+
}
|
|
710
|
+
const resolvedRoot = resolve(repositoryRoot);
|
|
711
|
+
if (isAbsolute(rawSuitePath)) {
|
|
712
|
+
const rel = relative(resolvedRoot, resolve(rawSuitePath));
|
|
713
|
+
if (rel.length === 0 || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
|
|
714
|
+
suiteInvalid('suite path escapes repository root', '/');
|
|
715
|
+
}
|
|
716
|
+
return normalizeRelativePath(rel.split(sep).join('/'), '/');
|
|
717
|
+
}
|
|
718
|
+
return normalizeRelativePath(posix.normalize(rawSuitePath.replace(/\\/g, '/')), '/');
|
|
719
|
+
}
|
|
720
|
+
function cloneManifestWithAdditionalProtectedPaths(manifest, additionalProtected, controlRoot, manifestPath) {
|
|
721
|
+
const builtInSet = new Set([...LOCAL_PROTECTED_AUTOMATION_PATHS, ...GITHUB_PROTECTED_AUTOMATION_PATHS]);
|
|
722
|
+
const merged = new Set(manifest.spec.scope.protected);
|
|
723
|
+
for (const entry of additionalProtected) {
|
|
724
|
+
if (!builtInSet.has(entry))
|
|
725
|
+
merged.add(entry);
|
|
726
|
+
}
|
|
727
|
+
const nextProtected = Object.freeze([...merged]);
|
|
728
|
+
if (nextProtected.length > LIMITS.patterns) {
|
|
729
|
+
suiteInvalid(`domain "${manifest.metadata.name}" merged protected paths exceed ${LIMITS.patterns} entries`, '/spec/domains');
|
|
730
|
+
}
|
|
731
|
+
const nextSpec = Object.freeze({
|
|
732
|
+
...manifest.spec,
|
|
733
|
+
scope: Object.freeze({
|
|
734
|
+
writable: manifest.spec.scope.writable,
|
|
735
|
+
protected: nextProtected,
|
|
736
|
+
}),
|
|
737
|
+
});
|
|
738
|
+
const cloned = {
|
|
739
|
+
apiVersion: manifest.apiVersion,
|
|
740
|
+
kind: manifest.kind,
|
|
741
|
+
metadata: manifest.metadata,
|
|
742
|
+
spec: nextSpec,
|
|
743
|
+
};
|
|
744
|
+
Object.defineProperty(cloned, 'controlRoot', { value: controlRoot, enumerable: false });
|
|
745
|
+
Object.defineProperty(cloned, 'manifestPath', { value: manifestPath, enumerable: false });
|
|
746
|
+
return Object.freeze(cloned);
|
|
747
|
+
}
|
|
748
|
+
/**
|
|
749
|
+
* Load and validate a `TaskpackSuite` manifest (`<= 65_536` bytes) and all declared domain `Taskpack`
|
|
750
|
+
* manifests under `repositoryRoot`, enforcing `O_NOFOLLOW` / `nlink === 1`, unique domain IDs/paths/names,
|
|
751
|
+
* pairwise prefix-disjoint `headBranchPrefix` per `targetBranch`, and the suite-wide mandatory protected
|
|
752
|
+
* path union (`<= 128` patterns, disjoint from every domain's `writable` paths).
|
|
753
|
+
*/
|
|
754
|
+
export async function loadTaskpackSuite(options) {
|
|
755
|
+
if (options.gitRevision !== undefined && options.verifyDigests === true) {
|
|
756
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', 'verifyDigests cannot be combined with gitRevision because digest verification inspects the working tree', '/');
|
|
757
|
+
}
|
|
758
|
+
const policyProfile = options.policyProfile ?? options.hostPolicy?.policyProfile ?? 'local';
|
|
759
|
+
const { resolvedRoot, realRoot } = await resolveSafeRepositoryRoot(options.repositoryRoot);
|
|
760
|
+
const pinnedGitSha = options.gitRevision !== undefined
|
|
761
|
+
? await resolveGitCommitSha(resolvedRoot, options.gitRevision, 15_000)
|
|
762
|
+
: undefined;
|
|
763
|
+
const readControlFile = async (relPath, maxBytes, diagPath) => {
|
|
764
|
+
if (pinnedGitSha !== undefined) {
|
|
765
|
+
const bytes = await readOptionalGitBlobBytes(resolvedRoot, pinnedGitSha, relPath, maxBytes, 15_000);
|
|
766
|
+
if (bytes === null) {
|
|
767
|
+
throw new TaskpackError('TASKPACK_MANIFEST_INVALID', `path "${relPath}" does not exist in git revision ${pinnedGitSha}`, diagPath);
|
|
768
|
+
}
|
|
769
|
+
return { bytes, sha256: createHash('sha256').update(bytes).digest('hex') };
|
|
770
|
+
}
|
|
771
|
+
return readSafeControlFileUnderRoot(resolvedRoot, realRoot, relPath, maxBytes, diagPath);
|
|
772
|
+
};
|
|
773
|
+
const suitePath = resolveSuiteRelativePath(resolvedRoot, options.suitePath);
|
|
774
|
+
const suiteExt = extname(suitePath).toLowerCase();
|
|
775
|
+
if (suiteExt !== '.yaml' && suiteExt !== '.yml' && suiteExt !== '.json') {
|
|
776
|
+
suiteInvalid('suite manifest extension must be .yaml, .yml, or .json', '/');
|
|
777
|
+
}
|
|
778
|
+
const suiteControlRoot = deriveControlRoot(suitePath);
|
|
779
|
+
const { bytes: suiteBytes, sha256: suiteSha256 } = await readControlFile(suitePath, TASKPACK_SUITE_MANIFEST_BYTES, '/');
|
|
780
|
+
const effectiveAllowLoopbackHttp = options.allowLoopbackHttp ?? (policyProfile === 'local');
|
|
781
|
+
const suiteManifest = parseTaskpackSuiteManifest(suiteBytes, {
|
|
782
|
+
suitePath,
|
|
783
|
+
controlRoot: suiteControlRoot,
|
|
784
|
+
format: suiteExt === '.json' ? 'json' : 'yaml',
|
|
785
|
+
allowLoopbackHttp: effectiveAllowLoopbackHttp,
|
|
786
|
+
});
|
|
787
|
+
const githubSiblings = policyProfile === 'github'
|
|
788
|
+
? collectGitHubSiblingPaths({ repositoryRoot: resolvedRoot })
|
|
789
|
+
: Object.freeze([]);
|
|
790
|
+
const seenManifestNames = new Map();
|
|
791
|
+
const rawDomains = [];
|
|
792
|
+
for (const [idx, decl] of suiteManifest.spec.domains.entries()) {
|
|
793
|
+
const diagPath = `/spec/domains/${idx}/taskpack`;
|
|
794
|
+
const domainExt = extname(decl.taskpack).toLowerCase();
|
|
795
|
+
if (domainExt !== '.yaml' && domainExt !== '.yml' && domainExt !== '.json') {
|
|
796
|
+
suiteInvalid('domain taskpack extension must be .yaml, .yml, or .json', diagPath);
|
|
797
|
+
}
|
|
798
|
+
const { bytes: domainBytes, sha256: manifestSha256 } = await readControlFile(decl.taskpack, TASKPACK_MANIFEST_BYTES, diagPath);
|
|
799
|
+
const domainControlRoot = deriveControlRoot(decl.taskpack);
|
|
800
|
+
const domainManifest = validateTaskpackV2Manifest(parseTaskpackDocument(domainBytes, domainExt === '.json' ? 'json' : 'yaml'), {
|
|
801
|
+
controlRoot: domainControlRoot,
|
|
802
|
+
manifestPath: decl.taskpack,
|
|
803
|
+
policyProfile,
|
|
804
|
+
hostPolicy: options.hostPolicy,
|
|
805
|
+
enforceHostAuthority: options.enforceHostAuthority,
|
|
806
|
+
allowLoopbackHttp: options.allowLoopbackHttp,
|
|
807
|
+
executionMode: options.executionMode,
|
|
808
|
+
githubSiblings,
|
|
809
|
+
});
|
|
810
|
+
const existingOwner = seenManifestNames.get(domainManifest.metadata.name);
|
|
811
|
+
if (existingOwner !== undefined) {
|
|
812
|
+
suiteInvalid(`duplicate taskpack metadata.name "${domainManifest.metadata.name}" across domains "${existingOwner}" and "${decl.id}"`, `/spec/domains/${idx}`);
|
|
813
|
+
}
|
|
814
|
+
seenManifestNames.set(domainManifest.metadata.name, decl.id);
|
|
815
|
+
if (options.verifyDigests === true && domainManifest.spec.execution?.digests.pinDigests === true) {
|
|
816
|
+
await assertDigestLockfileVerified(resolvedRoot, domainManifest, domainControlRoot);
|
|
817
|
+
}
|
|
818
|
+
const allowWorkflowWrites = (policyProfile === 'github'
|
|
819
|
+
&& domainManifest.spec.execution?.capabilities.allowWorkflowWrites === true
|
|
820
|
+
&& (options.enforceHostAuthority === false || options.hostPolicy?.allowWorkflowWrites === true));
|
|
821
|
+
const controlPlane = collectManifestControlPlanePaths(domainManifest, {
|
|
822
|
+
policyProfile,
|
|
823
|
+
controlRoot: domainControlRoot,
|
|
824
|
+
manifestPath: decl.taskpack,
|
|
825
|
+
allowWorkflowWrites,
|
|
826
|
+
githubSiblings,
|
|
827
|
+
});
|
|
828
|
+
rawDomains.push({
|
|
829
|
+
decl,
|
|
830
|
+
index: idx,
|
|
831
|
+
controlRoot: domainControlRoot,
|
|
832
|
+
manifestSha256,
|
|
833
|
+
manifest: domainManifest,
|
|
834
|
+
allowWorkflowWrites,
|
|
835
|
+
controlPlane,
|
|
836
|
+
});
|
|
837
|
+
}
|
|
838
|
+
// Pairwise prefix-disjoint headBranchPrefix per targetBranch across all pull_request domains
|
|
839
|
+
const prDomainsByTarget = new Map();
|
|
840
|
+
for (const item of rawDomains) {
|
|
841
|
+
if (item.manifest.spec.publication.mode === 'pull_request') {
|
|
842
|
+
const tb = item.manifest.spec.publication.targetBranch;
|
|
843
|
+
const list = prDomainsByTarget.get(tb) ?? [];
|
|
844
|
+
list.push(item);
|
|
845
|
+
prDomainsByTarget.set(tb, list);
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
for (const [targetBranch, list] of prDomainsByTarget.entries()) {
|
|
849
|
+
for (let i = 0; i < list.length; i += 1) {
|
|
850
|
+
for (let j = i + 1; j < list.length; j += 1) {
|
|
851
|
+
const domA = list[i];
|
|
852
|
+
const domB = list[j];
|
|
853
|
+
const prefA = domA.manifest.spec.publication.mode === 'pull_request' ? domA.manifest.spec.publication.headBranchPrefix : '';
|
|
854
|
+
const prefB = domB.manifest.spec.publication.mode === 'pull_request' ? domB.manifest.spec.publication.headBranchPrefix : '';
|
|
855
|
+
if (headBranchPrefixesCollide(prefA, prefB)) {
|
|
856
|
+
suiteInvalid(`domains "${domA.decl.id}" ("${prefA}") and "${domB.decl.id}" ("${prefB}") declare colliding headBranchPrefix values on targetBranch "${targetBranch}"`, `/spec/domains/${domB.index}`);
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
// Reject colliding carved-out proposal paths across domains or against the suite manifest (case-insensitively)
|
|
862
|
+
const seenCarvedProposals = [];
|
|
863
|
+
for (const item of rawDomains) {
|
|
864
|
+
const propPath = item.controlPlane.carvedOutProposalPath;
|
|
865
|
+
if (propPath === undefined)
|
|
866
|
+
continue;
|
|
867
|
+
if (pathCoveredByCaseInsensitive(propPath, suitePath) || pathCoveredByCaseInsensitive(suitePath, propPath)) {
|
|
868
|
+
suiteInvalid(`domain "${item.decl.id}" carved-out proposal.path "${propPath}" collides with suite manifest "${suitePath}"`, `/spec/domains/${item.index}`);
|
|
869
|
+
}
|
|
870
|
+
for (const prev of seenCarvedProposals) {
|
|
871
|
+
if (pathCoveredByCaseInsensitive(propPath, prev.path) || pathCoveredByCaseInsensitive(prev.path, propPath)) {
|
|
872
|
+
suiteInvalid(`domains "${prev.domainId}" ("${prev.path}") and "${item.decl.id}" ("${propPath}") declare colliding carved-out proposal.path values`, `/spec/domains/${item.index}`);
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
seenCarvedProposals.push({ domainId: item.decl.id, path: propPath, index: item.index });
|
|
876
|
+
}
|
|
877
|
+
// Compute suite-wide mandatory protected path union (paths NO domain in the suite may write).
|
|
878
|
+
// Carve-out matching uses exact `pathCoveredBy` to stay aligned with `canCarveOutControlRootProposal`
|
|
879
|
+
// and `collectControlRootSiblingPaths`; case-variant control roots fail closed during overlap checks.
|
|
880
|
+
const carvedOutProposals = seenCarvedProposals.map(entry => entry.path);
|
|
881
|
+
const isRootCarvedByAnyProposal = (dirRoot) => (carvedOutProposals.some(propPath => pathCoveredBy(propPath, dirRoot)));
|
|
882
|
+
const siblingCache = new Map();
|
|
883
|
+
const getControlRootSiblings = (dirRoot, propPath) => {
|
|
884
|
+
const key = `${dirRoot}\0${propPath}`;
|
|
885
|
+
const cached = siblingCache.get(key);
|
|
886
|
+
if (cached !== undefined)
|
|
887
|
+
return cached;
|
|
888
|
+
const computed = collectControlRootSiblingPaths({
|
|
889
|
+
repositoryRoot: resolvedRoot,
|
|
890
|
+
controlRoot: dirRoot,
|
|
891
|
+
proposalPath: propPath,
|
|
892
|
+
});
|
|
893
|
+
siblingCache.set(key, computed);
|
|
894
|
+
return computed;
|
|
895
|
+
};
|
|
896
|
+
const suiteDirRaw = posix.dirname(suitePath);
|
|
897
|
+
const hasDedicatedSuiteDir = suiteDirRaw !== '.' && suiteDirRaw !== '';
|
|
898
|
+
const allAllowWorkflowWrites = policyProfile === 'github'
|
|
899
|
+
&& rawDomains.length > 0
|
|
900
|
+
&& rawDomains.every(d => d.allowWorkflowWrites);
|
|
901
|
+
const builtInAutomation = policyProfile === 'local'
|
|
902
|
+
? LOCAL_PROTECTED_AUTOMATION_PATHS
|
|
903
|
+
: (allAllowWorkflowWrites
|
|
904
|
+
? GITHUB_PROTECTED_AUTOMATION_PATHS.filter(entry => entry !== '.github')
|
|
905
|
+
: GITHUB_PROTECTED_AUTOMATION_PATHS);
|
|
906
|
+
const suiteUnionSet = new Set([
|
|
907
|
+
...builtInAutomation,
|
|
908
|
+
suitePath,
|
|
909
|
+
]);
|
|
910
|
+
const addSuiteWideCarvedSiblings = (dirRoot) => {
|
|
911
|
+
for (const propPath of carvedOutProposals) {
|
|
912
|
+
if (!pathCoveredBy(propPath, dirRoot))
|
|
913
|
+
continue;
|
|
914
|
+
const sibs = getControlRootSiblings(dirRoot, propPath);
|
|
915
|
+
for (const s of sibs.prioritySiblings) {
|
|
916
|
+
if (!isRootCarvedByAnyProposal(s))
|
|
917
|
+
suiteUnionSet.add(s);
|
|
918
|
+
}
|
|
919
|
+
for (const s of sibs.regularSiblings) {
|
|
920
|
+
if (!isRootCarvedByAnyProposal(s))
|
|
921
|
+
suiteUnionSet.add(s);
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
};
|
|
925
|
+
if (hasDedicatedSuiteDir) {
|
|
926
|
+
if (!isRootCarvedByAnyProposal(suiteControlRoot)) {
|
|
927
|
+
suiteUnionSet.add(suiteControlRoot);
|
|
928
|
+
}
|
|
929
|
+
else {
|
|
930
|
+
suiteUnionSet.add(`${suiteControlRoot}/policies`);
|
|
931
|
+
suiteUnionSet.add(`${suiteControlRoot}/checks`);
|
|
932
|
+
suiteUnionSet.add(`${suiteControlRoot}/scripts`);
|
|
933
|
+
suiteUnionSet.add(`${suiteControlRoot}/memory`);
|
|
934
|
+
suiteUnionSet.add(`${suiteControlRoot}/taskpack.yaml`);
|
|
935
|
+
suiteUnionSet.add(`${suiteControlRoot}/taskpack.yml`);
|
|
936
|
+
suiteUnionSet.add(`${suiteControlRoot}/taskpack.json`);
|
|
937
|
+
suiteUnionSet.add(`${suiteControlRoot}/digests.lock.json`);
|
|
938
|
+
addSuiteWideCarvedSiblings(suiteControlRoot);
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
for (const item of rawDomains) {
|
|
942
|
+
if (isRootCarvedByAnyProposal(item.controlRoot)) {
|
|
943
|
+
for (const p of item.controlPlane.explicitWithoutControlRoot) {
|
|
944
|
+
suiteUnionSet.add(p);
|
|
945
|
+
}
|
|
946
|
+
addSuiteWideCarvedSiblings(item.controlRoot);
|
|
947
|
+
}
|
|
948
|
+
else {
|
|
949
|
+
for (const p of item.controlPlane.compactMandatoryPaths) {
|
|
950
|
+
suiteUnionSet.add(p);
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
const suiteProtectedPaths = Object.freeze([...suiteUnionSet]);
|
|
955
|
+
if (suiteProtectedPaths.length > LIMITS.patterns) {
|
|
956
|
+
suiteInvalid(`suite-wide mandatory protected path union (${suiteProtectedPaths.length}) exceeds ${LIMITS.patterns} patterns`, '/spec/domains');
|
|
957
|
+
}
|
|
958
|
+
const builtInProtectedSet = new Set([...LOCAL_PROTECTED_AUTOMATION_PATHS, ...GITHUB_PROTECTED_AUTOMATION_PATHS]);
|
|
959
|
+
const loadedDomains = [];
|
|
960
|
+
for (const item of rawDomains) {
|
|
961
|
+
const ownCarvedProposal = item.controlPlane.carvedOutProposalPath;
|
|
962
|
+
// Start with suite-wide invariants, then add peer control roots, peer proposals, and siblings along this domain's own carved-out spine.
|
|
963
|
+
const perDomainSuiteExtra = new Set(suiteProtectedPaths);
|
|
964
|
+
const addOwnCarvedSiblings = (dirRoot, propPath) => {
|
|
965
|
+
const sibs = getControlRootSiblings(dirRoot, propPath);
|
|
966
|
+
for (const s of sibs.prioritySiblings)
|
|
967
|
+
perDomainSuiteExtra.add(s);
|
|
968
|
+
for (const s of sibs.regularSiblings)
|
|
969
|
+
perDomainSuiteExtra.add(s);
|
|
970
|
+
};
|
|
971
|
+
if (hasDedicatedSuiteDir) {
|
|
972
|
+
if (ownCarvedProposal === undefined || !pathCoveredBy(ownCarvedProposal, suiteControlRoot)) {
|
|
973
|
+
perDomainSuiteExtra.add(suiteControlRoot);
|
|
974
|
+
}
|
|
975
|
+
else {
|
|
976
|
+
addOwnCarvedSiblings(suiteControlRoot, ownCarvedProposal);
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
if (ownCarvedProposal !== undefined && pathCoveredBy(ownCarvedProposal, item.controlRoot)) {
|
|
980
|
+
addOwnCarvedSiblings(item.controlRoot, ownCarvedProposal);
|
|
981
|
+
}
|
|
982
|
+
for (const peer of rawDomains) {
|
|
983
|
+
if (peer.decl.id === item.decl.id)
|
|
984
|
+
continue;
|
|
985
|
+
if (ownCarvedProposal === undefined || !pathCoveredBy(ownCarvedProposal, peer.controlRoot)) {
|
|
986
|
+
perDomainSuiteExtra.add(peer.controlRoot);
|
|
987
|
+
}
|
|
988
|
+
else {
|
|
989
|
+
addOwnCarvedSiblings(peer.controlRoot, ownCarvedProposal);
|
|
990
|
+
}
|
|
991
|
+
if (peer.controlPlane.carvedOutProposalPath !== undefined) {
|
|
992
|
+
perDomainSuiteExtra.add(peer.controlPlane.carvedOutProposalPath);
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
for (const [wIdx, writablePattern] of item.manifest.spec.scope.writable.entries()) {
|
|
996
|
+
for (const protectedEntry of perDomainSuiteExtra) {
|
|
997
|
+
const isBuiltIn = builtInProtectedSet.has(protectedEntry);
|
|
998
|
+
if (writableOverlapsMandatoryProtected(writablePattern, protectedEntry, item.allowWorkflowWrites, isBuiltIn)) {
|
|
999
|
+
suiteInvalid(`domain "${item.decl.id}" writable path "${writablePattern}" overlaps suite mandatory protected path "${protectedEntry}"`, `/spec/domains/${item.index}/scope/writable/${wIdx}`);
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
const extraList = Object.freeze([...perDomainSuiteExtra]);
|
|
1004
|
+
const domainEffectiveProtected = effectiveProtectedPaths(item.manifest.spec.scope.protected, {
|
|
1005
|
+
policyProfile,
|
|
1006
|
+
controlRoot: item.controlRoot,
|
|
1007
|
+
manifestPath: item.decl.taskpack,
|
|
1008
|
+
digestsLockfile: item.manifest.spec.execution?.digests.lockfile,
|
|
1009
|
+
instructions: [
|
|
1010
|
+
...(item.manifest.spec.instructions ?? []),
|
|
1011
|
+
...(item.manifest.spec.roles ?? []).flatMap(r => r.instructions ?? []),
|
|
1012
|
+
],
|
|
1013
|
+
skills: [
|
|
1014
|
+
...(item.manifest.spec.skills ?? []),
|
|
1015
|
+
...(item.manifest.spec.roles ?? []).flatMap(r => r.skills ?? []),
|
|
1016
|
+
],
|
|
1017
|
+
preflightScript: item.manifest.spec.preflight?.script,
|
|
1018
|
+
proposalPath: ownCarvedProposal,
|
|
1019
|
+
extraProtectedPaths: extraList,
|
|
1020
|
+
allowWorkflowWrites: item.allowWorkflowWrites,
|
|
1021
|
+
githubSiblings,
|
|
1022
|
+
});
|
|
1023
|
+
if (domainEffectiveProtected.length > LIMITS.patterns) {
|
|
1024
|
+
suiteInvalid(`domain "${item.decl.id}" effective protected path union (${domainEffectiveProtected.length}) exceeds ${LIMITS.patterns} patterns`, `/spec/domains/${item.index}`);
|
|
1025
|
+
}
|
|
1026
|
+
const augmentedManifest = cloneManifestWithAdditionalProtectedPaths(item.manifest, extraList, item.controlRoot, item.decl.taskpack);
|
|
1027
|
+
loadedDomains.push(Object.freeze({
|
|
1028
|
+
id: item.decl.id,
|
|
1029
|
+
taskpackPath: item.decl.taskpack,
|
|
1030
|
+
taskpackName: augmentedManifest.metadata.name,
|
|
1031
|
+
controlRoot: item.controlRoot,
|
|
1032
|
+
manifestSha256: item.manifestSha256,
|
|
1033
|
+
enabled: item.decl.enabled,
|
|
1034
|
+
...(item.decl.schedules !== undefined ? { schedules: item.decl.schedules } : {}),
|
|
1035
|
+
...(item.decl.stage !== undefined ? { stage: item.decl.stage } : {}),
|
|
1036
|
+
...(item.decl.matrix !== undefined ? { matrix: item.decl.matrix } : {}),
|
|
1037
|
+
manifest: augmentedManifest,
|
|
1038
|
+
protectedPaths: domainEffectiveProtected,
|
|
1039
|
+
}));
|
|
1040
|
+
}
|
|
1041
|
+
return Object.freeze({
|
|
1042
|
+
manifest: suiteManifest,
|
|
1043
|
+
suitePath,
|
|
1044
|
+
controlRoot: suiteControlRoot,
|
|
1045
|
+
suiteSha256,
|
|
1046
|
+
suiteProtectedPaths,
|
|
1047
|
+
stageOrder: computeTopologicalStageOrder(suiteManifest.spec.stages),
|
|
1048
|
+
domains: Object.freeze(loadedDomains),
|
|
1049
|
+
});
|
|
1050
|
+
}
|
|
1051
|
+
/** Alias for `loadTaskpackSuite` supporting optional `verifyDigests` check for CLI `suite check`. */
|
|
1052
|
+
export async function checkTaskpackSuite(options) {
|
|
1053
|
+
return loadTaskpackSuite(options);
|
|
1054
|
+
}
|
|
1055
|
+
/** Alias validating and loading a `TaskpackSuite` against `repositoryRoot`. */
|
|
1056
|
+
export async function validateTaskpackSuite(options) {
|
|
1057
|
+
return loadTaskpackSuite(options);
|
|
1058
|
+
}
|
|
1059
|
+
// ---------------------------------------------------------------------------
|
|
1060
|
+
// Strictly Git-backed versionFrom reader & stateless stage readiness probes
|
|
1061
|
+
// ---------------------------------------------------------------------------
|
|
1062
|
+
function extractByRfc6901Pointer(root, pointer) {
|
|
1063
|
+
const segments = validateRfc6901JsonPointer(pointer, '/jsonPointer');
|
|
1064
|
+
let current = root;
|
|
1065
|
+
for (const seg of segments) {
|
|
1066
|
+
if (Array.isArray(current)) {
|
|
1067
|
+
if (!/^(?:0|[1-9]\d*)$/.test(seg))
|
|
1068
|
+
return undefined;
|
|
1069
|
+
const idx = Number.parseInt(seg, 10);
|
|
1070
|
+
if (!Number.isSafeInteger(idx) || idx < 0 || idx >= current.length)
|
|
1071
|
+
return undefined;
|
|
1072
|
+
current = current[idx];
|
|
1073
|
+
}
|
|
1074
|
+
else if (isPlainRecord(current)) {
|
|
1075
|
+
if (FORBIDDEN_KEYS.has(seg) || !Object.hasOwn(current, seg))
|
|
1076
|
+
return undefined;
|
|
1077
|
+
current = current[seg];
|
|
1078
|
+
}
|
|
1079
|
+
else {
|
|
1080
|
+
return undefined;
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
if (typeof current !== 'string')
|
|
1084
|
+
return undefined;
|
|
1085
|
+
if (/[\0\r\n]/.test(current)) {
|
|
1086
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `JSON Pointer "${pointer}" resolved to a multiline or NUL-containing string`);
|
|
1087
|
+
}
|
|
1088
|
+
const trimmed = current.trim();
|
|
1089
|
+
if (trimmed.length === 0 || trimmed.length > 256)
|
|
1090
|
+
return undefined;
|
|
1091
|
+
return trimmed;
|
|
1092
|
+
}
|
|
1093
|
+
async function readOptionalGitBlobBytes(repositoryRoot, resolvedSha, relPath, maxBytes, timeoutMs) {
|
|
1094
|
+
const normalizedPath = normalizeRelativePath(relPath, '/baseline/path');
|
|
1095
|
+
const gitBin = resolveGitExecutable();
|
|
1096
|
+
const cleanEnv = buildCleanGitEnv();
|
|
1097
|
+
const { stdout: lsTreeOut } = await execFileAsync(gitBin, ['-C', repositoryRoot, '-c', 'core.hooksPath=/dev/null', 'ls-tree', '-z', resolvedSha, '--', normalizedPath], { env: cleanEnv, timeout: timeoutMs, maxBuffer: 65_536, encoding: 'utf8' });
|
|
1098
|
+
const rows = lsTreeOut.split('\0').filter(Boolean);
|
|
1099
|
+
if (rows.length === 0)
|
|
1100
|
+
return null;
|
|
1101
|
+
if (rows.length !== 1) {
|
|
1102
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `unexpected git ls-tree entry count for "${normalizedPath}"`);
|
|
1103
|
+
}
|
|
1104
|
+
const match = /^([0-9]{6}) ([a-z]+) ([0-9a-f]{40}|[0-9a-f]{64})\t(.+)$/s.exec(rows[0]);
|
|
1105
|
+
if (match === null || match[4] !== normalizedPath) {
|
|
1106
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `unexpected git ls-tree entry for "${normalizedPath}"`);
|
|
1107
|
+
}
|
|
1108
|
+
const mode = match[1];
|
|
1109
|
+
const objType = match[2];
|
|
1110
|
+
if (mode === '120000' || objType !== 'blob') {
|
|
1111
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `baseline path "${normalizedPath}" in commit ${resolvedSha} must be a regular blob (found mode=${mode} type=${objType})`);
|
|
1112
|
+
}
|
|
1113
|
+
const { stdout: sizeOut } = await execFileAsync(gitBin, ['-C', repositoryRoot, '-c', 'core.hooksPath=/dev/null', 'cat-file', '-s', `${resolvedSha}:${normalizedPath}`], { env: cleanEnv, timeout: timeoutMs, maxBuffer: 4_096, encoding: 'utf8' });
|
|
1114
|
+
const byteSize = Number.parseInt(sizeOut.trim(), 10);
|
|
1115
|
+
if (!Number.isSafeInteger(byteSize) || byteSize < 0 || byteSize > maxBytes) {
|
|
1116
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `baseline blob "${normalizedPath}" (${byteSize} bytes) exceeds ${maxBytes} bytes`);
|
|
1117
|
+
}
|
|
1118
|
+
const { stdout: blobBuf } = await execFileAsync(gitBin, ['-C', repositoryRoot, '-c', 'core.hooksPath=/dev/null', 'cat-file', '-p', `${resolvedSha}:${normalizedPath}`], { env: cleanEnv, timeout: timeoutMs, maxBuffer: maxBytes + 1_024, encoding: 'buffer' });
|
|
1119
|
+
return blobBuf;
|
|
1120
|
+
}
|
|
1121
|
+
async function hasLocalGitCommit(repositoryRoot, sha, timeoutMs) {
|
|
1122
|
+
if (!existsSync(join(resolve(repositoryRoot), '.git')))
|
|
1123
|
+
return false;
|
|
1124
|
+
try {
|
|
1125
|
+
const gitBin = resolveGitExecutable();
|
|
1126
|
+
const cleanEnv = buildCleanGitEnv();
|
|
1127
|
+
const { stdout } = await execFileAsync(gitBin, ['-C', repositoryRoot, '-c', 'core.hooksPath=/dev/null', 'cat-file', '-t', sha], { env: cleanEnv, timeout: timeoutMs, maxBuffer: 4_096, encoding: 'utf8' });
|
|
1128
|
+
return stdout.trim() === 'commit';
|
|
1129
|
+
}
|
|
1130
|
+
catch {
|
|
1131
|
+
return false;
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
const MAX_REMOTE_BLOB_CACHE_BYTES = 4 * 1024 * 1024;
|
|
1135
|
+
async function fetchGitHubContentsBlobBytes(options) {
|
|
1136
|
+
const normalizedPath = normalizeRelativePath(options.relPath, '/baseline/path');
|
|
1137
|
+
const treeEnvelopeLimit = Math.max(MAX_SUITE_STAGE_VERSION_BLOB_BYTES * 4, 4 * 1024 * 1024);
|
|
1138
|
+
const blobEnvelopeLimit = Math.ceil((options.maxBytes * 4) / 3) + 65_536;
|
|
1139
|
+
// 1. Resolve commit -> root tree SHA via Git Data API so symlinks (mode 120000) are NEVER dereferenced.
|
|
1140
|
+
const loadCommitTreeSha = () => {
|
|
1141
|
+
const cacheKey = `${options.repositoryFullName}\0${options.resolvedSha}`;
|
|
1142
|
+
const cached = options.cache?.commitTreeSha.get(cacheKey);
|
|
1143
|
+
if (cached !== undefined)
|
|
1144
|
+
return cached;
|
|
1145
|
+
const promise = (async () => {
|
|
1146
|
+
const commitUrl = `${options.apiBaseUrl}/repos/${options.repositoryFullName}/git/commits/${encodeURIComponent(options.resolvedSha)}`;
|
|
1147
|
+
const commitRes = await fetchBoundedProbeResponse(commitUrl, options.fetchImpl, options.githubHeaders, options.timeoutMs, MAX_SUITE_STAGE_VERSION_BLOB_BYTES);
|
|
1148
|
+
if (commitRes.status === 404) {
|
|
1149
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `remote commit ${options.resolvedSha} does not exist in "${options.repositoryFullName}"`);
|
|
1150
|
+
}
|
|
1151
|
+
if (!commitRes.ok) {
|
|
1152
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `remote commit lookup for ${options.resolvedSha} failed with HTTP ${commitRes.status}`);
|
|
1153
|
+
}
|
|
1154
|
+
let commitDoc;
|
|
1155
|
+
try {
|
|
1156
|
+
commitDoc = JSON.parse(commitRes.text);
|
|
1157
|
+
}
|
|
1158
|
+
catch {
|
|
1159
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `remote commit lookup for ${options.resolvedSha} returned invalid JSON`);
|
|
1160
|
+
}
|
|
1161
|
+
const rootTreeObj = isPlainRecord(commitDoc) && isPlainRecord(commitDoc['tree']) ? commitDoc['tree'] : null;
|
|
1162
|
+
const rootTreeSha = typeof rootTreeObj?.['sha'] === 'string' && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(rootTreeObj['sha'])
|
|
1163
|
+
? rootTreeObj['sha'].toLowerCase()
|
|
1164
|
+
: null;
|
|
1165
|
+
if (rootTreeSha === null) {
|
|
1166
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `remote commit ${options.resolvedSha} response lacks a valid tree SHA`);
|
|
1167
|
+
}
|
|
1168
|
+
return rootTreeSha;
|
|
1169
|
+
})();
|
|
1170
|
+
options.cache?.commitTreeSha.set(cacheKey, promise);
|
|
1171
|
+
return promise;
|
|
1172
|
+
};
|
|
1173
|
+
const rootTreeSha = await loadCommitTreeSha();
|
|
1174
|
+
const loadTreeDoc = (treeSha) => {
|
|
1175
|
+
const cacheKey = `${options.repositoryFullName}\0${treeSha}`;
|
|
1176
|
+
const cached = options.cache?.treeDocs.get(cacheKey);
|
|
1177
|
+
if (cached !== undefined)
|
|
1178
|
+
return cached;
|
|
1179
|
+
const promise = (async () => {
|
|
1180
|
+
const treeUrl = `${options.apiBaseUrl}/repos/${options.repositoryFullName}/git/trees/${encodeURIComponent(treeSha)}`;
|
|
1181
|
+
const treeRes = await fetchBoundedProbeResponse(treeUrl, options.fetchImpl, options.githubHeaders, options.timeoutMs, treeEnvelopeLimit);
|
|
1182
|
+
if (!treeRes.ok) {
|
|
1183
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `remote tree lookup for ${treeSha} failed with HTTP ${treeRes.status}`);
|
|
1184
|
+
}
|
|
1185
|
+
let treeDoc;
|
|
1186
|
+
try {
|
|
1187
|
+
treeDoc = JSON.parse(treeRes.text);
|
|
1188
|
+
}
|
|
1189
|
+
catch {
|
|
1190
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `remote tree lookup for ${treeSha} returned invalid JSON`);
|
|
1191
|
+
}
|
|
1192
|
+
if (!isPlainRecord(treeDoc) || !Array.isArray(treeDoc['tree'])) {
|
|
1193
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `remote tree ${treeSha} response lacks a tree array`);
|
|
1194
|
+
}
|
|
1195
|
+
const entries = [];
|
|
1196
|
+
for (const rawEntry of treeDoc['tree']) {
|
|
1197
|
+
if (isPlainRecord(rawEntry))
|
|
1198
|
+
entries.push(rawEntry);
|
|
1199
|
+
}
|
|
1200
|
+
return { entries, truncated: treeDoc['truncated'] === true };
|
|
1201
|
+
})();
|
|
1202
|
+
options.cache?.treeDocs.set(cacheKey, promise);
|
|
1203
|
+
return promise;
|
|
1204
|
+
};
|
|
1205
|
+
// 2. Walk every literal path segment through pinned Git trees, requiring 040000 dirs and 100644/100755 leaf blob.
|
|
1206
|
+
const segments = normalizedPath.split('/');
|
|
1207
|
+
let currentTreeSha = rootTreeSha;
|
|
1208
|
+
let leafBlobSha = null;
|
|
1209
|
+
for (let i = 0; i < segments.length; i += 1) {
|
|
1210
|
+
const seg = segments[i];
|
|
1211
|
+
const isLeaf = i === segments.length - 1;
|
|
1212
|
+
const treeDoc = await loadTreeDoc(currentTreeSha);
|
|
1213
|
+
let matchedEntry = null;
|
|
1214
|
+
for (const rawEntry of treeDoc.entries) {
|
|
1215
|
+
if (rawEntry['path'] === seg) {
|
|
1216
|
+
matchedEntry = rawEntry;
|
|
1217
|
+
break;
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
if (matchedEntry === null) {
|
|
1221
|
+
if (treeDoc.truncated) {
|
|
1222
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `remote tree ${currentTreeSha} was truncated while resolving "${normalizedPath}"`);
|
|
1223
|
+
}
|
|
1224
|
+
if (options.optional)
|
|
1225
|
+
return null;
|
|
1226
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `path "${normalizedPath}" does not exist in remote commit ${options.resolvedSha}`);
|
|
1227
|
+
}
|
|
1228
|
+
const mode = typeof matchedEntry['mode'] === 'string' ? matchedEntry['mode'] : '';
|
|
1229
|
+
const entryType = typeof matchedEntry['type'] === 'string' ? matchedEntry['type'] : '';
|
|
1230
|
+
const entrySha = typeof matchedEntry['sha'] === 'string' && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(matchedEntry['sha'])
|
|
1231
|
+
? matchedEntry['sha'].toLowerCase()
|
|
1232
|
+
: null;
|
|
1233
|
+
if (entrySha === null) {
|
|
1234
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `remote tree entry "${seg}" lacks a valid SHA`);
|
|
1235
|
+
}
|
|
1236
|
+
if (!isLeaf) {
|
|
1237
|
+
if (mode !== '040000' || entryType !== 'tree') {
|
|
1238
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `remote path "${normalizedPath}" traverses non-tree segment "${seg}" (mode=${mode} type=${entryType})`);
|
|
1239
|
+
}
|
|
1240
|
+
currentTreeSha = entrySha;
|
|
1241
|
+
}
|
|
1242
|
+
else {
|
|
1243
|
+
if ((mode !== '100644' && mode !== '100755') || entryType !== 'blob') {
|
|
1244
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `remote path "${normalizedPath}" at ${options.resolvedSha} must be a regular blob (found mode=${mode} type=${entryType})`);
|
|
1245
|
+
}
|
|
1246
|
+
if (typeof matchedEntry['size'] === 'number' && matchedEntry['size'] > options.maxBytes) {
|
|
1247
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `remote blob "${normalizedPath}" (${matchedEntry['size']} bytes) exceeds ${options.maxBytes} bytes`);
|
|
1248
|
+
}
|
|
1249
|
+
leafBlobSha = entrySha;
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
if (leafBlobSha === null)
|
|
1253
|
+
return null;
|
|
1254
|
+
const blobCacheKey = `${options.repositoryFullName}\0${leafBlobSha}`;
|
|
1255
|
+
const cachedBlobPromise = options.cache?.blobBytes.get(blobCacheKey);
|
|
1256
|
+
if (cachedBlobPromise !== undefined) {
|
|
1257
|
+
const cachedBytes = await cachedBlobPromise;
|
|
1258
|
+
if (cachedBytes.byteLength > options.maxBytes) {
|
|
1259
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `remote blob "${normalizedPath}" (${cachedBytes.byteLength} bytes) exceeds ${options.maxBytes} bytes`);
|
|
1260
|
+
}
|
|
1261
|
+
return cachedBytes;
|
|
1262
|
+
}
|
|
1263
|
+
// 3. Fetch the exact blob by object ID with transport cap sized for base64 JSON envelope,
|
|
1264
|
+
// then enforce maxBytes on the decoded bytes and verify the Git blob SHA-1.
|
|
1265
|
+
const fetchBlobPromise = (async () => {
|
|
1266
|
+
const blobUrl = `${options.apiBaseUrl}/repos/${options.repositoryFullName}/git/blobs/${encodeURIComponent(leafBlobSha)}`;
|
|
1267
|
+
const blobRes = await fetchBoundedProbeResponse(blobUrl, options.fetchImpl, options.githubHeaders, options.timeoutMs, blobEnvelopeLimit);
|
|
1268
|
+
if (!blobRes.ok) {
|
|
1269
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `remote blob lookup for "${normalizedPath}" (${leafBlobSha}) failed with HTTP ${blobRes.status}`);
|
|
1270
|
+
}
|
|
1271
|
+
let blobDoc;
|
|
1272
|
+
try {
|
|
1273
|
+
blobDoc = JSON.parse(blobRes.text);
|
|
1274
|
+
}
|
|
1275
|
+
catch {
|
|
1276
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `remote blob lookup for "${normalizedPath}" returned invalid JSON`);
|
|
1277
|
+
}
|
|
1278
|
+
if (!isPlainRecord(blobDoc)) {
|
|
1279
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `remote blob response for "${normalizedPath}" must be an object`);
|
|
1280
|
+
}
|
|
1281
|
+
if (typeof blobDoc['size'] === 'number' && blobDoc['size'] > options.maxBytes) {
|
|
1282
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `remote blob "${normalizedPath}" (${blobDoc['size']} bytes) exceeds ${options.maxBytes} bytes`);
|
|
1283
|
+
}
|
|
1284
|
+
if (blobDoc['encoding'] !== 'base64' || typeof blobDoc['content'] !== 'string') {
|
|
1285
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `remote blob "${normalizedPath}" lacks base64 content`);
|
|
1286
|
+
}
|
|
1287
|
+
const bytes = Buffer.from(blobDoc['content'].replace(/\s+/g, ''), 'base64');
|
|
1288
|
+
if (bytes.byteLength > options.maxBytes) {
|
|
1289
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `remote blob "${normalizedPath}" (${bytes.byteLength} bytes) exceeds ${options.maxBytes} bytes`);
|
|
1290
|
+
}
|
|
1291
|
+
const hashAlgo = leafBlobSha.length === 64 ? 'sha256' : 'sha1';
|
|
1292
|
+
const actualGitBlobSha = createHash(hashAlgo).update(`blob ${bytes.byteLength}\0`).update(bytes).digest('hex');
|
|
1293
|
+
if (actualGitBlobSha !== leafBlobSha) {
|
|
1294
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `remote blob "${normalizedPath}" ${hashAlgo.toUpperCase()} mismatch (expected ${leafBlobSha}, got ${actualGitBlobSha})`);
|
|
1295
|
+
}
|
|
1296
|
+
return bytes;
|
|
1297
|
+
})();
|
|
1298
|
+
const bytes = await fetchBlobPromise;
|
|
1299
|
+
if (options.cache !== undefined
|
|
1300
|
+
&& options.cache.totalCachedBlobBytes + bytes.byteLength <= MAX_REMOTE_BLOB_CACHE_BYTES) {
|
|
1301
|
+
options.cache.totalCachedBlobBytes += bytes.byteLength;
|
|
1302
|
+
options.cache.blobBytes.set(blobCacheKey, Promise.resolve(bytes));
|
|
1303
|
+
}
|
|
1304
|
+
return bytes;
|
|
1305
|
+
}
|
|
1306
|
+
function parseVersionFromBlobBytes(blobBuf, normalizedPath, selector) {
|
|
1307
|
+
if (blobBuf.byteLength > MAX_SUITE_STAGE_VERSION_BLOB_BYTES) {
|
|
1308
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `versionFrom blob "${normalizedPath}" exceeds ${MAX_SUITE_STAGE_VERSION_BLOB_BYTES} bytes`);
|
|
1309
|
+
}
|
|
1310
|
+
let text;
|
|
1311
|
+
try {
|
|
1312
|
+
text = new TextDecoder('utf-8', { fatal: true }).decode(blobBuf);
|
|
1313
|
+
}
|
|
1314
|
+
catch {
|
|
1315
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `versionFrom blob "${normalizedPath}" is not valid UTF-8`);
|
|
1316
|
+
}
|
|
1317
|
+
if (selector.jsonPointer !== undefined) {
|
|
1318
|
+
let parsed;
|
|
1319
|
+
try {
|
|
1320
|
+
parsed = JSON.parse(text);
|
|
1321
|
+
}
|
|
1322
|
+
catch (error) {
|
|
1323
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
1324
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `versionFrom "${normalizedPath}" is not valid JSON: ${detail}`);
|
|
1325
|
+
}
|
|
1326
|
+
const extracted = extractByRfc6901Pointer(parsed, selector.jsonPointer);
|
|
1327
|
+
if (extracted === undefined) {
|
|
1328
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `versionFrom pointer "${selector.jsonPointer}" did not resolve to a non-empty string in "${normalizedPath}"`);
|
|
1329
|
+
}
|
|
1330
|
+
return extracted;
|
|
1331
|
+
}
|
|
1332
|
+
if (normalizedPath.toLowerCase().endsWith('.json')) {
|
|
1333
|
+
let parsed;
|
|
1334
|
+
try {
|
|
1335
|
+
parsed = JSON.parse(text);
|
|
1336
|
+
}
|
|
1337
|
+
catch (error) {
|
|
1338
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
1339
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `versionFrom "${normalizedPath}" is not valid JSON: ${detail}`);
|
|
1340
|
+
}
|
|
1341
|
+
if (typeof parsed === 'string' && !/[\0\r\n]/.test(parsed) && parsed.trim().length > 0 && parsed.trim().length <= 256) {
|
|
1342
|
+
return parsed.trim();
|
|
1343
|
+
}
|
|
1344
|
+
if (isPlainRecord(parsed)
|
|
1345
|
+
&& Object.hasOwn(parsed, 'version')
|
|
1346
|
+
&& typeof parsed['version'] === 'string'
|
|
1347
|
+
&& !/[\0\r\n]/.test(parsed['version'])
|
|
1348
|
+
&& parsed['version'].trim().length > 0
|
|
1349
|
+
&& parsed['version'].trim().length <= 256) {
|
|
1350
|
+
return parsed['version'].trim();
|
|
1351
|
+
}
|
|
1352
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `versionFrom "${normalizedPath}" lacks a valid top-level "version" string`);
|
|
1353
|
+
}
|
|
1354
|
+
const trimmed = text.trim();
|
|
1355
|
+
if (trimmed.length === 0 || trimmed.length > 256 || /[\0\r\n]/.test(trimmed)) {
|
|
1356
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `versionFrom "${normalizedPath}" must contain a single-line string of 1..256 characters`);
|
|
1357
|
+
}
|
|
1358
|
+
return trimmed;
|
|
1359
|
+
}
|
|
1360
|
+
/**
|
|
1361
|
+
* Read a `versionFrom` string strictly from `baseRevision` in Git (`git cat-file -p <sha>:<path>`,
|
|
1362
|
+
* capped at `<= 1 MiB` UTF-8, refusing symlinks/trees and never reading the working tree on disk).
|
|
1363
|
+
*/
|
|
1364
|
+
export async function readGitRevisionVersionFrom(options) {
|
|
1365
|
+
const timeoutMs = options.timeoutMs ?? 15_000;
|
|
1366
|
+
const normalizedPath = normalizeRelativePath(options.selector.path, '/versionFrom/path');
|
|
1367
|
+
const resolvedSha = await resolveGitCommitSha(options.repositoryRoot, options.baseRevision, timeoutMs);
|
|
1368
|
+
const gitBin = resolveGitExecutable();
|
|
1369
|
+
const cleanEnv = buildCleanGitEnv();
|
|
1370
|
+
const { stdout: lsTreeOut } = await execFileAsync(gitBin, ['-C', options.repositoryRoot, '-c', 'core.hooksPath=/dev/null', 'ls-tree', '-z', resolvedSha, '--', normalizedPath], { env: cleanEnv, timeout: timeoutMs, maxBuffer: 65_536, encoding: 'utf8' });
|
|
1371
|
+
const rows = lsTreeOut.split('\0').filter(Boolean);
|
|
1372
|
+
if (rows.length !== 1) {
|
|
1373
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `versionFrom path "${normalizedPath}" does not exist in commit ${resolvedSha}`);
|
|
1374
|
+
}
|
|
1375
|
+
const match = /^([0-9]{6}) ([a-z]+) ([0-9a-f]{40}|[0-9a-f]{64})\t(.+)$/s.exec(rows[0]);
|
|
1376
|
+
if (match === null || match[4] !== normalizedPath) {
|
|
1377
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `unexpected git ls-tree entry for "${normalizedPath}"`);
|
|
1378
|
+
}
|
|
1379
|
+
const mode = match[1];
|
|
1380
|
+
const objType = match[2];
|
|
1381
|
+
if (mode === '120000' || objType !== 'blob') {
|
|
1382
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `versionFrom path "${normalizedPath}" in commit ${resolvedSha} must be a regular blob (found mode=${mode} type=${objType})`);
|
|
1383
|
+
}
|
|
1384
|
+
const { stdout: sizeOut } = await execFileAsync(gitBin, ['-C', options.repositoryRoot, '-c', 'core.hooksPath=/dev/null', 'cat-file', '-s', `${resolvedSha}:${normalizedPath}`], { env: cleanEnv, timeout: timeoutMs, maxBuffer: 4_096, encoding: 'utf8' });
|
|
1385
|
+
const byteSize = Number.parseInt(sizeOut.trim(), 10);
|
|
1386
|
+
if (!Number.isSafeInteger(byteSize) || byteSize < 0 || byteSize > MAX_SUITE_STAGE_VERSION_BLOB_BYTES) {
|
|
1387
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `versionFrom blob "${normalizedPath}" (${byteSize} bytes) exceeds ${MAX_SUITE_STAGE_VERSION_BLOB_BYTES} bytes`);
|
|
1388
|
+
}
|
|
1389
|
+
const { stdout: blobBuf } = await execFileAsync(gitBin, ['-C', options.repositoryRoot, '-c', 'core.hooksPath=/dev/null', 'cat-file', '-p', `${resolvedSha}:${normalizedPath}`], {
|
|
1390
|
+
env: cleanEnv,
|
|
1391
|
+
timeout: timeoutMs,
|
|
1392
|
+
maxBuffer: MAX_SUITE_STAGE_VERSION_BLOB_BYTES + 1_024,
|
|
1393
|
+
encoding: 'buffer',
|
|
1394
|
+
});
|
|
1395
|
+
return parseVersionFromBlobBytes(blobBuf, normalizedPath, options.selector);
|
|
1396
|
+
}
|
|
1397
|
+
function versionMatchesTag(observedTag, expectedVersion, explicitTagPrefix) {
|
|
1398
|
+
if (observedTag === expectedVersion)
|
|
1399
|
+
return true;
|
|
1400
|
+
if (explicitTagPrefix === undefined && STRICT_SEMVER_CORE_PATTERN.test(expectedVersion) && observedTag === `v${expectedVersion}`) {
|
|
1401
|
+
return true;
|
|
1402
|
+
}
|
|
1403
|
+
return false;
|
|
1404
|
+
}
|
|
1405
|
+
async function buildProbeAuthHeaders(githubToken, authHeaders, baseHeaders, scrubber) {
|
|
1406
|
+
const headers = { ...baseHeaders };
|
|
1407
|
+
const resolvedExtra = typeof authHeaders === 'function' ? await authHeaders() : authHeaders;
|
|
1408
|
+
if (resolvedExtra !== undefined) {
|
|
1409
|
+
for (const [key, value] of Object.entries(resolvedExtra)) {
|
|
1410
|
+
headers[key] = value;
|
|
1411
|
+
const lower = key.toLowerCase();
|
|
1412
|
+
if (lower === 'authorization' || lower === 'x-api-key' || lower === 'api-key') {
|
|
1413
|
+
scrubber.register(value);
|
|
1414
|
+
const bearerMatch = /^Bearer\s+(.+)$/i.exec(value);
|
|
1415
|
+
if (bearerMatch?.[1])
|
|
1416
|
+
scrubber.register(bearerMatch[1].trim());
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
const resolvedToken = (typeof githubToken === 'function' ? await githubToken() : githubToken)?.trim();
|
|
1421
|
+
if (resolvedToken !== undefined && resolvedToken.length > 0) {
|
|
1422
|
+
scrubber.register(resolvedToken);
|
|
1423
|
+
if (!Object.keys(headers).some(k => k.toLowerCase() === 'authorization')) {
|
|
1424
|
+
headers['authorization'] = `Bearer ${resolvedToken}`;
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
return headers;
|
|
1428
|
+
}
|
|
1429
|
+
const MAX_PROBE_API_PAGES = 10;
|
|
1430
|
+
function extractSameOriginNextLink(linkHeader, initialUrl) {
|
|
1431
|
+
if (linkHeader === null || linkHeader.trim().length === 0) {
|
|
1432
|
+
return { hasLinkHeader: false };
|
|
1433
|
+
}
|
|
1434
|
+
const initialOrigin = new URL(initialUrl).origin;
|
|
1435
|
+
for (const segment of linkHeader.split(',')) {
|
|
1436
|
+
const match = /<([^>\r\n]+)>\s*;\s*rel="?next"?(?:\s*;|\s*$)/i.exec(segment.trim());
|
|
1437
|
+
if (match?.[1] !== undefined) {
|
|
1438
|
+
let parsed;
|
|
1439
|
+
try {
|
|
1440
|
+
parsed = new URL(match[1]);
|
|
1441
|
+
}
|
|
1442
|
+
catch {
|
|
1443
|
+
return { hasLinkHeader: true, crossOriginError: `invalid pagination Link URL "${match[1]}"` };
|
|
1444
|
+
}
|
|
1445
|
+
if (parsed.origin !== initialOrigin) {
|
|
1446
|
+
return { hasLinkHeader: true, crossOriginError: `refusing cross-origin pagination Link "${parsed.origin}"` };
|
|
1447
|
+
}
|
|
1448
|
+
return { hasLinkHeader: true, nextUrl: parsed.toString() };
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
return { hasLinkHeader: true };
|
|
1452
|
+
}
|
|
1453
|
+
async function fetchBoundedProbeResponse(url, fetchImpl, headers, timeoutMs, maxResponseBytes = MAX_SUITE_STAGE_VERSION_BLOB_BYTES) {
|
|
1454
|
+
const controller = new AbortController();
|
|
1455
|
+
const timer = setTimeout(() => controller.abort(new Error(`probe request timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
1456
|
+
timer.unref?.();
|
|
1457
|
+
try {
|
|
1458
|
+
const response = await fetchImpl(url, {
|
|
1459
|
+
method: 'GET',
|
|
1460
|
+
headers,
|
|
1461
|
+
redirect: 'error',
|
|
1462
|
+
signal: controller.signal,
|
|
1463
|
+
});
|
|
1464
|
+
const contentLengthHeader = response.headers.get('content-length');
|
|
1465
|
+
if (contentLengthHeader !== null) {
|
|
1466
|
+
const declared = Number.parseInt(contentLengthHeader, 10);
|
|
1467
|
+
if (Number.isFinite(declared) && declared > maxResponseBytes) {
|
|
1468
|
+
await response.body?.cancel().catch(() => { });
|
|
1469
|
+
throw new Error(`probe response declared content-length ${declared} > ${maxResponseBytes}`);
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
const linkHeader = response.headers.get('link');
|
|
1473
|
+
if (response.body === null) {
|
|
1474
|
+
return { status: response.status, ok: response.ok, text: '', linkHeader };
|
|
1475
|
+
}
|
|
1476
|
+
const reader = response.body.getReader();
|
|
1477
|
+
const chunks = [];
|
|
1478
|
+
let total = 0;
|
|
1479
|
+
for (;;) {
|
|
1480
|
+
const { done, value } = await reader.read();
|
|
1481
|
+
if (done)
|
|
1482
|
+
break;
|
|
1483
|
+
total += value.byteLength;
|
|
1484
|
+
if (total > maxResponseBytes) {
|
|
1485
|
+
await reader.cancel().catch(() => { });
|
|
1486
|
+
throw new Error(`probe response exceeded ${maxResponseBytes} bytes`);
|
|
1487
|
+
}
|
|
1488
|
+
chunks.push(value);
|
|
1489
|
+
}
|
|
1490
|
+
const merged = Buffer.concat(chunks, total);
|
|
1491
|
+
const text = new TextDecoder('utf-8', { fatal: true }).decode(merged);
|
|
1492
|
+
return { status: response.status, ok: response.ok, text, linkHeader };
|
|
1493
|
+
}
|
|
1494
|
+
finally {
|
|
1495
|
+
clearTimeout(timer);
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
async function fetchProbeJsonPage(label, url, initialUrl, fetchImpl, headers, timeoutMs, scrubber) {
|
|
1499
|
+
const res = await fetchBoundedProbeResponse(url, fetchImpl, headers, timeoutMs);
|
|
1500
|
+
if (res.status === 404) {
|
|
1501
|
+
return {
|
|
1502
|
+
kind: 'result',
|
|
1503
|
+
outcome: {
|
|
1504
|
+
disposition: 'deferred',
|
|
1505
|
+
reason: 'stage_not_ready',
|
|
1506
|
+
detail: scrubber.scrub(`${label} returned 404`),
|
|
1507
|
+
},
|
|
1508
|
+
};
|
|
1509
|
+
}
|
|
1510
|
+
if (!res.ok) {
|
|
1511
|
+
return {
|
|
1512
|
+
kind: 'result',
|
|
1513
|
+
outcome: {
|
|
1514
|
+
disposition: 'blocked',
|
|
1515
|
+
reason: 'probe_failed',
|
|
1516
|
+
detail: scrubber.scrub(`${label} failed with HTTP ${res.status}: ${res.text.slice(0, 256)}`),
|
|
1517
|
+
},
|
|
1518
|
+
};
|
|
1519
|
+
}
|
|
1520
|
+
const linkInfo = extractSameOriginNextLink(res.linkHeader, initialUrl);
|
|
1521
|
+
if (linkInfo.crossOriginError !== undefined) {
|
|
1522
|
+
return {
|
|
1523
|
+
kind: 'result',
|
|
1524
|
+
outcome: {
|
|
1525
|
+
disposition: 'blocked',
|
|
1526
|
+
reason: 'probe_failed',
|
|
1527
|
+
detail: scrubber.scrub(`${label}: ${linkInfo.crossOriginError}`),
|
|
1528
|
+
},
|
|
1529
|
+
};
|
|
1530
|
+
}
|
|
1531
|
+
try {
|
|
1532
|
+
return {
|
|
1533
|
+
kind: 'ok',
|
|
1534
|
+
data: JSON.parse(res.text),
|
|
1535
|
+
hasLinkHeader: linkInfo.hasLinkHeader,
|
|
1536
|
+
nextUrl: linkInfo.nextUrl,
|
|
1537
|
+
};
|
|
1538
|
+
}
|
|
1539
|
+
catch (error) {
|
|
1540
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
1541
|
+
return {
|
|
1542
|
+
kind: 'result',
|
|
1543
|
+
outcome: {
|
|
1544
|
+
disposition: 'blocked',
|
|
1545
|
+
reason: 'probe_invalid_json',
|
|
1546
|
+
detail: scrubber.scrub(`${label} returned invalid JSON: ${detail}`),
|
|
1547
|
+
},
|
|
1548
|
+
};
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
function extractCandidateReleaseTag(item, allowPrerelease) {
|
|
1552
|
+
if (!isPlainRecord(item) || item['draft'] === true)
|
|
1553
|
+
return undefined;
|
|
1554
|
+
if (allowPrerelease !== true && item['prerelease'] === true)
|
|
1555
|
+
return undefined;
|
|
1556
|
+
const tag = typeof item['tag_name'] === 'string' && item['tag_name'].length > 0
|
|
1557
|
+
? item['tag_name']
|
|
1558
|
+
: (typeof item['name'] === 'string' && item['name'].length > 0 ? item['name'] : undefined);
|
|
1559
|
+
if (tag === undefined)
|
|
1560
|
+
return undefined;
|
|
1561
|
+
if (allowPrerelease === false && isPrereleaseVersionTag(tag))
|
|
1562
|
+
return undefined;
|
|
1563
|
+
return tag;
|
|
1564
|
+
}
|
|
1565
|
+
async function runDefaultReadinessProbe(input, context) {
|
|
1566
|
+
const { probe, expectedVersion, repositoryRoot, scrubber } = input;
|
|
1567
|
+
const { apiBaseUrl, githubHeaders, fetchImpl, timeoutMs, allowLoopbackHttp, policyProfile } = context;
|
|
1568
|
+
const assertSafeLocalGitProbeSource = async (rawSource) => {
|
|
1569
|
+
const resolvedSource = resolve(repositoryRoot, rawSource);
|
|
1570
|
+
if (policyProfile === 'github') {
|
|
1571
|
+
const realRepo = await realpath(resolve(repositoryRoot));
|
|
1572
|
+
const realSource = await realpath(resolvedSource);
|
|
1573
|
+
if (!isContainedInRoot(realSource, realRepo)) {
|
|
1574
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `local git probe source "${rawSource}" escapes repository root under github policy profile`);
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
return resolvedSource;
|
|
1578
|
+
};
|
|
1579
|
+
try {
|
|
1580
|
+
switch (probe.kind) {
|
|
1581
|
+
case 'github-release': {
|
|
1582
|
+
const perPage = 30;
|
|
1583
|
+
const initialUrl = probe.allowPrerelease === true
|
|
1584
|
+
? `${apiBaseUrl}/repos/${probe.source}/releases?per_page=${perPage}`
|
|
1585
|
+
: `${apiBaseUrl}/repos/${probe.source}/releases/latest`;
|
|
1586
|
+
let currentUrl = initialUrl;
|
|
1587
|
+
let firstObserved;
|
|
1588
|
+
let confirmedAbsence = false;
|
|
1589
|
+
for (let page = 1; page <= MAX_PROBE_API_PAGES; page += 1) {
|
|
1590
|
+
const fetched = await fetchProbeJsonPage(`github-release "${probe.source}"`, currentUrl, initialUrl, fetchImpl, githubHeaders, timeoutMs, scrubber);
|
|
1591
|
+
if (fetched.kind === 'result')
|
|
1592
|
+
return fetched.outcome;
|
|
1593
|
+
const data = fetched.data;
|
|
1594
|
+
const pageTags = [];
|
|
1595
|
+
if (Array.isArray(data)) {
|
|
1596
|
+
for (const item of data) {
|
|
1597
|
+
const tag = extractCandidateReleaseTag(item, probe.allowPrerelease);
|
|
1598
|
+
if (tag !== undefined)
|
|
1599
|
+
pageTags.push(tag);
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
else if (isPlainRecord(data)) {
|
|
1603
|
+
const tag = extractCandidateReleaseTag(data, probe.allowPrerelease);
|
|
1604
|
+
if (tag !== undefined)
|
|
1605
|
+
pageTags.push(tag);
|
|
1606
|
+
}
|
|
1607
|
+
else {
|
|
1608
|
+
return {
|
|
1609
|
+
disposition: 'blocked',
|
|
1610
|
+
reason: 'probe_invalid_json',
|
|
1611
|
+
detail: scrubber.scrub(`github-release "${probe.source}" payload must be a JSON object or array`),
|
|
1612
|
+
};
|
|
1613
|
+
}
|
|
1614
|
+
if (firstObserved === undefined && pageTags.length > 0) {
|
|
1615
|
+
firstObserved = pageTags[0];
|
|
1616
|
+
}
|
|
1617
|
+
if (expectedVersion !== undefined) {
|
|
1618
|
+
const matched = pageTags.find(tag => versionMatchesTag(tag, expectedVersion, probe.tagPrefix));
|
|
1619
|
+
if (matched !== undefined) {
|
|
1620
|
+
return {
|
|
1621
|
+
disposition: 'eligible',
|
|
1622
|
+
observedVersion: scrubber.scrub(matched),
|
|
1623
|
+
reason: 'probe_ready',
|
|
1624
|
+
};
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
else if (pageTags.length > 0) {
|
|
1628
|
+
return {
|
|
1629
|
+
disposition: 'eligible',
|
|
1630
|
+
observedVersion: scrubber.scrub(pageTags[0]),
|
|
1631
|
+
reason: 'probe_ready',
|
|
1632
|
+
};
|
|
1633
|
+
}
|
|
1634
|
+
const hasMore = Array.isArray(data) && (fetched.nextUrl !== undefined
|
|
1635
|
+
|| (!fetched.hasLinkHeader && data.length >= perPage));
|
|
1636
|
+
if (!hasMore) {
|
|
1637
|
+
confirmedAbsence = true;
|
|
1638
|
+
break;
|
|
1639
|
+
}
|
|
1640
|
+
currentUrl = fetched.nextUrl ?? `${apiBaseUrl}/repos/${probe.source}/releases?per_page=${perPage}&page=${page + 1}`;
|
|
1641
|
+
}
|
|
1642
|
+
if (!confirmedAbsence) {
|
|
1643
|
+
return {
|
|
1644
|
+
disposition: 'blocked',
|
|
1645
|
+
...(firstObserved !== undefined ? { observedVersion: scrubber.scrub(firstObserved) } : {}),
|
|
1646
|
+
reason: 'probe_pagination_exhausted',
|
|
1647
|
+
detail: scrubber.scrub(`github-release "${probe.source}" exhausted ${MAX_PROBE_API_PAGES} pages without confirming release absence`),
|
|
1648
|
+
};
|
|
1649
|
+
}
|
|
1650
|
+
if (firstObserved === undefined) {
|
|
1651
|
+
return {
|
|
1652
|
+
disposition: 'deferred',
|
|
1653
|
+
reason: 'stage_not_ready',
|
|
1654
|
+
detail: scrubber.scrub(`github-release "${probe.source}" has no published matching release`),
|
|
1655
|
+
};
|
|
1656
|
+
}
|
|
1657
|
+
return {
|
|
1658
|
+
disposition: 'deferred',
|
|
1659
|
+
observedVersion: scrubber.scrub(firstObserved),
|
|
1660
|
+
reason: 'stage_not_ready',
|
|
1661
|
+
detail: scrubber.scrub(`github-release "${probe.source}" observed "${firstObserved}", expected "${expectedVersion ?? ''}"`),
|
|
1662
|
+
};
|
|
1663
|
+
}
|
|
1664
|
+
case 'http-json': {
|
|
1665
|
+
try {
|
|
1666
|
+
validateSuiteHttpSourceUrl(probe.source, '/readiness/source', allowLoopbackHttp);
|
|
1667
|
+
}
|
|
1668
|
+
catch (error) {
|
|
1669
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
1670
|
+
return {
|
|
1671
|
+
disposition: 'blocked',
|
|
1672
|
+
reason: 'probe_url_disallowed',
|
|
1673
|
+
detail: scrubber.scrub(detail),
|
|
1674
|
+
};
|
|
1675
|
+
}
|
|
1676
|
+
const fetched = await fetchProbeJsonPage(`http-json "${probe.source}"`, probe.source, probe.source, fetchImpl, { accept: 'application/json', 'user-agent': 'loopwright-taskpack' }, timeoutMs, scrubber);
|
|
1677
|
+
if (fetched.kind === 'result')
|
|
1678
|
+
return fetched.outcome;
|
|
1679
|
+
const data = fetched.data;
|
|
1680
|
+
let observed;
|
|
1681
|
+
if (probe.jsonPointer !== undefined) {
|
|
1682
|
+
observed = extractByRfc6901Pointer(data, probe.jsonPointer);
|
|
1683
|
+
}
|
|
1684
|
+
else if (probe.versionPath !== undefined) {
|
|
1685
|
+
observed = extractJsonVersionPath(data, probe.versionPath);
|
|
1686
|
+
}
|
|
1687
|
+
else if (isPlainRecord(data)) {
|
|
1688
|
+
for (const key of ['version', 'tag_name', 'latest', 'sha']) {
|
|
1689
|
+
const val = data[key];
|
|
1690
|
+
if (typeof val === 'string' && !/[\0\r\n]/.test(val) && val.trim().length > 0 && val.trim().length <= 256) {
|
|
1691
|
+
observed = val.trim();
|
|
1692
|
+
break;
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
}
|
|
1696
|
+
if (observed === undefined) {
|
|
1697
|
+
return {
|
|
1698
|
+
disposition: 'deferred',
|
|
1699
|
+
reason: 'stage_not_ready',
|
|
1700
|
+
detail: scrubber.scrub(`http-json "${probe.source}" did not contain an active version string`),
|
|
1701
|
+
};
|
|
1702
|
+
}
|
|
1703
|
+
if (expectedVersion !== undefined && observed !== expectedVersion) {
|
|
1704
|
+
return {
|
|
1705
|
+
disposition: 'deferred',
|
|
1706
|
+
observedVersion: scrubber.scrub(observed),
|
|
1707
|
+
reason: 'stage_not_ready',
|
|
1708
|
+
detail: scrubber.scrub(`http-json "${probe.source}" observed "${observed}", expected "${expectedVersion}"`),
|
|
1709
|
+
};
|
|
1710
|
+
}
|
|
1711
|
+
return {
|
|
1712
|
+
disposition: 'eligible',
|
|
1713
|
+
observedVersion: scrubber.scrub(observed),
|
|
1714
|
+
reason: 'probe_ready',
|
|
1715
|
+
};
|
|
1716
|
+
}
|
|
1717
|
+
case 'git-tag': {
|
|
1718
|
+
const targetTag = expectedVersion ?? probe.ref;
|
|
1719
|
+
if (REPOSITORY_FULL_NAME_PATTERN.test(probe.source)) {
|
|
1720
|
+
const perPage = 100;
|
|
1721
|
+
const initialUrl = `${apiBaseUrl}/repos/${probe.source}/tags?per_page=${perPage}`;
|
|
1722
|
+
let currentUrl = initialUrl;
|
|
1723
|
+
let confirmedAbsence = false;
|
|
1724
|
+
for (let page = 1; page <= MAX_PROBE_API_PAGES; page += 1) {
|
|
1725
|
+
const fetched = await fetchProbeJsonPage(`git-tag "${probe.source}"`, currentUrl, initialUrl, fetchImpl, githubHeaders, timeoutMs, scrubber);
|
|
1726
|
+
if (fetched.kind === 'result')
|
|
1727
|
+
return fetched.outcome;
|
|
1728
|
+
if (!Array.isArray(fetched.data)) {
|
|
1729
|
+
return {
|
|
1730
|
+
disposition: 'blocked',
|
|
1731
|
+
reason: 'probe_invalid_json',
|
|
1732
|
+
detail: scrubber.scrub(`git-tag "${probe.source}" payload must be an array`),
|
|
1733
|
+
};
|
|
1734
|
+
}
|
|
1735
|
+
let pageTags = [];
|
|
1736
|
+
for (const item of fetched.data) {
|
|
1737
|
+
if (isPlainRecord(item) && typeof item['name'] === 'string' && item['name'].length > 0) {
|
|
1738
|
+
pageTags.push(item['name']);
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
if (probe.allowPrerelease === false) {
|
|
1742
|
+
pageTags = pageTags.filter(t => !isPrereleaseVersionTag(t));
|
|
1743
|
+
}
|
|
1744
|
+
if (targetTag !== undefined) {
|
|
1745
|
+
const matched = pageTags.find(tag => versionMatchesTag(tag, targetTag, probe.tagPrefix));
|
|
1746
|
+
if (matched !== undefined) {
|
|
1747
|
+
return {
|
|
1748
|
+
disposition: 'eligible',
|
|
1749
|
+
observedVersion: scrubber.scrub(matched),
|
|
1750
|
+
reason: 'probe_ready',
|
|
1751
|
+
};
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
else if (pageTags.length > 0) {
|
|
1755
|
+
return {
|
|
1756
|
+
disposition: 'eligible',
|
|
1757
|
+
observedVersion: scrubber.scrub(pageTags[0]),
|
|
1758
|
+
reason: 'probe_ready',
|
|
1759
|
+
};
|
|
1760
|
+
}
|
|
1761
|
+
const hasMore = fetched.nextUrl !== undefined || (!fetched.hasLinkHeader && fetched.data.length >= perPage);
|
|
1762
|
+
if (!hasMore) {
|
|
1763
|
+
confirmedAbsence = true;
|
|
1764
|
+
break;
|
|
1765
|
+
}
|
|
1766
|
+
currentUrl = fetched.nextUrl ?? `${apiBaseUrl}/repos/${probe.source}/tags?per_page=${perPage}&page=${page + 1}`;
|
|
1767
|
+
}
|
|
1768
|
+
if (!confirmedAbsence) {
|
|
1769
|
+
return {
|
|
1770
|
+
disposition: 'blocked',
|
|
1771
|
+
reason: 'probe_pagination_exhausted',
|
|
1772
|
+
detail: scrubber.scrub(`git-tag "${probe.source}" exhausted ${MAX_PROBE_API_PAGES} pages without confirming tag absence`),
|
|
1773
|
+
};
|
|
1774
|
+
}
|
|
1775
|
+
return {
|
|
1776
|
+
disposition: 'deferred',
|
|
1777
|
+
reason: 'stage_not_ready',
|
|
1778
|
+
detail: scrubber.scrub(targetTag !== undefined
|
|
1779
|
+
? `git-tag "${targetTag}" is not present on "${probe.source}"`
|
|
1780
|
+
: `no git tags found on "${probe.source}"`),
|
|
1781
|
+
};
|
|
1782
|
+
}
|
|
1783
|
+
const sourceKind = validateGitRemoteSource(probe.source, repositoryRoot);
|
|
1784
|
+
const gitSource = sourceKind === 'local-dir'
|
|
1785
|
+
? await assertSafeLocalGitProbeSource(probe.source)
|
|
1786
|
+
: probe.source;
|
|
1787
|
+
const gitBin = resolveGitExecutable();
|
|
1788
|
+
const protocolArgs = sourceKind === 'local-dir'
|
|
1789
|
+
? ['-c', 'protocol.file.allow=always', '-c', 'protocol.ext.allow=never', '-c', 'protocol.ssh.allow=never']
|
|
1790
|
+
: ['-c', 'protocol.ext.allow=never', '-c', 'protocol.ssh.allow=never'];
|
|
1791
|
+
const { stdout } = await execFileAsync(gitBin, [...protocolArgs, 'ls-remote', '--tags', '--refs', '--', gitSource], { env: buildCleanGitEnv(), timeout: timeoutMs, maxBuffer: MAX_SUITE_STAGE_VERSION_BLOB_BYTES, encoding: 'utf8' });
|
|
1792
|
+
let tags = stdout
|
|
1793
|
+
.split(/\r?\n/)
|
|
1794
|
+
.map(line => line.trim())
|
|
1795
|
+
.filter(Boolean)
|
|
1796
|
+
.map(line => {
|
|
1797
|
+
const tab = line.indexOf('\t');
|
|
1798
|
+
return (tab >= 0 ? line.slice(tab + 1) : line).replace(/^refs\/tags\//, '');
|
|
1799
|
+
})
|
|
1800
|
+
.filter(Boolean);
|
|
1801
|
+
if (probe.allowPrerelease === false) {
|
|
1802
|
+
tags = tags.filter(t => !isPrereleaseVersionTag(t));
|
|
1803
|
+
}
|
|
1804
|
+
if (targetTag !== undefined) {
|
|
1805
|
+
const matched = tags.find(tag => versionMatchesTag(tag, targetTag, probe.tagPrefix));
|
|
1806
|
+
if (matched === undefined) {
|
|
1807
|
+
return {
|
|
1808
|
+
disposition: 'deferred',
|
|
1809
|
+
reason: 'stage_not_ready',
|
|
1810
|
+
detail: scrubber.scrub(`git-tag "${targetTag}" is not present on "${probe.source}"`),
|
|
1811
|
+
};
|
|
1812
|
+
}
|
|
1813
|
+
return {
|
|
1814
|
+
disposition: 'eligible',
|
|
1815
|
+
observedVersion: scrubber.scrub(matched),
|
|
1816
|
+
reason: 'probe_ready',
|
|
1817
|
+
};
|
|
1818
|
+
}
|
|
1819
|
+
if (tags.length === 0) {
|
|
1820
|
+
return {
|
|
1821
|
+
disposition: 'deferred',
|
|
1822
|
+
reason: 'stage_not_ready',
|
|
1823
|
+
detail: scrubber.scrub(`no git tags found on "${probe.source}"`),
|
|
1824
|
+
};
|
|
1825
|
+
}
|
|
1826
|
+
return {
|
|
1827
|
+
disposition: 'eligible',
|
|
1828
|
+
observedVersion: scrubber.scrub(tags[0]),
|
|
1829
|
+
reason: 'probe_ready',
|
|
1830
|
+
};
|
|
1831
|
+
}
|
|
1832
|
+
case 'git-commit': {
|
|
1833
|
+
if (REPOSITORY_FULL_NAME_PATTERN.test(probe.source)) {
|
|
1834
|
+
if (probe.ref !== undefined && expectedVersion !== undefined) {
|
|
1835
|
+
const compareUrl = `${apiBaseUrl}/repos/${probe.source}/compare/${encodeURIComponent(expectedVersion)}...${encodeURIComponent(probe.ref)}`;
|
|
1836
|
+
const fetched = await fetchProbeJsonPage(`git-commit "${probe.source}"`, compareUrl, compareUrl, fetchImpl, githubHeaders, timeoutMs, scrubber);
|
|
1837
|
+
if (fetched.kind === 'result')
|
|
1838
|
+
return fetched.outcome;
|
|
1839
|
+
if (!isPlainRecord(fetched.data) || typeof fetched.data['status'] !== 'string') {
|
|
1840
|
+
return {
|
|
1841
|
+
disposition: 'blocked',
|
|
1842
|
+
reason: 'probe_invalid_json',
|
|
1843
|
+
detail: scrubber.scrub(`git-commit compare "${probe.source}" payload lacked status string`),
|
|
1844
|
+
};
|
|
1845
|
+
}
|
|
1846
|
+
const cmpStatus = fetched.data['status'];
|
|
1847
|
+
const mergeBase = isPlainRecord(fetched.data['merge_base_commit']) && typeof fetched.data['merge_base_commit']['sha'] === 'string'
|
|
1848
|
+
? fetched.data['merge_base_commit']['sha']
|
|
1849
|
+
: undefined;
|
|
1850
|
+
if (cmpStatus === 'ahead' || cmpStatus === 'identical') {
|
|
1851
|
+
return {
|
|
1852
|
+
disposition: 'eligible',
|
|
1853
|
+
observedVersion: scrubber.scrub(mergeBase ?? expectedVersion),
|
|
1854
|
+
reason: 'probe_ready',
|
|
1855
|
+
};
|
|
1856
|
+
}
|
|
1857
|
+
if (cmpStatus === 'behind' || cmpStatus === 'diverged') {
|
|
1858
|
+
return {
|
|
1859
|
+
disposition: 'deferred',
|
|
1860
|
+
...(mergeBase !== undefined ? { observedVersion: scrubber.scrub(mergeBase) } : {}),
|
|
1861
|
+
reason: 'stage_not_ready',
|
|
1862
|
+
detail: scrubber.scrub(`git-commit "${expectedVersion}" is not an ancestor of "${probe.ref}" on "${probe.source}" (status=${cmpStatus})`),
|
|
1863
|
+
};
|
|
1864
|
+
}
|
|
1865
|
+
return {
|
|
1866
|
+
disposition: 'blocked',
|
|
1867
|
+
reason: 'probe_invalid_json',
|
|
1868
|
+
detail: scrubber.scrub(`git-commit compare "${probe.source}" returned unexpected status "${cmpStatus}"`),
|
|
1869
|
+
};
|
|
1870
|
+
}
|
|
1871
|
+
const url = probe.ref !== undefined
|
|
1872
|
+
? `${apiBaseUrl}/repos/${probe.source}/commits?sha=${encodeURIComponent(probe.ref)}&per_page=1`
|
|
1873
|
+
: expectedVersion !== undefined
|
|
1874
|
+
? `${apiBaseUrl}/repos/${probe.source}/commits/${encodeURIComponent(expectedVersion)}`
|
|
1875
|
+
: `${apiBaseUrl}/repos/${probe.source}/commits?per_page=1`;
|
|
1876
|
+
const fetched = await fetchProbeJsonPage(`git-commit "${probe.source}"`, url, url, fetchImpl, githubHeaders, timeoutMs, scrubber);
|
|
1877
|
+
if (fetched.kind === 'result')
|
|
1878
|
+
return fetched.outcome;
|
|
1879
|
+
let sha;
|
|
1880
|
+
if (Array.isArray(fetched.data)) {
|
|
1881
|
+
if (fetched.data.length === 0) {
|
|
1882
|
+
return {
|
|
1883
|
+
disposition: 'deferred',
|
|
1884
|
+
reason: 'stage_not_ready',
|
|
1885
|
+
detail: scrubber.scrub(`git-commit returned empty commit list for "${probe.source}"`),
|
|
1886
|
+
};
|
|
1887
|
+
}
|
|
1888
|
+
if (isPlainRecord(fetched.data[0]) && typeof fetched.data[0]['sha'] === 'string') {
|
|
1889
|
+
sha = fetched.data[0]['sha'];
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1892
|
+
else if (isPlainRecord(fetched.data) && typeof fetched.data['sha'] === 'string') {
|
|
1893
|
+
sha = fetched.data['sha'];
|
|
1894
|
+
}
|
|
1895
|
+
if (sha === undefined || sha.length === 0) {
|
|
1896
|
+
return {
|
|
1897
|
+
disposition: 'blocked',
|
|
1898
|
+
reason: 'probe_invalid_json',
|
|
1899
|
+
detail: scrubber.scrub(`git-commit "${probe.source}" payload lacked commit sha`),
|
|
1900
|
+
};
|
|
1901
|
+
}
|
|
1902
|
+
if (expectedVersion !== undefined && sha.toLowerCase() !== expectedVersion.toLowerCase()) {
|
|
1903
|
+
return {
|
|
1904
|
+
disposition: 'deferred',
|
|
1905
|
+
observedVersion: scrubber.scrub(sha),
|
|
1906
|
+
reason: 'stage_not_ready',
|
|
1907
|
+
detail: scrubber.scrub(`git-commit observed "${sha}", expected "${expectedVersion}"`),
|
|
1908
|
+
};
|
|
1909
|
+
}
|
|
1910
|
+
return {
|
|
1911
|
+
disposition: 'eligible',
|
|
1912
|
+
observedVersion: scrubber.scrub(sha),
|
|
1913
|
+
reason: 'probe_ready',
|
|
1914
|
+
};
|
|
1915
|
+
}
|
|
1916
|
+
const sourceKind = validateGitRemoteSource(probe.source, repositoryRoot);
|
|
1917
|
+
const gitSource = sourceKind === 'local-dir'
|
|
1918
|
+
? await assertSafeLocalGitProbeSource(probe.source)
|
|
1919
|
+
: probe.source;
|
|
1920
|
+
const gitBin = resolveGitExecutable();
|
|
1921
|
+
const cleanEnv = buildCleanGitEnv();
|
|
1922
|
+
if (sourceKind === 'local-dir' && expectedVersion !== undefined && COMMIT_SHA_PATTERN.test(expectedVersion)) {
|
|
1923
|
+
// Verify gitSource is a valid Git repository first (otherwise fail closed as blocked).
|
|
1924
|
+
await execFileAsync(gitBin, ['-C', gitSource, 'rev-parse', '--git-dir'], { env: cleanEnv, timeout: timeoutMs, maxBuffer: 4_096, encoding: 'utf8' });
|
|
1925
|
+
const isGitProcessFailure = (error) => {
|
|
1926
|
+
if (error === null || typeof error !== 'object')
|
|
1927
|
+
return true;
|
|
1928
|
+
const err = error;
|
|
1929
|
+
return err.killed === true || (err.signal !== null && err.signal !== undefined) || typeof err.code !== 'number';
|
|
1930
|
+
};
|
|
1931
|
+
const targetRef = probe.ref ?? 'HEAD';
|
|
1932
|
+
let refExists = false;
|
|
1933
|
+
if (COMMIT_SHA_PATTERN.test(targetRef)) {
|
|
1934
|
+
try {
|
|
1935
|
+
await execFileAsync(gitBin, ['-C', gitSource, 'cat-file', '-e', targetRef], { env: cleanEnv, timeout: timeoutMs, maxBuffer: 4_096, encoding: 'utf8' });
|
|
1936
|
+
const { stdout: targetTypeOut } = await execFileAsync(gitBin, ['-C', gitSource, 'cat-file', '-t', targetRef], { env: cleanEnv, timeout: timeoutMs, maxBuffer: 4_096, encoding: 'utf8' });
|
|
1937
|
+
refExists = targetTypeOut.trim() === 'commit';
|
|
1938
|
+
}
|
|
1939
|
+
catch (error) {
|
|
1940
|
+
const exitCode = error.code;
|
|
1941
|
+
const stderrText = typeof error.stderr === 'string'
|
|
1942
|
+
? error.stderr
|
|
1943
|
+
: '';
|
|
1944
|
+
if (isGitProcessFailure(error) || exitCode !== 1 || /corrupt|bad object|unable to read/i.test(stderrText)) {
|
|
1945
|
+
throw error;
|
|
1946
|
+
}
|
|
1947
|
+
refExists = false;
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
else if (/[~^@:]/.test(targetRef)) {
|
|
1951
|
+
try {
|
|
1952
|
+
await execFileAsync(gitBin, ['-C', gitSource, 'rev-parse', '--verify', '--quiet', '--end-of-options', `${targetRef}^{commit}`], { env: cleanEnv, timeout: timeoutMs, maxBuffer: 4_096, encoding: 'utf8' });
|
|
1953
|
+
refExists = true;
|
|
1954
|
+
}
|
|
1955
|
+
catch (error) {
|
|
1956
|
+
const exitCode = error.code;
|
|
1957
|
+
const stderrText = typeof error.stderr === 'string'
|
|
1958
|
+
? error.stderr
|
|
1959
|
+
: '';
|
|
1960
|
+
if (isGitProcessFailure(error) || (exitCode !== 1 && exitCode !== 128) || /corrupt|bad object|unable to read/i.test(stderrText)) {
|
|
1961
|
+
throw error;
|
|
1962
|
+
}
|
|
1963
|
+
refExists = false;
|
|
1964
|
+
}
|
|
1965
|
+
}
|
|
1966
|
+
else {
|
|
1967
|
+
const candidateRefs = [];
|
|
1968
|
+
if (targetRef === 'HEAD') {
|
|
1969
|
+
try {
|
|
1970
|
+
const sym = await execFileAsync(gitBin, ['-C', gitSource, 'symbolic-ref', '--quiet', 'HEAD'], { env: cleanEnv, timeout: timeoutMs, maxBuffer: 4_096, encoding: 'utf8' });
|
|
1971
|
+
const symRef = sym.stdout.trim();
|
|
1972
|
+
if (symRef.length > 0)
|
|
1973
|
+
candidateRefs.push(symRef);
|
|
1974
|
+
}
|
|
1975
|
+
catch (error) {
|
|
1976
|
+
if (isGitProcessFailure(error) || error.code !== 1)
|
|
1977
|
+
throw error;
|
|
1978
|
+
// Detached HEAD: check `git rev-parse --verify HEAD` directly below.
|
|
1979
|
+
refExists = true;
|
|
1980
|
+
}
|
|
1981
|
+
}
|
|
1982
|
+
else if (targetRef.startsWith('refs/')) {
|
|
1983
|
+
candidateRefs.push(targetRef);
|
|
1984
|
+
}
|
|
1985
|
+
else {
|
|
1986
|
+
candidateRefs.push(`refs/heads/${targetRef}`, `refs/tags/${targetRef}`, `refs/remotes/${targetRef}`);
|
|
1987
|
+
}
|
|
1988
|
+
if (!refExists) {
|
|
1989
|
+
for (const fullRef of candidateRefs) {
|
|
1990
|
+
try {
|
|
1991
|
+
await execFileAsync(gitBin, ['-C', gitSource, 'show-ref', '--verify', '--quiet', '--', fullRef], { env: cleanEnv, timeout: timeoutMs, maxBuffer: 4_096, encoding: 'utf8' });
|
|
1992
|
+
refExists = true;
|
|
1993
|
+
break;
|
|
1994
|
+
}
|
|
1995
|
+
catch (error) {
|
|
1996
|
+
if (isGitProcessFailure(error) || error.code !== 1)
|
|
1997
|
+
throw error;
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
if (!refExists) {
|
|
2003
|
+
return {
|
|
2004
|
+
disposition: 'deferred',
|
|
2005
|
+
reason: 'stage_not_ready',
|
|
2006
|
+
detail: scrubber.scrub(`git ref "${targetRef}" is not yet available in "${probe.source}"`),
|
|
2007
|
+
};
|
|
2008
|
+
}
|
|
2009
|
+
const { stdout: refShaOut } = await execFileAsync(gitBin, ['-C', gitSource, 'rev-parse', '--verify', '--end-of-options', `${targetRef}^{commit}`], { env: cleanEnv, timeout: timeoutMs, maxBuffer: 4_096, encoding: 'utf8' });
|
|
2010
|
+
const refSha = refShaOut.trim().toLowerCase();
|
|
2011
|
+
let commitExists = true;
|
|
2012
|
+
try {
|
|
2013
|
+
await execFileAsync(gitBin, ['-C', gitSource, 'cat-file', '-e', expectedVersion], { env: cleanEnv, timeout: timeoutMs, maxBuffer: 4_096, encoding: 'utf8' });
|
|
2014
|
+
}
|
|
2015
|
+
catch (error) {
|
|
2016
|
+
const exitCode = error.code;
|
|
2017
|
+
const stderrText = typeof error.stderr === 'string'
|
|
2018
|
+
? error.stderr
|
|
2019
|
+
: '';
|
|
2020
|
+
if (isGitProcessFailure(error) || exitCode !== 1 || /corrupt|bad object|unable to read/i.test(stderrText)) {
|
|
2021
|
+
throw error;
|
|
2022
|
+
}
|
|
2023
|
+
commitExists = false;
|
|
2024
|
+
}
|
|
2025
|
+
if (!commitExists) {
|
|
2026
|
+
return {
|
|
2027
|
+
disposition: 'deferred',
|
|
2028
|
+
observedVersion: scrubber.scrub(refSha),
|
|
2029
|
+
reason: 'stage_not_ready',
|
|
2030
|
+
detail: scrubber.scrub(`commit "${expectedVersion}" is absent from "${probe.source}"`),
|
|
2031
|
+
};
|
|
2032
|
+
}
|
|
2033
|
+
const { stdout: objTypeOut } = await execFileAsync(gitBin, ['-C', gitSource, 'cat-file', '-t', expectedVersion], { env: cleanEnv, timeout: timeoutMs, maxBuffer: 4_096, encoding: 'utf8' });
|
|
2034
|
+
if (objTypeOut.trim() !== 'commit') {
|
|
2035
|
+
return {
|
|
2036
|
+
disposition: 'deferred',
|
|
2037
|
+
observedVersion: scrubber.scrub(refSha),
|
|
2038
|
+
reason: 'stage_not_ready',
|
|
2039
|
+
detail: scrubber.scrub(`object "${expectedVersion}" in "${probe.source}" is not a commit`),
|
|
2040
|
+
};
|
|
2041
|
+
}
|
|
2042
|
+
let isAncestor = true;
|
|
2043
|
+
try {
|
|
2044
|
+
await execFileAsync(gitBin, ['-C', gitSource, 'merge-base', '--is-ancestor', expectedVersion, refSha], { env: cleanEnv, timeout: timeoutMs, maxBuffer: 4_096, encoding: 'utf8' });
|
|
2045
|
+
}
|
|
2046
|
+
catch (error) {
|
|
2047
|
+
if (isGitProcessFailure(error) || error.code !== 1)
|
|
2048
|
+
throw error;
|
|
2049
|
+
isAncestor = false;
|
|
2050
|
+
}
|
|
2051
|
+
if (!isAncestor) {
|
|
2052
|
+
return {
|
|
2053
|
+
disposition: 'deferred',
|
|
2054
|
+
observedVersion: scrubber.scrub(refSha),
|
|
2055
|
+
reason: 'stage_not_ready',
|
|
2056
|
+
detail: scrubber.scrub(`commit "${expectedVersion}" is not an ancestor of "${targetRef}" in "${probe.source}"`),
|
|
2057
|
+
};
|
|
2058
|
+
}
|
|
2059
|
+
return {
|
|
2060
|
+
disposition: 'eligible',
|
|
2061
|
+
observedVersion: scrubber.scrub(expectedVersion.toLowerCase()),
|
|
2062
|
+
reason: 'probe_ready',
|
|
2063
|
+
};
|
|
2064
|
+
}
|
|
2065
|
+
// Raw `git ls-remote` fallback (generic HTTPS Git URLs or non-hex expectedVersion where full commit-graph ancestry is unavailable: exact advertised ref SHA match)
|
|
2066
|
+
const protocolArgs = sourceKind === 'local-dir'
|
|
2067
|
+
? ['-c', 'protocol.file.allow=always', '-c', 'protocol.ext.allow=never', '-c', 'protocol.ssh.allow=never']
|
|
2068
|
+
: ['-c', 'protocol.ext.allow=never', '-c', 'protocol.ssh.allow=never'];
|
|
2069
|
+
const queryRefs = probe.ref !== undefined ? [probe.ref] : ['HEAD', 'refs/heads/main', 'refs/heads/master'];
|
|
2070
|
+
const { stdout } = await execFileAsync(gitBin, [...protocolArgs, 'ls-remote', '--', gitSource, ...queryRefs], { env: cleanEnv, timeout: timeoutMs, maxBuffer: MAX_SUITE_STAGE_VERSION_BLOB_BYTES, encoding: 'utf8' });
|
|
2071
|
+
const shas = [];
|
|
2072
|
+
for (const rawLine of stdout.split(/\r?\n/)) {
|
|
2073
|
+
const trimmed = rawLine.trim();
|
|
2074
|
+
if (!trimmed)
|
|
2075
|
+
continue;
|
|
2076
|
+
const parts = trimmed.split(/\s+/);
|
|
2077
|
+
if (parts[0])
|
|
2078
|
+
shas.push(parts[0]);
|
|
2079
|
+
}
|
|
2080
|
+
if (shas.length === 0) {
|
|
2081
|
+
return {
|
|
2082
|
+
disposition: 'deferred',
|
|
2083
|
+
reason: 'stage_not_ready',
|
|
2084
|
+
detail: scrubber.scrub(`git-commit found no matching refs on "${probe.source}"`),
|
|
2085
|
+
};
|
|
2086
|
+
}
|
|
2087
|
+
if (expectedVersion !== undefined) {
|
|
2088
|
+
const matched = shas.find(s => s.toLowerCase() === expectedVersion.toLowerCase());
|
|
2089
|
+
if (matched === undefined) {
|
|
2090
|
+
return {
|
|
2091
|
+
disposition: 'deferred',
|
|
2092
|
+
observedVersion: scrubber.scrub(shas[0]),
|
|
2093
|
+
reason: 'stage_not_ready',
|
|
2094
|
+
detail: scrubber.scrub(`git-commit observed "${shas[0]}", expected "${expectedVersion}"`),
|
|
2095
|
+
};
|
|
2096
|
+
}
|
|
2097
|
+
return {
|
|
2098
|
+
disposition: 'eligible',
|
|
2099
|
+
observedVersion: scrubber.scrub(matched),
|
|
2100
|
+
reason: 'probe_ready',
|
|
2101
|
+
};
|
|
2102
|
+
}
|
|
2103
|
+
return {
|
|
2104
|
+
disposition: 'eligible',
|
|
2105
|
+
observedVersion: scrubber.scrub(shas[0]),
|
|
2106
|
+
reason: 'probe_ready',
|
|
2107
|
+
};
|
|
2108
|
+
}
|
|
2109
|
+
}
|
|
2110
|
+
}
|
|
2111
|
+
catch (error) {
|
|
2112
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
2113
|
+
return {
|
|
2114
|
+
disposition: 'blocked',
|
|
2115
|
+
reason: 'probe_transport_error',
|
|
2116
|
+
detail: scrubber.scrub(detail),
|
|
2117
|
+
};
|
|
2118
|
+
}
|
|
2119
|
+
}
|
|
2120
|
+
// ---------------------------------------------------------------------------
|
|
2121
|
+
// Pull-request comment & branch ownership routing
|
|
2122
|
+
// ---------------------------------------------------------------------------
|
|
2123
|
+
/**
|
|
2124
|
+
* Parse `/loopwright [<domainId>] retry|revise|status [guidance]` (and custom domain `commentPrefixes`).
|
|
2125
|
+
* Returns `null` when the comment body does not begin with a configured command prefix and valid command.
|
|
2126
|
+
*/
|
|
2127
|
+
export function parseSuiteCommentCommand(body, prefixes = DEFAULT_COMMENT_PREFIXES, commands = TASKPACK_COMMENT_COMMANDS, knownDomainIds) {
|
|
2128
|
+
const lines = body.split('\n');
|
|
2129
|
+
const firstLine = lines[0]?.trimEnd() ?? '';
|
|
2130
|
+
const trailingLines = lines.slice(1).join('\n');
|
|
2131
|
+
const sortedPrefixes = [...new Set(prefixes.length > 0 ? prefixes : DEFAULT_COMMENT_PREFIXES)]
|
|
2132
|
+
.sort((a, b) => b.length - a.length);
|
|
2133
|
+
const composeGuidance = (inlinePart) => {
|
|
2134
|
+
const inline = inlinePart.trim();
|
|
2135
|
+
if (inline.length > 0 && trailingLines.length > 0) {
|
|
2136
|
+
return `${inline}\n${trailingLines}`;
|
|
2137
|
+
}
|
|
2138
|
+
return inline.length > 0 ? inline : trailingLines;
|
|
2139
|
+
};
|
|
2140
|
+
for (const prefix of sortedPrefixes) {
|
|
2141
|
+
if (firstLine.trim() === prefix) {
|
|
2142
|
+
if (!commands.includes('revise'))
|
|
2143
|
+
return null;
|
|
2144
|
+
if (trailingLines.trim().length === 0)
|
|
2145
|
+
return null;
|
|
2146
|
+
return Object.freeze({ prefix, command: 'revise', guidance: trailingLines });
|
|
2147
|
+
}
|
|
2148
|
+
if (!firstLine.startsWith(`${prefix} `))
|
|
2149
|
+
continue;
|
|
2150
|
+
const afterPrefix = firstLine.slice(prefix.length).trim();
|
|
2151
|
+
if (afterPrefix.length === 0)
|
|
2152
|
+
continue;
|
|
2153
|
+
const firstTokenMatch = /^(\S+)(?:\s+(.*))?$/.exec(afterPrefix);
|
|
2154
|
+
if (firstTokenMatch === null)
|
|
2155
|
+
continue;
|
|
2156
|
+
const tok0 = firstTokenMatch[1];
|
|
2157
|
+
const afterTok0 = firstTokenMatch[2] ?? '';
|
|
2158
|
+
const secondTokenMatch = /^(\S+)(?:\s+(.*))?$/.exec(afterTok0.trim());
|
|
2159
|
+
const tok1 = secondTokenMatch?.[1];
|
|
2160
|
+
const afterTok1 = secondTokenMatch?.[2] ?? '';
|
|
2161
|
+
// `<prefix> <domainId> <command> [guidance]` takes precedence only when tok0 is a known domain ID or NOT itself a command keyword
|
|
2162
|
+
const tok0IsCommand = commands.includes(tok0);
|
|
2163
|
+
const tok0CanBeDomain = knownDomainIds !== undefined
|
|
2164
|
+
? (knownDomainIds.has(tok0) || !tok0IsCommand)
|
|
2165
|
+
: !tok0IsCommand;
|
|
2166
|
+
if (tok1 !== undefined && commands.includes(tok1) && tok0CanBeDomain) {
|
|
2167
|
+
return Object.freeze({
|
|
2168
|
+
prefix,
|
|
2169
|
+
domainId: tok0,
|
|
2170
|
+
command: tok1,
|
|
2171
|
+
guidance: composeGuidance(afterTok1),
|
|
2172
|
+
});
|
|
2173
|
+
}
|
|
2174
|
+
// Untargeted `<prefix> <command> [guidance]`
|
|
2175
|
+
if (commands.includes(tok0)) {
|
|
2176
|
+
return Object.freeze({
|
|
2177
|
+
prefix,
|
|
2178
|
+
command: tok0,
|
|
2179
|
+
guidance: composeGuidance(afterTok0),
|
|
2180
|
+
});
|
|
2181
|
+
}
|
|
2182
|
+
// `<prefix> <knownDomainId>` followed by multiline guidance -> revise
|
|
2183
|
+
if (tok1 === undefined
|
|
2184
|
+
&& knownDomainIds?.has(tok0) === true
|
|
2185
|
+
&& commands.includes('revise')
|
|
2186
|
+
&& trailingLines.trim().length > 0) {
|
|
2187
|
+
return Object.freeze({
|
|
2188
|
+
prefix,
|
|
2189
|
+
domainId: tok0,
|
|
2190
|
+
command: 'revise',
|
|
2191
|
+
guidance: trailingLines,
|
|
2192
|
+
});
|
|
2193
|
+
}
|
|
2194
|
+
}
|
|
2195
|
+
return null;
|
|
2196
|
+
}
|
|
2197
|
+
/** Match `(prBaseRef, prHeadRef)` against suite domains declaring `publication.mode === 'pull_request'`. */
|
|
2198
|
+
export function matchSuitePullRequestDomain(domains, prHeadRef, prBaseRef) {
|
|
2199
|
+
const candidates = [];
|
|
2200
|
+
for (const domain of domains) {
|
|
2201
|
+
const pub = domain.manifest.spec.publication;
|
|
2202
|
+
if (pub.mode !== 'pull_request')
|
|
2203
|
+
continue;
|
|
2204
|
+
if (prBaseRef !== undefined && pub.targetBranch !== prBaseRef)
|
|
2205
|
+
continue;
|
|
2206
|
+
if (prHeadRef.startsWith(pub.headBranchPrefix)
|
|
2207
|
+
&& (pub.headBranchPrefix.startsWith(MEMORY_PULL_REQUEST_BRANCH_PREFIX) || !prHeadRef.startsWith(MEMORY_PULL_REQUEST_BRANCH_PREFIX))) {
|
|
2208
|
+
candidates.push(domain);
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
if (candidates.length === 1) {
|
|
2212
|
+
return { matched: candidates[0], ambiguous: false };
|
|
2213
|
+
}
|
|
2214
|
+
if (candidates.length > 1 && prBaseRef === undefined) {
|
|
2215
|
+
const exactBranchMatches = candidates.filter(d => {
|
|
2216
|
+
const pub = d.manifest.spec.publication;
|
|
2217
|
+
return pub.mode === 'pull_request' && prHeadRef === `${pub.headBranchPrefix}${pub.targetBranch}`;
|
|
2218
|
+
});
|
|
2219
|
+
if (exactBranchMatches.length === 1) {
|
|
2220
|
+
return { matched: exactBranchMatches[0], ambiguous: false };
|
|
2221
|
+
}
|
|
2222
|
+
return { matched: null, ambiguous: true };
|
|
2223
|
+
}
|
|
2224
|
+
return { matched: null, ambiguous: candidates.length > 1 };
|
|
2225
|
+
}
|
|
2226
|
+
function toMatrixCell(domain, baseRevision, headSha) {
|
|
2227
|
+
return Object.freeze({
|
|
2228
|
+
domainId: domain.id,
|
|
2229
|
+
taskpackPath: domain.taskpackPath,
|
|
2230
|
+
taskpackName: domain.taskpackName,
|
|
2231
|
+
manifestSha256: domain.manifestSha256,
|
|
2232
|
+
controlRoot: domain.controlRoot,
|
|
2233
|
+
baseRevision,
|
|
2234
|
+
...(headSha !== undefined ? { headSha } : {}),
|
|
2235
|
+
...(domain.stage !== undefined ? { stage: domain.stage } : {}),
|
|
2236
|
+
...(domain.matrix !== undefined ? { matrix: domain.matrix } : {}),
|
|
2237
|
+
protectedPaths: domain.protectedPaths,
|
|
2238
|
+
});
|
|
2239
|
+
}
|
|
2240
|
+
async function resolveSuiteBaseRevision(repositoryRoot, rawBaseRevision, timeoutMs, remoteBaseRevision) {
|
|
2241
|
+
const candidate = rawBaseRevision?.trim() || 'HEAD';
|
|
2242
|
+
if (remoteBaseRevision === true && COMMIT_SHA_PATTERN.test(candidate)) {
|
|
2243
|
+
return candidate.toLowerCase();
|
|
2244
|
+
}
|
|
2245
|
+
if (existsSync(join(resolve(repositoryRoot), '.git'))) {
|
|
2246
|
+
return resolveGitCommitSha(repositoryRoot, candidate, timeoutMs);
|
|
2247
|
+
}
|
|
2248
|
+
if (COMMIT_SHA_PATTERN.test(candidate)) {
|
|
2249
|
+
return candidate.toLowerCase();
|
|
2250
|
+
}
|
|
2251
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `cannot resolve git revision "${candidate}" without a .git repository`);
|
|
2252
|
+
}
|
|
2253
|
+
function extractCommentMetadataFromPayload(payload) {
|
|
2254
|
+
if (!isPlainRecord(payload))
|
|
2255
|
+
return {};
|
|
2256
|
+
const action = typeof payload['action'] === 'string' ? payload['action'] : undefined;
|
|
2257
|
+
const commentObj = isPlainRecord(payload['comment'])
|
|
2258
|
+
? payload['comment']
|
|
2259
|
+
: (isPlainRecord(payload['review']) ? payload['review'] : undefined);
|
|
2260
|
+
const userObj = commentObj !== undefined && isPlainRecord(commentObj['user']) ? commentObj['user'] : undefined;
|
|
2261
|
+
const login = typeof userObj?.['login'] === 'string' ? userObj['login'] : undefined;
|
|
2262
|
+
const userType = typeof userObj?.['type'] === 'string' ? userObj['type'] : undefined;
|
|
2263
|
+
const isBot = userType === 'Bot' || (login !== undefined && login.toLowerCase().endsWith('[bot]'));
|
|
2264
|
+
const commentBody = typeof commentObj?.['body'] === 'string' ? commentObj['body'] : undefined;
|
|
2265
|
+
const authorAssociation = typeof commentObj?.['author_association'] === 'string' ? commentObj['author_association'] : undefined;
|
|
2266
|
+
const prObj = isPlainRecord(payload['pull_request']) ? payload['pull_request'] : undefined;
|
|
2267
|
+
const issueObj = isPlainRecord(payload['issue']) ? payload['issue'] : undefined;
|
|
2268
|
+
const isPlainIssueComment = issueObj !== undefined && !isPlainRecord(issueObj['pull_request']) && prObj === undefined;
|
|
2269
|
+
const headObj = prObj !== undefined && isPlainRecord(prObj['head']) ? prObj['head'] : undefined;
|
|
2270
|
+
const baseObj = prObj !== undefined && isPlainRecord(prObj['base']) ? prObj['base'] : undefined;
|
|
2271
|
+
const headRepo = headObj !== undefined && isPlainRecord(headObj['repo']) ? headObj['repo'] : undefined;
|
|
2272
|
+
const baseRepo = baseObj !== undefined && isPlainRecord(baseObj['repo']) ? baseObj['repo'] : undefined;
|
|
2273
|
+
const prHeadRepoNull = headObj !== undefined && headObj['repo'] === null;
|
|
2274
|
+
let prHeadRepoFork;
|
|
2275
|
+
if (typeof headRepo?.['fork'] === 'boolean') {
|
|
2276
|
+
const sameForkRepo = baseRepo !== undefined
|
|
2277
|
+
&& baseRepo['fork'] === true
|
|
2278
|
+
&& typeof headRepo['id'] === 'number'
|
|
2279
|
+
&& headRepo['id'] === baseRepo['id'];
|
|
2280
|
+
prHeadRepoFork = sameForkRepo ? false : headRepo['fork'];
|
|
2281
|
+
}
|
|
2282
|
+
let prNumber;
|
|
2283
|
+
if (typeof prObj?.['number'] === 'number' && Number.isSafeInteger(prObj['number']) && prObj['number'] > 0) {
|
|
2284
|
+
prNumber = prObj['number'];
|
|
2285
|
+
}
|
|
2286
|
+
else if (issueObj !== undefined && isPlainRecord(issueObj['pull_request'])) {
|
|
2287
|
+
const num = issueObj['number'];
|
|
2288
|
+
if (typeof num === 'number' && Number.isSafeInteger(num) && num > 0)
|
|
2289
|
+
prNumber = num;
|
|
2290
|
+
}
|
|
2291
|
+
return {
|
|
2292
|
+
...(action !== undefined ? { action } : {}),
|
|
2293
|
+
...(isPlainIssueComment ? { isPlainIssueComment: true } : {}),
|
|
2294
|
+
...(prObj !== undefined ? { hasPullRequestPayload: true } : {}),
|
|
2295
|
+
...(commentBody !== undefined ? { commentBody } : {}),
|
|
2296
|
+
...(typeof headObj?.['ref'] === 'string' ? { prHeadRef: headObj['ref'] } : {}),
|
|
2297
|
+
...(typeof baseObj?.['ref'] === 'string' ? { prBaseRef: baseObj['ref'] } : {}),
|
|
2298
|
+
...(typeof headObj?.['sha'] === 'string' ? { prHeadSha: headObj['sha'] } : {}),
|
|
2299
|
+
...(typeof headRepo?.['full_name'] === 'string' ? { prHeadRepoFullName: headRepo['full_name'] } : {}),
|
|
2300
|
+
...(prHeadRepoFork !== undefined ? { prHeadRepoFork } : {}),
|
|
2301
|
+
...(prHeadRepoNull ? { prHeadRepoNull: true } : {}),
|
|
2302
|
+
...(prNumber !== undefined ? { prNumber } : {}),
|
|
2303
|
+
...(login !== undefined ? { actorLogin: login } : {}),
|
|
2304
|
+
...(authorAssociation !== undefined ? { authorAssociation } : {}),
|
|
2305
|
+
...(isBot ? { isBot: true } : {}),
|
|
2306
|
+
};
|
|
2307
|
+
}
|
|
2308
|
+
/**
|
|
2309
|
+
* Statelessly resolve eligible, deferred, or blocked domain cells for `schedule`, `workflow_dispatch`,
|
|
2310
|
+
* PR comment (`issue_comment` / `pull_request_review` / `pull_request_review_comment`), or direct `domain`
|
|
2311
|
+
* revalidation without writing any suite state ledger file.
|
|
2312
|
+
*/
|
|
2313
|
+
export async function resolveTaskpackSuite(options) {
|
|
2314
|
+
const scrubber = options.scrubber ?? new SecretScrubber();
|
|
2315
|
+
const runtimeEnv = options.env ?? process.env;
|
|
2316
|
+
for (const envKey of ['GITHUB_TOKEN', 'GH_TOKEN', 'INPUT_GITHUB-TOKEN']) {
|
|
2317
|
+
const val = runtimeEnv[envKey]?.trim();
|
|
2318
|
+
if (val !== undefined && val.length > 0)
|
|
2319
|
+
scrubber.register(val);
|
|
2320
|
+
}
|
|
2321
|
+
const fallbackEnvToken = (runtimeEnv['GITHUB_TOKEN']?.trim()
|
|
2322
|
+
|| runtimeEnv['GH_TOKEN']?.trim()
|
|
2323
|
+
|| runtimeEnv['INPUT_GITHUB-TOKEN']?.trim()
|
|
2324
|
+
|| undefined);
|
|
2325
|
+
const effectiveGithubToken = options.githubToken ?? fallbackEnvToken;
|
|
2326
|
+
const rawRepoFullName = options.repositoryFullName?.trim() || runtimeEnv['GITHUB_REPOSITORY']?.trim();
|
|
2327
|
+
const effectiveRepoFullName = rawRepoFullName !== undefined && rawRepoFullName.length > 0 ? rawRepoFullName : undefined;
|
|
2328
|
+
const timeoutMs = options.timeoutMs ?? 15_000;
|
|
2329
|
+
const apiBaseUrl = (options.apiBaseUrl?.trim() || runtimeEnv['GITHUB_API_URL']?.trim() || 'https://api.github.com').replace(/\/+$/, '');
|
|
2330
|
+
const fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
2331
|
+
const githubHeaders = await buildProbeAuthHeaders(effectiveGithubToken, options.authHeaders, { accept: 'application/vnd.github+json', 'user-agent': 'loopwright-taskpack' }, scrubber);
|
|
2332
|
+
const effectivePolicyProfile = options.policyProfile ?? options.hostPolicy?.policyProfile ?? 'local';
|
|
2333
|
+
const effectiveAllowLoopbackHttp = options.allowLoopbackHttp ?? (effectivePolicyProfile === 'local');
|
|
2334
|
+
const suite = options.loadedSuite ?? await loadTaskpackSuite({
|
|
2335
|
+
...options,
|
|
2336
|
+
policyProfile: effectivePolicyProfile,
|
|
2337
|
+
allowLoopbackHttp: effectiveAllowLoopbackHttp,
|
|
2338
|
+
});
|
|
2339
|
+
const validDomainIds = Object.freeze(suite.domains.map(d => d.id));
|
|
2340
|
+
const domainById = new Map(suite.domains.map(d => [d.id, d]));
|
|
2341
|
+
const stageById = new Map(suite.manifest.spec.stages.map(s => [s.id, s]));
|
|
2342
|
+
const inferredEventName = options.eventName
|
|
2343
|
+
?? (options.commentBody !== undefined ? 'issue_comment' : (options.schedule !== undefined ? 'schedule' : 'workflow_dispatch'));
|
|
2344
|
+
let resolvedBaseRevision;
|
|
2345
|
+
try {
|
|
2346
|
+
resolvedBaseRevision = await resolveSuiteBaseRevision(options.repositoryRoot, options.baseRevision, timeoutMs, options.remoteBaseRevision);
|
|
2347
|
+
}
|
|
2348
|
+
catch (error) {
|
|
2349
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
2350
|
+
return Object.freeze({
|
|
2351
|
+
suiteName: suite.manifest.metadata.name,
|
|
2352
|
+
suitePath: suite.suitePath,
|
|
2353
|
+
suiteSha256: suite.suiteSha256,
|
|
2354
|
+
eventName: inferredEventName,
|
|
2355
|
+
baseRevision: options.baseRevision ?? '',
|
|
2356
|
+
disposition: 'blocked',
|
|
2357
|
+
reason: 'invalid_base_revision',
|
|
2358
|
+
detail: scrubber.scrub(detail),
|
|
2359
|
+
code: error instanceof TaskpackError ? error.code : 'ACTION_INPUT_INVALID',
|
|
2360
|
+
validDomainIds,
|
|
2361
|
+
suiteProtectedPaths: suite.suiteProtectedPaths,
|
|
2362
|
+
cells: Object.freeze([]),
|
|
2363
|
+
eligibleCells: Object.freeze([]),
|
|
2364
|
+
matrix: Object.freeze({ include: Object.freeze([]) }),
|
|
2365
|
+
});
|
|
2366
|
+
}
|
|
2367
|
+
const buildResult = (input) => {
|
|
2368
|
+
const cells = Object.freeze(input.cells ?? []);
|
|
2369
|
+
const eligibleCells = Object.freeze(cells
|
|
2370
|
+
.filter(c => c.disposition === 'eligible')
|
|
2371
|
+
.map(c => Object.freeze({
|
|
2372
|
+
domainId: c.domainId,
|
|
2373
|
+
taskpackPath: c.taskpackPath,
|
|
2374
|
+
taskpackName: c.taskpackName,
|
|
2375
|
+
manifestSha256: c.manifestSha256,
|
|
2376
|
+
controlRoot: c.controlRoot,
|
|
2377
|
+
baseRevision: c.baseRevision,
|
|
2378
|
+
...(c.headSha !== undefined ? { headSha: c.headSha } : {}),
|
|
2379
|
+
...(c.stage !== undefined ? { stage: c.stage } : {}),
|
|
2380
|
+
...(c.matrix !== undefined ? { matrix: c.matrix } : {}),
|
|
2381
|
+
protectedPaths: c.protectedPaths,
|
|
2382
|
+
})));
|
|
2383
|
+
return Object.freeze({
|
|
2384
|
+
suiteName: suite.manifest.metadata.name,
|
|
2385
|
+
suitePath: suite.suitePath,
|
|
2386
|
+
suiteSha256: suite.suiteSha256,
|
|
2387
|
+
eventName: inferredEventName,
|
|
2388
|
+
baseRevision: resolvedBaseRevision,
|
|
2389
|
+
disposition: input.disposition,
|
|
2390
|
+
reason: scrubber.scrub(input.reason),
|
|
2391
|
+
...(input.detail !== undefined ? { detail: scrubber.scrub(input.detail) } : {}),
|
|
2392
|
+
...(input.code !== undefined ? { code: input.code } : {}),
|
|
2393
|
+
validDomainIds,
|
|
2394
|
+
suiteProtectedPaths: suite.suiteProtectedPaths,
|
|
2395
|
+
...(input.comment !== undefined ? { comment: input.comment } : {}),
|
|
2396
|
+
cells,
|
|
2397
|
+
eligibleCells,
|
|
2398
|
+
matrix: Object.freeze({ include: eligibleCells }),
|
|
2399
|
+
});
|
|
2400
|
+
};
|
|
2401
|
+
const stageCache = new Map();
|
|
2402
|
+
const domainUpdatesCache = new Map();
|
|
2403
|
+
const openPrCache = new Map();
|
|
2404
|
+
const localCommitAvailabilityPromise = hasLocalGitCommit(options.repositoryRoot, resolvedBaseRevision, timeoutMs);
|
|
2405
|
+
const remoteGitDataCache = {
|
|
2406
|
+
commitTreeSha: new Map(),
|
|
2407
|
+
treeDocs: new Map(),
|
|
2408
|
+
blobBytes: new Map(),
|
|
2409
|
+
totalCachedBlobBytes: 0,
|
|
2410
|
+
};
|
|
2411
|
+
const versionFromCache = new Map();
|
|
2412
|
+
const readRevisionBlobBytes = async (relPath, maxBytes, optional) => {
|
|
2413
|
+
if (await localCommitAvailabilityPromise) {
|
|
2414
|
+
const localBytes = await readOptionalGitBlobBytes(options.repositoryRoot, resolvedBaseRevision, relPath, maxBytes, timeoutMs);
|
|
2415
|
+
if (localBytes === null && !optional) {
|
|
2416
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `path "${relPath}" does not exist in commit ${resolvedBaseRevision}`);
|
|
2417
|
+
}
|
|
2418
|
+
return localBytes;
|
|
2419
|
+
}
|
|
2420
|
+
if (effectiveRepoFullName !== undefined && REPOSITORY_FULL_NAME_PATTERN.test(effectiveRepoFullName)) {
|
|
2421
|
+
return fetchGitHubContentsBlobBytes({
|
|
2422
|
+
repositoryFullName: effectiveRepoFullName,
|
|
2423
|
+
resolvedSha: resolvedBaseRevision,
|
|
2424
|
+
relPath,
|
|
2425
|
+
apiBaseUrl,
|
|
2426
|
+
githubHeaders,
|
|
2427
|
+
fetchImpl,
|
|
2428
|
+
maxBytes,
|
|
2429
|
+
timeoutMs,
|
|
2430
|
+
optional,
|
|
2431
|
+
cache: remoteGitDataCache,
|
|
2432
|
+
});
|
|
2433
|
+
}
|
|
2434
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `commit ${resolvedBaseRevision} is not present locally and no GitHub repository is configured for remote blob lookup of "${relPath}"`);
|
|
2435
|
+
};
|
|
2436
|
+
const resolveCachedVersionFrom = (selector) => {
|
|
2437
|
+
const normalizedVersionPath = normalizeRelativePath(selector.path, '/versionFrom/path');
|
|
2438
|
+
const cacheKey = `${resolvedBaseRevision}\0${normalizedVersionPath}\0${selector.jsonPointer ?? ''}`;
|
|
2439
|
+
const existing = versionFromCache.get(cacheKey);
|
|
2440
|
+
if (existing !== undefined)
|
|
2441
|
+
return existing;
|
|
2442
|
+
const promise = (async () => ((await localCommitAvailabilityPromise)
|
|
2443
|
+
? readGitRevisionVersionFrom({
|
|
2444
|
+
repositoryRoot: options.repositoryRoot,
|
|
2445
|
+
baseRevision: resolvedBaseRevision,
|
|
2446
|
+
selector,
|
|
2447
|
+
timeoutMs,
|
|
2448
|
+
})
|
|
2449
|
+
: parseVersionFromBlobBytes((await readRevisionBlobBytes(normalizedVersionPath, MAX_SUITE_STAGE_VERSION_BLOB_BYTES, false)), normalizedVersionPath, selector)))();
|
|
2450
|
+
versionFromCache.set(cacheKey, promise);
|
|
2451
|
+
return promise;
|
|
2452
|
+
};
|
|
2453
|
+
const checkUpstreamDomainUpdates = (domain) => {
|
|
2454
|
+
const existing = domainUpdatesCache.get(domain.id);
|
|
2455
|
+
if (existing !== undefined)
|
|
2456
|
+
return existing;
|
|
2457
|
+
const promise = (async () => {
|
|
2458
|
+
if (options.domainPendingUpdates?.[domain.id] === true) {
|
|
2459
|
+
return { status: 'pending_updates', detail: `upstream domain "${domain.id}" has pending updates` };
|
|
2460
|
+
}
|
|
2461
|
+
if (options.checkDomainUpdates !== undefined) {
|
|
2462
|
+
try {
|
|
2463
|
+
const res = await options.checkDomainUpdates({ domain, baseRevision: resolvedBaseRevision });
|
|
2464
|
+
return res.detail !== undefined
|
|
2465
|
+
? { status: res.status, detail: scrubber.scrub(res.detail) }
|
|
2466
|
+
: { status: res.status };
|
|
2467
|
+
}
|
|
2468
|
+
catch (error) {
|
|
2469
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
2470
|
+
return { status: 'blocked', detail: scrubber.scrub(detail) };
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
2473
|
+
if (options.discoverUpstreamUpdates === true && domain.manifest.spec.upstreams.length > 0) {
|
|
2474
|
+
try {
|
|
2475
|
+
let gitBaselines;
|
|
2476
|
+
const proposal = domain.manifest.spec.proposal;
|
|
2477
|
+
const baselineRelPath = proposal !== undefined
|
|
2478
|
+
? (proposal.path.toLowerCase().endsWith('.json') ? proposal.path : null)
|
|
2479
|
+
: 'package.json';
|
|
2480
|
+
if (baselineRelPath !== null) {
|
|
2481
|
+
const rawBlob = await readRevisionBlobBytes(baselineRelPath, MAX_SUITE_STAGE_VERSION_BLOB_BYTES, true);
|
|
2482
|
+
if (rawBlob !== null) {
|
|
2483
|
+
const parsedDoc = JSON.parse(rawBlob.toString('utf8'));
|
|
2484
|
+
gitBaselines = extractBaselineVersionsFromDocument(domain.manifest, parsedDoc, proposal !== undefined ? 'proposal' : 'package-json');
|
|
2485
|
+
}
|
|
2486
|
+
}
|
|
2487
|
+
const discovered = await discoverTaskpackUpstreamsV2(domain.manifest, {
|
|
2488
|
+
repositoryRoot: options.repositoryRoot,
|
|
2489
|
+
apiBaseUrl,
|
|
2490
|
+
githubToken: effectiveGithubToken,
|
|
2491
|
+
authHeaders: options.authHeaders,
|
|
2492
|
+
fetchImpl,
|
|
2493
|
+
scrubber,
|
|
2494
|
+
env: runtimeEnv,
|
|
2495
|
+
timeoutMs,
|
|
2496
|
+
baselineVersions: gitBaselines,
|
|
2497
|
+
skipWorkingTreeBaselines: true,
|
|
2498
|
+
});
|
|
2499
|
+
if (discovered.disposition === 'blocked') {
|
|
2500
|
+
return { status: 'blocked', detail: scrubber.scrub(discovered.reason) };
|
|
2501
|
+
}
|
|
2502
|
+
if (discovered.disposition === 'candidate') {
|
|
2503
|
+
return { status: 'pending_updates', detail: scrubber.scrub(discovered.reason) };
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2506
|
+
catch (error) {
|
|
2507
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
2508
|
+
return { status: 'blocked', detail: scrubber.scrub(detail) };
|
|
2509
|
+
}
|
|
2510
|
+
}
|
|
2511
|
+
return { status: 'up_to_date' };
|
|
2512
|
+
})();
|
|
2513
|
+
domainUpdatesCache.set(domain.id, promise);
|
|
2514
|
+
return promise;
|
|
2515
|
+
};
|
|
2516
|
+
const checkUpstreamDomainOpenPr = (domain) => {
|
|
2517
|
+
const existing = openPrCache.get(domain.id);
|
|
2518
|
+
if (existing !== undefined)
|
|
2519
|
+
return existing;
|
|
2520
|
+
const promise = (async () => {
|
|
2521
|
+
const pub = domain.manifest.spec.publication;
|
|
2522
|
+
if (pub.mode !== 'pull_request') {
|
|
2523
|
+
return { ok: true, pr: null };
|
|
2524
|
+
}
|
|
2525
|
+
try {
|
|
2526
|
+
if (options.findOpenPullRequest !== undefined) {
|
|
2527
|
+
const pr = await options.findOpenPullRequest({
|
|
2528
|
+
domain,
|
|
2529
|
+
repositoryFullName: effectiveRepoFullName ?? '',
|
|
2530
|
+
targetBranch: pub.targetBranch,
|
|
2531
|
+
headBranchPrefix: pub.headBranchPrefix,
|
|
2532
|
+
});
|
|
2533
|
+
return { ok: true, pr };
|
|
2534
|
+
}
|
|
2535
|
+
if (options.allowOfflineStagePrCheck === true) {
|
|
2536
|
+
return { ok: true, pr: null };
|
|
2537
|
+
}
|
|
2538
|
+
if (effectiveRepoFullName !== undefined && REPOSITORY_FULL_NAME_PATTERN.test(effectiveRepoFullName)) {
|
|
2539
|
+
const pr = await findOpenManagedPullRequest({
|
|
2540
|
+
repositoryFullName: effectiveRepoFullName,
|
|
2541
|
+
targetBranch: pub.targetBranch,
|
|
2542
|
+
headBranchPrefix: pub.headBranchPrefix,
|
|
2543
|
+
apiBaseUrl,
|
|
2544
|
+
githubToken: effectiveGithubToken,
|
|
2545
|
+
authHeaders: options.authHeaders,
|
|
2546
|
+
fetchImpl,
|
|
2547
|
+
scrubber,
|
|
2548
|
+
env: runtimeEnv,
|
|
2549
|
+
timeoutMs,
|
|
2550
|
+
});
|
|
2551
|
+
return { ok: true, pr };
|
|
2552
|
+
}
|
|
2553
|
+
return {
|
|
2554
|
+
ok: false,
|
|
2555
|
+
reason: 'stage_pr_lookup_unavailable',
|
|
2556
|
+
detail: scrubber.scrub(`cannot verify open pull requests for upstream domain "${domain.id}" without findOpenPullRequest, repositoryFullName/GITHUB_REPOSITORY, or allowOfflineStagePrCheck: true`),
|
|
2557
|
+
};
|
|
2558
|
+
}
|
|
2559
|
+
catch (error) {
|
|
2560
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
2561
|
+
return { ok: false, reason: 'open_pr_lookup_failed', detail: scrubber.scrub(detail) };
|
|
2562
|
+
}
|
|
2563
|
+
})();
|
|
2564
|
+
openPrCache.set(domain.id, promise);
|
|
2565
|
+
return promise;
|
|
2566
|
+
};
|
|
2567
|
+
const evaluateStage = (stageId) => {
|
|
2568
|
+
const cached = stageCache.get(stageId);
|
|
2569
|
+
if (cached !== undefined)
|
|
2570
|
+
return cached;
|
|
2571
|
+
const promise = (async () => {
|
|
2572
|
+
const stage = stageById.get(stageId);
|
|
2573
|
+
if (stage === undefined) {
|
|
2574
|
+
return {
|
|
2575
|
+
disposition: 'blocked',
|
|
2576
|
+
reason: 'unknown_stage',
|
|
2577
|
+
detail: `unknown stage "${stageId}"`,
|
|
2578
|
+
probes: Object.freeze([]),
|
|
2579
|
+
};
|
|
2580
|
+
}
|
|
2581
|
+
const collectedProbes = [];
|
|
2582
|
+
const seenProbeKeys = new Set();
|
|
2583
|
+
const pushUniqueProbe = (entry) => {
|
|
2584
|
+
const key = `${entry.stageId}\0${entry.probeIndex}`;
|
|
2585
|
+
if (seenProbeKeys.has(key))
|
|
2586
|
+
return;
|
|
2587
|
+
seenProbeKeys.add(key);
|
|
2588
|
+
collectedProbes.push(entry);
|
|
2589
|
+
};
|
|
2590
|
+
let upstreamDeferredDetail;
|
|
2591
|
+
for (const parentStageId of stage.dependsOn) {
|
|
2592
|
+
const parentOutcome = await evaluateStage(parentStageId);
|
|
2593
|
+
for (const p of parentOutcome.probes) {
|
|
2594
|
+
pushUniqueProbe(p);
|
|
2595
|
+
}
|
|
2596
|
+
if (parentOutcome.disposition === 'blocked') {
|
|
2597
|
+
return {
|
|
2598
|
+
disposition: 'blocked',
|
|
2599
|
+
reason: parentOutcome.reason,
|
|
2600
|
+
detail: parentOutcome.detail ?? `upstream stage "${parentStageId}" is blocked`,
|
|
2601
|
+
probes: Object.freeze(collectedProbes),
|
|
2602
|
+
};
|
|
2603
|
+
}
|
|
2604
|
+
if (parentOutcome.disposition === 'deferred' && upstreamDeferredDetail === undefined) {
|
|
2605
|
+
upstreamDeferredDetail = parentOutcome.detail ?? `upstream stage "${parentStageId}" is not ready`;
|
|
2606
|
+
}
|
|
2607
|
+
const parentDomains = suite.domains.filter(d => d.enabled && d.stage === parentStageId);
|
|
2608
|
+
for (const parentDomain of parentDomains) {
|
|
2609
|
+
const upd = await checkUpstreamDomainUpdates(parentDomain);
|
|
2610
|
+
if (upd.status === 'blocked') {
|
|
2611
|
+
return {
|
|
2612
|
+
disposition: 'blocked',
|
|
2613
|
+
reason: 'upstream_stage_blocked',
|
|
2614
|
+
detail: upd.detail ?? `upstream domain "${parentDomain.id}" failed update check`,
|
|
2615
|
+
probes: Object.freeze(collectedProbes),
|
|
2616
|
+
};
|
|
2617
|
+
}
|
|
2618
|
+
if (upd.status === 'pending_updates' && upstreamDeferredDetail === undefined) {
|
|
2619
|
+
upstreamDeferredDetail = upd.detail ?? `upstream domain "${parentDomain.id}" has pending updates`;
|
|
2620
|
+
}
|
|
2621
|
+
const prCheck = await checkUpstreamDomainOpenPr(parentDomain);
|
|
2622
|
+
if (!prCheck.ok) {
|
|
2623
|
+
return {
|
|
2624
|
+
disposition: 'blocked',
|
|
2625
|
+
reason: prCheck.reason,
|
|
2626
|
+
detail: prCheck.detail,
|
|
2627
|
+
probes: Object.freeze(collectedProbes),
|
|
2628
|
+
};
|
|
2629
|
+
}
|
|
2630
|
+
if (prCheck.pr !== null && upstreamDeferredDetail === undefined) {
|
|
2631
|
+
upstreamDeferredDetail = `upstream domain "${parentDomain.id}" has open pull request #${prCheck.pr.number}`;
|
|
2632
|
+
}
|
|
2633
|
+
}
|
|
2634
|
+
}
|
|
2635
|
+
let probeBlockedDetail;
|
|
2636
|
+
let probeDeferredDetail;
|
|
2637
|
+
for (const [probeIndex, probe] of stage.readiness.entries()) {
|
|
2638
|
+
let expectedVersion;
|
|
2639
|
+
if (probe.versionFrom !== undefined) {
|
|
2640
|
+
try {
|
|
2641
|
+
const rawVersion = await resolveCachedVersionFrom(probe.versionFrom);
|
|
2642
|
+
expectedVersion = probe.tagPrefix !== undefined ? `${probe.tagPrefix}${rawVersion}` : rawVersion;
|
|
2643
|
+
}
|
|
2644
|
+
catch (error) {
|
|
2645
|
+
const detail = scrubber.scrub(error instanceof Error ? error.message : String(error));
|
|
2646
|
+
pushUniqueProbe(Object.freeze({
|
|
2647
|
+
stageId,
|
|
2648
|
+
probeIndex,
|
|
2649
|
+
...(probe.id !== undefined ? { probeId: probe.id } : {}),
|
|
2650
|
+
kind: probe.kind,
|
|
2651
|
+
source: scrubber.scrub(probe.source),
|
|
2652
|
+
disposition: 'blocked',
|
|
2653
|
+
reason: 'version_from_failed',
|
|
2654
|
+
detail,
|
|
2655
|
+
}));
|
|
2656
|
+
probeBlockedDetail ??= detail;
|
|
2657
|
+
continue;
|
|
2658
|
+
}
|
|
2659
|
+
}
|
|
2660
|
+
else if (probe.expectedVersion !== undefined) {
|
|
2661
|
+
expectedVersion = probe.tagPrefix !== undefined ? `${probe.tagPrefix}${probe.expectedVersion}` : probe.expectedVersion;
|
|
2662
|
+
}
|
|
2663
|
+
const runnerInput = {
|
|
2664
|
+
stageId,
|
|
2665
|
+
probeIndex,
|
|
2666
|
+
probe,
|
|
2667
|
+
expectedVersion,
|
|
2668
|
+
repositoryRoot: options.repositoryRoot,
|
|
2669
|
+
baseRevision: resolvedBaseRevision,
|
|
2670
|
+
scrubber,
|
|
2671
|
+
};
|
|
2672
|
+
let outcome;
|
|
2673
|
+
try {
|
|
2674
|
+
outcome = options.probeRunner !== undefined
|
|
2675
|
+
? await options.probeRunner(runnerInput)
|
|
2676
|
+
: await runDefaultReadinessProbe(runnerInput, {
|
|
2677
|
+
apiBaseUrl,
|
|
2678
|
+
githubHeaders,
|
|
2679
|
+
fetchImpl,
|
|
2680
|
+
timeoutMs,
|
|
2681
|
+
allowLoopbackHttp: effectiveAllowLoopbackHttp,
|
|
2682
|
+
policyProfile: effectivePolicyProfile,
|
|
2683
|
+
});
|
|
2684
|
+
}
|
|
2685
|
+
catch (error) {
|
|
2686
|
+
const detail = scrubber.scrub(error instanceof Error ? error.message : String(error));
|
|
2687
|
+
outcome = {
|
|
2688
|
+
disposition: 'blocked',
|
|
2689
|
+
reason: 'probe_transport_error',
|
|
2690
|
+
detail,
|
|
2691
|
+
};
|
|
2692
|
+
}
|
|
2693
|
+
const scrubbedReason = scrubber.scrub(outcome.reason);
|
|
2694
|
+
const scrubbedDetail = outcome.detail !== undefined ? scrubber.scrub(outcome.detail) : undefined;
|
|
2695
|
+
const scrubbedObserved = outcome.observedVersion !== undefined ? scrubber.scrub(outcome.observedVersion) : undefined;
|
|
2696
|
+
pushUniqueProbe(Object.freeze({
|
|
2697
|
+
stageId,
|
|
2698
|
+
probeIndex,
|
|
2699
|
+
...(probe.id !== undefined ? { probeId: probe.id } : {}),
|
|
2700
|
+
kind: probe.kind,
|
|
2701
|
+
source: scrubber.scrub(probe.source),
|
|
2702
|
+
disposition: outcome.disposition,
|
|
2703
|
+
...(expectedVersion !== undefined ? { expectedVersion: scrubber.scrub(expectedVersion) } : {}),
|
|
2704
|
+
...(scrubbedObserved !== undefined ? { observedVersion: scrubbedObserved } : {}),
|
|
2705
|
+
reason: scrubbedReason,
|
|
2706
|
+
...(scrubbedDetail !== undefined ? { detail: scrubbedDetail } : {}),
|
|
2707
|
+
}));
|
|
2708
|
+
if (outcome.disposition === 'blocked') {
|
|
2709
|
+
probeBlockedDetail ??= scrubbedDetail ?? scrubbedReason;
|
|
2710
|
+
}
|
|
2711
|
+
else if (outcome.disposition === 'deferred') {
|
|
2712
|
+
probeDeferredDetail ??= scrubbedDetail ?? scrubbedReason;
|
|
2713
|
+
}
|
|
2714
|
+
}
|
|
2715
|
+
if (probeBlockedDetail !== undefined) {
|
|
2716
|
+
return {
|
|
2717
|
+
disposition: 'blocked',
|
|
2718
|
+
reason: 'stage_probe_blocked',
|
|
2719
|
+
detail: probeBlockedDetail,
|
|
2720
|
+
probes: Object.freeze(collectedProbes),
|
|
2721
|
+
};
|
|
2722
|
+
}
|
|
2723
|
+
const deferredDetail = upstreamDeferredDetail ?? probeDeferredDetail;
|
|
2724
|
+
if (deferredDetail !== undefined) {
|
|
2725
|
+
return {
|
|
2726
|
+
disposition: 'deferred',
|
|
2727
|
+
reason: 'stage_not_ready',
|
|
2728
|
+
detail: deferredDetail,
|
|
2729
|
+
probes: Object.freeze(collectedProbes),
|
|
2730
|
+
};
|
|
2731
|
+
}
|
|
2732
|
+
return {
|
|
2733
|
+
disposition: 'eligible',
|
|
2734
|
+
reason: 'ready',
|
|
2735
|
+
probes: Object.freeze(collectedProbes),
|
|
2736
|
+
};
|
|
2737
|
+
})();
|
|
2738
|
+
stageCache.set(stageId, promise);
|
|
2739
|
+
return promise;
|
|
2740
|
+
};
|
|
2741
|
+
const evaluateDomainCell = async (domain, headSha) => {
|
|
2742
|
+
const baseCell = toMatrixCell(domain, resolvedBaseRevision, headSha);
|
|
2743
|
+
if (!domain.enabled) {
|
|
2744
|
+
return Object.freeze({
|
|
2745
|
+
...baseCell,
|
|
2746
|
+
disposition: 'deferred',
|
|
2747
|
+
reason: 'domain_disabled',
|
|
2748
|
+
detail: `domain "${domain.id}" has enabled: false`,
|
|
2749
|
+
});
|
|
2750
|
+
}
|
|
2751
|
+
if (domain.stage === undefined) {
|
|
2752
|
+
return Object.freeze({
|
|
2753
|
+
...baseCell,
|
|
2754
|
+
disposition: 'eligible',
|
|
2755
|
+
reason: 'ready',
|
|
2756
|
+
});
|
|
2757
|
+
}
|
|
2758
|
+
const stageOutcome = await evaluateStage(domain.stage);
|
|
2759
|
+
return Object.freeze({
|
|
2760
|
+
...baseCell,
|
|
2761
|
+
disposition: stageOutcome.disposition,
|
|
2762
|
+
reason: stageOutcome.reason,
|
|
2763
|
+
...(stageOutcome.detail !== undefined ? { detail: stageOutcome.detail } : {}),
|
|
2764
|
+
...(stageOutcome.probes.length > 0 ? { probes: stageOutcome.probes } : {}),
|
|
2765
|
+
});
|
|
2766
|
+
};
|
|
2767
|
+
// 1. Pull-request comment events (`issue_comment`, `pull_request_review`, `pull_request_review_comment`)
|
|
2768
|
+
const isCommentEvent = (inferredEventName === 'issue_comment'
|
|
2769
|
+
|| inferredEventName === 'pull_request_review'
|
|
2770
|
+
|| inferredEventName === 'pull_request_review_comment');
|
|
2771
|
+
if (isCommentEvent) {
|
|
2772
|
+
if (options.eventPayload !== undefined && !isPlainRecord(options.eventPayload)) {
|
|
2773
|
+
return buildResult({
|
|
2774
|
+
disposition: 'blocked',
|
|
2775
|
+
reason: 'invalid_event_payload',
|
|
2776
|
+
detail: 'eventPayload must be a JSON object',
|
|
2777
|
+
code: 'ACTION_INPUT_INVALID',
|
|
2778
|
+
});
|
|
2779
|
+
}
|
|
2780
|
+
const payloadMeta = extractCommentMetadataFromPayload(options.eventPayload);
|
|
2781
|
+
if (options.eventPayload !== undefined) {
|
|
2782
|
+
if (inferredEventName === 'pull_request_review') {
|
|
2783
|
+
if (payloadMeta.action !== undefined && payloadMeta.action !== 'submitted') {
|
|
2784
|
+
return buildResult({
|
|
2785
|
+
disposition: 'ignored',
|
|
2786
|
+
reason: 'non_submitted_review_ignored',
|
|
2787
|
+
});
|
|
2788
|
+
}
|
|
2789
|
+
}
|
|
2790
|
+
else if (payloadMeta.action !== undefined && payloadMeta.action !== 'created') {
|
|
2791
|
+
return buildResult({
|
|
2792
|
+
disposition: 'ignored',
|
|
2793
|
+
reason: 'non_created_comment_ignored',
|
|
2794
|
+
});
|
|
2795
|
+
}
|
|
2796
|
+
if (inferredEventName === 'issue_comment' && payloadMeta.isPlainIssueComment === true) {
|
|
2797
|
+
return buildResult({
|
|
2798
|
+
disposition: 'ignored',
|
|
2799
|
+
reason: 'non_pull_request_comment_ignored',
|
|
2800
|
+
});
|
|
2801
|
+
}
|
|
2802
|
+
}
|
|
2803
|
+
if (payloadMeta.isBot === true) {
|
|
2804
|
+
return buildResult({
|
|
2805
|
+
disposition: 'ignored',
|
|
2806
|
+
reason: 'bot_comment_ignored',
|
|
2807
|
+
});
|
|
2808
|
+
}
|
|
2809
|
+
const commentBody = options.commentBody ?? payloadMeta.commentBody;
|
|
2810
|
+
if (commentBody === undefined || commentBody.trim().length === 0) {
|
|
2811
|
+
return buildResult({
|
|
2812
|
+
disposition: 'ignored',
|
|
2813
|
+
reason: 'empty_comment_ignored',
|
|
2814
|
+
});
|
|
2815
|
+
}
|
|
2816
|
+
const allPrefixes = new Set(DEFAULT_COMMENT_PREFIXES);
|
|
2817
|
+
for (const p of options.commentPrefixes ?? [])
|
|
2818
|
+
allPrefixes.add(p);
|
|
2819
|
+
for (const dom of suite.domains) {
|
|
2820
|
+
for (const p of dom.manifest.spec.triggers.commentPrefixes)
|
|
2821
|
+
allPrefixes.add(p);
|
|
2822
|
+
}
|
|
2823
|
+
const knownDomainSet = new Set(validDomainIds);
|
|
2824
|
+
const parsedComment = parseSuiteCommentCommand(commentBody, [...allPrefixes], TASKPACK_COMMENT_COMMANDS, knownDomainSet);
|
|
2825
|
+
if (parsedComment === null) {
|
|
2826
|
+
return buildResult({
|
|
2827
|
+
disposition: 'ignored',
|
|
2828
|
+
reason: 'unrecognized_comment_ignored',
|
|
2829
|
+
});
|
|
2830
|
+
}
|
|
2831
|
+
const actorLogin = (options.actorLogin ?? payloadMeta.actorLogin)?.trim();
|
|
2832
|
+
const authorAssociation = (options.authorAssociation ?? payloadMeta.authorAssociation)?.trim();
|
|
2833
|
+
const requireCommentAuth = (options.eventPayload !== undefined
|
|
2834
|
+
|| options.actorLogin !== undefined
|
|
2835
|
+
|| options.authorAssociation !== undefined);
|
|
2836
|
+
if (requireCommentAuth) {
|
|
2837
|
+
if (actorLogin === undefined
|
|
2838
|
+
|| actorLogin.length === 0
|
|
2839
|
+
|| authorAssociation === undefined
|
|
2840
|
+
|| authorAssociation.length === 0) {
|
|
2841
|
+
return buildResult({
|
|
2842
|
+
disposition: 'blocked',
|
|
2843
|
+
reason: 'unauthorized_actor',
|
|
2844
|
+
detail: 'event payload is missing comment attribution',
|
|
2845
|
+
code: 'WEBHOOK_ACTOR_UNAUTHORIZED',
|
|
2846
|
+
comment: parsedComment,
|
|
2847
|
+
});
|
|
2848
|
+
}
|
|
2849
|
+
if (!authorizeRepositoryActor(authorAssociation, actorLogin, options.operatorAllowlist)) {
|
|
2850
|
+
return buildResult({
|
|
2851
|
+
disposition: 'blocked',
|
|
2852
|
+
reason: 'unauthorized_actor',
|
|
2853
|
+
detail: `actor "${actorLogin}" lacks write access (${authorAssociation})`,
|
|
2854
|
+
code: 'WEBHOOK_ACTOR_UNAUTHORIZED',
|
|
2855
|
+
comment: parsedComment,
|
|
2856
|
+
});
|
|
2857
|
+
}
|
|
2858
|
+
}
|
|
2859
|
+
const guidanceCheck = validateCommentGuidance(parsedComment.guidance);
|
|
2860
|
+
if (!guidanceCheck.ok) {
|
|
2861
|
+
return buildResult({
|
|
2862
|
+
disposition: 'blocked',
|
|
2863
|
+
reason: 'invalid_guidance',
|
|
2864
|
+
detail: guidanceCheck.detail,
|
|
2865
|
+
code: 'WEBHOOK_GUIDANCE_INVALID',
|
|
2866
|
+
comment: parsedComment,
|
|
2867
|
+
});
|
|
2868
|
+
}
|
|
2869
|
+
let prHeadRef = options.prHeadRef ?? payloadMeta.prHeadRef;
|
|
2870
|
+
let prBaseRef = options.prBaseRef ?? payloadMeta.prBaseRef;
|
|
2871
|
+
let prHeadSha = options.prHeadSha ?? payloadMeta.prHeadSha;
|
|
2872
|
+
let prHeadRepoFullName = options.prHeadRepoFullName ?? payloadMeta.prHeadRepoFullName;
|
|
2873
|
+
let prHeadRepoFork = options.prHeadRepoFork ?? payloadMeta.prHeadRepoFork;
|
|
2874
|
+
let prHeadRepoNull = payloadMeta.prHeadRepoNull === true;
|
|
2875
|
+
let usedApiPrLookup = false;
|
|
2876
|
+
// Fetch missing pull-request metadata via GitHub API when PR payload was omitted (e.g. issue_comment)
|
|
2877
|
+
if (payloadMeta.hasPullRequestPayload !== true
|
|
2878
|
+
&& !prHeadRepoNull
|
|
2879
|
+
&& (prHeadRef === undefined
|
|
2880
|
+
|| prBaseRef === undefined
|
|
2881
|
+
|| prHeadRepoFullName === undefined
|
|
2882
|
+
|| prHeadSha === undefined)
|
|
2883
|
+
&& payloadMeta.prNumber !== undefined
|
|
2884
|
+
&& effectiveRepoFullName !== undefined
|
|
2885
|
+
&& REPOSITORY_FULL_NAME_PATTERN.test(effectiveRepoFullName)) {
|
|
2886
|
+
usedApiPrLookup = true;
|
|
2887
|
+
try {
|
|
2888
|
+
const res = await fetchBoundedText(`${apiBaseUrl}/repos/${effectiveRepoFullName}/pulls/${payloadMeta.prNumber}`, fetchImpl, githubHeaders, timeoutMs, scrubber);
|
|
2889
|
+
if (!res.ok) {
|
|
2890
|
+
return buildResult({
|
|
2891
|
+
disposition: 'blocked',
|
|
2892
|
+
reason: 'pull_request_lookup_failed',
|
|
2893
|
+
detail: `pull request #${payloadMeta.prNumber} lookup failed with HTTP ${res.status}`,
|
|
2894
|
+
code: 'ACTION_INPUT_INVALID',
|
|
2895
|
+
comment: parsedComment,
|
|
2896
|
+
});
|
|
2897
|
+
}
|
|
2898
|
+
const prData = JSON.parse(res.text);
|
|
2899
|
+
if (!isPlainRecord(prData)) {
|
|
2900
|
+
return buildResult({
|
|
2901
|
+
disposition: 'blocked',
|
|
2902
|
+
reason: 'pull_request_lookup_failed',
|
|
2903
|
+
detail: `pull request #${payloadMeta.prNumber} returned non-object JSON`,
|
|
2904
|
+
code: 'ACTION_INPUT_INVALID',
|
|
2905
|
+
comment: parsedComment,
|
|
2906
|
+
});
|
|
2907
|
+
}
|
|
2908
|
+
const head = isPlainRecord(prData['head']) ? prData['head'] : undefined;
|
|
2909
|
+
const base = isPlainRecord(prData['base']) ? prData['base'] : undefined;
|
|
2910
|
+
const headRepo = head !== undefined && isPlainRecord(head['repo']) ? head['repo'] : undefined;
|
|
2911
|
+
const baseRepo = base !== undefined && isPlainRecord(base['repo']) ? base['repo'] : undefined;
|
|
2912
|
+
const apiHeadRepoNull = head !== undefined && head['repo'] === null;
|
|
2913
|
+
const apiHeadRef = typeof head?.['ref'] === 'string' && head['ref'].trim().length > 0 ? head['ref'] : undefined;
|
|
2914
|
+
const apiBaseRef = typeof base?.['ref'] === 'string' && base['ref'].trim().length > 0 ? base['ref'] : undefined;
|
|
2915
|
+
const apiHeadSha = typeof head?.['sha'] === 'string' && head['sha'].trim().length > 0 ? head['sha'] : undefined;
|
|
2916
|
+
const apiHeadRepoFullName = typeof headRepo?.['full_name'] === 'string' && headRepo['full_name'].trim().length > 0
|
|
2917
|
+
? headRepo['full_name']
|
|
2918
|
+
: undefined;
|
|
2919
|
+
let apiHeadRepoFork;
|
|
2920
|
+
if (typeof headRepo?.['fork'] === 'boolean') {
|
|
2921
|
+
const sameForkRepo = baseRepo !== undefined
|
|
2922
|
+
&& baseRepo['fork'] === true
|
|
2923
|
+
&& typeof headRepo['id'] === 'number'
|
|
2924
|
+
&& headRepo['id'] === baseRepo['id'];
|
|
2925
|
+
apiHeadRepoFork = sameForkRepo ? false : headRepo['fork'];
|
|
2926
|
+
}
|
|
2927
|
+
const pinMismatch = ((prHeadRef !== undefined && apiHeadRef !== undefined && prHeadRef.trim() !== apiHeadRef.trim())
|
|
2928
|
+
|| (prBaseRef !== undefined && apiBaseRef !== undefined && prBaseRef.trim() !== apiBaseRef.trim())
|
|
2929
|
+
|| (prHeadSha !== undefined
|
|
2930
|
+
&& COMMIT_SHA_PATTERN.test(prHeadSha.trim())
|
|
2931
|
+
&& apiHeadSha !== undefined
|
|
2932
|
+
&& COMMIT_SHA_PATTERN.test(apiHeadSha.trim())
|
|
2933
|
+
&& prHeadSha.trim().toLowerCase() !== apiHeadSha.trim().toLowerCase())
|
|
2934
|
+
|| (prHeadRepoFullName !== undefined
|
|
2935
|
+
&& apiHeadRepoFullName !== undefined
|
|
2936
|
+
&& prHeadRepoFullName.trim().toLowerCase() !== apiHeadRepoFullName.trim().toLowerCase()));
|
|
2937
|
+
if (pinMismatch) {
|
|
2938
|
+
return buildResult({
|
|
2939
|
+
disposition: 'blocked',
|
|
2940
|
+
reason: 'pull_request_snapshot_mismatch',
|
|
2941
|
+
detail: 'pull request metadata changed between caller/event payload and GitHub API lookup',
|
|
2942
|
+
code: 'TASKPACK_SCOPE_VIOLATION',
|
|
2943
|
+
comment: parsedComment,
|
|
2944
|
+
});
|
|
2945
|
+
}
|
|
2946
|
+
prHeadRepoNull = apiHeadRepoNull;
|
|
2947
|
+
prHeadRef = apiHeadRef;
|
|
2948
|
+
prBaseRef = apiBaseRef;
|
|
2949
|
+
prHeadSha = apiHeadSha;
|
|
2950
|
+
prHeadRepoFullName = apiHeadRepoFullName;
|
|
2951
|
+
prHeadRepoFork = apiHeadRepoFork;
|
|
2952
|
+
}
|
|
2953
|
+
catch (error) {
|
|
2954
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
2955
|
+
return buildResult({
|
|
2956
|
+
disposition: 'blocked',
|
|
2957
|
+
reason: 'pull_request_lookup_failed',
|
|
2958
|
+
detail,
|
|
2959
|
+
code: 'ACTION_INPUT_INVALID',
|
|
2960
|
+
comment: parsedComment,
|
|
2961
|
+
});
|
|
2962
|
+
}
|
|
2963
|
+
}
|
|
2964
|
+
// Enforce fail-closed cross-fork checks whenever resolving from a webhook/API PR or explicit repo metadata
|
|
2965
|
+
const requireCrossForkVerification = (options.eventPayload !== undefined
|
|
2966
|
+
|| usedApiPrLookup
|
|
2967
|
+
|| prHeadRepoFork !== undefined
|
|
2968
|
+
|| prHeadRepoFullName !== undefined);
|
|
2969
|
+
if (requireCrossForkVerification) {
|
|
2970
|
+
const trimmedHeadRepo = prHeadRepoFullName?.trim();
|
|
2971
|
+
if (prHeadRepoNull
|
|
2972
|
+
|| prHeadRepoFork === true
|
|
2973
|
+
|| trimmedHeadRepo === undefined
|
|
2974
|
+
|| trimmedHeadRepo.length === 0
|
|
2975
|
+
|| effectiveRepoFullName === undefined
|
|
2976
|
+
|| !REPOSITORY_FULL_NAME_PATTERN.test(effectiveRepoFullName)
|
|
2977
|
+
|| trimmedHeadRepo.toLowerCase() !== effectiveRepoFullName.toLowerCase()) {
|
|
2978
|
+
return buildResult({
|
|
2979
|
+
disposition: 'blocked',
|
|
2980
|
+
reason: 'cross_fork_pull_request',
|
|
2981
|
+
detail: 'cross-fork pull request comments are refused',
|
|
2982
|
+
code: 'TASKPACK_SCOPE_VIOLATION',
|
|
2983
|
+
comment: parsedComment,
|
|
2984
|
+
});
|
|
2985
|
+
}
|
|
2986
|
+
}
|
|
2987
|
+
let normalizedHeadSha;
|
|
2988
|
+
if (prHeadSha !== undefined) {
|
|
2989
|
+
const trimmedSha = prHeadSha.trim();
|
|
2990
|
+
if (!COMMIT_SHA_PATTERN.test(trimmedSha)) {
|
|
2991
|
+
return buildResult({
|
|
2992
|
+
disposition: 'blocked',
|
|
2993
|
+
reason: 'invalid_pull_request_head_sha',
|
|
2994
|
+
detail: `invalid pull request head SHA "${trimmedSha}"`,
|
|
2995
|
+
code: 'ACTION_INPUT_INVALID',
|
|
2996
|
+
comment: parsedComment,
|
|
2997
|
+
});
|
|
2998
|
+
}
|
|
2999
|
+
normalizedHeadSha = trimmedSha.toLowerCase();
|
|
3000
|
+
}
|
|
3001
|
+
if (prHeadRef === undefined || prHeadRef.trim().length === 0) {
|
|
3002
|
+
return buildResult({
|
|
3003
|
+
disposition: 'blocked',
|
|
3004
|
+
reason: 'missing_pull_request_branch',
|
|
3005
|
+
detail: `pull request head branch metadata is required to route comment commands; valid domains: ${validDomainIds.join(', ')}`,
|
|
3006
|
+
code: 'TASKPACK_SCOPE_VIOLATION',
|
|
3007
|
+
comment: parsedComment,
|
|
3008
|
+
});
|
|
3009
|
+
}
|
|
3010
|
+
const ownership = matchSuitePullRequestDomain(suite.domains, prHeadRef, prBaseRef);
|
|
3011
|
+
if (ownership.ambiguous) {
|
|
3012
|
+
return buildResult({
|
|
3013
|
+
disposition: 'blocked',
|
|
3014
|
+
reason: 'ambiguous_pull_request_branch',
|
|
3015
|
+
detail: `pull request branch "${prHeadRef}" is ambiguous without prBaseRef; valid domains: ${validDomainIds.join(', ')}`,
|
|
3016
|
+
code: 'TASKPACK_SCOPE_VIOLATION',
|
|
3017
|
+
comment: parsedComment,
|
|
3018
|
+
});
|
|
3019
|
+
}
|
|
3020
|
+
if (parsedComment.domainId !== undefined) {
|
|
3021
|
+
const explicitTarget = domainById.get(parsedComment.domainId);
|
|
3022
|
+
if (explicitTarget === undefined) {
|
|
3023
|
+
return buildResult({
|
|
3024
|
+
disposition: 'blocked',
|
|
3025
|
+
reason: 'unknown_domain',
|
|
3026
|
+
detail: `unknown suite domain "${parsedComment.domainId}"; valid domains: ${validDomainIds.join(', ')}`,
|
|
3027
|
+
code: 'TASKPACK_SCOPE_VIOLATION',
|
|
3028
|
+
comment: parsedComment,
|
|
3029
|
+
});
|
|
3030
|
+
}
|
|
3031
|
+
if (ownership.matched === null || ownership.matched.id !== explicitTarget.id) {
|
|
3032
|
+
return buildResult({
|
|
3033
|
+
disposition: 'blocked',
|
|
3034
|
+
reason: 'domain_branch_mismatch',
|
|
3035
|
+
detail: ownership.matched !== null
|
|
3036
|
+
? `comment targets domain "${explicitTarget.id}" on pull request branch "${prHeadRef}" owned by domain "${ownership.matched.id}"`
|
|
3037
|
+
: `comment targets domain "${explicitTarget.id}" on unmanaged pull request branch "${prHeadRef}"; valid domains: ${validDomainIds.join(', ')}`,
|
|
3038
|
+
code: 'TASKPACK_SCOPE_VIOLATION',
|
|
3039
|
+
comment: parsedComment,
|
|
3040
|
+
});
|
|
3041
|
+
}
|
|
3042
|
+
}
|
|
3043
|
+
if (ownership.matched === null) {
|
|
3044
|
+
return buildResult({
|
|
3045
|
+
disposition: 'blocked',
|
|
3046
|
+
reason: 'unmatched_pull_request_branch',
|
|
3047
|
+
detail: `pull request branch "${prHeadRef}" does not match any suite domain headBranchPrefix; valid domains: ${validDomainIds.join(', ')}`,
|
|
3048
|
+
code: 'TASKPACK_SCOPE_VIOLATION',
|
|
3049
|
+
comment: parsedComment,
|
|
3050
|
+
});
|
|
3051
|
+
}
|
|
3052
|
+
const targetDomain = ownership.matched;
|
|
3053
|
+
if (options.domain !== undefined && options.domain !== targetDomain.id) {
|
|
3054
|
+
return buildResult({
|
|
3055
|
+
disposition: 'blocked',
|
|
3056
|
+
reason: 'domain_branch_mismatch',
|
|
3057
|
+
detail: `explicit domain "${options.domain}" conflicts with pull request branch "${prHeadRef}" owned by domain "${targetDomain.id}"`,
|
|
3058
|
+
code: 'TASKPACK_SCOPE_VIOLATION',
|
|
3059
|
+
comment: parsedComment,
|
|
3060
|
+
});
|
|
3061
|
+
}
|
|
3062
|
+
if (!targetDomain.enabled) {
|
|
3063
|
+
return buildResult({
|
|
3064
|
+
disposition: 'blocked',
|
|
3065
|
+
reason: 'domain_disabled',
|
|
3066
|
+
detail: `suite domain "${targetDomain.id}" is disabled`,
|
|
3067
|
+
code: 'TASKPACK_SCOPE_VIOLATION',
|
|
3068
|
+
comment: parsedComment,
|
|
3069
|
+
});
|
|
3070
|
+
}
|
|
3071
|
+
const configuredPrefixes = targetDomain.manifest.spec.triggers.commentPrefixes.length > 0
|
|
3072
|
+
? targetDomain.manifest.spec.triggers.commentPrefixes
|
|
3073
|
+
: DEFAULT_COMMENT_PREFIXES;
|
|
3074
|
+
const effectiveAllowedPrefixes = options.commentPrefixes !== undefined && options.commentPrefixes.length > 0
|
|
3075
|
+
? options.commentPrefixes
|
|
3076
|
+
: configuredPrefixes;
|
|
3077
|
+
if (!effectiveAllowedPrefixes.includes(parsedComment.prefix)) {
|
|
3078
|
+
return buildResult({
|
|
3079
|
+
disposition: 'ignored',
|
|
3080
|
+
reason: 'comment_prefix_not_configured_for_domain',
|
|
3081
|
+
comment: parsedComment,
|
|
3082
|
+
});
|
|
3083
|
+
}
|
|
3084
|
+
const configuredCommands = targetDomain.manifest.spec.triggers.commentCommands;
|
|
3085
|
+
if ((configuredCommands.length > 0 || options.policyProfile === 'github')
|
|
3086
|
+
&& !configuredCommands.includes(parsedComment.command)) {
|
|
3087
|
+
return buildResult({
|
|
3088
|
+
disposition: 'blocked',
|
|
3089
|
+
reason: 'comment_command_unsupported',
|
|
3090
|
+
detail: `domain "${targetDomain.id}" does not enable comment command "${parsedComment.command}"`,
|
|
3091
|
+
code: 'TASKPACK_TRIGGER_UNSUPPORTED',
|
|
3092
|
+
comment: parsedComment,
|
|
3093
|
+
});
|
|
3094
|
+
}
|
|
3095
|
+
if (parsedComment.command === 'status') {
|
|
3096
|
+
const statusCell = Object.freeze({
|
|
3097
|
+
...toMatrixCell(targetDomain, resolvedBaseRevision, normalizedHeadSha),
|
|
3098
|
+
disposition: 'eligible',
|
|
3099
|
+
reason: 'ready',
|
|
3100
|
+
});
|
|
3101
|
+
return buildResult({
|
|
3102
|
+
disposition: 'eligible',
|
|
3103
|
+
reason: 'ready',
|
|
3104
|
+
comment: parsedComment,
|
|
3105
|
+
cells: [statusCell],
|
|
3106
|
+
});
|
|
3107
|
+
}
|
|
3108
|
+
const cell = await evaluateDomainCell(targetDomain, normalizedHeadSha);
|
|
3109
|
+
return buildResult({
|
|
3110
|
+
disposition: cell.disposition,
|
|
3111
|
+
reason: cell.reason,
|
|
3112
|
+
detail: cell.detail,
|
|
3113
|
+
code: cell.code,
|
|
3114
|
+
comment: parsedComment,
|
|
3115
|
+
cells: [cell],
|
|
3116
|
+
});
|
|
3117
|
+
}
|
|
3118
|
+
const payloadSchedule = isPlainRecord(options.eventPayload) && typeof options.eventPayload['schedule'] === 'string'
|
|
3119
|
+
? options.eventPayload['schedule']
|
|
3120
|
+
: undefined;
|
|
3121
|
+
const scheduleKey = options.schedule ?? payloadSchedule;
|
|
3122
|
+
const domainMatchesTriggerAndSchedule = (dom) => {
|
|
3123
|
+
if (!dom.enabled)
|
|
3124
|
+
return false;
|
|
3125
|
+
if (effectivePolicyProfile === 'github') {
|
|
3126
|
+
if (inferredEventName === 'release') {
|
|
3127
|
+
const releaseAction = isPlainRecord(options.eventPayload) && typeof options.eventPayload['action'] === 'string'
|
|
3128
|
+
? options.eventPayload['action']
|
|
3129
|
+
: undefined;
|
|
3130
|
+
if (releaseAction !== 'published') {
|
|
3131
|
+
return false;
|
|
3132
|
+
}
|
|
3133
|
+
}
|
|
3134
|
+
if (!isGitHubTriggerDeclared(dom.manifest.spec.triggers, { eventName: inferredEventName })) {
|
|
3135
|
+
return false;
|
|
3136
|
+
}
|
|
3137
|
+
}
|
|
3138
|
+
if (inferredEventName === 'schedule') {
|
|
3139
|
+
if (scheduleKey !== undefined && scheduleKey.length > 0) {
|
|
3140
|
+
return dom.schedules !== undefined && dom.schedules.includes(scheduleKey);
|
|
3141
|
+
}
|
|
3142
|
+
return dom.schedules === undefined || dom.schedules.length > 0;
|
|
3143
|
+
}
|
|
3144
|
+
return true;
|
|
3145
|
+
};
|
|
3146
|
+
// 2. Direct single-domain selection / matrix cell revalidation
|
|
3147
|
+
if (options.domain !== undefined) {
|
|
3148
|
+
let directHeadSha;
|
|
3149
|
+
if (options.prHeadSha !== undefined) {
|
|
3150
|
+
const trimmedSha = options.prHeadSha.trim();
|
|
3151
|
+
if (!COMMIT_SHA_PATTERN.test(trimmedSha)) {
|
|
3152
|
+
return buildResult({
|
|
3153
|
+
disposition: 'blocked',
|
|
3154
|
+
reason: 'invalid_pull_request_head_sha',
|
|
3155
|
+
detail: `invalid pull request head SHA "${trimmedSha}"`,
|
|
3156
|
+
code: 'ACTION_INPUT_INVALID',
|
|
3157
|
+
});
|
|
3158
|
+
}
|
|
3159
|
+
directHeadSha = trimmedSha.toLowerCase();
|
|
3160
|
+
}
|
|
3161
|
+
const selected = domainById.get(options.domain);
|
|
3162
|
+
if (selected === undefined) {
|
|
3163
|
+
return buildResult({
|
|
3164
|
+
disposition: 'blocked',
|
|
3165
|
+
reason: 'unknown_domain',
|
|
3166
|
+
detail: `unknown suite domain "${options.domain}"; valid domains: ${validDomainIds.join(', ')}`,
|
|
3167
|
+
code: 'TASKPACK_MANIFEST_INVALID',
|
|
3168
|
+
});
|
|
3169
|
+
}
|
|
3170
|
+
if (!selected.enabled) {
|
|
3171
|
+
const cell = await evaluateDomainCell(selected, directHeadSha);
|
|
3172
|
+
return buildResult({
|
|
3173
|
+
disposition: cell.disposition,
|
|
3174
|
+
reason: cell.reason,
|
|
3175
|
+
detail: cell.detail,
|
|
3176
|
+
code: cell.code,
|
|
3177
|
+
cells: [cell],
|
|
3178
|
+
});
|
|
3179
|
+
}
|
|
3180
|
+
if (!domainMatchesTriggerAndSchedule(selected)) {
|
|
3181
|
+
const detail = inferredEventName === 'schedule' && scheduleKey !== undefined && scheduleKey.length > 0
|
|
3182
|
+
? `domain "${selected.id}" does not match schedule "${scheduleKey}"`
|
|
3183
|
+
: `domain "${selected.id}" does not enable trigger "${inferredEventName}"`;
|
|
3184
|
+
const cell = Object.freeze({
|
|
3185
|
+
domainId: selected.id,
|
|
3186
|
+
taskpackPath: selected.taskpackPath,
|
|
3187
|
+
taskpackName: selected.manifest.metadata.name,
|
|
3188
|
+
manifestSha256: selected.manifestSha256,
|
|
3189
|
+
controlRoot: selected.controlRoot,
|
|
3190
|
+
baseRevision: resolvedBaseRevision,
|
|
3191
|
+
...(directHeadSha !== undefined ? { headSha: directHeadSha } : {}),
|
|
3192
|
+
...(selected.stage !== undefined ? { stage: selected.stage } : {}),
|
|
3193
|
+
...(selected.matrix !== undefined ? { matrix: selected.matrix } : {}),
|
|
3194
|
+
protectedPaths: selected.protectedPaths,
|
|
3195
|
+
disposition: 'deferred',
|
|
3196
|
+
reason: 'no_matching_domains',
|
|
3197
|
+
detail,
|
|
3198
|
+
});
|
|
3199
|
+
return buildResult({
|
|
3200
|
+
disposition: 'deferred',
|
|
3201
|
+
reason: 'no_matching_domains',
|
|
3202
|
+
detail,
|
|
3203
|
+
cells: [cell],
|
|
3204
|
+
});
|
|
3205
|
+
}
|
|
3206
|
+
const cell = await evaluateDomainCell(selected, directHeadSha);
|
|
3207
|
+
return buildResult({
|
|
3208
|
+
disposition: cell.disposition,
|
|
3209
|
+
reason: cell.reason,
|
|
3210
|
+
detail: cell.detail,
|
|
3211
|
+
code: cell.code,
|
|
3212
|
+
cells: [cell],
|
|
3213
|
+
});
|
|
3214
|
+
}
|
|
3215
|
+
// 3. Schedule & workflow_dispatch multi-domain resolution
|
|
3216
|
+
const requestedDomainSet = options.domains !== undefined ? new Set(options.domains) : null;
|
|
3217
|
+
const candidateDomains = suite.domains.filter(dom => ((requestedDomainSet === null || requestedDomainSet.has(dom.id))
|
|
3218
|
+
&& domainMatchesTriggerAndSchedule(dom)));
|
|
3219
|
+
if (candidateDomains.length === 0) {
|
|
3220
|
+
return buildResult({
|
|
3221
|
+
disposition: 'deferred',
|
|
3222
|
+
reason: 'no_matching_domains',
|
|
3223
|
+
detail: scheduleKey !== undefined
|
|
3224
|
+
? `no enabled domains matched schedule "${scheduleKey}"`
|
|
3225
|
+
: 'no enabled domains matched event',
|
|
3226
|
+
});
|
|
3227
|
+
}
|
|
3228
|
+
const cells = [];
|
|
3229
|
+
for (const dom of candidateDomains) {
|
|
3230
|
+
cells.push(await evaluateDomainCell(dom));
|
|
3231
|
+
}
|
|
3232
|
+
const blockedCell = cells.find(c => c.disposition === 'blocked');
|
|
3233
|
+
if (blockedCell !== undefined) {
|
|
3234
|
+
return buildResult({
|
|
3235
|
+
disposition: 'blocked',
|
|
3236
|
+
reason: blockedCell.reason,
|
|
3237
|
+
detail: blockedCell.detail,
|
|
3238
|
+
code: blockedCell.code,
|
|
3239
|
+
cells,
|
|
3240
|
+
});
|
|
3241
|
+
}
|
|
3242
|
+
const hasEligible = cells.some(c => c.disposition === 'eligible');
|
|
3243
|
+
if (hasEligible) {
|
|
3244
|
+
return buildResult({
|
|
3245
|
+
disposition: 'eligible',
|
|
3246
|
+
reason: 'ready',
|
|
3247
|
+
cells,
|
|
3248
|
+
});
|
|
3249
|
+
}
|
|
3250
|
+
return buildResult({
|
|
3251
|
+
disposition: 'deferred',
|
|
3252
|
+
reason: 'stage_not_ready',
|
|
3253
|
+
detail: cells.find(c => c.detail !== undefined)?.detail,
|
|
3254
|
+
cells,
|
|
3255
|
+
});
|
|
3256
|
+
}
|