@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,4189 @@
|
|
|
1
|
+
import { posix } from 'node:path';
|
|
2
|
+
import { HANDOFF_LIMITS, isWritablePath, LIMITS, OVERLAY_LIMITS, matchesScopePattern, resolveOverlayLimits, validateRelativePath, validateScopePattern, } from '@loopwright/core';
|
|
3
|
+
import { STANDARD_PI_PROVIDER_ENV } from '@loopwright/agent-pi/catalog';
|
|
4
|
+
import { DECISION_PROVIDER_API_KEY_ENV } from '@loopwright/decisions';
|
|
5
|
+
import { DEFAULT_MEMORY_MAX_ENTRIES, DEFAULT_MEMORY_MAX_PROMPT_ENTRIES, DEFAULT_MEMORY_TTL_DAYS, } from '@loopwright/memory';
|
|
6
|
+
import { BASELINE_ALIGNMENT_POLICIES, DEFAULT_BASELINE_ALIGNMENT_POLICY, DEFAULT_BASELINE_MAX_CONFLICT_BYTES, DEFAULT_BASELINE_MAX_CONFLICT_FILES, DEFAULT_COMMENT_PREFIXES, GITHUB_PROTECTED_AUTOMATION_PATHS, LOCAL_PROTECTED_AUTOMATION_PATHS, LOCAL_COMMAND_GATE_ENDPOINT_ID, MAX_BASELINE_MAX_CONFLICT_BYTES, MAX_BASELINE_MAX_CONFLICT_FILES, MAX_STEP_REWORKS, MAX_TASKPACK_ROLES, MAX_TASKPACK_STEPS, MIN_BASELINE_MAX_CONFLICT_BYTES, MIN_BASELINE_MAX_CONFLICT_FILES, MULTI_TENANT_HOST_POLICY, TASKPACK_COMMENT_COMMANDS, TASKPACK_MANIFEST_API_VERSION, TASKPACK_MANIFEST_BYTES, TASKPACK_OUTPUT_FORMATS, TASKPACK_TOOL_NAMES, TaskpackError, } from './types.js';
|
|
7
|
+
import { parseYamlDocument } from './yaml.js';
|
|
8
|
+
import { validateTaskpackModelsDeclaration } from './models-config.js';
|
|
9
|
+
export { MULTI_TENANT_HOST_POLICY };
|
|
10
|
+
export const IDENTIFIER_PATTERN = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/;
|
|
11
|
+
const TARGET_BRANCH_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/;
|
|
12
|
+
const COMMENT_PREFIX_PATTERN = /^\/[A-Za-z0-9_-]{0,31}$/;
|
|
13
|
+
const FIELD_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
|
|
14
|
+
const PATH_SEGMENT_PATTERN = /^[A-Za-z0-9._-]+$/;
|
|
15
|
+
const RESERVED_DEVICE_NAME_PATTERN = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i;
|
|
16
|
+
const COMMAND_ENV_NAME_PATTERN = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
17
|
+
const MCP_SERVER_ID_PATTERN = /^[a-z][a-z0-9_]*(?:-[a-z0-9_]+)*$/;
|
|
18
|
+
const HTTP_HEADER_NAME_PATTERN = /^[A-Za-z0-9-]+$/;
|
|
19
|
+
const VERSION_PATH_PATTERN = /^(?:\$(?:\.[A-Za-z0-9_-]+)?|[A-Za-z0-9_-]+)(?:\.[A-Za-z0-9_-]+|\[\d+\]|\['[^'\r\n]+'\]|\["[^"\r\n]+"\])*$/;
|
|
20
|
+
const SECRET_VAR_KEY_PATTERN = /(?:^|_)(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|APIKEY|PRIVATE_KEY|ACCESS_KEY|AUTH_KEY|CREDENTIAL|BEARER|COOKIE|SESSION_KEY|SIGNING_KEY|GH_PAT)(?:$|_)/i;
|
|
21
|
+
const SECRET_VAR_VALUE_PATTERN = /(?:^|[^A-Za-z0-9])(?:gh[pousr]_[A-Za-z0-9]{10,}|github_pat_[A-Za-z0-9_]{10,}|sk-[A-Za-z0-9_-]{12,}|AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----|Bearer\s+[A-Za-z0-9._-]{8,})/i;
|
|
22
|
+
const MAX_SPEC_VARS = 64;
|
|
23
|
+
const MAX_SPEC_VAR_VALUE_LENGTH = 512;
|
|
24
|
+
const MAX_DECISION_TRIAGE_RULES = 100;
|
|
25
|
+
const RESERVED_COMMAND_ENV_NAMES = new Set([
|
|
26
|
+
'GH_TOKEN', 'GITHUB_TOKEN', 'BASH_ENV', 'ENV', 'NODE_OPTIONS',
|
|
27
|
+
'PATH', 'HOME', 'TMPDIR', 'LANG', 'LC_ALL', 'LLM_TOKEN',
|
|
28
|
+
'AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN',
|
|
29
|
+
'NPM_TOKEN', 'NODE_AUTH_TOKEN',
|
|
30
|
+
...Object.values(STANDARD_PI_PROVIDER_ENV),
|
|
31
|
+
...Object.values(DECISION_PROVIDER_API_KEY_ENV).flat(),
|
|
32
|
+
]);
|
|
33
|
+
const RESERVED_COMMAND_ENV_PREFIXES = [
|
|
34
|
+
'LOOPWRIGHT_', 'INPUT_', 'GITHUB_APP_', 'ACTIONS_', 'RUNNER_', 'LD_', 'DYLD_', 'GIT_',
|
|
35
|
+
];
|
|
36
|
+
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
37
|
+
const LONE_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;
|
|
38
|
+
const DOTTED_VERSION_RE = /^\d+(?:\.\d+)*$/;
|
|
39
|
+
const METRIC_KEY_RE = /^[A-Za-z_][A-Za-z0-9._-]*$/;
|
|
40
|
+
const PRINTABLE_ASCII_RE = /^[\x20-\x7E]+$/;
|
|
41
|
+
const MAX_NODES = 4096;
|
|
42
|
+
const MAX_DEPTH = 16;
|
|
43
|
+
const MAX_COLLECTION = 512;
|
|
44
|
+
const MAX_STRING = 8192;
|
|
45
|
+
const DEFAULT_DECISION_MIN_CONFIDENCE = 0.8;
|
|
46
|
+
const DEFAULT_DECISION_CONFIRM_THRESHOLD = 0.6;
|
|
47
|
+
function manifestInvalid(message, path) {
|
|
48
|
+
throw new TaskpackError('TASKPACK_MANIFEST_INVALID', message, path);
|
|
49
|
+
}
|
|
50
|
+
function decodeText(bytes) {
|
|
51
|
+
try {
|
|
52
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
throw new TaskpackError('TASKPACK_MANIFEST_INVALID', 'manifest bytes are not valid UTF-8', '/');
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function resolvePolicyProfile(explicitProfile, hostProfile) {
|
|
59
|
+
if (explicitProfile !== undefined && explicitProfile !== 'local' && explicitProfile !== 'github') {
|
|
60
|
+
throw new TaskpackError('TASKPACK_HOST_BINDING_INVALID', `unsupported policyProfile "${String(explicitProfile)}"`, '/policyProfile');
|
|
61
|
+
}
|
|
62
|
+
if (hostProfile !== undefined && hostProfile !== 'local' && hostProfile !== 'github') {
|
|
63
|
+
throw new TaskpackError('TASKPACK_HOST_BINDING_INVALID', `unsupported hostPolicy.policyProfile "${String(hostProfile)}"`, '/hostPolicy/policyProfile');
|
|
64
|
+
}
|
|
65
|
+
if (explicitProfile !== undefined && hostProfile !== undefined && explicitProfile !== hostProfile) {
|
|
66
|
+
throw new TaskpackError('TASKPACK_HOST_BINDING_INVALID', `conflicting policyProfile "${explicitProfile}" and hostPolicy.policyProfile "${hostProfile}"`, '/policyProfile');
|
|
67
|
+
}
|
|
68
|
+
return explicitProfile ?? hostProfile ?? 'local';
|
|
69
|
+
}
|
|
70
|
+
export function parseJsonSubset(source, limits = {}) {
|
|
71
|
+
const maxNodes = limits.maxNodes ?? MAX_NODES;
|
|
72
|
+
const maxDepth = limits.maxDepth ?? MAX_DEPTH;
|
|
73
|
+
const maxCollection = limits.maxCollection ?? MAX_COLLECTION;
|
|
74
|
+
const maxString = limits.maxString ?? MAX_STRING;
|
|
75
|
+
const rootPath = limits.diagPath ?? '/';
|
|
76
|
+
let offset = 0, nodes = 0;
|
|
77
|
+
const charAt = (index) => source.charAt(index);
|
|
78
|
+
const string = () => {
|
|
79
|
+
const start = offset++;
|
|
80
|
+
let closed = false;
|
|
81
|
+
while (offset < source.length) {
|
|
82
|
+
const char = charAt(offset++);
|
|
83
|
+
if (char === '"') {
|
|
84
|
+
closed = true;
|
|
85
|
+
break;
|
|
86
|
+
}
|
|
87
|
+
if (char === '\\')
|
|
88
|
+
offset++;
|
|
89
|
+
}
|
|
90
|
+
if (!closed)
|
|
91
|
+
manifestInvalid('unterminated JSON string', rootPath);
|
|
92
|
+
let value;
|
|
93
|
+
try {
|
|
94
|
+
value = JSON.parse(source.slice(start, offset));
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
manifestInvalid('invalid JSON string escape', rootPath);
|
|
98
|
+
}
|
|
99
|
+
if (typeof value !== 'string' || value.length > maxString)
|
|
100
|
+
manifestInvalid('JSON string out of bounds', rootPath);
|
|
101
|
+
return value;
|
|
102
|
+
};
|
|
103
|
+
const value = (depth, path) => {
|
|
104
|
+
if (++nodes > maxNodes || depth > maxDepth)
|
|
105
|
+
manifestInvalid('JSON document exceeds node or depth limits', path);
|
|
106
|
+
skipSpace();
|
|
107
|
+
const char = charAt(offset);
|
|
108
|
+
if (char === '{') {
|
|
109
|
+
offset++;
|
|
110
|
+
const output = {}, keys = new Set();
|
|
111
|
+
skipSpace();
|
|
112
|
+
if (charAt(offset) === '}') {
|
|
113
|
+
offset++;
|
|
114
|
+
return output;
|
|
115
|
+
}
|
|
116
|
+
while (true) {
|
|
117
|
+
skipSpace();
|
|
118
|
+
if (charAt(offset) !== '"')
|
|
119
|
+
manifestInvalid('JSON object keys must be strings', path);
|
|
120
|
+
const key = string();
|
|
121
|
+
if (keys.has(key))
|
|
122
|
+
manifestInvalid(`duplicate JSON member "${key}"`, `${path}/${key}`);
|
|
123
|
+
if (FORBIDDEN_KEYS.has(key))
|
|
124
|
+
manifestInvalid(`forbidden JSON member "${key}"`, path);
|
|
125
|
+
keys.add(key);
|
|
126
|
+
skipSpace();
|
|
127
|
+
if (charAt(offset++) !== ':')
|
|
128
|
+
manifestInvalid('expected ":" after JSON member name', path);
|
|
129
|
+
output[key] = value(depth + 1, `${path}/${key}`);
|
|
130
|
+
skipSpace();
|
|
131
|
+
const delimiter = charAt(offset++);
|
|
132
|
+
if (delimiter === '}')
|
|
133
|
+
return output;
|
|
134
|
+
if (delimiter !== ',')
|
|
135
|
+
manifestInvalid('expected "," or "}" in JSON object', path);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (char === '[') {
|
|
139
|
+
offset++;
|
|
140
|
+
const items = [];
|
|
141
|
+
skipSpace();
|
|
142
|
+
if (charAt(offset) === ']') {
|
|
143
|
+
offset++;
|
|
144
|
+
return items;
|
|
145
|
+
}
|
|
146
|
+
while (true) {
|
|
147
|
+
if (items.length >= maxCollection)
|
|
148
|
+
manifestInvalid('JSON array exceeds collection limits', path);
|
|
149
|
+
items.push(value(depth + 1, `${path}/${items.length}`));
|
|
150
|
+
skipSpace();
|
|
151
|
+
const delimiter = charAt(offset++);
|
|
152
|
+
if (delimiter === ']')
|
|
153
|
+
return items;
|
|
154
|
+
if (delimiter !== ',')
|
|
155
|
+
manifestInvalid('expected "," or "]" in JSON array', path);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
if (char === '"')
|
|
159
|
+
return string();
|
|
160
|
+
const literal = /^(?:true|false|null|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)/.exec(source.slice(offset));
|
|
161
|
+
if (literal === null)
|
|
162
|
+
manifestInvalid('invalid JSON value', path);
|
|
163
|
+
offset += literal[0].length;
|
|
164
|
+
if (literal[0] === 'true')
|
|
165
|
+
return true;
|
|
166
|
+
if (literal[0] === 'false')
|
|
167
|
+
return false;
|
|
168
|
+
if (literal[0] === 'null')
|
|
169
|
+
return null;
|
|
170
|
+
const number = Number(literal[0]);
|
|
171
|
+
if (!Number.isFinite(number) || Object.is(number, -0))
|
|
172
|
+
manifestInvalid('JSON number out of bounds', path);
|
|
173
|
+
return number;
|
|
174
|
+
};
|
|
175
|
+
const skipSpace = () => { while (offset < source.length && /[\x20\t\r\n]/.test(charAt(offset)))
|
|
176
|
+
offset++; };
|
|
177
|
+
const parsed = value(1, rootPath);
|
|
178
|
+
skipSpace();
|
|
179
|
+
if (offset !== source.length)
|
|
180
|
+
manifestInvalid('trailing content after JSON document', rootPath);
|
|
181
|
+
return parsed;
|
|
182
|
+
}
|
|
183
|
+
// ---------------------------------------------------------------------------
|
|
184
|
+
// Taskpack 2.0 execution trust modes, trigger checks, & dual-key host authority
|
|
185
|
+
// ---------------------------------------------------------------------------
|
|
186
|
+
export const MAX_COMMAND_MOUNTS = 16;
|
|
187
|
+
export const MAX_ALLOWED_HOST_MOUNTS = 32;
|
|
188
|
+
const FORBIDDEN_HOST_MOUNT_EXACT_ROOTS = new Set([
|
|
189
|
+
'/',
|
|
190
|
+
'/Users',
|
|
191
|
+
'/home',
|
|
192
|
+
'/tmp',
|
|
193
|
+
'/private',
|
|
194
|
+
'/private/tmp',
|
|
195
|
+
'/var',
|
|
196
|
+
'/private/var',
|
|
197
|
+
'/var/folders',
|
|
198
|
+
'/private/var/folders',
|
|
199
|
+
'/opt',
|
|
200
|
+
'/usr',
|
|
201
|
+
'/bin',
|
|
202
|
+
'/sbin',
|
|
203
|
+
'/lib',
|
|
204
|
+
'/lib64',
|
|
205
|
+
'/lib32',
|
|
206
|
+
'/run',
|
|
207
|
+
'/var/run',
|
|
208
|
+
'/private/var/run',
|
|
209
|
+
'/var/lib',
|
|
210
|
+
]);
|
|
211
|
+
const FORBIDDEN_HOST_MOUNT_SOURCE_SUBTREES = Object.freeze([
|
|
212
|
+
'/etc',
|
|
213
|
+
'/private/etc',
|
|
214
|
+
'/proc',
|
|
215
|
+
'/sys',
|
|
216
|
+
'/dev',
|
|
217
|
+
'/root',
|
|
218
|
+
'/boot',
|
|
219
|
+
'/private/var/db',
|
|
220
|
+
'/var/lib',
|
|
221
|
+
]);
|
|
222
|
+
const FORBIDDEN_HOST_MOUNT_TARGET_SUBTREES = Object.freeze([
|
|
223
|
+
'/etc',
|
|
224
|
+
'/private/etc',
|
|
225
|
+
'/proc',
|
|
226
|
+
'/sys',
|
|
227
|
+
'/dev',
|
|
228
|
+
'/root',
|
|
229
|
+
'/boot',
|
|
230
|
+
'/usr',
|
|
231
|
+
'/bin',
|
|
232
|
+
'/sbin',
|
|
233
|
+
'/lib',
|
|
234
|
+
'/lib64',
|
|
235
|
+
'/lib32',
|
|
236
|
+
]);
|
|
237
|
+
function isPathWithinPrefix(candidate, prefix) {
|
|
238
|
+
return candidate === prefix || candidate.startsWith(`${prefix}/`);
|
|
239
|
+
}
|
|
240
|
+
/** Normalize and validate an absolute POSIX mount path (rejects `/`, `..`, and control/quote characters). */
|
|
241
|
+
export function normalizeAbsoluteHostMountPath(rawPath, diagPath, errorCode = 'TASKPACK_MANIFEST_INVALID') {
|
|
242
|
+
if (typeof rawPath !== 'string' || rawPath.length === 0 || rawPath.length > 1024) {
|
|
243
|
+
throw new TaskpackError(errorCode, 'host mount path must be a non-empty string of at most 1024 characters', diagPath);
|
|
244
|
+
}
|
|
245
|
+
if (/[\0\r\n"\\]/.test(rawPath) || !rawPath.startsWith('/')) {
|
|
246
|
+
throw new TaskpackError(errorCode, `host mount path "${rawPath}" must be a clean absolute POSIX path`, diagPath);
|
|
247
|
+
}
|
|
248
|
+
const rawSegments = rawPath.split('/');
|
|
249
|
+
if (rawSegments.includes('..')) {
|
|
250
|
+
throw new TaskpackError(errorCode, `host mount path "${rawPath}" must not contain ".." traversal segments`, diagPath);
|
|
251
|
+
}
|
|
252
|
+
let normalized = posix.normalize(rawPath);
|
|
253
|
+
if (normalized.length > 1 && normalized.endsWith('/')) {
|
|
254
|
+
normalized = normalized.slice(0, -1);
|
|
255
|
+
}
|
|
256
|
+
if (normalized === '/' || !normalized.startsWith('/')) {
|
|
257
|
+
throw new TaskpackError(errorCode, `host mount path "${rawPath}" must not be "/"`, diagPath);
|
|
258
|
+
}
|
|
259
|
+
return normalized;
|
|
260
|
+
}
|
|
261
|
+
/** True when a normalized mount path targets a forbidden broad root or sensitive system subtree. */
|
|
262
|
+
export function isForbiddenHostMountPath(normalizedPath, role) {
|
|
263
|
+
if (FORBIDDEN_HOST_MOUNT_EXACT_ROOTS.has(normalizedPath))
|
|
264
|
+
return true;
|
|
265
|
+
const subtrees = role === 'source'
|
|
266
|
+
? FORBIDDEN_HOST_MOUNT_SOURCE_SUBTREES
|
|
267
|
+
: FORBIDDEN_HOST_MOUNT_TARGET_SUBTREES;
|
|
268
|
+
return subtrees.some(prefix => isPathWithinPrefix(normalizedPath, prefix));
|
|
269
|
+
}
|
|
270
|
+
/** Parse operator-supplied `allow-host-mounts` (comma/newline string or array) into normalized absolute paths. */
|
|
271
|
+
export function parseAllowedHostMounts(raw, diagPath = 'allow-host-mounts') {
|
|
272
|
+
if (raw === undefined)
|
|
273
|
+
return Object.freeze([]);
|
|
274
|
+
const rawEntries = typeof raw === 'string'
|
|
275
|
+
? raw.split(/[,\r\n]+/).map(entry => entry.trim()).filter(entry => entry.length > 0)
|
|
276
|
+
: raw.map(entry => (typeof entry === 'string' ? entry.trim() : entry)).filter(entry => entry !== '');
|
|
277
|
+
if (rawEntries.length > MAX_ALLOWED_HOST_MOUNTS) {
|
|
278
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `allow-host-mounts exceeds maximum of ${MAX_ALLOWED_HOST_MOUNTS} entries`, diagPath);
|
|
279
|
+
}
|
|
280
|
+
const out = [];
|
|
281
|
+
const seen = new Set();
|
|
282
|
+
for (const [idx, entry] of rawEntries.entries()) {
|
|
283
|
+
const normalized = normalizeAbsoluteHostMountPath(entry, `${diagPath}/${idx}`, 'ACTION_INPUT_INVALID');
|
|
284
|
+
if (!seen.has(normalized)) {
|
|
285
|
+
seen.add(normalized);
|
|
286
|
+
out.push(normalized);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
return Object.freeze(out);
|
|
290
|
+
}
|
|
291
|
+
/** True when `mountSource` is explicitly authorized by `allowedHostMounts` (exact normalized match or optional canonical resolver). */
|
|
292
|
+
export function isHostMountAuthorized(mountSource, allowedHostMounts, canonicalize) {
|
|
293
|
+
if (allowedHostMounts === undefined || allowedHostMounts.length === 0)
|
|
294
|
+
return false;
|
|
295
|
+
let normalizedSource;
|
|
296
|
+
try {
|
|
297
|
+
normalizedSource = normalizeAbsoluteHostMountPath(mountSource, 'mount.source');
|
|
298
|
+
}
|
|
299
|
+
catch {
|
|
300
|
+
return false;
|
|
301
|
+
}
|
|
302
|
+
const canonSource = canonicalize?.(normalizedSource) ?? null;
|
|
303
|
+
for (const rawAllowed of allowedHostMounts) {
|
|
304
|
+
let normalizedAllowed;
|
|
305
|
+
try {
|
|
306
|
+
normalizedAllowed = normalizeAbsoluteHostMountPath(rawAllowed, 'allowedHostMounts', 'ACTION_INPUT_INVALID');
|
|
307
|
+
}
|
|
308
|
+
catch {
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
if (normalizedAllowed === normalizedSource)
|
|
312
|
+
return true;
|
|
313
|
+
if (canonSource !== null && canonicalize !== undefined) {
|
|
314
|
+
const canonAllowed = canonicalize(normalizedAllowed);
|
|
315
|
+
if (canonAllowed !== null && canonAllowed === canonSource)
|
|
316
|
+
return true;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
return false;
|
|
320
|
+
}
|
|
321
|
+
/** Resolve effective execution capability booleans from `mode` defaults plus explicit manifest overrides. */
|
|
322
|
+
export function resolveExecutionCapabilities(mode, overrides = {}) {
|
|
323
|
+
const privilegedDefault = mode === 'privileged';
|
|
324
|
+
return Object.freeze({
|
|
325
|
+
allowHostEnv: overrides.allowHostEnv ?? privilegedDefault,
|
|
326
|
+
allowHostPath: overrides.allowHostPath ?? privilegedDefault,
|
|
327
|
+
mountReadOnlyGit: overrides.mountReadOnlyGit ?? privilegedDefault,
|
|
328
|
+
allowCheckNetwork: overrides.allowCheckNetwork ?? privilegedDefault,
|
|
329
|
+
allowWorkflowWrites: overrides.allowWorkflowWrites ?? false,
|
|
330
|
+
allowAgentNetwork: overrides.allowAgentNetwork ?? false,
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
/** Validate and normalize an untrusted `command.v1` `parameters.mounts` array (shared across schema, compiler, and staged secrets). */
|
|
334
|
+
export function normalizeCommandMountList(rawMounts, diagPath, errorCode = 'TASKPACK_MANIFEST_INVALID') {
|
|
335
|
+
if (!Array.isArray(rawMounts) || rawMounts.length > MAX_COMMAND_MOUNTS) {
|
|
336
|
+
throw new TaskpackError(errorCode, `command.v1 mounts must be an array of 0..${MAX_COMMAND_MOUNTS} entries`, diagPath);
|
|
337
|
+
}
|
|
338
|
+
const seenTargets = new Set();
|
|
339
|
+
const parsedMounts = [];
|
|
340
|
+
for (const [mIdx, rawMount] of rawMounts.entries()) {
|
|
341
|
+
const mPath = `${diagPath}/${mIdx}`;
|
|
342
|
+
if (!isPlainObjectRecord(rawMount)) {
|
|
343
|
+
throw new TaskpackError(errorCode, 'command.v1 mount entry must be an object', mPath);
|
|
344
|
+
}
|
|
345
|
+
for (const key of Object.keys(rawMount)) {
|
|
346
|
+
if (FORBIDDEN_KEYS.has(key) || (key !== 'source' && key !== 'target' && key !== 'mode')) {
|
|
347
|
+
throw new TaskpackError(errorCode, `command.v1 mount entry has unsupported key "${key}"`, `${mPath}/${key}`);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
const source = normalizeAbsoluteHostMountPath(rawMount['source'], `${mPath}/source`, errorCode);
|
|
351
|
+
if (isForbiddenHostMountPath(source, 'source')) {
|
|
352
|
+
throw new TaskpackError(errorCode === 'ACTION_INPUT_INVALID' ? 'ACTION_INPUT_INVALID' : 'TASKPACK_SCOPE_VIOLATION', `command.v1 mount source "${source}" targets a forbidden host path`, `${mPath}/source`);
|
|
353
|
+
}
|
|
354
|
+
const target = rawMount['target'] === undefined
|
|
355
|
+
? source
|
|
356
|
+
: normalizeAbsoluteHostMountPath(rawMount['target'], `${mPath}/target`, errorCode);
|
|
357
|
+
if (isForbiddenHostMountPath(target, 'target')) {
|
|
358
|
+
throw new TaskpackError(errorCode === 'ACTION_INPUT_INVALID' ? 'ACTION_INPUT_INVALID' : 'TASKPACK_SCOPE_VIOLATION', `command.v1 mount target "${target}" targets a forbidden sandbox path`, `${mPath}/target`);
|
|
359
|
+
}
|
|
360
|
+
if (seenTargets.has(target)) {
|
|
361
|
+
throw new TaskpackError(errorCode, `duplicate command.v1 mount target "${target}"`, `${mPath}/target`);
|
|
362
|
+
}
|
|
363
|
+
seenTargets.add(target);
|
|
364
|
+
let mountMode = 'ro';
|
|
365
|
+
if (rawMount['mode'] !== undefined) {
|
|
366
|
+
if (rawMount['mode'] !== 'ro' && rawMount['mode'] !== 'rw') {
|
|
367
|
+
throw new TaskpackError(errorCode, 'command.v1 mount mode must be "ro" or "rw"', `${mPath}/mode`);
|
|
368
|
+
}
|
|
369
|
+
mountMode = rawMount['mode'];
|
|
370
|
+
}
|
|
371
|
+
parsedMounts.push(Object.freeze({ source, target, mode: mountMode }));
|
|
372
|
+
}
|
|
373
|
+
return Object.freeze(parsedMounts);
|
|
374
|
+
}
|
|
375
|
+
function extractDeclaredCommandMounts(check, checkIdx) {
|
|
376
|
+
if (check.implementation !== 'command.v1')
|
|
377
|
+
return [];
|
|
378
|
+
const raw = check.parameters?.['mounts'];
|
|
379
|
+
if (raw === undefined)
|
|
380
|
+
return [];
|
|
381
|
+
return normalizeCommandMountList(raw, `/spec/verification/localChecks/${checkIdx}/parameters/mounts`);
|
|
382
|
+
}
|
|
383
|
+
function pickPrivilegedAuthorityDiagPath(execution, hasExecPrivCap, perCheckMountReadOnlyGitIdx, perCheckLoopbackNetIdx, perCheckMountsIdx) {
|
|
384
|
+
if (execution?.mode === 'privileged')
|
|
385
|
+
return '/spec/execution/mode';
|
|
386
|
+
if (!hasExecPrivCap) {
|
|
387
|
+
if (perCheckMountReadOnlyGitIdx !== -1) {
|
|
388
|
+
return `/spec/verification/localChecks/${perCheckMountReadOnlyGitIdx}/parameters/mountReadOnlyGit`;
|
|
389
|
+
}
|
|
390
|
+
if (perCheckLoopbackNetIdx !== -1) {
|
|
391
|
+
return `/spec/verification/localChecks/${perCheckLoopbackNetIdx}/parameters/networkMode`;
|
|
392
|
+
}
|
|
393
|
+
if (perCheckMountsIdx !== -1) {
|
|
394
|
+
return `/spec/verification/localChecks/${perCheckMountsIdx}/parameters/mounts`;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
return '/spec/execution/capabilities';
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Dual-key host authorization guard: fails closed unless operator-controlled host flags match
|
|
401
|
+
* every privileged execution capability, host mount allowlist, or `.github/workflows/**` write unlock declared by the manifest.
|
|
402
|
+
*/
|
|
403
|
+
export function validateExecutionAuthority(execution, hostPolicy = {}, extra) {
|
|
404
|
+
const perCheckMountReadOnlyGitIdx = extra?.localChecks?.findIndex(check => check.implementation === 'command.v1' && check.parameters?.['mountReadOnlyGit'] === true) ?? -1;
|
|
405
|
+
const perCheckLoopbackNetIdx = extra?.localChecks?.findIndex(check => check.implementation === 'command.v1' && check.parameters?.['networkMode'] === 'loopback-only') ?? -1;
|
|
406
|
+
const parsedMountsByCheckIdx = new Map();
|
|
407
|
+
let perCheckMountsIdx = -1;
|
|
408
|
+
if (extra?.localChecks !== undefined) {
|
|
409
|
+
for (const [checkIdx, check] of extra.localChecks.entries()) {
|
|
410
|
+
const parsed = extractDeclaredCommandMounts(check, checkIdx);
|
|
411
|
+
if (parsed.length > 0) {
|
|
412
|
+
if (perCheckMountsIdx === -1)
|
|
413
|
+
perCheckMountsIdx = checkIdx;
|
|
414
|
+
parsedMountsByCheckIdx.set(checkIdx, parsed);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
if (execution === undefined
|
|
419
|
+
&& perCheckMountReadOnlyGitIdx === -1
|
|
420
|
+
&& perCheckLoopbackNetIdx === -1
|
|
421
|
+
&& perCheckMountsIdx === -1) {
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
const caps = execution?.capabilities;
|
|
425
|
+
const hasExecPrivCap = (caps?.allowHostEnv === true
|
|
426
|
+
|| caps?.allowHostPath === true
|
|
427
|
+
|| caps?.mountReadOnlyGit === true
|
|
428
|
+
|| caps?.allowCheckNetwork === true
|
|
429
|
+
|| caps?.allowAgentNetwork === true);
|
|
430
|
+
const requiresPrivileged = (execution?.mode === 'privileged'
|
|
431
|
+
|| hasExecPrivCap
|
|
432
|
+
|| perCheckMountReadOnlyGitIdx !== -1
|
|
433
|
+
|| perCheckLoopbackNetIdx !== -1
|
|
434
|
+
|| perCheckMountsIdx !== -1);
|
|
435
|
+
if (requiresPrivileged && hostPolicy.allowPrivileged !== true) {
|
|
436
|
+
const diagPath = pickPrivilegedAuthorityDiagPath(execution, hasExecPrivCap, perCheckMountReadOnlyGitIdx, perCheckLoopbackNetIdx, perCheckMountsIdx);
|
|
437
|
+
throw new TaskpackError('TASKPACK_HOST_BINDING_INVALID', 'manifest requests privileged execution capabilities without operator host authorization (allowPrivileged)', diagPath);
|
|
438
|
+
}
|
|
439
|
+
for (const [checkIdx, mounts] of parsedMountsByCheckIdx.entries()) {
|
|
440
|
+
for (const [mountIdx, mount] of mounts.entries()) {
|
|
441
|
+
if (!isHostMountAuthorized(mount.source, hostPolicy.allowedHostMounts)) {
|
|
442
|
+
throw new TaskpackError('TASKPACK_HOST_BINDING_INVALID', `command.v1 mount source "${mount.source}" is not authorized by operator hostPolicy.allowedHostMounts`, `/spec/verification/localChecks/${checkIdx}/parameters/mounts/${mountIdx}/source`);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
if (caps?.allowWorkflowWrites === true && hostPolicy.allowWorkflowWrites !== true) {
|
|
447
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', 'manifest declares allowWorkflowWrites: true without operator host authorization (allowWorkflowWrites)', '/spec/execution/capabilities/allowWorkflowWrites');
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
/** Validate a full manifest's execution authority against `hostPolicy` (defaulting to `'local'` profile). */
|
|
451
|
+
export function validateManifestExecutionAuthority(manifest, hostPolicy = {}) {
|
|
452
|
+
resolvePolicyProfile(undefined, hostPolicy.policyProfile);
|
|
453
|
+
validateExecutionAuthority(manifest.spec.execution, hostPolicy, {
|
|
454
|
+
localChecks: manifest.spec.verification.localChecks,
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
/** Enforce multi-tenant GitHub App authority: refuses all self-granted privileged capabilities and absolute host toolchains. */
|
|
458
|
+
export function assertMultiTenantManifestAuthority(manifest) {
|
|
459
|
+
validateExecutionAuthority(manifest.spec.execution, MULTI_TENANT_HOST_POLICY, {
|
|
460
|
+
localChecks: manifest.spec.verification.localChecks,
|
|
461
|
+
});
|
|
462
|
+
for (const [checkIdx, check] of manifest.spec.verification.localChecks.entries()) {
|
|
463
|
+
if (check.implementation !== 'command.v1')
|
|
464
|
+
continue;
|
|
465
|
+
const rawToolchains = check.parameters?.['toolchainPaths'];
|
|
466
|
+
if (Array.isArray(rawToolchains)) {
|
|
467
|
+
for (const [tIdx, entry] of rawToolchains.entries()) {
|
|
468
|
+
if (typeof entry === 'string' && entry.startsWith('/')) {
|
|
469
|
+
throw new TaskpackError('TASKPACK_HOST_BINDING_INVALID', `multi-tenant control plane refuses absolute host toolchainPaths entry "${entry}"`, `/spec/verification/localChecks/${checkIdx}/parameters/toolchainPaths/${tIdx}`);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
/** True when at least one GitHub event or comment command trigger is declared on `spec.triggers`. */
|
|
476
|
+
export function hasAnyDeclaredGitHubTrigger(triggers) {
|
|
477
|
+
return triggers.schedule
|
|
478
|
+
|| triggers.workflowDispatch
|
|
479
|
+
|| triggers.releasePublished
|
|
480
|
+
|| triggers.commentCommands.length > 0;
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* Check whether an incoming GitHub event (and optional comment command) is explicitly declared
|
|
484
|
+
* by the manifest's `spec.triggers`. Fails closed (`false`) for undeclared or unknown events.
|
|
485
|
+
*/
|
|
486
|
+
export function isGitHubTriggerDeclared(triggers, event) {
|
|
487
|
+
const eventName = typeof event === 'string' ? event : event.eventName;
|
|
488
|
+
const commentCommand = typeof event === 'string' ? undefined : event.commentCommand;
|
|
489
|
+
switch (eventName) {
|
|
490
|
+
case 'schedule':
|
|
491
|
+
return triggers.schedule === true;
|
|
492
|
+
case 'workflow_dispatch':
|
|
493
|
+
return triggers.workflowDispatch === true;
|
|
494
|
+
case 'release':
|
|
495
|
+
return triggers.releasePublished === true;
|
|
496
|
+
case 'issue_comment':
|
|
497
|
+
case 'pull_request_review':
|
|
498
|
+
case 'pull_request_review_comment':
|
|
499
|
+
if (commentCommand !== undefined) {
|
|
500
|
+
return triggers.commentCommands.includes(commentCommand);
|
|
501
|
+
}
|
|
502
|
+
return triggers.commentCommands.length > 0;
|
|
503
|
+
default:
|
|
504
|
+
return false;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
// ---------------------------------------------------------------------------
|
|
508
|
+
// Post-parse spec.vars validation & single-pass AST interpolation
|
|
509
|
+
// ---------------------------------------------------------------------------
|
|
510
|
+
function isPlainObjectRecord(value) {
|
|
511
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
512
|
+
return false;
|
|
513
|
+
const proto = Object.getPrototypeOf(value);
|
|
514
|
+
return proto === Object.prototype || proto === null;
|
|
515
|
+
}
|
|
516
|
+
function assertNoInterpolationTemplate(node, astPath, depth = 0) {
|
|
517
|
+
if (depth > MAX_DEPTH)
|
|
518
|
+
return;
|
|
519
|
+
if (typeof node === 'string') {
|
|
520
|
+
if (node.includes('${')) {
|
|
521
|
+
throw new TaskpackError('TASKPACK_UNTRUSTED_INTERPOLATION', `interpolation expression is not permitted at "${astPath}"`, astPath || '/');
|
|
522
|
+
}
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
if (Array.isArray(node)) {
|
|
526
|
+
for (const [idx, item] of node.entries()) {
|
|
527
|
+
assertNoInterpolationTemplate(item, `${astPath}/${idx}`, depth + 1);
|
|
528
|
+
}
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
if (node !== null && typeof node === 'object') {
|
|
532
|
+
for (const [key, val] of Object.entries(node)) {
|
|
533
|
+
if (key.includes('${')) {
|
|
534
|
+
throw new TaskpackError('TASKPACK_UNTRUSTED_INTERPOLATION', `interpolation expression is not permitted in object key "${key}"`, `${astPath}/${key}`);
|
|
535
|
+
}
|
|
536
|
+
assertNoInterpolationTemplate(val, `${astPath}/${key}`, depth + 1);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
function validateSpecVarsRecord(raw, path) {
|
|
541
|
+
assertNoInterpolationTemplate(raw, path);
|
|
542
|
+
if (!isPlainObjectRecord(raw)) {
|
|
543
|
+
manifestInvalid('spec.vars must be a plain object mapping variable names to strings', path);
|
|
544
|
+
}
|
|
545
|
+
const entries = Object.entries(raw);
|
|
546
|
+
if (entries.length > MAX_SPEC_VARS) {
|
|
547
|
+
manifestInvalid(`spec.vars exceeds ${MAX_SPEC_VARS} entries`, path);
|
|
548
|
+
}
|
|
549
|
+
const out = Object.create(null);
|
|
550
|
+
for (const [key, val] of entries) {
|
|
551
|
+
const entryPath = `${path}/${key}`;
|
|
552
|
+
if (FORBIDDEN_KEYS.has(key) || !COMMAND_ENV_NAME_PATTERN.test(key)) {
|
|
553
|
+
manifestInvalid(`spec.vars key "${key}" must match ^[A-Z][A-Z0-9_]{0,63}$`, entryPath);
|
|
554
|
+
}
|
|
555
|
+
if (isReservedCommandEnvName(key) || FORBIDDEN_LITERAL_COMMAND_ENV_NAMES.has(key) || SECRET_VAR_KEY_PATTERN.test(key)) {
|
|
556
|
+
manifestInvalid(`spec.vars key "${key}" must not declare reserved or secret-like variable names`, entryPath);
|
|
557
|
+
}
|
|
558
|
+
if (typeof val !== 'string' || val.length > MAX_SPEC_VAR_VALUE_LENGTH || /[\0\r\n]/.test(val)) {
|
|
559
|
+
manifestInvalid(`spec.vars value for "${key}" must be a string of at most ${MAX_SPEC_VAR_VALUE_LENGTH} characters without control characters`, entryPath);
|
|
560
|
+
}
|
|
561
|
+
if (SECRET_VAR_VALUE_PATTERN.test(val)) {
|
|
562
|
+
manifestInvalid(`spec.vars value for "${key}" appears to contain a secret credential`, entryPath);
|
|
563
|
+
}
|
|
564
|
+
out[key] = val;
|
|
565
|
+
}
|
|
566
|
+
return Object.freeze(out);
|
|
567
|
+
}
|
|
568
|
+
const PERMITTED_INTERPOLATION_EXACT_PATHS = new Set([
|
|
569
|
+
'/spec/publication/titleTemplate',
|
|
570
|
+
'/spec/publication/bodyTemplate',
|
|
571
|
+
'/spec/goal/candidate',
|
|
572
|
+
'/spec/goal/noChange',
|
|
573
|
+
]);
|
|
574
|
+
function isPermittedInterpolationPath(astPath) {
|
|
575
|
+
if (PERMITTED_INTERPOLATION_EXACT_PATHS.has(astPath))
|
|
576
|
+
return true;
|
|
577
|
+
if (/^\/spec\/roles\/\d+\/prompt$/.test(astPath))
|
|
578
|
+
return true;
|
|
579
|
+
if (/^\/spec\/preflight\/env\/\d+$/.test(astPath))
|
|
580
|
+
return true;
|
|
581
|
+
if (/^\/spec\/verification\/localChecks\/\d+\/parameters\/(?:args\/\d+|env\/[^/]+|startMarker|endMarker|allowedPointers\/\d+)$/.test(astPath)) {
|
|
582
|
+
return true;
|
|
583
|
+
}
|
|
584
|
+
return false;
|
|
585
|
+
}
|
|
586
|
+
function validateAndInterpolateString(text, vars, astPath, interpolate) {
|
|
587
|
+
if (!text.includes('${'))
|
|
588
|
+
return text;
|
|
589
|
+
if (!isPermittedInterpolationPath(astPath)) {
|
|
590
|
+
throw new TaskpackError('TASKPACK_UNTRUSTED_INTERPOLATION', `interpolation expression is not permitted at "${astPath}"`, astPath || '/');
|
|
591
|
+
}
|
|
592
|
+
let cursor = 0;
|
|
593
|
+
let result = '';
|
|
594
|
+
while (cursor < text.length) {
|
|
595
|
+
const start = text.indexOf('${', cursor);
|
|
596
|
+
if (start === -1) {
|
|
597
|
+
result += text.slice(cursor);
|
|
598
|
+
break;
|
|
599
|
+
}
|
|
600
|
+
result += text.slice(cursor, start);
|
|
601
|
+
const end = text.indexOf('}', start + 2);
|
|
602
|
+
if (end === -1) {
|
|
603
|
+
throw new TaskpackError('TASKPACK_UNTRUSTED_INTERPOLATION', `unterminated \${...} interpolation expression at "${astPath}"`, astPath || '/');
|
|
604
|
+
}
|
|
605
|
+
const varName = text.slice(start + 2, end);
|
|
606
|
+
if (!COMMAND_ENV_NAME_PATTERN.test(varName) || !Object.hasOwn(vars, varName)) {
|
|
607
|
+
throw new TaskpackError('TASKPACK_UNTRUSTED_INTERPOLATION', `undeclared interpolation variable "\${${varName}}" at "${astPath}"`, astPath || '/');
|
|
608
|
+
}
|
|
609
|
+
result += vars[varName];
|
|
610
|
+
cursor = end + 1;
|
|
611
|
+
}
|
|
612
|
+
if (result.includes('${')) {
|
|
613
|
+
throw new TaskpackError('TASKPACK_UNTRUSTED_INTERPOLATION', `interpolated value at "${astPath}" must not synthesize a "\${...}" expression`, astPath || '/');
|
|
614
|
+
}
|
|
615
|
+
if (result.length > MAX_STRING) {
|
|
616
|
+
manifestInvalid(`interpolated value at "${astPath}" exceeds ${MAX_STRING} characters`, astPath || '/');
|
|
617
|
+
}
|
|
618
|
+
return interpolate ? result : text;
|
|
619
|
+
}
|
|
620
|
+
function walkAstForInterpolation(node, vars, astPath, interpolate, skipValidatedSpecVars = false, depth = 0) {
|
|
621
|
+
if (depth > MAX_DEPTH) {
|
|
622
|
+
manifestInvalid('manifest exceeds maximum nesting depth during AST validation', astPath || '/');
|
|
623
|
+
}
|
|
624
|
+
if (typeof node === 'string') {
|
|
625
|
+
return validateAndInterpolateString(node, vars, astPath, interpolate);
|
|
626
|
+
}
|
|
627
|
+
if (Array.isArray(node)) {
|
|
628
|
+
if (!interpolate) {
|
|
629
|
+
for (const [idx, item] of node.entries()) {
|
|
630
|
+
walkAstForInterpolation(item, vars, `${astPath}/${idx}`, false, skipValidatedSpecVars, depth + 1);
|
|
631
|
+
}
|
|
632
|
+
return node;
|
|
633
|
+
}
|
|
634
|
+
return node.map((item, idx) => walkAstForInterpolation(item, vars, `${astPath}/${idx}`, true, skipValidatedSpecVars, depth + 1));
|
|
635
|
+
}
|
|
636
|
+
if (node !== null && typeof node === 'object') {
|
|
637
|
+
const proto = Object.getPrototypeOf(node);
|
|
638
|
+
if (proto !== Object.prototype && proto !== null) {
|
|
639
|
+
manifestInvalid('expected an object', astPath || '/');
|
|
640
|
+
}
|
|
641
|
+
const record = node;
|
|
642
|
+
const out = interpolate ? Object.create(null) : null;
|
|
643
|
+
for (const [key, val] of Object.entries(record)) {
|
|
644
|
+
if (key.includes('${')) {
|
|
645
|
+
throw new TaskpackError('TASKPACK_UNTRUSTED_INTERPOLATION', `interpolation expression is not permitted in object key "${key}"`, `${astPath}/${key}`);
|
|
646
|
+
}
|
|
647
|
+
const childPath = `${astPath}/${key}`;
|
|
648
|
+
if (skipValidatedSpecVars && childPath === '/spec/vars') {
|
|
649
|
+
if (out !== null)
|
|
650
|
+
out[key] = val;
|
|
651
|
+
continue;
|
|
652
|
+
}
|
|
653
|
+
const visited = walkAstForInterpolation(val, vars, childPath, interpolate, skipValidatedSpecVars, depth + 1);
|
|
654
|
+
if (out !== null)
|
|
655
|
+
out[key] = visited;
|
|
656
|
+
}
|
|
657
|
+
return out ?? node;
|
|
658
|
+
}
|
|
659
|
+
return node;
|
|
660
|
+
}
|
|
661
|
+
/**
|
|
662
|
+
* Parse manifest bytes in the named format and perform post-parse AST interpolation validation.
|
|
663
|
+
* Oversized or non-UTF-8 input is refused before parsing; undeclared or disallowed `${...}` expressions
|
|
664
|
+
* fail closed with `TASKPACK_UNTRUSTED_INTERPOLATION`.
|
|
665
|
+
*/
|
|
666
|
+
export function parseTaskpackDocument(bytes, format) {
|
|
667
|
+
if (bytes.byteLength > TASKPACK_MANIFEST_BYTES) {
|
|
668
|
+
throw new TaskpackError('TASKPACK_MANIFEST_INVALID', `manifest exceeds ${TASKPACK_MANIFEST_BYTES} bytes`, '/');
|
|
669
|
+
}
|
|
670
|
+
const source = decodeText(bytes);
|
|
671
|
+
const parsed = format === 'json' ? parseJsonSubset(source) : parseYamlDocument(source);
|
|
672
|
+
const emptyVars = Object.freeze(Object.create(null));
|
|
673
|
+
let vars = emptyVars;
|
|
674
|
+
let validatedSpecVars = false;
|
|
675
|
+
if (isPlainObjectRecord(parsed) && parsed['kind'] === 'Taskpack' && isPlainObjectRecord(parsed['spec'])) {
|
|
676
|
+
const rawVars = parsed['spec']['vars'];
|
|
677
|
+
if (rawVars !== undefined) {
|
|
678
|
+
vars = validateSpecVarsRecord(rawVars, '/spec/vars');
|
|
679
|
+
validatedSpecVars = true;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
walkAstForInterpolation(parsed, vars, '', false, validatedSpecVars);
|
|
683
|
+
return parsed;
|
|
684
|
+
}
|
|
685
|
+
// ---------------------------------------------------------------------------
|
|
686
|
+
// Path guards and scope helpers
|
|
687
|
+
// ---------------------------------------------------------------------------
|
|
688
|
+
/** Validate a manifest-declared relative path: strict `@loopwright/core` segment grammar, no traversal, no absolutes. */
|
|
689
|
+
export function normalizeRelativePath(input, path) {
|
|
690
|
+
// Cap at 1021 characters so appending `/**` during scope compilation never exceeds LIMITS.path (1024).
|
|
691
|
+
if (typeof input !== 'string' || input.length === 0 || input.length > 1021) {
|
|
692
|
+
manifestInvalid('path must be a non-empty string of at most 1021 characters', path);
|
|
693
|
+
}
|
|
694
|
+
if (input.includes('\0') || input.includes('\\') || input.includes(':'))
|
|
695
|
+
manifestInvalid('path contains forbidden characters', path);
|
|
696
|
+
if (input.startsWith('/'))
|
|
697
|
+
manifestInvalid('path must be relative', path);
|
|
698
|
+
const segments = input.split('/');
|
|
699
|
+
if (segments.length > 64)
|
|
700
|
+
manifestInvalid('path exceeds 64 segments', path);
|
|
701
|
+
for (const segment of segments) {
|
|
702
|
+
if (segment === '' || segment === '.' || segment === '..' || segment.endsWith('.')) {
|
|
703
|
+
manifestInvalid(`path segment "${segment}" is not allowed`, path);
|
|
704
|
+
}
|
|
705
|
+
if (!PATH_SEGMENT_PATTERN.test(segment)) {
|
|
706
|
+
manifestInvalid(`path segment "${segment}" contains invalid characters`, path);
|
|
707
|
+
}
|
|
708
|
+
if (RESERVED_DEVICE_NAME_PATTERN.test(segment)) {
|
|
709
|
+
manifestInvalid(`path segment "${segment}" is a reserved device name`, path);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
return input;
|
|
713
|
+
}
|
|
714
|
+
export function tryNormalizeRelativePath(input) {
|
|
715
|
+
if (typeof input !== 'string' || input.length === 0 || input.length > 1021)
|
|
716
|
+
return undefined;
|
|
717
|
+
if (input.includes('\0') || input.includes('\\') || input.includes(':') || input.startsWith('/'))
|
|
718
|
+
return undefined;
|
|
719
|
+
const segments = input.split('/');
|
|
720
|
+
if (segments.length > 64)
|
|
721
|
+
return undefined;
|
|
722
|
+
for (const segment of segments) {
|
|
723
|
+
if (segment === '' || segment === '.' || segment === '..' || segment.endsWith('.'))
|
|
724
|
+
return undefined;
|
|
725
|
+
if (!PATH_SEGMENT_PATTERN.test(segment))
|
|
726
|
+
return undefined;
|
|
727
|
+
if (RESERVED_DEVICE_NAME_PATTERN.test(segment))
|
|
728
|
+
return undefined;
|
|
729
|
+
}
|
|
730
|
+
return input;
|
|
731
|
+
}
|
|
732
|
+
function deriveControlRoot(relativeTaskpackPath) {
|
|
733
|
+
if (relativeTaskpackPath === undefined)
|
|
734
|
+
return '.loopwright';
|
|
735
|
+
const dir = posix.dirname(relativeTaskpackPath);
|
|
736
|
+
return dir === '.' || dir === '' ? '.loopwright' : dir;
|
|
737
|
+
}
|
|
738
|
+
/** Resolve the control root and optional repository-relative manifest path for a validated manifest. */
|
|
739
|
+
export function resolveManifestControlRoot(manifest, taskpackPath) {
|
|
740
|
+
const normalized = taskpackPath === undefined
|
|
741
|
+
? undefined
|
|
742
|
+
: normalizeRelativePath(posix.normalize(taskpackPath.replace(/\\/g, '/')), '/');
|
|
743
|
+
if (normalized !== undefined) {
|
|
744
|
+
const expectedControlRoot = deriveControlRoot(normalized);
|
|
745
|
+
if ((manifest.controlRoot !== undefined && manifest.controlRoot !== expectedControlRoot) ||
|
|
746
|
+
(manifest.manifestPath !== undefined && manifest.manifestPath !== normalized)) {
|
|
747
|
+
throw new TaskpackError('TASKPACK_HOST_BINDING_INVALID', 'bindings.taskpackPath conflicts with manifest controlRoot or manifestPath', '/taskpackPath');
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
if (manifest.controlRoot !== undefined) {
|
|
751
|
+
return {
|
|
752
|
+
controlRoot: manifest.controlRoot,
|
|
753
|
+
...(manifest.manifestPath !== undefined
|
|
754
|
+
? { manifestPath: manifest.manifestPath }
|
|
755
|
+
: normalized !== undefined
|
|
756
|
+
? { manifestPath: normalized }
|
|
757
|
+
: {}),
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
if (normalized !== undefined) {
|
|
761
|
+
return { controlRoot: deriveControlRoot(normalized), manifestPath: normalized };
|
|
762
|
+
}
|
|
763
|
+
return { controlRoot: '.loopwright' };
|
|
764
|
+
}
|
|
765
|
+
/** Validate a Taskpack 2.0 scope pattern (exact path, explicit `dir/**`, or single-segment `*`/`?` glob) via `@loopwright/core`. */
|
|
766
|
+
export function normalizeScopePattern(input, path) {
|
|
767
|
+
if (typeof input !== 'string' || input.length === 0 || input.length > LIMITS.path) {
|
|
768
|
+
manifestInvalid(`scope pattern must be a non-empty string of at most ${LIMITS.path} characters`, path);
|
|
769
|
+
}
|
|
770
|
+
if (input === '**') {
|
|
771
|
+
manifestInvalid('unbounded "**" scope pattern is not allowed in manifest scope declarations', path);
|
|
772
|
+
}
|
|
773
|
+
const validated = validateScopePattern(input);
|
|
774
|
+
if (!validated.ok) {
|
|
775
|
+
manifestInvalid(`invalid scope pattern "${input}": ${validated.errors[0]?.code ?? 'PATTERN_UNSUPPORTED'}`, path);
|
|
776
|
+
}
|
|
777
|
+
return validated.value;
|
|
778
|
+
}
|
|
779
|
+
/** True when `candidate` equals `root` or lives underneath it. */
|
|
780
|
+
export function pathCoveredBy(candidate, root) {
|
|
781
|
+
return candidate === root || candidate.startsWith(root.endsWith('/') ? root : `${root}/`);
|
|
782
|
+
}
|
|
783
|
+
export function pathCoveredByCaseInsensitive(candidate, root) {
|
|
784
|
+
return pathCoveredBy(candidate.normalize('NFC').toLowerCase(), root.normalize('NFC').toLowerCase());
|
|
785
|
+
}
|
|
786
|
+
/** Exact polynomial-time check for whether two single-segment `*`/`?` patterns share any matching non-empty segment. */
|
|
787
|
+
function segmentsMayIntersect(a, b) {
|
|
788
|
+
const m = a.length;
|
|
789
|
+
const n = b.length;
|
|
790
|
+
const memo = new Int8Array((m + 1) * (n + 1));
|
|
791
|
+
const solve = (i, j) => {
|
|
792
|
+
const idx = i * (n + 1) + j;
|
|
793
|
+
if (memo[idx] !== 0)
|
|
794
|
+
return memo[idx] === 1;
|
|
795
|
+
let res = false;
|
|
796
|
+
if (i === m && j === n) {
|
|
797
|
+
res = true;
|
|
798
|
+
}
|
|
799
|
+
else if (i < m && a[i] === '*') {
|
|
800
|
+
res = solve(i + 1, j) || (j < n && solve(i, j + 1));
|
|
801
|
+
}
|
|
802
|
+
else if (j < n && b[j] === '*') {
|
|
803
|
+
res = solve(i, j + 1) || (i < m && solve(i + 1, j));
|
|
804
|
+
}
|
|
805
|
+
else if (i < m && j < n && (a[i] === '?' || b[j] === '?' || a[i] === b[j])) {
|
|
806
|
+
res = solve(i + 1, j + 1);
|
|
807
|
+
}
|
|
808
|
+
memo[idx] = res ? 1 : -1;
|
|
809
|
+
return res;
|
|
810
|
+
};
|
|
811
|
+
return solve(0, 0);
|
|
812
|
+
}
|
|
813
|
+
function splitScopePattern(pattern, caseInsensitive) {
|
|
814
|
+
const norm = caseInsensitive ? pattern.normalize('NFC').toLowerCase() : pattern;
|
|
815
|
+
if (norm === '**')
|
|
816
|
+
return { segments: [], recursive: true };
|
|
817
|
+
const recursive = norm.endsWith('/**');
|
|
818
|
+
const body = recursive ? norm.slice(0, -3) : norm;
|
|
819
|
+
return { segments: body.split('/'), recursive };
|
|
820
|
+
}
|
|
821
|
+
/** True when two scope patterns could match at least one common repository path. */
|
|
822
|
+
function scopePatternsMayIntersect(patternA, patternB, caseInsensitive = false) {
|
|
823
|
+
const a = splitScopePattern(patternA, caseInsensitive);
|
|
824
|
+
const b = splitScopePattern(patternB, caseInsensitive);
|
|
825
|
+
const maxLen = Math.max(a.segments.length, b.segments.length);
|
|
826
|
+
for (let k = 0; k < maxLen; k++) {
|
|
827
|
+
if (k >= a.segments.length)
|
|
828
|
+
return a.recursive;
|
|
829
|
+
if (k >= b.segments.length)
|
|
830
|
+
return b.recursive;
|
|
831
|
+
if (!segmentsMayIntersect(a.segments[k], b.segments[k]))
|
|
832
|
+
return false;
|
|
833
|
+
}
|
|
834
|
+
return true;
|
|
835
|
+
}
|
|
836
|
+
/** Exact polynomial-time check for whether every segment matched by `a` is also matched by `b`. */
|
|
837
|
+
function segmentSubsetOf(a, b) {
|
|
838
|
+
const m = a.length;
|
|
839
|
+
const n = b.length;
|
|
840
|
+
const memo = new Int8Array((m + 1) * (n + 1));
|
|
841
|
+
const solve = (i, j) => {
|
|
842
|
+
const idx = i * (n + 1) + j;
|
|
843
|
+
if (memo[idx] !== 0)
|
|
844
|
+
return memo[idx] === 1;
|
|
845
|
+
let res = false;
|
|
846
|
+
if (i === m && j === n) {
|
|
847
|
+
res = true;
|
|
848
|
+
}
|
|
849
|
+
else if (j < n && b[j] === '*') {
|
|
850
|
+
res = solve(i, j + 1) || (i < m && solve(i + 1, j));
|
|
851
|
+
}
|
|
852
|
+
else if (i < m && j < n && a[i] !== '*' && (b[j] === '?' || a[i] === b[j])) {
|
|
853
|
+
res = solve(i + 1, j + 1);
|
|
854
|
+
}
|
|
855
|
+
memo[idx] = res ? 1 : -1;
|
|
856
|
+
return res;
|
|
857
|
+
};
|
|
858
|
+
return solve(0, 0);
|
|
859
|
+
}
|
|
860
|
+
/** True when every repository path matched by `sub` is also matched by `sup`. */
|
|
861
|
+
function scopePatternSubsetOf(sub, sup, caseInsensitive = false) {
|
|
862
|
+
const a = splitScopePattern(sub, caseInsensitive);
|
|
863
|
+
const b = splitScopePattern(sup, caseInsensitive);
|
|
864
|
+
if (b.recursive) {
|
|
865
|
+
if (a.segments.length < b.segments.length)
|
|
866
|
+
return false;
|
|
867
|
+
for (let k = 0; k < b.segments.length; k++) {
|
|
868
|
+
if (!segmentSubsetOf(a.segments[k], b.segments[k]))
|
|
869
|
+
return false;
|
|
870
|
+
}
|
|
871
|
+
return true;
|
|
872
|
+
}
|
|
873
|
+
if (a.recursive || a.segments.length !== b.segments.length)
|
|
874
|
+
return false;
|
|
875
|
+
for (let k = 0; k < b.segments.length; k++) {
|
|
876
|
+
if (!segmentSubsetOf(a.segments[k], b.segments[k]))
|
|
877
|
+
return false;
|
|
878
|
+
}
|
|
879
|
+
return true;
|
|
880
|
+
}
|
|
881
|
+
function asProtectedSubtreePattern(protectedEntry) {
|
|
882
|
+
if (protectedEntry === '**' || protectedEntry.endsWith('/**'))
|
|
883
|
+
return protectedEntry;
|
|
884
|
+
return `${protectedEntry}/**`;
|
|
885
|
+
}
|
|
886
|
+
/** True when a scope pattern targets exclusively `.github/workflows` or paths inside it. */
|
|
887
|
+
function isWorkflowSubpathPattern(pattern) {
|
|
888
|
+
const base = pattern.endsWith('/**') ? pattern.slice(0, -3) : pattern;
|
|
889
|
+
return base === '.github/workflows' || base.startsWith('.github/workflows/');
|
|
890
|
+
}
|
|
891
|
+
function isWorkflowSubpathCaseInsensitive(pattern) {
|
|
892
|
+
const norm = pattern.normalize('NFC').toLowerCase();
|
|
893
|
+
const base = norm.endsWith('/**') ? norm.slice(0, -3) : norm;
|
|
894
|
+
return base === '.github/workflows' || base.startsWith('.github/workflows/');
|
|
895
|
+
}
|
|
896
|
+
function writableEntryOverlapsProtected(writablePattern, protectedEntry, allowWorkflowWrites, isBuiltInProtected) {
|
|
897
|
+
if (allowWorkflowWrites
|
|
898
|
+
&& isBuiltInProtected
|
|
899
|
+
&& (protectedEntry === '.github' || protectedEntry === '.github/**')
|
|
900
|
+
&& isWorkflowSubpathPattern(writablePattern)) {
|
|
901
|
+
return false;
|
|
902
|
+
}
|
|
903
|
+
const protectedSubtree = asProtectedSubtreePattern(protectedEntry);
|
|
904
|
+
return scopePatternsMayIntersect(writablePattern, protectedSubtree, false)
|
|
905
|
+
|| scopePatternsMayIntersect(writablePattern, protectedSubtree, true);
|
|
906
|
+
}
|
|
907
|
+
function writableScopeCoversPath(writableEntry, candidatePath, legacyPrefixFallback) {
|
|
908
|
+
const matched = matchesScopePattern(writableEntry, candidatePath);
|
|
909
|
+
if (matched.ok && matched.value)
|
|
910
|
+
return true;
|
|
911
|
+
if (legacyPrefixFallback && !writableEntry.includes('*') && !writableEntry.includes('?')) {
|
|
912
|
+
return pathCoveredBy(candidatePath, writableEntry);
|
|
913
|
+
}
|
|
914
|
+
return false;
|
|
915
|
+
}
|
|
916
|
+
/** Extract the repository-relative path from a plain string or conditional resource entry. */
|
|
917
|
+
export function resolveTaskpackResourcePath(entry) {
|
|
918
|
+
return typeof entry === 'string' ? entry : entry.path;
|
|
919
|
+
}
|
|
920
|
+
/** Extract repository-relative paths from a list of plain string or conditional resource entries. */
|
|
921
|
+
export function extractTaskpackResourcePaths(entries) {
|
|
922
|
+
if (entries === undefined || entries.length === 0)
|
|
923
|
+
return Object.freeze([]);
|
|
924
|
+
return Object.freeze(entries.map(resolveTaskpackResourcePath));
|
|
925
|
+
}
|
|
926
|
+
/** Extract the optional `when` activation rule from a plain string or conditional resource entry. */
|
|
927
|
+
export function resolveTaskpackResourceWhen(entry) {
|
|
928
|
+
return typeof entry === 'string' ? undefined : entry.when;
|
|
929
|
+
}
|
|
930
|
+
/** Deterministic canonical key for comparing two optional `ResourceActivationRule` predicates. */
|
|
931
|
+
export function canonicalizeResourceActivationRule(when) {
|
|
932
|
+
if (when === undefined)
|
|
933
|
+
return 'UNCONDITIONAL';
|
|
934
|
+
const normalized = {};
|
|
935
|
+
if (when.changedPaths !== undefined)
|
|
936
|
+
normalized['changedPaths'] = [...when.changedPaths].sort();
|
|
937
|
+
if (when.extensions !== undefined)
|
|
938
|
+
normalized['extensions'] = [...when.extensions].sort();
|
|
939
|
+
if (when.phases !== undefined)
|
|
940
|
+
normalized['phases'] = [...when.phases].sort();
|
|
941
|
+
if (when.failedChecks !== undefined)
|
|
942
|
+
normalized['failedChecks'] = [...when.failedChecks].sort();
|
|
943
|
+
if (when.failureCodes !== undefined)
|
|
944
|
+
normalized['failureCodes'] = [...when.failureCodes].sort();
|
|
945
|
+
return JSON.stringify(normalized);
|
|
946
|
+
}
|
|
947
|
+
function resolveUntrustedResourceEntryPath(entry, diagPath) {
|
|
948
|
+
if (typeof entry === 'string')
|
|
949
|
+
return normalizeRelativePath(entry, diagPath);
|
|
950
|
+
if (isPlainObjectRecord(entry) && Object.hasOwn(entry, 'path')) {
|
|
951
|
+
return normalizeRelativePath(entry['path'], `${diagPath}/path`);
|
|
952
|
+
}
|
|
953
|
+
manifestInvalid('resource entry must be a relative path string or { path, when } object', diagPath);
|
|
954
|
+
}
|
|
955
|
+
function automationPathsFor(policyProfile, allowWorkflowWrites) {
|
|
956
|
+
if (policyProfile === 'local') {
|
|
957
|
+
return LOCAL_PROTECTED_AUTOMATION_PATHS;
|
|
958
|
+
}
|
|
959
|
+
if (!allowWorkflowWrites)
|
|
960
|
+
return GITHUB_PROTECTED_AUTOMATION_PATHS;
|
|
961
|
+
return GITHUB_PROTECTED_AUTOMATION_PATHS.filter(entry => entry !== '.github');
|
|
962
|
+
}
|
|
963
|
+
function commandScriptOutsideParentDir(script, controlRoot) {
|
|
964
|
+
const slash = script.lastIndexOf('/');
|
|
965
|
+
if (slash <= 0)
|
|
966
|
+
return undefined;
|
|
967
|
+
const parent = script.slice(0, slash);
|
|
968
|
+
if (pathCoveredBy(parent, controlRoot) || pathCoveredByCaseInsensitive(parent, controlRoot)) {
|
|
969
|
+
return undefined;
|
|
970
|
+
}
|
|
971
|
+
return parent;
|
|
972
|
+
}
|
|
973
|
+
function explicitProtectedPathsWithoutControlRoot(manifestProtected, options) {
|
|
974
|
+
const policyProfile = resolvePolicyProfile(options.policyProfile, undefined);
|
|
975
|
+
const controlRoot = options.controlRoot ?? '.loopwright';
|
|
976
|
+
const allowWorkflowWrites = policyProfile === 'github' && options.allowWorkflowWrites === true;
|
|
977
|
+
const baseSet = new Set([
|
|
978
|
+
...automationPathsFor(policyProfile, allowWorkflowWrites),
|
|
979
|
+
`${controlRoot}/policies`,
|
|
980
|
+
`${controlRoot}/checks`,
|
|
981
|
+
`${controlRoot}/scripts`,
|
|
982
|
+
`${controlRoot}/memory`,
|
|
983
|
+
`${controlRoot}/taskpack.yaml`,
|
|
984
|
+
`${controlRoot}/taskpack.yml`,
|
|
985
|
+
`${controlRoot}/taskpack.json`,
|
|
986
|
+
`${controlRoot}/digests.lock.json`,
|
|
987
|
+
]);
|
|
988
|
+
if (options.manifestPath !== undefined)
|
|
989
|
+
baseSet.add(options.manifestPath);
|
|
990
|
+
if (options.digestsLockfile !== undefined)
|
|
991
|
+
baseSet.add(options.digestsLockfile);
|
|
992
|
+
if (options.extraProtectedPaths !== undefined) {
|
|
993
|
+
for (const extra of options.extraProtectedPaths)
|
|
994
|
+
baseSet.add(extra);
|
|
995
|
+
}
|
|
996
|
+
if (options.instructions !== undefined) {
|
|
997
|
+
for (const instruction of options.instructions)
|
|
998
|
+
baseSet.add(resolveTaskpackResourcePath(instruction));
|
|
999
|
+
}
|
|
1000
|
+
if (options.skills !== undefined) {
|
|
1001
|
+
for (const skill of options.skills)
|
|
1002
|
+
baseSet.add(resolveTaskpackResourcePath(skill));
|
|
1003
|
+
}
|
|
1004
|
+
if (options.preflightScript !== undefined)
|
|
1005
|
+
baseSet.add(options.preflightScript);
|
|
1006
|
+
if (options.commandScripts !== undefined) {
|
|
1007
|
+
for (const script of options.commandScripts) {
|
|
1008
|
+
baseSet.add(script);
|
|
1009
|
+
const parentDir = commandScriptOutsideParentDir(script, controlRoot);
|
|
1010
|
+
if (parentDir !== undefined)
|
|
1011
|
+
baseSet.add(parentDir);
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
if (options.toolchainPaths !== undefined) {
|
|
1015
|
+
for (const entry of options.toolchainPaths) {
|
|
1016
|
+
if (!entry.startsWith('/'))
|
|
1017
|
+
baseSet.add(entry);
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
for (const entry of manifestProtected)
|
|
1021
|
+
baseSet.add(entry);
|
|
1022
|
+
if (options.priorityControlRootSiblings !== undefined) {
|
|
1023
|
+
for (const sibling of options.priorityControlRootSiblings)
|
|
1024
|
+
baseSet.add(sibling);
|
|
1025
|
+
}
|
|
1026
|
+
if (policyProfile === 'github' && allowWorkflowWrites && options.githubSiblings !== undefined) {
|
|
1027
|
+
for (const sibling of options.githubSiblings) {
|
|
1028
|
+
if (isWorkflowSubpathCaseInsensitive(sibling))
|
|
1029
|
+
continue;
|
|
1030
|
+
if (baseSet.size >= 128)
|
|
1031
|
+
break;
|
|
1032
|
+
baseSet.add(sibling);
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
if (options.controlRootSiblings !== undefined) {
|
|
1036
|
+
for (const sibling of options.controlRootSiblings) {
|
|
1037
|
+
if (baseSet.size >= 128)
|
|
1038
|
+
break;
|
|
1039
|
+
baseSet.add(sibling);
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
return Object.freeze([...baseSet]);
|
|
1043
|
+
}
|
|
1044
|
+
/**
|
|
1045
|
+
* True when `proposalPath` is a valid `.yaml`/`.yml`/`.json` file strictly inside `controlRoot`
|
|
1046
|
+
* that does not overlap any built-in or manifest control-plane path.
|
|
1047
|
+
*/
|
|
1048
|
+
export function canCarveOutControlRootProposal(proposalPath, controlRoot, explicitProtectedPaths) {
|
|
1049
|
+
if (proposalPath === undefined)
|
|
1050
|
+
return false;
|
|
1051
|
+
if (tryNormalizeRelativePath(proposalPath) !== proposalPath)
|
|
1052
|
+
return false;
|
|
1053
|
+
if (tryNormalizeRelativePath(controlRoot) !== controlRoot)
|
|
1054
|
+
return false;
|
|
1055
|
+
if (!/\.(?:yaml|yml|json)$/i.test(proposalPath))
|
|
1056
|
+
return false;
|
|
1057
|
+
if (proposalPath === controlRoot || !pathCoveredBy(proposalPath, controlRoot))
|
|
1058
|
+
return false;
|
|
1059
|
+
for (const protectedPath of explicitProtectedPaths) {
|
|
1060
|
+
const protectedSubtree = asProtectedSubtreePattern(protectedPath);
|
|
1061
|
+
if (scopePatternsMayIntersect(proposalPath, protectedSubtree, false)
|
|
1062
|
+
|| scopePatternsMayIntersect(proposalPath, protectedSubtree, true)) {
|
|
1063
|
+
return false;
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
return true;
|
|
1067
|
+
}
|
|
1068
|
+
/**
|
|
1069
|
+
* True when `proposalPath` inside `controlRoot` is eligible for carve-out AND `writable`
|
|
1070
|
+
* reaches `controlRoot` exclusively via the exact `proposalPath` file entry.
|
|
1071
|
+
*/
|
|
1072
|
+
export function isControlRootProposalWritableAllowed(proposalPath, writable, controlRoot, explicitProtectedPaths = []) {
|
|
1073
|
+
if (!canCarveOutControlRootProposal(proposalPath, controlRoot, explicitProtectedPaths))
|
|
1074
|
+
return false;
|
|
1075
|
+
if (writable.length === 0 || !writable.includes(proposalPath))
|
|
1076
|
+
return false;
|
|
1077
|
+
const controlRootSubtree = `${controlRoot}/**`;
|
|
1078
|
+
for (const entry of writable) {
|
|
1079
|
+
if (!validateScopePattern(entry).ok)
|
|
1080
|
+
return false;
|
|
1081
|
+
if (entry === proposalPath)
|
|
1082
|
+
continue;
|
|
1083
|
+
if (scopePatternsMayIntersect(entry, controlRootSubtree, false) || scopePatternsMayIntersect(entry, controlRootSubtree, true)) {
|
|
1084
|
+
return false;
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
return true;
|
|
1088
|
+
}
|
|
1089
|
+
/** The manifest-protected set merged with profile-scoped built-in paths and the active control root. */
|
|
1090
|
+
export function effectiveProtectedPaths(manifestProtected, options = {}) {
|
|
1091
|
+
const policyProfile = resolvePolicyProfile(options.policyProfile, undefined);
|
|
1092
|
+
const controlRoot = options.controlRoot ?? '.loopwright';
|
|
1093
|
+
const allowWorkflowWrites = policyProfile === 'github' && options.allowWorkflowWrites === true;
|
|
1094
|
+
const explicit = explicitProtectedPathsWithoutControlRoot(manifestProtected, options);
|
|
1095
|
+
if (canCarveOutControlRootProposal(options.proposalPath, controlRoot, explicit)) {
|
|
1096
|
+
return explicit;
|
|
1097
|
+
}
|
|
1098
|
+
const items = [
|
|
1099
|
+
...automationPathsFor(policyProfile, allowWorkflowWrites),
|
|
1100
|
+
controlRoot,
|
|
1101
|
+
...explicit,
|
|
1102
|
+
];
|
|
1103
|
+
return Object.freeze([...new Set(items)]);
|
|
1104
|
+
}
|
|
1105
|
+
/** Resolve effective protected paths directly from a validated manifest (defaulting to `'local'` profile). */
|
|
1106
|
+
export function resolveEffectiveProtectedPaths(manifest, options = {}) {
|
|
1107
|
+
const controlRoot = options.controlRoot ?? manifest.controlRoot ?? '.loopwright';
|
|
1108
|
+
const manifestPath = options.manifestPath ?? manifest.manifestPath;
|
|
1109
|
+
const instructions = extractTaskpackResourcePaths(options.instructions ?? [
|
|
1110
|
+
...(manifest.spec.instructions ?? []),
|
|
1111
|
+
...(manifest.spec.roles ?? []).flatMap(role => role.instructions ?? []),
|
|
1112
|
+
]);
|
|
1113
|
+
const skills = extractTaskpackResourcePaths(options.skills ?? [
|
|
1114
|
+
...(manifest.spec.skills ?? []),
|
|
1115
|
+
...(manifest.spec.roles ?? []).flatMap(role => role.skills ?? []),
|
|
1116
|
+
]);
|
|
1117
|
+
const commandScripts = options.commandScripts ?? manifest.spec.verification.localChecks
|
|
1118
|
+
.filter(c => c.implementation === 'command.v1')
|
|
1119
|
+
.map(c => c.parameters?.['script'])
|
|
1120
|
+
.filter((s) => typeof s === 'string' && s.length > 0);
|
|
1121
|
+
const toolchainPaths = options.toolchainPaths ?? manifest.spec.verification.localChecks
|
|
1122
|
+
.flatMap(c => (c.implementation === 'command.v1' && Array.isArray(c.parameters?.['toolchainPaths'])
|
|
1123
|
+
? c.parameters['toolchainPaths'].filter((entry) => typeof entry === 'string' && entry.length > 0 && !entry.startsWith('/'))
|
|
1124
|
+
: []));
|
|
1125
|
+
return effectiveProtectedPaths(manifest.spec.scope.protected, {
|
|
1126
|
+
...options,
|
|
1127
|
+
controlRoot,
|
|
1128
|
+
manifestPath,
|
|
1129
|
+
digestsLockfile: options.digestsLockfile ?? manifest.spec.execution?.digests.lockfile,
|
|
1130
|
+
instructions: instructions.length > 0 ? instructions : undefined,
|
|
1131
|
+
skills: skills.length > 0 ? skills : undefined,
|
|
1132
|
+
preflightScript: options.preflightScript ?? manifest.spec.preflight?.script,
|
|
1133
|
+
commandScripts: commandScripts.length > 0 ? commandScripts : undefined,
|
|
1134
|
+
toolchainPaths: toolchainPaths.length > 0 ? toolchainPaths : undefined,
|
|
1135
|
+
proposalPath: options.proposalPath ?? manifest.spec.proposal?.path,
|
|
1136
|
+
});
|
|
1137
|
+
}
|
|
1138
|
+
function resolveProtectedPathSets(manifestProtected, options) {
|
|
1139
|
+
const policyProfile = resolvePolicyProfile(options.policyProfile, undefined);
|
|
1140
|
+
const controlRoot = options.controlRoot ?? '.loopwright';
|
|
1141
|
+
const allowWorkflowWrites = policyProfile === 'github' && options.allowWorkflowWrites === true;
|
|
1142
|
+
const explicitWithManifest = explicitProtectedPathsWithoutControlRoot(manifestProtected, options);
|
|
1143
|
+
const carvedOut = canCarveOutControlRootProposal(options.proposalPath, controlRoot, explicitWithManifest);
|
|
1144
|
+
const allProtected = carvedOut
|
|
1145
|
+
? explicitWithManifest
|
|
1146
|
+
: Object.freeze([...new Set([...automationPathsFor(policyProfile, allowWorkflowWrites), controlRoot, ...explicitWithManifest])]);
|
|
1147
|
+
const mandatoryWithoutControlRoot = explicitProtectedPathsWithoutControlRoot([], options);
|
|
1148
|
+
const mandatoryProtectedSet = new Set(mandatoryWithoutControlRoot);
|
|
1149
|
+
if (!carvedOut)
|
|
1150
|
+
mandatoryProtectedSet.add(controlRoot);
|
|
1151
|
+
return { allProtected, mandatoryProtectedSet, explicitWithManifest };
|
|
1152
|
+
}
|
|
1153
|
+
function assertWritablesDisjointFromProtected(writable, allProtected, mandatoryProtectedSet, controlRoot, proposalPath, policyProfile, allowWorkflowWrites) {
|
|
1154
|
+
const controlRootSubtree = `${controlRoot}/**`;
|
|
1155
|
+
const githubAllowWorkflows = policyProfile === 'github' && allowWorkflowWrites;
|
|
1156
|
+
for (const [index, entry] of writable.entries()) {
|
|
1157
|
+
const covering = allProtected.find(protectedPath => {
|
|
1158
|
+
if (mandatoryProtectedSet.has(protectedPath)) {
|
|
1159
|
+
return writableEntryOverlapsProtected(entry, protectedPath, githubAllowWorkflows, true);
|
|
1160
|
+
}
|
|
1161
|
+
// A broad writable pattern may encompass narrower user-only `protected` exclusions (blacklist wins),
|
|
1162
|
+
// so reject only when the writable pattern is a glob/case-insensitive subset of the protected pattern.
|
|
1163
|
+
const protectedSubtree = asProtectedSubtreePattern(protectedPath);
|
|
1164
|
+
return scopePatternSubsetOf(entry, protectedSubtree, false)
|
|
1165
|
+
|| scopePatternSubsetOf(entry, protectedSubtree, true);
|
|
1166
|
+
});
|
|
1167
|
+
if (covering !== undefined) {
|
|
1168
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `writable path "${entry}" overlaps protected path "${covering}"`, `/spec/scope/writable/${index}`);
|
|
1169
|
+
}
|
|
1170
|
+
if (githubAllowWorkflows && writableEntryOverlapsProtected(entry, '.github', true, true)) {
|
|
1171
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `writable path "${entry}" overlaps protected path ".github"`, `/spec/scope/writable/${index}`);
|
|
1172
|
+
}
|
|
1173
|
+
if ((scopePatternsMayIntersect(entry, controlRootSubtree, false) || scopePatternsMayIntersect(entry, controlRootSubtree, true))
|
|
1174
|
+
&& entry !== proposalPath) {
|
|
1175
|
+
if (entry === controlRoot || scopePatternsMayIntersect(controlRoot, entry, false) || scopePatternsMayIntersect(controlRoot, entry, true)) {
|
|
1176
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `writable path "${entry}" encompasses protected control root "${controlRoot}"`, `/spec/scope/writable/${index}`);
|
|
1177
|
+
}
|
|
1178
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `writable path "${entry}" inside control root "${controlRoot}" must exactly match spec.proposal.path`, `/spec/scope/writable/${index}`);
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
/**
|
|
1183
|
+
* Re-validate `spec.scope` and optional `spec.proposal.path` against the resolved `(controlRoot, manifestPath)`
|
|
1184
|
+
* so callers passing in-memory or JSON-roundtripped manifests cannot bypass control-root or host-authority protection.
|
|
1185
|
+
*/
|
|
1186
|
+
export function assertManifestScopeInvariants(manifest, options) {
|
|
1187
|
+
const policyProfile = resolvePolicyProfile(options.policyProfile, options.hostPolicy?.policyProfile);
|
|
1188
|
+
const controlRoot = normalizeRelativePath(options.controlRoot, '/');
|
|
1189
|
+
const manifestPath = options.manifestPath !== undefined ? normalizeRelativePath(options.manifestPath, '/') : undefined;
|
|
1190
|
+
const proposalPath = manifest.spec.proposal !== undefined
|
|
1191
|
+
? normalizeRelativePath(manifest.spec.proposal.path, '/spec/proposal/path')
|
|
1192
|
+
: undefined;
|
|
1193
|
+
if (options.enforceHostAuthority !== false) {
|
|
1194
|
+
validateExecutionAuthority(manifest.spec.execution, options.hostPolicy, {
|
|
1195
|
+
localChecks: manifest.spec.verification.localChecks,
|
|
1196
|
+
});
|
|
1197
|
+
}
|
|
1198
|
+
const allowWorkflowWrites = (policyProfile === 'github'
|
|
1199
|
+
&& manifest.spec.execution?.capabilities.allowWorkflowWrites === true
|
|
1200
|
+
&& (options.enforceHostAuthority === false || options.hostPolicy?.allowWorkflowWrites === true));
|
|
1201
|
+
if (manifest.spec.sandbox?.networkMode === 'allow-outbound' && manifest.spec.execution?.capabilities.allowAgentNetwork !== true) {
|
|
1202
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', 'spec.sandbox.networkMode "allow-outbound" requires spec.execution.capabilities.allowAgentNetwork: true', '/spec/sandbox/networkMode');
|
|
1203
|
+
}
|
|
1204
|
+
const rawWritable = manifest.spec.scope.writable;
|
|
1205
|
+
const isSingleWildcardWritable = (options.allowWildcardWritableWhenControlRootProtected === true
|
|
1206
|
+
&& rawWritable.length === 1
|
|
1207
|
+
&& rawWritable[0] === '**');
|
|
1208
|
+
const writable = isSingleWildcardWritable
|
|
1209
|
+
? Object.freeze([])
|
|
1210
|
+
: rawWritable.map((entry, index) => normalizeScopePattern(entry, `/spec/scope/writable/${index}`));
|
|
1211
|
+
const manifestProtected = manifest.spec.scope.protected.map((entry, index) => (normalizeScopePattern(entry, `/spec/scope/protected/${index}`)));
|
|
1212
|
+
const manifestProtectedSet = new Set(manifestProtected);
|
|
1213
|
+
const instructions = [
|
|
1214
|
+
...(manifest.spec.instructions?.map((entry, index) => resolveUntrustedResourceEntryPath(entry, `/spec/instructions/${index}`)) ?? []),
|
|
1215
|
+
...(manifest.spec.roles?.flatMap((role, rIdx) => (role.instructions?.map((entry, iIdx) => resolveUntrustedResourceEntryPath(entry, `/spec/roles/${rIdx}/instructions/${iIdx}`)) ?? [])) ?? []),
|
|
1216
|
+
];
|
|
1217
|
+
const skills = [
|
|
1218
|
+
...(manifest.spec.skills?.map((entry, index) => resolveUntrustedResourceEntryPath(entry, `/spec/skills/${index}`)) ?? []),
|
|
1219
|
+
...(manifest.spec.roles?.flatMap((role, rIdx) => (role.skills?.map((entry, sIdx) => resolveUntrustedResourceEntryPath(entry, `/spec/roles/${rIdx}/skills/${sIdx}`)) ?? [])) ?? []),
|
|
1220
|
+
];
|
|
1221
|
+
const preflightScript = manifest.spec.preflight !== undefined
|
|
1222
|
+
? normalizeRelativePath(manifest.spec.preflight.script, '/spec/preflight/script')
|
|
1223
|
+
: undefined;
|
|
1224
|
+
const digestsLockfile = manifest.spec.execution?.digests.lockfile !== undefined
|
|
1225
|
+
? normalizeRelativePath(manifest.spec.execution.digests.lockfile, '/spec/execution/digests/lockfile')
|
|
1226
|
+
: undefined;
|
|
1227
|
+
const rawCommandScripts = options.commandScripts ?? manifest.spec.verification.localChecks
|
|
1228
|
+
.filter(c => c.implementation === 'command.v1')
|
|
1229
|
+
.map(c => c.parameters?.['script'])
|
|
1230
|
+
.filter((s) => typeof s === 'string' && s.length > 0);
|
|
1231
|
+
const commandScripts = rawCommandScripts.map((entry, index) => (normalizeRelativePath(entry, `/spec/verification/localChecks/${index}/parameters/script`)));
|
|
1232
|
+
const relativeToolchainPaths = [];
|
|
1233
|
+
for (const [cIdx, check] of manifest.spec.verification.localChecks.entries()) {
|
|
1234
|
+
if (check.implementation !== 'command.v1')
|
|
1235
|
+
continue;
|
|
1236
|
+
const rawToolchains = check.parameters?.['toolchainPaths'];
|
|
1237
|
+
if (!Array.isArray(rawToolchains))
|
|
1238
|
+
continue;
|
|
1239
|
+
for (const [tIdx, entry] of rawToolchains.entries()) {
|
|
1240
|
+
const validated = validateToolchainPath(entry, `/spec/verification/localChecks/${cIdx}/parameters/toolchainPaths/${tIdx}`);
|
|
1241
|
+
if (!validated.startsWith('/'))
|
|
1242
|
+
relativeToolchainPaths.push(validated);
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
const scriptPlacementProtected = effectiveProtectedPaths(manifestProtected, {
|
|
1246
|
+
policyProfile,
|
|
1247
|
+
controlRoot,
|
|
1248
|
+
manifestPath,
|
|
1249
|
+
instructions,
|
|
1250
|
+
skills,
|
|
1251
|
+
allowWorkflowWrites,
|
|
1252
|
+
githubSiblings: options.githubSiblings,
|
|
1253
|
+
});
|
|
1254
|
+
if (digestsLockfile !== undefined) {
|
|
1255
|
+
if (!scriptPlacementProtected.some(protectedPath => scopePatternsMayIntersect(digestsLockfile, asProtectedSubtreePattern(protectedPath), false))) {
|
|
1256
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `digest lockfile "${digestsLockfile}" must reside inside a protected path`, '/spec/execution/digests/lockfile');
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
if (preflightScript !== undefined) {
|
|
1260
|
+
if (!scriptPlacementProtected.some(protectedPath => scopePatternsMayIntersect(preflightScript, asProtectedSubtreePattern(protectedPath), false))) {
|
|
1261
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `preflight script "${preflightScript}" must reside inside a protected path`, '/spec/preflight/script');
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
for (const [index, script] of commandScripts.entries()) {
|
|
1265
|
+
if (!scriptPlacementProtected.some(protectedPath => scopePatternsMayIntersect(script, asProtectedSubtreePattern(protectedPath), false))) {
|
|
1266
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `command.v1 script "${script}" must reside inside a protected path`, `/spec/verification/localChecks/${index}/parameters/script`);
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
for (const relToolchain of relativeToolchainPaths) {
|
|
1270
|
+
if (!scriptPlacementProtected.some(protectedPath => scopePatternsMayIntersect(relToolchain, asProtectedSubtreePattern(protectedPath), false))) {
|
|
1271
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `command.v1 toolchainPaths entry "${relToolchain}" must reside inside a protected path`, '/spec/verification/localChecks');
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
const extraProtectedPaths = options.extraProtectedPaths?.map((entry, idx) => (normalizeScopePattern(entry, `/extraProtectedPaths/${idx}`)));
|
|
1275
|
+
const protectedOptions = {
|
|
1276
|
+
policyProfile,
|
|
1277
|
+
controlRoot,
|
|
1278
|
+
manifestPath,
|
|
1279
|
+
digestsLockfile,
|
|
1280
|
+
instructions,
|
|
1281
|
+
skills,
|
|
1282
|
+
preflightScript,
|
|
1283
|
+
commandScripts,
|
|
1284
|
+
toolchainPaths: relativeToolchainPaths.length > 0 ? relativeToolchainPaths : undefined,
|
|
1285
|
+
proposalPath,
|
|
1286
|
+
extraProtectedPaths,
|
|
1287
|
+
controlRootSiblings: options.controlRootSiblings,
|
|
1288
|
+
priorityControlRootSiblings: options.priorityControlRootSiblings,
|
|
1289
|
+
allowWorkflowWrites,
|
|
1290
|
+
githubSiblings: options.githubSiblings,
|
|
1291
|
+
};
|
|
1292
|
+
const { allProtected, mandatoryProtectedSet, explicitWithManifest } = resolveProtectedPathSets(manifestProtected, protectedOptions);
|
|
1293
|
+
if (allProtected.length > 128) {
|
|
1294
|
+
manifestInvalid('effective protected path set exceeds 128 entries', '/spec/scope/protected');
|
|
1295
|
+
}
|
|
1296
|
+
assertWritablesDisjointFromProtected(writable, allProtected, mandatoryProtectedSet, controlRoot, proposalPath, policyProfile, allowWorkflowWrites);
|
|
1297
|
+
if (proposalPath !== undefined) {
|
|
1298
|
+
pathInsideWritable(proposalPath, writable, allProtected, '/spec/proposal/path', true, policyProfile, allowWorkflowWrites, manifestProtectedSet);
|
|
1299
|
+
if ((pathCoveredBy(proposalPath, controlRoot) || pathCoveredByCaseInsensitive(proposalPath, controlRoot))
|
|
1300
|
+
&& (isSingleWildcardWritable
|
|
1301
|
+
|| !isControlRootProposalWritableAllowed(proposalPath, writable, controlRoot, explicitWithManifest))) {
|
|
1302
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `spec.proposal.path "${proposalPath}" inside control root "${controlRoot}" must be listed as an exact file in spec.scope.writable without overlapping protected control-plane paths`, '/spec/proposal/path');
|
|
1303
|
+
}
|
|
1304
|
+
if (!/\.(?:yaml|yml|json)$/i.test(proposalPath)) {
|
|
1305
|
+
manifestInvalid('spec.proposal.path must end in .yaml, .yml, or .json', '/spec/proposal/path');
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
if (manifest.spec.submission !== undefined) {
|
|
1309
|
+
const submissionPath = normalizeRelativePath(manifest.spec.submission.path, '/spec/submission/path');
|
|
1310
|
+
pathInsideWritable(submissionPath, writable, allProtected, '/spec/submission/path', false, policyProfile, allowWorkflowWrites, manifestProtectedSet);
|
|
1311
|
+
}
|
|
1312
|
+
return allProtected;
|
|
1313
|
+
}
|
|
1314
|
+
// ---------------------------------------------------------------------------
|
|
1315
|
+
// TaskpackManifest validator
|
|
1316
|
+
// ---------------------------------------------------------------------------
|
|
1317
|
+
function requireObject(value, path, fields) {
|
|
1318
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
1319
|
+
manifestInvalid('expected an object', path);
|
|
1320
|
+
const proto = Object.getPrototypeOf(value);
|
|
1321
|
+
if (proto !== Object.prototype && proto !== null)
|
|
1322
|
+
manifestInvalid('expected an object', path);
|
|
1323
|
+
const record = value;
|
|
1324
|
+
for (const key of Object.keys(record)) {
|
|
1325
|
+
if (FORBIDDEN_KEYS.has(key) || !fields.includes(key))
|
|
1326
|
+
manifestInvalid(`unknown field "${key}"`, path);
|
|
1327
|
+
}
|
|
1328
|
+
return record;
|
|
1329
|
+
}
|
|
1330
|
+
function requireString(value, path, min, max) {
|
|
1331
|
+
if (typeof value !== 'string' || value.length < min || value.length > max) {
|
|
1332
|
+
manifestInvalid(`expected a string of ${min}..${max} characters`, path);
|
|
1333
|
+
}
|
|
1334
|
+
if (/[\0\r\n]/.test(value))
|
|
1335
|
+
manifestInvalid('string contains forbidden control characters', path);
|
|
1336
|
+
return value;
|
|
1337
|
+
}
|
|
1338
|
+
function requireBoolean(value, path) {
|
|
1339
|
+
if (typeof value !== 'boolean')
|
|
1340
|
+
manifestInvalid('expected a boolean', path);
|
|
1341
|
+
return value;
|
|
1342
|
+
}
|
|
1343
|
+
function requireIdentifier(value, path) {
|
|
1344
|
+
const text = requireString(value, path, 1, 64);
|
|
1345
|
+
if (!IDENTIFIER_PATTERN.test(text))
|
|
1346
|
+
manifestInvalid('expected a lowercase identifier', path);
|
|
1347
|
+
return text;
|
|
1348
|
+
}
|
|
1349
|
+
function requireNullProtoObject(value, path, fields) {
|
|
1350
|
+
const raw = requireObject(value, path, fields);
|
|
1351
|
+
const out = Object.create(null);
|
|
1352
|
+
for (const key of fields) {
|
|
1353
|
+
if (Object.hasOwn(raw, key)) {
|
|
1354
|
+
out[key] = raw[key];
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
return out;
|
|
1358
|
+
}
|
|
1359
|
+
function requireLabel(value, path) {
|
|
1360
|
+
const text = requireString(value, path, 1, 128);
|
|
1361
|
+
if (/[\s\p{C}]/u.test(text) || LONE_SURROGATE_RE.test(text)) {
|
|
1362
|
+
manifestInvalid('expected a 1..128 character non-whitespace label', path);
|
|
1363
|
+
}
|
|
1364
|
+
return text;
|
|
1365
|
+
}
|
|
1366
|
+
function requirePrintableAscii(value, path, min, max) {
|
|
1367
|
+
if (typeof value !== 'string' || value.length < min || value.length > max) {
|
|
1368
|
+
manifestInvalid(`expected a printable ASCII string of ${min}..${max} characters`, path);
|
|
1369
|
+
}
|
|
1370
|
+
if (value.trim() !== value || !PRINTABLE_ASCII_RE.test(value)) {
|
|
1371
|
+
manifestInvalid('expected trimmed printable ASCII characters', path);
|
|
1372
|
+
}
|
|
1373
|
+
return value;
|
|
1374
|
+
}
|
|
1375
|
+
function requirePrintableText(value, path, min, max) {
|
|
1376
|
+
if (typeof value !== 'string' || value.length < min || value.length > max) {
|
|
1377
|
+
manifestInvalid(`expected a printable string of ${min}..${max} characters`, path);
|
|
1378
|
+
}
|
|
1379
|
+
if (value.trim() !== value || /[\r\n\t\p{C}]/u.test(value) || LONE_SURROGATE_RE.test(value)) {
|
|
1380
|
+
manifestInvalid('expected trimmed printable text without control characters or lone surrogates', path);
|
|
1381
|
+
}
|
|
1382
|
+
return value;
|
|
1383
|
+
}
|
|
1384
|
+
function requireFiniteNumber(value, path) {
|
|
1385
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || Object.is(value, -0)) {
|
|
1386
|
+
manifestInvalid('expected a finite number (not NaN, Infinity, or -0)', path);
|
|
1387
|
+
}
|
|
1388
|
+
return value;
|
|
1389
|
+
}
|
|
1390
|
+
function isValidDottedVersion(value) {
|
|
1391
|
+
if (!value.length || !DOTTED_VERSION_RE.test(value))
|
|
1392
|
+
return false;
|
|
1393
|
+
for (const part of value.split('.')) {
|
|
1394
|
+
const parsed = Number(part);
|
|
1395
|
+
if (!Number.isSafeInteger(parsed) || parsed < 0)
|
|
1396
|
+
return false;
|
|
1397
|
+
}
|
|
1398
|
+
return true;
|
|
1399
|
+
}
|
|
1400
|
+
function validateHardwareTargetSpec(value, path) {
|
|
1401
|
+
const raw = requireNullProtoObject(value, path, [
|
|
1402
|
+
'accelerator', 'isolationMode', 'deviceCount', 'driverConstraint', 'topology',
|
|
1403
|
+
]);
|
|
1404
|
+
const accelerator = requirePrintableAscii(raw['accelerator'], `${path}/accelerator`, 1, 64);
|
|
1405
|
+
const rawIsolation = raw['isolationMode'];
|
|
1406
|
+
if (rawIsolation !== 'whole_device' && rawIsolation !== 'sliced') {
|
|
1407
|
+
manifestInvalid('hardware.isolationMode must be "whole_device" or "sliced"', `${path}/isolationMode`);
|
|
1408
|
+
}
|
|
1409
|
+
const deviceCount = raw['deviceCount'] === undefined
|
|
1410
|
+
? undefined
|
|
1411
|
+
: requireSafeIntInRange(raw['deviceCount'], `${path}/deviceCount`, 1, 64);
|
|
1412
|
+
let driverConstraint;
|
|
1413
|
+
if (raw['driverConstraint'] !== undefined) {
|
|
1414
|
+
driverConstraint = requirePrintableText(raw['driverConstraint'], `${path}/driverConstraint`, 1, 128);
|
|
1415
|
+
if (driverConstraint.startsWith('>=') && !isValidDottedVersion(driverConstraint.slice(2))) {
|
|
1416
|
+
manifestInvalid('hardware.driverConstraint ">=" comparator requires a dotted version', `${path}/driverConstraint`);
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
const topology = raw['topology'] === undefined
|
|
1420
|
+
? undefined
|
|
1421
|
+
: requirePrintableText(raw['topology'], `${path}/topology`, 1, 128);
|
|
1422
|
+
return Object.freeze({
|
|
1423
|
+
accelerator,
|
|
1424
|
+
isolationMode: rawIsolation,
|
|
1425
|
+
...(deviceCount === undefined ? {} : { deviceCount }),
|
|
1426
|
+
...(driverConstraint === undefined ? {} : { driverConstraint }),
|
|
1427
|
+
...(topology === undefined ? {} : { topology }),
|
|
1428
|
+
});
|
|
1429
|
+
}
|
|
1430
|
+
function requireMetricKey(value, path) {
|
|
1431
|
+
if (typeof value !== 'string' || value.length < 1 || value.length > LIMITS.metricKey) {
|
|
1432
|
+
manifestInvalid(`expected a metric key of 1..${LIMITS.metricKey} characters`, path);
|
|
1433
|
+
}
|
|
1434
|
+
if (FORBIDDEN_KEYS.has(value) || !METRIC_KEY_RE.test(value)) {
|
|
1435
|
+
manifestInvalid(`invalid metric key ${JSON.stringify(value)}`, path);
|
|
1436
|
+
}
|
|
1437
|
+
return value;
|
|
1438
|
+
}
|
|
1439
|
+
function validateMetricThresholdRule(value, path) {
|
|
1440
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
1441
|
+
manifestInvalid('expected a metric threshold rule object', path);
|
|
1442
|
+
}
|
|
1443
|
+
const proto = Object.getPrototypeOf(value);
|
|
1444
|
+
if (proto !== Object.prototype && proto !== null) {
|
|
1445
|
+
manifestInvalid('expected a metric threshold rule object', path);
|
|
1446
|
+
}
|
|
1447
|
+
const rawRecord = value;
|
|
1448
|
+
if (!Object.hasOwn(rawRecord, 'kind')) {
|
|
1449
|
+
manifestInvalid('metric threshold rule requires "kind"', `${path}/kind`);
|
|
1450
|
+
}
|
|
1451
|
+
const kind = rawRecord['kind'];
|
|
1452
|
+
if (kind === 'bounds') {
|
|
1453
|
+
const raw = requireNullProtoObject(value, path, ['kind', 'metric', 'min', 'max']);
|
|
1454
|
+
const metric = requireMetricKey(raw['metric'], `${path}/metric`);
|
|
1455
|
+
const min = raw['min'] === undefined ? undefined : requireFiniteNumber(raw['min'], `${path}/min`);
|
|
1456
|
+
const max = raw['max'] === undefined ? undefined : requireFiniteNumber(raw['max'], `${path}/max`);
|
|
1457
|
+
if (min === undefined && max === undefined) {
|
|
1458
|
+
manifestInvalid('bounds metric threshold requires at least one of "min" or "max"', path);
|
|
1459
|
+
}
|
|
1460
|
+
if (min !== undefined && max !== undefined && min > max) {
|
|
1461
|
+
manifestInvalid('bounds metric threshold requires min <= max', path);
|
|
1462
|
+
}
|
|
1463
|
+
return Object.freeze({
|
|
1464
|
+
kind: 'bounds',
|
|
1465
|
+
metric,
|
|
1466
|
+
...(min === undefined ? {} : { min }),
|
|
1467
|
+
...(max === undefined ? {} : { max }),
|
|
1468
|
+
});
|
|
1469
|
+
}
|
|
1470
|
+
if (kind === 'comparative') {
|
|
1471
|
+
const raw = requireNullProtoObject(value, path, ['kind', 'metric', 'baselineMetric', 'operator', 'threshold']);
|
|
1472
|
+
const metric = requireMetricKey(raw['metric'], `${path}/metric`);
|
|
1473
|
+
const baselineMetric = requireMetricKey(raw['baselineMetric'], `${path}/baselineMetric`);
|
|
1474
|
+
const operator = raw['operator'];
|
|
1475
|
+
if (operator !== 'min_ratio' && operator !== 'max_ratio' && operator !== 'max_delta') {
|
|
1476
|
+
manifestInvalid('comparative metric threshold operator must be "min_ratio", "max_ratio", or "max_delta"', `${path}/operator`);
|
|
1477
|
+
}
|
|
1478
|
+
// Reject -0/NaN/Infinity on untrusted manifest input (stricter than @loopwright/core's -0 -> 0 normalization)
|
|
1479
|
+
// while matching @loopwright/core's allowance of finite negative comparative thresholds (e.g. -0.25).
|
|
1480
|
+
const threshold = requireFiniteNumber(raw['threshold'], `${path}/threshold`);
|
|
1481
|
+
return Object.freeze({
|
|
1482
|
+
kind: 'comparative',
|
|
1483
|
+
metric,
|
|
1484
|
+
baselineMetric,
|
|
1485
|
+
operator,
|
|
1486
|
+
threshold,
|
|
1487
|
+
});
|
|
1488
|
+
}
|
|
1489
|
+
manifestInvalid('metric threshold rule kind must be "bounds" or "comparative"', `${path}/kind`);
|
|
1490
|
+
}
|
|
1491
|
+
function requireStringList(value, path, min, max) {
|
|
1492
|
+
if (!Array.isArray(value) || value.length < min || value.length > max) {
|
|
1493
|
+
manifestInvalid(`expected an array of ${min}..${max} items`, path);
|
|
1494
|
+
}
|
|
1495
|
+
const seen = new Set();
|
|
1496
|
+
return value.map((item, index) => {
|
|
1497
|
+
const text = requireString(item, `${path}/${index}`, 1, MAX_STRING);
|
|
1498
|
+
if (seen.has(text))
|
|
1499
|
+
manifestInvalid('duplicate list entry', path);
|
|
1500
|
+
seen.add(text);
|
|
1501
|
+
return text;
|
|
1502
|
+
});
|
|
1503
|
+
}
|
|
1504
|
+
function requireParameters(value, path) {
|
|
1505
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
1506
|
+
manifestInvalid('expected an object of scalar parameters', path);
|
|
1507
|
+
const record = value;
|
|
1508
|
+
const output = {};
|
|
1509
|
+
for (const [key, item] of Object.entries(record)) {
|
|
1510
|
+
if (FORBIDDEN_KEYS.has(key))
|
|
1511
|
+
manifestInvalid(`forbidden parameter key "${key}"`, path);
|
|
1512
|
+
if (item !== null && typeof item !== 'string' && typeof item !== 'number' && typeof item !== 'boolean') {
|
|
1513
|
+
manifestInvalid('parameter values must be scalars', path);
|
|
1514
|
+
}
|
|
1515
|
+
if (typeof item === 'string' && item.length > 1024)
|
|
1516
|
+
manifestInvalid('parameter string exceeds 1024 characters', path);
|
|
1517
|
+
output[key] = item;
|
|
1518
|
+
}
|
|
1519
|
+
return Object.freeze(output);
|
|
1520
|
+
}
|
|
1521
|
+
function requireMultilineString(value, path, min, max) {
|
|
1522
|
+
if (typeof value !== 'string' || value.length < min || value.length > max) {
|
|
1523
|
+
manifestInvalid(`expected a string of ${min}..${max} characters`, path);
|
|
1524
|
+
}
|
|
1525
|
+
if (value.includes('\0'))
|
|
1526
|
+
manifestInvalid('string contains forbidden NUL control character', path);
|
|
1527
|
+
return value;
|
|
1528
|
+
}
|
|
1529
|
+
function pathInsideWritable(candidate, writable, protectedPaths, path, legacyPrefixFallback = false, policyProfile = 'local', allowWorkflowWrites = false, manifestProtectedSet = new Set()) {
|
|
1530
|
+
const githubAllowWorkflows = policyProfile === 'github' && allowWorkflowWrites;
|
|
1531
|
+
if (writable.length > 0 && !writable.some(root => writableScopeCoversPath(root, candidate, legacyPrefixFallback))) {
|
|
1532
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `path "${candidate}" is not inside spec.scope.writable`, path);
|
|
1533
|
+
}
|
|
1534
|
+
if (githubAllowWorkflows && writableEntryOverlapsProtected(candidate, '.github', true, true)) {
|
|
1535
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `path "${candidate}" overlaps protected path ".github"`, path);
|
|
1536
|
+
}
|
|
1537
|
+
const overlap = protectedPaths.find(protectedPath => {
|
|
1538
|
+
if (githubAllowWorkflows
|
|
1539
|
+
&& !manifestProtectedSet.has(protectedPath)
|
|
1540
|
+
&& (protectedPath === '.github' || protectedPath === '.github/**')
|
|
1541
|
+
&& isWorkflowSubpathPattern(candidate)) {
|
|
1542
|
+
return false;
|
|
1543
|
+
}
|
|
1544
|
+
const protectedSubtree = asProtectedSubtreePattern(protectedPath);
|
|
1545
|
+
return scopePatternsMayIntersect(candidate, protectedSubtree, false)
|
|
1546
|
+
|| scopePatternsMayIntersect(candidate, protectedSubtree, true);
|
|
1547
|
+
});
|
|
1548
|
+
if (overlap !== undefined) {
|
|
1549
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `path "${candidate}" overlaps protected path "${overlap}"`, path);
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
const ALLOWED_COMMAND_RUNNER_ENV_NAMES = new Set(['RUNNER_ENVIRONMENT']);
|
|
1553
|
+
const FORBIDDEN_LITERAL_COMMAND_ENV_NAMES = new Set(['RUNNER_ENVIRONMENT', 'GITHUB_ACTIONS']);
|
|
1554
|
+
function isReservedCommandEnvName(name) {
|
|
1555
|
+
if (ALLOWED_COMMAND_RUNNER_ENV_NAMES.has(name))
|
|
1556
|
+
return false;
|
|
1557
|
+
if (RESERVED_COMMAND_ENV_NAMES.has(name))
|
|
1558
|
+
return true;
|
|
1559
|
+
return RESERVED_COMMAND_ENV_PREFIXES.some(prefix => name.startsWith(prefix));
|
|
1560
|
+
}
|
|
1561
|
+
function requireSafeIntInRange(value, path, min, max) {
|
|
1562
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || Object.is(value, -0) || value < min || value > max) {
|
|
1563
|
+
manifestInvalid(`expected an integer in ${min}..${max}`, path);
|
|
1564
|
+
}
|
|
1565
|
+
return value;
|
|
1566
|
+
}
|
|
1567
|
+
export function validateTaskpackLimitsDeclaration(value, path) {
|
|
1568
|
+
const raw = requireObject(value, path, [
|
|
1569
|
+
'wallTimeSeconds', 'totalTokens', 'contextWindow', 'maxOutputTokens',
|
|
1570
|
+
'maxModelCalls', 'maxTurns', 'maxRepairTurns', 'maxAttempts', 'maxFormatRepairs', 'maxImplementationRepairs', 'maxTransportRetries',
|
|
1571
|
+
'toolTimeoutSeconds', 'commandTimeoutSeconds', 'responseBytes', 'toolResultBytes',
|
|
1572
|
+
'toolArgsBytes', 'promptBytes', 'maxRequestBytes', 'workingWindowBytes', 'fileBytes',
|
|
1573
|
+
'sessionBytes', 'candidateEntries', 'overlay',
|
|
1574
|
+
]);
|
|
1575
|
+
const out = {};
|
|
1576
|
+
const setOpt = (key, min, max) => {
|
|
1577
|
+
if (raw[key] !== undefined) {
|
|
1578
|
+
out[key] = requireSafeIntInRange(raw[key], `${path}/${key}`, min, max);
|
|
1579
|
+
}
|
|
1580
|
+
};
|
|
1581
|
+
setOpt('wallTimeSeconds', 60, 21_600);
|
|
1582
|
+
setOpt('totalTokens', 1_000, 1_000_000_000);
|
|
1583
|
+
setOpt('contextWindow', 1_024, 10_000_000);
|
|
1584
|
+
setOpt('maxOutputTokens', 256, 262_144);
|
|
1585
|
+
setOpt('maxModelCalls', 1, 1_024);
|
|
1586
|
+
setOpt('maxTurns', 1, 1_024);
|
|
1587
|
+
setOpt('maxRepairTurns', 1, 1_024);
|
|
1588
|
+
setOpt('maxAttempts', 1, 16);
|
|
1589
|
+
setOpt('maxFormatRepairs', 0, 1_024);
|
|
1590
|
+
setOpt('maxImplementationRepairs', 0, 1_024);
|
|
1591
|
+
setOpt('maxTransportRetries', 0, 8);
|
|
1592
|
+
setOpt('toolTimeoutSeconds', 1, 1_800);
|
|
1593
|
+
setOpt('commandTimeoutSeconds', 1, 3_600);
|
|
1594
|
+
setOpt('responseBytes', 65_536, 67_108_864);
|
|
1595
|
+
setOpt('toolResultBytes', 16_384, 4_194_304);
|
|
1596
|
+
setOpt('toolArgsBytes', 16_384, 4_194_304);
|
|
1597
|
+
setOpt('promptBytes', 4_096, 1_048_576);
|
|
1598
|
+
setOpt('maxRequestBytes', 65_536, 16_777_216);
|
|
1599
|
+
setOpt('workingWindowBytes', 131_072, 16_777_216);
|
|
1600
|
+
setOpt('fileBytes', 65_536, OVERLAY_LIMITS.maxMaxBytes);
|
|
1601
|
+
setOpt('sessionBytes', 524_288, 67_108_864);
|
|
1602
|
+
setOpt('candidateEntries', 16, OVERLAY_LIMITS.maxMaxFiles);
|
|
1603
|
+
if (raw['overlay'] !== undefined) {
|
|
1604
|
+
requireObject(raw['overlay'], `${path}/overlay`, ['maxFiles', 'maxBytes']);
|
|
1605
|
+
const resolved = resolveOverlayLimits(raw['overlay']);
|
|
1606
|
+
if (!resolved.ok) {
|
|
1607
|
+
manifestInvalid(`invalid limits.overlay: ${resolved.errors[0]?.code ?? 'VALUE_RANGE'}`, `${path}/overlay`);
|
|
1608
|
+
}
|
|
1609
|
+
out['overlay'] = Object.freeze({ maxFiles: resolved.value.maxFiles, maxBytes: resolved.value.maxBytes });
|
|
1610
|
+
}
|
|
1611
|
+
return Object.freeze(out);
|
|
1612
|
+
}
|
|
1613
|
+
export function validateMcpServerDeclarations(value, path, options = {}) {
|
|
1614
|
+
if (!Array.isArray(value) || value.length > 16) {
|
|
1615
|
+
manifestInvalid('mcp.servers must be an array of 0..16 server declarations', path);
|
|
1616
|
+
}
|
|
1617
|
+
const seenIds = new Set();
|
|
1618
|
+
const servers = [];
|
|
1619
|
+
for (const [idx, item] of value.entries()) {
|
|
1620
|
+
const serverPath = `${path}/${idx}`;
|
|
1621
|
+
if (item === null || typeof item !== 'object' || Array.isArray(item)) {
|
|
1622
|
+
manifestInvalid('expected an MCP server declaration object', serverPath);
|
|
1623
|
+
}
|
|
1624
|
+
const rawAny = item;
|
|
1625
|
+
if (rawAny['oauth'] !== undefined) {
|
|
1626
|
+
throw new TaskpackError('MCP_OAUTH_UNSUPPORTED', 'MCP OAuth authentication is unsupported', `${serverPath}/oauth`);
|
|
1627
|
+
}
|
|
1628
|
+
if (rawAny['auth'] !== undefined && rawAny['auth'] !== null && typeof rawAny['auth'] === 'object') {
|
|
1629
|
+
const authType = rawAny['auth']['type'];
|
|
1630
|
+
if (typeof authType === 'string' && authType.trim().toLowerCase() === 'oauth') {
|
|
1631
|
+
throw new TaskpackError('MCP_OAUTH_UNSUPPORTED', 'MCP OAuth authentication is unsupported', `${serverPath}/auth`);
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
const transportRaw = rawAny['transport'];
|
|
1635
|
+
if (transportRaw !== 'stdio' && transportRaw !== 'http') {
|
|
1636
|
+
manifestInvalid('mcp server transport must be "stdio" or "http"', `${serverPath}/transport`);
|
|
1637
|
+
}
|
|
1638
|
+
const serverId = requireString(rawAny['id'], `${serverPath}/id`, 1, 24);
|
|
1639
|
+
if (!MCP_SERVER_ID_PATTERN.test(serverId) || serverId === 'workspace') {
|
|
1640
|
+
manifestInvalid('mcp server id must match ^[a-z][a-z0-9_]*(?:-[a-z0-9_]+)*$ and must not be "workspace"', `${serverPath}/id`);
|
|
1641
|
+
}
|
|
1642
|
+
if (seenIds.has(serverId)) {
|
|
1643
|
+
manifestInvalid(`duplicate mcp server id "${serverId}"`, `${serverPath}/id`);
|
|
1644
|
+
}
|
|
1645
|
+
seenIds.add(serverId);
|
|
1646
|
+
if (transportRaw === 'stdio') {
|
|
1647
|
+
const raw = requireObject(item, serverPath, [
|
|
1648
|
+
'id', 'transport', 'command', 'args', 'env', 'envFrom', 'timeoutSeconds', 'includeTools', 'readOnly', 'required',
|
|
1649
|
+
]);
|
|
1650
|
+
const command = requireString(raw['command'], `${serverPath}/command`, 1, 512);
|
|
1651
|
+
const isBareCommand = !command.includes('/') && !command.includes('\\');
|
|
1652
|
+
const isAbsoluteCommand = command.startsWith('/') && !command.includes('..') && !command.includes('\\');
|
|
1653
|
+
if (!isBareCommand && !isAbsoluteCommand) {
|
|
1654
|
+
manifestInvalid('stdio mcp command must be a bare executable name on PATH or an absolute path', `${serverPath}/command`);
|
|
1655
|
+
}
|
|
1656
|
+
let args;
|
|
1657
|
+
if (raw['args'] !== undefined) {
|
|
1658
|
+
if (!Array.isArray(raw['args']) || raw['args'].length > 64) {
|
|
1659
|
+
manifestInvalid('stdio mcp args must be an array of 0..64 strings', `${serverPath}/args`);
|
|
1660
|
+
}
|
|
1661
|
+
args = Object.freeze(raw['args'].map((arg, aIdx) => requireString(arg, `${serverPath}/args/${aIdx}`, 0, 1024)));
|
|
1662
|
+
}
|
|
1663
|
+
let env;
|
|
1664
|
+
if (raw['env'] !== undefined) {
|
|
1665
|
+
if (raw['env'] === null || typeof raw['env'] !== 'object' || Array.isArray(raw['env'])) {
|
|
1666
|
+
manifestInvalid('stdio mcp env must be an object of string entries', `${serverPath}/env`);
|
|
1667
|
+
}
|
|
1668
|
+
const entries = Object.entries(raw['env']);
|
|
1669
|
+
if (entries.length > 32)
|
|
1670
|
+
manifestInvalid('stdio mcp env exceeds 32 entries', `${serverPath}/env`);
|
|
1671
|
+
const envOut = {};
|
|
1672
|
+
for (const [k, v] of entries) {
|
|
1673
|
+
if (FORBIDDEN_KEYS.has(k) || !COMMAND_ENV_NAME_PATTERN.test(k)) {
|
|
1674
|
+
manifestInvalid(`invalid env variable name "${k}"`, `${serverPath}/env/${k}`);
|
|
1675
|
+
}
|
|
1676
|
+
envOut[k] = requireString(v, `${serverPath}/env/${k}`, 0, 2048);
|
|
1677
|
+
}
|
|
1678
|
+
env = Object.freeze(envOut);
|
|
1679
|
+
}
|
|
1680
|
+
let envFrom;
|
|
1681
|
+
if (raw['envFrom'] !== undefined) {
|
|
1682
|
+
if (raw['envFrom'] === null || typeof raw['envFrom'] !== 'object' || Array.isArray(raw['envFrom'])) {
|
|
1683
|
+
manifestInvalid('stdio mcp envFrom must be an object mapping target env names to host env names', `${serverPath}/envFrom`);
|
|
1684
|
+
}
|
|
1685
|
+
const entries = Object.entries(raw['envFrom']);
|
|
1686
|
+
if (entries.length > 32)
|
|
1687
|
+
manifestInvalid('stdio mcp envFrom exceeds 32 entries', `${serverPath}/envFrom`);
|
|
1688
|
+
const envFromOut = {};
|
|
1689
|
+
for (const [targetName, sourceName] of entries) {
|
|
1690
|
+
if (FORBIDDEN_KEYS.has(targetName) || !COMMAND_ENV_NAME_PATTERN.test(targetName)) {
|
|
1691
|
+
manifestInvalid(`invalid target env variable name "${targetName}"`, `${serverPath}/envFrom/${targetName}`);
|
|
1692
|
+
}
|
|
1693
|
+
const src = requireString(sourceName, `${serverPath}/envFrom/${targetName}`, 1, 64);
|
|
1694
|
+
if (!COMMAND_ENV_NAME_PATTERN.test(src) && !/^INPUT_[A-Z0-9_-]{1,63}$/.test(src)) {
|
|
1695
|
+
manifestInvalid(`invalid source env variable name "${src}"`, `${serverPath}/envFrom/${targetName}`);
|
|
1696
|
+
}
|
|
1697
|
+
envFromOut[targetName] = src;
|
|
1698
|
+
}
|
|
1699
|
+
envFrom = Object.freeze(envFromOut);
|
|
1700
|
+
}
|
|
1701
|
+
const timeoutSeconds = raw['timeoutSeconds'] === undefined ? undefined : requireSafeIntInRange(raw['timeoutSeconds'], `${serverPath}/timeoutSeconds`, 1, 600);
|
|
1702
|
+
const includeTools = raw['includeTools'] === undefined ? undefined : requireStringList(raw['includeTools'], `${serverPath}/includeTools`, 1, 64);
|
|
1703
|
+
const readOnly = raw['readOnly'] === undefined ? undefined : requireBoolean(raw['readOnly'], `${serverPath}/readOnly`);
|
|
1704
|
+
const required = raw['required'] === undefined ? undefined : requireBoolean(raw['required'], `${serverPath}/required`);
|
|
1705
|
+
const decl = Object.freeze({
|
|
1706
|
+
id: serverId,
|
|
1707
|
+
transport: 'stdio',
|
|
1708
|
+
command,
|
|
1709
|
+
...(args === undefined ? {} : { args }),
|
|
1710
|
+
...(env === undefined ? {} : { env }),
|
|
1711
|
+
...(envFrom === undefined ? {} : { envFrom }),
|
|
1712
|
+
...(timeoutSeconds === undefined ? {} : { timeoutSeconds }),
|
|
1713
|
+
...(includeTools === undefined ? {} : { includeTools }),
|
|
1714
|
+
...(readOnly === undefined ? {} : { readOnly }),
|
|
1715
|
+
...(required === undefined ? {} : { required }),
|
|
1716
|
+
});
|
|
1717
|
+
servers.push(decl);
|
|
1718
|
+
}
|
|
1719
|
+
else {
|
|
1720
|
+
const raw = requireObject(item, serverPath, [
|
|
1721
|
+
'id', 'transport', 'url', 'headers', 'headersFrom', 'bearerTokenEnv', 'timeoutSeconds', 'includeTools', 'readOnly', 'required',
|
|
1722
|
+
]);
|
|
1723
|
+
const urlStr = requireString(raw['url'], `${serverPath}/url`, 1, 2048);
|
|
1724
|
+
let parsedUrl;
|
|
1725
|
+
try {
|
|
1726
|
+
parsedUrl = new URL(urlStr);
|
|
1727
|
+
}
|
|
1728
|
+
catch {
|
|
1729
|
+
manifestInvalid('http mcp url is not a valid URL', `${serverPath}/url`);
|
|
1730
|
+
}
|
|
1731
|
+
if (parsedUrl.username !== '' || parsedUrl.password !== '' || parsedUrl.hash !== '') {
|
|
1732
|
+
manifestInvalid('http mcp url must not contain credentials or fragments', `${serverPath}/url`);
|
|
1733
|
+
}
|
|
1734
|
+
const isLoopback = parsedUrl.hostname === '127.0.0.1' || parsedUrl.hostname === '[::1]' || parsedUrl.hostname === 'localhost';
|
|
1735
|
+
if (parsedUrl.protocol !== 'https:' && !(options.allowLoopbackHttp === true && parsedUrl.protocol === 'http:' && isLoopback)) {
|
|
1736
|
+
manifestInvalid('http mcp url must use https://', `${serverPath}/url`);
|
|
1737
|
+
}
|
|
1738
|
+
let headers;
|
|
1739
|
+
if (raw['headers'] !== undefined) {
|
|
1740
|
+
if (raw['headers'] === null || typeof raw['headers'] !== 'object' || Array.isArray(raw['headers'])) {
|
|
1741
|
+
manifestInvalid('http mcp headers must be an object of string entries', `${serverPath}/headers`);
|
|
1742
|
+
}
|
|
1743
|
+
const entries = Object.entries(raw['headers']);
|
|
1744
|
+
if (entries.length > 32)
|
|
1745
|
+
manifestInvalid('http mcp headers exceeds 32 entries', `${serverPath}/headers`);
|
|
1746
|
+
const headersOut = {};
|
|
1747
|
+
for (const [k, v] of entries) {
|
|
1748
|
+
if (FORBIDDEN_KEYS.has(k) || !HTTP_HEADER_NAME_PATTERN.test(k)) {
|
|
1749
|
+
manifestInvalid(`invalid header name "${k}"`, `${serverPath}/headers/${k}`);
|
|
1750
|
+
}
|
|
1751
|
+
if (k.toLowerCase() === 'authorization') {
|
|
1752
|
+
manifestInvalid('use bearerTokenEnv or headersFrom instead of literal authorization header', `${serverPath}/headers/${k}`);
|
|
1753
|
+
}
|
|
1754
|
+
headersOut[k] = requireString(v, `${serverPath}/headers/${k}`, 0, 2048);
|
|
1755
|
+
}
|
|
1756
|
+
headers = Object.freeze(headersOut);
|
|
1757
|
+
}
|
|
1758
|
+
let headersFrom;
|
|
1759
|
+
if (raw['headersFrom'] !== undefined) {
|
|
1760
|
+
if (raw['headersFrom'] === null || typeof raw['headersFrom'] !== 'object' || Array.isArray(raw['headersFrom'])) {
|
|
1761
|
+
manifestInvalid('http mcp headersFrom must be an object mapping header names to host env names', `${serverPath}/headersFrom`);
|
|
1762
|
+
}
|
|
1763
|
+
const entries = Object.entries(raw['headersFrom']);
|
|
1764
|
+
if (entries.length > 32)
|
|
1765
|
+
manifestInvalid('http mcp headersFrom exceeds 32 entries', `${serverPath}/headersFrom`);
|
|
1766
|
+
const headersFromOut = {};
|
|
1767
|
+
for (const [headerName, sourceName] of entries) {
|
|
1768
|
+
if (FORBIDDEN_KEYS.has(headerName) || !HTTP_HEADER_NAME_PATTERN.test(headerName)) {
|
|
1769
|
+
manifestInvalid(`invalid header name "${headerName}"`, `${serverPath}/headersFrom/${headerName}`);
|
|
1770
|
+
}
|
|
1771
|
+
const src = requireString(sourceName, `${serverPath}/headersFrom/${headerName}`, 1, 64);
|
|
1772
|
+
if (!COMMAND_ENV_NAME_PATTERN.test(src) && !/^INPUT_[A-Z0-9_-]{1,63}$/.test(src)) {
|
|
1773
|
+
manifestInvalid(`invalid source env variable name "${src}"`, `${serverPath}/headersFrom/${headerName}`);
|
|
1774
|
+
}
|
|
1775
|
+
headersFromOut[headerName] = src;
|
|
1776
|
+
}
|
|
1777
|
+
headersFrom = Object.freeze(headersFromOut);
|
|
1778
|
+
}
|
|
1779
|
+
let bearerTokenEnv;
|
|
1780
|
+
if (raw['bearerTokenEnv'] !== undefined) {
|
|
1781
|
+
const src = requireString(raw['bearerTokenEnv'], `${serverPath}/bearerTokenEnv`, 1, 64);
|
|
1782
|
+
if (!COMMAND_ENV_NAME_PATTERN.test(src) && !/^INPUT_[A-Z0-9_-]{1,63}$/.test(src)) {
|
|
1783
|
+
manifestInvalid(`invalid bearerTokenEnv "${src}"`, `${serverPath}/bearerTokenEnv`);
|
|
1784
|
+
}
|
|
1785
|
+
bearerTokenEnv = src;
|
|
1786
|
+
}
|
|
1787
|
+
const timeoutSeconds = raw['timeoutSeconds'] === undefined ? undefined : requireSafeIntInRange(raw['timeoutSeconds'], `${serverPath}/timeoutSeconds`, 1, 600);
|
|
1788
|
+
const includeTools = raw['includeTools'] === undefined ? undefined : requireStringList(raw['includeTools'], `${serverPath}/includeTools`, 1, 64);
|
|
1789
|
+
const readOnly = raw['readOnly'] === undefined ? undefined : requireBoolean(raw['readOnly'], `${serverPath}/readOnly`);
|
|
1790
|
+
const required = raw['required'] === undefined ? undefined : requireBoolean(raw['required'], `${serverPath}/required`);
|
|
1791
|
+
const decl = Object.freeze({
|
|
1792
|
+
id: serverId,
|
|
1793
|
+
transport: 'http',
|
|
1794
|
+
url: urlStr,
|
|
1795
|
+
...(headers === undefined ? {} : { headers }),
|
|
1796
|
+
...(headersFrom === undefined ? {} : { headersFrom }),
|
|
1797
|
+
...(bearerTokenEnv === undefined ? {} : { bearerTokenEnv }),
|
|
1798
|
+
...(timeoutSeconds === undefined ? {} : { timeoutSeconds }),
|
|
1799
|
+
...(includeTools === undefined ? {} : { includeTools }),
|
|
1800
|
+
...(readOnly === undefined ? {} : { readOnly }),
|
|
1801
|
+
...(required === undefined ? {} : { required }),
|
|
1802
|
+
});
|
|
1803
|
+
servers.push(decl);
|
|
1804
|
+
}
|
|
1805
|
+
}
|
|
1806
|
+
return Object.freeze(servers);
|
|
1807
|
+
}
|
|
1808
|
+
export function collectMcpReferencedEnvNames(servers) {
|
|
1809
|
+
const names = new Set();
|
|
1810
|
+
if (!servers)
|
|
1811
|
+
return names;
|
|
1812
|
+
for (const server of servers) {
|
|
1813
|
+
if (server.transport === 'stdio' && server.envFrom !== undefined) {
|
|
1814
|
+
for (const src of Object.values(server.envFrom))
|
|
1815
|
+
names.add(src);
|
|
1816
|
+
}
|
|
1817
|
+
else if (server.transport === 'http') {
|
|
1818
|
+
if (server.headersFrom !== undefined) {
|
|
1819
|
+
for (const src of Object.values(server.headersFrom))
|
|
1820
|
+
names.add(src);
|
|
1821
|
+
}
|
|
1822
|
+
if (server.bearerTokenEnv !== undefined) {
|
|
1823
|
+
names.add(server.bearerTokenEnv);
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
return names;
|
|
1828
|
+
}
|
|
1829
|
+
/**
|
|
1830
|
+
* Validate a non-root RFC 6901 JSON Pointer (`1..256` chars, `1..32` segments),
|
|
1831
|
+
* decode `~1` (`/`) and `~0` (`~`), and reject prototype-chain segments (`__proto__`, `constructor`, `prototype`).
|
|
1832
|
+
*/
|
|
1833
|
+
export function validateRfc6901JsonPointer(value, path) {
|
|
1834
|
+
const text = requireString(value, path, 1, 256);
|
|
1835
|
+
const rfc6901PointerPattern = /^(?:\/(?:[^~/]|~[01])*)+$/;
|
|
1836
|
+
if (!rfc6901PointerPattern.test(text)) {
|
|
1837
|
+
manifestInvalid(`invalid RFC 6901 JSON Pointer "${text}"`, path);
|
|
1838
|
+
}
|
|
1839
|
+
const rawSegments = text.slice(1).split('/');
|
|
1840
|
+
if (rawSegments.length < 1 || rawSegments.length > 32) {
|
|
1841
|
+
manifestInvalid('RFC 6901 JSON Pointer must contain 1..32 segments', path);
|
|
1842
|
+
}
|
|
1843
|
+
const decodedSegments = rawSegments.map(seg => {
|
|
1844
|
+
const decoded = seg.replace(/~1/g, '/').replace(/~0/g, '~');
|
|
1845
|
+
if (FORBIDDEN_KEYS.has(decoded)) {
|
|
1846
|
+
manifestInvalid(`RFC 6901 JSON Pointer must not reference forbidden property "${decoded}"`, path);
|
|
1847
|
+
}
|
|
1848
|
+
return decoded;
|
|
1849
|
+
});
|
|
1850
|
+
return Object.freeze(decodedSegments);
|
|
1851
|
+
}
|
|
1852
|
+
/**
|
|
1853
|
+
* True when two `headBranchPrefix` values on the same `targetBranch` collide (either one is a
|
|
1854
|
+
* string prefix of the other or one stripped Git ref path covers the other).
|
|
1855
|
+
*/
|
|
1856
|
+
export function headBranchPrefixesCollide(prefixA, prefixB) {
|
|
1857
|
+
if (prefixA.startsWith(prefixB) || prefixB.startsWith(prefixA)) {
|
|
1858
|
+
return true;
|
|
1859
|
+
}
|
|
1860
|
+
const stripA = prefixA.replace(/\/+$/, '');
|
|
1861
|
+
const stripB = prefixB.replace(/\/+$/, '');
|
|
1862
|
+
return stripA.length === 0 || stripB.length === 0 || pathCoveredBy(stripA, stripB) || pathCoveredBy(stripB, stripA);
|
|
1863
|
+
}
|
|
1864
|
+
/** True when a `writable` scope pattern could overlap a mandatory protected path or subtree. */
|
|
1865
|
+
export function writableOverlapsMandatoryProtected(writablePattern, protectedEntry, allowWorkflowWrites = false, isBuiltInProtected = false) {
|
|
1866
|
+
return writableEntryOverlapsProtected(writablePattern, protectedEntry, allowWorkflowWrites, isBuiltInProtected);
|
|
1867
|
+
}
|
|
1868
|
+
/**
|
|
1869
|
+
* Collect mandatory control-plane paths declared by a validated domain manifest (excluding user
|
|
1870
|
+
* `spec.scope.protected` exclusions so peer domains can still own disjoint writable trees).
|
|
1871
|
+
*/
|
|
1872
|
+
export function collectManifestControlPlanePaths(manifest, options = {}) {
|
|
1873
|
+
const policyProfile = resolvePolicyProfile(options.policyProfile, undefined);
|
|
1874
|
+
const controlRoot = options.controlRoot ?? manifest.controlRoot ?? '.loopwright';
|
|
1875
|
+
const manifestPath = options.manifestPath ?? manifest.manifestPath;
|
|
1876
|
+
const allowWorkflowWrites = policyProfile === 'github' && options.allowWorkflowWrites === true;
|
|
1877
|
+
const instructions = extractTaskpackResourcePaths(options.instructions ?? [
|
|
1878
|
+
...(manifest.spec.instructions ?? []),
|
|
1879
|
+
...(manifest.spec.roles ?? []).flatMap(role => role.instructions ?? []),
|
|
1880
|
+
]);
|
|
1881
|
+
const skills = extractTaskpackResourcePaths(options.skills ?? [
|
|
1882
|
+
...(manifest.spec.skills ?? []),
|
|
1883
|
+
...(manifest.spec.roles ?? []).flatMap(role => role.skills ?? []),
|
|
1884
|
+
]);
|
|
1885
|
+
const preflightScript = options.preflightScript ?? manifest.spec.preflight?.script;
|
|
1886
|
+
const digestsLockfile = options.digestsLockfile ?? manifest.spec.execution?.digests.lockfile;
|
|
1887
|
+
const commandScripts = options.commandScripts ?? manifest.spec.verification.localChecks
|
|
1888
|
+
.filter(c => c.implementation === 'command.v1')
|
|
1889
|
+
.map(c => c.parameters?.['script'])
|
|
1890
|
+
.filter((s) => typeof s === 'string' && s.length > 0);
|
|
1891
|
+
const toolchainPaths = options.toolchainPaths ?? manifest.spec.verification.localChecks
|
|
1892
|
+
.flatMap(c => (c.implementation === 'command.v1' && Array.isArray(c.parameters?.['toolchainPaths'])
|
|
1893
|
+
? c.parameters['toolchainPaths'].filter((entry) => typeof entry === 'string' && entry.length > 0 && !entry.startsWith('/'))
|
|
1894
|
+
: []));
|
|
1895
|
+
const proposalPath = options.proposalPath ?? manifest.spec.proposal?.path;
|
|
1896
|
+
const effectiveOpts = {
|
|
1897
|
+
...options,
|
|
1898
|
+
policyProfile,
|
|
1899
|
+
controlRoot,
|
|
1900
|
+
manifestPath,
|
|
1901
|
+
digestsLockfile,
|
|
1902
|
+
instructions: instructions.length > 0 ? instructions : undefined,
|
|
1903
|
+
skills: skills.length > 0 ? skills : undefined,
|
|
1904
|
+
preflightScript,
|
|
1905
|
+
commandScripts: commandScripts.length > 0 ? commandScripts : undefined,
|
|
1906
|
+
toolchainPaths: toolchainPaths.length > 0 ? toolchainPaths : undefined,
|
|
1907
|
+
proposalPath,
|
|
1908
|
+
allowWorkflowWrites,
|
|
1909
|
+
};
|
|
1910
|
+
const explicitWithManifest = explicitProtectedPathsWithoutControlRoot(manifest.spec.scope.protected, effectiveOpts);
|
|
1911
|
+
const explicitWithoutControlRoot = explicitProtectedPathsWithoutControlRoot([], effectiveOpts);
|
|
1912
|
+
const carvedOut = canCarveOutControlRootProposal(proposalPath, controlRoot, explicitWithManifest)
|
|
1913
|
+
&& isControlRootProposalWritableAllowed(proposalPath, manifest.spec.scope.writable, controlRoot, explicitWithManifest);
|
|
1914
|
+
const compact = new Set([
|
|
1915
|
+
...automationPathsFor(policyProfile, allowWorkflowWrites),
|
|
1916
|
+
controlRoot,
|
|
1917
|
+
]);
|
|
1918
|
+
if (manifestPath !== undefined)
|
|
1919
|
+
compact.add(manifestPath);
|
|
1920
|
+
if (digestsLockfile !== undefined && !pathCoveredBy(digestsLockfile, controlRoot)) {
|
|
1921
|
+
compact.add(digestsLockfile);
|
|
1922
|
+
}
|
|
1923
|
+
for (const instruction of instructions)
|
|
1924
|
+
compact.add(instruction);
|
|
1925
|
+
for (const skill of skills)
|
|
1926
|
+
compact.add(skill);
|
|
1927
|
+
if (preflightScript !== undefined && !pathCoveredBy(preflightScript, controlRoot)) {
|
|
1928
|
+
compact.add(preflightScript);
|
|
1929
|
+
}
|
|
1930
|
+
for (const script of commandScripts) {
|
|
1931
|
+
if (!pathCoveredBy(script, controlRoot))
|
|
1932
|
+
compact.add(script);
|
|
1933
|
+
const parentDir = commandScriptOutsideParentDir(script, controlRoot);
|
|
1934
|
+
if (parentDir !== undefined)
|
|
1935
|
+
compact.add(parentDir);
|
|
1936
|
+
}
|
|
1937
|
+
for (const entry of toolchainPaths) {
|
|
1938
|
+
if (!entry.startsWith('/') && !pathCoveredBy(entry, controlRoot))
|
|
1939
|
+
compact.add(entry);
|
|
1940
|
+
}
|
|
1941
|
+
if (policyProfile === 'github' && allowWorkflowWrites && options.githubSiblings !== undefined) {
|
|
1942
|
+
for (const sibling of options.githubSiblings) {
|
|
1943
|
+
if (!isWorkflowSubpathCaseInsensitive(sibling))
|
|
1944
|
+
compact.add(sibling);
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1947
|
+
return Object.freeze({
|
|
1948
|
+
controlRoot,
|
|
1949
|
+
...(manifestPath !== undefined ? { manifestPath } : {}),
|
|
1950
|
+
...(carvedOut && proposalPath !== undefined ? { carvedOutProposalPath: proposalPath } : {}),
|
|
1951
|
+
explicitWithoutControlRoot,
|
|
1952
|
+
compactMandatoryPaths: Object.freeze([...compact]),
|
|
1953
|
+
});
|
|
1954
|
+
}
|
|
1955
|
+
function isValidCredentialRef(value) {
|
|
1956
|
+
return value.length <= 64 && (IDENTIFIER_PATTERN.test(value) || COMMAND_ENV_NAME_PATTERN.test(value));
|
|
1957
|
+
}
|
|
1958
|
+
const RESOURCE_EXTENSION_PATTERN = /^\.[a-z0-9][a-z0-9_-]*(?:\.[a-z0-9][a-z0-9_-]*)*$/;
|
|
1959
|
+
const RULE_FAILURE_CODE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
|
|
1960
|
+
const RESOURCE_ACTIVATION_PHASES = Object.freeze([
|
|
1961
|
+
'author',
|
|
1962
|
+
'review',
|
|
1963
|
+
'repair',
|
|
1964
|
+
'rework',
|
|
1965
|
+
]);
|
|
1966
|
+
function validateResourceActivationRule(raw, path) {
|
|
1967
|
+
const rec = requireObject(raw, path, [
|
|
1968
|
+
'changedPaths',
|
|
1969
|
+
'extensions',
|
|
1970
|
+
'phases',
|
|
1971
|
+
'failedChecks',
|
|
1972
|
+
'failureCodes',
|
|
1973
|
+
]);
|
|
1974
|
+
const out = {};
|
|
1975
|
+
if (Object.hasOwn(rec, 'changedPaths') && rec['changedPaths'] !== undefined) {
|
|
1976
|
+
const rawPatterns = requireStringList(rec['changedPaths'], `${path}/changedPaths`, 1, LIMITS.ruleChangedPaths);
|
|
1977
|
+
const validated = [];
|
|
1978
|
+
for (const [idx, item] of rawPatterns.entries()) {
|
|
1979
|
+
const itemPath = `${path}/changedPaths/${idx}`;
|
|
1980
|
+
if (item.length === 0 || item.length > LIMITS.path) {
|
|
1981
|
+
manifestInvalid(`changedPaths entry must be 1..${LIMITS.path} characters`, itemPath);
|
|
1982
|
+
}
|
|
1983
|
+
const checked = validateScopePattern(item);
|
|
1984
|
+
if (!checked.ok) {
|
|
1985
|
+
manifestInvalid(`invalid changedPaths pattern "${item}": ${checked.errors[0]?.code ?? 'PATTERN_UNSUPPORTED'}`, itemPath);
|
|
1986
|
+
}
|
|
1987
|
+
validated.push(checked.value);
|
|
1988
|
+
}
|
|
1989
|
+
out.changedPaths = Object.freeze(validated);
|
|
1990
|
+
}
|
|
1991
|
+
if (Object.hasOwn(rec, 'extensions') && rec['extensions'] !== undefined) {
|
|
1992
|
+
const rawExts = requireStringList(rec['extensions'], `${path}/extensions`, 1, LIMITS.ruleExtensions);
|
|
1993
|
+
const validated = [];
|
|
1994
|
+
for (const [idx, item] of rawExts.entries()) {
|
|
1995
|
+
const itemPath = `${path}/extensions/${idx}`;
|
|
1996
|
+
if (item.length < 2 || item.length > LIMITS.ruleExtension || !RESOURCE_EXTENSION_PATTERN.test(item)) {
|
|
1997
|
+
manifestInvalid(`invalid extension "${item}" (expected lowercase ".ext" suffix of 2..${LIMITS.ruleExtension} characters)`, itemPath);
|
|
1998
|
+
}
|
|
1999
|
+
validated.push(item);
|
|
2000
|
+
}
|
|
2001
|
+
out.extensions = Object.freeze(validated);
|
|
2002
|
+
}
|
|
2003
|
+
if (Object.hasOwn(rec, 'phases') && rec['phases'] !== undefined) {
|
|
2004
|
+
const rawPhases = requireStringList(rec['phases'], `${path}/phases`, 1, LIMITS.rulePhases);
|
|
2005
|
+
const validated = [];
|
|
2006
|
+
for (const [idx, item] of rawPhases.entries()) {
|
|
2007
|
+
const itemPath = `${path}/phases/${idx}`;
|
|
2008
|
+
if (!RESOURCE_ACTIVATION_PHASES.includes(item)) {
|
|
2009
|
+
manifestInvalid(`unsupported activation phase "${item}" (expected one of ${RESOURCE_ACTIVATION_PHASES.join(', ')})`, itemPath);
|
|
2010
|
+
}
|
|
2011
|
+
validated.push(item);
|
|
2012
|
+
}
|
|
2013
|
+
out.phases = Object.freeze(validated);
|
|
2014
|
+
}
|
|
2015
|
+
if (Object.hasOwn(rec, 'failedChecks') && rec['failedChecks'] !== undefined) {
|
|
2016
|
+
const rawChecks = requireStringList(rec['failedChecks'], `${path}/failedChecks`, 1, LIMITS.ruleFailedChecks);
|
|
2017
|
+
const validated = [];
|
|
2018
|
+
for (const [idx, item] of rawChecks.entries()) {
|
|
2019
|
+
validated.push(requireIdentifier(item, `${path}/failedChecks/${idx}`));
|
|
2020
|
+
}
|
|
2021
|
+
out.failedChecks = Object.freeze(validated);
|
|
2022
|
+
}
|
|
2023
|
+
if (Object.hasOwn(rec, 'failureCodes') && rec['failureCodes'] !== undefined) {
|
|
2024
|
+
const rawCodes = requireStringList(rec['failureCodes'], `${path}/failureCodes`, 1, LIMITS.ruleFailureCodes);
|
|
2025
|
+
const validated = [];
|
|
2026
|
+
for (const [idx, item] of rawCodes.entries()) {
|
|
2027
|
+
const itemPath = `${path}/failureCodes/${idx}`;
|
|
2028
|
+
if (item.length < 1 || item.length > LIMITS.ruleFailureCode || !RULE_FAILURE_CODE_PATTERN.test(item)) {
|
|
2029
|
+
manifestInvalid(`invalid failure code "${item}"`, itemPath);
|
|
2030
|
+
}
|
|
2031
|
+
validated.push(item);
|
|
2032
|
+
}
|
|
2033
|
+
out.failureCodes = Object.freeze(validated);
|
|
2034
|
+
}
|
|
2035
|
+
if (out.changedPaths === undefined
|
|
2036
|
+
&& out.extensions === undefined
|
|
2037
|
+
&& out.phases === undefined
|
|
2038
|
+
&& out.failedChecks === undefined
|
|
2039
|
+
&& out.failureCodes === undefined) {
|
|
2040
|
+
manifestInvalid('conditional "when" rule must specify at least one predicate', path);
|
|
2041
|
+
}
|
|
2042
|
+
return Object.freeze(out);
|
|
2043
|
+
}
|
|
2044
|
+
function validateResourceEntry(value, path) {
|
|
2045
|
+
if (typeof value === 'string') {
|
|
2046
|
+
return normalizeRelativePath(value, path);
|
|
2047
|
+
}
|
|
2048
|
+
const rec = requireObject(value, path, ['path', 'when']);
|
|
2049
|
+
if (!Object.hasOwn(rec, 'path')) {
|
|
2050
|
+
manifestInvalid('resource entry object requires "path"', `${path}/path`);
|
|
2051
|
+
}
|
|
2052
|
+
const normalizedPath = normalizeRelativePath(rec['path'], `${path}/path`);
|
|
2053
|
+
if (!Object.hasOwn(rec, 'when') || rec['when'] === undefined) {
|
|
2054
|
+
return normalizedPath;
|
|
2055
|
+
}
|
|
2056
|
+
const when = validateResourceActivationRule(rec['when'], `${path}/when`);
|
|
2057
|
+
return Object.freeze({ path: normalizedPath, when });
|
|
2058
|
+
}
|
|
2059
|
+
function validateResourceEntryOrList(value, path) {
|
|
2060
|
+
if (typeof value === 'string' || isPlainObjectRecord(value)) {
|
|
2061
|
+
return Object.freeze([validateResourceEntry(value, path)]);
|
|
2062
|
+
}
|
|
2063
|
+
if (!Array.isArray(value) || value.length < 1 || value.length > 16) {
|
|
2064
|
+
manifestInvalid('expected a resource path/object or an array of 1..16 resource entries', path);
|
|
2065
|
+
}
|
|
2066
|
+
const seenPaths = new Set();
|
|
2067
|
+
const entries = [];
|
|
2068
|
+
for (const [idx, item] of value.entries()) {
|
|
2069
|
+
const itemPath = `${path}/${idx}`;
|
|
2070
|
+
const parsed = validateResourceEntry(item, itemPath);
|
|
2071
|
+
const normalizedPath = resolveTaskpackResourcePath(parsed);
|
|
2072
|
+
if (seenPaths.has(normalizedPath)) {
|
|
2073
|
+
manifestInvalid('duplicate list entry', path);
|
|
2074
|
+
}
|
|
2075
|
+
seenPaths.add(normalizedPath);
|
|
2076
|
+
entries.push(parsed);
|
|
2077
|
+
}
|
|
2078
|
+
return Object.freeze(entries);
|
|
2079
|
+
}
|
|
2080
|
+
function validateHandoffHeading(value, path) {
|
|
2081
|
+
if (typeof value !== 'string' || value.length < 1 || value.length > HANDOFF_LIMITS.maxHeadingChars) {
|
|
2082
|
+
manifestInvalid(`handoff heading must be a string of 1..${HANDOFF_LIMITS.maxHeadingChars} characters`, path);
|
|
2083
|
+
}
|
|
2084
|
+
if (/[\r\n\0\p{C}]/u.test(value) || value.trim().length === 0) {
|
|
2085
|
+
manifestInvalid('handoff heading must be a non-empty single-line string without control characters', path);
|
|
2086
|
+
}
|
|
2087
|
+
const trimmed = value.trim();
|
|
2088
|
+
const headingBody = /^(#{1,6})(?:[ \t]+(.*)|[ \t]*)$/.exec(trimmed)?.[2] ?? trimmed;
|
|
2089
|
+
const cleaned = headingBody.replace(/[ \t]+$/, '');
|
|
2090
|
+
const title = /^#+$/.test(cleaned) ? '' : cleaned.replace(/[ \t]+#+$/, '').trim();
|
|
2091
|
+
if (title.length === 0) {
|
|
2092
|
+
manifestInvalid('handoff heading must contain non-empty heading text', path);
|
|
2093
|
+
}
|
|
2094
|
+
return value;
|
|
2095
|
+
}
|
|
2096
|
+
function validateHandoffJsonPointer(value, path) {
|
|
2097
|
+
if (typeof value !== 'string' || value.length > HANDOFF_LIMITS.maxPointerChars) {
|
|
2098
|
+
manifestInvalid(`handoff JSON pointer must be a string of 0..${HANDOFF_LIMITS.maxPointerChars} characters`, path);
|
|
2099
|
+
}
|
|
2100
|
+
if (/[\0\r\n\p{C}]/u.test(value)) {
|
|
2101
|
+
manifestInvalid('handoff JSON pointer contains forbidden control characters', path);
|
|
2102
|
+
}
|
|
2103
|
+
if (value === '')
|
|
2104
|
+
return value;
|
|
2105
|
+
if (!value.startsWith('/')) {
|
|
2106
|
+
manifestInvalid(`invalid RFC 6901 JSON Pointer "${value}"`, path);
|
|
2107
|
+
}
|
|
2108
|
+
const rawSegments = value.slice(1).split('/');
|
|
2109
|
+
if (rawSegments.length > LIMITS.segments) {
|
|
2110
|
+
manifestInvalid(`handoff JSON pointer exceeds ${LIMITS.segments} segments`, path);
|
|
2111
|
+
}
|
|
2112
|
+
for (const segment of rawSegments) {
|
|
2113
|
+
let decoded = '';
|
|
2114
|
+
for (let i = 0; i < segment.length; i += 1) {
|
|
2115
|
+
const ch = segment[i];
|
|
2116
|
+
if (ch === '~') {
|
|
2117
|
+
const next = segment[i + 1];
|
|
2118
|
+
if (next === '0') {
|
|
2119
|
+
decoded += '~';
|
|
2120
|
+
i += 1;
|
|
2121
|
+
}
|
|
2122
|
+
else if (next === '1') {
|
|
2123
|
+
decoded += '/';
|
|
2124
|
+
i += 1;
|
|
2125
|
+
}
|
|
2126
|
+
else {
|
|
2127
|
+
manifestInvalid(`invalid RFC 6901 escape in JSON Pointer "${value}"`, path);
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
else {
|
|
2131
|
+
decoded += ch;
|
|
2132
|
+
}
|
|
2133
|
+
}
|
|
2134
|
+
if (FORBIDDEN_KEYS.has(decoded)) {
|
|
2135
|
+
manifestInvalid(`handoff JSON pointer must not reference forbidden property "${decoded}"`, path);
|
|
2136
|
+
}
|
|
2137
|
+
}
|
|
2138
|
+
return value;
|
|
2139
|
+
}
|
|
2140
|
+
function validateHandoffSelectors(raw, path) {
|
|
2141
|
+
if (!Array.isArray(raw) || raw.length < 1 || raw.length > HANDOFF_LIMITS.maxPerStep) {
|
|
2142
|
+
manifestInvalid(`handoffs must contain 1..${HANDOFF_LIMITS.maxPerStep} selectors`, path);
|
|
2143
|
+
}
|
|
2144
|
+
const seenIds = new Set();
|
|
2145
|
+
const selectors = [];
|
|
2146
|
+
let aggregateBytes = 0;
|
|
2147
|
+
for (const [idx, item] of raw.entries()) {
|
|
2148
|
+
const itemPath = `${path}/${idx}`;
|
|
2149
|
+
const rec = requireObject(item, itemPath, ['id', 'fromStep', 'source', 'select', 'maxBytes', 'required']);
|
|
2150
|
+
let id;
|
|
2151
|
+
if (Object.hasOwn(rec, 'id') && rec['id'] !== undefined) {
|
|
2152
|
+
id = requireIdentifier(rec['id'], `${itemPath}/id`);
|
|
2153
|
+
}
|
|
2154
|
+
const effectiveId = id ?? `handoff-${idx + 1}`;
|
|
2155
|
+
if (seenIds.has(effectiveId)) {
|
|
2156
|
+
manifestInvalid(`duplicate handoff selector id "${effectiveId}"`, `${itemPath}/id`);
|
|
2157
|
+
}
|
|
2158
|
+
seenIds.add(effectiveId);
|
|
2159
|
+
if (!Object.hasOwn(rec, 'fromStep')) {
|
|
2160
|
+
manifestInvalid('handoff selector requires "fromStep"', `${itemPath}/fromStep`);
|
|
2161
|
+
}
|
|
2162
|
+
const fromStep = requireIdentifier(rec['fromStep'], `${itemPath}/fromStep`);
|
|
2163
|
+
if (!Object.hasOwn(rec, 'source')) {
|
|
2164
|
+
manifestInvalid('handoff selector requires "source"', `${itemPath}/source`);
|
|
2165
|
+
}
|
|
2166
|
+
const rawSource = rec['source'];
|
|
2167
|
+
if (!isPlainObjectRecord(rawSource)) {
|
|
2168
|
+
manifestInvalid('handoff source must be an object', `${itemPath}/source`);
|
|
2169
|
+
}
|
|
2170
|
+
if (!Object.hasOwn(rawSource, 'kind') || typeof rawSource['kind'] !== 'string') {
|
|
2171
|
+
manifestInvalid('handoff source requires string "kind"', `${itemPath}/source/kind`);
|
|
2172
|
+
}
|
|
2173
|
+
let source;
|
|
2174
|
+
const sourceKind = rawSource['kind'];
|
|
2175
|
+
if (sourceKind === 'artifact') {
|
|
2176
|
+
const artifactSrc = requireObject(rawSource, `${itemPath}/source`, ['kind', 'path']);
|
|
2177
|
+
if (!Object.hasOwn(artifactSrc, 'path') || typeof artifactSrc['path'] !== 'string') {
|
|
2178
|
+
manifestInvalid('artifact handoff source requires string "path"', `${itemPath}/source/path`);
|
|
2179
|
+
}
|
|
2180
|
+
const checkedPath = validateRelativePath(artifactSrc['path']);
|
|
2181
|
+
if (!checkedPath.ok) {
|
|
2182
|
+
manifestInvalid(`invalid handoff artifact path "${artifactSrc['path']}"`, `${itemPath}/source/path`);
|
|
2183
|
+
}
|
|
2184
|
+
source = Object.freeze({ kind: 'artifact', path: checkedPath.value });
|
|
2185
|
+
}
|
|
2186
|
+
else if (sourceKind === 'submission') {
|
|
2187
|
+
requireObject(rawSource, `${itemPath}/source`, ['kind']);
|
|
2188
|
+
source = Object.freeze({ kind: 'submission' });
|
|
2189
|
+
}
|
|
2190
|
+
else if (sourceKind === 'verdict') {
|
|
2191
|
+
requireObject(rawSource, `${itemPath}/source`, ['kind']);
|
|
2192
|
+
source = Object.freeze({ kind: 'verdict' });
|
|
2193
|
+
}
|
|
2194
|
+
else {
|
|
2195
|
+
manifestInvalid(`unsupported handoff source kind "${sourceKind}"`, `${itemPath}/source/kind`);
|
|
2196
|
+
}
|
|
2197
|
+
if (!Object.hasOwn(rec, 'select')) {
|
|
2198
|
+
manifestInvalid('handoff selector requires "select"', `${itemPath}/select`);
|
|
2199
|
+
}
|
|
2200
|
+
const rawSelect = rec['select'];
|
|
2201
|
+
if (!isPlainObjectRecord(rawSelect)) {
|
|
2202
|
+
manifestInvalid('handoff select must be an object', `${itemPath}/select`);
|
|
2203
|
+
}
|
|
2204
|
+
if (!Object.hasOwn(rawSelect, 'kind') || typeof rawSelect['kind'] !== 'string') {
|
|
2205
|
+
manifestInvalid('handoff select requires string "kind"', `${itemPath}/select/kind`);
|
|
2206
|
+
}
|
|
2207
|
+
let select;
|
|
2208
|
+
const selectKind = rawSelect['kind'];
|
|
2209
|
+
if (selectKind === 'markdown_heading') {
|
|
2210
|
+
const mdSelect = requireObject(rawSelect, `${itemPath}/select`, ['kind', 'heading', 'includeSubheadings']);
|
|
2211
|
+
if (!Object.hasOwn(mdSelect, 'heading')) {
|
|
2212
|
+
manifestInvalid('markdown_heading select requires "heading"', `${itemPath}/select/heading`);
|
|
2213
|
+
}
|
|
2214
|
+
const heading = validateHandoffHeading(mdSelect['heading'], `${itemPath}/select/heading`);
|
|
2215
|
+
const includeSubheadings = Object.hasOwn(mdSelect, 'includeSubheadings') && mdSelect['includeSubheadings'] !== undefined
|
|
2216
|
+
? requireBoolean(mdSelect['includeSubheadings'], `${itemPath}/select/includeSubheadings`)
|
|
2217
|
+
: undefined;
|
|
2218
|
+
select = Object.freeze({
|
|
2219
|
+
kind: 'markdown_heading',
|
|
2220
|
+
heading,
|
|
2221
|
+
...(includeSubheadings === undefined ? {} : { includeSubheadings }),
|
|
2222
|
+
});
|
|
2223
|
+
}
|
|
2224
|
+
else if (selectKind === 'json_pointer') {
|
|
2225
|
+
const jpSelect = requireObject(rawSelect, `${itemPath}/select`, ['kind', 'pointers']);
|
|
2226
|
+
if (!Object.hasOwn(jpSelect, 'pointers') || !Array.isArray(jpSelect['pointers'])) {
|
|
2227
|
+
manifestInvalid(`json_pointer select requires 1..${HANDOFF_LIMITS.maxPointers} pointers`, `${itemPath}/select/pointers`);
|
|
2228
|
+
}
|
|
2229
|
+
const rawPointers = jpSelect['pointers'];
|
|
2230
|
+
if (rawPointers.length < 1 || rawPointers.length > HANDOFF_LIMITS.maxPointers) {
|
|
2231
|
+
manifestInvalid(`json_pointer select requires 1..${HANDOFF_LIMITS.maxPointers} pointers`, `${itemPath}/select/pointers`);
|
|
2232
|
+
}
|
|
2233
|
+
const seenPointers = new Set();
|
|
2234
|
+
const pointers = [];
|
|
2235
|
+
for (const [pIdx, pVal] of rawPointers.entries()) {
|
|
2236
|
+
const ptr = validateHandoffJsonPointer(pVal, `${itemPath}/select/pointers/${pIdx}`);
|
|
2237
|
+
if (seenPointers.has(ptr)) {
|
|
2238
|
+
manifestInvalid(`duplicate handoff JSON pointer "${ptr}"`, `${itemPath}/select/pointers/${pIdx}`);
|
|
2239
|
+
}
|
|
2240
|
+
seenPointers.add(ptr);
|
|
2241
|
+
pointers.push(ptr);
|
|
2242
|
+
}
|
|
2243
|
+
select = Object.freeze({
|
|
2244
|
+
kind: 'json_pointer',
|
|
2245
|
+
pointers: Object.freeze(pointers),
|
|
2246
|
+
});
|
|
2247
|
+
}
|
|
2248
|
+
else if (selectKind === 'full') {
|
|
2249
|
+
requireObject(rawSelect, `${itemPath}/select`, ['kind']);
|
|
2250
|
+
select = Object.freeze({ kind: 'full' });
|
|
2251
|
+
}
|
|
2252
|
+
else {
|
|
2253
|
+
manifestInvalid(`unsupported handoff select kind "${selectKind}"`, `${itemPath}/select/kind`);
|
|
2254
|
+
}
|
|
2255
|
+
let maxBytes;
|
|
2256
|
+
if (Object.hasOwn(rec, 'maxBytes') && rec['maxBytes'] !== undefined) {
|
|
2257
|
+
maxBytes = requireSafeIntInRange(rec['maxBytes'], `${itemPath}/maxBytes`, HANDOFF_LIMITS.minBytes, HANDOFF_LIMITS.maxBytes);
|
|
2258
|
+
}
|
|
2259
|
+
aggregateBytes += maxBytes ?? HANDOFF_LIMITS.defaultBytes;
|
|
2260
|
+
if (aggregateBytes > HANDOFF_LIMITS.maxAggregateBytes) {
|
|
2261
|
+
manifestInvalid(`aggregate handoff maxBytes (${aggregateBytes}) exceeds ${HANDOFF_LIMITS.maxAggregateBytes} bytes`, itemPath);
|
|
2262
|
+
}
|
|
2263
|
+
let required;
|
|
2264
|
+
if (Object.hasOwn(rec, 'required') && rec['required'] !== undefined) {
|
|
2265
|
+
required = requireBoolean(rec['required'], `${itemPath}/required`);
|
|
2266
|
+
}
|
|
2267
|
+
selectors.push(Object.freeze({
|
|
2268
|
+
...(id === undefined ? {} : { id }),
|
|
2269
|
+
fromStep,
|
|
2270
|
+
source,
|
|
2271
|
+
select,
|
|
2272
|
+
...(maxBytes === undefined ? {} : { maxBytes }),
|
|
2273
|
+
...(required === undefined ? {} : { required }),
|
|
2274
|
+
}));
|
|
2275
|
+
}
|
|
2276
|
+
return Object.freeze(selectors);
|
|
2277
|
+
}
|
|
2278
|
+
function validateToolchainPath(value, path) {
|
|
2279
|
+
const text = requireString(value, path, 1, 512);
|
|
2280
|
+
if (text !== text.trim()) {
|
|
2281
|
+
manifestInvalid('toolchainPaths entry must not have leading or trailing whitespace', path);
|
|
2282
|
+
}
|
|
2283
|
+
if (text.includes(':') || text.includes('\\')) {
|
|
2284
|
+
manifestInvalid('toolchainPaths entry must not contain ":" or "\\"', path);
|
|
2285
|
+
}
|
|
2286
|
+
if (text.startsWith('/')) {
|
|
2287
|
+
if (text === '/') {
|
|
2288
|
+
manifestInvalid('toolchainPaths entry must not be root "/"', path);
|
|
2289
|
+
}
|
|
2290
|
+
const segments = text.slice(1).split('/');
|
|
2291
|
+
for (const segment of segments) {
|
|
2292
|
+
if (segment === '' || segment === '.' || segment === '..') {
|
|
2293
|
+
manifestInvalid(`toolchainPaths entry "${text}" contains forbidden segment "${segment}"`, path);
|
|
2294
|
+
}
|
|
2295
|
+
}
|
|
2296
|
+
return text;
|
|
2297
|
+
}
|
|
2298
|
+
return normalizeRelativePath(text, path);
|
|
2299
|
+
}
|
|
2300
|
+
function validateVersionPath(value, path) {
|
|
2301
|
+
const text = requireString(value, path, 1, 256);
|
|
2302
|
+
if (!VERSION_PATH_PATTERN.test(text)) {
|
|
2303
|
+
manifestInvalid(`invalid versionPath selector "${text}"`, path);
|
|
2304
|
+
}
|
|
2305
|
+
for (const forbidden of FORBIDDEN_KEYS) {
|
|
2306
|
+
const segRe = new RegExp(`(?:^|[.\\['"])${forbidden}(?:$|[.\\]'"])`);
|
|
2307
|
+
if (segRe.test(text)) {
|
|
2308
|
+
manifestInvalid(`versionPath must not reference forbidden property "${forbidden}"`, path);
|
|
2309
|
+
}
|
|
2310
|
+
}
|
|
2311
|
+
return text;
|
|
2312
|
+
}
|
|
2313
|
+
function parseBaselineAlignmentObject(raw, path, errorCode, defaults) {
|
|
2314
|
+
function fail(message, fieldPath = path) {
|
|
2315
|
+
throw new TaskpackError(errorCode, message, fieldPath);
|
|
2316
|
+
}
|
|
2317
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
2318
|
+
fail('expected an object');
|
|
2319
|
+
}
|
|
2320
|
+
const proto = Object.getPrototypeOf(raw);
|
|
2321
|
+
if (proto !== Object.prototype && proto !== null) {
|
|
2322
|
+
fail('expected an object');
|
|
2323
|
+
}
|
|
2324
|
+
const record = raw;
|
|
2325
|
+
for (const key of Object.keys(record)) {
|
|
2326
|
+
if (!Object.hasOwn(record, key)
|
|
2327
|
+
|| FORBIDDEN_KEYS.has(key)
|
|
2328
|
+
|| (key !== 'policy' && key !== 'maxConflictFiles' && key !== 'maxConflictBytes')) {
|
|
2329
|
+
fail(`unknown field "${key}"`);
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
let policy = defaults.policy;
|
|
2333
|
+
if (Object.hasOwn(record, 'policy') && record['policy'] !== undefined) {
|
|
2334
|
+
const rawPolicy = record['policy'];
|
|
2335
|
+
if (typeof rawPolicy !== 'string' || !BASELINE_ALIGNMENT_POLICIES.includes(rawPolicy)) {
|
|
2336
|
+
fail('spec.baselineAlignment.policy must be "off", "fail-fast", or "extract-context"', `${path}/policy`);
|
|
2337
|
+
}
|
|
2338
|
+
policy = rawPolicy;
|
|
2339
|
+
}
|
|
2340
|
+
let maxConflictFiles = defaults.maxConflictFiles;
|
|
2341
|
+
if (Object.hasOwn(record, 'maxConflictFiles') && record['maxConflictFiles'] !== undefined) {
|
|
2342
|
+
const rawMaxFiles = record['maxConflictFiles'];
|
|
2343
|
+
if (typeof rawMaxFiles !== 'number') {
|
|
2344
|
+
fail(`spec.baselineAlignment.maxConflictFiles must be an integer in [${MIN_BASELINE_MAX_CONFLICT_FILES}, ${MAX_BASELINE_MAX_CONFLICT_FILES}]`, `${path}/maxConflictFiles`);
|
|
2345
|
+
}
|
|
2346
|
+
const numMaxFiles = rawMaxFiles;
|
|
2347
|
+
if (!Number.isSafeInteger(numMaxFiles)
|
|
2348
|
+
|| Object.is(numMaxFiles, -0)
|
|
2349
|
+
|| numMaxFiles < MIN_BASELINE_MAX_CONFLICT_FILES
|
|
2350
|
+
|| numMaxFiles > MAX_BASELINE_MAX_CONFLICT_FILES) {
|
|
2351
|
+
fail(`spec.baselineAlignment.maxConflictFiles must be an integer in [${MIN_BASELINE_MAX_CONFLICT_FILES}, ${MAX_BASELINE_MAX_CONFLICT_FILES}]`, `${path}/maxConflictFiles`);
|
|
2352
|
+
}
|
|
2353
|
+
maxConflictFiles = numMaxFiles;
|
|
2354
|
+
}
|
|
2355
|
+
let maxConflictBytes = defaults.maxConflictBytes;
|
|
2356
|
+
if (Object.hasOwn(record, 'maxConflictBytes') && record['maxConflictBytes'] !== undefined) {
|
|
2357
|
+
const rawMaxBytes = record['maxConflictBytes'];
|
|
2358
|
+
if (typeof rawMaxBytes !== 'number') {
|
|
2359
|
+
fail(`spec.baselineAlignment.maxConflictBytes must be an integer in [${MIN_BASELINE_MAX_CONFLICT_BYTES}, ${MAX_BASELINE_MAX_CONFLICT_BYTES}]`, `${path}/maxConflictBytes`);
|
|
2360
|
+
}
|
|
2361
|
+
const numMaxBytes = rawMaxBytes;
|
|
2362
|
+
if (!Number.isSafeInteger(numMaxBytes)
|
|
2363
|
+
|| Object.is(numMaxBytes, -0)
|
|
2364
|
+
|| numMaxBytes < MIN_BASELINE_MAX_CONFLICT_BYTES
|
|
2365
|
+
|| numMaxBytes > MAX_BASELINE_MAX_CONFLICT_BYTES) {
|
|
2366
|
+
fail(`spec.baselineAlignment.maxConflictBytes must be an integer in [${MIN_BASELINE_MAX_CONFLICT_BYTES}, ${MAX_BASELINE_MAX_CONFLICT_BYTES}]`, `${path}/maxConflictBytes`);
|
|
2367
|
+
}
|
|
2368
|
+
maxConflictBytes = numMaxBytes;
|
|
2369
|
+
}
|
|
2370
|
+
return Object.freeze({ policy, maxConflictFiles, maxConflictBytes });
|
|
2371
|
+
}
|
|
2372
|
+
/** Validate `spec.baselineAlignment` (`off | fail-fast | extract-context`, file/byte bounds, null-prototype-safe closed keys). */
|
|
2373
|
+
export function validateBaselineAlignmentDeclaration(raw, path = '/spec/baselineAlignment') {
|
|
2374
|
+
return parseBaselineAlignmentObject(raw, path, 'TASKPACK_MANIFEST_INVALID', {
|
|
2375
|
+
policy: DEFAULT_BASELINE_ALIGNMENT_POLICY,
|
|
2376
|
+
maxConflictFiles: DEFAULT_BASELINE_MAX_CONFLICT_FILES,
|
|
2377
|
+
maxConflictBytes: DEFAULT_BASELINE_MAX_CONFLICT_BYTES,
|
|
2378
|
+
});
|
|
2379
|
+
}
|
|
2380
|
+
/** Parse a CLI/Action runtime baseline alignment policy string (`off | fail-fast | extract-context`). */
|
|
2381
|
+
export function parseBaselineAlignmentPolicy(raw, path = '/baselineAlignment') {
|
|
2382
|
+
if (typeof raw !== 'string' || !BASELINE_ALIGNMENT_POLICIES.includes(raw)) {
|
|
2383
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', 'baselineAlignment policy must be "off", "fail-fast", or "extract-context"', path);
|
|
2384
|
+
}
|
|
2385
|
+
return raw;
|
|
2386
|
+
}
|
|
2387
|
+
/** Resolve effective `ResolvedBaselineAlignmentConfig` from manifest declaration plus optional CLI/Action runtime override. */
|
|
2388
|
+
export function resolveBaselineAlignmentConfig(manifestConfig, override) {
|
|
2389
|
+
const base = manifestConfig !== undefined
|
|
2390
|
+
? validateBaselineAlignmentDeclaration(manifestConfig, '/spec/baselineAlignment')
|
|
2391
|
+
: Object.freeze({
|
|
2392
|
+
policy: DEFAULT_BASELINE_ALIGNMENT_POLICY,
|
|
2393
|
+
maxConflictFiles: DEFAULT_BASELINE_MAX_CONFLICT_FILES,
|
|
2394
|
+
maxConflictBytes: DEFAULT_BASELINE_MAX_CONFLICT_BYTES,
|
|
2395
|
+
});
|
|
2396
|
+
if (override === undefined) {
|
|
2397
|
+
return base;
|
|
2398
|
+
}
|
|
2399
|
+
if (typeof override === 'string') {
|
|
2400
|
+
const policy = parseBaselineAlignmentPolicy(override, '/baselineAlignment');
|
|
2401
|
+
return Object.freeze({
|
|
2402
|
+
policy,
|
|
2403
|
+
maxConflictFiles: base.maxConflictFiles,
|
|
2404
|
+
maxConflictBytes: base.maxConflictBytes,
|
|
2405
|
+
});
|
|
2406
|
+
}
|
|
2407
|
+
return parseBaselineAlignmentObject(override, '/baselineAlignment', 'ACTION_INPUT_INVALID', base);
|
|
2408
|
+
}
|
|
2409
|
+
function validateExecutionSection(rawExecution, controlRoot) {
|
|
2410
|
+
const exec = requireObject(rawExecution, '/spec/execution', ['mode', 'capabilities', 'digests']);
|
|
2411
|
+
let mode = 'strict';
|
|
2412
|
+
if (exec['mode'] !== undefined) {
|
|
2413
|
+
const modeStr = requireString(exec['mode'], '/spec/execution/mode', 1, 16);
|
|
2414
|
+
if (modeStr !== 'strict' && modeStr !== 'privileged') {
|
|
2415
|
+
manifestInvalid('spec.execution.mode must be "strict" or "privileged"', '/spec/execution/mode');
|
|
2416
|
+
}
|
|
2417
|
+
mode = modeStr;
|
|
2418
|
+
}
|
|
2419
|
+
const overrides = {};
|
|
2420
|
+
if (exec['capabilities'] !== undefined) {
|
|
2421
|
+
const rawCaps = requireObject(exec['capabilities'], '/spec/execution/capabilities', [
|
|
2422
|
+
'allowHostEnv', 'allowHostPath', 'mountReadOnlyGit',
|
|
2423
|
+
'allowCheckNetwork', 'allowWorkflowWrites', 'allowAgentNetwork',
|
|
2424
|
+
]);
|
|
2425
|
+
if (rawCaps['allowHostEnv'] !== undefined)
|
|
2426
|
+
overrides.allowHostEnv = requireBoolean(rawCaps['allowHostEnv'], '/spec/execution/capabilities/allowHostEnv');
|
|
2427
|
+
if (rawCaps['allowHostPath'] !== undefined)
|
|
2428
|
+
overrides.allowHostPath = requireBoolean(rawCaps['allowHostPath'], '/spec/execution/capabilities/allowHostPath');
|
|
2429
|
+
if (rawCaps['mountReadOnlyGit'] !== undefined)
|
|
2430
|
+
overrides.mountReadOnlyGit = requireBoolean(rawCaps['mountReadOnlyGit'], '/spec/execution/capabilities/mountReadOnlyGit');
|
|
2431
|
+
if (rawCaps['allowCheckNetwork'] !== undefined)
|
|
2432
|
+
overrides.allowCheckNetwork = requireBoolean(rawCaps['allowCheckNetwork'], '/spec/execution/capabilities/allowCheckNetwork');
|
|
2433
|
+
if (rawCaps['allowWorkflowWrites'] !== undefined)
|
|
2434
|
+
overrides.allowWorkflowWrites = requireBoolean(rawCaps['allowWorkflowWrites'], '/spec/execution/capabilities/allowWorkflowWrites');
|
|
2435
|
+
if (rawCaps['allowAgentNetwork'] !== undefined)
|
|
2436
|
+
overrides.allowAgentNetwork = requireBoolean(rawCaps['allowAgentNetwork'], '/spec/execution/capabilities/allowAgentNetwork');
|
|
2437
|
+
}
|
|
2438
|
+
const capabilities = resolveExecutionCapabilities(mode, overrides);
|
|
2439
|
+
let pinDigests = false;
|
|
2440
|
+
let lockfile;
|
|
2441
|
+
if (exec['digests'] !== undefined) {
|
|
2442
|
+
const rawDigests = requireObject(exec['digests'], '/spec/execution/digests', ['pinDigests', 'lockfile']);
|
|
2443
|
+
if (rawDigests['pinDigests'] !== undefined) {
|
|
2444
|
+
pinDigests = requireBoolean(rawDigests['pinDigests'], '/spec/execution/digests/pinDigests');
|
|
2445
|
+
}
|
|
2446
|
+
if (rawDigests['lockfile'] !== undefined) {
|
|
2447
|
+
lockfile = normalizeRelativePath(rawDigests['lockfile'], '/spec/execution/digests/lockfile');
|
|
2448
|
+
}
|
|
2449
|
+
}
|
|
2450
|
+
if (pinDigests && lockfile === undefined) {
|
|
2451
|
+
lockfile = `${controlRoot}/digests.lock.json`;
|
|
2452
|
+
}
|
|
2453
|
+
const digests = Object.freeze({
|
|
2454
|
+
pinDigests,
|
|
2455
|
+
...(lockfile === undefined ? {} : { lockfile }),
|
|
2456
|
+
});
|
|
2457
|
+
return Object.freeze({ mode, capabilities, digests });
|
|
2458
|
+
}
|
|
2459
|
+
function collectStrictAncestors(startId, getDeps) {
|
|
2460
|
+
const visited = new Set();
|
|
2461
|
+
const stack = [...(getDeps(startId) ?? [])];
|
|
2462
|
+
while (stack.length > 0) {
|
|
2463
|
+
const current = stack.pop();
|
|
2464
|
+
if (visited.has(current))
|
|
2465
|
+
continue;
|
|
2466
|
+
visited.add(current);
|
|
2467
|
+
for (const parent of getDeps(current) ?? []) {
|
|
2468
|
+
stack.push(parent);
|
|
2469
|
+
}
|
|
2470
|
+
}
|
|
2471
|
+
return visited;
|
|
2472
|
+
}
|
|
2473
|
+
function validateStepsDag(rawSteps, roles, roleById, checkIds, executionMode) {
|
|
2474
|
+
if (!Array.isArray(rawSteps) || rawSteps.length < 1 || rawSteps.length > MAX_TASKPACK_STEPS) {
|
|
2475
|
+
manifestInvalid(`spec.steps must contain 1..${MAX_TASKPACK_STEPS} entries`, '/spec/steps');
|
|
2476
|
+
}
|
|
2477
|
+
const reservedStepIds = new Set(['controller.scope', 'controller.no-change']);
|
|
2478
|
+
const stepIds = new Set();
|
|
2479
|
+
const steps = [];
|
|
2480
|
+
for (const [idx, item] of rawSteps.entries()) {
|
|
2481
|
+
const sPath = `/spec/steps/${idx}`;
|
|
2482
|
+
const rawStep = requireObject(item, sPath, ['id', 'kind', 'role', 'check', 'dependsOn', 'onRework', 'handoffs']);
|
|
2483
|
+
const id = requireIdentifier(rawStep['id'], `${sPath}/id`);
|
|
2484
|
+
if (stepIds.has(id))
|
|
2485
|
+
manifestInvalid(`duplicate step id "${id}"`, `${sPath}/id`);
|
|
2486
|
+
if (reservedStepIds.has(id))
|
|
2487
|
+
manifestInvalid(`step id "${id}" is reserved`, `${sPath}/id`);
|
|
2488
|
+
stepIds.add(id);
|
|
2489
|
+
const kindStr = requireString(rawStep['kind'], `${sPath}/kind`, 1, 16);
|
|
2490
|
+
if (kindStr !== 'agent' && kindStr !== 'check' && kindStr !== 'compact') {
|
|
2491
|
+
manifestInvalid('step kind must be "agent", "check", or "compact"', `${sPath}/kind`);
|
|
2492
|
+
}
|
|
2493
|
+
const kind = kindStr;
|
|
2494
|
+
let role;
|
|
2495
|
+
let check;
|
|
2496
|
+
if (kind === 'agent' || kind === 'compact') {
|
|
2497
|
+
if (rawStep['check'] !== undefined) {
|
|
2498
|
+
manifestInvalid(`step "${id}" of kind "${kind}" must not specify "check"`, `${sPath}/check`);
|
|
2499
|
+
}
|
|
2500
|
+
role = requireIdentifier(rawStep['role'], `${sPath}/role`);
|
|
2501
|
+
const declaredRole = roleById.get(role);
|
|
2502
|
+
if (declaredRole === undefined) {
|
|
2503
|
+
manifestInvalid(`step "${id}" references unknown role "${role}"`, `${sPath}/role`);
|
|
2504
|
+
}
|
|
2505
|
+
if (kind === 'compact') {
|
|
2506
|
+
if (executionMode === 'delegated' || declaredRole.provider === 'delegated') {
|
|
2507
|
+
manifestInvalid(`compact step "${id}" cannot target delegated role "${role}"`, `${sPath}/role`);
|
|
2508
|
+
}
|
|
2509
|
+
}
|
|
2510
|
+
}
|
|
2511
|
+
else {
|
|
2512
|
+
if (rawStep['role'] !== undefined) {
|
|
2513
|
+
manifestInvalid(`check step "${id}" must not specify "role"`, `${sPath}/role`);
|
|
2514
|
+
}
|
|
2515
|
+
check = requireIdentifier(rawStep['check'], `${sPath}/check`);
|
|
2516
|
+
if (!checkIds.has(check)) {
|
|
2517
|
+
manifestInvalid(`check step "${id}" references unknown check "${check}"`, `${sPath}/check`);
|
|
2518
|
+
}
|
|
2519
|
+
}
|
|
2520
|
+
let dependsOn = Object.freeze([]);
|
|
2521
|
+
if (rawStep['dependsOn'] !== undefined) {
|
|
2522
|
+
const deps = requireStringList(rawStep['dependsOn'], `${sPath}/dependsOn`, 0, MAX_TASKPACK_STEPS - 1);
|
|
2523
|
+
for (const [dIdx, depId] of deps.entries()) {
|
|
2524
|
+
requireIdentifier(depId, `${sPath}/dependsOn/${dIdx}`);
|
|
2525
|
+
}
|
|
2526
|
+
dependsOn = Object.freeze([...deps]);
|
|
2527
|
+
}
|
|
2528
|
+
let onRework;
|
|
2529
|
+
if (rawStep['onRework'] !== undefined) {
|
|
2530
|
+
if (kind === 'compact') {
|
|
2531
|
+
manifestInvalid(`compact step "${id}" must not declare onRework`, `${sPath}/onRework`);
|
|
2532
|
+
}
|
|
2533
|
+
const rawRework = requireObject(rawStep['onRework'], `${sPath}/onRework`, ['rejectTo', 'maxReworks']);
|
|
2534
|
+
const rejectTo = requireIdentifier(rawRework['rejectTo'], `${sPath}/onRework/rejectTo`);
|
|
2535
|
+
const maxReworks = requireSafeIntInRange(rawRework['maxReworks'], `${sPath}/onRework/maxReworks`, 1, Math.min(MAX_STEP_REWORKS, LIMITS.maxReworks));
|
|
2536
|
+
onRework = Object.freeze({ rejectTo, maxReworks });
|
|
2537
|
+
}
|
|
2538
|
+
let handoffs;
|
|
2539
|
+
if (Object.hasOwn(rawStep, 'handoffs') && rawStep['handoffs'] !== undefined) {
|
|
2540
|
+
if (kind !== 'agent') {
|
|
2541
|
+
manifestInvalid(`step "${id}" of kind "${kind}" must not declare handoffs`, `${sPath}/handoffs`);
|
|
2542
|
+
}
|
|
2543
|
+
handoffs = validateHandoffSelectors(rawStep['handoffs'], `${sPath}/handoffs`);
|
|
2544
|
+
}
|
|
2545
|
+
steps.push(Object.freeze({
|
|
2546
|
+
id,
|
|
2547
|
+
kind,
|
|
2548
|
+
...(role === undefined ? {} : { role }),
|
|
2549
|
+
...(check === undefined ? {} : { check }),
|
|
2550
|
+
dependsOn,
|
|
2551
|
+
...(onRework === undefined ? {} : { onRework }),
|
|
2552
|
+
...(handoffs === undefined ? {} : { handoffs }),
|
|
2553
|
+
}));
|
|
2554
|
+
}
|
|
2555
|
+
const stepById = new Map(steps.map(s => [s.id, s]));
|
|
2556
|
+
for (const [idx, step] of steps.entries()) {
|
|
2557
|
+
for (const [dIdx, depId] of step.dependsOn.entries()) {
|
|
2558
|
+
if (!stepById.has(depId)) {
|
|
2559
|
+
manifestInvalid(`step "${step.id}" dependsOn unknown step "${depId}"`, `/spec/steps/${idx}/dependsOn/${dIdx}`);
|
|
2560
|
+
}
|
|
2561
|
+
if (depId === step.id) {
|
|
2562
|
+
manifestInvalid(`step "${step.id}" cannot depend on itself`, `/spec/steps/${idx}/dependsOn/${dIdx}`);
|
|
2563
|
+
}
|
|
2564
|
+
}
|
|
2565
|
+
if (step.onRework !== undefined && !stepById.has(step.onRework.rejectTo)) {
|
|
2566
|
+
manifestInvalid(`step "${step.id}" onRework.rejectTo references unknown step "${step.onRework.rejectTo}"`, `/spec/steps/${idx}/onRework/rejectTo`);
|
|
2567
|
+
}
|
|
2568
|
+
}
|
|
2569
|
+
const state = new Map();
|
|
2570
|
+
const dfsCycle = (id) => {
|
|
2571
|
+
const cur = state.get(id) ?? 0;
|
|
2572
|
+
if (cur === 2)
|
|
2573
|
+
return;
|
|
2574
|
+
if (cur === 1) {
|
|
2575
|
+
manifestInvalid(`spec.steps contains a dependency cycle involving "${id}"`, '/spec/steps');
|
|
2576
|
+
}
|
|
2577
|
+
state.set(id, 1);
|
|
2578
|
+
const node = stepById.get(id);
|
|
2579
|
+
for (const dep of node.dependsOn) {
|
|
2580
|
+
dfsCycle(dep);
|
|
2581
|
+
}
|
|
2582
|
+
state.set(id, 2);
|
|
2583
|
+
};
|
|
2584
|
+
for (const step of steps)
|
|
2585
|
+
dfsCycle(step.id);
|
|
2586
|
+
const strictAncestors = (startId) => (collectStrictAncestors(startId, id => stepById.get(id)?.dependsOn));
|
|
2587
|
+
for (const [roleIdx, roleDecl] of roles.entries()) {
|
|
2588
|
+
if (roleDecl.handoffs === undefined)
|
|
2589
|
+
continue;
|
|
2590
|
+
for (const [hIdx, handoff] of roleDecl.handoffs.entries()) {
|
|
2591
|
+
const diagPath = `/spec/roles/${roleIdx}/handoffs/${hIdx}/fromStep`;
|
|
2592
|
+
const sourceStep = stepById.get(handoff.fromStep);
|
|
2593
|
+
if (sourceStep === undefined) {
|
|
2594
|
+
manifestInvalid(`role "${roleDecl.id}" handoff fromStep references unknown step "${handoff.fromStep}"`, diagPath);
|
|
2595
|
+
}
|
|
2596
|
+
if (sourceStep.kind === 'compact') {
|
|
2597
|
+
manifestInvalid(`role "${roleDecl.id}" handoff fromStep "${handoff.fromStep}" must not reference a compact step`, diagPath);
|
|
2598
|
+
}
|
|
2599
|
+
if (sourceStep.kind === 'check' && handoff.source.kind === 'artifact') {
|
|
2600
|
+
manifestInvalid(`role "${roleDecl.id}" handoff fromStep "${handoff.fromStep}" is a check step and cannot supply an artifact handoff`, `/spec/roles/${roleIdx}/handoffs/${hIdx}/source/kind`);
|
|
2601
|
+
}
|
|
2602
|
+
}
|
|
2603
|
+
}
|
|
2604
|
+
for (const [idx, step] of steps.entries()) {
|
|
2605
|
+
if (step.onRework !== undefined) {
|
|
2606
|
+
const ancestors = strictAncestors(step.id);
|
|
2607
|
+
if (!ancestors.has(step.onRework.rejectTo)) {
|
|
2608
|
+
manifestInvalid(`step "${step.id}" onRework.rejectTo "${step.onRework.rejectTo}" must be a strict ancestor in spec.steps`, `/spec/steps/${idx}/onRework/rejectTo`);
|
|
2609
|
+
}
|
|
2610
|
+
const targetStep = stepById.get(step.onRework.rejectTo);
|
|
2611
|
+
const targetRole = targetStep.role !== undefined ? roleById.get(targetStep.role) : undefined;
|
|
2612
|
+
if (targetStep.kind !== 'agent' || targetRole?.purpose !== 'task') {
|
|
2613
|
+
manifestInvalid(`step "${step.id}" onRework.rejectTo "${step.onRework.rejectTo}" must target an agent step with role purpose "task"`, `/spec/steps/${idx}/onRework/rejectTo`);
|
|
2614
|
+
}
|
|
2615
|
+
}
|
|
2616
|
+
if (step.kind === 'agent') {
|
|
2617
|
+
const inheritedRoleHandoffs = step.handoffs === undefined && step.role !== undefined
|
|
2618
|
+
? roleById.get(step.role)?.handoffs
|
|
2619
|
+
: undefined;
|
|
2620
|
+
const effectiveHandoffs = step.handoffs ?? inheritedRoleHandoffs;
|
|
2621
|
+
if (effectiveHandoffs !== undefined) {
|
|
2622
|
+
const ancestors = strictAncestors(step.id);
|
|
2623
|
+
for (const [hIdx, handoff] of effectiveHandoffs.entries()) {
|
|
2624
|
+
const diagPath = step.handoffs !== undefined
|
|
2625
|
+
? `/spec/steps/${idx}/handoffs/${hIdx}/fromStep`
|
|
2626
|
+
: `/spec/steps/${idx}/role`;
|
|
2627
|
+
const sourceStep = stepById.get(handoff.fromStep);
|
|
2628
|
+
if (sourceStep === undefined) {
|
|
2629
|
+
manifestInvalid(`step "${step.id}" handoff fromStep references unknown step "${handoff.fromStep}"`, diagPath);
|
|
2630
|
+
}
|
|
2631
|
+
if (handoff.fromStep === step.id || !ancestors.has(handoff.fromStep)) {
|
|
2632
|
+
manifestInvalid(`step "${step.id}" handoff fromStep "${handoff.fromStep}" must be a strict ancestor in spec.steps`, diagPath);
|
|
2633
|
+
}
|
|
2634
|
+
if (sourceStep.kind === 'compact') {
|
|
2635
|
+
manifestInvalid(`step "${step.id}" handoff fromStep "${handoff.fromStep}" must not reference a compact step`, diagPath);
|
|
2636
|
+
}
|
|
2637
|
+
if (sourceStep.kind === 'check' && handoff.source.kind === 'artifact') {
|
|
2638
|
+
manifestInvalid(`step "${step.id}" handoff fromStep "${handoff.fromStep}" is a check step and cannot supply an artifact handoff`, step.handoffs !== undefined ? `/spec/steps/${idx}/handoffs/${hIdx}/source/kind` : diagPath);
|
|
2639
|
+
}
|
|
2640
|
+
}
|
|
2641
|
+
}
|
|
2642
|
+
}
|
|
2643
|
+
if (step.kind === 'compact') {
|
|
2644
|
+
const ancestors = strictAncestors(step.id);
|
|
2645
|
+
const sameRoleAgents = steps.filter(candidate => ancestors.has(candidate.id) && candidate.kind === 'agent' && candidate.role === step.role);
|
|
2646
|
+
const maximal = sameRoleAgents.filter(candidate => !sameRoleAgents.some(other => other.id !== candidate.id && strictAncestors(other.id).has(candidate.id)));
|
|
2647
|
+
if (maximal.length !== 1) {
|
|
2648
|
+
manifestInvalid(`compact step "${step.id}" must have exactly one maximal ancestor agent step for role "${step.role}" (found ${maximal.length})`, `/spec/steps/${idx}`);
|
|
2649
|
+
}
|
|
2650
|
+
}
|
|
2651
|
+
}
|
|
2652
|
+
return Object.freeze(steps);
|
|
2653
|
+
}
|
|
2654
|
+
function validateTaskpackManifestInternal(value, options, schemaMode) {
|
|
2655
|
+
const policyProfile = resolvePolicyProfile(options.policyProfile, options.hostPolicy?.policyProfile);
|
|
2656
|
+
const controlRoot = options.controlRoot !== undefined ? normalizeRelativePath(options.controlRoot, '/') : '.loopwright';
|
|
2657
|
+
const manifestPath = options.manifestPath !== undefined ? normalizeRelativePath(options.manifestPath, '/') : undefined;
|
|
2658
|
+
const rawRoot = requireObject(value, '/', ['apiVersion', 'kind', 'metadata', 'spec']);
|
|
2659
|
+
if (rawRoot['apiVersion'] !== TASKPACK_MANIFEST_API_VERSION)
|
|
2660
|
+
manifestInvalid('unsupported apiVersion', '/apiVersion');
|
|
2661
|
+
if (rawRoot['kind'] !== 'Taskpack')
|
|
2662
|
+
manifestInvalid('kind must be Taskpack', '/kind');
|
|
2663
|
+
const rawSpecBeforeInterp = requireObject(rawRoot['spec'], '/spec', [
|
|
2664
|
+
'goal', 'scope', 'instructions', 'skills', 'execution', 'preflight', 'vars', 'target',
|
|
2665
|
+
'upstreams', 'upstreamGroups', 'proposal', 'submission', 'verification',
|
|
2666
|
+
'publication', 'memory', 'triggers', 'baselineAlignment', 'sandbox', 'decisions', 'models', 'mcp', 'limits', 'roles', 'steps', 'output',
|
|
2667
|
+
]);
|
|
2668
|
+
const vars = rawSpecBeforeInterp['vars'] === undefined
|
|
2669
|
+
? undefined
|
|
2670
|
+
: validateSpecVarsRecord(rawSpecBeforeInterp['vars'], '/spec/vars');
|
|
2671
|
+
const activeVars = vars ?? Object.freeze(Object.create(null));
|
|
2672
|
+
const interpolatedRoot = walkAstForInterpolation(rawRoot, activeVars, '', true, vars !== undefined);
|
|
2673
|
+
const metadata = requireObject(interpolatedRoot['metadata'], '/metadata', ['name']);
|
|
2674
|
+
const name = requireIdentifier(metadata['name'], '/metadata/name');
|
|
2675
|
+
const spec = interpolatedRoot['spec'];
|
|
2676
|
+
const hasExplicitExecution = spec['execution'] !== undefined;
|
|
2677
|
+
const resolvedExecution = hasExplicitExecution
|
|
2678
|
+
? validateExecutionSection(spec['execution'], controlRoot)
|
|
2679
|
+
: Object.freeze({
|
|
2680
|
+
mode: 'strict',
|
|
2681
|
+
capabilities: resolveExecutionCapabilities('strict'),
|
|
2682
|
+
digests: Object.freeze({ pinDigests: false }),
|
|
2683
|
+
});
|
|
2684
|
+
if (options.enforceHostAuthority !== false) {
|
|
2685
|
+
validateExecutionAuthority(resolvedExecution, options.hostPolicy);
|
|
2686
|
+
}
|
|
2687
|
+
const allowWorkflowWrites = (policyProfile === 'github'
|
|
2688
|
+
&& resolvedExecution.capabilities.allowWorkflowWrites
|
|
2689
|
+
&& (options.enforceHostAuthority === false || options.hostPolicy?.allowWorkflowWrites === true));
|
|
2690
|
+
const digestsLockfile = resolvedExecution.digests.lockfile;
|
|
2691
|
+
const limits = spec['limits'] === undefined
|
|
2692
|
+
? undefined
|
|
2693
|
+
: validateTaskpackLimitsDeclaration(spec['limits'], '/spec/limits');
|
|
2694
|
+
const goal = requireObject(spec['goal'], '/spec/goal', ['candidate', 'noChange']);
|
|
2695
|
+
const goalCandidate = requireString(goal['candidate'], '/spec/goal/candidate', 1, 1024);
|
|
2696
|
+
const goalNoChange = requireString(goal['noChange'], '/spec/goal/noChange', 1, 1024);
|
|
2697
|
+
const instructions = spec['instructions'] === undefined
|
|
2698
|
+
? undefined
|
|
2699
|
+
: validateResourceEntryOrList(spec['instructions'], '/spec/instructions');
|
|
2700
|
+
const skills = spec['skills'] === undefined
|
|
2701
|
+
? undefined
|
|
2702
|
+
: validateResourceEntryOrList(spec['skills'], '/spec/skills');
|
|
2703
|
+
let writable = [];
|
|
2704
|
+
let manifestProtected = [];
|
|
2705
|
+
if (spec['scope'] !== undefined) {
|
|
2706
|
+
const scope = requireObject(spec['scope'], '/spec/scope', ['writable', 'protected']);
|
|
2707
|
+
if (scope['writable'] !== undefined) {
|
|
2708
|
+
writable = requireStringList(scope['writable'], '/spec/scope/writable', 1, 128)
|
|
2709
|
+
.map((entry, index) => normalizeScopePattern(entry, `/spec/scope/writable/${index}`));
|
|
2710
|
+
}
|
|
2711
|
+
if (scope['protected'] !== undefined) {
|
|
2712
|
+
manifestProtected = requireStringList(scope['protected'], '/spec/scope/protected', 0, 128)
|
|
2713
|
+
.map((entry, index) => normalizeScopePattern(entry, `/spec/scope/protected/${index}`));
|
|
2714
|
+
}
|
|
2715
|
+
}
|
|
2716
|
+
const rawProposalObj = spec['proposal'];
|
|
2717
|
+
const candidateProposalPath = (rawProposalObj !== null
|
|
2718
|
+
&& typeof rawProposalObj === 'object'
|
|
2719
|
+
&& !Array.isArray(rawProposalObj)
|
|
2720
|
+
&& Object.hasOwn(rawProposalObj, 'path'))
|
|
2721
|
+
? tryNormalizeRelativePath(rawProposalObj['path'])
|
|
2722
|
+
: undefined;
|
|
2723
|
+
const scriptPlacementProtected = effectiveProtectedPaths(manifestProtected, {
|
|
2724
|
+
policyProfile,
|
|
2725
|
+
controlRoot,
|
|
2726
|
+
manifestPath,
|
|
2727
|
+
instructions,
|
|
2728
|
+
skills,
|
|
2729
|
+
allowWorkflowWrites,
|
|
2730
|
+
githubSiblings: options.githubSiblings,
|
|
2731
|
+
});
|
|
2732
|
+
if (digestsLockfile !== undefined) {
|
|
2733
|
+
if (!scriptPlacementProtected.some(protectedPath => scopePatternsMayIntersect(digestsLockfile, asProtectedSubtreePattern(protectedPath), false))) {
|
|
2734
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `digest lockfile "${digestsLockfile}" must reside inside a protected path`, '/spec/execution/digests/lockfile');
|
|
2735
|
+
}
|
|
2736
|
+
}
|
|
2737
|
+
let preflight;
|
|
2738
|
+
if (spec['preflight'] !== undefined) {
|
|
2739
|
+
const rawPre = requireObject(spec['preflight'], '/spec/preflight', ['script', 'timeoutSeconds', 'env']);
|
|
2740
|
+
const script = normalizeRelativePath(rawPre['script'], '/spec/preflight/script');
|
|
2741
|
+
if (!scriptPlacementProtected.some(protectedPath => scopePatternsMayIntersect(script, asProtectedSubtreePattern(protectedPath), false))) {
|
|
2742
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `preflight script "${script}" must reside inside a protected path`, '/spec/preflight/script');
|
|
2743
|
+
}
|
|
2744
|
+
const timeoutSeconds = rawPre['timeoutSeconds'] === undefined
|
|
2745
|
+
? undefined
|
|
2746
|
+
: requireSafeIntInRange(rawPre['timeoutSeconds'], '/spec/preflight/timeoutSeconds', 1, 3_600);
|
|
2747
|
+
let env;
|
|
2748
|
+
if (rawPre['env'] !== undefined) {
|
|
2749
|
+
const rawEnv = requireStringList(rawPre['env'], '/spec/preflight/env', 0, 32);
|
|
2750
|
+
for (const [eIdx, envName] of rawEnv.entries()) {
|
|
2751
|
+
if (!COMMAND_ENV_NAME_PATTERN.test(envName)) {
|
|
2752
|
+
manifestInvalid(`preflight env "${envName}" must match ^[A-Z][A-Z0-9_]{0,63}$`, `/spec/preflight/env/${eIdx}`);
|
|
2753
|
+
}
|
|
2754
|
+
if (isReservedCommandEnvName(envName)) {
|
|
2755
|
+
manifestInvalid(`preflight env "${envName}" is reserved`, `/spec/preflight/env/${eIdx}`);
|
|
2756
|
+
}
|
|
2757
|
+
}
|
|
2758
|
+
env = Object.freeze([...rawEnv]);
|
|
2759
|
+
}
|
|
2760
|
+
preflight = Object.freeze({
|
|
2761
|
+
script,
|
|
2762
|
+
...(timeoutSeconds === undefined ? {} : { timeoutSeconds }),
|
|
2763
|
+
...(env === undefined ? {} : { env }),
|
|
2764
|
+
});
|
|
2765
|
+
}
|
|
2766
|
+
let target;
|
|
2767
|
+
if (spec['target'] !== undefined) {
|
|
2768
|
+
const rawTarget = requireObject(spec['target'], '/spec/target', ['matrix']);
|
|
2769
|
+
if (rawTarget['matrix'] === undefined) {
|
|
2770
|
+
target = Object.freeze({});
|
|
2771
|
+
}
|
|
2772
|
+
else if (rawTarget['matrix'] === null) {
|
|
2773
|
+
target = Object.freeze({ matrix: null });
|
|
2774
|
+
}
|
|
2775
|
+
else {
|
|
2776
|
+
const rawMatrix = rawTarget['matrix'];
|
|
2777
|
+
if (!Array.isArray(rawMatrix) || rawMatrix.length < 1 || rawMatrix.length > LIMITS.targets) {
|
|
2778
|
+
manifestInvalid(`spec.target.matrix must contain 1..${LIMITS.targets} cells`, '/spec/target/matrix');
|
|
2779
|
+
}
|
|
2780
|
+
const seenCellIds = new Set();
|
|
2781
|
+
const cells = rawMatrix.map((item, idx) => {
|
|
2782
|
+
const cPath = `/spec/target/matrix/${idx}`;
|
|
2783
|
+
const rawCell = requireNullProtoObject(item, cPath, ['id', 'platform', 'variant', 'hardware']);
|
|
2784
|
+
const id = requireIdentifier(rawCell['id'], `${cPath}/id`);
|
|
2785
|
+
if (seenCellIds.has(id))
|
|
2786
|
+
manifestInvalid(`duplicate target matrix cell id "${id}"`, `${cPath}/id`);
|
|
2787
|
+
seenCellIds.add(id);
|
|
2788
|
+
const platform = requireLabel(rawCell['platform'], `${cPath}/platform`);
|
|
2789
|
+
const variant = requireLabel(rawCell['variant'], `${cPath}/variant`);
|
|
2790
|
+
const hardware = rawCell['hardware'] === undefined
|
|
2791
|
+
? undefined
|
|
2792
|
+
: validateHardwareTargetSpec(rawCell['hardware'], `${cPath}/hardware`);
|
|
2793
|
+
return Object.freeze({
|
|
2794
|
+
id,
|
|
2795
|
+
platform,
|
|
2796
|
+
variant,
|
|
2797
|
+
...(hardware === undefined ? {} : { hardware }),
|
|
2798
|
+
});
|
|
2799
|
+
});
|
|
2800
|
+
target = Object.freeze({ matrix: Object.freeze(cells) });
|
|
2801
|
+
}
|
|
2802
|
+
}
|
|
2803
|
+
const manifestProtectedSet = new Set(manifestProtected);
|
|
2804
|
+
const earlyProtected = resolveProtectedPathSets(manifestProtected, {
|
|
2805
|
+
policyProfile,
|
|
2806
|
+
controlRoot,
|
|
2807
|
+
manifestPath,
|
|
2808
|
+
digestsLockfile,
|
|
2809
|
+
instructions,
|
|
2810
|
+
skills,
|
|
2811
|
+
preflightScript: preflight?.script,
|
|
2812
|
+
proposalPath: candidateProposalPath,
|
|
2813
|
+
allowWorkflowWrites,
|
|
2814
|
+
githubSiblings: options.githubSiblings,
|
|
2815
|
+
});
|
|
2816
|
+
const protectedPaths = earlyProtected.allProtected;
|
|
2817
|
+
assertWritablesDisjointFromProtected(writable, protectedPaths, earlyProtected.mandatoryProtectedSet, controlRoot, candidateProposalPath, policyProfile, allowWorkflowWrites);
|
|
2818
|
+
const rawUpstreams = spec['upstreams'];
|
|
2819
|
+
const minUpstreams = (schemaMode === 'v2' || preflight !== undefined) ? 0 : 1;
|
|
2820
|
+
const upstreamsValue = (schemaMode === 'v2' && rawUpstreams === undefined) ? [] : rawUpstreams;
|
|
2821
|
+
if (!Array.isArray(upstreamsValue) || upstreamsValue.length < minUpstreams || upstreamsValue.length > 32) {
|
|
2822
|
+
manifestInvalid(`spec.upstreams must contain ${minUpstreams}..32 entries`, '/spec/upstreams');
|
|
2823
|
+
}
|
|
2824
|
+
const upstreamIds = new Set();
|
|
2825
|
+
const upstreams = upstreamsValue.map((item, index) => {
|
|
2826
|
+
const uPath = `/spec/upstreams/${index}`;
|
|
2827
|
+
const upstream = requireObject(item, uPath, [
|
|
2828
|
+
'id', 'kind', 'source', 'watchedPaths', 'allowPrerelease', 'versionPath', 'monotonicSemver',
|
|
2829
|
+
]);
|
|
2830
|
+
const upstreamId = requireIdentifier(upstream['id'], `${uPath}/id`);
|
|
2831
|
+
if (upstreamIds.has(upstreamId))
|
|
2832
|
+
manifestInvalid('duplicate upstream id', `${uPath}/id`);
|
|
2833
|
+
upstreamIds.add(upstreamId);
|
|
2834
|
+
const kindText = requireString(upstream['kind'], `${uPath}/kind`, 1, 32);
|
|
2835
|
+
if (!['github-release', 'git-tag', 'git-commit', 'http-json', 'custom-table'].includes(kindText)) {
|
|
2836
|
+
manifestInvalid('unsupported upstream kind', `${uPath}/kind`);
|
|
2837
|
+
}
|
|
2838
|
+
const source = requireString(upstream['source'], `${uPath}/source`, 1, 512);
|
|
2839
|
+
const watchedPaths = requireStringList(upstream['watchedPaths'], `${uPath}/watchedPaths`, 0, 64)
|
|
2840
|
+
.map((entry, entryIndex) => normalizeRelativePath(entry, `${uPath}/watchedPaths/${entryIndex}`));
|
|
2841
|
+
const allowPrerelease = upstream['allowPrerelease'] === undefined
|
|
2842
|
+
? undefined
|
|
2843
|
+
: requireBoolean(upstream['allowPrerelease'], `${uPath}/allowPrerelease`);
|
|
2844
|
+
let versionPath;
|
|
2845
|
+
if (upstream['versionPath'] !== undefined) {
|
|
2846
|
+
if (kindText !== 'http-json') {
|
|
2847
|
+
manifestInvalid('versionPath is only supported on http-json upstreams', `${uPath}/versionPath`);
|
|
2848
|
+
}
|
|
2849
|
+
versionPath = validateVersionPath(upstream['versionPath'], `${uPath}/versionPath`);
|
|
2850
|
+
}
|
|
2851
|
+
let monotonicSemver;
|
|
2852
|
+
if (upstream['monotonicSemver'] !== undefined) {
|
|
2853
|
+
if (kindText !== 'http-json') {
|
|
2854
|
+
manifestInvalid('monotonicSemver is only supported on http-json upstreams', `${uPath}/monotonicSemver`);
|
|
2855
|
+
}
|
|
2856
|
+
monotonicSemver = requireBoolean(upstream['monotonicSemver'], `${uPath}/monotonicSemver`);
|
|
2857
|
+
}
|
|
2858
|
+
const descriptor = Object.freeze({
|
|
2859
|
+
id: upstreamId,
|
|
2860
|
+
kind: kindText,
|
|
2861
|
+
source,
|
|
2862
|
+
watchedPaths,
|
|
2863
|
+
...(allowPrerelease === undefined ? {} : { allowPrerelease }),
|
|
2864
|
+
...(versionPath === undefined ? {} : { versionPath }),
|
|
2865
|
+
...(monotonicSemver === undefined ? {} : { monotonicSemver }),
|
|
2866
|
+
});
|
|
2867
|
+
return descriptor;
|
|
2868
|
+
});
|
|
2869
|
+
let upstreamGroups;
|
|
2870
|
+
if (spec['upstreamGroups'] !== undefined) {
|
|
2871
|
+
const rawGroups = spec['upstreamGroups'];
|
|
2872
|
+
if (!Array.isArray(rawGroups) || rawGroups.length > 32) {
|
|
2873
|
+
manifestInvalid('spec.upstreamGroups must contain 0..32 entries', '/spec/upstreamGroups');
|
|
2874
|
+
}
|
|
2875
|
+
const seenGroupIds = new Set();
|
|
2876
|
+
const lockstepMemberOwner = new Map();
|
|
2877
|
+
const parsedGroups = rawGroups.map((item, idx) => {
|
|
2878
|
+
const gPath = `/spec/upstreamGroups/${idx}`;
|
|
2879
|
+
const rawGroup = requireObject(item, gPath, ['id', 'members', 'policy']);
|
|
2880
|
+
const groupId = requireIdentifier(rawGroup['id'], `${gPath}/id`);
|
|
2881
|
+
if (seenGroupIds.has(groupId))
|
|
2882
|
+
manifestInvalid(`duplicate upstreamGroup id "${groupId}"`, `${gPath}/id`);
|
|
2883
|
+
seenGroupIds.add(groupId);
|
|
2884
|
+
const policyStr = requireString(rawGroup['policy'], `${gPath}/policy`, 1, 16);
|
|
2885
|
+
if (policyStr !== 'lockstep' && policyStr !== 'independent') {
|
|
2886
|
+
manifestInvalid('upstreamGroup policy must be "lockstep" or "independent"', `${gPath}/policy`);
|
|
2887
|
+
}
|
|
2888
|
+
const policy = policyStr;
|
|
2889
|
+
const members = requireStringList(rawGroup['members'], `${gPath}/members`, 1, 32);
|
|
2890
|
+
for (const [mIdx, memberId] of members.entries()) {
|
|
2891
|
+
requireIdentifier(memberId, `${gPath}/members/${mIdx}`);
|
|
2892
|
+
if (!upstreamIds.has(memberId)) {
|
|
2893
|
+
manifestInvalid(`upstreamGroup "${groupId}" references unknown upstream "${memberId}"`, `${gPath}/members/${mIdx}`);
|
|
2894
|
+
}
|
|
2895
|
+
if (policy === 'lockstep') {
|
|
2896
|
+
const existingOwner = lockstepMemberOwner.get(memberId);
|
|
2897
|
+
if (existingOwner !== undefined) {
|
|
2898
|
+
manifestInvalid(`upstream "${memberId}" cannot belong to multiple lockstep groups ("${existingOwner}" and "${groupId}")`, `${gPath}/members/${mIdx}`);
|
|
2899
|
+
}
|
|
2900
|
+
lockstepMemberOwner.set(memberId, groupId);
|
|
2901
|
+
}
|
|
2902
|
+
}
|
|
2903
|
+
return Object.freeze({ id: groupId, members: Object.freeze([...members]), policy });
|
|
2904
|
+
});
|
|
2905
|
+
upstreamGroups = Object.freeze(parsedGroups);
|
|
2906
|
+
}
|
|
2907
|
+
const legacyPrefixFallback = schemaMode === 'v1-compat';
|
|
2908
|
+
let proposalDecl;
|
|
2909
|
+
let proposalPath;
|
|
2910
|
+
if (spec['proposal'] !== undefined || schemaMode === 'v1-compat') {
|
|
2911
|
+
const proposal = requireObject(spec['proposal'], '/spec/proposal', ['path', 'requiredFields', 'schemaVersion']);
|
|
2912
|
+
proposalPath = normalizeRelativePath(proposal['path'], '/spec/proposal/path');
|
|
2913
|
+
pathInsideWritable(proposalPath, writable, protectedPaths, '/spec/proposal/path', legacyPrefixFallback, policyProfile, allowWorkflowWrites, manifestProtectedSet);
|
|
2914
|
+
if ((pathCoveredBy(proposalPath, controlRoot) || pathCoveredByCaseInsensitive(proposalPath, controlRoot))
|
|
2915
|
+
&& !isControlRootProposalWritableAllowed(proposalPath, writable, controlRoot, earlyProtected.explicitWithManifest)) {
|
|
2916
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `spec.proposal.path "${proposalPath}" inside control root "${controlRoot}" must be listed as an exact file in spec.scope.writable without overlapping protected control-plane paths`, '/spec/proposal/path');
|
|
2917
|
+
}
|
|
2918
|
+
if (!/\.(?:yaml|yml|json)$/i.test(proposalPath)) {
|
|
2919
|
+
manifestInvalid('spec.proposal.path must end in .yaml, .yml, or .json', '/spec/proposal/path');
|
|
2920
|
+
}
|
|
2921
|
+
const requiredFields = requireStringList(proposal['requiredFields'], '/spec/proposal/requiredFields', 1, 32);
|
|
2922
|
+
for (const [index, field] of requiredFields.entries()) {
|
|
2923
|
+
if (!FIELD_NAME_PATTERN.test(field))
|
|
2924
|
+
manifestInvalid(`required field "${field}" is not a valid field name`, `/spec/proposal/requiredFields/${index}`);
|
|
2925
|
+
}
|
|
2926
|
+
const schemaVersion = proposal['schemaVersion'];
|
|
2927
|
+
if (typeof schemaVersion !== 'number' || !Number.isSafeInteger(schemaVersion) || schemaVersion < 1) {
|
|
2928
|
+
manifestInvalid('schemaVersion must be a positive integer', '/spec/proposal/schemaVersion');
|
|
2929
|
+
}
|
|
2930
|
+
proposalDecl = Object.freeze({ path: proposalPath, requiredFields: Object.freeze(requiredFields), schemaVersion });
|
|
2931
|
+
}
|
|
2932
|
+
let submissionDecl;
|
|
2933
|
+
if (spec['submission'] !== undefined) {
|
|
2934
|
+
const rawSub = requireObject(spec['submission'], '/spec/submission', ['path', 'required']);
|
|
2935
|
+
const subPath = normalizeRelativePath(rawSub['path'], '/spec/submission/path');
|
|
2936
|
+
if (!/\.json$/i.test(subPath)) {
|
|
2937
|
+
manifestInvalid('spec.submission.path must end in .json', '/spec/submission/path');
|
|
2938
|
+
}
|
|
2939
|
+
pathInsideWritable(subPath, writable, protectedPaths, '/spec/submission/path', legacyPrefixFallback, policyProfile, allowWorkflowWrites, manifestProtectedSet);
|
|
2940
|
+
const required = rawSub['required'] === undefined
|
|
2941
|
+
? false
|
|
2942
|
+
: requireBoolean(rawSub['required'], '/spec/submission/required');
|
|
2943
|
+
submissionDecl = Object.freeze({ path: subPath, required });
|
|
2944
|
+
}
|
|
2945
|
+
const verification = requireObject(spec['verification'], '/spec/verification', ['localChecks', 'externalGates']);
|
|
2946
|
+
const localChecksValue = verification['localChecks'];
|
|
2947
|
+
if (!Array.isArray(localChecksValue) || localChecksValue.length > 32)
|
|
2948
|
+
manifestInvalid('spec.verification.localChecks must contain 0..32 entries', '/spec/verification/localChecks');
|
|
2949
|
+
const externalGatesValue = verification['externalGates'];
|
|
2950
|
+
if (!Array.isArray(externalGatesValue) || externalGatesValue.length > 32)
|
|
2951
|
+
manifestInvalid('spec.verification.externalGates must contain 0..32 entries', '/spec/verification/externalGates');
|
|
2952
|
+
const checkIds = new Set();
|
|
2953
|
+
const reservedIds = new Set(['scope', 'no-change', 'taskpack-author', 'taskpack-no-change']);
|
|
2954
|
+
const allowedLocalCheckImpls = schemaMode === 'v2'
|
|
2955
|
+
? ['json-artifact.v1', 'scope.v1', 'no-change.v1', 'command.v1', 'json-keys-guard.v1', 'line-section-guard.v1']
|
|
2956
|
+
: ['json-artifact.v1', 'scope.v1', 'no-change.v1', 'command.v1'];
|
|
2957
|
+
const relativeToolchainPaths = [];
|
|
2958
|
+
const localChecks = localChecksValue.map((item, index) => {
|
|
2959
|
+
const check = requireObject(item, `/spec/verification/localChecks/${index}`, ['id', 'implementation', 'parameters']);
|
|
2960
|
+
const checkId = requireIdentifier(check['id'], `/spec/verification/localChecks/${index}/id`);
|
|
2961
|
+
if (checkIds.has(checkId))
|
|
2962
|
+
manifestInvalid('duplicate check id across localChecks and externalGates', `/spec/verification/localChecks/${index}/id`);
|
|
2963
|
+
if (reservedIds.has(checkId))
|
|
2964
|
+
manifestInvalid(`check id "${checkId}" is reserved by the compiler`, `/spec/verification/localChecks/${index}/id`);
|
|
2965
|
+
checkIds.add(checkId);
|
|
2966
|
+
const implementation = requireString(check['implementation'], `/spec/verification/localChecks/${index}/implementation`, 1, 32);
|
|
2967
|
+
if (!allowedLocalCheckImpls.includes(implementation)) {
|
|
2968
|
+
manifestInvalid('unsupported local check implementation', `/spec/verification/localChecks/${index}/implementation`);
|
|
2969
|
+
}
|
|
2970
|
+
if (implementation === 'command.v1') {
|
|
2971
|
+
const paramPath = `/spec/verification/localChecks/${index}/parameters`;
|
|
2972
|
+
const params = requireObject(check['parameters'], paramPath, [
|
|
2973
|
+
'script', 'args', 'timeoutSeconds', 'allowReadOnlyGitHubToken', 'env',
|
|
2974
|
+
'toolchainPaths', 'preserveRepoDirName', 'mountReadOnlyGit', 'networkMode', 'mounts',
|
|
2975
|
+
]);
|
|
2976
|
+
const script = normalizeRelativePath(params['script'], `${paramPath}/script`);
|
|
2977
|
+
if (!scriptPlacementProtected.some(protectedPath => scopePatternsMayIntersect(script, asProtectedSubtreePattern(protectedPath), false))) {
|
|
2978
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `command.v1 script "${script}" must reside inside a protected path`, `${paramPath}/script`);
|
|
2979
|
+
}
|
|
2980
|
+
let args;
|
|
2981
|
+
if (params['args'] !== undefined) {
|
|
2982
|
+
if (!Array.isArray(params['args']) || params['args'].length > 64) {
|
|
2983
|
+
manifestInvalid('command.v1 args must be an array of 0..64 strings', `${paramPath}/args`);
|
|
2984
|
+
}
|
|
2985
|
+
args = Object.freeze(params['args'].map((arg, aIdx) => requireString(arg, `${paramPath}/args/${aIdx}`, 0, 1024)));
|
|
2986
|
+
}
|
|
2987
|
+
let explicitTimeoutSeconds;
|
|
2988
|
+
if (params['timeoutSeconds'] !== undefined) {
|
|
2989
|
+
explicitTimeoutSeconds = requireSafeIntInRange(params['timeoutSeconds'], `${paramPath}/timeoutSeconds`, 1, 3_600);
|
|
2990
|
+
}
|
|
2991
|
+
const allowReadOnlyGitHubToken = params['allowReadOnlyGitHubToken'] === undefined
|
|
2992
|
+
? false
|
|
2993
|
+
: requireBoolean(params['allowReadOnlyGitHubToken'], `${paramPath}/allowReadOnlyGitHubToken`);
|
|
2994
|
+
let env = Object.freeze([]);
|
|
2995
|
+
if (params['env'] !== undefined) {
|
|
2996
|
+
if (Array.isArray(params['env'])) {
|
|
2997
|
+
const rawEnv = requireStringList(params['env'], `${paramPath}/env`, 0, 16);
|
|
2998
|
+
for (const [envIdx, envName] of rawEnv.entries()) {
|
|
2999
|
+
if (!COMMAND_ENV_NAME_PATTERN.test(envName)) {
|
|
3000
|
+
manifestInvalid(`command.v1 env "${envName}" must match ^[A-Z][A-Z0-9_]{0,63}$`, `${paramPath}/env/${envIdx}`);
|
|
3001
|
+
}
|
|
3002
|
+
if (isReservedCommandEnvName(envName)) {
|
|
3003
|
+
manifestInvalid(`command.v1 env "${envName}" is reserved`, `${paramPath}/env/${envIdx}`);
|
|
3004
|
+
}
|
|
3005
|
+
}
|
|
3006
|
+
env = Object.freeze([...rawEnv]);
|
|
3007
|
+
}
|
|
3008
|
+
else if (isPlainObjectRecord(params['env'])) {
|
|
3009
|
+
const entries = Object.entries(params['env']);
|
|
3010
|
+
if (entries.length > 32) {
|
|
3011
|
+
manifestInvalid('command.v1 env map exceeds 32 entries', `${paramPath}/env`);
|
|
3012
|
+
}
|
|
3013
|
+
const envMap = Object.create(null);
|
|
3014
|
+
for (const [k, v] of entries) {
|
|
3015
|
+
if (FORBIDDEN_KEYS.has(k) || !COMMAND_ENV_NAME_PATTERN.test(k)) {
|
|
3016
|
+
manifestInvalid(`command.v1 env "${k}" must match ^[A-Z][A-Z0-9_]{0,63}$`, `${paramPath}/env/${k}`);
|
|
3017
|
+
}
|
|
3018
|
+
if (isReservedCommandEnvName(k) || FORBIDDEN_LITERAL_COMMAND_ENV_NAMES.has(k)) {
|
|
3019
|
+
manifestInvalid(`command.v1 env "${k}" is reserved`, `${paramPath}/env/${k}`);
|
|
3020
|
+
}
|
|
3021
|
+
envMap[k] = requireString(v, `${paramPath}/env/${k}`, 0, 1024);
|
|
3022
|
+
}
|
|
3023
|
+
env = Object.freeze(envMap);
|
|
3024
|
+
}
|
|
3025
|
+
else {
|
|
3026
|
+
manifestInvalid('command.v1 env must be an array of env names or an object of string values', `${paramPath}/env`);
|
|
3027
|
+
}
|
|
3028
|
+
}
|
|
3029
|
+
let toolchainPaths;
|
|
3030
|
+
if (params['toolchainPaths'] !== undefined) {
|
|
3031
|
+
const rawToolchain = requireStringList(params['toolchainPaths'], `${paramPath}/toolchainPaths`, 0, 32);
|
|
3032
|
+
toolchainPaths = Object.freeze(rawToolchain.map((entry, tIdx) => {
|
|
3033
|
+
const tPath = `${paramPath}/toolchainPaths/${tIdx}`;
|
|
3034
|
+
const validated = validateToolchainPath(entry, tPath);
|
|
3035
|
+
if (!validated.startsWith('/')) {
|
|
3036
|
+
if (!scriptPlacementProtected.some(protectedPath => scopePatternsMayIntersect(validated, asProtectedSubtreePattern(protectedPath), false))) {
|
|
3037
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `command.v1 toolchainPaths entry "${validated}" must reside inside a protected path`, tPath);
|
|
3038
|
+
}
|
|
3039
|
+
const overlapWritable = writable.find(w => (scopePatternsMayIntersect(w, asProtectedSubtreePattern(validated), false)
|
|
3040
|
+
|| scopePatternsMayIntersect(w, asProtectedSubtreePattern(validated), true)));
|
|
3041
|
+
if (overlapWritable !== undefined) {
|
|
3042
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `command.v1 toolchainPaths entry "${validated}" must not overlap spec.scope.writable "${overlapWritable}"`, tPath);
|
|
3043
|
+
}
|
|
3044
|
+
relativeToolchainPaths.push(validated);
|
|
3045
|
+
}
|
|
3046
|
+
return validated;
|
|
3047
|
+
}));
|
|
3048
|
+
}
|
|
3049
|
+
const preserveRepoDirName = params['preserveRepoDirName'] === undefined
|
|
3050
|
+
? undefined
|
|
3051
|
+
: requireBoolean(params['preserveRepoDirName'], `${paramPath}/preserveRepoDirName`);
|
|
3052
|
+
const mountReadOnlyGit = params['mountReadOnlyGit'] === undefined
|
|
3053
|
+
? undefined
|
|
3054
|
+
: requireBoolean(params['mountReadOnlyGit'], `${paramPath}/mountReadOnlyGit`);
|
|
3055
|
+
if (mountReadOnlyGit === true && options.enforceHostAuthority !== false && options.hostPolicy?.allowPrivileged !== true) {
|
|
3056
|
+
throw new TaskpackError('TASKPACK_HOST_BINDING_INVALID', 'command.v1 parameters.mountReadOnlyGit: true requires operator host authorization (allowPrivileged)', `${paramPath}/mountReadOnlyGit`);
|
|
3057
|
+
}
|
|
3058
|
+
let checkNetworkMode;
|
|
3059
|
+
if (params['networkMode'] !== undefined) {
|
|
3060
|
+
const nm = requireString(params['networkMode'], `${paramPath}/networkMode`, 1, 32);
|
|
3061
|
+
if (nm !== 'none' && nm !== 'loopback-only') {
|
|
3062
|
+
manifestInvalid('command.v1 networkMode must be "none" or "loopback-only"', `${paramPath}/networkMode`);
|
|
3063
|
+
}
|
|
3064
|
+
if (nm === 'loopback-only') {
|
|
3065
|
+
if (!resolvedExecution.capabilities.allowCheckNetwork) {
|
|
3066
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', 'command.v1 parameters.networkMode: "loopback-only" requires spec.execution.capabilities.allowCheckNetwork: true', `${paramPath}/networkMode`);
|
|
3067
|
+
}
|
|
3068
|
+
if (options.enforceHostAuthority !== false && options.hostPolicy?.allowPrivileged !== true) {
|
|
3069
|
+
throw new TaskpackError('TASKPACK_HOST_BINDING_INVALID', 'command.v1 parameters.networkMode: "loopback-only" requires operator host authorization (allowPrivileged)', `${paramPath}/networkMode`);
|
|
3070
|
+
}
|
|
3071
|
+
}
|
|
3072
|
+
checkNetworkMode = nm;
|
|
3073
|
+
}
|
|
3074
|
+
let mounts;
|
|
3075
|
+
if (params['mounts'] !== undefined) {
|
|
3076
|
+
mounts = normalizeCommandMountList(params['mounts'], `${paramPath}/mounts`);
|
|
3077
|
+
if (mounts.length > 0 && options.enforceHostAuthority !== false) {
|
|
3078
|
+
if (options.hostPolicy?.allowPrivileged !== true) {
|
|
3079
|
+
throw new TaskpackError('TASKPACK_HOST_BINDING_INVALID', 'command.v1 parameters.mounts requires operator host authorization (allowPrivileged)', `${paramPath}/mounts`);
|
|
3080
|
+
}
|
|
3081
|
+
for (const [mIdx, mount] of mounts.entries()) {
|
|
3082
|
+
if (!isHostMountAuthorized(mount.source, options.hostPolicy?.allowedHostMounts)) {
|
|
3083
|
+
throw new TaskpackError('TASKPACK_HOST_BINDING_INVALID', `command.v1 mount source "${mount.source}" is not authorized by operator hostPolicy.allowedHostMounts`, `${paramPath}/mounts/${mIdx}/source`);
|
|
3084
|
+
}
|
|
3085
|
+
}
|
|
3086
|
+
}
|
|
3087
|
+
}
|
|
3088
|
+
const compiledParams = {
|
|
3089
|
+
script,
|
|
3090
|
+
...(args !== undefined ? { args } : {}),
|
|
3091
|
+
...(explicitTimeoutSeconds !== undefined ? { timeoutSeconds: explicitTimeoutSeconds } : {}),
|
|
3092
|
+
allowReadOnlyGitHubToken,
|
|
3093
|
+
env,
|
|
3094
|
+
...(toolchainPaths !== undefined ? { toolchainPaths } : {}),
|
|
3095
|
+
...(preserveRepoDirName !== undefined ? { preserveRepoDirName } : {}),
|
|
3096
|
+
...(mountReadOnlyGit !== undefined ? { mountReadOnlyGit } : {}),
|
|
3097
|
+
...(checkNetworkMode !== undefined ? { networkMode: checkNetworkMode } : {}),
|
|
3098
|
+
...(mounts !== undefined && mounts.length > 0 ? { mounts } : {}),
|
|
3099
|
+
};
|
|
3100
|
+
return Object.freeze({
|
|
3101
|
+
id: checkId,
|
|
3102
|
+
implementation: 'command.v1',
|
|
3103
|
+
parameters: Object.freeze(compiledParams),
|
|
3104
|
+
});
|
|
3105
|
+
}
|
|
3106
|
+
if (implementation === 'json-keys-guard.v1') {
|
|
3107
|
+
const paramPath = `/spec/verification/localChecks/${index}/parameters`;
|
|
3108
|
+
const params = requireObject(check['parameters'], paramPath, ['path', 'allowedPointers']);
|
|
3109
|
+
const targetPath = normalizeRelativePath(params['path'], `${paramPath}/path`);
|
|
3110
|
+
const rawPointers = requireStringList(params['allowedPointers'], `${paramPath}/allowedPointers`, 1, 128);
|
|
3111
|
+
const rfc6901PointerPattern = /^(?:\/(?:[^~/]|~[01])*)+$/;
|
|
3112
|
+
for (const [pIdx, pointer] of rawPointers.entries()) {
|
|
3113
|
+
if (pointer.length > 256 || !rfc6901PointerPattern.test(pointer)) {
|
|
3114
|
+
manifestInvalid(`json-keys-guard.v1 allowedPointer "${pointer}" must be a valid non-root RFC 6901 JSON Pointer of at most 256 characters`, `${paramPath}/allowedPointers/${pIdx}`);
|
|
3115
|
+
}
|
|
3116
|
+
}
|
|
3117
|
+
return Object.freeze({
|
|
3118
|
+
id: checkId,
|
|
3119
|
+
implementation: 'json-keys-guard.v1',
|
|
3120
|
+
parameters: Object.freeze({
|
|
3121
|
+
path: targetPath,
|
|
3122
|
+
allowedPointers: Object.freeze([...rawPointers]),
|
|
3123
|
+
}),
|
|
3124
|
+
});
|
|
3125
|
+
}
|
|
3126
|
+
if (implementation === 'line-section-guard.v1') {
|
|
3127
|
+
const paramPath = `/spec/verification/localChecks/${index}/parameters`;
|
|
3128
|
+
const params = requireObject(check['parameters'], paramPath, ['path', 'startMarker', 'endMarker']);
|
|
3129
|
+
const targetPath = normalizeRelativePath(params['path'], `${paramPath}/path`);
|
|
3130
|
+
const startMarker = requireString(params['startMarker'], `${paramPath}/startMarker`, 1, 256);
|
|
3131
|
+
const endMarker = requireString(params['endMarker'], `${paramPath}/endMarker`, 1, 256);
|
|
3132
|
+
if (/[\r\n]/.test(startMarker)) {
|
|
3133
|
+
manifestInvalid('line-section-guard.v1 startMarker must not contain newline characters', `${paramPath}/startMarker`);
|
|
3134
|
+
}
|
|
3135
|
+
if (/[\r\n]/.test(endMarker)) {
|
|
3136
|
+
manifestInvalid('line-section-guard.v1 endMarker must not contain newline characters', `${paramPath}/endMarker`);
|
|
3137
|
+
}
|
|
3138
|
+
if (startMarker === endMarker) {
|
|
3139
|
+
manifestInvalid('line-section-guard.v1 startMarker and endMarker must be distinct', paramPath);
|
|
3140
|
+
}
|
|
3141
|
+
return Object.freeze({
|
|
3142
|
+
id: checkId,
|
|
3143
|
+
implementation: 'line-section-guard.v1',
|
|
3144
|
+
parameters: Object.freeze({
|
|
3145
|
+
path: targetPath,
|
|
3146
|
+
startMarker,
|
|
3147
|
+
endMarker,
|
|
3148
|
+
}),
|
|
3149
|
+
});
|
|
3150
|
+
}
|
|
3151
|
+
const parametersKey = Object.hasOwn(check, 'parameters') ? 'parameters' : '';
|
|
3152
|
+
const record = {
|
|
3153
|
+
id: checkId,
|
|
3154
|
+
implementation: implementation,
|
|
3155
|
+
};
|
|
3156
|
+
if (parametersKey !== '')
|
|
3157
|
+
record.parameters = requireParameters(check['parameters'], `/spec/verification/localChecks/${index}/parameters`);
|
|
3158
|
+
return Object.freeze(record);
|
|
3159
|
+
});
|
|
3160
|
+
const commandScripts = localChecks
|
|
3161
|
+
.filter(c => c.implementation === 'command.v1')
|
|
3162
|
+
.map(c => String(c.parameters?.['script'] ?? ''))
|
|
3163
|
+
.filter(s => s.length > 0);
|
|
3164
|
+
const targetMatrixById = new Map((target?.matrix ?? []).map(cell => [cell.id, cell]));
|
|
3165
|
+
const externalGates = externalGatesValue.map((item, index) => {
|
|
3166
|
+
const gPath = `/spec/verification/externalGates/${index}`;
|
|
3167
|
+
if (item === null || typeof item !== 'object' || Array.isArray(item)) {
|
|
3168
|
+
manifestInvalid('expected an object', gPath);
|
|
3169
|
+
}
|
|
3170
|
+
const proto = Object.getPrototypeOf(item);
|
|
3171
|
+
if (proto !== Object.prototype && proto !== null) {
|
|
3172
|
+
manifestInvalid('expected an object', gPath);
|
|
3173
|
+
}
|
|
3174
|
+
const rawGateRecord = item;
|
|
3175
|
+
let declaredImplementation;
|
|
3176
|
+
if (Object.hasOwn(rawGateRecord, 'implementation') && rawGateRecord['implementation'] !== undefined) {
|
|
3177
|
+
const rawImpl = rawGateRecord['implementation'];
|
|
3178
|
+
if (rawImpl !== 'gate.v1' && rawImpl !== 'benchmark-gate.v1') {
|
|
3179
|
+
manifestInvalid('external gate implementation must be "gate.v1" or "benchmark-gate.v1"', `${gPath}/implementation`);
|
|
3180
|
+
}
|
|
3181
|
+
declaredImplementation = rawImpl;
|
|
3182
|
+
}
|
|
3183
|
+
const effectiveImplementation = declaredImplementation ?? 'gate.v1';
|
|
3184
|
+
if (effectiveImplementation === 'benchmark-gate.v1') {
|
|
3185
|
+
for (const forbidden of ['url', 'signingCredentialRef', 'authCredentialRef']) {
|
|
3186
|
+
if (Object.hasOwn(rawGateRecord, forbidden)) {
|
|
3187
|
+
manifestInvalid(`benchmark-gate.v1 external gate forbids manifest-level "${forbidden}" override; bind endpoints via host gateEndpoints`, `${gPath}/${forbidden}`);
|
|
3188
|
+
}
|
|
3189
|
+
}
|
|
3190
|
+
const gate = requireNullProtoObject(item, gPath, [
|
|
3191
|
+
'id',
|
|
3192
|
+
'implementation',
|
|
3193
|
+
'gateId',
|
|
3194
|
+
'endpointId',
|
|
3195
|
+
'required',
|
|
3196
|
+
'targetCellId',
|
|
3197
|
+
'heldOutWorkloadId',
|
|
3198
|
+
'maxPreemptions',
|
|
3199
|
+
'allowSyntheticHardwareProbe',
|
|
3200
|
+
'metricThresholds',
|
|
3201
|
+
]);
|
|
3202
|
+
const gateCheckId = requireIdentifier(gate['id'], `${gPath}/id`);
|
|
3203
|
+
if (checkIds.has(gateCheckId))
|
|
3204
|
+
manifestInvalid('duplicate check id across localChecks and externalGates', `${gPath}/id`);
|
|
3205
|
+
if (reservedIds.has(gateCheckId))
|
|
3206
|
+
manifestInvalid(`check id "${gateCheckId}" is reserved by the compiler`, `${gPath}/id`);
|
|
3207
|
+
checkIds.add(gateCheckId);
|
|
3208
|
+
const endpointId = requireIdentifier(gate['endpointId'], `${gPath}/endpointId`);
|
|
3209
|
+
if (endpointId === LOCAL_COMMAND_GATE_ENDPOINT_ID) {
|
|
3210
|
+
manifestInvalid(`endpointId "${LOCAL_COMMAND_GATE_ENDPOINT_ID}" is reserved for command.v1 local checks`, `${gPath}/endpointId`);
|
|
3211
|
+
}
|
|
3212
|
+
const gateId = requirePrintableAscii(gate['gateId'], `${gPath}/gateId`, 1, 128);
|
|
3213
|
+
const required = requireBoolean(gate['required'], `${gPath}/required`);
|
|
3214
|
+
const targetCellId = requireIdentifier(gate['targetCellId'], `${gPath}/targetCellId`);
|
|
3215
|
+
const matchedCell = targetMatrixById.get(targetCellId);
|
|
3216
|
+
if (matchedCell === undefined) {
|
|
3217
|
+
manifestInvalid(`benchmark-gate.v1 targetCellId "${targetCellId}" does not match any declared spec.target.matrix cell`, `${gPath}/targetCellId`);
|
|
3218
|
+
}
|
|
3219
|
+
if (matchedCell.hardware === undefined) {
|
|
3220
|
+
manifestInvalid(`benchmark-gate.v1 targetCellId "${targetCellId}" references a spec.target.matrix cell without hardware metadata`, `${gPath}/targetCellId`);
|
|
3221
|
+
}
|
|
3222
|
+
const heldOutWorkloadId = requireIdentifier(gate['heldOutWorkloadId'], `${gPath}/heldOutWorkloadId`);
|
|
3223
|
+
const maxPreemptions = gate['maxPreemptions'] === undefined
|
|
3224
|
+
? undefined
|
|
3225
|
+
: requireSafeIntInRange(gate['maxPreemptions'], `${gPath}/maxPreemptions`, 0, 16);
|
|
3226
|
+
const allowSyntheticHardwareProbe = gate['allowSyntheticHardwareProbe'] === undefined
|
|
3227
|
+
? undefined
|
|
3228
|
+
: requireBoolean(gate['allowSyntheticHardwareProbe'], `${gPath}/allowSyntheticHardwareProbe`);
|
|
3229
|
+
let metricThresholds;
|
|
3230
|
+
if (gate['metricThresholds'] !== undefined) {
|
|
3231
|
+
const rawThresholds = gate['metricThresholds'];
|
|
3232
|
+
if (!Array.isArray(rawThresholds) || rawThresholds.length > LIMITS.metricThresholds) {
|
|
3233
|
+
manifestInvalid(`benchmark-gate.v1 metricThresholds must contain 0..${LIMITS.metricThresholds} entries`, `${gPath}/metricThresholds`);
|
|
3234
|
+
}
|
|
3235
|
+
metricThresholds = Object.freeze(rawThresholds.map((rule, rIdx) => validateMetricThresholdRule(rule, `${gPath}/metricThresholds/${rIdx}`)));
|
|
3236
|
+
}
|
|
3237
|
+
return Object.freeze({
|
|
3238
|
+
id: gateCheckId,
|
|
3239
|
+
implementation: 'benchmark-gate.v1',
|
|
3240
|
+
gateId,
|
|
3241
|
+
endpointId,
|
|
3242
|
+
required,
|
|
3243
|
+
targetCellId,
|
|
3244
|
+
heldOutWorkloadId,
|
|
3245
|
+
...(maxPreemptions === undefined ? {} : { maxPreemptions }),
|
|
3246
|
+
...(allowSyntheticHardwareProbe === undefined ? {} : { allowSyntheticHardwareProbe }),
|
|
3247
|
+
...(metricThresholds === undefined ? {} : { metricThresholds }),
|
|
3248
|
+
});
|
|
3249
|
+
}
|
|
3250
|
+
const gate = requireNullProtoObject(item, gPath, [
|
|
3251
|
+
'id', 'implementation', 'gateId', 'endpointId', 'required', 'signingCredentialRef', 'authCredentialRef', 'url',
|
|
3252
|
+
]);
|
|
3253
|
+
const gateCheckId = requireIdentifier(gate['id'], `${gPath}/id`);
|
|
3254
|
+
if (checkIds.has(gateCheckId))
|
|
3255
|
+
manifestInvalid('duplicate check id across localChecks and externalGates', `${gPath}/id`);
|
|
3256
|
+
if (reservedIds.has(gateCheckId))
|
|
3257
|
+
manifestInvalid(`check id "${gateCheckId}" is reserved by the compiler`, `${gPath}/id`);
|
|
3258
|
+
checkIds.add(gateCheckId);
|
|
3259
|
+
const endpointId = requireIdentifier(gate['endpointId'], `${gPath}/endpointId`);
|
|
3260
|
+
if (endpointId === LOCAL_COMMAND_GATE_ENDPOINT_ID) {
|
|
3261
|
+
manifestInvalid(`endpointId "${LOCAL_COMMAND_GATE_ENDPOINT_ID}" is reserved for command.v1 local checks`, `${gPath}/endpointId`);
|
|
3262
|
+
}
|
|
3263
|
+
let signingCredentialRef;
|
|
3264
|
+
if (gate['signingCredentialRef'] !== undefined) {
|
|
3265
|
+
signingCredentialRef = requireString(gate['signingCredentialRef'], `${gPath}/signingCredentialRef`, 1, 64);
|
|
3266
|
+
if (!isValidCredentialRef(signingCredentialRef)) {
|
|
3267
|
+
manifestInvalid('invalid signingCredentialRef', `${gPath}/signingCredentialRef`);
|
|
3268
|
+
}
|
|
3269
|
+
}
|
|
3270
|
+
let authCredentialRef;
|
|
3271
|
+
if (gate['authCredentialRef'] !== undefined) {
|
|
3272
|
+
authCredentialRef = requireString(gate['authCredentialRef'], `${gPath}/authCredentialRef`, 1, 64);
|
|
3273
|
+
if (!isValidCredentialRef(authCredentialRef)) {
|
|
3274
|
+
manifestInvalid('invalid authCredentialRef', `${gPath}/authCredentialRef`);
|
|
3275
|
+
}
|
|
3276
|
+
}
|
|
3277
|
+
let url;
|
|
3278
|
+
if (gate['url'] !== undefined) {
|
|
3279
|
+
const urlStr = requireString(gate['url'], `${gPath}/url`, 1, 2048);
|
|
3280
|
+
let parsedUrl;
|
|
3281
|
+
try {
|
|
3282
|
+
parsedUrl = new URL(urlStr);
|
|
3283
|
+
}
|
|
3284
|
+
catch {
|
|
3285
|
+
manifestInvalid('external gate url is not a valid URL', `${gPath}/url`);
|
|
3286
|
+
}
|
|
3287
|
+
if (parsedUrl.href !== urlStr
|
|
3288
|
+
|| parsedUrl.username !== ''
|
|
3289
|
+
|| parsedUrl.password !== ''
|
|
3290
|
+
|| parsedUrl.hash !== ''
|
|
3291
|
+
|| parsedUrl.search !== '') {
|
|
3292
|
+
manifestInvalid('external gate url must be a normalized URL without credentials, query strings, or fragments', `${gPath}/url`);
|
|
3293
|
+
}
|
|
3294
|
+
const isLoopback = (parsedUrl.hostname === '127.0.0.1' || parsedUrl.hostname === '[::1]') && parsedUrl.port !== '';
|
|
3295
|
+
if (parsedUrl.protocol !== 'https:' && !(options.allowLoopbackHttp === true && parsedUrl.protocol === 'http:' && isLoopback)) {
|
|
3296
|
+
manifestInvalid('external gate url must use https:// or explicit-port loopback http:// when allowLoopbackHttp is enabled', `${gPath}/url`);
|
|
3297
|
+
}
|
|
3298
|
+
url = urlStr;
|
|
3299
|
+
}
|
|
3300
|
+
return Object.freeze({
|
|
3301
|
+
id: gateCheckId,
|
|
3302
|
+
...(declaredImplementation === undefined ? {} : { implementation: declaredImplementation }),
|
|
3303
|
+
gateId: requireIdentifier(gate['gateId'], `${gPath}/gateId`),
|
|
3304
|
+
endpointId,
|
|
3305
|
+
required: requireBoolean(gate['required'], `${gPath}/required`),
|
|
3306
|
+
...(signingCredentialRef === undefined ? {} : { signingCredentialRef }),
|
|
3307
|
+
...(authCredentialRef === undefined ? {} : { authCredentialRef }),
|
|
3308
|
+
...(url === undefined ? {} : { url }),
|
|
3309
|
+
});
|
|
3310
|
+
});
|
|
3311
|
+
// Optional `spec.publication` (defaults to `{ mode: 'disabled' }`; branch/title required only for `pull_request`).
|
|
3312
|
+
let publicationRecord;
|
|
3313
|
+
if (spec['publication'] === undefined) {
|
|
3314
|
+
publicationRecord = Object.freeze({ mode: 'disabled' });
|
|
3315
|
+
}
|
|
3316
|
+
else {
|
|
3317
|
+
const publication = requireObject(spec['publication'], '/spec/publication', [
|
|
3318
|
+
'mode', 'targetBranch', 'headBranchPrefix', 'titleTemplate', 'bodyTemplate',
|
|
3319
|
+
]);
|
|
3320
|
+
const publicationMode = requireString(publication['mode'], '/spec/publication/mode', 1, 16);
|
|
3321
|
+
if (publicationMode !== 'pull_request' && publicationMode !== 'disabled') {
|
|
3322
|
+
manifestInvalid('publication mode must be pull_request or disabled', '/spec/publication/mode');
|
|
3323
|
+
}
|
|
3324
|
+
const validateTargetBranch = (val) => {
|
|
3325
|
+
const tb = requireString(val, '/spec/publication/targetBranch', 1, 128);
|
|
3326
|
+
if (!TARGET_BRANCH_PATTERN.test(tb))
|
|
3327
|
+
manifestInvalid('targetBranch is not a valid branch name', '/spec/publication/targetBranch');
|
|
3328
|
+
return tb;
|
|
3329
|
+
};
|
|
3330
|
+
const validateHeadBranchPrefix = (val) => {
|
|
3331
|
+
const hbp = requireString(val, '/spec/publication/headBranchPrefix', 1, 64);
|
|
3332
|
+
const trimmed = hbp.replace(/\/$/, '');
|
|
3333
|
+
const segments = trimmed.split('/');
|
|
3334
|
+
if (hbp.includes('//')
|
|
3335
|
+
|| hbp.startsWith('/')
|
|
3336
|
+
|| !/^[A-Za-z0-9][A-Za-z0-9._/-]{0,62}$/.test(trimmed)
|
|
3337
|
+
|| segments.some(seg => seg.length === 0 || seg === '.' || seg === '..' || seg.startsWith('.') || seg.endsWith('.lock'))) {
|
|
3338
|
+
manifestInvalid('headBranchPrefix is not a valid branch prefix', '/spec/publication/headBranchPrefix');
|
|
3339
|
+
}
|
|
3340
|
+
return hbp;
|
|
3341
|
+
};
|
|
3342
|
+
const bodyTemplate = publication['bodyTemplate'] === undefined
|
|
3343
|
+
? undefined
|
|
3344
|
+
: requireMultilineString(publication['bodyTemplate'], '/spec/publication/bodyTemplate', 1, MAX_STRING);
|
|
3345
|
+
if (publicationMode === 'pull_request') {
|
|
3346
|
+
const targetBranch = validateTargetBranch(publication['targetBranch']);
|
|
3347
|
+
const headBranchPrefix = validateHeadBranchPrefix(publication['headBranchPrefix']);
|
|
3348
|
+
const titleTemplate = requireString(publication['titleTemplate'], '/spec/publication/titleTemplate', 1, 256);
|
|
3349
|
+
publicationRecord = Object.freeze({
|
|
3350
|
+
mode: 'pull_request',
|
|
3351
|
+
targetBranch,
|
|
3352
|
+
headBranchPrefix,
|
|
3353
|
+
titleTemplate,
|
|
3354
|
+
...(bodyTemplate === undefined ? {} : { bodyTemplate }),
|
|
3355
|
+
});
|
|
3356
|
+
}
|
|
3357
|
+
else {
|
|
3358
|
+
const targetBranch = publication['targetBranch'] === undefined
|
|
3359
|
+
? undefined
|
|
3360
|
+
: validateTargetBranch(publication['targetBranch']);
|
|
3361
|
+
const headBranchPrefix = publication['headBranchPrefix'] === undefined
|
|
3362
|
+
? undefined
|
|
3363
|
+
: validateHeadBranchPrefix(publication['headBranchPrefix']);
|
|
3364
|
+
const titleTemplate = publication['titleTemplate'] === undefined
|
|
3365
|
+
? undefined
|
|
3366
|
+
: requireString(publication['titleTemplate'], '/spec/publication/titleTemplate', 1, 256);
|
|
3367
|
+
publicationRecord = Object.freeze({
|
|
3368
|
+
mode: 'disabled',
|
|
3369
|
+
...(targetBranch === undefined ? {} : { targetBranch }),
|
|
3370
|
+
...(headBranchPrefix === undefined ? {} : { headBranchPrefix }),
|
|
3371
|
+
...(titleTemplate === undefined ? {} : { titleTemplate }),
|
|
3372
|
+
...(bodyTemplate === undefined ? {} : { bodyTemplate }),
|
|
3373
|
+
});
|
|
3374
|
+
}
|
|
3375
|
+
}
|
|
3376
|
+
// Optional `spec.memory` (defaults to `<controlRoot>/memory/default`, `apply: 'disabled'`, `onNoModelBudget: 'skip'`).
|
|
3377
|
+
const memoryRoot = `${controlRoot}/memory`;
|
|
3378
|
+
let memoryRecord;
|
|
3379
|
+
if (spec['memory'] === undefined) {
|
|
3380
|
+
const defaultDirectory = `${memoryRoot}/default`;
|
|
3381
|
+
const memoryOverlap = writable.find(entry => scopePatternsMayIntersect(entry, `${defaultDirectory}/**`, false));
|
|
3382
|
+
if (memoryOverlap !== undefined) {
|
|
3383
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `memory directory "${defaultDirectory}" overlaps writable path "${memoryOverlap}"`, '/spec/memory/directory');
|
|
3384
|
+
}
|
|
3385
|
+
memoryRecord = Object.freeze({
|
|
3386
|
+
directory: defaultDirectory,
|
|
3387
|
+
apply: 'disabled',
|
|
3388
|
+
onNoModelBudget: 'skip',
|
|
3389
|
+
ttlDays: DEFAULT_MEMORY_TTL_DAYS,
|
|
3390
|
+
maxEntries: DEFAULT_MEMORY_MAX_ENTRIES,
|
|
3391
|
+
maxPromptEntries: DEFAULT_MEMORY_MAX_PROMPT_ENTRIES,
|
|
3392
|
+
checkCodeFingerprint: false,
|
|
3393
|
+
checkUpstreamVersions: false,
|
|
3394
|
+
publishOnFailure: false,
|
|
3395
|
+
skipCi: true,
|
|
3396
|
+
});
|
|
3397
|
+
}
|
|
3398
|
+
else {
|
|
3399
|
+
const memory = requireObject(spec['memory'], '/spec/memory', [
|
|
3400
|
+
'directory', 'apply', 'onNoModelBudget', 'ttlDays', 'maxEntries', 'maxPromptEntries',
|
|
3401
|
+
'checkCodeFingerprint', 'checkUpstreamVersions', 'publishOnFailure', 'skipCi',
|
|
3402
|
+
]);
|
|
3403
|
+
const memoryDirectory = normalizeRelativePath(memory['directory'], '/spec/memory/directory');
|
|
3404
|
+
if (!pathCoveredBy(memoryDirectory, memoryRoot)) {
|
|
3405
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `memory directory must be under ${memoryRoot}`, '/spec/memory/directory');
|
|
3406
|
+
}
|
|
3407
|
+
const memoryOverlap = writable.find(entry => scopePatternsMayIntersect(entry, `${memoryDirectory}/**`, false));
|
|
3408
|
+
if (memoryOverlap !== undefined) {
|
|
3409
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `memory directory "${memoryDirectory}" overlaps writable path "${memoryOverlap}"`, '/spec/memory/directory');
|
|
3410
|
+
}
|
|
3411
|
+
const applyRaw = requireString(memory['apply'], '/spec/memory/apply', 1, 32);
|
|
3412
|
+
if (applyRaw !== 'separate-pull-request'
|
|
3413
|
+
&& applyRaw !== 'inline-with-candidate'
|
|
3414
|
+
&& applyRaw !== 'local-only'
|
|
3415
|
+
&& applyRaw !== 'disabled') {
|
|
3416
|
+
manifestInvalid('memory apply must be separate-pull-request, inline-with-candidate, local-only, or disabled', '/spec/memory/apply');
|
|
3417
|
+
}
|
|
3418
|
+
const apply = applyRaw;
|
|
3419
|
+
let onNoModelBudget;
|
|
3420
|
+
if (memory['onNoModelBudget'] === undefined) {
|
|
3421
|
+
if (apply === 'disabled') {
|
|
3422
|
+
onNoModelBudget = 'skip';
|
|
3423
|
+
}
|
|
3424
|
+
else {
|
|
3425
|
+
manifestInvalid('onNoModelBudget must be deterministic-observations-only or skip', '/spec/memory/onNoModelBudget');
|
|
3426
|
+
}
|
|
3427
|
+
}
|
|
3428
|
+
else {
|
|
3429
|
+
const rawNoBudget = requireString(memory['onNoModelBudget'], '/spec/memory/onNoModelBudget', 1, 48);
|
|
3430
|
+
if (rawNoBudget !== 'deterministic-observations-only' && rawNoBudget !== 'skip') {
|
|
3431
|
+
manifestInvalid('onNoModelBudget must be deterministic-observations-only or skip', '/spec/memory/onNoModelBudget');
|
|
3432
|
+
}
|
|
3433
|
+
onNoModelBudget = rawNoBudget;
|
|
3434
|
+
}
|
|
3435
|
+
const ttlDays = memory['ttlDays'] === undefined
|
|
3436
|
+
? DEFAULT_MEMORY_TTL_DAYS
|
|
3437
|
+
: requireSafeIntInRange(memory['ttlDays'], '/spec/memory/ttlDays', 1, 365);
|
|
3438
|
+
const maxEntries = memory['maxEntries'] === undefined
|
|
3439
|
+
? DEFAULT_MEMORY_MAX_ENTRIES
|
|
3440
|
+
: requireSafeIntInRange(memory['maxEntries'], '/spec/memory/maxEntries', 1, 512);
|
|
3441
|
+
const maxPromptEntries = memory['maxPromptEntries'] === undefined
|
|
3442
|
+
? DEFAULT_MEMORY_MAX_PROMPT_ENTRIES
|
|
3443
|
+
: requireSafeIntInRange(memory['maxPromptEntries'], '/spec/memory/maxPromptEntries', 1, 128);
|
|
3444
|
+
const checkCodeFingerprint = memory['checkCodeFingerprint'] === undefined
|
|
3445
|
+
? false
|
|
3446
|
+
: requireBoolean(memory['checkCodeFingerprint'], '/spec/memory/checkCodeFingerprint');
|
|
3447
|
+
const checkUpstreamVersions = memory['checkUpstreamVersions'] === undefined
|
|
3448
|
+
? false
|
|
3449
|
+
: requireBoolean(memory['checkUpstreamVersions'], '/spec/memory/checkUpstreamVersions');
|
|
3450
|
+
const publishOnFailure = memory['publishOnFailure'] === undefined
|
|
3451
|
+
? false
|
|
3452
|
+
: requireBoolean(memory['publishOnFailure'], '/spec/memory/publishOnFailure');
|
|
3453
|
+
const skipCi = memory['skipCi'] === undefined
|
|
3454
|
+
? apply !== 'inline-with-candidate'
|
|
3455
|
+
: requireBoolean(memory['skipCi'], '/spec/memory/skipCi');
|
|
3456
|
+
memoryRecord = Object.freeze({
|
|
3457
|
+
directory: memoryDirectory,
|
|
3458
|
+
apply,
|
|
3459
|
+
onNoModelBudget,
|
|
3460
|
+
ttlDays,
|
|
3461
|
+
maxEntries,
|
|
3462
|
+
maxPromptEntries,
|
|
3463
|
+
checkCodeFingerprint,
|
|
3464
|
+
checkUpstreamVersions,
|
|
3465
|
+
publishOnFailure,
|
|
3466
|
+
skipCi,
|
|
3467
|
+
});
|
|
3468
|
+
}
|
|
3469
|
+
// Optional `spec.triggers` (omitted normalizes to all-false and empty arrays).
|
|
3470
|
+
let triggersRecord;
|
|
3471
|
+
if (spec['triggers'] === undefined) {
|
|
3472
|
+
triggersRecord = Object.freeze({
|
|
3473
|
+
schedule: false,
|
|
3474
|
+
workflowDispatch: false,
|
|
3475
|
+
releasePublished: false,
|
|
3476
|
+
commentCommands: Object.freeze([]),
|
|
3477
|
+
commentPrefixes: Object.freeze([]),
|
|
3478
|
+
});
|
|
3479
|
+
}
|
|
3480
|
+
else {
|
|
3481
|
+
const triggers = requireObject(spec['triggers'], '/spec/triggers', ['schedule', 'workflowDispatch', 'releasePublished', 'commentCommands', 'commentPrefixes']);
|
|
3482
|
+
const schedule = requireBoolean(triggers['schedule'], '/spec/triggers/schedule');
|
|
3483
|
+
const workflowDispatch = requireBoolean(triggers['workflowDispatch'], '/spec/triggers/workflowDispatch');
|
|
3484
|
+
const releasePublished = requireBoolean(triggers['releasePublished'], '/spec/triggers/releasePublished');
|
|
3485
|
+
const commentCommandsValue = triggers['commentCommands'];
|
|
3486
|
+
if (!Array.isArray(commentCommandsValue) || commentCommandsValue.length > TASKPACK_COMMENT_COMMANDS.length) {
|
|
3487
|
+
manifestInvalid(`commentCommands must contain 0..${TASKPACK_COMMENT_COMMANDS.length} entries`, '/spec/triggers/commentCommands');
|
|
3488
|
+
}
|
|
3489
|
+
const seenCommands = new Set();
|
|
3490
|
+
const commentCommands = commentCommandsValue.map((item, index) => {
|
|
3491
|
+
const command = requireString(item, `/spec/triggers/commentCommands/${index}`, 1, 8);
|
|
3492
|
+
if (!TASKPACK_COMMENT_COMMANDS.includes(command))
|
|
3493
|
+
manifestInvalid(`unsupported comment command "${command}"`, '/spec/triggers/commentCommands');
|
|
3494
|
+
if (seenCommands.has(command))
|
|
3495
|
+
manifestInvalid('duplicate comment command', '/spec/triggers/commentCommands');
|
|
3496
|
+
seenCommands.add(command);
|
|
3497
|
+
return command;
|
|
3498
|
+
});
|
|
3499
|
+
const commentPrefixesValue = triggers['commentPrefixes'];
|
|
3500
|
+
const commentPrefixes = commentPrefixesValue === undefined
|
|
3501
|
+
? DEFAULT_COMMENT_PREFIXES
|
|
3502
|
+
: requireStringList(commentPrefixesValue, '/spec/triggers/commentPrefixes', 1, 8).map((entry, index) => {
|
|
3503
|
+
if (!COMMENT_PREFIX_PATTERN.test(entry))
|
|
3504
|
+
manifestInvalid(`comment prefix "${entry}" must match /<token>`, `/spec/triggers/commentPrefixes/${index}`);
|
|
3505
|
+
return entry;
|
|
3506
|
+
});
|
|
3507
|
+
triggersRecord = Object.freeze({
|
|
3508
|
+
schedule,
|
|
3509
|
+
workflowDispatch,
|
|
3510
|
+
releasePublished,
|
|
3511
|
+
commentCommands: Object.freeze(commentCommands),
|
|
3512
|
+
commentPrefixes: Object.freeze(commentPrefixes),
|
|
3513
|
+
});
|
|
3514
|
+
}
|
|
3515
|
+
if (policyProfile === 'github' && options.requireDeclaredTrigger === true && !hasAnyDeclaredGitHubTrigger(triggersRecord)) {
|
|
3516
|
+
throw new TaskpackError('TASKPACK_TRIGGER_UNSUPPORTED', 'manifest declares no enabled GitHub triggers under policyProfile "github"', '/spec/triggers');
|
|
3517
|
+
}
|
|
3518
|
+
const baselineAlignment = Object.hasOwn(spec, 'baselineAlignment') && spec['baselineAlignment'] !== undefined
|
|
3519
|
+
? validateBaselineAlignmentDeclaration(spec['baselineAlignment'], '/spec/baselineAlignment')
|
|
3520
|
+
: undefined;
|
|
3521
|
+
let sandbox;
|
|
3522
|
+
if (spec['sandbox'] !== undefined) {
|
|
3523
|
+
const rawSandbox = requireObject(spec['sandbox'], '/spec/sandbox', ['preferredBackends', 'networkMode', 'requiredCapabilities', 'deniedReadPaths']);
|
|
3524
|
+
const allowedBackends = ['macos-seatbelt', 'linux-bwrap', 'linux-landlock', 'docker', 'direct-dedicated'];
|
|
3525
|
+
const allowedCapabilities = [
|
|
3526
|
+
'filesystemReadContainment', 'filesystemWriteContainment', 'protectedPathReadOnlyMask',
|
|
3527
|
+
'networkIsolation', 'processTreeCleanup', 'syscallFiltering',
|
|
3528
|
+
];
|
|
3529
|
+
let preferredBackends;
|
|
3530
|
+
if (rawSandbox['preferredBackends'] !== undefined) {
|
|
3531
|
+
preferredBackends = Object.freeze(requireStringList(rawSandbox['preferredBackends'], '/spec/sandbox/preferredBackends', 1, 5).map((item, idx) => {
|
|
3532
|
+
if (!allowedBackends.includes(item)) {
|
|
3533
|
+
manifestInvalid(`unsupported sandbox backend "${item}"`, `/spec/sandbox/preferredBackends/${idx}`);
|
|
3534
|
+
}
|
|
3535
|
+
return item;
|
|
3536
|
+
}));
|
|
3537
|
+
}
|
|
3538
|
+
let networkMode;
|
|
3539
|
+
if (rawSandbox['networkMode'] !== undefined) {
|
|
3540
|
+
const modeStr = requireString(rawSandbox['networkMode'], '/spec/sandbox/networkMode', 1, 32);
|
|
3541
|
+
if (modeStr !== 'none' && modeStr !== 'loopback-only' && modeStr !== 'allow-outbound') {
|
|
3542
|
+
manifestInvalid(`unsupported sandbox networkMode "${modeStr}"`, '/spec/sandbox/networkMode');
|
|
3543
|
+
}
|
|
3544
|
+
if (modeStr === 'allow-outbound' && !resolvedExecution.capabilities.allowAgentNetwork) {
|
|
3545
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', 'spec.sandbox.networkMode "allow-outbound" requires spec.execution.capabilities.allowAgentNetwork: true', '/spec/sandbox/networkMode');
|
|
3546
|
+
}
|
|
3547
|
+
networkMode = modeStr;
|
|
3548
|
+
}
|
|
3549
|
+
let requiredCapabilities;
|
|
3550
|
+
if (rawSandbox['requiredCapabilities'] !== undefined) {
|
|
3551
|
+
requiredCapabilities = Object.freeze(requireStringList(rawSandbox['requiredCapabilities'], '/spec/sandbox/requiredCapabilities', 0, 6).map((item, idx) => {
|
|
3552
|
+
if (!allowedCapabilities.includes(item)) {
|
|
3553
|
+
manifestInvalid(`unsupported sandbox capability "${item}"`, `/spec/sandbox/requiredCapabilities/${idx}`);
|
|
3554
|
+
}
|
|
3555
|
+
return item;
|
|
3556
|
+
}));
|
|
3557
|
+
}
|
|
3558
|
+
let deniedReadPaths;
|
|
3559
|
+
if (rawSandbox['deniedReadPaths'] !== undefined) {
|
|
3560
|
+
deniedReadPaths = Object.freeze(requireStringList(rawSandbox['deniedReadPaths'], '/spec/sandbox/deniedReadPaths', 0, 64).map((entry, idx) => {
|
|
3561
|
+
const itemPath = `/spec/sandbox/deniedReadPaths/${idx}`;
|
|
3562
|
+
if (entry.startsWith('~/')) {
|
|
3563
|
+
return `~/${normalizeRelativePath(entry.slice(2), itemPath)}`;
|
|
3564
|
+
}
|
|
3565
|
+
return normalizeRelativePath(entry, itemPath);
|
|
3566
|
+
}));
|
|
3567
|
+
}
|
|
3568
|
+
const sandboxObj = {};
|
|
3569
|
+
if (networkMode !== undefined)
|
|
3570
|
+
sandboxObj.networkMode = networkMode;
|
|
3571
|
+
if (preferredBackends !== undefined)
|
|
3572
|
+
sandboxObj.preferredBackends = preferredBackends;
|
|
3573
|
+
if (requiredCapabilities !== undefined)
|
|
3574
|
+
sandboxObj.requiredCapabilities = requiredCapabilities;
|
|
3575
|
+
if (deniedReadPaths !== undefined)
|
|
3576
|
+
sandboxObj.deniedReadPaths = deniedReadPaths;
|
|
3577
|
+
sandbox = Object.freeze(sandboxObj);
|
|
3578
|
+
}
|
|
3579
|
+
let decisions;
|
|
3580
|
+
if (spec['decisions'] !== undefined) {
|
|
3581
|
+
const rawDecisions = requireObject(spec['decisions'], '/spec/decisions', [
|
|
3582
|
+
'enabled', 'provider', 'disclosurePolicy', 'minConfidence', 'confirmThreshold',
|
|
3583
|
+
'hardDeadlineMs', 'maxAttempts', 'allowImages', 'triageRules',
|
|
3584
|
+
]);
|
|
3585
|
+
const enabled = requireBoolean(rawDecisions['enabled'], '/spec/decisions/enabled');
|
|
3586
|
+
const allowedProviders = [
|
|
3587
|
+
'typesafe-jev', 'openai-decisions', 'startlux-decision', 'microsoft-decision',
|
|
3588
|
+
'perplexity-decider', 'cloudflare-clef', 'liquid-d1',
|
|
3589
|
+
];
|
|
3590
|
+
const allowedDisclosures = [
|
|
3591
|
+
'disabled', 'repo-approved-redacted-evidence', 'public-metadata-only',
|
|
3592
|
+
];
|
|
3593
|
+
const decisionsObj = { enabled };
|
|
3594
|
+
if (rawDecisions['provider'] !== undefined) {
|
|
3595
|
+
const providerStr = requireString(rawDecisions['provider'], '/spec/decisions/provider', 1, 64);
|
|
3596
|
+
if (!allowedProviders.includes(providerStr)) {
|
|
3597
|
+
manifestInvalid(`unsupported decisions provider "${providerStr}"`, '/spec/decisions/provider');
|
|
3598
|
+
}
|
|
3599
|
+
decisionsObj.provider = providerStr;
|
|
3600
|
+
}
|
|
3601
|
+
if (rawDecisions['disclosurePolicy'] !== undefined) {
|
|
3602
|
+
const disclosureStr = requireString(rawDecisions['disclosurePolicy'], '/spec/decisions/disclosurePolicy', 1, 64);
|
|
3603
|
+
if (!allowedDisclosures.includes(disclosureStr)) {
|
|
3604
|
+
manifestInvalid(`unsupported decisions disclosurePolicy "${disclosureStr}"`, '/spec/decisions/disclosurePolicy');
|
|
3605
|
+
}
|
|
3606
|
+
decisionsObj.disclosurePolicy = disclosureStr;
|
|
3607
|
+
}
|
|
3608
|
+
if (rawDecisions['minConfidence'] !== undefined) {
|
|
3609
|
+
const minConf = rawDecisions['minConfidence'];
|
|
3610
|
+
if (typeof minConf !== 'number' || !Number.isFinite(minConf) || minConf < 0.5 || minConf > 1) {
|
|
3611
|
+
manifestInvalid('decisions.minConfidence must be a finite number in [0.5, 1.0]', '/spec/decisions/minConfidence');
|
|
3612
|
+
}
|
|
3613
|
+
decisionsObj.minConfidence = minConf;
|
|
3614
|
+
}
|
|
3615
|
+
if (rawDecisions['confirmThreshold'] !== undefined) {
|
|
3616
|
+
const confirmThresh = rawDecisions['confirmThreshold'];
|
|
3617
|
+
if (typeof confirmThresh !== 'number' || !Number.isFinite(confirmThresh) || confirmThresh < 0 || confirmThresh > 1) {
|
|
3618
|
+
manifestInvalid('decisions.confirmThreshold must be a finite number in [0.0, 1.0]', '/spec/decisions/confirmThreshold');
|
|
3619
|
+
}
|
|
3620
|
+
decisionsObj.confirmThreshold = confirmThresh;
|
|
3621
|
+
}
|
|
3622
|
+
const effectiveConfirmThresh = decisionsObj.confirmThreshold ?? DEFAULT_DECISION_CONFIRM_THRESHOLD;
|
|
3623
|
+
const effectiveMinConf = decisionsObj.minConfidence ?? DEFAULT_DECISION_MIN_CONFIDENCE;
|
|
3624
|
+
if (effectiveConfirmThresh > effectiveMinConf) {
|
|
3625
|
+
manifestInvalid('decisions.confirmThreshold must not exceed minConfidence', '/spec/decisions/confirmThreshold');
|
|
3626
|
+
}
|
|
3627
|
+
if (rawDecisions['hardDeadlineMs'] !== undefined) {
|
|
3628
|
+
const deadline = rawDecisions['hardDeadlineMs'];
|
|
3629
|
+
if (typeof deadline !== 'number' || !Number.isSafeInteger(deadline) || deadline < 100 || deadline > 30_000) {
|
|
3630
|
+
manifestInvalid('decisions.hardDeadlineMs must be an integer in [100, 30000]', '/spec/decisions/hardDeadlineMs');
|
|
3631
|
+
}
|
|
3632
|
+
decisionsObj.hardDeadlineMs = deadline;
|
|
3633
|
+
}
|
|
3634
|
+
if (rawDecisions['maxAttempts'] !== undefined) {
|
|
3635
|
+
const attempts = rawDecisions['maxAttempts'];
|
|
3636
|
+
if (attempts !== 1 && attempts !== 2) {
|
|
3637
|
+
manifestInvalid('decisions.maxAttempts must be 1 or 2', '/spec/decisions/maxAttempts');
|
|
3638
|
+
}
|
|
3639
|
+
decisionsObj.maxAttempts = attempts;
|
|
3640
|
+
}
|
|
3641
|
+
if (rawDecisions['allowImages'] !== undefined) {
|
|
3642
|
+
decisionsObj.allowImages = requireBoolean(rawDecisions['allowImages'], '/spec/decisions/allowImages');
|
|
3643
|
+
}
|
|
3644
|
+
if (rawDecisions['triageRules'] !== undefined) {
|
|
3645
|
+
const rawRules = rawDecisions['triageRules'];
|
|
3646
|
+
if (!Array.isArray(rawRules) || rawRules.length > MAX_DECISION_TRIAGE_RULES) {
|
|
3647
|
+
manifestInvalid(`decisions.triageRules must be an array of 0..${MAX_DECISION_TRIAGE_RULES} entries`, '/spec/decisions/triageRules');
|
|
3648
|
+
}
|
|
3649
|
+
const seenRuleIds = new Set();
|
|
3650
|
+
const rules = rawRules.map((item, rIdx) => {
|
|
3651
|
+
const rulePath = `/spec/decisions/triageRules/${rIdx}`;
|
|
3652
|
+
const rawRule = requireObject(item, rulePath, ['id', 'description', 'severity', 'kind', 'threshold']);
|
|
3653
|
+
const ruleId = requireIdentifier(rawRule['id'], `${rulePath}/id`);
|
|
3654
|
+
if (seenRuleIds.has(ruleId))
|
|
3655
|
+
manifestInvalid(`duplicate triage rule id "${ruleId}"`, `${rulePath}/id`);
|
|
3656
|
+
seenRuleIds.add(ruleId);
|
|
3657
|
+
const description = requireString(rawRule['description'], `${rulePath}/description`, 1, 512);
|
|
3658
|
+
const sevStr = requireString(rawRule['severity'], `${rulePath}/severity`, 1, 16);
|
|
3659
|
+
if (sevStr !== 'blocking' && sevStr !== 'important' && sevStr !== 'nit') {
|
|
3660
|
+
manifestInvalid('triage rule severity must be "blocking", "important", or "nit"', `${rulePath}/severity`);
|
|
3661
|
+
}
|
|
3662
|
+
const kindStr = requireString(rawRule['kind'], `${rulePath}/kind`, 1, 16);
|
|
3663
|
+
if (kindStr !== 'noul' && kindStr !== 'score') {
|
|
3664
|
+
manifestInvalid('triage rule kind must be "noul" or "score"', `${rulePath}/kind`);
|
|
3665
|
+
}
|
|
3666
|
+
let threshold;
|
|
3667
|
+
if (rawRule['threshold'] !== undefined) {
|
|
3668
|
+
const t = rawRule['threshold'];
|
|
3669
|
+
if (typeof t !== 'number' || !Number.isFinite(t) || Object.is(t, -0) || t < 0 || t > 1) {
|
|
3670
|
+
manifestInvalid('triage rule threshold must be a finite number in [0.0, 1.0]', `${rulePath}/threshold`);
|
|
3671
|
+
}
|
|
3672
|
+
threshold = t;
|
|
3673
|
+
}
|
|
3674
|
+
return Object.freeze({
|
|
3675
|
+
id: ruleId,
|
|
3676
|
+
description,
|
|
3677
|
+
severity: sevStr,
|
|
3678
|
+
kind: kindStr,
|
|
3679
|
+
...(threshold === undefined ? {} : { threshold }),
|
|
3680
|
+
});
|
|
3681
|
+
});
|
|
3682
|
+
decisionsObj.triageRules = Object.freeze(rules);
|
|
3683
|
+
}
|
|
3684
|
+
decisions = Object.freeze(decisionsObj);
|
|
3685
|
+
}
|
|
3686
|
+
const checkEnvConflict = (secretEnvs, sourceLabel) => {
|
|
3687
|
+
if (secretEnvs.size === 0)
|
|
3688
|
+
return;
|
|
3689
|
+
if (preflight?.env !== undefined) {
|
|
3690
|
+
for (const [eIdx, envName] of preflight.env.entries()) {
|
|
3691
|
+
if (secretEnvs.has(envName)) {
|
|
3692
|
+
manifestInvalid(`preflight env "${envName}" conflicts with ${sourceLabel}`, `/spec/preflight/env/${eIdx}`);
|
|
3693
|
+
}
|
|
3694
|
+
}
|
|
3695
|
+
}
|
|
3696
|
+
for (const [checkIdx, check] of localChecks.entries()) {
|
|
3697
|
+
if (check.implementation !== 'command.v1')
|
|
3698
|
+
continue;
|
|
3699
|
+
const envVal = check.parameters?.['env'];
|
|
3700
|
+
if (Array.isArray(envVal)) {
|
|
3701
|
+
for (const [envIdx, envName] of envVal.entries()) {
|
|
3702
|
+
if (typeof envName === 'string' && secretEnvs.has(envName)) {
|
|
3703
|
+
manifestInvalid(`command.v1 env "${envName}" conflicts with ${sourceLabel}`, `/spec/verification/localChecks/${checkIdx}/parameters/env/${envIdx}`);
|
|
3704
|
+
}
|
|
3705
|
+
}
|
|
3706
|
+
}
|
|
3707
|
+
else if (envVal !== undefined && envVal !== null && typeof envVal === 'object') {
|
|
3708
|
+
for (const envName of Object.keys(envVal)) {
|
|
3709
|
+
if (secretEnvs.has(envName)) {
|
|
3710
|
+
manifestInvalid(`command.v1 env "${envName}" conflicts with ${sourceLabel}`, `/spec/verification/localChecks/${checkIdx}/parameters/env/${envName}`);
|
|
3711
|
+
}
|
|
3712
|
+
}
|
|
3713
|
+
}
|
|
3714
|
+
}
|
|
3715
|
+
};
|
|
3716
|
+
let models;
|
|
3717
|
+
if (spec['models'] !== undefined) {
|
|
3718
|
+
models = validateTaskpackModelsDeclaration(spec['models'], '/spec/models');
|
|
3719
|
+
const modelApiKeyEnvs = new Set(models.map(m => m.apiKeyEnv).filter((v) => v !== undefined));
|
|
3720
|
+
checkEnvConflict(modelApiKeyEnvs, 'spec.models apiKeyEnv');
|
|
3721
|
+
}
|
|
3722
|
+
const externalGateSecretEnvs = new Set();
|
|
3723
|
+
for (const gate of externalGates) {
|
|
3724
|
+
for (const ref of [gate.signingCredentialRef, gate.authCredentialRef]) {
|
|
3725
|
+
if (typeof ref === 'string' && COMMAND_ENV_NAME_PATTERN.test(ref)) {
|
|
3726
|
+
externalGateSecretEnvs.add(ref);
|
|
3727
|
+
}
|
|
3728
|
+
}
|
|
3729
|
+
}
|
|
3730
|
+
checkEnvConflict(externalGateSecretEnvs, 'spec.verification.externalGates credential ref');
|
|
3731
|
+
checkEnvConflict(new Set(Object.values(DECISION_PROVIDER_API_KEY_ENV).flat()), 'spec.decisions provider api key');
|
|
3732
|
+
let mcp;
|
|
3733
|
+
if (spec['mcp'] !== undefined) {
|
|
3734
|
+
const rawMcp = Array.isArray(spec['mcp'])
|
|
3735
|
+
? { servers: spec['mcp'] }
|
|
3736
|
+
: requireObject(spec['mcp'], '/spec/mcp', ['servers']);
|
|
3737
|
+
const servers = validateMcpServerDeclarations(rawMcp['servers'], Array.isArray(spec['mcp']) ? '/spec/mcp' : '/spec/mcp/servers', { allowLoopbackHttp: options.allowLoopbackHttp });
|
|
3738
|
+
mcp = Object.freeze({ servers });
|
|
3739
|
+
checkEnvConflict(collectMcpReferencedEnvNames(servers), 'spec.mcp secret env binding');
|
|
3740
|
+
}
|
|
3741
|
+
const mcpServerById = new Map(mcp?.servers.map(s => [s.id, s]) ?? []);
|
|
3742
|
+
let roles;
|
|
3743
|
+
const roleById = new Map();
|
|
3744
|
+
const allRoleInstructions = [];
|
|
3745
|
+
const allRoleSkills = [];
|
|
3746
|
+
if (spec['roles'] !== undefined) {
|
|
3747
|
+
const rawRoles = spec['roles'];
|
|
3748
|
+
if (!Array.isArray(rawRoles) || rawRoles.length < 1 || rawRoles.length > MAX_TASKPACK_ROLES) {
|
|
3749
|
+
manifestInvalid(`spec.roles must contain 1..${MAX_TASKPACK_ROLES} entries`, '/spec/roles');
|
|
3750
|
+
}
|
|
3751
|
+
const roleIds = new Set();
|
|
3752
|
+
const reservedRoleIds = new Set([
|
|
3753
|
+
...reservedIds,
|
|
3754
|
+
'controller.scope',
|
|
3755
|
+
'controller.no-change',
|
|
3756
|
+
'author-candidate',
|
|
3757
|
+
'author-assessment',
|
|
3758
|
+
]);
|
|
3759
|
+
const roleIndexById = new Map();
|
|
3760
|
+
const parsedRoles = rawRoles.map((item, idx) => {
|
|
3761
|
+
const rPath = `/spec/roles/${idx}`;
|
|
3762
|
+
const rawRole = requireObject(item, rPath, [
|
|
3763
|
+
'id', 'purpose', 'provider', 'model', 'thinking', 'tools', 'dependsOn',
|
|
3764
|
+
'instructions', 'skills', 'prompt', 'mcpServers', 'models', 'handoffs',
|
|
3765
|
+
]);
|
|
3766
|
+
const roleId = requireIdentifier(rawRole['id'], `${rPath}/id`);
|
|
3767
|
+
if (roleIds.has(roleId))
|
|
3768
|
+
manifestInvalid(`duplicate role id "${roleId}"`, `${rPath}/id`);
|
|
3769
|
+
if (checkIds.has(roleId))
|
|
3770
|
+
manifestInvalid(`role id "${roleId}" collides with check id`, `${rPath}/id`);
|
|
3771
|
+
if (reservedRoleIds.has(roleId))
|
|
3772
|
+
manifestInvalid(`role id "${roleId}" is reserved`, `${rPath}/id`);
|
|
3773
|
+
roleIds.add(roleId);
|
|
3774
|
+
let purpose = 'task';
|
|
3775
|
+
if (rawRole['purpose'] !== undefined) {
|
|
3776
|
+
const pStr = requireString(rawRole['purpose'], `${rPath}/purpose`, 1, 16);
|
|
3777
|
+
if (pStr !== 'task' && pStr !== 'review') {
|
|
3778
|
+
manifestInvalid('role purpose must be "task" or "review"', `${rPath}/purpose`);
|
|
3779
|
+
}
|
|
3780
|
+
purpose = pStr;
|
|
3781
|
+
}
|
|
3782
|
+
const provider = requireLabel(rawRole['provider'], `${rPath}/provider`);
|
|
3783
|
+
const model = requireLabel(rawRole['model'], `${rPath}/model`);
|
|
3784
|
+
const thinking = rawRole['thinking'] === undefined
|
|
3785
|
+
? 'medium'
|
|
3786
|
+
: requireLabel(rawRole['thinking'], `${rPath}/thinking`);
|
|
3787
|
+
let tools;
|
|
3788
|
+
if (rawRole['tools'] === undefined) {
|
|
3789
|
+
tools = purpose === 'review'
|
|
3790
|
+
? Object.freeze(['read'])
|
|
3791
|
+
: Object.freeze(['read', 'write', 'edit', 'bash']);
|
|
3792
|
+
}
|
|
3793
|
+
else {
|
|
3794
|
+
const rawTools = requireStringList(rawRole['tools'], `${rPath}/tools`, 1, TASKPACK_TOOL_NAMES.length);
|
|
3795
|
+
const validatedTools = [];
|
|
3796
|
+
for (const [tIdx, toolStr] of rawTools.entries()) {
|
|
3797
|
+
if (!TASKPACK_TOOL_NAMES.includes(toolStr)) {
|
|
3798
|
+
manifestInvalid(`unsupported role tool "${toolStr}"`, `${rPath}/tools/${tIdx}`);
|
|
3799
|
+
}
|
|
3800
|
+
if (purpose === 'review' && (toolStr === 'write' || toolStr === 'edit' || toolStr === 'delete')) {
|
|
3801
|
+
manifestInvalid(`review role "${roleId}" must not declare mutating tool "${toolStr}"`, `${rPath}/tools/${tIdx}`);
|
|
3802
|
+
}
|
|
3803
|
+
validatedTools.push(toolStr);
|
|
3804
|
+
}
|
|
3805
|
+
tools = Object.freeze(validatedTools);
|
|
3806
|
+
}
|
|
3807
|
+
let dependsOn = Object.freeze([]);
|
|
3808
|
+
if (rawRole['dependsOn'] !== undefined) {
|
|
3809
|
+
const rawDeps = requireStringList(rawRole['dependsOn'], `${rPath}/dependsOn`, 0, MAX_TASKPACK_ROLES - 1);
|
|
3810
|
+
for (const [dIdx, depId] of rawDeps.entries()) {
|
|
3811
|
+
requireIdentifier(depId, `${rPath}/dependsOn/${dIdx}`);
|
|
3812
|
+
const parentIdx = roleIndexById.get(depId);
|
|
3813
|
+
if (parentIdx === undefined || parentIdx >= idx) {
|
|
3814
|
+
manifestInvalid(`role "${roleId}" dependsOn "${depId}" must reference a prior role id`, `${rPath}/dependsOn/${dIdx}`);
|
|
3815
|
+
}
|
|
3816
|
+
}
|
|
3817
|
+
dependsOn = Object.freeze([...rawDeps]);
|
|
3818
|
+
}
|
|
3819
|
+
const roleInstructions = rawRole['instructions'] === undefined
|
|
3820
|
+
? undefined
|
|
3821
|
+
: validateResourceEntryOrList(rawRole['instructions'], `${rPath}/instructions`);
|
|
3822
|
+
if (roleInstructions !== undefined)
|
|
3823
|
+
allRoleInstructions.push(...roleInstructions);
|
|
3824
|
+
const roleSkills = rawRole['skills'] === undefined
|
|
3825
|
+
? undefined
|
|
3826
|
+
: validateResourceEntryOrList(rawRole['skills'], `${rPath}/skills`);
|
|
3827
|
+
if (roleSkills !== undefined)
|
|
3828
|
+
allRoleSkills.push(...roleSkills);
|
|
3829
|
+
const prompt = rawRole['prompt'] === undefined
|
|
3830
|
+
? undefined
|
|
3831
|
+
: requireMultilineString(rawRole['prompt'], `${rPath}/prompt`, 1, MAX_STRING);
|
|
3832
|
+
let mcpServers;
|
|
3833
|
+
if (rawRole['mcpServers'] !== undefined) {
|
|
3834
|
+
const rawServers = requireStringList(rawRole['mcpServers'], `${rPath}/mcpServers`, 0, 16);
|
|
3835
|
+
for (const [mIdx, serverId] of rawServers.entries()) {
|
|
3836
|
+
const declaredServer = MCP_SERVER_ID_PATTERN.test(serverId) ? mcpServerById.get(serverId) : undefined;
|
|
3837
|
+
if (declaredServer === undefined) {
|
|
3838
|
+
manifestInvalid(`role "${roleId}" mcpServers references undeclared MCP server "${serverId}"`, `${rPath}/mcpServers/${mIdx}`);
|
|
3839
|
+
}
|
|
3840
|
+
if (purpose === 'review' && declaredServer.readOnly !== true) {
|
|
3841
|
+
manifestInvalid(`review role "${roleId}" mcpServers entry "${serverId}" must reference a readOnly MCP server`, `${rPath}/mcpServers/${mIdx}`);
|
|
3842
|
+
}
|
|
3843
|
+
}
|
|
3844
|
+
mcpServers = Object.freeze([...rawServers]);
|
|
3845
|
+
}
|
|
3846
|
+
else if (purpose === 'review') {
|
|
3847
|
+
mcpServers = Object.freeze([]);
|
|
3848
|
+
}
|
|
3849
|
+
let roleModels;
|
|
3850
|
+
if (rawRole['models'] !== undefined) {
|
|
3851
|
+
const rawRoleModels = requireStringList(rawRole['models'], `${rPath}/models`, 1, 8);
|
|
3852
|
+
roleModels = Object.freeze(rawRoleModels.map((m, mIdx) => requireLabel(m, `${rPath}/models/${mIdx}`)));
|
|
3853
|
+
}
|
|
3854
|
+
let roleHandoffs;
|
|
3855
|
+
if (Object.hasOwn(rawRole, 'handoffs') && rawRole['handoffs'] !== undefined) {
|
|
3856
|
+
roleHandoffs = validateHandoffSelectors(rawRole['handoffs'], `${rPath}/handoffs`);
|
|
3857
|
+
}
|
|
3858
|
+
roleIndexById.set(roleId, idx);
|
|
3859
|
+
const roleDecl = Object.freeze({
|
|
3860
|
+
id: roleId,
|
|
3861
|
+
purpose,
|
|
3862
|
+
provider,
|
|
3863
|
+
model,
|
|
3864
|
+
thinking,
|
|
3865
|
+
tools,
|
|
3866
|
+
dependsOn,
|
|
3867
|
+
...(roleInstructions === undefined ? {} : { instructions: roleInstructions }),
|
|
3868
|
+
...(roleSkills === undefined ? {} : { skills: roleSkills }),
|
|
3869
|
+
...(prompt === undefined ? {} : { prompt }),
|
|
3870
|
+
...(mcpServers === undefined ? {} : { mcpServers }),
|
|
3871
|
+
...(roleModels === undefined ? {} : { models: roleModels }),
|
|
3872
|
+
...(roleHandoffs === undefined ? {} : { handoffs: roleHandoffs }),
|
|
3873
|
+
});
|
|
3874
|
+
roleById.set(roleId, roleDecl);
|
|
3875
|
+
return roleDecl;
|
|
3876
|
+
});
|
|
3877
|
+
roles = Object.freeze(parsedRoles);
|
|
3878
|
+
}
|
|
3879
|
+
// Enforce manifest-wide consistency for same-path resource `when` predicates (preserving first-wins cross-kind dedup).
|
|
3880
|
+
const declaredResourceByPath = new Map();
|
|
3881
|
+
const registerManifestResource = (entry, diagPath) => {
|
|
3882
|
+
const normalizedPath = resolveTaskpackResourcePath(entry);
|
|
3883
|
+
const whenKey = canonicalizeResourceActivationRule(resolveTaskpackResourceWhen(entry));
|
|
3884
|
+
const prior = declaredResourceByPath.get(normalizedPath);
|
|
3885
|
+
if (prior === undefined) {
|
|
3886
|
+
declaredResourceByPath.set(normalizedPath, { whenKey, firstPath: diagPath });
|
|
3887
|
+
return;
|
|
3888
|
+
}
|
|
3889
|
+
if (prior.whenKey !== whenKey) {
|
|
3890
|
+
manifestInvalid(`conflicting "when" predicate for resource path "${normalizedPath}" (previously declared at ${prior.firstPath})`, diagPath);
|
|
3891
|
+
}
|
|
3892
|
+
};
|
|
3893
|
+
for (const [idx, entry] of (instructions ?? []).entries()) {
|
|
3894
|
+
registerManifestResource(entry, `/spec/instructions/${idx}`);
|
|
3895
|
+
}
|
|
3896
|
+
for (const [idx, entry] of (skills ?? []).entries()) {
|
|
3897
|
+
registerManifestResource(entry, `/spec/skills/${idx}`);
|
|
3898
|
+
}
|
|
3899
|
+
for (const [rIdx, role] of (roles ?? []).entries()) {
|
|
3900
|
+
for (const [iIdx, entry] of (role.instructions ?? []).entries()) {
|
|
3901
|
+
registerManifestResource(entry, `/spec/roles/${rIdx}/instructions/${iIdx}`);
|
|
3902
|
+
}
|
|
3903
|
+
for (const [sIdx, entry] of (role.skills ?? []).entries()) {
|
|
3904
|
+
registerManifestResource(entry, `/spec/roles/${rIdx}/skills/${sIdx}`);
|
|
3905
|
+
}
|
|
3906
|
+
}
|
|
3907
|
+
let steps;
|
|
3908
|
+
if (spec['steps'] !== undefined) {
|
|
3909
|
+
steps = validateStepsDag(spec['steps'], roles ?? [], roleById, checkIds, options.executionMode);
|
|
3910
|
+
}
|
|
3911
|
+
else if (roles !== undefined) {
|
|
3912
|
+
for (const [rIdx, role] of roles.entries()) {
|
|
3913
|
+
if (role.handoffs === undefined)
|
|
3914
|
+
continue;
|
|
3915
|
+
const ancestors = collectStrictAncestors(role.id, id => roleById.get(id)?.dependsOn);
|
|
3916
|
+
for (const [hIdx, handoff] of role.handoffs.entries()) {
|
|
3917
|
+
const diagPath = `/spec/roles/${rIdx}/handoffs/${hIdx}/fromStep`;
|
|
3918
|
+
if (!roleById.has(handoff.fromStep)) {
|
|
3919
|
+
manifestInvalid(`role "${role.id}" handoff fromStep references unknown role "${handoff.fromStep}"`, diagPath);
|
|
3920
|
+
}
|
|
3921
|
+
if (handoff.fromStep === role.id || !ancestors.has(handoff.fromStep)) {
|
|
3922
|
+
manifestInvalid(`role "${role.id}" handoff fromStep "${handoff.fromStep}" must be a strict ancestor in spec.roles`, diagPath);
|
|
3923
|
+
}
|
|
3924
|
+
}
|
|
3925
|
+
}
|
|
3926
|
+
}
|
|
3927
|
+
// Final effective protected-path check including command scripts, preflight script, lockfile, toolchainPaths, and per-role assets.
|
|
3928
|
+
const combinedInstructions = [...(instructions ?? []), ...allRoleInstructions];
|
|
3929
|
+
const combinedSkills = [...(skills ?? []), ...allRoleSkills];
|
|
3930
|
+
const extraProtectedPaths = options.extraProtectedPaths?.map((entry, idx) => (normalizeScopePattern(entry, `/extraProtectedPaths/${idx}`)));
|
|
3931
|
+
const finalProtected = resolveProtectedPathSets(manifestProtected, {
|
|
3932
|
+
policyProfile,
|
|
3933
|
+
controlRoot,
|
|
3934
|
+
manifestPath,
|
|
3935
|
+
digestsLockfile,
|
|
3936
|
+
instructions: combinedInstructions.length > 0 ? combinedInstructions : undefined,
|
|
3937
|
+
skills: combinedSkills.length > 0 ? combinedSkills : undefined,
|
|
3938
|
+
preflightScript: preflight?.script,
|
|
3939
|
+
commandScripts,
|
|
3940
|
+
toolchainPaths: relativeToolchainPaths.length > 0 ? relativeToolchainPaths : undefined,
|
|
3941
|
+
proposalPath,
|
|
3942
|
+
extraProtectedPaths,
|
|
3943
|
+
allowWorkflowWrites,
|
|
3944
|
+
githubSiblings: options.githubSiblings,
|
|
3945
|
+
});
|
|
3946
|
+
const allProtected = finalProtected.allProtected;
|
|
3947
|
+
if (allProtected.length > 128) {
|
|
3948
|
+
manifestInvalid('effective protected path set exceeds 128 entries', '/spec/scope/protected');
|
|
3949
|
+
}
|
|
3950
|
+
assertWritablesDisjointFromProtected(writable, allProtected, finalProtected.mandatoryProtectedSet, controlRoot, proposalPath, policyProfile, allowWorkflowWrites);
|
|
3951
|
+
if (proposalPath !== undefined) {
|
|
3952
|
+
pathInsideWritable(proposalPath, writable, allProtected, '/spec/proposal/path', legacyPrefixFallback, policyProfile, allowWorkflowWrites, manifestProtectedSet);
|
|
3953
|
+
if ((pathCoveredBy(proposalPath, controlRoot) || pathCoveredByCaseInsensitive(proposalPath, controlRoot))
|
|
3954
|
+
&& !isControlRootProposalWritableAllowed(proposalPath, writable, controlRoot, finalProtected.explicitWithManifest)) {
|
|
3955
|
+
throw new TaskpackError('TASKPACK_SCOPE_VIOLATION', `spec.proposal.path "${proposalPath}" inside control root "${controlRoot}" must be listed as an exact file in spec.scope.writable without overlapping protected control-plane paths`, '/spec/proposal/path');
|
|
3956
|
+
}
|
|
3957
|
+
}
|
|
3958
|
+
if (submissionDecl !== undefined) {
|
|
3959
|
+
pathInsideWritable(submissionDecl.path, writable, allProtected, '/spec/submission/path', legacyPrefixFallback, policyProfile, allowWorkflowWrites, manifestProtectedSet);
|
|
3960
|
+
}
|
|
3961
|
+
let output;
|
|
3962
|
+
if (spec['output'] !== undefined) {
|
|
3963
|
+
const parseOutputFormats = (rawFormats, fmtPath) => {
|
|
3964
|
+
const asOutputFormat = (token, tokenPath) => {
|
|
3965
|
+
const matched = TASKPACK_OUTPUT_FORMATS.find(fmt => fmt === token);
|
|
3966
|
+
if (matched === undefined) {
|
|
3967
|
+
manifestInvalid(`unsupported output format "${token}"`, tokenPath);
|
|
3968
|
+
}
|
|
3969
|
+
return matched;
|
|
3970
|
+
};
|
|
3971
|
+
if (typeof rawFormats === 'string') {
|
|
3972
|
+
if (rawFormats.length === 0 || /[\0\r\n]/.test(rawFormats)) {
|
|
3973
|
+
manifestInvalid('output formats string must be non-empty without control characters', fmtPath);
|
|
3974
|
+
}
|
|
3975
|
+
const parts = rawFormats.split(',').map(part => part.trim());
|
|
3976
|
+
if (parts.length > TASKPACK_OUTPUT_FORMATS.length) {
|
|
3977
|
+
manifestInvalid(`expected 1..${TASKPACK_OUTPUT_FORMATS.length} output formats`, fmtPath);
|
|
3978
|
+
}
|
|
3979
|
+
const seen = new Set();
|
|
3980
|
+
const parsed = [];
|
|
3981
|
+
for (const part of parts) {
|
|
3982
|
+
if (part.length === 0) {
|
|
3983
|
+
manifestInvalid('output formats must not contain empty tokens', fmtPath);
|
|
3984
|
+
}
|
|
3985
|
+
const fmt = asOutputFormat(part, fmtPath);
|
|
3986
|
+
if (seen.has(fmt)) {
|
|
3987
|
+
manifestInvalid(`duplicate output format "${fmt}"`, fmtPath);
|
|
3988
|
+
}
|
|
3989
|
+
seen.add(fmt);
|
|
3990
|
+
parsed.push(fmt);
|
|
3991
|
+
}
|
|
3992
|
+
return Object.freeze(parsed);
|
|
3993
|
+
}
|
|
3994
|
+
const list = requireStringList(rawFormats, fmtPath, 1, TASKPACK_OUTPUT_FORMATS.length);
|
|
3995
|
+
const seen = new Set();
|
|
3996
|
+
const formats = [];
|
|
3997
|
+
for (const [idx, fmt] of list.entries()) {
|
|
3998
|
+
const normalized = asOutputFormat(fmt, `${fmtPath}/${idx}`);
|
|
3999
|
+
if (seen.has(normalized)) {
|
|
4000
|
+
manifestInvalid(`duplicate output format "${normalized}"`, `${fmtPath}/${idx}`);
|
|
4001
|
+
}
|
|
4002
|
+
seen.add(normalized);
|
|
4003
|
+
formats.push(normalized);
|
|
4004
|
+
}
|
|
4005
|
+
return Object.freeze(formats);
|
|
4006
|
+
};
|
|
4007
|
+
const rawSpecOutput = spec['output'];
|
|
4008
|
+
const formats = typeof rawSpecOutput === 'string' || Array.isArray(rawSpecOutput)
|
|
4009
|
+
? parseOutputFormats(rawSpecOutput, '/spec/output')
|
|
4010
|
+
: parseOutputFormats(requireObject(rawSpecOutput, '/spec/output', ['formats'])['formats'], '/spec/output/formats');
|
|
4011
|
+
output = Object.freeze({ formats });
|
|
4012
|
+
}
|
|
4013
|
+
const baseSpec = Object.freeze({
|
|
4014
|
+
goal: Object.freeze({ candidate: goalCandidate, noChange: goalNoChange }),
|
|
4015
|
+
scope: Object.freeze({ writable: Object.freeze(writable), protected: Object.freeze(manifestProtected) }),
|
|
4016
|
+
...(instructions === undefined ? {} : { instructions }),
|
|
4017
|
+
...(skills === undefined ? {} : { skills }),
|
|
4018
|
+
...(schemaMode === 'v2' || hasExplicitExecution ? { execution: resolvedExecution } : {}),
|
|
4019
|
+
...(preflight === undefined ? {} : { preflight }),
|
|
4020
|
+
...(vars === undefined ? {} : { vars }),
|
|
4021
|
+
...(target === undefined ? {} : { target }),
|
|
4022
|
+
upstreams: Object.freeze(upstreams),
|
|
4023
|
+
...(upstreamGroups === undefined ? {} : { upstreamGroups }),
|
|
4024
|
+
...(proposalDecl === undefined ? {} : { proposal: proposalDecl }),
|
|
4025
|
+
...(submissionDecl === undefined ? {} : { submission: submissionDecl }),
|
|
4026
|
+
verification: Object.freeze({ localChecks: Object.freeze(localChecks), externalGates: Object.freeze(externalGates) }),
|
|
4027
|
+
publication: publicationRecord,
|
|
4028
|
+
memory: memoryRecord,
|
|
4029
|
+
triggers: triggersRecord,
|
|
4030
|
+
...(baselineAlignment === undefined ? {} : { baselineAlignment }),
|
|
4031
|
+
...(sandbox === undefined ? {} : { sandbox }),
|
|
4032
|
+
...(decisions === undefined ? {} : { decisions }),
|
|
4033
|
+
...(models === undefined ? {} : { models }),
|
|
4034
|
+
...(mcp === undefined ? {} : { mcp }),
|
|
4035
|
+
...(limits === undefined ? {} : { limits }),
|
|
4036
|
+
...(roles === undefined ? {} : { roles }),
|
|
4037
|
+
...(steps === undefined ? {} : { steps }),
|
|
4038
|
+
...(output === undefined ? {} : { output }),
|
|
4039
|
+
});
|
|
4040
|
+
const manifest = {
|
|
4041
|
+
apiVersion: TASKPACK_MANIFEST_API_VERSION,
|
|
4042
|
+
kind: 'Taskpack',
|
|
4043
|
+
metadata: Object.freeze({ name }),
|
|
4044
|
+
spec: baseSpec,
|
|
4045
|
+
};
|
|
4046
|
+
// Keep controlRoot and manifestPath non-enumerable so JSON.stringify round-trips cleanly.
|
|
4047
|
+
Object.defineProperty(manifest, 'controlRoot', { value: controlRoot, enumerable: false });
|
|
4048
|
+
if (manifestPath !== undefined) {
|
|
4049
|
+
Object.defineProperty(manifest, 'manifestPath', { value: manifestPath, enumerable: false });
|
|
4050
|
+
}
|
|
4051
|
+
return Object.freeze(manifest);
|
|
4052
|
+
}
|
|
4053
|
+
/**
|
|
4054
|
+
* Validate a parsed Taskpack 2.0 manifest document (defaulting `policyProfile` to `'local'`).
|
|
4055
|
+
*/
|
|
4056
|
+
export function validateTaskpackV2Manifest(value, options = {}) {
|
|
4057
|
+
return validateTaskpackManifestInternal(value, options, 'v2');
|
|
4058
|
+
}
|
|
4059
|
+
/** Alias for `validateTaskpackV2Manifest` validating a parsed Taskpack manifest object. */
|
|
4060
|
+
export function validateTaskpackManifestObject(raw, options = {}) {
|
|
4061
|
+
return validateTaskpackManifestInternal(raw, options, 'v2');
|
|
4062
|
+
}
|
|
4063
|
+
/** Parse YAML text/bytes and validate as a Taskpack 2.0 manifest (defaulting `policyProfile` to `'local'`). */
|
|
4064
|
+
export function parseTaskpackManifest(rawYaml, options = {}) {
|
|
4065
|
+
const bytes = typeof rawYaml === 'string' ? Buffer.from(rawYaml, 'utf8') : rawYaml;
|
|
4066
|
+
const parsed = parseTaskpackDocument(bytes, 'yaml');
|
|
4067
|
+
return validateTaskpackV2Manifest(parsed, options);
|
|
4068
|
+
}
|
|
4069
|
+
/**
|
|
4070
|
+
* Validate a parsed manifest document and return the compile-compatible `TaskpackManifestWithProposal`
|
|
4071
|
+
* (requiring `spec.proposal` and v1 check implementations for legacy callers while supporting all additive
|
|
4072
|
+
* Taskpack 2.0 fields).
|
|
4073
|
+
*/
|
|
4074
|
+
export function validateTaskpackManifest(value, options = {}) {
|
|
4075
|
+
const v2 = validateTaskpackManifestInternal(value, options, 'v1-compat');
|
|
4076
|
+
if (v2.spec.proposal === undefined) {
|
|
4077
|
+
manifestInvalid('spec.proposal is required', '/spec/proposal');
|
|
4078
|
+
}
|
|
4079
|
+
return v2;
|
|
4080
|
+
}
|
|
4081
|
+
// ---------------------------------------------------------------------------
|
|
4082
|
+
// Shared candidate path & scope pattern helpers
|
|
4083
|
+
// ---------------------------------------------------------------------------
|
|
4084
|
+
/** Compile manifest `writable` or `protected` path entries into `@loopwright/core` scope patterns. */
|
|
4085
|
+
export function compileScopePatterns(entries, mode, options) {
|
|
4086
|
+
if (entries === undefined || entries.length === 0) {
|
|
4087
|
+
return mode === 'writable' ? Object.freeze(['**']) : Object.freeze([]);
|
|
4088
|
+
}
|
|
4089
|
+
const exactEntries = options?.exactEntries;
|
|
4090
|
+
const compiled = [];
|
|
4091
|
+
for (const [index, entry] of entries.entries()) {
|
|
4092
|
+
const diagPath = `/spec/scope/${mode}/${index}`;
|
|
4093
|
+
const check = validateScopePattern(entry);
|
|
4094
|
+
if (!check.ok) {
|
|
4095
|
+
manifestInvalid(`invalid scope pattern "${entry}": ${check.errors[0]?.code ?? 'PATTERN_UNSUPPORTED'}`, diagPath);
|
|
4096
|
+
}
|
|
4097
|
+
if (mode === 'writable') {
|
|
4098
|
+
compiled.push(check.value);
|
|
4099
|
+
}
|
|
4100
|
+
else if (exactEntries?.has(check.value)
|
|
4101
|
+
|| check.value === '**'
|
|
4102
|
+
|| check.value.endsWith('/**')
|
|
4103
|
+
|| check.value.includes('*')
|
|
4104
|
+
|| check.value.includes('?')
|
|
4105
|
+
|| check.value.length > LIMITS.path - 3) {
|
|
4106
|
+
compiled.push(check.value);
|
|
4107
|
+
}
|
|
4108
|
+
else {
|
|
4109
|
+
compiled.push(`${check.value}/**`);
|
|
4110
|
+
}
|
|
4111
|
+
}
|
|
4112
|
+
return Object.freeze([...new Set(compiled)]);
|
|
4113
|
+
}
|
|
4114
|
+
function normalizeProtectedCandidatePrefix(protectedEntry) {
|
|
4115
|
+
const withoutGlob = protectedEntry.endsWith('/**') ? protectedEntry.slice(0, -3) : protectedEntry;
|
|
4116
|
+
return withoutGlob.replace(/\/+$/, '');
|
|
4117
|
+
}
|
|
4118
|
+
/** True when `name` matches or sits beneath any entry in `protectedPaths`. */
|
|
4119
|
+
export function isProtectedCandidatePath(name, protectedPaths) {
|
|
4120
|
+
for (const protectedEntry of protectedPaths) {
|
|
4121
|
+
if (protectedEntry === '**')
|
|
4122
|
+
return true;
|
|
4123
|
+
const directMatch = matchesScopePattern(protectedEntry, name);
|
|
4124
|
+
if (directMatch.ok && directMatch.value)
|
|
4125
|
+
return true;
|
|
4126
|
+
const clean = normalizeProtectedCandidatePrefix(protectedEntry);
|
|
4127
|
+
if (clean.length === 0)
|
|
4128
|
+
continue;
|
|
4129
|
+
if (!clean.includes('*') && !clean.includes('?')) {
|
|
4130
|
+
if (name === clean || name.startsWith(`${clean}/`)) {
|
|
4131
|
+
return true;
|
|
4132
|
+
}
|
|
4133
|
+
}
|
|
4134
|
+
else {
|
|
4135
|
+
const subtreeMatch = matchesScopePattern(`${clean}/**`, name);
|
|
4136
|
+
if (subtreeMatch.ok && subtreeMatch.value) {
|
|
4137
|
+
return true;
|
|
4138
|
+
}
|
|
4139
|
+
}
|
|
4140
|
+
}
|
|
4141
|
+
return false;
|
|
4142
|
+
}
|
|
4143
|
+
/** True when `name` is outside `protectedPaths` (including NFC case-insensitive checks) and within `writable` scope. */
|
|
4144
|
+
export function isAllowedCandidateWrite(name, snapshot) {
|
|
4145
|
+
if (isProtectedCandidatePath(name, snapshot.protectedPaths)) {
|
|
4146
|
+
return false;
|
|
4147
|
+
}
|
|
4148
|
+
const lowerName = name.normalize('NFC').toLowerCase();
|
|
4149
|
+
const lowerProtected = snapshot.protectedPaths.map(entry => entry.normalize('NFC').toLowerCase());
|
|
4150
|
+
if (isProtectedCandidatePath(lowerName, lowerProtected)) {
|
|
4151
|
+
return false;
|
|
4152
|
+
}
|
|
4153
|
+
if (snapshot.contract !== undefined) {
|
|
4154
|
+
const writableCheck = isWritablePath(snapshot.contract, name);
|
|
4155
|
+
return writableCheck.ok && writableCheck.value === true;
|
|
4156
|
+
}
|
|
4157
|
+
if (snapshot.writablePaths !== undefined) {
|
|
4158
|
+
if (!validateRelativePath(name).ok)
|
|
4159
|
+
return false;
|
|
4160
|
+
const isProt = snapshot.protectedPaths.some(pattern => {
|
|
4161
|
+
const res = matchesScopePattern(pattern, name);
|
|
4162
|
+
return res.ok && res.value;
|
|
4163
|
+
});
|
|
4164
|
+
if (isProt)
|
|
4165
|
+
return false;
|
|
4166
|
+
return snapshot.writablePaths.some(pattern => {
|
|
4167
|
+
const res = matchesScopePattern(pattern, name);
|
|
4168
|
+
return res.ok && res.value;
|
|
4169
|
+
});
|
|
4170
|
+
}
|
|
4171
|
+
return false;
|
|
4172
|
+
}
|
|
4173
|
+
/** Validate a non-empty POSIX candidate relative path without NUL, backslashes, leading `/`, `.`, or `..`. */
|
|
4174
|
+
export function normalizeCandidateRelativePath(name) {
|
|
4175
|
+
if (typeof name !== 'string'
|
|
4176
|
+
|| name.length === 0
|
|
4177
|
+
|| name.includes('\0')
|
|
4178
|
+
|| name.includes('\\')
|
|
4179
|
+
|| name.startsWith('/')) {
|
|
4180
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `invalid candidate relative file path "${name}"`);
|
|
4181
|
+
}
|
|
4182
|
+
const parts = name.split('/');
|
|
4183
|
+
for (const part of parts) {
|
|
4184
|
+
if (part.length === 0 || part === '.' || part === '..') {
|
|
4185
|
+
throw new TaskpackError('ACTION_INPUT_INVALID', `invalid candidate path segment in "${name}"`);
|
|
4186
|
+
}
|
|
4187
|
+
}
|
|
4188
|
+
return name;
|
|
4189
|
+
}
|