@kungfu-tech/buildchain 2.14.15 → 2.14.16-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,7 @@
4
4
  "product": {
5
5
  "name": "Buildchain",
6
6
  "package": "@kungfu-tech/buildchain",
7
- "version": "2.14.15",
7
+ "version": "2.14.16-alpha.0",
8
8
  "repository": "https://github.com/kungfu-systems/buildchain"
9
9
  },
10
10
  "majorLine": "v2",
@@ -582,7 +582,7 @@
582
582
  "manual entries carry source file digests so downstream sites and agents can detect stale hand-written documentation"
583
583
  ],
584
584
  "breakingDigest": "sha256:7d0d2819e3a3e72989d9c57b5efe9d0bc0a79bc0f2c82a0c7b9d6c5a211a91f2",
585
- "auditDigest": "sha256:52a865116f5c733466a2f6eee866aeb2631d08b9baefa57de5c4d3bb4e471743"
585
+ "auditDigest": "sha256:b012b8c27fda3a7b5816b14fbd30c7761b899ba65c83079014d8d1f891b60608"
586
586
  },
587
587
  {
588
588
  "contractVersion": 1,
@@ -2913,5 +2913,5 @@
2913
2913
  }
2914
2914
  ],
2915
2915
  "compatibilityDigest": "sha256:cdf588422ec6b460bd6f631400efa6e361a045e052c8967d6c50fadd7aa4dd90",
2916
- "contractDigest": "sha256:f9d0f434a73812c3b2349104101f45541cb8fa7e7d1da789f775712fd2d9510e"
2916
+ "contractDigest": "sha256:1eb4a09877bfb2efea892d7125f0e3327f67e578f11fb6b10d044f4b6d34f987"
2917
2917
  }
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "contract": "kungfu-buildchain-site-bundle",
4
- "generatedAt": "2026-07-22T09:42:53.063Z",
5
- "publishedAt": "2026-07-22T09:42:53.063Z",
4
+ "generatedAt": "2026-07-22T10:03:39.987Z",
5
+ "publishedAt": "2026-07-22T10:03:39.987Z",
6
6
  "reproducible": true,
7
7
  "timestampPolicy": "ci-injected",
8
8
  "deterministicInputs": [
@@ -19,7 +19,7 @@
19
19
  "declared Buildchain surface manifest contract"
20
20
  ],
21
21
  "sourceDateEpoch": "0",
22
- "sourceRevision": "f092fb829717f4cd61d44522c9f96322d819fcef",
22
+ "sourceRevision": "473c1be9602573a533aac703e8f0802eda27e430",
23
23
  "timestampPolicyDetails": {
24
24
  "contract": "kungfu-buildchain-surface-timestamp-policy",
25
25
  "timestampFields": [
@@ -37,7 +37,7 @@
37
37
  },
38
38
  "package": {
39
39
  "name": "@kungfu-tech/buildchain",
40
- "version": "2.14.15",
40
+ "version": "2.14.16-alpha.0",
41
41
  "versionSource": "package.json#version"
42
42
  },
43
43
  "source": {
@@ -2084,7 +2084,7 @@
2084
2084
  ],
2085
2085
  "maturity": "stable",
2086
2086
  "sourcePath": "docs/web-surface-deployments.md",
2087
- "digest": "sha256:efbfc97a947978e61c79dac9d67f87050b1bef2297617303340af8aa499703c9",
2087
+ "digest": "sha256:ecdece4b7d916b7d8b323db68c5d81c533d67348c71907b46eb97d3c2fe432ba",
2088
2088
  "headings": [
2089
2089
  {
2090
2090
  "level": 1,
@@ -2156,6 +2156,11 @@
2156
2156
  "title": "Explicit Apply",
2157
2157
  "anchor": "explicit-apply"
2158
2158
  },
2159
+ {
2160
+ "level": 3,
2161
+ "title": "Explicit cache classes",
2162
+ "anchor": "explicit-cache-classes"
2163
+ },
2159
2164
  {
2160
2165
  "level": 3,
2161
2166
  "title": "Immutable publication paths",
@@ -2187,7 +2192,7 @@
2187
2192
  "anchor": "boundaries"
2188
2193
  }
2189
2194
  ],
2190
- "markdown": "# Web-Surface Deployment Contract\n\nBuildchain supports `project.type = \"web-surface\"` for repositories that publish\nsites, docs, product pages, operator consoles, or browser apps. These projects\nneed auditable deployment semantics, but they are not package release lines and\nshould not be forced into `dev/alpha/release` version-state automation.\n\nThe release object for a web surface is:\n\n```text\nsource commit + build artifact + deploy target + channel + deployment manifest\n```\n\nThis keeps the evidence chain clear:\n\n- the source SHA explains what code was built;\n- the artifact hash explains exactly what was deployed;\n- the channel explains who can see it and whether it is promotable;\n- the deploy target and adapter explain where it would be published;\n- the deployment manifest records retention, rollback, security, and secret\n reference metadata.\n\n## Configuration\n\n`.buildchain/buildchain.toml` is the source of truth. Web-surface projects must declare\npreview, staging, and production channels plus a deploy adapter for each.\n\n```toml\nschema = 1\n\n[project]\ntype = \"web-surface\"\nname = \"site-kungfu-tech\"\nsite = \"kungfu-tech\"\n\n[channels.preview]\nurl_pattern = \"https://{alias}.preview.kungfu.tech\"\nvisibility = \"ephemeral\"\nrequires_auth = false\nnoindex = true\n\n[channels.staging]\nurl = \"https://staging.kungfu.tech\"\nvisibility = \"protected\"\naccess_control = \"managed-network\"\nedge_auth = \"none\"\nnoindex = true\npromotable = true\n\n[channels.production]\nurl = \"https://kungfu.tech\"\nvisibility = \"public\"\ncanonical = true\nnoindex = false\n\n[deploy.preview]\nadapter = \"aws-s3-cloudfront\"\nbucket = \"kungfu-tech-preview\"\ncloudfront_distribution = \"E-PREVIEW\"\nartifact_path = \"dist\"\nsecret_refs = [\"AWS_ROLE_ARN\"]\n# Optional. Defaults to \"buildchain\".\n# Use \"external\" when an existing viewer-request CloudFront Function already\n# owns preview alias, surface-prefix, and directory-index routing.\ndirectory_index_rewrite = \"buildchain\"\n# Optional. Defaults to HTTP for public channels and S3 object evidence for\n# managed-network channels. Use \"s3-object\" when CI should verify uploaded\n# objects and manifests instead of waiting for public edge convergence.\nhealth_strategy = \"http\"\n```\n\n### Multi-Surface Host Mapping\n\nSome site repositories publish more than one first-class web surface from the\nsame artifact. For example, `site-libkungfu-dev` has a hub plus separate\nhostnames for core, Buildchain, and Kung Fu Decisions. These are not just\nnavigation paths; staging, production preflight, and post-deploy health checks\nmust verify host-level behavior for each surface.\n\nDeclare named surfaces with per-channel URLs:\n\n```toml\n[surfaces.hub]\npath = \"/\"\nproduction_url = \"https://libkungfu.dev\"\nstaging_url = \"https://staging.libkungfu.dev\"\npreview_url_pattern = \"https://{alias}.preview.libkungfu.dev\"\n\n[surfaces.core]\npath = \"/core/\"\nproduction_url = \"https://core.libkungfu.dev\"\nstaging_url = \"https://core.staging.libkungfu.dev\"\npreview_url_pattern = \"https://core-{alias}.preview.libkungfu.dev\"\n\n[surfaces.buildchain]\npath = \"/buildchain/\"\nproduction_url = \"https://buildchain.libkungfu.dev\"\nstaging_url = \"https://buildchain.staging.libkungfu.dev\"\npreview_url_pattern = \"https://buildchain-{alias}.preview.libkungfu.dev\"\n\n[surfaces.kfd]\npath = \"/kfd/\"\nproduction_url = \"https://kfd.libkungfu.dev\"\nstaging_url = \"https://kfd.staging.libkungfu.dev\"\npreview_url_pattern = \"https://kfd-{alias}.preview.libkungfu.dev\"\n```\n\nBuildchain resolves every `(channel, surface)` pair. A preview alias such as\n`pr-12` becomes:\n\n```text\nhub: https://pr-12.preview.libkungfu.dev\ncore: https://core-pr-12.preview.libkungfu.dev\nbuildchain: https://buildchain-pr-12.preview.libkungfu.dev\nkfd: https://kfd-pr-12.preview.libkungfu.dev\n```\n\nWhen `surfaces` is omitted, Buildchain preserves the legacy single-surface\ncontract by creating an implicit `default` surface from the channel URL. When a\nsurface is intentionally path-only, declare it explicitly:\n\n```toml\n[surfaces.docs]\npath = \"/docs/\"\npath_only = true\n```\n\n`path_only = true` is an exception, not the default. Without it, every named\nsurface must declare `preview_url_pattern`, `staging_url`, and\n`production_url`. This makes staging/production mismatches fail during\nvalidation instead of becoming invisible deploy drift.\n\nAdapter strategy remains explicit. The default `aws-s3-cloudfront` plan uses the\nchannel deploy target for every surface, and each binding records its own\nbucket, distribution id, object prefix, manifest key, source path, and URL. A\nchannel can override target details per surface:\n\n```toml\n[deploy.staging.surfaces.core]\nbucket = \"libkungfu-dev-core-staging\"\ncloudfront_distribution = \"E-CORE-STAGING\"\norigin_path = \"/core\"\n```\n\nBuildchain validates these hard constraints:\n\n- `channels.preview.url_pattern` is required and must contain the alias shape\n used by preview deployments.\n- `channels.staging.access_control` must protect staging. Supported modes are\n `managed-network`, `edge-basic-auth`, `oidc`, and `app-auth`.\n- `channels.staging.edge_auth` records whether the edge layer owns auth. Use\n `edge_auth = \"none\"` when staging is protected by managed network controls\n such as WAF/IP allowlists or VPN access.\n- `channels.staging.noindex = true` is required.\n- `channels.production.url` is required.\n- deploy adapters must be declared per channel.\n- named surfaces must declare first-class URLs for every channel unless\n `path_only = true` is explicitly set.\n- secret material must be declared as reference names, such as\n `secret_refs = [\"AWS_ROLE_ARN\"]`; inline secret-like deploy keys are rejected.\n\n### Floating Runtime Contract Lock\n\nWeb-surface repositories can consume the stable Buildchain workflow shell with a\nfloating ref, such as:\n\n```yaml\njobs:\n web:\n uses: kungfu-systems/buildchain/.github/workflows/.web-surface.yml@v2\n with:\n buildchain-contract-lock-path: .buildchain/contract-lock.json\n buildchain-contract-compatibility-policy: major-compatible\n buildchain-contract-drift-issue-mode: compatible-and-breaking\n build-command: pnpm build\n artifact-path: dist\n```\n\nThe caller repository commits `.buildchain/contract-lock.json` after reviewing an\naccepted Buildchain runtime SHA and contract digest. The reusable workflow then\nresolves the floating runtime to an immutable SHA, checks the lock before the\ncaller build command, and applies these rules:\n\n- unchanged lock: continue without feedback;\n- compatible drift: continue, write the drift summary, and open or update a\n caller-repository issue when permissions allow;\n- breaking drift: fail closed before rendering, deployment planning, deploy\n apply, or release publication.\n\nThe caller no longer needs to run `scripts/buildchain-contract-lock.mjs` inside\nits own build command. That check belongs to Buildchain because the actual\ncontract world is stored in the Buildchain runtime ref being used.\n\nSupported adapter names are:\n\n| Adapter | Initial use |\n| --- | --- |\n| `aws-s3-cloudfront` | Static site artifact sync plus CDN invalidation plan |\n| `aws-elastic-beanstalk` | Future dynamic app environment adapter |\n| `aws-ecs-service` | Future dynamic service adapter |\n\nThe channel ontology is independent of the adapter. A future dynamic staging\nenvironment still remains `channel = \"staging\"` with protected/noindex/security\nrequirements.\n\n## Preview Aliases\n\nPreview uses subdomains, not path prefixes:\n\n```text\nhttps://pr-123.preview.kungfu.tech\nhttps://sha-abcdef123456.preview.kungfu.tech\n```\n\nAlias semantics are explicit:\n\n| Alias | Meaning | Mutable | Retention |\n| --- | --- | --- | --- |\n| `pr-123` | Current preview for a pull request | yes | short-lived |\n| `sha-abcdef123456` | Immutable preview for one source SHA | no | longer-lived |\n\nThis allows PR comments to stay stable while preserving immutable evidence for a\nspecific source commit.\n\n## Deployment Manifest\n\nBuildchain emits a manifest with the deployment facts that matter for audit and\nrollback:\n\n```json\n{\n \"schemaVersion\": 1,\n \"contract\": \"kungfu-buildchain-web-surface-deployment\",\n \"site\": \"libkungfu-dev\",\n \"channel\": \"preview\",\n \"alias\": \"sha-abcdef123456\",\n \"url\": \"https://sha-abcdef123456.preview.libkungfu.dev\",\n \"generatedAt\": \"2026-07-01T00:00:00.000Z\",\n \"publishedAt\": \"2026-07-01T00:00:00.000Z\",\n \"reproducible\": true,\n \"timestampPolicy\": \"ci-injected\",\n \"deterministicInputs\": [\n \"web-surface artifact content\",\n \"buildchain.toml web-surface channels/deploy/surfaces\",\n \"sourceSha\",\n \"artifactHash\",\n \"deployment channel\",\n \"deployment alias\"\n ],\n \"sourceRevision\": \"...\",\n \"timestampPolicyDetails\": {\n \"contract\": \"kungfu-buildchain-surface-timestamp-policy\",\n \"timestampFields\": [\"generatedAt\", \"publishedAt\", \"deployedAt\"],\n \"timestampFieldsParticipateInArtifactDigest\": false,\n \"artifactDigestScope\": \"web-surface artifactHash excludes deployment manifest timestamps\"\n },\n \"sourceSha\": \"...\",\n \"artifactHash\": \"...\",\n \"deployTarget\": \"libkungfu-dev-preview\",\n \"adapter\": \"aws-s3-cloudfront\",\n \"deployedAt\": \"2026-07-01T00:00:00.000Z\",\n \"retentionClass\": \"preview-sha-immutable\",\n \"expiresAt\": \"2026-09-29T00:00:00.000Z\",\n \"accessControl\": \"none\",\n \"edgeAuth\": \"none\",\n \"noindex\": true,\n \"secretRefs\": [\"AWS_ROLE_ARN\"],\n \"surfaceBindings\": [\n {\n \"surface\": \"hub\",\n \"channel\": \"preview\",\n \"alias\": \"sha-abcdef123456\",\n \"url\": \"https://sha-abcdef123456.preview.libkungfu.dev\",\n \"sourcePath\": \"/\",\n \"artifactPathPrefix\": \"\",\n \"viewerPathPrefix\": \"/\",\n \"directoryIndex\": \"index.html\",\n \"directoryIndexResolution\": true,\n \"canonicalUrl\": \"https://libkungfu.dev\",\n \"bucket\": \"libkungfu-dev-preview\",\n \"distributionId\": \"E-PREVIEW\",\n \"originPath\": \"\",\n \"objectPrefix\": \"sha-abcdef123456\",\n \"manifestKey\": \".buildchain/deployments/sha-abcdef123456/hub.json\",\n \"routing\": {\n \"contract\": \"kungfu-buildchain-web-surface-path-prefix-rewrite\",\n \"viewerPathPrefix\": \"/\",\n \"artifactPathPrefix\": \"\",\n \"objectPrefix\": \"sha-abcdef123456\",\n \"directoryIndex\": \"index.html\",\n \"directoryIndexResolution\": true\n },\n \"smokeUrls\": [\n {\n \"kind\": \"root\",\n \"requestPath\": \"/\",\n \"url\": \"https://sha-abcdef123456.preview.libkungfu.dev/\",\n \"required\": true\n }\n ],\n \"noindex\": true,\n \"accessControl\": \"none\"\n }\n ]\n}\n```\n\nDynamic adapters can also fill `runtimeId`, `configFingerprint`,\n`healthCheck`, `migrationState`, `rollbackPointer`, and\n`rollbackLimitations`. Buildchain records secret reference names only, never\nsecret values.\n\nThe timestamp policy is shared with package site bundles. Public deployment\nmanifests should expose real workflow generation/publication times while\nseparately declaring why the deployed artifact remains reproducible. For\nweb-surface deployment manifests, `artifactHash` is the static site artifact\ndigest and does not include deployment timestamp fields; the manifest itself\nstill records those fields for human and agent audit.\n\n## Deploy Plans\n\nDeploy planning is the default behavior. It plans the adapter steps and writes\nmanifest JSON, but it does not touch AWS, DNS, CloudFront, or deployment\ncredentials.\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode deploy-plan \\\n --cwd fixtures/web-surface-shaped \\\n --source-sha aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \\\n --alias sha-aaaaaaaaaaaa\n```\n\nFor manifest-only output:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode manifest \\\n --cwd fixtures/web-surface-shaped \\\n --source-sha aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \\\n --alias pr-123 \\\n --output .buildchain/web-surface-manifest.json\n```\n\nThe CLI emits GitHub outputs when `GITHUB_OUTPUT` is present:\n\n- `web-surface-channel`\n- `web-surface-alias`\n- `web-surface-url`\n- `web-surface-urls-json`\n- `web-surface-artifact-hash`\n- `web-surface-manifest-json`\n\nThe reusable workflow resolves that same effective channel before running the\ncaller build or verify command. Both steps receive\n`BUILDCHAIN_WEB_SURFACE_CHANNEL` (`preview`, `staging`, or `production`) and\n`BUILDCHAIN_PREVIEW_ALIAS` for previews. Compatibility aliases\n`BUILDCHAIN_SURFACE_CHANNEL` and `BUILDCHAIN_WEB_SURFACE_ALIAS` are also\nprovided. Callers should consume these variables instead of reconstructing the\nrelease-intent state machine from raw GitHub events.\nAn unapproved manual canary resolves to `staging`; a trusted manual dispatch\nwith `production-approved=true` resolves to `production` through the same path.\n\n## Explicit Apply\n\n`deploy-apply` and `cleanup-apply` are explicit execution modes for the\n`aws-s3-cloudfront` static-site adapter. They still default to `--dry-run true`;\nlive AWS mutation requires `--dry-run false`.\n\nDeploy apply syncs the artifact, writes the deployment manifest, and invalidates\nCloudFront when a distribution id is configured:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode deploy-apply \\\n --cwd fixtures/web-surface-shaped \\\n --channel staging \\\n --source-sha aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \\\n --artifact-path dist \\\n --dry-run false \\\n --output .buildchain/web-surface-staging-apply.json\n```\n\n### Immutable publication paths\n\nWhen a surface artifact contains `manifest.json` with\n`archivePolicy.contract = \"kungfu-buildchain-publication-archive-policy\"`,\nBuildchain treats every declared `publications[].versions[].immutablePath` as\nan append-only publication boundary. This applies identically to preview,\nstaging, and production adapters.\n\nThe adapter derives the protected archive root from those declared version\npaths and applies four ordered safeguards:\n\n1. every local immutable file is checked against an existing S3 object;\n2. missing files are uploaded with `aws s3 sync --no-overwrite` and a SHA-256\n checksum;\n3. every immutable file is checked again after upload, closing the race between\n the first check and the no-overwrite transfer;\n4. mutable site content keeps normal `sync --delete` behavior, but every parent\n or owning surface sync excludes the protected archive root from deletion.\n\nAn existing object with a different SHA-256 digest fails apply before mutable\ncontent is changed. Older objects without a stored S3 SHA-256 checksum are read\nand byte-hashed for compatibility. Directory-index alias writes are skipped\nunder protected roots so they cannot overwrite immutable route objects; viewer\nrequest rewriting remains the directory-index authority.\n\nThe deploy plan and manifest record `immutablePublication`,\n`mutableDeleteExcludes`, and the parent-surface coverage. Apply output records\n`immutablePreservation` plus every pre-check, no-overwrite sync, post-check, and\nmutable sync operation. Health output adds an `__immutable__` check proving that\nthe owning and parent surface syncs carried their required delete exclusions.\nThe runner must provide an AWS CLI version whose `s3 sync` supports\n`--no-overwrite`.\n\nFor multi-surface sites, each surface host is treated as a root-relative view\nof that surface's artifact path prefix. For example, a `buildchain` surface with\n`path = \"/buildchain/\"` and preview URL\n`https://buildchain-pr-29.preview.libkungfu.dev` syncs the artifact subtree\n`dist/buildchain/` to the preview object prefix `pr-29/buildchain`. A viewer\nrequest for `https://buildchain-pr-29.preview.libkungfu.dev/docs/` therefore\nresolves against the artifact's `dist/buildchain/docs/index.html`, not\n`dist/docs/index.html` and not the hub surface root. The deployment manifest\nrecords this as `routing.contract =\n\"kungfu-buildchain-web-surface-path-prefix-rewrite\"` with\n`viewerPathPrefix = \"/\"`, `artifactPathPrefix = \"buildchain\"`, and\n`directoryIndexResolution = true`.\n\nWhen a surface uses an S3 object prefix, directory-index routing must be handled\nat the viewer-request layer. By default, `directory_index_rewrite =\n\"buildchain\"` makes Buildchain install or update one CloudFront Function per\ndistribution before uploading payloads. The function rewrites any request path\nending in `/` to the corresponding `index.html`, so\n`https://buildchain-pr-29.preview.libkungfu.dev/` resolves to\n`pr-29/buildchain/index.html` and\n`https://buildchain-pr-29.preview.libkungfu.dev/docs/` resolves to\n`pr-29/buildchain/docs/index.html`. This keeps multi-host preview roots\ncompatible with S3 REST origins, where copying alias objects such as\n`pr-29/buildchain` or `pr-29/buildchain/` is not a reliable substitute for an\nedge rewrite.\n\nIf the distribution already has a viewer-request function that owns preview\nalias routing and surface-prefix routing, set `directory_index_rewrite =\n\"external\"` on the deploy channel or surface override. In that mode Buildchain\ndoes not create, update, or attach a generic directory-index function. Instead,\nthe deployment manifest records `directoryIndexRewrite = \"external\"` and\n`directoryIndexStrategy = \"external-viewer-request-function\"`, then the normal\nhealth check still verifies every required root and nested surface URL. This is\nthe correct contract for shared preview distributions such as\n`site-libkungfu-dev`, where a generic function cannot replace the existing\nprefix router.\n\nBuildchain still writes directory-index alias objects during apply as\ncompatibility evidence, but root correctness comes from the viewer-request\nrewrite contract, not from extensionless S3 keys. If Buildchain-managed mode\nfinds a distribution with a different viewer-request function, apply fails\nclosed and records that conflict in the apply result instead of silently serving\n403s. If CloudFront rejects `UpdateDistribution` because its optimistic-lock\nETag became stale, Buildchain re-reads the distribution and retries with the\nnew ETag at most twice. A concurrent update that already attached the intended\nfunction is accepted as converged; a different viewer-request function or any\nnon-ETag AWS error still fails immediately. The reusable workflow uploads\n`buildchain-web-surface-*-diagnostics`\nartifacts containing the apply and health JSON so the failing AWS operation or\nHTTP check is visible from the consumer run.\n\nIt can also execute a previously saved deploy plan. In that mode Buildchain\nrecomputes the local artifact hash before running AWS commands and fails closed\nif the artifact no longer matches the saved plan. Before any adapter operation,\nit also checks channel-aware JSON manifests in the artifact: top-level\n`canonicalHost` and declared `pages[].host` facts must belong to the plan's\nsurface hosts. A production plan therefore rejects staging/preview host facts\nbefore AWS apply:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode deploy-apply \\\n --cwd fixtures/web-surface-shaped \\\n --plan .buildchain/web-surface-staging-plan.json \\\n --dry-run false \\\n --output .buildchain/web-surface-staging-apply.json\n```\n\nCleanup apply deletes preview content, deletes the preview manifest, and\ninvalidates CloudFront:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode cleanup-apply \\\n --cwd fixtures/web-surface-shaped \\\n --event pull-request-closed \\\n --pull-number 123 \\\n --source-sha aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \\\n --dry-run false \\\n --output .buildchain/web-surface-cleanup-apply.json\n```\n\nCleanup apply can also execute a saved cleanup plan:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode cleanup-apply \\\n --cwd fixtures/web-surface-shaped \\\n --plan .buildchain/web-surface-cleanup-plan.json \\\n --dry-run false \\\n --output .buildchain/web-surface-cleanup-apply.json\n```\n\nApply output records the channel, alias, source SHA, artifact hash, target\nbucket, object prefix, manifest key, all surface URLs, all surface bindings, CDN\ninvalidation paths, actor/run metadata, immutable preservation evidence, and\nevery adapter operation with\n`executed`, `exitCode`, `stdout`, and `stderr`. If an operation fails,\nBuildchain records the failed operation, stops subsequent adapter operations,\nand exits non-zero after writing the result JSON. Buildchain records secret\nreference names only; the runner must provide the AWS CLI and credentials\noutside Buildchain, typically through OIDC and the declared `secret_refs`.\n\n## Production Preflight And Health\n\nProduction promotion is not just `deploy-apply --channel production`. Before a\nlive production apply, the reusable workflow runs:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode production-preflight \\\n --cwd fixtures/web-surface-shaped \\\n --plan .buildchain/web-surface-production-plan.json \\\n --execute true \\\n --output .buildchain/web-surface-production-preflight.json\n```\n\nThe production preflight checks that:\n\n- `channels.production` is canonical and indexable;\n- every surface has concrete production bucket and CloudFront targets;\n- every production surface URL is HTTPS;\n- the production AWS role can inspect the declared bucket and distribution;\n- CloudFront aliases cover every surface host, including product hosts such as\n `kfd.libkungfu.dev`;\n- DNS resolves for every surface host.\n\nAfter preview, staging, and production apply, the workflow runs:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode health-check \\\n --cwd fixtures/web-surface-shaped \\\n --result .buildchain/web-surface-production-apply.json \\\n --output .buildchain/web-surface-production-health.json\n```\n\nWhen the apply result includes CloudFront invalidations from the\n`aws-s3-cloudfront` adapter, health check waits for those invalidations to reach\n`Completed` before fetching public smoke URLs. This avoids reporting stale\nCloudFront 403 responses as deployment failures immediately after a successful\nS3 sync and invalidation request.\n\nAfter the invalidation wait, HTTP smoke checks also retry transient 403, 404, and\n5xx responses before recording failure. This keeps the public health signal\nstrict while absorbing short CloudFront edge propagation windows that can remain\nvisible after the invalidation waiter returns. By default, Buildchain attempts\neach HTTP smoke URL 12 times with a 10 second interval. Consumers can override\nthat window with `BUILDCHAIN_WEB_SURFACE_HEALTH_HTTP_RETRY_ATTEMPTS` and\n`BUILDCHAIN_WEB_SURFACE_HEALTH_HTTP_RETRY_INTERVAL_MS` when they need a\nsite-specific health policy.\n\nThe health check fetches every surface root URL and any nested smoke URLs\nrecorded in each surface binding. Nested smoke URLs are derived from nested HTML\nartifact files under the surface path prefix, with directory index resolution\nsuch as `dist/buildchain/docs/index.html` becoming `/docs/` on the buildchain\npreview host. If a surface has no nested HTML route, Buildchain records only\nthe root smoke URL; absence of nested HTML is not a deployment failure. When a\nnested route is present, the check fails closed if a deploy reports success but\nthat child page returns 403 or another unexpected status. Surface root checks\nexpect the apply result to have installed the directory-index rewrite, so a\nmulti-host preview root such as `https://buildchain-pr-29.preview.libkungfu.dev/`\nmust resolve to the surface `index.html`, not the bare prefix directory.\nProduction additionally fails if a response is unreachable, returns an\nunexpected status, or still sends `x-robots-tag: noindex`. The health check also\nverifies that each surface binding recorded a deployment manifest pointer. The\nproduction release passport embeds the deploy plan, apply result, production\npreflight, and health check so a reviewer or agent can audit why the production\nsite changed and whether every declared host and every existing nested route was\nactually covered.\n\nPublic channels can opt into object-level health with\n`deploy.<channel>.health_strategy = \"s3-object\"` when the deployment contract is\nalready covered by S3 manifest/object writes and public edge convergence is not\nthe right CI gate. This is useful for preview distributions whose viewer-request\nrouting is owned by an external CloudFront Function. The channel remains public;\nonly the CI health evidence changes from HTTP fetches to S3 `head-object`\nchecks.\n\nChannels declared with `access_control = \"managed-network\"` use a different\nhealth strategy by default. Buildchain does not require a GitHub-hosted runner\nto fetch a URL that is intentionally reachable only from an approved network.\nInstead, after a live apply the health check uses the deploy role to run S3\n`head-object` checks for each surface manifest and the smoke target object, such\nas the surface `index.html` or a nested `docs/index.html`. The check records\n`healthStrategy = \"s3-object\"` and skips the public HTTP fetch. Dry-run and\nplan-only checks fall back to deployment evidence: each surface must have a\nmanifest key, bucket, object prefix, `sync-static-artifact`, and\n`write-deployment-manifest` evidence, recorded as\n`healthStrategy = \"deployment-evidence\"`. If the workflow is running on a runner\nthat is allowed to reach the managed network, set\n`BUILDCHAIN_WEB_SURFACE_HEALTH_ALLOWED_RUNNER=true` or pass\n`--allowed-managed-network-runner true` to keep the normal HTTP smoke checks.\nSet `BUILDCHAIN_WEB_SURFACE_HEALTH_S3_OBJECTS=false` or pass\n`--managed-network-s3-object-verification false` only when an external channel\npolicy owns managed-network object verification.\n\n## Cleanup Plans\n\nPreview cleanup is an auditable cleanup contract. It can run as a dry-run plan,\nan apply-mode plan, or the explicit `cleanup-apply` executor with preview-only\ncredentials:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode cleanup-plan \\\n --cwd fixtures/web-surface-shaped \\\n --event pull-request-closed \\\n --pull-number 123 \\\n --aliases pr-123,sha-abcdef123456\n```\n\nThe plan and apply result keep mutable PR aliases and immutable SHA aliases\ndistinct so a caller can expire them with different retention windows. Closed-PR\ncleanup can derive `pr-N` from `--pull-number`, records the event, source SHA,\nactor, run id, preview bucket/prefix, manifest key, and adapter steps, and is an\nauditable no-op when no aliases are requested.\n\n## Reusable Workflow Shape\n\nBuildchain ships `.github/workflows/.web-surface.yml` for repositories that want\nthe standard PR review and promotion flow without copying bespoke glue:\n\n```yaml\njobs:\n web-surface:\n uses: kungfu-systems/buildchain/.github/workflows/.web-surface.yml@v2\n with:\n build-command: npm run build\n verify-command: npm run check\n artifact-path: dist\n```\n\nThe reusable workflow maps GitHub events to Buildchain web-surface semantics:\n\n| Event | Buildchain behavior |\n| --- | --- |\n| `pull_request` opened / synchronized / reopened | validate, build, verify, and plan `preview` for `pr-N` |\n| `pull_request` closed | plan apply-mode cleanup for the `pr-N` preview alias and manifest |\n| `push` to `main` | validate, build, verify, plan and apply `staging` from the merged `main` SHA, then optionally open a production release PR |\n| `push` to `main` from a matching release PR merge | validate the associated release PR, plan `production`, and enter the configured GitHub Environment gate |\n| `workflow_dispatch` with `production-approved = true` | plan `production` and enter the configured GitHub Environment gate |\n\nThe optional `buildchain-ref` input is empty by default. Empty keeps the\nweb-surface run on the stable Buildchain runtime selected by the reusable\nworkflow ref, normally `@v2`. A trusted maintainer can expose a\n`workflow_dispatch` input and pass it through for one-off train validation.\nSee [`runtime-train-validation.md`](runtime-train-validation.md) for the shared\ntrain protocol and notification template:\n\n```yaml\non:\n workflow_dispatch:\n inputs:\n buildchain-ref:\n description: \"Temporary Buildchain runtime ref for trusted manual validation\"\n required: false\n default: \"\"\n\njobs:\n web-surface:\n uses: kungfu-systems/buildchain/.github/workflows/.web-surface.yml@v2\n with:\n buildchain-ref: ${{ inputs.buildchain-ref || '' }}\n build-command: pnpm run build\n verify-command: pnpm run check\n artifact-path: dist\n```\n\nOnly trusted `workflow_dispatch` runs by repository actors with write,\nmaintain, or admin permission may use a non-empty runtime override. Train refs\nsuch as `train/v2/v2.3/site-source-of-truth` are temporary validation refs, not\nstable production dependencies or pending merge targets. They may remain for a\nretention window after release as a fast-use and rollback channel, with old\ntrains handled by periodic Buildchain cleanup. The web-surface deployment\nmanifest records the resolved runtime SHA as `runtimeId` and the stable\nrollback ref as `rollbackPointer`.\n\nThe workflow deliberately plans and emits manifests by default. Live mutation is\nopt-in per channel:\n\n```yaml\npermissions:\n contents: read\n id-token: write\n pull-requests: write\n\njobs:\n web-surface:\n uses: kungfu-systems/buildchain/.github/workflows/.web-surface.yml@v2\n with:\n build-command: pnpm run build\n verify-command: pnpm run check\n artifact-path: dist\n preview-apply: true\n preview-cleanup-apply: true\n preview-aws-role-arn: arn:aws:iam::123456789012:role/site-preview-github-actions\n staging-apply: true\n staging-aws-role-arn: arn:aws:iam::123456789012:role/site-staging-github-actions\n production-apply: false\n production-release-on-main: false\n production-aws-role-arn: arn:aws:iam::123456789012:role/site-production-github-actions\n production-environment: production\n release-feedback-actor-privacy: public\n```\n\nWhen enabled, Buildchain owns the full release apply state machine:\n\n- PR preview deploys run `deploy-apply --dry-run false` with the preview role\n and update a single idempotent PR comment.\n- Closed PR cleanup runs `cleanup-apply --dry-run false` with the preview role\n only.\n- Pushes to `main` run staging `deploy-apply --dry-run false` with the staging\n role, then write a staging release feedback passport artifact and comment the\n associated merged PR with the staging URL, source SHA, artifact identity, run\n URL, and failure context when apply did not complete.\n- When `production-release-on-main=true`, successful staging applies open or\n update a Buildchain-owned release PR from\n `release/<channel>-<short-sha>` to `main`, unless the current push already\n came from a matching release PR merge. The release PR contains one empty\n release-intent commit, carries `production-release-label`, and includes the\n staging URLs, source SHA, artifact hash, and staging release-passport artifact\n link in the PR body.\n- Production release PR handoff is permission-aware. Staging apply and staging\n health remain successful even when the repository or organization has\n GitHub Actions workflow permissions set to read-only. In that case Buildchain\n records `release-pr-status=permission-denied`, uploads the release PR handoff\n summary/body plus staging release passport artifacts, and writes an exact\n manual `gh pr create` command to the step summary. Set\n `fail-on-release-pr-error=true` only when PR creation failure should fail the\n whole workflow.\n- Release pull requests that match the configured production gate get a\n Buildchain review comment with the staging URL and production target, so the\n operator can verify staging from the PR page and use merge as the approval\n action. Consumers do not need to hand-write `gh pr create` or production\n release-intent glue.\n- `production-apply=true` enables the production capability; it does not request\n production for every event. Ordinary `main` pushes remain staging-only and\n can create or update a release PR. Production runs only when the capability\n is enabled and either:\n - a `workflow_dispatch` passes `production-approved=true` and the triggering\n actor currently has `write`, `maintain`, or `admin` permission; or\n - `production-release-on-main=true` and the `main` push commit is associated\n with exactly one same-repository, merged release pull request matching\n `production-release-label` and `production-release-head-prefix`.\n The production job is then gated by the configured GitHub Environment.\n- Before production artifact download, Buildchain assembles a managed sealed\n publication capability from the exact source/runtime SHAs, production plan\n and artifact hash, a qualifying pre-publication controller receipt, the\n trusted manual or reviewed-release-PR decision, production Environment and\n AWS role target, an ephemeral-runner receipt, and a fresh nonce. Production\n revalidates that capability against the downloaded plan before it downloads\n product bytes. The later AWS OIDC exchange remains the provider's final\n transaction-time authorization decision and fails closed before deploy apply.\n- The `publication-*-json` inputs are an advanced external-evidence\n compatibility path, not a prerequisite for the standard release-PR or trusted\n manual mechanisms. External evidence must now include\n `publication-gate-aggregate-json`; supplying only a partial set still fails\n closed.\n- Production apply writes a production release feedback passport artifact and\n comments the release PR with the production URL, source SHA, artifact\n identity, run URL, rollback pointer, and failure context when apply did not\n complete.\n\nThe feedback passport records the release responsibility chain:\n\n- human decision actor;\n- trigger actor;\n- runner/execution actor;\n- OIDC/deploy identity reference;\n- decision type and time;\n- source event, PR number, merge commit, and required gate label/head-prefix.\n\n`release-feedback-actor-privacy` controls actor values in the passport and\ncomments. `public` records GitHub actor names, `redacted` records only the actor\nrole, and `private-ref` records a stable private reference hash without exposing\nthe actor name.\n\nFor release-PR publishing, callers opt in explicitly:\n\n```yaml\njobs:\n web-surface:\n uses: kungfu-systems/buildchain/.github/workflows/.web-surface.yml@v2\n with:\n build-command: npm run build\n verify-command: npm run check\n artifact-path: dist\n production-apply: true\n production-release-on-main: true\n production-release-label: buildchain-release\n production-release-head-prefix: release/\n production-release-branch-channel: production\n production-release-pr-mode: auto\n production-aws-role-arn: arn:aws:iam::123456789012:role/site-production-github-actions\n production-environment: production\n```\n\nKeep `production-apply` enabled in the caller when the repository supports\nproduction. Buildchain derives whether the current event may use that\ncapability: an ordinary `main` push plans and applies staging, a matching\nreviewed release PR merge authorizes production, and an approved trusted manual\ndispatch authorizes production. Inputs from an untrusted event cannot turn that\ndecision on.\n\n`production-release-pr-mode` controls the post-staging handoff:\n\n| Mode | Behavior |\n| --- | --- |\n| `auto` | Generate release PR facts, create/update the empty release-intent branch and PR, and label it when token permissions allow. This is the default. |\n| `summary-only` | Generate and upload release PR facts, body, passport evidence, and manual command, but do not call the GitHub PR API. |\n| `disabled` | Record a disabled handoff and skip release PR API calls. |\n\nAutomatic release PR creation normally uses the workflow `github.token`.\nConsumers that cannot enable \"GitHub Actions can create and approve pull\nrequests\" globally should prefer the first-class GitHub App path. Pass the App\nclient id as an input and the private key as a reusable workflow secret; Buildchain\ncreates an installation token inside the release PR job and uses it only for the\nrelease-intent branch, PR, and label operations:\n\n```yaml\nwith:\n production-release-app-client-id: ${{ vars.KUNGFU_RELEASE_APP_CLIENT_ID }}\nsecrets:\n production-release-app-private-key: ${{ secrets.KUNGFU_RELEASE_APP_PRIVATE_KEY }}\n```\n\nWhen either side of the App configuration is missing, Buildchain does not hide\nthat behind the fallback `github.token`. The handoff JSON and job summary report\n`status: \"app-token-unavailable\"` with an `appTokenStatus` such as\n`missing-client-id`, `missing-private-key`, or `create-failed`, and still include\nthe manual PR creation command. If the repository intentionally uses another\nnarrow token, pass it through `production-release-pr-token`.\n\n`production-release-app-id` remains accepted as a deprecated alias for the input\nname, but the value should be the GitHub App client id. GitHub App numeric App\nIDs and client IDs are distinct, and Buildchain passes the value to\n`actions/create-github-app-token` through its non-deprecated `client-id` input so\nnew runs do not emit the deprecated `app-id` warning.\n\nIf a repository already generates its own narrow token or PAT, it can still pass\nthat through `production-release-pr-token`:\n\n```yaml\nwith:\n production-release-pr-token: ${{ secrets.BUILDCHAIN_RELEASE_PR_TOKEN }}\n```\n\nToken priority is: generated GitHub App installation token,\n`production-release-pr-token`, then `github.token`.\n\nThe merge button becomes the production approval only for a PR that carries the\nrelease label and comes from the configured source-branch prefix. Ordinary pull\nrequests merged into `main` deploy staging and open a release-intent PR; merging\nthat release PR triggers production. A release PR merge push does not open\nanother release PR.\n\nApply-only inputs are validated before the caller build or verification command\nruns. If the current event would run preview, staging, or production apply,\nmissing role inputs, a production apply without `production-approved=true` on\nmanual dispatch, or a manual actor without repository write authority fail\nimmediately instead of spending the build and plan jobs first.\n\nCallers must grant `id-token: write` for OIDC role assumption. Preview comments\nneed `pull-requests: write`. Automatic release PR creation also needs\n`contents: write`, `pull-requests: write`, and `issues: write` so Buildchain can\ncreate the release branch, write the empty release-intent commit, open or update\nthe PR, and apply the release label. If these permissions are unavailable,\nBuildchain degrades the release handoff instead of marking a successful staging\ndeployment as failed, unless `fail-on-release-pr-error=true`. The AWS roles remain caller-owned and\nshould be scoped by channel: preview can mutate only preview resources, staging\ncan mutate only staging resources, and production can mutate only production\nresources.\n\nApply mode fails closed when the deploy config still contains placeholder AWS\ntargets such as `pending-preview-distribution`. Planning can use placeholders\nfor dry-run-only design work, but live apply requires concrete bucket and\nCloudFront distribution identifiers.\n\n## Site Repository Shape\n\nA site repository can start with:\n\n```toml\nschema = 1\n\n[project]\ntype = \"web-surface\"\nname = \"site-kungfu-tech\"\nsite = \"kungfu-tech\"\n\n[lifecycle.build]\ncommand = \"pnpm run build\"\n\n[lifecycle.verify]\ncommand = \"pnpm run check\"\n```\n\nThen add the channel, deploy, retention, and security declarations shown above.\nThe project may use pnpm, npm, yarn, Vite, Astro, Next static export, Sphinx,\nMkDocs, CMake-generated docs, or another lifecycle command source. Buildchain\nonly needs a deterministic artifact path and the manifest facts.\n\n## Boundaries\n\nBuildchain only performs live AWS mutations in explicit apply modes with\n`--dry-run false`. Production deploys must still be gated by a human-controlled\nworkflow, release, or GitHub Environment. DNS changes, staging auth\nimplementation, CloudFront distribution creation, and credential provisioning\nremain explicitly authorized infrastructure operations outside the web-surface\nartifact apply contract."
2195
+ "markdown": "# Web-Surface Deployment Contract\n\nBuildchain supports `project.type = \"web-surface\"` for repositories that publish\nsites, docs, product pages, operator consoles, or browser apps. These projects\nneed auditable deployment semantics, but they are not package release lines and\nshould not be forced into `dev/alpha/release` version-state automation.\n\nThe release object for a web surface is:\n\n```text\nsource commit + build artifact + deploy target + channel + deployment manifest\n```\n\nThis keeps the evidence chain clear:\n\n- the source SHA explains what code was built;\n- the artifact hash explains exactly what was deployed;\n- the channel explains who can see it and whether it is promotable;\n- the deploy target and adapter explain where it would be published;\n- the deployment manifest records retention, rollback, security, and secret\n reference metadata.\n\n## Configuration\n\n`.buildchain/buildchain.toml` is the source of truth. Web-surface projects must declare\npreview, staging, and production channels plus a deploy adapter for each.\n\n```toml\nschema = 1\n\n[project]\ntype = \"web-surface\"\nname = \"site-kungfu-tech\"\nsite = \"kungfu-tech\"\n\n[channels.preview]\nurl_pattern = \"https://{alias}.preview.kungfu.tech\"\nvisibility = \"ephemeral\"\nrequires_auth = false\nnoindex = true\n\n[channels.staging]\nurl = \"https://staging.kungfu.tech\"\nvisibility = \"protected\"\naccess_control = \"managed-network\"\nedge_auth = \"none\"\nnoindex = true\npromotable = true\n\n[channels.production]\nurl = \"https://kungfu.tech\"\nvisibility = \"public\"\ncanonical = true\nnoindex = false\n\n[deploy.preview]\nadapter = \"aws-s3-cloudfront\"\nbucket = \"kungfu-tech-preview\"\ncloudfront_distribution = \"E-PREVIEW\"\nartifact_path = \"dist\"\nsecret_refs = [\"AWS_ROLE_ARN\"]\n# Optional. Defaults to \"buildchain\".\n# Use \"external\" when an existing viewer-request CloudFront Function already\n# owns preview alias, surface-prefix, and directory-index routing.\ndirectory_index_rewrite = \"buildchain\"\n# Optional. Defaults to HTTP for public channels and S3 object evidence for\n# managed-network channels. Use \"s3-object\" when CI should verify uploaded\n# objects and manifests instead of waiting for public edge convergence.\nhealth_strategy = \"http\"\n```\n\n### Multi-Surface Host Mapping\n\nSome site repositories publish more than one first-class web surface from the\nsame artifact. For example, `site-libkungfu-dev` has a hub plus separate\nhostnames for core, Buildchain, and Kung Fu Decisions. These are not just\nnavigation paths; staging, production preflight, and post-deploy health checks\nmust verify host-level behavior for each surface.\n\nDeclare named surfaces with per-channel URLs:\n\n```toml\n[surfaces.hub]\npath = \"/\"\nproduction_url = \"https://libkungfu.dev\"\nstaging_url = \"https://staging.libkungfu.dev\"\npreview_url_pattern = \"https://{alias}.preview.libkungfu.dev\"\n\n[surfaces.core]\npath = \"/core/\"\nproduction_url = \"https://core.libkungfu.dev\"\nstaging_url = \"https://core.staging.libkungfu.dev\"\npreview_url_pattern = \"https://core-{alias}.preview.libkungfu.dev\"\n\n[surfaces.buildchain]\npath = \"/buildchain/\"\nproduction_url = \"https://buildchain.libkungfu.dev\"\nstaging_url = \"https://buildchain.staging.libkungfu.dev\"\npreview_url_pattern = \"https://buildchain-{alias}.preview.libkungfu.dev\"\n\n[surfaces.kfd]\npath = \"/kfd/\"\nproduction_url = \"https://kfd.libkungfu.dev\"\nstaging_url = \"https://kfd.staging.libkungfu.dev\"\npreview_url_pattern = \"https://kfd-{alias}.preview.libkungfu.dev\"\n```\n\nBuildchain resolves every `(channel, surface)` pair. A preview alias such as\n`pr-12` becomes:\n\n```text\nhub: https://pr-12.preview.libkungfu.dev\ncore: https://core-pr-12.preview.libkungfu.dev\nbuildchain: https://buildchain-pr-12.preview.libkungfu.dev\nkfd: https://kfd-pr-12.preview.libkungfu.dev\n```\n\nWhen `surfaces` is omitted, Buildchain preserves the legacy single-surface\ncontract by creating an implicit `default` surface from the channel URL. When a\nsurface is intentionally path-only, declare it explicitly:\n\n```toml\n[surfaces.docs]\npath = \"/docs/\"\npath_only = true\n```\n\n`path_only = true` is an exception, not the default. Without it, every named\nsurface must declare `preview_url_pattern`, `staging_url`, and\n`production_url`. This makes staging/production mismatches fail during\nvalidation instead of becoming invisible deploy drift.\n\nAdapter strategy remains explicit. The default `aws-s3-cloudfront` plan uses the\nchannel deploy target for every surface, and each binding records its own\nbucket, distribution id, object prefix, manifest key, source path, and URL. A\nchannel can override target details per surface:\n\n```toml\n[deploy.staging.surfaces.core]\nbucket = \"libkungfu-dev-core-staging\"\ncloudfront_distribution = \"E-CORE-STAGING\"\norigin_path = \"/core\"\n```\n\nBuildchain validates these hard constraints:\n\n- `channels.preview.url_pattern` is required and must contain the alias shape\n used by preview deployments.\n- `channels.staging.access_control` must protect staging. Supported modes are\n `managed-network`, `edge-basic-auth`, `oidc`, and `app-auth`.\n- `channels.staging.edge_auth` records whether the edge layer owns auth. Use\n `edge_auth = \"none\"` when staging is protected by managed network controls\n such as WAF/IP allowlists or VPN access.\n- `channels.staging.noindex = true` is required.\n- `channels.production.url` is required.\n- deploy adapters must be declared per channel.\n- named surfaces must declare first-class URLs for every channel unless\n `path_only = true` is explicitly set.\n- secret material must be declared as reference names, such as\n `secret_refs = [\"AWS_ROLE_ARN\"]`; inline secret-like deploy keys are rejected.\n\n### Floating Runtime Contract Lock\n\nWeb-surface repositories can consume the stable Buildchain workflow shell with a\nfloating ref, such as:\n\n```yaml\njobs:\n web:\n uses: kungfu-systems/buildchain/.github/workflows/.web-surface.yml@v2\n with:\n buildchain-contract-lock-path: .buildchain/contract-lock.json\n buildchain-contract-compatibility-policy: major-compatible\n buildchain-contract-drift-issue-mode: compatible-and-breaking\n build-command: pnpm build\n artifact-path: dist\n```\n\nThe caller repository commits `.buildchain/contract-lock.json` after reviewing an\naccepted Buildchain runtime SHA and contract digest. The reusable workflow then\nresolves the floating runtime to an immutable SHA, checks the lock before the\ncaller build command, and applies these rules:\n\n- unchanged lock: continue without feedback;\n- compatible drift: continue, write the drift summary, and open or update a\n caller-repository issue when permissions allow;\n- breaking drift: fail closed before rendering, deployment planning, deploy\n apply, or release publication.\n\nThe caller no longer needs to run `scripts/buildchain-contract-lock.mjs` inside\nits own build command. That check belongs to Buildchain because the actual\ncontract world is stored in the Buildchain runtime ref being used.\n\nSupported adapter names are:\n\n| Adapter | Initial use |\n| --- | --- |\n| `aws-s3-cloudfront` | Static site artifact sync plus CDN invalidation plan |\n| `aws-elastic-beanstalk` | Future dynamic app environment adapter |\n| `aws-ecs-service` | Future dynamic service adapter |\n\nThe channel ontology is independent of the adapter. A future dynamic staging\nenvironment still remains `channel = \"staging\"` with protected/noindex/security\nrequirements.\n\n## Preview Aliases\n\nPreview uses subdomains, not path prefixes:\n\n```text\nhttps://pr-123.preview.kungfu.tech\nhttps://sha-abcdef123456.preview.kungfu.tech\n```\n\nAlias semantics are explicit:\n\n| Alias | Meaning | Mutable | Retention |\n| --- | --- | --- | --- |\n| `pr-123` | Current preview for a pull request | yes | short-lived |\n| `sha-abcdef123456` | Immutable preview for one source SHA | no | longer-lived |\n\nThis allows PR comments to stay stable while preserving immutable evidence for a\nspecific source commit.\n\n## Deployment Manifest\n\nBuildchain emits a manifest with the deployment facts that matter for audit and\nrollback:\n\n```json\n{\n \"schemaVersion\": 1,\n \"contract\": \"kungfu-buildchain-web-surface-deployment\",\n \"site\": \"libkungfu-dev\",\n \"channel\": \"preview\",\n \"alias\": \"sha-abcdef123456\",\n \"url\": \"https://sha-abcdef123456.preview.libkungfu.dev\",\n \"generatedAt\": \"2026-07-01T00:00:00.000Z\",\n \"publishedAt\": \"2026-07-01T00:00:00.000Z\",\n \"reproducible\": true,\n \"timestampPolicy\": \"ci-injected\",\n \"deterministicInputs\": [\n \"web-surface artifact content\",\n \"buildchain.toml web-surface channels/deploy/surfaces\",\n \"sourceSha\",\n \"artifactHash\",\n \"deployment channel\",\n \"deployment alias\"\n ],\n \"sourceRevision\": \"...\",\n \"timestampPolicyDetails\": {\n \"contract\": \"kungfu-buildchain-surface-timestamp-policy\",\n \"timestampFields\": [\"generatedAt\", \"publishedAt\", \"deployedAt\"],\n \"timestampFieldsParticipateInArtifactDigest\": false,\n \"artifactDigestScope\": \"web-surface artifactHash excludes deployment manifest timestamps\"\n },\n \"sourceSha\": \"...\",\n \"artifactHash\": \"...\",\n \"deployTarget\": \"libkungfu-dev-preview\",\n \"adapter\": \"aws-s3-cloudfront\",\n \"deployedAt\": \"2026-07-01T00:00:00.000Z\",\n \"retentionClass\": \"preview-sha-immutable\",\n \"expiresAt\": \"2026-09-29T00:00:00.000Z\",\n \"accessControl\": \"none\",\n \"edgeAuth\": \"none\",\n \"noindex\": true,\n \"secretRefs\": [\"AWS_ROLE_ARN\"],\n \"surfaceBindings\": [\n {\n \"surface\": \"hub\",\n \"channel\": \"preview\",\n \"alias\": \"sha-abcdef123456\",\n \"url\": \"https://sha-abcdef123456.preview.libkungfu.dev\",\n \"sourcePath\": \"/\",\n \"artifactPathPrefix\": \"\",\n \"viewerPathPrefix\": \"/\",\n \"directoryIndex\": \"index.html\",\n \"directoryIndexResolution\": true,\n \"canonicalUrl\": \"https://libkungfu.dev\",\n \"bucket\": \"libkungfu-dev-preview\",\n \"distributionId\": \"E-PREVIEW\",\n \"originPath\": \"\",\n \"objectPrefix\": \"sha-abcdef123456\",\n \"manifestKey\": \".buildchain/deployments/sha-abcdef123456/hub.json\",\n \"routing\": {\n \"contract\": \"kungfu-buildchain-web-surface-path-prefix-rewrite\",\n \"viewerPathPrefix\": \"/\",\n \"artifactPathPrefix\": \"\",\n \"objectPrefix\": \"sha-abcdef123456\",\n \"directoryIndex\": \"index.html\",\n \"directoryIndexResolution\": true\n },\n \"smokeUrls\": [\n {\n \"kind\": \"root\",\n \"requestPath\": \"/\",\n \"url\": \"https://sha-abcdef123456.preview.libkungfu.dev/\",\n \"required\": true\n }\n ],\n \"noindex\": true,\n \"accessControl\": \"none\"\n }\n ]\n}\n```\n\nDynamic adapters can also fill `runtimeId`, `configFingerprint`,\n`healthCheck`, `migrationState`, `rollbackPointer`, and\n`rollbackLimitations`. Buildchain records secret reference names only, never\nsecret values.\n\nThe timestamp policy is shared with package site bundles. Public deployment\nmanifests should expose real workflow generation/publication times while\nseparately declaring why the deployed artifact remains reproducible. For\nweb-surface deployment manifests, `artifactHash` is the static site artifact\ndigest and does not include deployment timestamp fields; the manifest itself\nstill records those fields for human and agent audit.\n\n## Deploy Plans\n\nDeploy planning is the default behavior. It plans the adapter steps and writes\nmanifest JSON, but it does not touch AWS, DNS, CloudFront, or deployment\ncredentials.\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode deploy-plan \\\n --cwd fixtures/web-surface-shaped \\\n --source-sha aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \\\n --alias sha-aaaaaaaaaaaa\n```\n\nFor manifest-only output:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode manifest \\\n --cwd fixtures/web-surface-shaped \\\n --source-sha aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \\\n --alias pr-123 \\\n --output .buildchain/web-surface-manifest.json\n```\n\nThe CLI emits GitHub outputs when `GITHUB_OUTPUT` is present:\n\n- `web-surface-channel`\n- `web-surface-alias`\n- `web-surface-url`\n- `web-surface-urls-json`\n- `web-surface-artifact-hash`\n- `web-surface-manifest-json`\n\nThe reusable workflow resolves that same effective channel before running the\ncaller build or verify command. Both steps receive\n`BUILDCHAIN_WEB_SURFACE_CHANNEL` (`preview`, `staging`, or `production`) and\n`BUILDCHAIN_PREVIEW_ALIAS` for previews. Compatibility aliases\n`BUILDCHAIN_SURFACE_CHANNEL` and `BUILDCHAIN_WEB_SURFACE_ALIAS` are also\nprovided. Callers should consume these variables instead of reconstructing the\nrelease-intent state machine from raw GitHub events.\nAn unapproved manual canary resolves to `staging`; a trusted manual dispatch\nwith `production-approved=true` resolves to `production` through the same path.\n\n## Explicit Apply\n\n`deploy-apply` and `cleanup-apply` are explicit execution modes for the\n`aws-s3-cloudfront` static-site adapter. They still default to `--dry-run true`;\nlive AWS mutation requires `--dry-run false`.\n\nDeploy apply syncs the artifact, writes the deployment manifest, and invalidates\nCloudFront when a distribution id is configured:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode deploy-apply \\\n --cwd fixtures/web-surface-shaped \\\n --channel staging \\\n --source-sha aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \\\n --artifact-path dist \\\n --dry-run false \\\n --output .buildchain/web-surface-staging-apply.json\n```\n\n### Explicit cache classes\n\nThe S3/CloudFront adapter can declare cache metadata per deploy channel or\nsurface override:\n\n```toml\n[deploy.production]\nadapter = \"aws-s3-cloudfront\"\ncache_control_default = \"public,max-age=3600\"\ncache_control_mutable = \"public,max-age=300,must-revalidate\"\ncache_control_immutable = \"public,max-age=31536000,immutable\"\n```\n\n`cache_control_default` applies to the ordinary artifact sync.\n`cache_control_mutable` is then applied to HTML, JSON, XML, generated directory\nindex aliases, and the deployment manifest. `cache_control_immutable` applies\nto append-only publication roots discovered through the archive policy below.\nMutable metadata updates exclude those append-only roots, so HTML or JSON inside\nan immutable version archive keeps the immutable class.\nThe deploy plan, surface binding, apply operations, and deployment manifest all\nrecord the effective values. Existing consumers that omit these fields retain\ntheir prior upload behavior.\n\nCache metadata complements, rather than replaces, invalidation. Every deploy\nstill records and creates the exact surface wildcard and deployment-manifest\ninvalidation paths.\n\n### Immutable publication paths\n\nWhen a surface artifact contains `manifest.json` with\n`archivePolicy.contract = \"kungfu-buildchain-publication-archive-policy\"`,\nBuildchain treats every declared `publications[].versions[].immutablePath` as\nan append-only publication boundary. This applies identically to preview,\nstaging, and production adapters.\n\nThe adapter derives the protected archive root from those declared version\npaths and applies four ordered safeguards:\n\n1. every local immutable file is checked against an existing S3 object;\n2. missing files are uploaded with `aws s3 sync --no-overwrite` and a SHA-256\n checksum;\n3. every immutable file is checked again after upload, closing the race between\n the first check and the no-overwrite transfer;\n4. mutable site content keeps normal `sync --delete` behavior, but every parent\n or owning surface sync excludes the protected archive root from deletion.\n\nAn existing object with a different SHA-256 digest fails apply before mutable\ncontent is changed. Older objects without a stored S3 SHA-256 checksum are read\nand byte-hashed for compatibility. Directory-index alias writes are skipped\nunder protected roots so they cannot overwrite immutable route objects; viewer\nrequest rewriting remains the directory-index authority.\n\nThe deploy plan and manifest record `immutablePublication`,\n`mutableDeleteExcludes`, and the parent-surface coverage. Apply output records\n`immutablePreservation` plus every pre-check, no-overwrite sync, post-check, and\nmutable sync operation. Health output adds an `__immutable__` check proving that\nthe owning and parent surface syncs carried their required delete exclusions.\nThe runner must provide an AWS CLI version whose `s3 sync` supports\n`--no-overwrite`.\n\nFor multi-surface sites, each surface host is treated as a root-relative view\nof that surface's artifact path prefix. For example, a `buildchain` surface with\n`path = \"/buildchain/\"` and preview URL\n`https://buildchain-pr-29.preview.libkungfu.dev` syncs the artifact subtree\n`dist/buildchain/` to the preview object prefix `pr-29/buildchain`. A viewer\nrequest for `https://buildchain-pr-29.preview.libkungfu.dev/docs/` therefore\nresolves against the artifact's `dist/buildchain/docs/index.html`, not\n`dist/docs/index.html` and not the hub surface root. The deployment manifest\nrecords this as `routing.contract =\n\"kungfu-buildchain-web-surface-path-prefix-rewrite\"` with\n`viewerPathPrefix = \"/\"`, `artifactPathPrefix = \"buildchain\"`, and\n`directoryIndexResolution = true`.\n\nWhen a surface uses an S3 object prefix, directory-index routing must be handled\nat the viewer-request layer. By default, `directory_index_rewrite =\n\"buildchain\"` makes Buildchain install or update one CloudFront Function per\ndistribution before uploading payloads. The function rewrites any request path\nending in `/` to the corresponding `index.html`, so\n`https://buildchain-pr-29.preview.libkungfu.dev/` resolves to\n`pr-29/buildchain/index.html` and\n`https://buildchain-pr-29.preview.libkungfu.dev/docs/` resolves to\n`pr-29/buildchain/docs/index.html`. This keeps multi-host preview roots\ncompatible with S3 REST origins, where copying alias objects such as\n`pr-29/buildchain` or `pr-29/buildchain/` is not a reliable substitute for an\nedge rewrite.\n\nIf the distribution already has a viewer-request function that owns preview\nalias routing and surface-prefix routing, set `directory_index_rewrite =\n\"external\"` on the deploy channel or surface override. In that mode Buildchain\ndoes not create, update, or attach a generic directory-index function. Instead,\nthe deployment manifest records `directoryIndexRewrite = \"external\"` and\n`directoryIndexStrategy = \"external-viewer-request-function\"`, then the normal\nhealth check still verifies every required root and nested surface URL. This is\nthe correct contract for shared preview distributions such as\n`site-libkungfu-dev`, where a generic function cannot replace the existing\nprefix router.\n\nBuildchain still writes directory-index alias objects during apply as\ncompatibility evidence, but root correctness comes from the viewer-request\nrewrite contract, not from extensionless S3 keys. If Buildchain-managed mode\nfinds a distribution with a different viewer-request function, apply fails\nclosed and records that conflict in the apply result instead of silently serving\n403s. If CloudFront rejects `UpdateDistribution` because its optimistic-lock\nETag became stale, Buildchain re-reads the distribution and retries with the\nnew ETag at most twice. A concurrent update that already attached the intended\nfunction is accepted as converged; a different viewer-request function or any\nnon-ETag AWS error still fails immediately. The reusable workflow uploads\n`buildchain-web-surface-*-diagnostics`\nartifacts containing the apply and health JSON so the failing AWS operation or\nHTTP check is visible from the consumer run.\n\nIt can also execute a previously saved deploy plan. In that mode Buildchain\nrecomputes the local artifact hash before running AWS commands and fails closed\nif the artifact no longer matches the saved plan. Before any adapter operation,\nit also checks channel-aware JSON manifests in the artifact: top-level\n`canonicalHost` and declared `pages[].host` facts must belong to the plan's\nsurface hosts. A production plan therefore rejects staging/preview host facts\nbefore AWS apply:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode deploy-apply \\\n --cwd fixtures/web-surface-shaped \\\n --plan .buildchain/web-surface-staging-plan.json \\\n --dry-run false \\\n --output .buildchain/web-surface-staging-apply.json\n```\n\nCleanup apply deletes preview content, deletes the preview manifest, and\ninvalidates CloudFront:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode cleanup-apply \\\n --cwd fixtures/web-surface-shaped \\\n --event pull-request-closed \\\n --pull-number 123 \\\n --source-sha aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \\\n --dry-run false \\\n --output .buildchain/web-surface-cleanup-apply.json\n```\n\nCleanup apply can also execute a saved cleanup plan:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode cleanup-apply \\\n --cwd fixtures/web-surface-shaped \\\n --plan .buildchain/web-surface-cleanup-plan.json \\\n --dry-run false \\\n --output .buildchain/web-surface-cleanup-apply.json\n```\n\nApply output records the channel, alias, source SHA, artifact hash, target\nbucket, object prefix, manifest key, all surface URLs, all surface bindings, CDN\ninvalidation paths, actor/run metadata, immutable preservation evidence, and\nevery adapter operation with\n`executed`, `exitCode`, `stdout`, and `stderr`. If an operation fails,\nBuildchain records the failed operation, stops subsequent adapter operations,\nand exits non-zero after writing the result JSON. Buildchain records secret\nreference names only; the runner must provide the AWS CLI and credentials\noutside Buildchain, typically through OIDC and the declared `secret_refs`.\n\n## Production Preflight And Health\n\nProduction promotion is not just `deploy-apply --channel production`. Before a\nlive production apply, the reusable workflow runs:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode production-preflight \\\n --cwd fixtures/web-surface-shaped \\\n --plan .buildchain/web-surface-production-plan.json \\\n --execute true \\\n --output .buildchain/web-surface-production-preflight.json\n```\n\nThe production preflight checks that:\n\n- `channels.production` is canonical and indexable;\n- every surface has concrete production bucket and CloudFront targets;\n- every production surface URL is HTTPS;\n- the production AWS role can inspect the declared bucket and distribution;\n- CloudFront aliases cover every surface host, including product hosts such as\n `kfd.libkungfu.dev`;\n- DNS resolves for every surface host.\n\nAfter preview, staging, and production apply, the workflow runs:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode health-check \\\n --cwd fixtures/web-surface-shaped \\\n --result .buildchain/web-surface-production-apply.json \\\n --output .buildchain/web-surface-production-health.json\n```\n\nWhen the apply result includes CloudFront invalidations from the\n`aws-s3-cloudfront` adapter, health check waits for those invalidations to reach\n`Completed` before fetching public smoke URLs. This avoids reporting stale\nCloudFront 403 responses as deployment failures immediately after a successful\nS3 sync and invalidation request.\n\nAfter the invalidation wait, HTTP smoke checks also retry transient 403, 404, and\n5xx responses before recording failure. This keeps the public health signal\nstrict while absorbing short CloudFront edge propagation windows that can remain\nvisible after the invalidation waiter returns. By default, Buildchain attempts\neach HTTP smoke URL 12 times with a 10 second interval. Consumers can override\nthat window with `BUILDCHAIN_WEB_SURFACE_HEALTH_HTTP_RETRY_ATTEMPTS` and\n`BUILDCHAIN_WEB_SURFACE_HEALTH_HTTP_RETRY_INTERVAL_MS` when they need a\nsite-specific health policy.\n\nThe health check fetches every surface root URL and any nested smoke URLs\nrecorded in each surface binding. Nested smoke URLs are derived from nested HTML\nartifact files under the surface path prefix, with directory index resolution\nsuch as `dist/buildchain/docs/index.html` becoming `/docs/` on the buildchain\npreview host. If a surface has no nested HTML route, Buildchain records only\nthe root smoke URL; absence of nested HTML is not a deployment failure. When a\nnested route is present, the check fails closed if a deploy reports success but\nthat child page returns 403 or another unexpected status. Surface root checks\nexpect the apply result to have installed the directory-index rewrite, so a\nmulti-host preview root such as `https://buildchain-pr-29.preview.libkungfu.dev/`\nmust resolve to the surface `index.html`, not the bare prefix directory.\nProduction additionally fails if a response is unreachable, returns an\nunexpected status, or still sends `x-robots-tag: noindex`. The health check also\nverifies that each surface binding recorded a deployment manifest pointer. The\nproduction release passport embeds the deploy plan, apply result, production\npreflight, and health check so a reviewer or agent can audit why the production\nsite changed and whether every declared host and every existing nested route was\nactually covered.\n\nPublic channels can opt into object-level health with\n`deploy.<channel>.health_strategy = \"s3-object\"` when the deployment contract is\nalready covered by S3 manifest/object writes and public edge convergence is not\nthe right CI gate. This is useful for preview distributions whose viewer-request\nrouting is owned by an external CloudFront Function. The channel remains public;\nonly the CI health evidence changes from HTTP fetches to S3 `head-object`\nchecks.\n\nChannels declared with `access_control = \"managed-network\"` use a different\nhealth strategy by default. Buildchain does not require a GitHub-hosted runner\nto fetch a URL that is intentionally reachable only from an approved network.\nInstead, after a live apply the health check uses the deploy role to run S3\n`head-object` checks for each surface manifest and the smoke target object, such\nas the surface `index.html` or a nested `docs/index.html`. The check records\n`healthStrategy = \"s3-object\"` and skips the public HTTP fetch. Dry-run and\nplan-only checks fall back to deployment evidence: each surface must have a\nmanifest key, bucket, object prefix, `sync-static-artifact`, and\n`write-deployment-manifest` evidence, recorded as\n`healthStrategy = \"deployment-evidence\"`. If the workflow is running on a runner\nthat is allowed to reach the managed network, set\n`BUILDCHAIN_WEB_SURFACE_HEALTH_ALLOWED_RUNNER=true` or pass\n`--allowed-managed-network-runner true` to keep the normal HTTP smoke checks.\nSet `BUILDCHAIN_WEB_SURFACE_HEALTH_S3_OBJECTS=false` or pass\n`--managed-network-s3-object-verification false` only when an external channel\npolicy owns managed-network object verification.\n\n## Cleanup Plans\n\nPreview cleanup is an auditable cleanup contract. It can run as a dry-run plan,\nan apply-mode plan, or the explicit `cleanup-apply` executor with preview-only\ncredentials:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode cleanup-plan \\\n --cwd fixtures/web-surface-shaped \\\n --event pull-request-closed \\\n --pull-number 123 \\\n --aliases pr-123,sha-abcdef123456\n```\n\nThe plan and apply result keep mutable PR aliases and immutable SHA aliases\ndistinct so a caller can expire them with different retention windows. Closed-PR\ncleanup can derive `pr-N` from `--pull-number`, records the event, source SHA,\nactor, run id, preview bucket/prefix, manifest key, and adapter steps, and is an\nauditable no-op when no aliases are requested.\n\n## Reusable Workflow Shape\n\nBuildchain ships `.github/workflows/.web-surface.yml` for repositories that want\nthe standard PR review and promotion flow without copying bespoke glue:\n\n```yaml\njobs:\n web-surface:\n uses: kungfu-systems/buildchain/.github/workflows/.web-surface.yml@v2\n with:\n build-command: npm run build\n verify-command: npm run check\n artifact-path: dist\n```\n\nThe reusable workflow maps GitHub events to Buildchain web-surface semantics:\n\n| Event | Buildchain behavior |\n| --- | --- |\n| `pull_request` opened / synchronized / reopened | validate, build, verify, and plan `preview` for `pr-N` |\n| `pull_request` closed | plan apply-mode cleanup for the `pr-N` preview alias and manifest |\n| `push` to `main` | validate, build, verify, plan and apply `staging` from the merged `main` SHA, then optionally open a production release PR |\n| `push` to `main` from a matching release PR merge | validate the associated release PR, plan `production`, and enter the configured GitHub Environment gate |\n| `workflow_dispatch` with `production-approved = true` | plan `production` and enter the configured GitHub Environment gate |\n\nThe optional `buildchain-ref` input is empty by default. Empty keeps the\nweb-surface run on the stable Buildchain runtime selected by the reusable\nworkflow ref, normally `@v2`. A trusted maintainer can expose a\n`workflow_dispatch` input and pass it through for one-off train validation.\nSee [`runtime-train-validation.md`](runtime-train-validation.md) for the shared\ntrain protocol and notification template:\n\n```yaml\non:\n workflow_dispatch:\n inputs:\n buildchain-ref:\n description: \"Temporary Buildchain runtime ref for trusted manual validation\"\n required: false\n default: \"\"\n\njobs:\n web-surface:\n uses: kungfu-systems/buildchain/.github/workflows/.web-surface.yml@v2\n with:\n buildchain-ref: ${{ inputs.buildchain-ref || '' }}\n build-command: pnpm run build\n verify-command: pnpm run check\n artifact-path: dist\n```\n\nOnly trusted `workflow_dispatch` runs by repository actors with write,\nmaintain, or admin permission may use a non-empty runtime override. Train refs\nsuch as `train/v2/v2.3/site-source-of-truth` are temporary validation refs, not\nstable production dependencies or pending merge targets. They may remain for a\nretention window after release as a fast-use and rollback channel, with old\ntrains handled by periodic Buildchain cleanup. The web-surface deployment\nmanifest records the resolved runtime SHA as `runtimeId` and the stable\nrollback ref as `rollbackPointer`.\n\nThe workflow deliberately plans and emits manifests by default. Live mutation is\nopt-in per channel:\n\n```yaml\npermissions:\n contents: read\n id-token: write\n pull-requests: write\n\njobs:\n web-surface:\n uses: kungfu-systems/buildchain/.github/workflows/.web-surface.yml@v2\n with:\n build-command: pnpm run build\n verify-command: pnpm run check\n artifact-path: dist\n preview-apply: true\n preview-cleanup-apply: true\n preview-aws-role-arn: arn:aws:iam::123456789012:role/site-preview-github-actions\n staging-apply: true\n staging-aws-role-arn: arn:aws:iam::123456789012:role/site-staging-github-actions\n production-apply: false\n production-release-on-main: false\n production-aws-role-arn: arn:aws:iam::123456789012:role/site-production-github-actions\n production-environment: production\n release-feedback-actor-privacy: public\n```\n\nWhen enabled, Buildchain owns the full release apply state machine:\n\n- PR preview deploys run `deploy-apply --dry-run false` with the preview role\n and update a single idempotent PR comment.\n- Closed PR cleanup runs `cleanup-apply --dry-run false` with the preview role\n only.\n- Pushes to `main` run staging `deploy-apply --dry-run false` with the staging\n role, then write a staging release feedback passport artifact and comment the\n associated merged PR with the staging URL, source SHA, artifact identity, run\n URL, and failure context when apply did not complete.\n- When `production-release-on-main=true`, successful staging applies open or\n update a Buildchain-owned release PR from\n `release/<channel>-<short-sha>` to `main`, unless the current push already\n came from a matching release PR merge. The release PR contains one empty\n release-intent commit, carries `production-release-label`, and includes the\n staging URLs, source SHA, artifact hash, and staging release-passport artifact\n link in the PR body.\n- Production release PR handoff is permission-aware. Staging apply and staging\n health remain successful even when the repository or organization has\n GitHub Actions workflow permissions set to read-only. In that case Buildchain\n records `release-pr-status=permission-denied`, uploads the release PR handoff\n summary/body plus staging release passport artifacts, and writes an exact\n manual `gh pr create` command to the step summary. Set\n `fail-on-release-pr-error=true` only when PR creation failure should fail the\n whole workflow.\n- Release pull requests that match the configured production gate get a\n Buildchain review comment with the staging URL and production target, so the\n operator can verify staging from the PR page and use merge as the approval\n action. Consumers do not need to hand-write `gh pr create` or production\n release-intent glue.\n- `production-apply=true` enables the production capability; it does not request\n production for every event. Ordinary `main` pushes remain staging-only and\n can create or update a release PR. Production runs only when the capability\n is enabled and either:\n - a `workflow_dispatch` passes `production-approved=true` and the triggering\n actor currently has `write`, `maintain`, or `admin` permission; or\n - `production-release-on-main=true` and the `main` push commit is associated\n with exactly one same-repository, merged release pull request matching\n `production-release-label` and `production-release-head-prefix`.\n The production job is then gated by the configured GitHub Environment.\n- Before production artifact download, Buildchain assembles a managed sealed\n publication capability from the exact source/runtime SHAs, production plan\n and artifact hash, a qualifying pre-publication controller receipt, the\n trusted manual or reviewed-release-PR decision, production Environment and\n AWS role target, an ephemeral-runner receipt, and a fresh nonce. Production\n revalidates that capability against the downloaded plan before it downloads\n product bytes. The later AWS OIDC exchange remains the provider's final\n transaction-time authorization decision and fails closed before deploy apply.\n- The `publication-*-json` inputs are an advanced external-evidence\n compatibility path, not a prerequisite for the standard release-PR or trusted\n manual mechanisms. External evidence must now include\n `publication-gate-aggregate-json`; supplying only a partial set still fails\n closed.\n- Production apply writes a production release feedback passport artifact and\n comments the release PR with the production URL, source SHA, artifact\n identity, run URL, rollback pointer, and failure context when apply did not\n complete.\n\nThe feedback passport records the release responsibility chain:\n\n- human decision actor;\n- trigger actor;\n- runner/execution actor;\n- OIDC/deploy identity reference;\n- decision type and time;\n- source event, PR number, merge commit, and required gate label/head-prefix.\n\n`release-feedback-actor-privacy` controls actor values in the passport and\ncomments. `public` records GitHub actor names, `redacted` records only the actor\nrole, and `private-ref` records a stable private reference hash without exposing\nthe actor name.\n\nFor release-PR publishing, callers opt in explicitly:\n\n```yaml\njobs:\n web-surface:\n uses: kungfu-systems/buildchain/.github/workflows/.web-surface.yml@v2\n with:\n build-command: npm run build\n verify-command: npm run check\n artifact-path: dist\n production-apply: true\n production-release-on-main: true\n production-release-label: buildchain-release\n production-release-head-prefix: release/\n production-release-branch-channel: production\n production-release-pr-mode: auto\n production-aws-role-arn: arn:aws:iam::123456789012:role/site-production-github-actions\n production-environment: production\n```\n\nKeep `production-apply` enabled in the caller when the repository supports\nproduction. Buildchain derives whether the current event may use that\ncapability: an ordinary `main` push plans and applies staging, a matching\nreviewed release PR merge authorizes production, and an approved trusted manual\ndispatch authorizes production. Inputs from an untrusted event cannot turn that\ndecision on.\n\n`production-release-pr-mode` controls the post-staging handoff:\n\n| Mode | Behavior |\n| --- | --- |\n| `auto` | Generate release PR facts, create/update the empty release-intent branch and PR, and label it when token permissions allow. This is the default. |\n| `summary-only` | Generate and upload release PR facts, body, passport evidence, and manual command, but do not call the GitHub PR API. |\n| `disabled` | Record a disabled handoff and skip release PR API calls. |\n\nAutomatic release PR creation normally uses the workflow `github.token`.\nConsumers that cannot enable \"GitHub Actions can create and approve pull\nrequests\" globally should prefer the first-class GitHub App path. Pass the App\nclient id as an input and the private key as a reusable workflow secret; Buildchain\ncreates an installation token inside the release PR job and uses it only for the\nrelease-intent branch, PR, and label operations:\n\n```yaml\nwith:\n production-release-app-client-id: ${{ vars.KUNGFU_RELEASE_APP_CLIENT_ID }}\nsecrets:\n production-release-app-private-key: ${{ secrets.KUNGFU_RELEASE_APP_PRIVATE_KEY }}\n```\n\nWhen either side of the App configuration is missing, Buildchain does not hide\nthat behind the fallback `github.token`. The handoff JSON and job summary report\n`status: \"app-token-unavailable\"` with an `appTokenStatus` such as\n`missing-client-id`, `missing-private-key`, or `create-failed`, and still include\nthe manual PR creation command. If the repository intentionally uses another\nnarrow token, pass it through `production-release-pr-token`.\n\n`production-release-app-id` remains accepted as a deprecated alias for the input\nname, but the value should be the GitHub App client id. GitHub App numeric App\nIDs and client IDs are distinct, and Buildchain passes the value to\n`actions/create-github-app-token` through its non-deprecated `client-id` input so\nnew runs do not emit the deprecated `app-id` warning.\n\nIf a repository already generates its own narrow token or PAT, it can still pass\nthat through `production-release-pr-token`:\n\n```yaml\nwith:\n production-release-pr-token: ${{ secrets.BUILDCHAIN_RELEASE_PR_TOKEN }}\n```\n\nToken priority is: generated GitHub App installation token,\n`production-release-pr-token`, then `github.token`.\n\nThe merge button becomes the production approval only for a PR that carries the\nrelease label and comes from the configured source-branch prefix. Ordinary pull\nrequests merged into `main` deploy staging and open a release-intent PR; merging\nthat release PR triggers production. A release PR merge push does not open\nanother release PR.\n\nApply-only inputs are validated before the caller build or verification command\nruns. If the current event would run preview, staging, or production apply,\nmissing role inputs, a production apply without `production-approved=true` on\nmanual dispatch, or a manual actor without repository write authority fail\nimmediately instead of spending the build and plan jobs first.\n\nCallers must grant `id-token: write` for OIDC role assumption. Preview comments\nneed `pull-requests: write`. Automatic release PR creation also needs\n`contents: write`, `pull-requests: write`, and `issues: write` so Buildchain can\ncreate the release branch, write the empty release-intent commit, open or update\nthe PR, and apply the release label. If these permissions are unavailable,\nBuildchain degrades the release handoff instead of marking a successful staging\ndeployment as failed, unless `fail-on-release-pr-error=true`. The AWS roles remain caller-owned and\nshould be scoped by channel: preview can mutate only preview resources, staging\ncan mutate only staging resources, and production can mutate only production\nresources.\n\nApply mode fails closed when the deploy config still contains placeholder AWS\ntargets such as `pending-preview-distribution`. Planning can use placeholders\nfor dry-run-only design work, but live apply requires concrete bucket and\nCloudFront distribution identifiers.\n\n## Site Repository Shape\n\nA site repository can start with:\n\n```toml\nschema = 1\n\n[project]\ntype = \"web-surface\"\nname = \"site-kungfu-tech\"\nsite = \"kungfu-tech\"\n\n[lifecycle.build]\ncommand = \"pnpm run build\"\n\n[lifecycle.verify]\ncommand = \"pnpm run check\"\n```\n\nThen add the channel, deploy, retention, and security declarations shown above.\nThe project may use pnpm, npm, yarn, Vite, Astro, Next static export, Sphinx,\nMkDocs, CMake-generated docs, or another lifecycle command source. Buildchain\nonly needs a deterministic artifact path and the manifest facts.\n\n## Boundaries\n\nBuildchain only performs live AWS mutations in explicit apply modes with\n`--dry-run false`. Production deploys must still be gated by a human-controlled\nworkflow, release, or GitHub Environment. DNS changes, staging auth\nimplementation, CloudFront distribution creation, and credential provisioning\nremain explicitly authorized infrastructure operations outside the web-surface\nartifact apply contract."
2191
2196
  },
2192
2197
  {
2193
2198
  "id": "fixture:infra-contract-aws-cdk-shaped",
@@ -2800,7 +2805,7 @@
2800
2805
  "path": "docs/web-surface-deployments.md",
2801
2806
  "plane": "use",
2802
2807
  "exists": true,
2803
- "digest": "sha256:efbfc97a947978e61c79dac9d67f87050b1bef2297617303340af8aa499703c9"
2808
+ "digest": "sha256:ecdece4b7d916b7d8b323db68c5d81c533d67348c71907b46eb97d3c2fe432ba"
2804
2809
  }
2805
2810
  ],
2806
2811
  "releaseModel": {
@@ -21,7 +21,7 @@
21
21
  "contract": "kungfu-buildchain-public-surface-reverse-audit",
22
22
  "path": "dist/site/public-surface-audit.json",
23
23
  "status": "passed",
24
- "sha256": "985325d77f75673576fff45c81afd458fe46c6f8b71b5784e8359dc31129dc86",
24
+ "sha256": "85d9b19de156773aab9a45cc7f8c201c0cebfc07a3f8d4ae902ca2d0e9fbfd86",
25
25
  "summary": {
26
26
  "cliCommandCount": 85,
27
27
  "workflowCount": 51,
@@ -228,7 +228,7 @@
228
228
  "contract": "kungfu-buildchain-public-surface-reverse-audit",
229
229
  "path": "dist/site/public-surface-audit.json",
230
230
  "status": "passed",
231
- "sha256": "985325d77f75673576fff45c81afd458fe46c6f8b71b5784e8359dc31129dc86",
231
+ "sha256": "85d9b19de156773aab9a45cc7f8c201c0cebfc07a3f8d4ae902ca2d0e9fbfd86",
232
232
  "summary": {
233
233
  "cliCommandCount": 85,
234
234
  "workflowCount": 51,
@@ -4,7 +4,7 @@
4
4
  "product": {
5
5
  "id": "kungfu-tech-buildchain",
6
6
  "name": "@kungfu-tech/buildchain",
7
- "version": "2.14.15",
7
+ "version": "2.14.16-alpha.0",
8
8
  "repository": "https://github.com/kungfu-systems/buildchain"
9
9
  },
10
10
  "source": {
@@ -399,7 +399,7 @@
399
399
  "title": "Web surface deployments",
400
400
  "path": "docs/web-surface-deployments.md",
401
401
  "plane": "use",
402
- "digest": "sha256:efbfc97a947978e61c79dac9d67f87050b1bef2297617303340af8aa499703c9",
402
+ "digest": "sha256:ecdece4b7d916b7d8b323db68c5d81c533d67348c71907b46eb97d3c2fe432ba",
403
403
  "capabilityGroup": "site-and-propagation",
404
404
  "audience": [
405
405
  "site",
@@ -2018,7 +2018,7 @@
2018
2018
  ],
2019
2019
  "maturity": "stable",
2020
2020
  "sourcePath": "docs/web-surface-deployments.md",
2021
- "digest": "sha256:efbfc97a947978e61c79dac9d67f87050b1bef2297617303340af8aa499703c9",
2021
+ "digest": "sha256:ecdece4b7d916b7d8b323db68c5d81c533d67348c71907b46eb97d3c2fe432ba",
2022
2022
  "headings": [
2023
2023
  {
2024
2024
  "level": 1,
@@ -2090,6 +2090,11 @@
2090
2090
  "title": "Explicit Apply",
2091
2091
  "anchor": "explicit-apply"
2092
2092
  },
2093
+ {
2094
+ "level": 3,
2095
+ "title": "Explicit cache classes",
2096
+ "anchor": "explicit-cache-classes"
2097
+ },
2093
2098
  {
2094
2099
  "level": 3,
2095
2100
  "title": "Immutable publication paths",
@@ -2121,7 +2126,7 @@
2121
2126
  "anchor": "boundaries"
2122
2127
  }
2123
2128
  ],
2124
- "markdown": "# Web-Surface Deployment Contract\n\nBuildchain supports `project.type = \"web-surface\"` for repositories that publish\nsites, docs, product pages, operator consoles, or browser apps. These projects\nneed auditable deployment semantics, but they are not package release lines and\nshould not be forced into `dev/alpha/release` version-state automation.\n\nThe release object for a web surface is:\n\n```text\nsource commit + build artifact + deploy target + channel + deployment manifest\n```\n\nThis keeps the evidence chain clear:\n\n- the source SHA explains what code was built;\n- the artifact hash explains exactly what was deployed;\n- the channel explains who can see it and whether it is promotable;\n- the deploy target and adapter explain where it would be published;\n- the deployment manifest records retention, rollback, security, and secret\n reference metadata.\n\n## Configuration\n\n`.buildchain/buildchain.toml` is the source of truth. Web-surface projects must declare\npreview, staging, and production channels plus a deploy adapter for each.\n\n```toml\nschema = 1\n\n[project]\ntype = \"web-surface\"\nname = \"site-kungfu-tech\"\nsite = \"kungfu-tech\"\n\n[channels.preview]\nurl_pattern = \"https://{alias}.preview.kungfu.tech\"\nvisibility = \"ephemeral\"\nrequires_auth = false\nnoindex = true\n\n[channels.staging]\nurl = \"https://staging.kungfu.tech\"\nvisibility = \"protected\"\naccess_control = \"managed-network\"\nedge_auth = \"none\"\nnoindex = true\npromotable = true\n\n[channels.production]\nurl = \"https://kungfu.tech\"\nvisibility = \"public\"\ncanonical = true\nnoindex = false\n\n[deploy.preview]\nadapter = \"aws-s3-cloudfront\"\nbucket = \"kungfu-tech-preview\"\ncloudfront_distribution = \"E-PREVIEW\"\nartifact_path = \"dist\"\nsecret_refs = [\"AWS_ROLE_ARN\"]\n# Optional. Defaults to \"buildchain\".\n# Use \"external\" when an existing viewer-request CloudFront Function already\n# owns preview alias, surface-prefix, and directory-index routing.\ndirectory_index_rewrite = \"buildchain\"\n# Optional. Defaults to HTTP for public channels and S3 object evidence for\n# managed-network channels. Use \"s3-object\" when CI should verify uploaded\n# objects and manifests instead of waiting for public edge convergence.\nhealth_strategy = \"http\"\n```\n\n### Multi-Surface Host Mapping\n\nSome site repositories publish more than one first-class web surface from the\nsame artifact. For example, `site-libkungfu-dev` has a hub plus separate\nhostnames for core, Buildchain, and Kung Fu Decisions. These are not just\nnavigation paths; staging, production preflight, and post-deploy health checks\nmust verify host-level behavior for each surface.\n\nDeclare named surfaces with per-channel URLs:\n\n```toml\n[surfaces.hub]\npath = \"/\"\nproduction_url = \"https://libkungfu.dev\"\nstaging_url = \"https://staging.libkungfu.dev\"\npreview_url_pattern = \"https://{alias}.preview.libkungfu.dev\"\n\n[surfaces.core]\npath = \"/core/\"\nproduction_url = \"https://core.libkungfu.dev\"\nstaging_url = \"https://core.staging.libkungfu.dev\"\npreview_url_pattern = \"https://core-{alias}.preview.libkungfu.dev\"\n\n[surfaces.buildchain]\npath = \"/buildchain/\"\nproduction_url = \"https://buildchain.libkungfu.dev\"\nstaging_url = \"https://buildchain.staging.libkungfu.dev\"\npreview_url_pattern = \"https://buildchain-{alias}.preview.libkungfu.dev\"\n\n[surfaces.kfd]\npath = \"/kfd/\"\nproduction_url = \"https://kfd.libkungfu.dev\"\nstaging_url = \"https://kfd.staging.libkungfu.dev\"\npreview_url_pattern = \"https://kfd-{alias}.preview.libkungfu.dev\"\n```\n\nBuildchain resolves every `(channel, surface)` pair. A preview alias such as\n`pr-12` becomes:\n\n```text\nhub: https://pr-12.preview.libkungfu.dev\ncore: https://core-pr-12.preview.libkungfu.dev\nbuildchain: https://buildchain-pr-12.preview.libkungfu.dev\nkfd: https://kfd-pr-12.preview.libkungfu.dev\n```\n\nWhen `surfaces` is omitted, Buildchain preserves the legacy single-surface\ncontract by creating an implicit `default` surface from the channel URL. When a\nsurface is intentionally path-only, declare it explicitly:\n\n```toml\n[surfaces.docs]\npath = \"/docs/\"\npath_only = true\n```\n\n`path_only = true` is an exception, not the default. Without it, every named\nsurface must declare `preview_url_pattern`, `staging_url`, and\n`production_url`. This makes staging/production mismatches fail during\nvalidation instead of becoming invisible deploy drift.\n\nAdapter strategy remains explicit. The default `aws-s3-cloudfront` plan uses the\nchannel deploy target for every surface, and each binding records its own\nbucket, distribution id, object prefix, manifest key, source path, and URL. A\nchannel can override target details per surface:\n\n```toml\n[deploy.staging.surfaces.core]\nbucket = \"libkungfu-dev-core-staging\"\ncloudfront_distribution = \"E-CORE-STAGING\"\norigin_path = \"/core\"\n```\n\nBuildchain validates these hard constraints:\n\n- `channels.preview.url_pattern` is required and must contain the alias shape\n used by preview deployments.\n- `channels.staging.access_control` must protect staging. Supported modes are\n `managed-network`, `edge-basic-auth`, `oidc`, and `app-auth`.\n- `channels.staging.edge_auth` records whether the edge layer owns auth. Use\n `edge_auth = \"none\"` when staging is protected by managed network controls\n such as WAF/IP allowlists or VPN access.\n- `channels.staging.noindex = true` is required.\n- `channels.production.url` is required.\n- deploy adapters must be declared per channel.\n- named surfaces must declare first-class URLs for every channel unless\n `path_only = true` is explicitly set.\n- secret material must be declared as reference names, such as\n `secret_refs = [\"AWS_ROLE_ARN\"]`; inline secret-like deploy keys are rejected.\n\n### Floating Runtime Contract Lock\n\nWeb-surface repositories can consume the stable Buildchain workflow shell with a\nfloating ref, such as:\n\n```yaml\njobs:\n web:\n uses: kungfu-systems/buildchain/.github/workflows/.web-surface.yml@v2\n with:\n buildchain-contract-lock-path: .buildchain/contract-lock.json\n buildchain-contract-compatibility-policy: major-compatible\n buildchain-contract-drift-issue-mode: compatible-and-breaking\n build-command: pnpm build\n artifact-path: dist\n```\n\nThe caller repository commits `.buildchain/contract-lock.json` after reviewing an\naccepted Buildchain runtime SHA and contract digest. The reusable workflow then\nresolves the floating runtime to an immutable SHA, checks the lock before the\ncaller build command, and applies these rules:\n\n- unchanged lock: continue without feedback;\n- compatible drift: continue, write the drift summary, and open or update a\n caller-repository issue when permissions allow;\n- breaking drift: fail closed before rendering, deployment planning, deploy\n apply, or release publication.\n\nThe caller no longer needs to run `scripts/buildchain-contract-lock.mjs` inside\nits own build command. That check belongs to Buildchain because the actual\ncontract world is stored in the Buildchain runtime ref being used.\n\nSupported adapter names are:\n\n| Adapter | Initial use |\n| --- | --- |\n| `aws-s3-cloudfront` | Static site artifact sync plus CDN invalidation plan |\n| `aws-elastic-beanstalk` | Future dynamic app environment adapter |\n| `aws-ecs-service` | Future dynamic service adapter |\n\nThe channel ontology is independent of the adapter. A future dynamic staging\nenvironment still remains `channel = \"staging\"` with protected/noindex/security\nrequirements.\n\n## Preview Aliases\n\nPreview uses subdomains, not path prefixes:\n\n```text\nhttps://pr-123.preview.kungfu.tech\nhttps://sha-abcdef123456.preview.kungfu.tech\n```\n\nAlias semantics are explicit:\n\n| Alias | Meaning | Mutable | Retention |\n| --- | --- | --- | --- |\n| `pr-123` | Current preview for a pull request | yes | short-lived |\n| `sha-abcdef123456` | Immutable preview for one source SHA | no | longer-lived |\n\nThis allows PR comments to stay stable while preserving immutable evidence for a\nspecific source commit.\n\n## Deployment Manifest\n\nBuildchain emits a manifest with the deployment facts that matter for audit and\nrollback:\n\n```json\n{\n \"schemaVersion\": 1,\n \"contract\": \"kungfu-buildchain-web-surface-deployment\",\n \"site\": \"libkungfu-dev\",\n \"channel\": \"preview\",\n \"alias\": \"sha-abcdef123456\",\n \"url\": \"https://sha-abcdef123456.preview.libkungfu.dev\",\n \"generatedAt\": \"2026-07-01T00:00:00.000Z\",\n \"publishedAt\": \"2026-07-01T00:00:00.000Z\",\n \"reproducible\": true,\n \"timestampPolicy\": \"ci-injected\",\n \"deterministicInputs\": [\n \"web-surface artifact content\",\n \"buildchain.toml web-surface channels/deploy/surfaces\",\n \"sourceSha\",\n \"artifactHash\",\n \"deployment channel\",\n \"deployment alias\"\n ],\n \"sourceRevision\": \"...\",\n \"timestampPolicyDetails\": {\n \"contract\": \"kungfu-buildchain-surface-timestamp-policy\",\n \"timestampFields\": [\"generatedAt\", \"publishedAt\", \"deployedAt\"],\n \"timestampFieldsParticipateInArtifactDigest\": false,\n \"artifactDigestScope\": \"web-surface artifactHash excludes deployment manifest timestamps\"\n },\n \"sourceSha\": \"...\",\n \"artifactHash\": \"...\",\n \"deployTarget\": \"libkungfu-dev-preview\",\n \"adapter\": \"aws-s3-cloudfront\",\n \"deployedAt\": \"2026-07-01T00:00:00.000Z\",\n \"retentionClass\": \"preview-sha-immutable\",\n \"expiresAt\": \"2026-09-29T00:00:00.000Z\",\n \"accessControl\": \"none\",\n \"edgeAuth\": \"none\",\n \"noindex\": true,\n \"secretRefs\": [\"AWS_ROLE_ARN\"],\n \"surfaceBindings\": [\n {\n \"surface\": \"hub\",\n \"channel\": \"preview\",\n \"alias\": \"sha-abcdef123456\",\n \"url\": \"https://sha-abcdef123456.preview.libkungfu.dev\",\n \"sourcePath\": \"/\",\n \"artifactPathPrefix\": \"\",\n \"viewerPathPrefix\": \"/\",\n \"directoryIndex\": \"index.html\",\n \"directoryIndexResolution\": true,\n \"canonicalUrl\": \"https://libkungfu.dev\",\n \"bucket\": \"libkungfu-dev-preview\",\n \"distributionId\": \"E-PREVIEW\",\n \"originPath\": \"\",\n \"objectPrefix\": \"sha-abcdef123456\",\n \"manifestKey\": \".buildchain/deployments/sha-abcdef123456/hub.json\",\n \"routing\": {\n \"contract\": \"kungfu-buildchain-web-surface-path-prefix-rewrite\",\n \"viewerPathPrefix\": \"/\",\n \"artifactPathPrefix\": \"\",\n \"objectPrefix\": \"sha-abcdef123456\",\n \"directoryIndex\": \"index.html\",\n \"directoryIndexResolution\": true\n },\n \"smokeUrls\": [\n {\n \"kind\": \"root\",\n \"requestPath\": \"/\",\n \"url\": \"https://sha-abcdef123456.preview.libkungfu.dev/\",\n \"required\": true\n }\n ],\n \"noindex\": true,\n \"accessControl\": \"none\"\n }\n ]\n}\n```\n\nDynamic adapters can also fill `runtimeId`, `configFingerprint`,\n`healthCheck`, `migrationState`, `rollbackPointer`, and\n`rollbackLimitations`. Buildchain records secret reference names only, never\nsecret values.\n\nThe timestamp policy is shared with package site bundles. Public deployment\nmanifests should expose real workflow generation/publication times while\nseparately declaring why the deployed artifact remains reproducible. For\nweb-surface deployment manifests, `artifactHash` is the static site artifact\ndigest and does not include deployment timestamp fields; the manifest itself\nstill records those fields for human and agent audit.\n\n## Deploy Plans\n\nDeploy planning is the default behavior. It plans the adapter steps and writes\nmanifest JSON, but it does not touch AWS, DNS, CloudFront, or deployment\ncredentials.\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode deploy-plan \\\n --cwd fixtures/web-surface-shaped \\\n --source-sha aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \\\n --alias sha-aaaaaaaaaaaa\n```\n\nFor manifest-only output:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode manifest \\\n --cwd fixtures/web-surface-shaped \\\n --source-sha aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \\\n --alias pr-123 \\\n --output .buildchain/web-surface-manifest.json\n```\n\nThe CLI emits GitHub outputs when `GITHUB_OUTPUT` is present:\n\n- `web-surface-channel`\n- `web-surface-alias`\n- `web-surface-url`\n- `web-surface-urls-json`\n- `web-surface-artifact-hash`\n- `web-surface-manifest-json`\n\nThe reusable workflow resolves that same effective channel before running the\ncaller build or verify command. Both steps receive\n`BUILDCHAIN_WEB_SURFACE_CHANNEL` (`preview`, `staging`, or `production`) and\n`BUILDCHAIN_PREVIEW_ALIAS` for previews. Compatibility aliases\n`BUILDCHAIN_SURFACE_CHANNEL` and `BUILDCHAIN_WEB_SURFACE_ALIAS` are also\nprovided. Callers should consume these variables instead of reconstructing the\nrelease-intent state machine from raw GitHub events.\nAn unapproved manual canary resolves to `staging`; a trusted manual dispatch\nwith `production-approved=true` resolves to `production` through the same path.\n\n## Explicit Apply\n\n`deploy-apply` and `cleanup-apply` are explicit execution modes for the\n`aws-s3-cloudfront` static-site adapter. They still default to `--dry-run true`;\nlive AWS mutation requires `--dry-run false`.\n\nDeploy apply syncs the artifact, writes the deployment manifest, and invalidates\nCloudFront when a distribution id is configured:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode deploy-apply \\\n --cwd fixtures/web-surface-shaped \\\n --channel staging \\\n --source-sha aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \\\n --artifact-path dist \\\n --dry-run false \\\n --output .buildchain/web-surface-staging-apply.json\n```\n\n### Immutable publication paths\n\nWhen a surface artifact contains `manifest.json` with\n`archivePolicy.contract = \"kungfu-buildchain-publication-archive-policy\"`,\nBuildchain treats every declared `publications[].versions[].immutablePath` as\nan append-only publication boundary. This applies identically to preview,\nstaging, and production adapters.\n\nThe adapter derives the protected archive root from those declared version\npaths and applies four ordered safeguards:\n\n1. every local immutable file is checked against an existing S3 object;\n2. missing files are uploaded with `aws s3 sync --no-overwrite` and a SHA-256\n checksum;\n3. every immutable file is checked again after upload, closing the race between\n the first check and the no-overwrite transfer;\n4. mutable site content keeps normal `sync --delete` behavior, but every parent\n or owning surface sync excludes the protected archive root from deletion.\n\nAn existing object with a different SHA-256 digest fails apply before mutable\ncontent is changed. Older objects without a stored S3 SHA-256 checksum are read\nand byte-hashed for compatibility. Directory-index alias writes are skipped\nunder protected roots so they cannot overwrite immutable route objects; viewer\nrequest rewriting remains the directory-index authority.\n\nThe deploy plan and manifest record `immutablePublication`,\n`mutableDeleteExcludes`, and the parent-surface coverage. Apply output records\n`immutablePreservation` plus every pre-check, no-overwrite sync, post-check, and\nmutable sync operation. Health output adds an `__immutable__` check proving that\nthe owning and parent surface syncs carried their required delete exclusions.\nThe runner must provide an AWS CLI version whose `s3 sync` supports\n`--no-overwrite`.\n\nFor multi-surface sites, each surface host is treated as a root-relative view\nof that surface's artifact path prefix. For example, a `buildchain` surface with\n`path = \"/buildchain/\"` and preview URL\n`https://buildchain-pr-29.preview.libkungfu.dev` syncs the artifact subtree\n`dist/buildchain/` to the preview object prefix `pr-29/buildchain`. A viewer\nrequest for `https://buildchain-pr-29.preview.libkungfu.dev/docs/` therefore\nresolves against the artifact's `dist/buildchain/docs/index.html`, not\n`dist/docs/index.html` and not the hub surface root. The deployment manifest\nrecords this as `routing.contract =\n\"kungfu-buildchain-web-surface-path-prefix-rewrite\"` with\n`viewerPathPrefix = \"/\"`, `artifactPathPrefix = \"buildchain\"`, and\n`directoryIndexResolution = true`.\n\nWhen a surface uses an S3 object prefix, directory-index routing must be handled\nat the viewer-request layer. By default, `directory_index_rewrite =\n\"buildchain\"` makes Buildchain install or update one CloudFront Function per\ndistribution before uploading payloads. The function rewrites any request path\nending in `/` to the corresponding `index.html`, so\n`https://buildchain-pr-29.preview.libkungfu.dev/` resolves to\n`pr-29/buildchain/index.html` and\n`https://buildchain-pr-29.preview.libkungfu.dev/docs/` resolves to\n`pr-29/buildchain/docs/index.html`. This keeps multi-host preview roots\ncompatible with S3 REST origins, where copying alias objects such as\n`pr-29/buildchain` or `pr-29/buildchain/` is not a reliable substitute for an\nedge rewrite.\n\nIf the distribution already has a viewer-request function that owns preview\nalias routing and surface-prefix routing, set `directory_index_rewrite =\n\"external\"` on the deploy channel or surface override. In that mode Buildchain\ndoes not create, update, or attach a generic directory-index function. Instead,\nthe deployment manifest records `directoryIndexRewrite = \"external\"` and\n`directoryIndexStrategy = \"external-viewer-request-function\"`, then the normal\nhealth check still verifies every required root and nested surface URL. This is\nthe correct contract for shared preview distributions such as\n`site-libkungfu-dev`, where a generic function cannot replace the existing\nprefix router.\n\nBuildchain still writes directory-index alias objects during apply as\ncompatibility evidence, but root correctness comes from the viewer-request\nrewrite contract, not from extensionless S3 keys. If Buildchain-managed mode\nfinds a distribution with a different viewer-request function, apply fails\nclosed and records that conflict in the apply result instead of silently serving\n403s. If CloudFront rejects `UpdateDistribution` because its optimistic-lock\nETag became stale, Buildchain re-reads the distribution and retries with the\nnew ETag at most twice. A concurrent update that already attached the intended\nfunction is accepted as converged; a different viewer-request function or any\nnon-ETag AWS error still fails immediately. The reusable workflow uploads\n`buildchain-web-surface-*-diagnostics`\nartifacts containing the apply and health JSON so the failing AWS operation or\nHTTP check is visible from the consumer run.\n\nIt can also execute a previously saved deploy plan. In that mode Buildchain\nrecomputes the local artifact hash before running AWS commands and fails closed\nif the artifact no longer matches the saved plan. Before any adapter operation,\nit also checks channel-aware JSON manifests in the artifact: top-level\n`canonicalHost` and declared `pages[].host` facts must belong to the plan's\nsurface hosts. A production plan therefore rejects staging/preview host facts\nbefore AWS apply:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode deploy-apply \\\n --cwd fixtures/web-surface-shaped \\\n --plan .buildchain/web-surface-staging-plan.json \\\n --dry-run false \\\n --output .buildchain/web-surface-staging-apply.json\n```\n\nCleanup apply deletes preview content, deletes the preview manifest, and\ninvalidates CloudFront:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode cleanup-apply \\\n --cwd fixtures/web-surface-shaped \\\n --event pull-request-closed \\\n --pull-number 123 \\\n --source-sha aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \\\n --dry-run false \\\n --output .buildchain/web-surface-cleanup-apply.json\n```\n\nCleanup apply can also execute a saved cleanup plan:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode cleanup-apply \\\n --cwd fixtures/web-surface-shaped \\\n --plan .buildchain/web-surface-cleanup-plan.json \\\n --dry-run false \\\n --output .buildchain/web-surface-cleanup-apply.json\n```\n\nApply output records the channel, alias, source SHA, artifact hash, target\nbucket, object prefix, manifest key, all surface URLs, all surface bindings, CDN\ninvalidation paths, actor/run metadata, immutable preservation evidence, and\nevery adapter operation with\n`executed`, `exitCode`, `stdout`, and `stderr`. If an operation fails,\nBuildchain records the failed operation, stops subsequent adapter operations,\nand exits non-zero after writing the result JSON. Buildchain records secret\nreference names only; the runner must provide the AWS CLI and credentials\noutside Buildchain, typically through OIDC and the declared `secret_refs`.\n\n## Production Preflight And Health\n\nProduction promotion is not just `deploy-apply --channel production`. Before a\nlive production apply, the reusable workflow runs:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode production-preflight \\\n --cwd fixtures/web-surface-shaped \\\n --plan .buildchain/web-surface-production-plan.json \\\n --execute true \\\n --output .buildchain/web-surface-production-preflight.json\n```\n\nThe production preflight checks that:\n\n- `channels.production` is canonical and indexable;\n- every surface has concrete production bucket and CloudFront targets;\n- every production surface URL is HTTPS;\n- the production AWS role can inspect the declared bucket and distribution;\n- CloudFront aliases cover every surface host, including product hosts such as\n `kfd.libkungfu.dev`;\n- DNS resolves for every surface host.\n\nAfter preview, staging, and production apply, the workflow runs:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode health-check \\\n --cwd fixtures/web-surface-shaped \\\n --result .buildchain/web-surface-production-apply.json \\\n --output .buildchain/web-surface-production-health.json\n```\n\nWhen the apply result includes CloudFront invalidations from the\n`aws-s3-cloudfront` adapter, health check waits for those invalidations to reach\n`Completed` before fetching public smoke URLs. This avoids reporting stale\nCloudFront 403 responses as deployment failures immediately after a successful\nS3 sync and invalidation request.\n\nAfter the invalidation wait, HTTP smoke checks also retry transient 403, 404, and\n5xx responses before recording failure. This keeps the public health signal\nstrict while absorbing short CloudFront edge propagation windows that can remain\nvisible after the invalidation waiter returns. By default, Buildchain attempts\neach HTTP smoke URL 12 times with a 10 second interval. Consumers can override\nthat window with `BUILDCHAIN_WEB_SURFACE_HEALTH_HTTP_RETRY_ATTEMPTS` and\n`BUILDCHAIN_WEB_SURFACE_HEALTH_HTTP_RETRY_INTERVAL_MS` when they need a\nsite-specific health policy.\n\nThe health check fetches every surface root URL and any nested smoke URLs\nrecorded in each surface binding. Nested smoke URLs are derived from nested HTML\nartifact files under the surface path prefix, with directory index resolution\nsuch as `dist/buildchain/docs/index.html` becoming `/docs/` on the buildchain\npreview host. If a surface has no nested HTML route, Buildchain records only\nthe root smoke URL; absence of nested HTML is not a deployment failure. When a\nnested route is present, the check fails closed if a deploy reports success but\nthat child page returns 403 or another unexpected status. Surface root checks\nexpect the apply result to have installed the directory-index rewrite, so a\nmulti-host preview root such as `https://buildchain-pr-29.preview.libkungfu.dev/`\nmust resolve to the surface `index.html`, not the bare prefix directory.\nProduction additionally fails if a response is unreachable, returns an\nunexpected status, or still sends `x-robots-tag: noindex`. The health check also\nverifies that each surface binding recorded a deployment manifest pointer. The\nproduction release passport embeds the deploy plan, apply result, production\npreflight, and health check so a reviewer or agent can audit why the production\nsite changed and whether every declared host and every existing nested route was\nactually covered.\n\nPublic channels can opt into object-level health with\n`deploy.<channel>.health_strategy = \"s3-object\"` when the deployment contract is\nalready covered by S3 manifest/object writes and public edge convergence is not\nthe right CI gate. This is useful for preview distributions whose viewer-request\nrouting is owned by an external CloudFront Function. The channel remains public;\nonly the CI health evidence changes from HTTP fetches to S3 `head-object`\nchecks.\n\nChannels declared with `access_control = \"managed-network\"` use a different\nhealth strategy by default. Buildchain does not require a GitHub-hosted runner\nto fetch a URL that is intentionally reachable only from an approved network.\nInstead, after a live apply the health check uses the deploy role to run S3\n`head-object` checks for each surface manifest and the smoke target object, such\nas the surface `index.html` or a nested `docs/index.html`. The check records\n`healthStrategy = \"s3-object\"` and skips the public HTTP fetch. Dry-run and\nplan-only checks fall back to deployment evidence: each surface must have a\nmanifest key, bucket, object prefix, `sync-static-artifact`, and\n`write-deployment-manifest` evidence, recorded as\n`healthStrategy = \"deployment-evidence\"`. If the workflow is running on a runner\nthat is allowed to reach the managed network, set\n`BUILDCHAIN_WEB_SURFACE_HEALTH_ALLOWED_RUNNER=true` or pass\n`--allowed-managed-network-runner true` to keep the normal HTTP smoke checks.\nSet `BUILDCHAIN_WEB_SURFACE_HEALTH_S3_OBJECTS=false` or pass\n`--managed-network-s3-object-verification false` only when an external channel\npolicy owns managed-network object verification.\n\n## Cleanup Plans\n\nPreview cleanup is an auditable cleanup contract. It can run as a dry-run plan,\nan apply-mode plan, or the explicit `cleanup-apply` executor with preview-only\ncredentials:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode cleanup-plan \\\n --cwd fixtures/web-surface-shaped \\\n --event pull-request-closed \\\n --pull-number 123 \\\n --aliases pr-123,sha-abcdef123456\n```\n\nThe plan and apply result keep mutable PR aliases and immutable SHA aliases\ndistinct so a caller can expire them with different retention windows. Closed-PR\ncleanup can derive `pr-N` from `--pull-number`, records the event, source SHA,\nactor, run id, preview bucket/prefix, manifest key, and adapter steps, and is an\nauditable no-op when no aliases are requested.\n\n## Reusable Workflow Shape\n\nBuildchain ships `.github/workflows/.web-surface.yml` for repositories that want\nthe standard PR review and promotion flow without copying bespoke glue:\n\n```yaml\njobs:\n web-surface:\n uses: kungfu-systems/buildchain/.github/workflows/.web-surface.yml@v2\n with:\n build-command: npm run build\n verify-command: npm run check\n artifact-path: dist\n```\n\nThe reusable workflow maps GitHub events to Buildchain web-surface semantics:\n\n| Event | Buildchain behavior |\n| --- | --- |\n| `pull_request` opened / synchronized / reopened | validate, build, verify, and plan `preview` for `pr-N` |\n| `pull_request` closed | plan apply-mode cleanup for the `pr-N` preview alias and manifest |\n| `push` to `main` | validate, build, verify, plan and apply `staging` from the merged `main` SHA, then optionally open a production release PR |\n| `push` to `main` from a matching release PR merge | validate the associated release PR, plan `production`, and enter the configured GitHub Environment gate |\n| `workflow_dispatch` with `production-approved = true` | plan `production` and enter the configured GitHub Environment gate |\n\nThe optional `buildchain-ref` input is empty by default. Empty keeps the\nweb-surface run on the stable Buildchain runtime selected by the reusable\nworkflow ref, normally `@v2`. A trusted maintainer can expose a\n`workflow_dispatch` input and pass it through for one-off train validation.\nSee [`runtime-train-validation.md`](runtime-train-validation.md) for the shared\ntrain protocol and notification template:\n\n```yaml\non:\n workflow_dispatch:\n inputs:\n buildchain-ref:\n description: \"Temporary Buildchain runtime ref for trusted manual validation\"\n required: false\n default: \"\"\n\njobs:\n web-surface:\n uses: kungfu-systems/buildchain/.github/workflows/.web-surface.yml@v2\n with:\n buildchain-ref: ${{ inputs.buildchain-ref || '' }}\n build-command: pnpm run build\n verify-command: pnpm run check\n artifact-path: dist\n```\n\nOnly trusted `workflow_dispatch` runs by repository actors with write,\nmaintain, or admin permission may use a non-empty runtime override. Train refs\nsuch as `train/v2/v2.3/site-source-of-truth` are temporary validation refs, not\nstable production dependencies or pending merge targets. They may remain for a\nretention window after release as a fast-use and rollback channel, with old\ntrains handled by periodic Buildchain cleanup. The web-surface deployment\nmanifest records the resolved runtime SHA as `runtimeId` and the stable\nrollback ref as `rollbackPointer`.\n\nThe workflow deliberately plans and emits manifests by default. Live mutation is\nopt-in per channel:\n\n```yaml\npermissions:\n contents: read\n id-token: write\n pull-requests: write\n\njobs:\n web-surface:\n uses: kungfu-systems/buildchain/.github/workflows/.web-surface.yml@v2\n with:\n build-command: pnpm run build\n verify-command: pnpm run check\n artifact-path: dist\n preview-apply: true\n preview-cleanup-apply: true\n preview-aws-role-arn: arn:aws:iam::123456789012:role/site-preview-github-actions\n staging-apply: true\n staging-aws-role-arn: arn:aws:iam::123456789012:role/site-staging-github-actions\n production-apply: false\n production-release-on-main: false\n production-aws-role-arn: arn:aws:iam::123456789012:role/site-production-github-actions\n production-environment: production\n release-feedback-actor-privacy: public\n```\n\nWhen enabled, Buildchain owns the full release apply state machine:\n\n- PR preview deploys run `deploy-apply --dry-run false` with the preview role\n and update a single idempotent PR comment.\n- Closed PR cleanup runs `cleanup-apply --dry-run false` with the preview role\n only.\n- Pushes to `main` run staging `deploy-apply --dry-run false` with the staging\n role, then write a staging release feedback passport artifact and comment the\n associated merged PR with the staging URL, source SHA, artifact identity, run\n URL, and failure context when apply did not complete.\n- When `production-release-on-main=true`, successful staging applies open or\n update a Buildchain-owned release PR from\n `release/<channel>-<short-sha>` to `main`, unless the current push already\n came from a matching release PR merge. The release PR contains one empty\n release-intent commit, carries `production-release-label`, and includes the\n staging URLs, source SHA, artifact hash, and staging release-passport artifact\n link in the PR body.\n- Production release PR handoff is permission-aware. Staging apply and staging\n health remain successful even when the repository or organization has\n GitHub Actions workflow permissions set to read-only. In that case Buildchain\n records `release-pr-status=permission-denied`, uploads the release PR handoff\n summary/body plus staging release passport artifacts, and writes an exact\n manual `gh pr create` command to the step summary. Set\n `fail-on-release-pr-error=true` only when PR creation failure should fail the\n whole workflow.\n- Release pull requests that match the configured production gate get a\n Buildchain review comment with the staging URL and production target, so the\n operator can verify staging from the PR page and use merge as the approval\n action. Consumers do not need to hand-write `gh pr create` or production\n release-intent glue.\n- `production-apply=true` enables the production capability; it does not request\n production for every event. Ordinary `main` pushes remain staging-only and\n can create or update a release PR. Production runs only when the capability\n is enabled and either:\n - a `workflow_dispatch` passes `production-approved=true` and the triggering\n actor currently has `write`, `maintain`, or `admin` permission; or\n - `production-release-on-main=true` and the `main` push commit is associated\n with exactly one same-repository, merged release pull request matching\n `production-release-label` and `production-release-head-prefix`.\n The production job is then gated by the configured GitHub Environment.\n- Before production artifact download, Buildchain assembles a managed sealed\n publication capability from the exact source/runtime SHAs, production plan\n and artifact hash, a qualifying pre-publication controller receipt, the\n trusted manual or reviewed-release-PR decision, production Environment and\n AWS role target, an ephemeral-runner receipt, and a fresh nonce. Production\n revalidates that capability against the downloaded plan before it downloads\n product bytes. The later AWS OIDC exchange remains the provider's final\n transaction-time authorization decision and fails closed before deploy apply.\n- The `publication-*-json` inputs are an advanced external-evidence\n compatibility path, not a prerequisite for the standard release-PR or trusted\n manual mechanisms. External evidence must now include\n `publication-gate-aggregate-json`; supplying only a partial set still fails\n closed.\n- Production apply writes a production release feedback passport artifact and\n comments the release PR with the production URL, source SHA, artifact\n identity, run URL, rollback pointer, and failure context when apply did not\n complete.\n\nThe feedback passport records the release responsibility chain:\n\n- human decision actor;\n- trigger actor;\n- runner/execution actor;\n- OIDC/deploy identity reference;\n- decision type and time;\n- source event, PR number, merge commit, and required gate label/head-prefix.\n\n`release-feedback-actor-privacy` controls actor values in the passport and\ncomments. `public` records GitHub actor names, `redacted` records only the actor\nrole, and `private-ref` records a stable private reference hash without exposing\nthe actor name.\n\nFor release-PR publishing, callers opt in explicitly:\n\n```yaml\njobs:\n web-surface:\n uses: kungfu-systems/buildchain/.github/workflows/.web-surface.yml@v2\n with:\n build-command: npm run build\n verify-command: npm run check\n artifact-path: dist\n production-apply: true\n production-release-on-main: true\n production-release-label: buildchain-release\n production-release-head-prefix: release/\n production-release-branch-channel: production\n production-release-pr-mode: auto\n production-aws-role-arn: arn:aws:iam::123456789012:role/site-production-github-actions\n production-environment: production\n```\n\nKeep `production-apply` enabled in the caller when the repository supports\nproduction. Buildchain derives whether the current event may use that\ncapability: an ordinary `main` push plans and applies staging, a matching\nreviewed release PR merge authorizes production, and an approved trusted manual\ndispatch authorizes production. Inputs from an untrusted event cannot turn that\ndecision on.\n\n`production-release-pr-mode` controls the post-staging handoff:\n\n| Mode | Behavior |\n| --- | --- |\n| `auto` | Generate release PR facts, create/update the empty release-intent branch and PR, and label it when token permissions allow. This is the default. |\n| `summary-only` | Generate and upload release PR facts, body, passport evidence, and manual command, but do not call the GitHub PR API. |\n| `disabled` | Record a disabled handoff and skip release PR API calls. |\n\nAutomatic release PR creation normally uses the workflow `github.token`.\nConsumers that cannot enable \"GitHub Actions can create and approve pull\nrequests\" globally should prefer the first-class GitHub App path. Pass the App\nclient id as an input and the private key as a reusable workflow secret; Buildchain\ncreates an installation token inside the release PR job and uses it only for the\nrelease-intent branch, PR, and label operations:\n\n```yaml\nwith:\n production-release-app-client-id: ${{ vars.KUNGFU_RELEASE_APP_CLIENT_ID }}\nsecrets:\n production-release-app-private-key: ${{ secrets.KUNGFU_RELEASE_APP_PRIVATE_KEY }}\n```\n\nWhen either side of the App configuration is missing, Buildchain does not hide\nthat behind the fallback `github.token`. The handoff JSON and job summary report\n`status: \"app-token-unavailable\"` with an `appTokenStatus` such as\n`missing-client-id`, `missing-private-key`, or `create-failed`, and still include\nthe manual PR creation command. If the repository intentionally uses another\nnarrow token, pass it through `production-release-pr-token`.\n\n`production-release-app-id` remains accepted as a deprecated alias for the input\nname, but the value should be the GitHub App client id. GitHub App numeric App\nIDs and client IDs are distinct, and Buildchain passes the value to\n`actions/create-github-app-token` through its non-deprecated `client-id` input so\nnew runs do not emit the deprecated `app-id` warning.\n\nIf a repository already generates its own narrow token or PAT, it can still pass\nthat through `production-release-pr-token`:\n\n```yaml\nwith:\n production-release-pr-token: ${{ secrets.BUILDCHAIN_RELEASE_PR_TOKEN }}\n```\n\nToken priority is: generated GitHub App installation token,\n`production-release-pr-token`, then `github.token`.\n\nThe merge button becomes the production approval only for a PR that carries the\nrelease label and comes from the configured source-branch prefix. Ordinary pull\nrequests merged into `main` deploy staging and open a release-intent PR; merging\nthat release PR triggers production. A release PR merge push does not open\nanother release PR.\n\nApply-only inputs are validated before the caller build or verification command\nruns. If the current event would run preview, staging, or production apply,\nmissing role inputs, a production apply without `production-approved=true` on\nmanual dispatch, or a manual actor without repository write authority fail\nimmediately instead of spending the build and plan jobs first.\n\nCallers must grant `id-token: write` for OIDC role assumption. Preview comments\nneed `pull-requests: write`. Automatic release PR creation also needs\n`contents: write`, `pull-requests: write`, and `issues: write` so Buildchain can\ncreate the release branch, write the empty release-intent commit, open or update\nthe PR, and apply the release label. If these permissions are unavailable,\nBuildchain degrades the release handoff instead of marking a successful staging\ndeployment as failed, unless `fail-on-release-pr-error=true`. The AWS roles remain caller-owned and\nshould be scoped by channel: preview can mutate only preview resources, staging\ncan mutate only staging resources, and production can mutate only production\nresources.\n\nApply mode fails closed when the deploy config still contains placeholder AWS\ntargets such as `pending-preview-distribution`. Planning can use placeholders\nfor dry-run-only design work, but live apply requires concrete bucket and\nCloudFront distribution identifiers.\n\n## Site Repository Shape\n\nA site repository can start with:\n\n```toml\nschema = 1\n\n[project]\ntype = \"web-surface\"\nname = \"site-kungfu-tech\"\nsite = \"kungfu-tech\"\n\n[lifecycle.build]\ncommand = \"pnpm run build\"\n\n[lifecycle.verify]\ncommand = \"pnpm run check\"\n```\n\nThen add the channel, deploy, retention, and security declarations shown above.\nThe project may use pnpm, npm, yarn, Vite, Astro, Next static export, Sphinx,\nMkDocs, CMake-generated docs, or another lifecycle command source. Buildchain\nonly needs a deterministic artifact path and the manifest facts.\n\n## Boundaries\n\nBuildchain only performs live AWS mutations in explicit apply modes with\n`--dry-run false`. Production deploys must still be gated by a human-controlled\nworkflow, release, or GitHub Environment. DNS changes, staging auth\nimplementation, CloudFront distribution creation, and credential provisioning\nremain explicitly authorized infrastructure operations outside the web-surface\nartifact apply contract."
2129
+ "markdown": "# Web-Surface Deployment Contract\n\nBuildchain supports `project.type = \"web-surface\"` for repositories that publish\nsites, docs, product pages, operator consoles, or browser apps. These projects\nneed auditable deployment semantics, but they are not package release lines and\nshould not be forced into `dev/alpha/release` version-state automation.\n\nThe release object for a web surface is:\n\n```text\nsource commit + build artifact + deploy target + channel + deployment manifest\n```\n\nThis keeps the evidence chain clear:\n\n- the source SHA explains what code was built;\n- the artifact hash explains exactly what was deployed;\n- the channel explains who can see it and whether it is promotable;\n- the deploy target and adapter explain where it would be published;\n- the deployment manifest records retention, rollback, security, and secret\n reference metadata.\n\n## Configuration\n\n`.buildchain/buildchain.toml` is the source of truth. Web-surface projects must declare\npreview, staging, and production channels plus a deploy adapter for each.\n\n```toml\nschema = 1\n\n[project]\ntype = \"web-surface\"\nname = \"site-kungfu-tech\"\nsite = \"kungfu-tech\"\n\n[channels.preview]\nurl_pattern = \"https://{alias}.preview.kungfu.tech\"\nvisibility = \"ephemeral\"\nrequires_auth = false\nnoindex = true\n\n[channels.staging]\nurl = \"https://staging.kungfu.tech\"\nvisibility = \"protected\"\naccess_control = \"managed-network\"\nedge_auth = \"none\"\nnoindex = true\npromotable = true\n\n[channels.production]\nurl = \"https://kungfu.tech\"\nvisibility = \"public\"\ncanonical = true\nnoindex = false\n\n[deploy.preview]\nadapter = \"aws-s3-cloudfront\"\nbucket = \"kungfu-tech-preview\"\ncloudfront_distribution = \"E-PREVIEW\"\nartifact_path = \"dist\"\nsecret_refs = [\"AWS_ROLE_ARN\"]\n# Optional. Defaults to \"buildchain\".\n# Use \"external\" when an existing viewer-request CloudFront Function already\n# owns preview alias, surface-prefix, and directory-index routing.\ndirectory_index_rewrite = \"buildchain\"\n# Optional. Defaults to HTTP for public channels and S3 object evidence for\n# managed-network channels. Use \"s3-object\" when CI should verify uploaded\n# objects and manifests instead of waiting for public edge convergence.\nhealth_strategy = \"http\"\n```\n\n### Multi-Surface Host Mapping\n\nSome site repositories publish more than one first-class web surface from the\nsame artifact. For example, `site-libkungfu-dev` has a hub plus separate\nhostnames for core, Buildchain, and Kung Fu Decisions. These are not just\nnavigation paths; staging, production preflight, and post-deploy health checks\nmust verify host-level behavior for each surface.\n\nDeclare named surfaces with per-channel URLs:\n\n```toml\n[surfaces.hub]\npath = \"/\"\nproduction_url = \"https://libkungfu.dev\"\nstaging_url = \"https://staging.libkungfu.dev\"\npreview_url_pattern = \"https://{alias}.preview.libkungfu.dev\"\n\n[surfaces.core]\npath = \"/core/\"\nproduction_url = \"https://core.libkungfu.dev\"\nstaging_url = \"https://core.staging.libkungfu.dev\"\npreview_url_pattern = \"https://core-{alias}.preview.libkungfu.dev\"\n\n[surfaces.buildchain]\npath = \"/buildchain/\"\nproduction_url = \"https://buildchain.libkungfu.dev\"\nstaging_url = \"https://buildchain.staging.libkungfu.dev\"\npreview_url_pattern = \"https://buildchain-{alias}.preview.libkungfu.dev\"\n\n[surfaces.kfd]\npath = \"/kfd/\"\nproduction_url = \"https://kfd.libkungfu.dev\"\nstaging_url = \"https://kfd.staging.libkungfu.dev\"\npreview_url_pattern = \"https://kfd-{alias}.preview.libkungfu.dev\"\n```\n\nBuildchain resolves every `(channel, surface)` pair. A preview alias such as\n`pr-12` becomes:\n\n```text\nhub: https://pr-12.preview.libkungfu.dev\ncore: https://core-pr-12.preview.libkungfu.dev\nbuildchain: https://buildchain-pr-12.preview.libkungfu.dev\nkfd: https://kfd-pr-12.preview.libkungfu.dev\n```\n\nWhen `surfaces` is omitted, Buildchain preserves the legacy single-surface\ncontract by creating an implicit `default` surface from the channel URL. When a\nsurface is intentionally path-only, declare it explicitly:\n\n```toml\n[surfaces.docs]\npath = \"/docs/\"\npath_only = true\n```\n\n`path_only = true` is an exception, not the default. Without it, every named\nsurface must declare `preview_url_pattern`, `staging_url`, and\n`production_url`. This makes staging/production mismatches fail during\nvalidation instead of becoming invisible deploy drift.\n\nAdapter strategy remains explicit. The default `aws-s3-cloudfront` plan uses the\nchannel deploy target for every surface, and each binding records its own\nbucket, distribution id, object prefix, manifest key, source path, and URL. A\nchannel can override target details per surface:\n\n```toml\n[deploy.staging.surfaces.core]\nbucket = \"libkungfu-dev-core-staging\"\ncloudfront_distribution = \"E-CORE-STAGING\"\norigin_path = \"/core\"\n```\n\nBuildchain validates these hard constraints:\n\n- `channels.preview.url_pattern` is required and must contain the alias shape\n used by preview deployments.\n- `channels.staging.access_control` must protect staging. Supported modes are\n `managed-network`, `edge-basic-auth`, `oidc`, and `app-auth`.\n- `channels.staging.edge_auth` records whether the edge layer owns auth. Use\n `edge_auth = \"none\"` when staging is protected by managed network controls\n such as WAF/IP allowlists or VPN access.\n- `channels.staging.noindex = true` is required.\n- `channels.production.url` is required.\n- deploy adapters must be declared per channel.\n- named surfaces must declare first-class URLs for every channel unless\n `path_only = true` is explicitly set.\n- secret material must be declared as reference names, such as\n `secret_refs = [\"AWS_ROLE_ARN\"]`; inline secret-like deploy keys are rejected.\n\n### Floating Runtime Contract Lock\n\nWeb-surface repositories can consume the stable Buildchain workflow shell with a\nfloating ref, such as:\n\n```yaml\njobs:\n web:\n uses: kungfu-systems/buildchain/.github/workflows/.web-surface.yml@v2\n with:\n buildchain-contract-lock-path: .buildchain/contract-lock.json\n buildchain-contract-compatibility-policy: major-compatible\n buildchain-contract-drift-issue-mode: compatible-and-breaking\n build-command: pnpm build\n artifact-path: dist\n```\n\nThe caller repository commits `.buildchain/contract-lock.json` after reviewing an\naccepted Buildchain runtime SHA and contract digest. The reusable workflow then\nresolves the floating runtime to an immutable SHA, checks the lock before the\ncaller build command, and applies these rules:\n\n- unchanged lock: continue without feedback;\n- compatible drift: continue, write the drift summary, and open or update a\n caller-repository issue when permissions allow;\n- breaking drift: fail closed before rendering, deployment planning, deploy\n apply, or release publication.\n\nThe caller no longer needs to run `scripts/buildchain-contract-lock.mjs` inside\nits own build command. That check belongs to Buildchain because the actual\ncontract world is stored in the Buildchain runtime ref being used.\n\nSupported adapter names are:\n\n| Adapter | Initial use |\n| --- | --- |\n| `aws-s3-cloudfront` | Static site artifact sync plus CDN invalidation plan |\n| `aws-elastic-beanstalk` | Future dynamic app environment adapter |\n| `aws-ecs-service` | Future dynamic service adapter |\n\nThe channel ontology is independent of the adapter. A future dynamic staging\nenvironment still remains `channel = \"staging\"` with protected/noindex/security\nrequirements.\n\n## Preview Aliases\n\nPreview uses subdomains, not path prefixes:\n\n```text\nhttps://pr-123.preview.kungfu.tech\nhttps://sha-abcdef123456.preview.kungfu.tech\n```\n\nAlias semantics are explicit:\n\n| Alias | Meaning | Mutable | Retention |\n| --- | --- | --- | --- |\n| `pr-123` | Current preview for a pull request | yes | short-lived |\n| `sha-abcdef123456` | Immutable preview for one source SHA | no | longer-lived |\n\nThis allows PR comments to stay stable while preserving immutable evidence for a\nspecific source commit.\n\n## Deployment Manifest\n\nBuildchain emits a manifest with the deployment facts that matter for audit and\nrollback:\n\n```json\n{\n \"schemaVersion\": 1,\n \"contract\": \"kungfu-buildchain-web-surface-deployment\",\n \"site\": \"libkungfu-dev\",\n \"channel\": \"preview\",\n \"alias\": \"sha-abcdef123456\",\n \"url\": \"https://sha-abcdef123456.preview.libkungfu.dev\",\n \"generatedAt\": \"2026-07-01T00:00:00.000Z\",\n \"publishedAt\": \"2026-07-01T00:00:00.000Z\",\n \"reproducible\": true,\n \"timestampPolicy\": \"ci-injected\",\n \"deterministicInputs\": [\n \"web-surface artifact content\",\n \"buildchain.toml web-surface channels/deploy/surfaces\",\n \"sourceSha\",\n \"artifactHash\",\n \"deployment channel\",\n \"deployment alias\"\n ],\n \"sourceRevision\": \"...\",\n \"timestampPolicyDetails\": {\n \"contract\": \"kungfu-buildchain-surface-timestamp-policy\",\n \"timestampFields\": [\"generatedAt\", \"publishedAt\", \"deployedAt\"],\n \"timestampFieldsParticipateInArtifactDigest\": false,\n \"artifactDigestScope\": \"web-surface artifactHash excludes deployment manifest timestamps\"\n },\n \"sourceSha\": \"...\",\n \"artifactHash\": \"...\",\n \"deployTarget\": \"libkungfu-dev-preview\",\n \"adapter\": \"aws-s3-cloudfront\",\n \"deployedAt\": \"2026-07-01T00:00:00.000Z\",\n \"retentionClass\": \"preview-sha-immutable\",\n \"expiresAt\": \"2026-09-29T00:00:00.000Z\",\n \"accessControl\": \"none\",\n \"edgeAuth\": \"none\",\n \"noindex\": true,\n \"secretRefs\": [\"AWS_ROLE_ARN\"],\n \"surfaceBindings\": [\n {\n \"surface\": \"hub\",\n \"channel\": \"preview\",\n \"alias\": \"sha-abcdef123456\",\n \"url\": \"https://sha-abcdef123456.preview.libkungfu.dev\",\n \"sourcePath\": \"/\",\n \"artifactPathPrefix\": \"\",\n \"viewerPathPrefix\": \"/\",\n \"directoryIndex\": \"index.html\",\n \"directoryIndexResolution\": true,\n \"canonicalUrl\": \"https://libkungfu.dev\",\n \"bucket\": \"libkungfu-dev-preview\",\n \"distributionId\": \"E-PREVIEW\",\n \"originPath\": \"\",\n \"objectPrefix\": \"sha-abcdef123456\",\n \"manifestKey\": \".buildchain/deployments/sha-abcdef123456/hub.json\",\n \"routing\": {\n \"contract\": \"kungfu-buildchain-web-surface-path-prefix-rewrite\",\n \"viewerPathPrefix\": \"/\",\n \"artifactPathPrefix\": \"\",\n \"objectPrefix\": \"sha-abcdef123456\",\n \"directoryIndex\": \"index.html\",\n \"directoryIndexResolution\": true\n },\n \"smokeUrls\": [\n {\n \"kind\": \"root\",\n \"requestPath\": \"/\",\n \"url\": \"https://sha-abcdef123456.preview.libkungfu.dev/\",\n \"required\": true\n }\n ],\n \"noindex\": true,\n \"accessControl\": \"none\"\n }\n ]\n}\n```\n\nDynamic adapters can also fill `runtimeId`, `configFingerprint`,\n`healthCheck`, `migrationState`, `rollbackPointer`, and\n`rollbackLimitations`. Buildchain records secret reference names only, never\nsecret values.\n\nThe timestamp policy is shared with package site bundles. Public deployment\nmanifests should expose real workflow generation/publication times while\nseparately declaring why the deployed artifact remains reproducible. For\nweb-surface deployment manifests, `artifactHash` is the static site artifact\ndigest and does not include deployment timestamp fields; the manifest itself\nstill records those fields for human and agent audit.\n\n## Deploy Plans\n\nDeploy planning is the default behavior. It plans the adapter steps and writes\nmanifest JSON, but it does not touch AWS, DNS, CloudFront, or deployment\ncredentials.\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode deploy-plan \\\n --cwd fixtures/web-surface-shaped \\\n --source-sha aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \\\n --alias sha-aaaaaaaaaaaa\n```\n\nFor manifest-only output:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode manifest \\\n --cwd fixtures/web-surface-shaped \\\n --source-sha aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \\\n --alias pr-123 \\\n --output .buildchain/web-surface-manifest.json\n```\n\nThe CLI emits GitHub outputs when `GITHUB_OUTPUT` is present:\n\n- `web-surface-channel`\n- `web-surface-alias`\n- `web-surface-url`\n- `web-surface-urls-json`\n- `web-surface-artifact-hash`\n- `web-surface-manifest-json`\n\nThe reusable workflow resolves that same effective channel before running the\ncaller build or verify command. Both steps receive\n`BUILDCHAIN_WEB_SURFACE_CHANNEL` (`preview`, `staging`, or `production`) and\n`BUILDCHAIN_PREVIEW_ALIAS` for previews. Compatibility aliases\n`BUILDCHAIN_SURFACE_CHANNEL` and `BUILDCHAIN_WEB_SURFACE_ALIAS` are also\nprovided. Callers should consume these variables instead of reconstructing the\nrelease-intent state machine from raw GitHub events.\nAn unapproved manual canary resolves to `staging`; a trusted manual dispatch\nwith `production-approved=true` resolves to `production` through the same path.\n\n## Explicit Apply\n\n`deploy-apply` and `cleanup-apply` are explicit execution modes for the\n`aws-s3-cloudfront` static-site adapter. They still default to `--dry-run true`;\nlive AWS mutation requires `--dry-run false`.\n\nDeploy apply syncs the artifact, writes the deployment manifest, and invalidates\nCloudFront when a distribution id is configured:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode deploy-apply \\\n --cwd fixtures/web-surface-shaped \\\n --channel staging \\\n --source-sha aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \\\n --artifact-path dist \\\n --dry-run false \\\n --output .buildchain/web-surface-staging-apply.json\n```\n\n### Explicit cache classes\n\nThe S3/CloudFront adapter can declare cache metadata per deploy channel or\nsurface override:\n\n```toml\n[deploy.production]\nadapter = \"aws-s3-cloudfront\"\ncache_control_default = \"public,max-age=3600\"\ncache_control_mutable = \"public,max-age=300,must-revalidate\"\ncache_control_immutable = \"public,max-age=31536000,immutable\"\n```\n\n`cache_control_default` applies to the ordinary artifact sync.\n`cache_control_mutable` is then applied to HTML, JSON, XML, generated directory\nindex aliases, and the deployment manifest. `cache_control_immutable` applies\nto append-only publication roots discovered through the archive policy below.\nMutable metadata updates exclude those append-only roots, so HTML or JSON inside\nan immutable version archive keeps the immutable class.\nThe deploy plan, surface binding, apply operations, and deployment manifest all\nrecord the effective values. Existing consumers that omit these fields retain\ntheir prior upload behavior.\n\nCache metadata complements, rather than replaces, invalidation. Every deploy\nstill records and creates the exact surface wildcard and deployment-manifest\ninvalidation paths.\n\n### Immutable publication paths\n\nWhen a surface artifact contains `manifest.json` with\n`archivePolicy.contract = \"kungfu-buildchain-publication-archive-policy\"`,\nBuildchain treats every declared `publications[].versions[].immutablePath` as\nan append-only publication boundary. This applies identically to preview,\nstaging, and production adapters.\n\nThe adapter derives the protected archive root from those declared version\npaths and applies four ordered safeguards:\n\n1. every local immutable file is checked against an existing S3 object;\n2. missing files are uploaded with `aws s3 sync --no-overwrite` and a SHA-256\n checksum;\n3. every immutable file is checked again after upload, closing the race between\n the first check and the no-overwrite transfer;\n4. mutable site content keeps normal `sync --delete` behavior, but every parent\n or owning surface sync excludes the protected archive root from deletion.\n\nAn existing object with a different SHA-256 digest fails apply before mutable\ncontent is changed. Older objects without a stored S3 SHA-256 checksum are read\nand byte-hashed for compatibility. Directory-index alias writes are skipped\nunder protected roots so they cannot overwrite immutable route objects; viewer\nrequest rewriting remains the directory-index authority.\n\nThe deploy plan and manifest record `immutablePublication`,\n`mutableDeleteExcludes`, and the parent-surface coverage. Apply output records\n`immutablePreservation` plus every pre-check, no-overwrite sync, post-check, and\nmutable sync operation. Health output adds an `__immutable__` check proving that\nthe owning and parent surface syncs carried their required delete exclusions.\nThe runner must provide an AWS CLI version whose `s3 sync` supports\n`--no-overwrite`.\n\nFor multi-surface sites, each surface host is treated as a root-relative view\nof that surface's artifact path prefix. For example, a `buildchain` surface with\n`path = \"/buildchain/\"` and preview URL\n`https://buildchain-pr-29.preview.libkungfu.dev` syncs the artifact subtree\n`dist/buildchain/` to the preview object prefix `pr-29/buildchain`. A viewer\nrequest for `https://buildchain-pr-29.preview.libkungfu.dev/docs/` therefore\nresolves against the artifact's `dist/buildchain/docs/index.html`, not\n`dist/docs/index.html` and not the hub surface root. The deployment manifest\nrecords this as `routing.contract =\n\"kungfu-buildchain-web-surface-path-prefix-rewrite\"` with\n`viewerPathPrefix = \"/\"`, `artifactPathPrefix = \"buildchain\"`, and\n`directoryIndexResolution = true`.\n\nWhen a surface uses an S3 object prefix, directory-index routing must be handled\nat the viewer-request layer. By default, `directory_index_rewrite =\n\"buildchain\"` makes Buildchain install or update one CloudFront Function per\ndistribution before uploading payloads. The function rewrites any request path\nending in `/` to the corresponding `index.html`, so\n`https://buildchain-pr-29.preview.libkungfu.dev/` resolves to\n`pr-29/buildchain/index.html` and\n`https://buildchain-pr-29.preview.libkungfu.dev/docs/` resolves to\n`pr-29/buildchain/docs/index.html`. This keeps multi-host preview roots\ncompatible with S3 REST origins, where copying alias objects such as\n`pr-29/buildchain` or `pr-29/buildchain/` is not a reliable substitute for an\nedge rewrite.\n\nIf the distribution already has a viewer-request function that owns preview\nalias routing and surface-prefix routing, set `directory_index_rewrite =\n\"external\"` on the deploy channel or surface override. In that mode Buildchain\ndoes not create, update, or attach a generic directory-index function. Instead,\nthe deployment manifest records `directoryIndexRewrite = \"external\"` and\n`directoryIndexStrategy = \"external-viewer-request-function\"`, then the normal\nhealth check still verifies every required root and nested surface URL. This is\nthe correct contract for shared preview distributions such as\n`site-libkungfu-dev`, where a generic function cannot replace the existing\nprefix router.\n\nBuildchain still writes directory-index alias objects during apply as\ncompatibility evidence, but root correctness comes from the viewer-request\nrewrite contract, not from extensionless S3 keys. If Buildchain-managed mode\nfinds a distribution with a different viewer-request function, apply fails\nclosed and records that conflict in the apply result instead of silently serving\n403s. If CloudFront rejects `UpdateDistribution` because its optimistic-lock\nETag became stale, Buildchain re-reads the distribution and retries with the\nnew ETag at most twice. A concurrent update that already attached the intended\nfunction is accepted as converged; a different viewer-request function or any\nnon-ETag AWS error still fails immediately. The reusable workflow uploads\n`buildchain-web-surface-*-diagnostics`\nartifacts containing the apply and health JSON so the failing AWS operation or\nHTTP check is visible from the consumer run.\n\nIt can also execute a previously saved deploy plan. In that mode Buildchain\nrecomputes the local artifact hash before running AWS commands and fails closed\nif the artifact no longer matches the saved plan. Before any adapter operation,\nit also checks channel-aware JSON manifests in the artifact: top-level\n`canonicalHost` and declared `pages[].host` facts must belong to the plan's\nsurface hosts. A production plan therefore rejects staging/preview host facts\nbefore AWS apply:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode deploy-apply \\\n --cwd fixtures/web-surface-shaped \\\n --plan .buildchain/web-surface-staging-plan.json \\\n --dry-run false \\\n --output .buildchain/web-surface-staging-apply.json\n```\n\nCleanup apply deletes preview content, deletes the preview manifest, and\ninvalidates CloudFront:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode cleanup-apply \\\n --cwd fixtures/web-surface-shaped \\\n --event pull-request-closed \\\n --pull-number 123 \\\n --source-sha aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \\\n --dry-run false \\\n --output .buildchain/web-surface-cleanup-apply.json\n```\n\nCleanup apply can also execute a saved cleanup plan:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode cleanup-apply \\\n --cwd fixtures/web-surface-shaped \\\n --plan .buildchain/web-surface-cleanup-plan.json \\\n --dry-run false \\\n --output .buildchain/web-surface-cleanup-apply.json\n```\n\nApply output records the channel, alias, source SHA, artifact hash, target\nbucket, object prefix, manifest key, all surface URLs, all surface bindings, CDN\ninvalidation paths, actor/run metadata, immutable preservation evidence, and\nevery adapter operation with\n`executed`, `exitCode`, `stdout`, and `stderr`. If an operation fails,\nBuildchain records the failed operation, stops subsequent adapter operations,\nand exits non-zero after writing the result JSON. Buildchain records secret\nreference names only; the runner must provide the AWS CLI and credentials\noutside Buildchain, typically through OIDC and the declared `secret_refs`.\n\n## Production Preflight And Health\n\nProduction promotion is not just `deploy-apply --channel production`. Before a\nlive production apply, the reusable workflow runs:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode production-preflight \\\n --cwd fixtures/web-surface-shaped \\\n --plan .buildchain/web-surface-production-plan.json \\\n --execute true \\\n --output .buildchain/web-surface-production-preflight.json\n```\n\nThe production preflight checks that:\n\n- `channels.production` is canonical and indexable;\n- every surface has concrete production bucket and CloudFront targets;\n- every production surface URL is HTTPS;\n- the production AWS role can inspect the declared bucket and distribution;\n- CloudFront aliases cover every surface host, including product hosts such as\n `kfd.libkungfu.dev`;\n- DNS resolves for every surface host.\n\nAfter preview, staging, and production apply, the workflow runs:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode health-check \\\n --cwd fixtures/web-surface-shaped \\\n --result .buildchain/web-surface-production-apply.json \\\n --output .buildchain/web-surface-production-health.json\n```\n\nWhen the apply result includes CloudFront invalidations from the\n`aws-s3-cloudfront` adapter, health check waits for those invalidations to reach\n`Completed` before fetching public smoke URLs. This avoids reporting stale\nCloudFront 403 responses as deployment failures immediately after a successful\nS3 sync and invalidation request.\n\nAfter the invalidation wait, HTTP smoke checks also retry transient 403, 404, and\n5xx responses before recording failure. This keeps the public health signal\nstrict while absorbing short CloudFront edge propagation windows that can remain\nvisible after the invalidation waiter returns. By default, Buildchain attempts\neach HTTP smoke URL 12 times with a 10 second interval. Consumers can override\nthat window with `BUILDCHAIN_WEB_SURFACE_HEALTH_HTTP_RETRY_ATTEMPTS` and\n`BUILDCHAIN_WEB_SURFACE_HEALTH_HTTP_RETRY_INTERVAL_MS` when they need a\nsite-specific health policy.\n\nThe health check fetches every surface root URL and any nested smoke URLs\nrecorded in each surface binding. Nested smoke URLs are derived from nested HTML\nartifact files under the surface path prefix, with directory index resolution\nsuch as `dist/buildchain/docs/index.html` becoming `/docs/` on the buildchain\npreview host. If a surface has no nested HTML route, Buildchain records only\nthe root smoke URL; absence of nested HTML is not a deployment failure. When a\nnested route is present, the check fails closed if a deploy reports success but\nthat child page returns 403 or another unexpected status. Surface root checks\nexpect the apply result to have installed the directory-index rewrite, so a\nmulti-host preview root such as `https://buildchain-pr-29.preview.libkungfu.dev/`\nmust resolve to the surface `index.html`, not the bare prefix directory.\nProduction additionally fails if a response is unreachable, returns an\nunexpected status, or still sends `x-robots-tag: noindex`. The health check also\nverifies that each surface binding recorded a deployment manifest pointer. The\nproduction release passport embeds the deploy plan, apply result, production\npreflight, and health check so a reviewer or agent can audit why the production\nsite changed and whether every declared host and every existing nested route was\nactually covered.\n\nPublic channels can opt into object-level health with\n`deploy.<channel>.health_strategy = \"s3-object\"` when the deployment contract is\nalready covered by S3 manifest/object writes and public edge convergence is not\nthe right CI gate. This is useful for preview distributions whose viewer-request\nrouting is owned by an external CloudFront Function. The channel remains public;\nonly the CI health evidence changes from HTTP fetches to S3 `head-object`\nchecks.\n\nChannels declared with `access_control = \"managed-network\"` use a different\nhealth strategy by default. Buildchain does not require a GitHub-hosted runner\nto fetch a URL that is intentionally reachable only from an approved network.\nInstead, after a live apply the health check uses the deploy role to run S3\n`head-object` checks for each surface manifest and the smoke target object, such\nas the surface `index.html` or a nested `docs/index.html`. The check records\n`healthStrategy = \"s3-object\"` and skips the public HTTP fetch. Dry-run and\nplan-only checks fall back to deployment evidence: each surface must have a\nmanifest key, bucket, object prefix, `sync-static-artifact`, and\n`write-deployment-manifest` evidence, recorded as\n`healthStrategy = \"deployment-evidence\"`. If the workflow is running on a runner\nthat is allowed to reach the managed network, set\n`BUILDCHAIN_WEB_SURFACE_HEALTH_ALLOWED_RUNNER=true` or pass\n`--allowed-managed-network-runner true` to keep the normal HTTP smoke checks.\nSet `BUILDCHAIN_WEB_SURFACE_HEALTH_S3_OBJECTS=false` or pass\n`--managed-network-s3-object-verification false` only when an external channel\npolicy owns managed-network object verification.\n\n## Cleanup Plans\n\nPreview cleanup is an auditable cleanup contract. It can run as a dry-run plan,\nan apply-mode plan, or the explicit `cleanup-apply` executor with preview-only\ncredentials:\n\n```bash\nnode scripts/web-surface.mjs \\\n --mode cleanup-plan \\\n --cwd fixtures/web-surface-shaped \\\n --event pull-request-closed \\\n --pull-number 123 \\\n --aliases pr-123,sha-abcdef123456\n```\n\nThe plan and apply result keep mutable PR aliases and immutable SHA aliases\ndistinct so a caller can expire them with different retention windows. Closed-PR\ncleanup can derive `pr-N` from `--pull-number`, records the event, source SHA,\nactor, run id, preview bucket/prefix, manifest key, and adapter steps, and is an\nauditable no-op when no aliases are requested.\n\n## Reusable Workflow Shape\n\nBuildchain ships `.github/workflows/.web-surface.yml` for repositories that want\nthe standard PR review and promotion flow without copying bespoke glue:\n\n```yaml\njobs:\n web-surface:\n uses: kungfu-systems/buildchain/.github/workflows/.web-surface.yml@v2\n with:\n build-command: npm run build\n verify-command: npm run check\n artifact-path: dist\n```\n\nThe reusable workflow maps GitHub events to Buildchain web-surface semantics:\n\n| Event | Buildchain behavior |\n| --- | --- |\n| `pull_request` opened / synchronized / reopened | validate, build, verify, and plan `preview` for `pr-N` |\n| `pull_request` closed | plan apply-mode cleanup for the `pr-N` preview alias and manifest |\n| `push` to `main` | validate, build, verify, plan and apply `staging` from the merged `main` SHA, then optionally open a production release PR |\n| `push` to `main` from a matching release PR merge | validate the associated release PR, plan `production`, and enter the configured GitHub Environment gate |\n| `workflow_dispatch` with `production-approved = true` | plan `production` and enter the configured GitHub Environment gate |\n\nThe optional `buildchain-ref` input is empty by default. Empty keeps the\nweb-surface run on the stable Buildchain runtime selected by the reusable\nworkflow ref, normally `@v2`. A trusted maintainer can expose a\n`workflow_dispatch` input and pass it through for one-off train validation.\nSee [`runtime-train-validation.md`](runtime-train-validation.md) for the shared\ntrain protocol and notification template:\n\n```yaml\non:\n workflow_dispatch:\n inputs:\n buildchain-ref:\n description: \"Temporary Buildchain runtime ref for trusted manual validation\"\n required: false\n default: \"\"\n\njobs:\n web-surface:\n uses: kungfu-systems/buildchain/.github/workflows/.web-surface.yml@v2\n with:\n buildchain-ref: ${{ inputs.buildchain-ref || '' }}\n build-command: pnpm run build\n verify-command: pnpm run check\n artifact-path: dist\n```\n\nOnly trusted `workflow_dispatch` runs by repository actors with write,\nmaintain, or admin permission may use a non-empty runtime override. Train refs\nsuch as `train/v2/v2.3/site-source-of-truth` are temporary validation refs, not\nstable production dependencies or pending merge targets. They may remain for a\nretention window after release as a fast-use and rollback channel, with old\ntrains handled by periodic Buildchain cleanup. The web-surface deployment\nmanifest records the resolved runtime SHA as `runtimeId` and the stable\nrollback ref as `rollbackPointer`.\n\nThe workflow deliberately plans and emits manifests by default. Live mutation is\nopt-in per channel:\n\n```yaml\npermissions:\n contents: read\n id-token: write\n pull-requests: write\n\njobs:\n web-surface:\n uses: kungfu-systems/buildchain/.github/workflows/.web-surface.yml@v2\n with:\n build-command: pnpm run build\n verify-command: pnpm run check\n artifact-path: dist\n preview-apply: true\n preview-cleanup-apply: true\n preview-aws-role-arn: arn:aws:iam::123456789012:role/site-preview-github-actions\n staging-apply: true\n staging-aws-role-arn: arn:aws:iam::123456789012:role/site-staging-github-actions\n production-apply: false\n production-release-on-main: false\n production-aws-role-arn: arn:aws:iam::123456789012:role/site-production-github-actions\n production-environment: production\n release-feedback-actor-privacy: public\n```\n\nWhen enabled, Buildchain owns the full release apply state machine:\n\n- PR preview deploys run `deploy-apply --dry-run false` with the preview role\n and update a single idempotent PR comment.\n- Closed PR cleanup runs `cleanup-apply --dry-run false` with the preview role\n only.\n- Pushes to `main` run staging `deploy-apply --dry-run false` with the staging\n role, then write a staging release feedback passport artifact and comment the\n associated merged PR with the staging URL, source SHA, artifact identity, run\n URL, and failure context when apply did not complete.\n- When `production-release-on-main=true`, successful staging applies open or\n update a Buildchain-owned release PR from\n `release/<channel>-<short-sha>` to `main`, unless the current push already\n came from a matching release PR merge. The release PR contains one empty\n release-intent commit, carries `production-release-label`, and includes the\n staging URLs, source SHA, artifact hash, and staging release-passport artifact\n link in the PR body.\n- Production release PR handoff is permission-aware. Staging apply and staging\n health remain successful even when the repository or organization has\n GitHub Actions workflow permissions set to read-only. In that case Buildchain\n records `release-pr-status=permission-denied`, uploads the release PR handoff\n summary/body plus staging release passport artifacts, and writes an exact\n manual `gh pr create` command to the step summary. Set\n `fail-on-release-pr-error=true` only when PR creation failure should fail the\n whole workflow.\n- Release pull requests that match the configured production gate get a\n Buildchain review comment with the staging URL and production target, so the\n operator can verify staging from the PR page and use merge as the approval\n action. Consumers do not need to hand-write `gh pr create` or production\n release-intent glue.\n- `production-apply=true` enables the production capability; it does not request\n production for every event. Ordinary `main` pushes remain staging-only and\n can create or update a release PR. Production runs only when the capability\n is enabled and either:\n - a `workflow_dispatch` passes `production-approved=true` and the triggering\n actor currently has `write`, `maintain`, or `admin` permission; or\n - `production-release-on-main=true` and the `main` push commit is associated\n with exactly one same-repository, merged release pull request matching\n `production-release-label` and `production-release-head-prefix`.\n The production job is then gated by the configured GitHub Environment.\n- Before production artifact download, Buildchain assembles a managed sealed\n publication capability from the exact source/runtime SHAs, production plan\n and artifact hash, a qualifying pre-publication controller receipt, the\n trusted manual or reviewed-release-PR decision, production Environment and\n AWS role target, an ephemeral-runner receipt, and a fresh nonce. Production\n revalidates that capability against the downloaded plan before it downloads\n product bytes. The later AWS OIDC exchange remains the provider's final\n transaction-time authorization decision and fails closed before deploy apply.\n- The `publication-*-json` inputs are an advanced external-evidence\n compatibility path, not a prerequisite for the standard release-PR or trusted\n manual mechanisms. External evidence must now include\n `publication-gate-aggregate-json`; supplying only a partial set still fails\n closed.\n- Production apply writes a production release feedback passport artifact and\n comments the release PR with the production URL, source SHA, artifact\n identity, run URL, rollback pointer, and failure context when apply did not\n complete.\n\nThe feedback passport records the release responsibility chain:\n\n- human decision actor;\n- trigger actor;\n- runner/execution actor;\n- OIDC/deploy identity reference;\n- decision type and time;\n- source event, PR number, merge commit, and required gate label/head-prefix.\n\n`release-feedback-actor-privacy` controls actor values in the passport and\ncomments. `public` records GitHub actor names, `redacted` records only the actor\nrole, and `private-ref` records a stable private reference hash without exposing\nthe actor name.\n\nFor release-PR publishing, callers opt in explicitly:\n\n```yaml\njobs:\n web-surface:\n uses: kungfu-systems/buildchain/.github/workflows/.web-surface.yml@v2\n with:\n build-command: npm run build\n verify-command: npm run check\n artifact-path: dist\n production-apply: true\n production-release-on-main: true\n production-release-label: buildchain-release\n production-release-head-prefix: release/\n production-release-branch-channel: production\n production-release-pr-mode: auto\n production-aws-role-arn: arn:aws:iam::123456789012:role/site-production-github-actions\n production-environment: production\n```\n\nKeep `production-apply` enabled in the caller when the repository supports\nproduction. Buildchain derives whether the current event may use that\ncapability: an ordinary `main` push plans and applies staging, a matching\nreviewed release PR merge authorizes production, and an approved trusted manual\ndispatch authorizes production. Inputs from an untrusted event cannot turn that\ndecision on.\n\n`production-release-pr-mode` controls the post-staging handoff:\n\n| Mode | Behavior |\n| --- | --- |\n| `auto` | Generate release PR facts, create/update the empty release-intent branch and PR, and label it when token permissions allow. This is the default. |\n| `summary-only` | Generate and upload release PR facts, body, passport evidence, and manual command, but do not call the GitHub PR API. |\n| `disabled` | Record a disabled handoff and skip release PR API calls. |\n\nAutomatic release PR creation normally uses the workflow `github.token`.\nConsumers that cannot enable \"GitHub Actions can create and approve pull\nrequests\" globally should prefer the first-class GitHub App path. Pass the App\nclient id as an input and the private key as a reusable workflow secret; Buildchain\ncreates an installation token inside the release PR job and uses it only for the\nrelease-intent branch, PR, and label operations:\n\n```yaml\nwith:\n production-release-app-client-id: ${{ vars.KUNGFU_RELEASE_APP_CLIENT_ID }}\nsecrets:\n production-release-app-private-key: ${{ secrets.KUNGFU_RELEASE_APP_PRIVATE_KEY }}\n```\n\nWhen either side of the App configuration is missing, Buildchain does not hide\nthat behind the fallback `github.token`. The handoff JSON and job summary report\n`status: \"app-token-unavailable\"` with an `appTokenStatus` such as\n`missing-client-id`, `missing-private-key`, or `create-failed`, and still include\nthe manual PR creation command. If the repository intentionally uses another\nnarrow token, pass it through `production-release-pr-token`.\n\n`production-release-app-id` remains accepted as a deprecated alias for the input\nname, but the value should be the GitHub App client id. GitHub App numeric App\nIDs and client IDs are distinct, and Buildchain passes the value to\n`actions/create-github-app-token` through its non-deprecated `client-id` input so\nnew runs do not emit the deprecated `app-id` warning.\n\nIf a repository already generates its own narrow token or PAT, it can still pass\nthat through `production-release-pr-token`:\n\n```yaml\nwith:\n production-release-pr-token: ${{ secrets.BUILDCHAIN_RELEASE_PR_TOKEN }}\n```\n\nToken priority is: generated GitHub App installation token,\n`production-release-pr-token`, then `github.token`.\n\nThe merge button becomes the production approval only for a PR that carries the\nrelease label and comes from the configured source-branch prefix. Ordinary pull\nrequests merged into `main` deploy staging and open a release-intent PR; merging\nthat release PR triggers production. A release PR merge push does not open\nanother release PR.\n\nApply-only inputs are validated before the caller build or verification command\nruns. If the current event would run preview, staging, or production apply,\nmissing role inputs, a production apply without `production-approved=true` on\nmanual dispatch, or a manual actor without repository write authority fail\nimmediately instead of spending the build and plan jobs first.\n\nCallers must grant `id-token: write` for OIDC role assumption. Preview comments\nneed `pull-requests: write`. Automatic release PR creation also needs\n`contents: write`, `pull-requests: write`, and `issues: write` so Buildchain can\ncreate the release branch, write the empty release-intent commit, open or update\nthe PR, and apply the release label. If these permissions are unavailable,\nBuildchain degrades the release handoff instead of marking a successful staging\ndeployment as failed, unless `fail-on-release-pr-error=true`. The AWS roles remain caller-owned and\nshould be scoped by channel: preview can mutate only preview resources, staging\ncan mutate only staging resources, and production can mutate only production\nresources.\n\nApply mode fails closed when the deploy config still contains placeholder AWS\ntargets such as `pending-preview-distribution`. Planning can use placeholders\nfor dry-run-only design work, but live apply requires concrete bucket and\nCloudFront distribution identifiers.\n\n## Site Repository Shape\n\nA site repository can start with:\n\n```toml\nschema = 1\n\n[project]\ntype = \"web-surface\"\nname = \"site-kungfu-tech\"\nsite = \"kungfu-tech\"\n\n[lifecycle.build]\ncommand = \"pnpm run build\"\n\n[lifecycle.verify]\ncommand = \"pnpm run check\"\n```\n\nThen add the channel, deploy, retention, and security declarations shown above.\nThe project may use pnpm, npm, yarn, Vite, Astro, Next static export, Sphinx,\nMkDocs, CMake-generated docs, or another lifecycle command source. Buildchain\nonly needs a deterministic artifact path and the manifest facts.\n\n## Boundaries\n\nBuildchain only performs live AWS mutations in explicit apply modes with\n`--dry-run false`. Production deploys must still be gated by a human-controlled\nworkflow, release, or GitHub Environment. DNS changes, staging auth\nimplementation, CloudFront distribution creation, and credential provisioning\nremain explicitly authorized infrastructure operations outside the web-surface\nartifact apply contract."
2125
2130
  },
2126
2131
  {
2127
2132
  "id": "fixture:infra-contract-aws-cdk-shaped",
@@ -3738,7 +3738,7 @@
3738
3738
  "pageRegistryPath": "dist/site/page-registry.json",
3739
3739
  "cliRegistryDigest": "07802d410c2111838c8c5f3d93392d7e8205ba64ab4c76ce594f09864ab5baaf",
3740
3740
  "workflowRegistryDigest": "a954f67672292e16be1f4f663a98d0c69285f7359a43d5d6333b3ffcf6463c35",
3741
- "pageRegistryDigest": "21cef72eb7210cf206d4d6797d3467ad0e196dc30cf018aed1921528c19360d9"
3741
+ "pageRegistryDigest": "75384a857698af54b7a739b40b6eefe0bb641e90bae584c47dd1e2c0b7aa8b2b"
3742
3742
  },
3743
3743
  "comparison": {
3744
3744
  "missingCliRegistry": [],
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "contract": "kungfu-buildchain-publication-release-registry",
4
- "generatedAt": "2026-07-22T09:42:53.063Z",
5
- "publishedAt": "2026-07-22T09:42:53.063Z",
4
+ "generatedAt": "2026-07-22T10:03:39.987Z",
5
+ "publishedAt": "2026-07-22T10:03:39.987Z",
6
6
  "reproducible": true,
7
7
  "timestampPolicy": "ci-injected",
8
8
  "deterministicInputs": [
@@ -19,7 +19,7 @@
19
19
  "declared Buildchain surface manifest contract"
20
20
  ],
21
21
  "sourceDateEpoch": "0",
22
- "sourceRevision": "f092fb829717f4cd61d44522c9f96322d819fcef",
22
+ "sourceRevision": "473c1be9602573a533aac703e8f0802eda27e430",
23
23
  "timestampPolicyDetails": {
24
24
  "contract": "kungfu-buildchain-surface-timestamp-policy",
25
25
  "timestampFields": [
@@ -32,7 +32,7 @@
32
32
  },
33
33
  "package": {
34
34
  "name": "@kungfu-tech/buildchain",
35
- "version": "2.14.15",
35
+ "version": "2.14.16-alpha.0",
36
36
  "versionSource": "package.json#version"
37
37
  },
38
38
  "sourceKind": "package-site-bundle",
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "contract": "kungfu-buildchain-site-manifest",
4
- "generatedAt": "2026-07-22T09:42:53.063Z",
5
- "publishedAt": "2026-07-22T09:42:53.063Z",
4
+ "generatedAt": "2026-07-22T10:03:39.987Z",
5
+ "publishedAt": "2026-07-22T10:03:39.987Z",
6
6
  "reproducible": true,
7
7
  "timestampPolicy": "ci-injected",
8
8
  "deterministicInputs": [
@@ -19,7 +19,7 @@
19
19
  "declared Buildchain surface manifest contract"
20
20
  ],
21
21
  "sourceDateEpoch": "0",
22
- "sourceRevision": "f092fb829717f4cd61d44522c9f96322d819fcef",
22
+ "sourceRevision": "473c1be9602573a533aac703e8f0802eda27e430",
23
23
  "timestampPolicyDetails": {
24
24
  "contract": "kungfu-buildchain-surface-timestamp-policy",
25
25
  "timestampFields": [
@@ -37,7 +37,7 @@
37
37
  },
38
38
  "package": {
39
39
  "name": "@kungfu-tech/buildchain",
40
- "version": "2.14.15",
40
+ "version": "2.14.16-alpha.0",
41
41
  "versionSource": "package.json#version"
42
42
  },
43
43
  "entrypoint": "buildchain-site.json",
@@ -277,7 +277,7 @@
277
277
  "path": "docs/web-surface-deployments.md",
278
278
  "plane": "use",
279
279
  "exists": true,
280
- "digest": "sha256:efbfc97a947978e61c79dac9d67f87050b1bef2297617303340af8aa499703c9"
280
+ "digest": "sha256:ecdece4b7d916b7d8b323db68c5d81c533d67348c71907b46eb97d3c2fe432ba"
281
281
  }
282
282
  ],
283
283
  "facts": [
@@ -381,6 +381,33 @@ node scripts/web-surface.mjs \
381
381
  --output .buildchain/web-surface-staging-apply.json
382
382
  ```
383
383
 
384
+ ### Explicit cache classes
385
+
386
+ The S3/CloudFront adapter can declare cache metadata per deploy channel or
387
+ surface override:
388
+
389
+ ```toml
390
+ [deploy.production]
391
+ adapter = "aws-s3-cloudfront"
392
+ cache_control_default = "public,max-age=3600"
393
+ cache_control_mutable = "public,max-age=300,must-revalidate"
394
+ cache_control_immutable = "public,max-age=31536000,immutable"
395
+ ```
396
+
397
+ `cache_control_default` applies to the ordinary artifact sync.
398
+ `cache_control_mutable` is then applied to HTML, JSON, XML, generated directory
399
+ index aliases, and the deployment manifest. `cache_control_immutable` applies
400
+ to append-only publication roots discovered through the archive policy below.
401
+ Mutable metadata updates exclude those append-only roots, so HTML or JSON inside
402
+ an immutable version archive keeps the immutable class.
403
+ The deploy plan, surface binding, apply operations, and deployment manifest all
404
+ record the effective values. Existing consumers that omit these fields retain
405
+ their prior upload behavior.
406
+
407
+ Cache metadata complements, rather than replaces, invalidation. Every deploy
408
+ still records and creates the exact surface wildcard and deployment-manifest
409
+ invalidation paths.
410
+
384
411
  ### Immutable publication paths
385
412
 
386
413
  When a surface artifact contains `manifest.json` with
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kungfu-tech/buildchain",
3
- "version": "2.14.15",
3
+ "version": "2.14.16-alpha.0",
4
4
  "private": false,
5
5
  "description": "Buildchain Release Passport, release governance, CLI toolkit, and site facts.",
6
6
  "repository": "https://github.com/kungfu-systems/buildchain",
@@ -827,11 +827,13 @@ function normalizeDeployConfig(name, config) {
827
827
  if (healthStrategy !== undefined && !SUPPORTED_HEALTH_STRATEGIES.has(healthStrategy)) {
828
828
  throw new Error(`deploy.${name}.health_strategy must be one of http or s3-object`);
829
829
  }
830
+ const cacheControl = normalizeWebSurfaceCacheControl(config, `deploy.${name}`);
830
831
  const normalized = {
831
832
  ...config,
832
833
  adapter,
833
834
  directoryIndexRewrite,
834
835
  healthStrategy,
836
+ cacheControl,
835
837
  artifactPath: config.artifact_path === undefined
836
838
  ? undefined
837
839
  : posixPath(assertString(config.artifact_path, `deploy.${name}.artifact_path`)),
@@ -842,11 +844,17 @@ function normalizeDeployConfig(name, config) {
842
844
  };
843
845
  delete normalized.directory_index_rewrite;
844
846
  delete normalized.health_strategy;
847
+ delete normalized.cache_control_default;
848
+ delete normalized.cache_control_mutable;
849
+ delete normalized.cache_control_immutable;
845
850
  delete normalized.artifact_path;
846
851
  delete normalized.secret_refs;
847
852
  if (normalized.healthStrategy === undefined) {
848
853
  delete normalized.healthStrategy;
849
854
  }
855
+ if (normalized.cacheControl === undefined) {
856
+ delete normalized.cacheControl;
857
+ }
850
858
  if (normalized.surfaces === undefined) {
851
859
  delete normalized.surfaces;
852
860
  }
@@ -854,6 +862,19 @@ function normalizeDeployConfig(name, config) {
854
862
  return normalized;
855
863
  }
856
864
 
865
+ function normalizeWebSurfaceCacheControl(config, label) {
866
+ const entries = [
867
+ ["default", "cache_control_default"],
868
+ ["mutable", "cache_control_mutable"],
869
+ ["immutable", "cache_control_immutable"],
870
+ ].flatMap(([normalizedKey, sourceKey]) => (
871
+ config[sourceKey] === undefined
872
+ ? []
873
+ : [[normalizedKey, assertString(config[sourceKey], `${label}.${sourceKey}`)]]
874
+ ));
875
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
876
+ }
877
+
857
878
  function normalizeDeploySurfaceOverrides(channelName, surfaces) {
858
879
  assertPlainObject(surfaces, `deploy.${channelName}.surfaces`);
859
880
  return Object.fromEntries(
@@ -879,10 +900,12 @@ function normalizeDeploySurfaceOverride(channelName, surfaceName, override) {
879
900
  if (healthStrategy !== undefined && !SUPPORTED_HEALTH_STRATEGIES.has(healthStrategy)) {
880
901
  throw new Error(`${label}.health_strategy must be one of http or s3-object`);
881
902
  }
903
+ const cacheControl = normalizeWebSurfaceCacheControl(override, label);
882
904
  const normalized = {
883
905
  ...override,
884
906
  directoryIndexRewrite,
885
907
  healthStrategy,
908
+ cacheControl,
886
909
  artifactPath: override.artifact_path === undefined
887
910
  ? undefined
888
911
  : posixPath(assertString(override.artifact_path, `${label}.artifact_path`)),
@@ -893,6 +916,9 @@ function normalizeDeploySurfaceOverride(channelName, surfaceName, override) {
893
916
  };
894
917
  delete normalized.directory_index_rewrite;
895
918
  delete normalized.health_strategy;
919
+ delete normalized.cache_control_default;
920
+ delete normalized.cache_control_mutable;
921
+ delete normalized.cache_control_immutable;
896
922
  delete normalized.artifact_path;
897
923
  delete normalized.origin_path;
898
924
  delete normalized.secret_refs;
@@ -911,6 +937,9 @@ function normalizeDeploySurfaceOverride(channelName, surfaceName, override) {
911
937
  if (normalized.healthStrategy === undefined) {
912
938
  delete normalized.healthStrategy;
913
939
  }
940
+ if (normalized.cacheControl === undefined) {
941
+ delete normalized.cacheControl;
942
+ }
914
943
  assertNoInlineSecretValues(override, label, new Set(["secret_refs"]));
915
944
  return normalized;
916
945
  }
@@ -182,6 +182,9 @@ function surfaceDeployConfig(deployConfig, surfaceName) {
182
182
  return {
183
183
  ...deployConfig,
184
184
  ...overrides,
185
+ cacheControl: deployConfig.cacheControl || overrides.cacheControl
186
+ ? { ...(deployConfig.cacheControl || {}), ...(overrides.cacheControl || {}) }
187
+ : undefined,
185
188
  surfaces: deployConfig.surfaces,
186
189
  secretRefs: [
187
190
  ...new Set([
@@ -273,7 +276,7 @@ function surfaceArtifactRootFor({ artifactRoot, binding }) {
273
276
  return artifactRoot;
274
277
  }
275
278
 
276
- function syncStaticArtifactArgs({ artifactRoot, bucket, objectPrefix, deleteExcludes = [] }) {
279
+ function syncStaticArtifactArgs({ artifactRoot, bucket, objectPrefix, deleteExcludes = [], cacheControl = "" }) {
277
280
  const args = ["s3", "sync", artifactRoot, s3Uri(bucket, objectPrefix), "--delete"];
278
281
  if (!objectPrefix) {
279
282
  args.push("--exclude", ".buildchain/*");
@@ -281,6 +284,33 @@ function syncStaticArtifactArgs({ artifactRoot, bucket, objectPrefix, deleteExcl
281
284
  for (const pattern of deleteExcludes) {
282
285
  args.push("--exclude", pattern);
283
286
  }
287
+ if (cacheControl) {
288
+ args.push("--cache-control", cacheControl);
289
+ }
290
+ return args;
291
+ }
292
+
293
+ function mutableCacheControlArgs({ artifactRoot, bucket, objectPrefix, cacheControl = "", excludePatterns = [] }) {
294
+ if (!cacheControl) return [];
295
+ const args = [
296
+ "s3",
297
+ "cp",
298
+ artifactRoot,
299
+ s3Uri(bucket, objectPrefix),
300
+ "--recursive",
301
+ "--exclude",
302
+ "*",
303
+ "--include",
304
+ "*.html",
305
+ "--include",
306
+ "*.json",
307
+ "--include",
308
+ "*.xml",
309
+ ];
310
+ for (const pattern of excludePatterns) {
311
+ args.push("--exclude", pattern);
312
+ }
313
+ args.push("--cache-control", cacheControl);
284
314
  return args;
285
315
  }
286
316
 
@@ -486,6 +516,9 @@ function directoryIndexAliasOperations({ surfaceArtifactRoot, bucket, binding })
486
516
  filePath,
487
517
  "--content-type",
488
518
  "text/html",
519
+ ...(binding.cacheControl?.mutable
520
+ ? ["--cache-control", binding.cacheControl.mutable]
521
+ : []),
489
522
  ],
490
523
  routing: {
491
524
  ...(binding.routing || {}),
@@ -836,6 +869,7 @@ function resolveSurfaceBindings({ config, channelName, alias, deployConfig }) {
836
869
  directoryIndexResolution: true,
837
870
  directoryIndexRewrite: effectiveDeploy.directoryIndexRewrite || "buildchain",
838
871
  healthStrategy: effectiveDeploy.healthStrategy || "",
872
+ cacheControl: effectiveDeploy.cacheControl || undefined,
839
873
  canonicalUrl: surface.productionUrl || (channelName === "production" ? url : ""),
840
874
  pathOnly: Boolean(surface.pathOnly),
841
875
  bucket,
@@ -1985,6 +2019,9 @@ function deployBindingOperations({ artifactRoot, deployConfig, manifest, binding
1985
2019
  "--no-overwrite",
1986
2020
  "--checksum-algorithm",
1987
2021
  "SHA256",
2022
+ ...(binding.cacheControl?.immutable
2023
+ ? ["--cache-control", binding.cacheControl.immutable]
2024
+ : []),
1988
2025
  ],
1989
2026
  immutable: {
1990
2027
  preservedRoot: root,
@@ -2004,6 +2041,7 @@ function deployBindingOperations({ artifactRoot, deployConfig, manifest, binding
2004
2041
  bucket,
2005
2042
  objectPrefix: binding.objectPrefix,
2006
2043
  deleteExcludes: binding.mutableDeleteExcludes || [],
2044
+ cacheControl: binding.cacheControl?.default || "",
2007
2045
  }),
2008
2046
  routing: binding.routing,
2009
2047
  preservation: binding.mutableDeleteExcludes?.length > 0
@@ -2013,12 +2051,39 @@ function deployBindingOperations({ artifactRoot, deployConfig, manifest, binding
2013
2051
  }
2014
2052
  : undefined,
2015
2053
  },
2054
+ ...(binding.cacheControl?.mutable
2055
+ ? [{
2056
+ action: "apply-mutable-cache-control",
2057
+ surface: binding.surface,
2058
+ command: "aws",
2059
+ args: mutableCacheControlArgs({
2060
+ artifactRoot: surfaceArtifactRoot,
2061
+ bucket,
2062
+ objectPrefix: binding.objectPrefix,
2063
+ cacheControl: binding.cacheControl.mutable,
2064
+ excludePatterns: binding.mutableDeleteExcludes || [],
2065
+ }),
2066
+ cacheControl: binding.cacheControl.mutable,
2067
+ patterns: ["*.html", "*.json", "*.xml"],
2068
+ excludes: binding.mutableDeleteExcludes || [],
2069
+ }]
2070
+ : []),
2016
2071
  ...directoryIndexAliasOperations({ surfaceArtifactRoot, bucket, binding }),
2017
2072
  {
2018
2073
  action: "write-deployment-manifest",
2019
2074
  surface: binding.surface,
2020
2075
  command: "aws",
2021
- args: ["s3", "cp", "-", s3Uri(bucket, binding.manifestKey), "--content-type", "application/json"],
2076
+ args: [
2077
+ "s3",
2078
+ "cp",
2079
+ "-",
2080
+ s3Uri(bucket, binding.manifestKey),
2081
+ "--content-type",
2082
+ "application/json",
2083
+ ...(binding.cacheControl?.mutable
2084
+ ? ["--cache-control", binding.cacheControl.mutable]
2085
+ : []),
2086
+ ],
2022
2087
  stdin: `${JSON.stringify({
2023
2088
  ...manifest,
2024
2089
  surface: binding.surface,
@@ -2075,7 +2140,17 @@ function planAdapterSteps(adapter, deployConfig, manifest) {
2075
2140
  target: binding.bucket,
2076
2141
  prefix: binding.objectPrefix,
2077
2142
  deleteExcludes: binding.mutableDeleteExcludes || [],
2143
+ cacheControl: binding.cacheControl || undefined,
2078
2144
  },
2145
+ ...(binding.cacheControl?.mutable
2146
+ ? [{
2147
+ action: "apply-mutable-cache-control",
2148
+ surface: binding.surface,
2149
+ cacheControl: binding.cacheControl.mutable,
2150
+ patterns: ["*.html", "*.json", "*.xml"],
2151
+ excludes: binding.mutableDeleteExcludes || [],
2152
+ }]
2153
+ : []),
2079
2154
  {
2080
2155
  action: "write-deployment-manifest",
2081
2156
  surface: binding.surface,