@kungfu-tech/buildchain 3.0.1-alpha.2 → 3.0.1-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/buildchain.mjs +7 -0
- package/dist/site/buildchain-contract.json +10 -10
- package/dist/site/buildchain-site.json +10 -10
- package/dist/site/kfd-claims.json +2 -2
- package/dist/site/kfd-upstream-aggregate.json +1 -1
- package/dist/site/manual-registry.json +2 -2
- package/dist/site/node-api-registry.json +3 -3
- package/dist/site/page-registry.json +4 -4
- package/dist/site/public-surface-audit.json +1 -1
- package/dist/site/publication-registry.json +4 -4
- package/dist/site/site-manifest.json +6 -6
- package/docs/cli.md +6 -0
- package/docs/toolkit-observability.md +14 -0
- package/package.json +1 -1
- package/packages/core/issue-reporting.js +8 -3
- package/packages/core/logging.js +101 -0
- package/scripts/check-inventory.mjs +29 -10
- package/scripts/web-surface-production-release-pr.mjs +99 -0
- package/scripts/workflow-friction-report.mjs +10 -0
package/bin/buildchain.mjs
CHANGED
|
@@ -1542,6 +1542,13 @@ async function main(argv = process.argv.slice(2)) {
|
|
|
1542
1542
|
process.stdout.write(`buildchain log summary: ${summary.eventCount} events\n`);
|
|
1543
1543
|
process.stdout.write(`sources: ${Object.keys(summary.sources).join(", ") || "none"}\n`);
|
|
1544
1544
|
process.stdout.write(`phases: ${Object.keys(summary.phases).join(", ") || "none"}\n`);
|
|
1545
|
+
if (summary.controlPlane.eventCount > 0) {
|
|
1546
|
+
process.stdout.write(
|
|
1547
|
+
`control plane: ${summary.controlPlane.eventCount} events, ` +
|
|
1548
|
+
`incident reuse ${summary.controlPlane.workflowFriction.incidentReuseRate ?? "n/a"}, ` +
|
|
1549
|
+
`release-intent suppression ${summary.controlPlane.releaseIntent.suppressionRate ?? "n/a"}\n`,
|
|
1550
|
+
);
|
|
1551
|
+
}
|
|
1545
1552
|
}
|
|
1546
1553
|
return;
|
|
1547
1554
|
}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"product": {
|
|
5
5
|
"name": "Buildchain",
|
|
6
6
|
"package": "@kungfu-tech/buildchain",
|
|
7
|
-
"version": "3.0.1-alpha.
|
|
7
|
+
"version": "3.0.1-alpha.3",
|
|
8
8
|
"repository": "https://github.com/kungfu-systems/buildchain"
|
|
9
9
|
},
|
|
10
10
|
"majorLine": "v3",
|
|
@@ -212,7 +212,7 @@
|
|
|
212
212
|
"promotion reuses PR-stage release-candidate artifacts and does not run the heavy native build matrix"
|
|
213
213
|
],
|
|
214
214
|
"breakingDigest": "sha256:aa30f22e3af0a89841310bdbdc900844dd95a66974db173fa140a71bbd7e82c0",
|
|
215
|
-
"auditDigest": "sha256:
|
|
215
|
+
"auditDigest": "sha256:e7d185bca91ebc65d7c42f6bbe72e1466c3be2b651143d75af6af08711f51b8c"
|
|
216
216
|
},
|
|
217
217
|
{
|
|
218
218
|
"contractVersion": 1,
|
|
@@ -256,7 +256,7 @@
|
|
|
256
256
|
"channel-aware artifact host facts are checked against the deploy plan before adapter side effects"
|
|
257
257
|
],
|
|
258
258
|
"breakingDigest": "sha256:da569f90374e878948e3d5160ed9929338ce0572473ca8ee54867b0fe1aaeace",
|
|
259
|
-
"auditDigest": "sha256:
|
|
259
|
+
"auditDigest": "sha256:6277559c749bcc9ae6c737b068b44c478e796377273acc9fc22ab9804be409d1"
|
|
260
260
|
},
|
|
261
261
|
{
|
|
262
262
|
"contractVersion": 1,
|
|
@@ -468,7 +468,7 @@
|
|
|
468
468
|
"missing issue permissions produce a copyable summary fallback"
|
|
469
469
|
],
|
|
470
470
|
"breakingDigest": "sha256:575a2cb02cdb2e61bb2e84d5bbaaf64b430aa5d7936645660b592de4549d81b0",
|
|
471
|
-
"auditDigest": "sha256:
|
|
471
|
+
"auditDigest": "sha256:10b766e026f8089235dfd6a9356cdbfa42c5dd290ba3003e5fcfd886432a0a34"
|
|
472
472
|
},
|
|
473
473
|
{
|
|
474
474
|
"contractVersion": 1,
|
|
@@ -601,7 +601,7 @@
|
|
|
601
601
|
"README badge block checks and writes are generated from machine-readable repository facts"
|
|
602
602
|
],
|
|
603
603
|
"breakingDigest": "sha256:90a73892b2d6c214048448d5f45df75639bdf7b7e8fefd9c596e04b087407bcc",
|
|
604
|
-
"auditDigest": "sha256:
|
|
604
|
+
"auditDigest": "sha256:5c6b806014d119683be0d7671a915aedbe88b87c216032d2a741a7e5b4ea07df"
|
|
605
605
|
},
|
|
606
606
|
{
|
|
607
607
|
"contractVersion": 1,
|
|
@@ -691,7 +691,7 @@
|
|
|
691
691
|
"manual entries carry source file digests so downstream sites and agents can detect stale hand-written documentation"
|
|
692
692
|
],
|
|
693
693
|
"breakingDigest": "sha256:7d0d2819e3a3e72989d9c57b5efe9d0bc0a79bc0f2c82a0c7b9d6c5a211a91f2",
|
|
694
|
-
"auditDigest": "sha256:
|
|
694
|
+
"auditDigest": "sha256:d942995e6cfab9063857c2f21fb8ef9fe6b07cc5c6cb3edbb585b540384ea4f2"
|
|
695
695
|
},
|
|
696
696
|
{
|
|
697
697
|
"contractVersion": 1,
|
|
@@ -713,7 +713,7 @@
|
|
|
713
713
|
"agents can discover supported Node APIs without importing internal file paths"
|
|
714
714
|
],
|
|
715
715
|
"breakingDigest": "sha256:48f925608d3e2131d90936b07dc2a30341204cae3e6e785c0f77d61ad755c945",
|
|
716
|
-
"auditDigest": "sha256:
|
|
716
|
+
"auditDigest": "sha256:b0408f64aac5e5cf5164943de14f750ef9d41d422aec0963f0c04be54d0afb32"
|
|
717
717
|
},
|
|
718
718
|
{
|
|
719
719
|
"contractVersion": 1,
|
|
@@ -2073,7 +2073,7 @@
|
|
|
2073
2073
|
"missing receipts are non-qualifying and must not be represented as a successful controller run"
|
|
2074
2074
|
],
|
|
2075
2075
|
"breakingDigest": "sha256:f14825324a16b51c2e9ed708ebe64e1932e05b6d5e0866f83aea8439decb4a27",
|
|
2076
|
-
"auditDigest": "sha256:
|
|
2076
|
+
"auditDigest": "sha256:6277559c749bcc9ae6c737b068b44c478e796377273acc9fc22ab9804be409d1"
|
|
2077
2077
|
},
|
|
2078
2078
|
{
|
|
2079
2079
|
"contractVersion": 1,
|
|
@@ -3008,7 +3008,7 @@
|
|
|
3008
3008
|
"missing receipts are non-qualifying and must not be represented as a successful controller run"
|
|
3009
3009
|
],
|
|
3010
3010
|
"breakingDigest": "sha256:015d8de793adbd4c539416be7d7512e18cc92097e629b0203fa06d2c183e98bd",
|
|
3011
|
-
"auditDigest": "sha256:
|
|
3011
|
+
"auditDigest": "sha256:e7d185bca91ebc65d7c42f6bbe72e1466c3be2b651143d75af6af08711f51b8c"
|
|
3012
3012
|
},
|
|
3013
3013
|
{
|
|
3014
3014
|
"contractVersion": 1,
|
|
@@ -3206,5 +3206,5 @@
|
|
|
3206
3206
|
}
|
|
3207
3207
|
],
|
|
3208
3208
|
"compatibilityDigest": "sha256:008b1c5a90a787cf30106829ac7aca68ab501f6d9c375e415d9c5c6b89039f46",
|
|
3209
|
-
"contractDigest": "sha256:
|
|
3209
|
+
"contractDigest": "sha256:a449d8913fab1ff8d5d341250c04f30c99bb3f577eb9803b09f2be31895b0d73"
|
|
3210
3210
|
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schemaVersion": 1,
|
|
3
3
|
"contract": "kungfu-buildchain-site-bundle",
|
|
4
|
-
"generatedAt": "2026-07-
|
|
5
|
-
"publishedAt": "2026-07-
|
|
4
|
+
"generatedAt": "2026-07-26T09:59:00.019Z",
|
|
5
|
+
"publishedAt": "2026-07-26T09:59:00.019Z",
|
|
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": "
|
|
22
|
+
"sourceRevision": "7bbc59abd8516132b06c588bdc191f7bc5fbdef9",
|
|
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": "3.0.1-alpha.
|
|
40
|
+
"version": "3.0.1-alpha.3",
|
|
41
41
|
"versionSource": "package.json#version"
|
|
42
42
|
},
|
|
43
43
|
"source": {
|
|
@@ -514,7 +514,7 @@
|
|
|
514
514
|
],
|
|
515
515
|
"maturity": "stable",
|
|
516
516
|
"sourcePath": "docs/cli.md",
|
|
517
|
-
"digest": "sha256:
|
|
517
|
+
"digest": "sha256:f7a27ef72c0ffe3e18ad5d4d0520e14d8f343a55a417182c5da74a150b8f58fc",
|
|
518
518
|
"headings": [
|
|
519
519
|
{
|
|
520
520
|
"level": 1,
|
|
@@ -542,7 +542,7 @@
|
|
|
542
542
|
"anchor": "npm-publish-gate"
|
|
543
543
|
}
|
|
544
544
|
],
|
|
545
|
-
"markdown": "# Buildchain CLI, npm Package, and Toolkit API\n\nBuildchain is published as the public npm package\n`@kungfu-tech/buildchain`. The package contains the `buildchain` command,\nthe importable ESM toolkit APIs, and the local scripts needed to initialize and\nvalidate repositories before they use the reusable GitHub workflow surface.\n\nThe npm package is not the release authority. Release authority still comes\nfrom the protected Buildchain branch and tag state machine. npm publishing is a\nside effect of an exact release tag that has already been produced by that\nstate machine.\n\n## Install and Run\n\nUse the published package directly:\n\n```bash\nnpx @kungfu-tech/buildchain --help\nnpx @kungfu-tech/buildchain init --type package\nnpx @kungfu-tech/buildchain validate --require-version-state\n```\n\nOr install it in a repository:\n\n```bash\npnpm add -D @kungfu-tech/buildchain\npnpm exec buildchain validate\n```\n\nConsumers should pin the exact Buildchain version that was validated in their\nrepository. When dogfooding a fresh Buildchain release immediately after it is\npublished, pnpm may block the install through a minimum release-age policy. In\nthat case, add a temporary package/version-specific `minimumReleaseAgeExclude`\nentry, such as `@kungfu-tech/buildchain@2.2.5`, and remove it once the package\nhas aged past the normal policy window. Do not replace that with a broad\nregistry or scope-wide exclude.\n\nUse the package API directly inside JavaScript build scripts:\n\n```js\nimport { createBuildchainLogger } from \"@kungfu-tech/buildchain/logging\";\n\nconst logger = createBuildchainLogger({ source: \"user\", component: \"build\" });\nawait logger.span(\"build.native\", { phase: \"build\" }, async () => {\n await buildNativeArtifacts();\n});\n```\n\nThe standalone binary and CLI are for workflow steps, shell scripts, and\nnon-JavaScript environments. JavaScript code that already depends on\n`@kungfu-tech/buildchain` should import the toolkit API instead of spawning\n`npx buildchain` or a downloaded binary.\n\n## Node API and Package Exports\n\nBuildchain's public Node API is the package `exports` surface, not arbitrary\ninternal file paths. The npm package also ships\n`dist/site/node-api-registry.json` and exports it as\n`@kungfu-tech/buildchain/site/node-api-registry.json` so agents can enumerate\nthe supported imports from the installed package.\nFor navigation, start with `dist/site/capability-registry.json`: it groups\nmanuals, CLI commands, workflow/action inputs, Node exports, site pages, and KFD\nclaim facts by product capability before an agent chooses a concrete command or\nmanual.\n\nCurrent public import families include:\n\n```js\nimport * as buildchain from \"@kungfu-tech/buildchain\";\nimport { createBuildchainLogger } from \"@kungfu-tech/buildchain/logging\";\nimport { collectModuleBuildFacts } from \"@kungfu-tech/buildchain/build-facts\";\nimport { checkHomebrewTap } from \"@kungfu-tech/buildchain/homebrew\";\nimport { verifyKfd1ReleaseGate } from \"@kungfu-tech/buildchain/kfd-gate\";\nimport { collectBadgeBundleFacts } from \"@kungfu-tech/buildchain/badges\";\nimport { collectReadmeBadgeFacts } from \"@kungfu-tech/buildchain/readme-badges\";\nimport { verifyReleasePassport } from \"@kungfu-tech/buildchain/release-passport\";\nimport { createReleasePropagationPlan } from \"@kungfu-tech/buildchain/release-propagation\";\nimport { planReleaseLineBootstrap } from \"@kungfu-tech/buildchain/release-line-bootstrap\";\nimport { collectPublicSurfaceReverseAudit } from \"@kungfu-tech/buildchain/public-surface-audit\";\nimport { createBuildchainLayoutDiscovery } from \"@kungfu-tech/buildchain/buildchain-layout\";\nimport { createPortableDevCachePlan } from \"@kungfu-tech/buildchain/portable-dev-cache\";\nimport contractWorld from \"@kungfu-tech/buildchain/site/buildchain-contract.json\" with { type: \"json\" };\nimport capabilityRegistry from \"@kungfu-tech/buildchain/site/capability-registry.json\" with { type: \"json\" };\nimport manualRegistry from \"@kungfu-tech/buildchain/site/manual-registry.json\" with { type: \"json\" };\nimport nodeApiRegistry from \"@kungfu-tech/buildchain/site/node-api-registry.json\" with { type: \"json\" };\nimport publicSurfaceAudit from \"@kungfu-tech/buildchain/site/public-surface-audit.json\" with { type: \"json\" };\n```\n\nUse `dist/site/manual-registry.json` to find the packaged operating manuals and\ntheir SHA-256 digests. Use `dist/site/buildchain-contract.json` to verify the\nfloating-ref contract world for a runtime such as `@v2`.\n\n## Commands\n\n`buildchain layout` is the stable machine question for repository layout. Tools\nsuch as Shifu should call it instead of copying `.buildchain/` path constants:\n\n```bash\nbuildchain layout --cwd /path/to/repository --json\n```\n\nThe result identifies the Buildchain version pin, repository root and config,\nthe canonical and currently resolved KFD-3 registry paths, and the KFD field\nused to declare Shifu jurisdiction. A repository is in Shifu's distribution\njurisdiction only when a KFD-3 surface explicitly declares\n`distribution.registrar=\"shifu\"`; the presence of Buildchain configuration is\nnot sufficient. The same contract is available through\n`createBuildchainLayoutDiscovery()` from\n`@kungfu-tech/buildchain/buildchain-layout`.\n\n`buildchain init` writes a starter `.buildchain/buildchain.toml` and a reusable workflow\ncaller at `.github/workflows/build.yml`.\n\n`buildchain portable-cache plan` turns a consumer-owned, secret-free manifest\ninto GitHub Actions cache inputs without letting each consumer invent key or\nrestore-prefix semantics. The exact key binds source SHA and the consumer plan\ndigest; the compatible restore prefix still requires the same provider schema,\nlayer, roots, runner image, platform/architecture, toolchain, dependency lock,\nand build profile.\n\n```bash\nbuildchain portable-cache plan \\\n --manifest .buildchain/portable-cache.json \\\n --output .buildchain/portable-cache-plan.json \\\n --github-output \"$GITHUB_OUTPUT\"\n```\n\nThe emitted `cache-key`, `restore-keys`, and `cache-paths` values are intended\nfor pinned `actions/cache/restore` and `actions/cache/save` actions. After\nrestore and a consumer validation probe, seal the provider result:\n\n```bash\nbuildchain portable-cache receipt \\\n --plan .buildchain/portable-cache-plan.json \\\n --matched-key \"$CACHE_MATCHED_KEY\" \\\n --cache-hit \"$CACHE_HIT\" \\\n --validation-status pass \\\n --cold-fallback-status passed \\\n --output .buildchain/portable-cache-receipt.json\n```\n\nThe receipt distinguishes `exact`, `compatible`, `miss`, and `corrupt`.\nUnknown or contradictory provider evidence fails closed. A miss or corruption\nrequires the consumer's audited cold path; a cache never substitutes for the\nconsumer's current build or tests. Roots must be workspace-relative or under\n`~/`, and manifests cannot carry credentials, absolute host paths, or escape\nsegments. `cold-fallback-status=passed` qualifies a miss only after the current\nsource has completed its normal build and test path.\n\nSupported presets:\n\n- `--type package` for Node package repositories with pnpm, npm, or yarn.\n- `--type native` for CMake-style native projects.\n- `--type web-surface` for preview/staging/production site or app deployments.\n- `--type infra-contract` for provider-agnostic infrastructure contract\n validation, observation, contract publication, and downstream propagation\n planning without default mutation. Provider adapters expose built-in command\n plans by default, and only configured `[infra.commands]` hooks can execute.\n- `--type publication-artifact` for papers, reports, specifications, and other\n publication repositories that produce PDFs, metadata, source bundles, and\n site-consumable manifests without becoming web-surface repositories. The\n scaffold uses Buildchain's pinned\n `ghcr.io/kungfu-systems/build-images/latex-pdf-builder:v1.2.0` toolchain for\n LaTeX PDF builds.\n- `--type distribution-index` for Homebrew taps and other index repositories\n whose files are projections of upstream release passport evidence.\n- `--type anchored-package` for packages whose version is anchored to an\n explicit upstream release manifest.\n\nThe native preset includes an opt-in `[diagnostics.native]` profile with common\ntool/cache/artifact probes. Consumers can keep it enabled, adjust the tool and\ndirectory lists, or disable it if a repository does not need native diagnostics.\n\n`buildchain validate` parses `.buildchain/buildchain.toml`, checks configured version-state\nfiles, and can require named lifecycle stages:\n\n```bash\nbuildchain validate \\\n --require-version-state \\\n --require-lifecycle-stages install,build,verify\n```\n\n`buildchain lifecycle run <stage>` executes a lifecycle stage and writes the\nsame deterministic artifact manifest contract used by the reusable workflow:\n\n```bash\nbuildchain lifecycle run build \\\n --artifact-path dist \\\n --artifact-name \"{repo}-{version}-{platform}\"\n```\n\n`buildchain dev merge-queue` plans a GitHub merge-queue policy for a protected\nBuildchain dev channel. Declare every workflow that emits a required check; the\ncommand fails closed unless each file handles both `pull_request` and\n`merge_group` without reading `github.event.pull_request` directly:\n\n```bash\nbuildchain dev merge-queue \\\n --repository kungfu-systems/example \\\n --branch dev/v4/v4.0 \\\n --workflow .github/workflows/source-acceptance.yml \\\n --workflow .github/workflows/affected-native-pr.yml\n```\n\nThe default output is a read-only plan. Add `--apply` only after reviewing it.\nApply creates the exact-branch merge-queue ruleset before changing classic\nrequired status checks from strict to loose, preserves the required check\nidentities, and is safe to repeat. `gh` must be authenticated with repository\nAdministration write permission for apply mode.\n\nRepositories can make that policy declarative in `buildchain.toml`:\n\n```toml\n[governance.dev.merge_queue]\nmode = \"enabled\" # enabled, inherit, or disabled\nrequired_workflows = [\".github/workflows/verify.yml\"]\ncheck_response_timeout_minutes = 120\nmax_entries_to_build = 1\nbypass_users = [\"release-owner\"]\n```\n\nUse `buildchain dev merge-queue --from-config` to resolve and reconcile the\ndeclaration. `enabled` requires an exact queue on the target dev branch;\n`disabled` suppresses automatic queue creation; `inherit` copies the active\ndefault dev branch's queue parameters and bypass actors. When the table is\nabsent, release-line bootstrap uses the backward-compatible `inherit` mode.\nEvery inherited or explicitly enabled queue still validates each declared\nrequired workflow before any mutation. For a legacy repository with no table,\nan already-active exact queue on the current default dev branch is accepted as\nthe inheritance evidence; new declarations should list the workflows so future\nchanges are revalidated from source.\nThe `Dev Merge Queue Governance` workflow runs this reconciliation after\ngovernance-relevant changes land on a dev branch; its manual dispatch remains\ndry-run by default.\n\n`buildchain release line open` plans or writes the first version-state commit\nfor a new semver minor line. It does not publish anything. The dry-run mode is\nthe default and returns the dev/alpha/release refs, protection contract, default\nbranch action, and initial version before any GitHub mutation happens:\n\n```bash\nbuildchain release line open \\\n --major 2 \\\n --minor 10 \\\n --source-ref release/v2/v2.9 \\\n --json\n```\n\nThe write mode only updates local version-state files. The repository workflow\n`Release Line Bootstrap` wraps this command and, when `apply=true`, commits the\ninitial version state, creates `dev/vX/vX.Y`, `alpha/vX/vX.Y`, and\n`release/vX/vX.Y`, applies one-review branch protection, reconciles declared or\ninherited merge-queue governance, switches the default branch only after that\nreconciliation succeeds, and opens the first dev-to-alpha channel PR:\n\n```bash\nbuildchain release line open \\\n --major 2 \\\n --minor 10 \\\n --source-ref release/v2/v2.9 \\\n --write \\\n --json\n```\n\n`buildchain` also publishes a public surface reverse audit as\n`dist/site/public-surface-audit.json`. The audit enumerates CLI commands from\n`bin/buildchain.mjs`, workflow inputs, action inputs, site pages, and docs\ncommand references, then compares them with the generated registries. Buildchain\nself-checks fail closed when an enumerable public surface is missing from the\nregistry:\n\n```js\nimport {\n collectPublicSurfaceReverseAudit,\n assertPublicSurfaceReverseAudit,\n} from \"@kungfu-tech/buildchain/public-surface-audit\";\n\nassertPublicSurfaceReverseAudit(collectPublicSurfaceReverseAudit({ root: process.cwd() }));\n```\n\n`buildchain kfd` is the product-facing KFD namespace. Schema commands expose the\nmachine-readable KFD standards shipped by `@kungfu-tech/kfd`, while versioned\nsubcommands host concrete product workflows. KFD-1, KFD-2, and KFD-3 are\nfirst-class Buildchain surfaces. KFD-4 is schema-only until Buildchain has a\nreal verification protocol for it.\n\n`status` reports implemented support and the active repo-owned file layout.\n`migrate-layout` moves legacy root files into `.buildchain/`:\n\n```bash\nbuildchain kfd status --json\nbuildchain kfd migrate-layout --write\n```\n\nKFD-1 commands generate and validate contract-world release evidence:\n\n```bash\nbuildchain kfd 1 schema --json\nbuildchain kfd 1 witness --json\nbuildchain kfd 1 gate --witness-json kfd-1-witness.json --json\nbuildchain kfd 1 verify --gate-json kfd-1-gate.json --json\n```\n\nKFD-2 commands validate trust taxonomy entries and generate Buildchain's public\nclaim evidence. Product repositories use the `product-claims` subcommand to\nvalidate and render their own declared KFD-2 release claims under the canonical\nBuildchain KFD layout:\n\n```bash\nbuildchain kfd 2 schema --json\nbuildchain kfd 2 taxonomy --entry-json residual-risk.json --kind residualRisk --json\nbuildchain kfd 2 claims --json\nbuildchain kfd 2 product-claims check --json\nbuildchain kfd 2 product-claims write --json\nbuildchain kfd 2 product-claims render --json\n```\n\nThe default source is `.buildchain/kfd/kfd-2/registry.json`; outputs are\n`.buildchain/kfd/kfd-2/release-claims.json`, per-claim release-passport inputs\nunder `claims/`, and `buildchain-claim-args.txt`. Use `--registry` or\n`--output-dir` only for an explicit product packaging projection. `check` never\nwrites and exits non-zero when outputs drift.\n\nKFD-3 commands are separate from Buildchain's self reverse audit: products can\ndetect standard public surfaces, register the accepted boundary, audit the\ncurrent source or artifact tree, generate a release-passport-compatible witness,\nand expose a capability map for agents:\n\n```bash\nbuildchain kfd schema list --json\nbuildchain kfd schema show kfd-3 --json\nbuildchain kfd 3 detect --kind node-api --kind cli --json\nbuildchain kfd 3 register node-api --product Buildchain\nbuildchain kfd 3 audit --json\nbuildchain kfd 3 witness --kind prebuild --output .buildchain/kfd/kfd-3/collaboration-interface.prebuild.json\nbuildchain kfd 3 query buildchain --json\nbuildchain kfd 4 schema --json\n```\n\nThe public Node API is exported from `@kungfu-tech/buildchain/kfd`. See\n[`kfd-support.md`](kfd-support.md) for the detected / declared / enforced model\nand the agent query flow.\n\nLifecycle runs also write a Buildchain observability JSONL log at\n`.buildchain/logs/events.jsonl` by default. Framework events use\n`source=buildchain`; consumer lifecycle commands use `source=user`. This lets a\nmaintainer tell apart time spent inside Buildchain's artifact/manifest\nframework from time spent in the repository's own build, test, packaging, or\npublish commands. The artifact manifest and summary embed the observability\nsummary for that lifecycle run id, so uploaded artifacts preserve the timing\nfacts without mixing in older JSONL events.\n\n`buildchain log`, `buildchain mark`, and `buildchain span` expose the same event\nprotocol to repository scripts:\n\n```bash\nbuildchain mark --event configure.ready --phase configure --attribute target=release\nbuildchain span --event native.build --phase build -- cmake --build build\nbuildchain log warn --event cache.miss --component conan --attribute token=hidden\nbuildchain log summary --json\nbuildchain verify observability-log .buildchain/logs/events.jsonl --min-events 4 --require-phase build\nbuildchain diagnostics summary .buildchain/artifacts/*/diagnostics.json --json\nbuildchain sample process-tree --label native-build --interval-ms 15000 -- make -j20\n```\n\nDuring `buildchain lifecycle run`, child processes receive\n`BUILDCHAIN_LOG_PATH` and `BUILDCHAIN_LOG_RUN_ID`. A shell, Python, CMake, Conan,\nor JavaScript helper can call `buildchain mark` or `buildchain span` mid-build\nand have those events grouped into the same lifecycle summary.\n`buildchain verify observability-log` is a release gate: it fails when the log\nis missing, has too few events, contains error events, or does not include\nrequired phases, components, or event names.\n\nThe event protocol is JSONL and is also available from the SDK:\n\n```js\nimport { createBuildchainLogger } from \"@kungfu-tech/buildchain/logging\";\n\nconst logger = createBuildchainLogger({ source: \"user\", component: \"native-build\" });\nlogger.mark(\"configure.ready\", { phase: \"configure\" });\n```\n\nSecret-looking attribute keys such as `token`, `password`, `secret`,\n`authorization`, `cookie`, and `private-key` are redacted before they are written.\nFull command strings are not recorded by `span`; scripts should provide stable\nevent names and safe attributes instead.\n\n`buildchain diagnostics summary` reads one or more small diagnostics artifacts\nand emits the same cross-platform summary as the diagnostics SDK:\n\n```bash\nbuildchain diagnostics summary \\\n .buildchain/artifacts/linux-x64/diagnostics.json \\\n .buildchain/artifacts/macos-arm64/diagnostics.json \\\n --output .buildchain/artifacts/diagnostics-summary.json \\\n --json\n```\n\nThe JSON summary keeps per-platform lifecycle stage tables, adds lifecycle\ntotal durations, carries top slow spans, aggregates warning/error counts, and\nsorts the slowest platforms. Each platform row carries compact runner facts,\nchecked tool versions/missing tools, package manager/cache directory details,\ncompiler-cache availability, and a compact process sampler summary: requested\nparallelism, observed max active processes, the ratio between them, sample\ncount, process categories, and the top sampled command basenames. This lets\nmaintainers inspect matrix timing, runner, tool, cache, and concurrency context\nwithout downloading large platform binaries or process sidecars first.\nWhen a sibling `diagnostics-manifest.json` is available, the summary also records\nits file list and verifies the listed `diagnostics.json` byte count and sha256.\nMissing, unreadable, or mismatched sidecar manifests are reported through\n`diagnosticsManifestWarningCount` and the per-platform `diagnosticsManifest`\nfield without failing the timing rollup.\nThe summary also compares each `diagnostics.json` contract to\n`BUILDCHAIN_DIAGNOSTICS_CONTRACT`; mismatches are reported through\n`diagnosticsContractWarningCount` and the per-platform `diagnosticsContract`\nfield so reviewers can separate diagnostics schema drift from lifecycle\nwarnings or build failures.\n\nWithout `--json`, the command prints a compact lifecycle timing table with\ninstall/build/verify/publish, artifact scan/upload, total, warning, and error\ncolumns for each platform, plus `jobs` and `active` columns for requested and\nobserved process concurrency when sampler data is present.\n\n`buildchain facts` collects and verifies source/version/output facts for\nmodules and products:\n\n```bash\nbuildchain facts module \\\n --module native-core \\\n --output .buildchain/facts/native-core.json \\\n --legacy-kungfu-buildinfo framework/core/src/kungfu/yijinjing/kungfubuildinfo.json\n\nbuildchain facts aggregate \\\n --product kungfu \\\n --module-fact .buildchain/facts/native-core.json \\\n --artifact dist/kungfu.zip \\\n --output .buildchain/facts/kungfu.json\n\nbuildchain facts verify --fact .buildchain/facts/kungfu.json\n```\n\nThe same implementation is available from\n`@kungfu-tech/buildchain/build-facts`. Release passports can include these\nfacts with repeated `--build-facts-json` arguments to\n`buildchain collect github-release`. See\n[`build-facts.md`](build-facts.md) for the config schema and Node API.\n\n`buildchain sample process-tree` wraps a long-running command and periodically\nwrites process-tree snapshots:\n\n```bash\nbuildchain sample process-tree \\\n --label native-build \\\n --interval-ms 15000 \\\n --output .buildchain/diagnostics/process-samples.jsonl \\\n --summary-output .buildchain/diagnostics/process-summary.json \\\n -- \\\n make -j20\n```\n\nThe command returns the wrapped command's exit status. The JSONL file contains\nsmall timestamped samples; the summary JSON records requested parallelism,\nobserved concurrency, sampled CPU, command categories, and top command\nbasenames. Use it when a native build requests high parallelism but appears to\nspend long stretches in low-concurrency compile, archive, link, or cache steps.\n\n`buildchain doctor` checks repository readiness before remote side effects:\n\n```bash\nbuildchain doctor --json\n```\n\nIt validates `.buildchain/buildchain.toml`, package-manager detection, Git repository state,\nand the reusable workflow caller. For `version.strategy = \"anchored\"` with\n`version.next = \"manual\"`, it also embeds the anchored package release contract\ncheck: anchor manifest readability, configured version files, trusted\npublishing, package publish order, and required lifecycle stages. Add\n`--require-publish-source-lock` inside a publish job when the doctor report\nshould also fail unless the job is running from a resolved `publish-gate/*`\nsource lock.\n\nAnchored/manual package publish jobs can run the narrower source-lock gate\ndirectly:\n\n```bash\nbuildchain publish-source validate-anchored-release --json\n```\n\nThe command requires `BUILDCHAIN_PUBLISH_SOURCE_REF`,\n`BUILDCHAIN_PUBLISH_SOURCE_SHA`, and `BUILDCHAIN_PUBLISH_SOURCE_LOCKED` from the\nreusable build workflow outputs. It fails closed for direct `alpha/*` or\n`release/*` channel-branch publication, and checks the publish-gate consumer\nversion against configured version files and the anchor manifest. The JSON\nresult is shaped for future `buildchain.libkungfu.dev` fact ingestion.\n\n`buildchain release`, `buildchain web-surface`, `buildchain infra-contract`,\n`buildchain publication-artifact`, `buildchain publish-source`,\n`buildchain badges`, `buildchain homebrew`, and `buildchain build-contract`\nroute to the same implementation used by\nBuildchain's package APIs or GitHub Actions workflows. This keeps local\ninspection and CI behavior on the same implementation path.\n\nGenerate publication artifact metadata after building a paper or report:\n\n```bash\nbuildchain publication-artifact manifest \\\n --source-sha \"$(git rev-parse HEAD)\" \\\n --json\n```\n\nGenerate the Buildchain-owned npm paper package contents from declared\npublication facts:\n\n```bash\nbuildchain publication-artifact npm-package --json\n```\n\nThis command reads `project.type = \"publication-artifact\"`,\n`publication.version`, and `[publish] kind = \"npm-paper-package\"` plus\n`publish.package`; it writes `.buildchain/publication/npm-package` by default.\nThe `paper-release.yml@v2` reusable workflow uses the same command before\nrunning the standard npm publish transaction.\n\nThe command writes `.buildchain/publication/publication-artifact.json`,\n`.buildchain/publication/publication-artifact-passport.json`, a source bundle,\nand, when `[publication.archive]` is configured,\n`.buildchain/publication/publication-registry.json` by default. See\n[`publication-artifacts.md`](publication-artifacts.md) for the repository\ncontract, pinned LaTeX builder, and reusable workflow.\n\nGenerate, check, or update the managed README badge block:\n\n```bash\nbuildchain badges readme --json\nbuildchain badges readme --check\nbuildchain badges readme --write\nbuildchain badges bundle --json\nbuildchain badges bundle --check\nbuildchain badges bundle --write\nbuildchain badges bundle --claims kfd-1,release-passport --write\n```\n\nThe `--json` form emits the `kungfu-buildchain-readme-badge-facts` object.\n`--check` fails closed when the README marker block is missing or stale.\n`--write` inserts or replaces only the marked block. KFD passed badges come\nfrom the repository's own verified release passport; unreleased repositories\ndowngrade to explicit local declarations such as `declared`, `aligned`, or\n`planned`. `buildchain badges bundle` is the focused trust-badge entrypoint: it\nemits `kungfu-buildchain-badge-bundle-facts` and defaults to KFD-1, KFD-2,\nKFD-3, and Release Passport. See [`readme-badges.md`](readme-badges.md) for the\nmarker contract and `[badges]` / `[badges.bundle]` configuration.\n\nGenerate or check Homebrew tap projections from upstream release passports:\n\n```bash\nbuildchain homebrew update-formula \\\n --package buildchain \\\n --release-passport https://github.com/kungfu-systems/buildchain/releases/download/v2.8.15/buildchain.release.json \\\n --write\n\nbuildchain homebrew check --json\n```\n\n`update-formula` writes `Formula/buildchain.rb` and `tap-manifest.json` from\nupstream release passport evidence. `check` fails closed when the Formula,\nmanifest, artifact digests, or KFD status drift from the upstream passport. See\n[`homebrew.md`](homebrew.md) for the distribution-index project contract.\n\n`buildchain collect github-release` creates a release passport bundle from\nGitHub Release assets or a local asset directory:\n\n```bash\nbuildchain collect github-release \\\n --tag v2.2.0 \\\n --repository kungfu-systems/buildchain \\\n --assets-dir dist \\\n --output-dir .buildchain/release-passport\n```\n\nThe bundle includes `buildchain.release.json`, `artifact-evidence.json`,\n`impact.json`, `agent-index.json`, `product-mechanism.json`, `check-report.json`,\nand `llms.txt`. Production binary distribution defaults to GitHub-hosted\nrunners so other projects can reproduce the release lane; self-hosted runners\nremain compatibility fixtures and are recorded as runner facts when used.\n\nFor publish-transaction releases, pass the additional evidence inputs so\n`buildchain.release.json` becomes the unified passport instead of a binary-only\nasset summary:\n\n```bash\nbuildchain collect github-release \\\n --tag v2.3.2 \\\n --repository kungfu-systems/buildchain \\\n --assets-dir dist \\\n --publish-evidence-json .buildchain/release-evidence/v2.3.2/evidence.json \\\n --transaction-json .buildchain/release-state/v2.3.2/state.json \\\n --package-set-json package-set.json \\\n --impact-json impact.json \\\n --trusted-publishing-json trusted-publishing.json \\\n --anchor-manifest-json libnode.release.json \\\n --build-summary-json .buildchain/artifacts/build-summary.json \\\n --platform-manifest-json .buildchain/artifacts/linux-x64/manifest.json \\\n --platform-manifest-json .buildchain/artifacts/darwin-arm64/manifest.json \\\n --platform-manifest-json .buildchain/artifacts/win32-x64/manifest.json \\\n --dist-tag-evidence-json .buildchain/release-evidence/v2.3.2/dist-tag-evidence.json \\\n --kfd-1-witness-json .buildchain/kfd/kfd-1/contract-world.witness.json \\\n --kfd-2-claim-json .buildchain/kfd/kfd-2/release-claims.json \\\n --kfd-3-prebuild-witness-json .buildchain/kfd/kfd-3/collaboration-interface.prebuild.json \\\n --kfd-3-artifact-verify-cmd \"kungfu agent verify --json\" \\\n --release-extra-json '{\"channel\":\"release\",\"targetRef\":\"release/v2/v2.3\"}' \\\n --output-dir .buildchain/release-passport\n```\n\nThe generated passport records the main and platform packages, npm dist-tags,\npublished versions, release source/ref state, anchor manifest digest, registry\nartifact digests, trusted publishing evidence, and Buildchain transaction\nresult. It also records `buildSummary`, `platformArtifactManifests`, and\n`distTagPromotion` when those JSON inputs are supplied. `packageSet` keeps the\nordered package set; `publish.packages[]` is the agent-readable npm publication\nsummary for each main/platform package. For Buildchain releases, verification\nexpects the supplied package set to include the main package plus the three\nplatform packages with version, dist-tag, and digest evidence. Verification\nfails closed if supplied sections are internally incomplete or point to\nartifacts without matching evidence.\n\n`--kfd-1-witness-json` attaches a KFD-1 contract-world release gate. The witness\nis structured JSON: consumers declare the contract world, canonical JSON policy,\nartifact paths, and expected SHA-256 digests. Buildchain imports KFD-owned\nmetadata from `@kungfu-tech/kfd`, freezes the witness before build publication,\nthen verifies the resulting artifact bytes itself and writes the evidence under\nthe KFD-provided top-level key currently named `kfd-1`. Consumers should not\nduplicate this by running repository-specific scripts or invoking the Kungfu\nSDK from their release workflow.\n\nFor the KFD repository, KFD-1 witnesses may be self-hosted standard-contract\nwitnesses: docs, schemas, standards metadata, package exports, and\nsite-consumption entrypoints are checked from source hashes to packaged artifact\nhashes, and the passport records schema IDs, self-hosting boundary, result, and\nresponsibility state.\n\n`--kfd-2-claim-json` attaches explicit public release claims to the KFD-2\nrelease trust passport audit. Buildchain also derives KFD-2 claims from KFD-1\nand KFD-3 gate evidence. Public claims must bind declared sources,\nmachine-readable evidence, hashes, artifact coordinates, verification results,\naudit boundary, responsibility state, and residual risk. Unbound claims fail\npassport verification; prose-only claims downgrade the KFD-2 audit and emit a\nwarning.\n\n`--kfd-3-prebuild-witness-json` attaches a KFD-3 collaboration-interface\nrelease gate. The product remains the source of truth: it emits a pre-build\nwitness that contains or points to its KFD-3 collaboration interface, declared\nparticipant-facing public surfaces, and registry digest. Buildchain freezes\nthat declaration before publication. The artifact side is supplied either by\n`--kfd-3-artifact-witness-json` or by a product-owned command such as\n`--kfd-3-artifact-verify-cmd \"kungfu agent verify --json\"`. Buildchain then\nchecks closure: every declared shipped public surface must be present in the\nartifact witness, and every artifact-exposed participant-facing public surface\nmust have been declared. The generated passport writes this evidence under the\nKFD-provided top-level key currently named `kfd-3`.\n\nThis gate is useful for agent-facing products because it turns KFD-3 from prose\ninto release evidence. A package cannot claim KFD-3 collaboration-interface\nsupport merely because the docs mention it; the release passport must show the\nfrozen declaration, the artifact-side witness digest, and a passing closure\ncomparison.\n\n`--invariant-passport-json` attaches a product-owned invariant Passport to the\nrelease gate and may be repeated. `--invariant-passport-cmd` runs a product\ncommand that emits one Passport JSON document. Buildchain verifies the\nPassport root, exact clean source identity, `verified` verdict, complete\nplatform coverage, and residual-risk shape; it does not redefine the product's\ninvariant semantics. Declared invariant Passport input is fail-closed.\nFor the KFD repository itself, the witness can declare docs, schemas, standards\nmetadata, package exports, and site-consumption contracts as grouped public\nsurfaces; the artifact witness must expose the same enumerable package/site\nsurfaces or verification fails closed.\n\n`--impact-json` supplies the surface-aware impact ledger. Production release\npassports (`release/*`) and major publish-gate passports require\n`surfaceImpacts[]`; alpha, local, and legacy passport contexts keep it\noptional. When `surfaceImpacts[]` is required or supplied, the verifier requires\neach entry to include an id, impact, and rationale, and requires\n`versionImpact.final` to match the highest declared surface impact. The\ncollector copies `versionImpact` plus `surfaceImpacts` into\n`buildchain.release.json`. This lets\n`buildchain explain release --for agent --json` state why a release is patch,\nminor, or major instead of relying on file-path memory.\n\nFor a promote-only stable transaction, Buildchain can derive a patch-level\nrelease-governance ledger when the PR-stage release-candidate passport proves\nthe stable source tree is exactly the previously qualified candidate tree.\nThis fallback is unavailable when candidate evidence is absent, stale, or not\ntree-equivalent.\n\nBuildchain dogfoods its observability toolkit in this lane. The standalone\nbuilder writes API-generated events, while the workflow uses `buildchain mark`,\n`buildchain span`, `buildchain verify observability-log`, and `buildchain log\nsummary`; the event logs and summaries are published as release passport assets.\n\nVerify and explain release passports:\n\n```bash\nbuildchain verify release-passport .buildchain/release-passport/buildchain.release.json\nbuildchain explain release --passport .buildchain/release-passport/buildchain.release.json --for agent --json\nbuildchain inspect release --passport .buildchain/release-passport/buildchain.release.json\n```\n\nThe verifier fails closed when required protocol files are absent, artifacts are\nnot covered by evidence, or digests disagree. The explanation output is shaped\nfor agents: trust, completeness, impact, recovery route, and next action.\n\nVerify a published artifact by subject:\n\n```bash\nbuildchain verify artifact ./Kungfu-2.8.0-windows-x64.exe\nbuildchain inspect artifact ./Kungfu-2.8.0-windows-x64.exe --json\nbuildchain explain artifact ./Kungfu-2.8.0-windows-x64.exe --for agent --json\nbuildchain verify artifact npm:@kungfu-tech/libnode@22.22.3-kf.3-alpha.18 \\\n --repository kungfu-systems/libnode \\\n --tag v22.22.3-kf.3-alpha.18 \\\n --json\n```\n\n`verify artifact` computes or obtains the subject digest, discovers the\ndetached release passport, verifies the passport, then requires that the\nsubject digest appears in the passport's release assets, package set, publish\nevidence, or artifact evidence. Outcomes are explicit: `pass`, `fail`, or\n`unverifiable`. A filename is only a hint; trust comes from digest equality.\nFor `npm:<name>@<version>` subjects, Buildchain resolves `dist.integrity` from\nthe npm registry before matching passport evidence. Use `--npm-registry <url>`\nto verify packages from a custom registry; otherwise Buildchain uses\n`npm_config_registry` or `https://registry.npmjs.org/`.\n\nDiscovery is fail-closed and ordered:\n\n1. `--passport <file-or-url>`.\n2. Sidecar pointer, such as `<artifact>.buildchain-passport.json`.\n3. Embedded/package pointer, such as `package.json` `buildchain.releasePassport`.\n4. Local config or org index, such as `.buildchain/artifact-passport-locators.json`.\n5. GitHub Release default discovery from `github-release:` subjects, GitHub\n Release asset URLs, or `--repository <owner/repo> --tag <tag>`.\n6. Custom `--locator-config <json-or-url>`.\n7. `unverifiable` with retry guidance.\n\nLocator files are policy, not protocol. They map subject fields such as\n`name`, `kind`, `version`, `digest`, `repository`, or `tag` to a detached\npassport location:\n\n```json\n{\n \"schemaVersion\": 1,\n \"contract\": \"kungfu-buildchain-artifact-passport-locator\",\n \"locators\": [\n {\n \"match\": {\n \"name\": \"Kungfu-2.8.0-windows-x64.exe\",\n \"digest\": \"sha256:...\"\n },\n \"passport\": \"../release-passport/buildchain.release.json\"\n }\n ]\n}\n```\n\nSupported subject shapes include local files and directories, URLs,\n`npm:<name>@<version>`, `oci:...`, `s3:...`,\n`github-release:<owner/repo>@<tag>/<asset>`, and deployment endpoints. Local\nfiles, directories, and URLs are digestable directly; remote package, OCI,\nobject storage, and deployment subjects should provide a digest or resolve to a\nlocator that records one.\n\nSeal an exact artifact verification with the Node API, then verify or project\nthe resulting KFX admission envelope without reconstructing its roots:\n\n```bash\nbuildchain verify artifact-envelope envelope.json \\\n --assessment-time 150 \\\n --expected-root sha256:... \\\n --expected-issuer buildchain.libkungfu.dev \\\n --expected-publisher kungfu-systems \\\n --expected-contract buildchain.release/v1 \\\n --json\n\nbuildchain project kfx-admission envelope.json \\\n --assessment-time 150 \\\n --json\n```\n\nBoth commands call the public artifact-verification-envelope verifier. The\nprojected `attestation`, `trustInputs`, and `kfdAssessment` are direct copies of\nthe sealed envelope, and `envelopeRoot` stays identical across Node and CLI.\nSee [`artifact-verification-envelope.md`](artifact-verification-envelope.md).\n\nVerify infra-contract lifecycle evidence bundles:\n\n```bash\nbuildchain infra-contract --mode ci --source-sha \"$GITHUB_SHA\"\nbuildchain verify infra-contract-evidence-bundle .buildchain/infra-contract-evidence-bundle.json\n```\n\nThe infra-contract `ci` mode is mutation-free. It writes validate, plan,\ncontract, propagation dry-run, evidence bundle, and verification JSON artifacts\nunder `.buildchain/`, giving reusable workflows one standard responsibility\nchain instead of hand-written command sequences.\n\nThe infra-contract verifier is read-only. It recomputes the bundle hash and\nchecks that desired, plan, approval, apply, observe, contract, and propagate\nevidence remain bound to the same contract artifact. It also recomputes the\nbundle validation summary, so stale or misleading summary booleans fail closed\neven when the bundle hash has been refreshed.\n\n`buildchain release --dry-run` explains the release-line state machine before a\nmaintainer opens or merges a channel PR:\n\n```bash\nbuildchain release --dry-run --target-ref alpha/v2/v2.2\nbuildchain release --dry-run --target-ref release/v2/v2.2 --sha <verified-sha>\nbuildchain release dry-run --target-ref publish-gate/major --source-ref release/v2/v2.2\nbuildchain release explain --target-ref alpha/v2/v2.1 --json\n```\n\nThis is a Buildchain-level dry-run, not an npm dry-run. It explains the legal\nsource branch, exact release or alpha tags, floating tags, channel branches,\nversion-state files, governance checks, and publish transaction behavior that\nwould apply if the corresponding PR merge were promoted. It does not move\nbranches, move tags, edit files, publish npm packages, or run lifecycle publish\ncommands. `release explain` is the same explanation surface with a clearer name.\nPass `--json` for a machine-readable plan.\n\n`buildchain transaction inspect` is the top-level recovery inspection command\nfor the publish transaction state:\n\n```bash\nbuildchain transaction inspect --version v2.1.0-alpha.0\n```\n\nIt reads or locally initializes the durable transaction record and validates\navailable publish evidence. Remote durable refs and public Git ref finalization\nremain owned by `actions/promote-buildchain-ref`; the CLI inspection surface is\nfor preflight and recovery reasoning before a maintainer reruns or resumes a\npromotion.\n\n`buildchain npm dry-run` verifies the package shape before a release tag exists:\n\n```bash\nbuildchain npm dry-run --json\n```\n\nThe command validates `package.json`, infers the exact release tag\n`v${package.json.version}`, chooses npm dist-tag `alpha` for prereleases and\n`latest` for stable releases, runs `npm pack --dry-run --json`, and then runs\n`npm publish --dry-run --access public --tag <alpha|latest>` unless\n`--skip-npm-publish-dry-run` is passed. It never performs a real publish.\n\n## npm Publish Gate\n\nBuildchain's own npm package is published from\n`.github/workflows/buildchain-ref-promotion.yml`, inside the same publish\ntransaction that promotes release refs:\n\n- `v2.0.13-alpha.0` publishes to npm with dist-tag `alpha`.\n- `v2.0.13` publishes to npm with dist-tag `latest`.\n- moving refs such as `v2`, `v2.0`, and `v2.0-alpha` do not match the publish\n workflow and do not publish.\n\nThe promotion workflow uses npm Trusted Publishing through GitHub Actions OIDC.\nIt runs on a GitHub-hosted runner with `id-token: write`, but it does not\nmanually run the release-candidate resolver or promote action. Buildchain's own\ndogfood path calls the declarative `release-candidate-promote.yml` wrapper with\nchannel, target ref/SHA, PR-stage workflow, artifact, status-check, and passport\ninputs. The wrapper generates the version-state commit, runs\n`lifecycle.verify`, runs `lifecycle.publish`, writes Buildchain publish\nevidence, validates that evidence, and only then moves exact tags and floating\nrefs.\n\n```bash\nnode scripts/npm-publish-transaction.mjs\n```\n\nBefore the first real release, configure npm Trusted Publishing for:\n\n- package: `@kungfu-tech/buildchain`\n- repository: `kungfu-systems/buildchain`\n- workflow: `.github/workflows/buildchain-ref-promotion.yml`\n\nNo npm package is published by manual dispatch or ordinary branch builds.\nManual dispatch on `.github/workflows/npm-publish.yml` remains dry-run only, so\nmaintainers can verify package contents and npm publish shape before opening or\nmerging the release PR."
|
|
545
|
+
"markdown": "# Buildchain CLI, npm Package, and Toolkit API\n\nBuildchain is published as the public npm package\n`@kungfu-tech/buildchain`. The package contains the `buildchain` command,\nthe importable ESM toolkit APIs, and the local scripts needed to initialize and\nvalidate repositories before they use the reusable GitHub workflow surface.\n\nThe npm package is not the release authority. Release authority still comes\nfrom the protected Buildchain branch and tag state machine. npm publishing is a\nside effect of an exact release tag that has already been produced by that\nstate machine.\n\n## Install and Run\n\nUse the published package directly:\n\n```bash\nnpx @kungfu-tech/buildchain --help\nnpx @kungfu-tech/buildchain init --type package\nnpx @kungfu-tech/buildchain validate --require-version-state\n```\n\nOr install it in a repository:\n\n```bash\npnpm add -D @kungfu-tech/buildchain\npnpm exec buildchain validate\n```\n\nConsumers should pin the exact Buildchain version that was validated in their\nrepository. When dogfooding a fresh Buildchain release immediately after it is\npublished, pnpm may block the install through a minimum release-age policy. In\nthat case, add a temporary package/version-specific `minimumReleaseAgeExclude`\nentry, such as `@kungfu-tech/buildchain@2.2.5`, and remove it once the package\nhas aged past the normal policy window. Do not replace that with a broad\nregistry or scope-wide exclude.\n\nUse the package API directly inside JavaScript build scripts:\n\n```js\nimport { createBuildchainLogger } from \"@kungfu-tech/buildchain/logging\";\n\nconst logger = createBuildchainLogger({ source: \"user\", component: \"build\" });\nawait logger.span(\"build.native\", { phase: \"build\" }, async () => {\n await buildNativeArtifacts();\n});\n```\n\nThe standalone binary and CLI are for workflow steps, shell scripts, and\nnon-JavaScript environments. JavaScript code that already depends on\n`@kungfu-tech/buildchain` should import the toolkit API instead of spawning\n`npx buildchain` or a downloaded binary.\n\n## Node API and Package Exports\n\nBuildchain's public Node API is the package `exports` surface, not arbitrary\ninternal file paths. The npm package also ships\n`dist/site/node-api-registry.json` and exports it as\n`@kungfu-tech/buildchain/site/node-api-registry.json` so agents can enumerate\nthe supported imports from the installed package.\nFor navigation, start with `dist/site/capability-registry.json`: it groups\nmanuals, CLI commands, workflow/action inputs, Node exports, site pages, and KFD\nclaim facts by product capability before an agent chooses a concrete command or\nmanual.\n\nCurrent public import families include:\n\n```js\nimport * as buildchain from \"@kungfu-tech/buildchain\";\nimport { createBuildchainLogger } from \"@kungfu-tech/buildchain/logging\";\nimport { collectModuleBuildFacts } from \"@kungfu-tech/buildchain/build-facts\";\nimport { checkHomebrewTap } from \"@kungfu-tech/buildchain/homebrew\";\nimport { verifyKfd1ReleaseGate } from \"@kungfu-tech/buildchain/kfd-gate\";\nimport { collectBadgeBundleFacts } from \"@kungfu-tech/buildchain/badges\";\nimport { collectReadmeBadgeFacts } from \"@kungfu-tech/buildchain/readme-badges\";\nimport { verifyReleasePassport } from \"@kungfu-tech/buildchain/release-passport\";\nimport { createReleasePropagationPlan } from \"@kungfu-tech/buildchain/release-propagation\";\nimport { planReleaseLineBootstrap } from \"@kungfu-tech/buildchain/release-line-bootstrap\";\nimport { collectPublicSurfaceReverseAudit } from \"@kungfu-tech/buildchain/public-surface-audit\";\nimport { createBuildchainLayoutDiscovery } from \"@kungfu-tech/buildchain/buildchain-layout\";\nimport { createPortableDevCachePlan } from \"@kungfu-tech/buildchain/portable-dev-cache\";\nimport contractWorld from \"@kungfu-tech/buildchain/site/buildchain-contract.json\" with { type: \"json\" };\nimport capabilityRegistry from \"@kungfu-tech/buildchain/site/capability-registry.json\" with { type: \"json\" };\nimport manualRegistry from \"@kungfu-tech/buildchain/site/manual-registry.json\" with { type: \"json\" };\nimport nodeApiRegistry from \"@kungfu-tech/buildchain/site/node-api-registry.json\" with { type: \"json\" };\nimport publicSurfaceAudit from \"@kungfu-tech/buildchain/site/public-surface-audit.json\" with { type: \"json\" };\n```\n\nUse `dist/site/manual-registry.json` to find the packaged operating manuals and\ntheir SHA-256 digests. Use `dist/site/buildchain-contract.json` to verify the\nfloating-ref contract world for a runtime such as `@v2`.\n\n## Commands\n\n`buildchain layout` is the stable machine question for repository layout. Tools\nsuch as Shifu should call it instead of copying `.buildchain/` path constants:\n\n```bash\nbuildchain layout --cwd /path/to/repository --json\n```\n\nThe result identifies the Buildchain version pin, repository root and config,\nthe canonical and currently resolved KFD-3 registry paths, and the KFD field\nused to declare Shifu jurisdiction. A repository is in Shifu's distribution\njurisdiction only when a KFD-3 surface explicitly declares\n`distribution.registrar=\"shifu\"`; the presence of Buildchain configuration is\nnot sufficient. The same contract is available through\n`createBuildchainLayoutDiscovery()` from\n`@kungfu-tech/buildchain/buildchain-layout`.\n\n`buildchain init` writes a starter `.buildchain/buildchain.toml` and a reusable workflow\ncaller at `.github/workflows/build.yml`.\n\n`buildchain portable-cache plan` turns a consumer-owned, secret-free manifest\ninto GitHub Actions cache inputs without letting each consumer invent key or\nrestore-prefix semantics. The exact key binds source SHA and the consumer plan\ndigest; the compatible restore prefix still requires the same provider schema,\nlayer, roots, runner image, platform/architecture, toolchain, dependency lock,\nand build profile.\n\n```bash\nbuildchain portable-cache plan \\\n --manifest .buildchain/portable-cache.json \\\n --output .buildchain/portable-cache-plan.json \\\n --github-output \"$GITHUB_OUTPUT\"\n```\n\nThe emitted `cache-key`, `restore-keys`, and `cache-paths` values are intended\nfor pinned `actions/cache/restore` and `actions/cache/save` actions. After\nrestore and a consumer validation probe, seal the provider result:\n\n```bash\nbuildchain portable-cache receipt \\\n --plan .buildchain/portable-cache-plan.json \\\n --matched-key \"$CACHE_MATCHED_KEY\" \\\n --cache-hit \"$CACHE_HIT\" \\\n --validation-status pass \\\n --cold-fallback-status passed \\\n --output .buildchain/portable-cache-receipt.json\n```\n\nThe receipt distinguishes `exact`, `compatible`, `miss`, and `corrupt`.\nUnknown or contradictory provider evidence fails closed. A miss or corruption\nrequires the consumer's audited cold path; a cache never substitutes for the\nconsumer's current build or tests. Roots must be workspace-relative or under\n`~/`, and manifests cannot carry credentials, absolute host paths, or escape\nsegments. `cold-fallback-status=passed` qualifies a miss only after the current\nsource has completed its normal build and test path.\n\nSupported presets:\n\n- `--type package` for Node package repositories with pnpm, npm, or yarn.\n- `--type native` for CMake-style native projects.\n- `--type web-surface` for preview/staging/production site or app deployments.\n- `--type infra-contract` for provider-agnostic infrastructure contract\n validation, observation, contract publication, and downstream propagation\n planning without default mutation. Provider adapters expose built-in command\n plans by default, and only configured `[infra.commands]` hooks can execute.\n- `--type publication-artifact` for papers, reports, specifications, and other\n publication repositories that produce PDFs, metadata, source bundles, and\n site-consumable manifests without becoming web-surface repositories. The\n scaffold uses Buildchain's pinned\n `ghcr.io/kungfu-systems/build-images/latex-pdf-builder:v1.2.0` toolchain for\n LaTeX PDF builds.\n- `--type distribution-index` for Homebrew taps and other index repositories\n whose files are projections of upstream release passport evidence.\n- `--type anchored-package` for packages whose version is anchored to an\n explicit upstream release manifest.\n\nThe native preset includes an opt-in `[diagnostics.native]` profile with common\ntool/cache/artifact probes. Consumers can keep it enabled, adjust the tool and\ndirectory lists, or disable it if a repository does not need native diagnostics.\n\n`buildchain validate` parses `.buildchain/buildchain.toml`, checks configured version-state\nfiles, and can require named lifecycle stages:\n\n```bash\nbuildchain validate \\\n --require-version-state \\\n --require-lifecycle-stages install,build,verify\n```\n\n`buildchain lifecycle run <stage>` executes a lifecycle stage and writes the\nsame deterministic artifact manifest contract used by the reusable workflow:\n\n```bash\nbuildchain lifecycle run build \\\n --artifact-path dist \\\n --artifact-name \"{repo}-{version}-{platform}\"\n```\n\n`buildchain dev merge-queue` plans a GitHub merge-queue policy for a protected\nBuildchain dev channel. Declare every workflow that emits a required check; the\ncommand fails closed unless each file handles both `pull_request` and\n`merge_group` without reading `github.event.pull_request` directly:\n\n```bash\nbuildchain dev merge-queue \\\n --repository kungfu-systems/example \\\n --branch dev/v4/v4.0 \\\n --workflow .github/workflows/source-acceptance.yml \\\n --workflow .github/workflows/affected-native-pr.yml\n```\n\nThe default output is a read-only plan. Add `--apply` only after reviewing it.\nApply creates the exact-branch merge-queue ruleset before changing classic\nrequired status checks from strict to loose, preserves the required check\nidentities, and is safe to repeat. `gh` must be authenticated with repository\nAdministration write permission for apply mode.\n\nRepositories can make that policy declarative in `buildchain.toml`:\n\n```toml\n[governance.dev.merge_queue]\nmode = \"enabled\" # enabled, inherit, or disabled\nrequired_workflows = [\".github/workflows/verify.yml\"]\ncheck_response_timeout_minutes = 120\nmax_entries_to_build = 1\nbypass_users = [\"release-owner\"]\n```\n\nUse `buildchain dev merge-queue --from-config` to resolve and reconcile the\ndeclaration. `enabled` requires an exact queue on the target dev branch;\n`disabled` suppresses automatic queue creation; `inherit` copies the active\ndefault dev branch's queue parameters and bypass actors. When the table is\nabsent, release-line bootstrap uses the backward-compatible `inherit` mode.\nEvery inherited or explicitly enabled queue still validates each declared\nrequired workflow before any mutation. For a legacy repository with no table,\nan already-active exact queue on the current default dev branch is accepted as\nthe inheritance evidence; new declarations should list the workflows so future\nchanges are revalidated from source.\nThe `Dev Merge Queue Governance` workflow runs this reconciliation after\ngovernance-relevant changes land on a dev branch; its manual dispatch remains\ndry-run by default.\n\n`buildchain release line open` plans or writes the first version-state commit\nfor a new semver minor line. It does not publish anything. The dry-run mode is\nthe default and returns the dev/alpha/release refs, protection contract, default\nbranch action, and initial version before any GitHub mutation happens:\n\n```bash\nbuildchain release line open \\\n --major 2 \\\n --minor 10 \\\n --source-ref release/v2/v2.9 \\\n --json\n```\n\nThe write mode only updates local version-state files. The repository workflow\n`Release Line Bootstrap` wraps this command and, when `apply=true`, commits the\ninitial version state, creates `dev/vX/vX.Y`, `alpha/vX/vX.Y`, and\n`release/vX/vX.Y`, applies one-review branch protection, reconciles declared or\ninherited merge-queue governance, switches the default branch only after that\nreconciliation succeeds, and opens the first dev-to-alpha channel PR:\n\n```bash\nbuildchain release line open \\\n --major 2 \\\n --minor 10 \\\n --source-ref release/v2/v2.9 \\\n --write \\\n --json\n```\n\n`buildchain` also publishes a public surface reverse audit as\n`dist/site/public-surface-audit.json`. The audit enumerates CLI commands from\n`bin/buildchain.mjs`, workflow inputs, action inputs, site pages, and docs\ncommand references, then compares them with the generated registries. Buildchain\nself-checks fail closed when an enumerable public surface is missing from the\nregistry:\n\n```js\nimport {\n collectPublicSurfaceReverseAudit,\n assertPublicSurfaceReverseAudit,\n} from \"@kungfu-tech/buildchain/public-surface-audit\";\n\nassertPublicSurfaceReverseAudit(collectPublicSurfaceReverseAudit({ root: process.cwd() }));\n```\n\n`buildchain kfd` is the product-facing KFD namespace. Schema commands expose the\nmachine-readable KFD standards shipped by `@kungfu-tech/kfd`, while versioned\nsubcommands host concrete product workflows. KFD-1, KFD-2, and KFD-3 are\nfirst-class Buildchain surfaces. KFD-4 is schema-only until Buildchain has a\nreal verification protocol for it.\n\n`status` reports implemented support and the active repo-owned file layout.\n`migrate-layout` moves legacy root files into `.buildchain/`:\n\n```bash\nbuildchain kfd status --json\nbuildchain kfd migrate-layout --write\n```\n\nKFD-1 commands generate and validate contract-world release evidence:\n\n```bash\nbuildchain kfd 1 schema --json\nbuildchain kfd 1 witness --json\nbuildchain kfd 1 gate --witness-json kfd-1-witness.json --json\nbuildchain kfd 1 verify --gate-json kfd-1-gate.json --json\n```\n\nKFD-2 commands validate trust taxonomy entries and generate Buildchain's public\nclaim evidence. Product repositories use the `product-claims` subcommand to\nvalidate and render their own declared KFD-2 release claims under the canonical\nBuildchain KFD layout:\n\n```bash\nbuildchain kfd 2 schema --json\nbuildchain kfd 2 taxonomy --entry-json residual-risk.json --kind residualRisk --json\nbuildchain kfd 2 claims --json\nbuildchain kfd 2 product-claims check --json\nbuildchain kfd 2 product-claims write --json\nbuildchain kfd 2 product-claims render --json\n```\n\nThe default source is `.buildchain/kfd/kfd-2/registry.json`; outputs are\n`.buildchain/kfd/kfd-2/release-claims.json`, per-claim release-passport inputs\nunder `claims/`, and `buildchain-claim-args.txt`. Use `--registry` or\n`--output-dir` only for an explicit product packaging projection. `check` never\nwrites and exits non-zero when outputs drift.\n\nKFD-3 commands are separate from Buildchain's self reverse audit: products can\ndetect standard public surfaces, register the accepted boundary, audit the\ncurrent source or artifact tree, generate a release-passport-compatible witness,\nand expose a capability map for agents:\n\n```bash\nbuildchain kfd schema list --json\nbuildchain kfd schema show kfd-3 --json\nbuildchain kfd 3 detect --kind node-api --kind cli --json\nbuildchain kfd 3 register node-api --product Buildchain\nbuildchain kfd 3 audit --json\nbuildchain kfd 3 witness --kind prebuild --output .buildchain/kfd/kfd-3/collaboration-interface.prebuild.json\nbuildchain kfd 3 query buildchain --json\nbuildchain kfd 4 schema --json\n```\n\nThe public Node API is exported from `@kungfu-tech/buildchain/kfd`. See\n[`kfd-support.md`](kfd-support.md) for the detected / declared / enforced model\nand the agent query flow.\n\nLifecycle runs also write a Buildchain observability JSONL log at\n`.buildchain/logs/events.jsonl` by default. Framework events use\n`source=buildchain`; consumer lifecycle commands use `source=user`. This lets a\nmaintainer tell apart time spent inside Buildchain's artifact/manifest\nframework from time spent in the repository's own build, test, packaging, or\npublish commands. The artifact manifest and summary embed the observability\nsummary for that lifecycle run id, so uploaded artifacts preserve the timing\nfacts without mixing in older JSONL events.\n\n`buildchain log`, `buildchain mark`, and `buildchain span` expose the same event\nprotocol to repository scripts:\n\n```bash\nbuildchain mark --event configure.ready --phase configure --attribute target=release\nbuildchain span --event native.build --phase build -- cmake --build build\nbuildchain log warn --event cache.miss --component conan --attribute token=hidden\nbuildchain log summary --json\nbuildchain verify observability-log .buildchain/logs/events.jsonl --min-events 4 --require-phase build\nbuildchain diagnostics summary .buildchain/artifacts/*/diagnostics.json --json\nbuildchain sample process-tree --label native-build --interval-ms 15000 -- make -j20\n```\n\nDuring `buildchain lifecycle run`, child processes receive\n`BUILDCHAIN_LOG_PATH` and `BUILDCHAIN_LOG_RUN_ID`. A shell, Python, CMake, Conan,\nor JavaScript helper can call `buildchain mark` or `buildchain span` mid-build\nand have those events grouped into the same lifecycle summary.\n`buildchain verify observability-log` is a release gate: it fails when the log\nis missing, has too few events, contains error events, or does not include\nrequired phases, components, or event names.\n\nThe JSON summary also includes an additive `controlPlane` block. It counts\nworkflow-friction incident outcomes and production release-intent outcomes,\nincluding incident reuse rate, release-intent suppression rate, and suppression\nreasons. Buildchain writes those outcome events locally; it does not send\ntelemetry outside the runner.\n\nThe event protocol is JSONL and is also available from the SDK:\n\n```js\nimport { createBuildchainLogger } from \"@kungfu-tech/buildchain/logging\";\n\nconst logger = createBuildchainLogger({ source: \"user\", component: \"native-build\" });\nlogger.mark(\"configure.ready\", { phase: \"configure\" });\n```\n\nSecret-looking attribute keys such as `token`, `password`, `secret`,\n`authorization`, `cookie`, and `private-key` are redacted before they are written.\nFull command strings are not recorded by `span`; scripts should provide stable\nevent names and safe attributes instead.\n\n`buildchain diagnostics summary` reads one or more small diagnostics artifacts\nand emits the same cross-platform summary as the diagnostics SDK:\n\n```bash\nbuildchain diagnostics summary \\\n .buildchain/artifacts/linux-x64/diagnostics.json \\\n .buildchain/artifacts/macos-arm64/diagnostics.json \\\n --output .buildchain/artifacts/diagnostics-summary.json \\\n --json\n```\n\nThe JSON summary keeps per-platform lifecycle stage tables, adds lifecycle\ntotal durations, carries top slow spans, aggregates warning/error counts, and\nsorts the slowest platforms. Each platform row carries compact runner facts,\nchecked tool versions/missing tools, package manager/cache directory details,\ncompiler-cache availability, and a compact process sampler summary: requested\nparallelism, observed max active processes, the ratio between them, sample\ncount, process categories, and the top sampled command basenames. This lets\nmaintainers inspect matrix timing, runner, tool, cache, and concurrency context\nwithout downloading large platform binaries or process sidecars first.\nWhen a sibling `diagnostics-manifest.json` is available, the summary also records\nits file list and verifies the listed `diagnostics.json` byte count and sha256.\nMissing, unreadable, or mismatched sidecar manifests are reported through\n`diagnosticsManifestWarningCount` and the per-platform `diagnosticsManifest`\nfield without failing the timing rollup.\nThe summary also compares each `diagnostics.json` contract to\n`BUILDCHAIN_DIAGNOSTICS_CONTRACT`; mismatches are reported through\n`diagnosticsContractWarningCount` and the per-platform `diagnosticsContract`\nfield so reviewers can separate diagnostics schema drift from lifecycle\nwarnings or build failures.\n\nWithout `--json`, the command prints a compact lifecycle timing table with\ninstall/build/verify/publish, artifact scan/upload, total, warning, and error\ncolumns for each platform, plus `jobs` and `active` columns for requested and\nobserved process concurrency when sampler data is present.\n\n`buildchain facts` collects and verifies source/version/output facts for\nmodules and products:\n\n```bash\nbuildchain facts module \\\n --module native-core \\\n --output .buildchain/facts/native-core.json \\\n --legacy-kungfu-buildinfo framework/core/src/kungfu/yijinjing/kungfubuildinfo.json\n\nbuildchain facts aggregate \\\n --product kungfu \\\n --module-fact .buildchain/facts/native-core.json \\\n --artifact dist/kungfu.zip \\\n --output .buildchain/facts/kungfu.json\n\nbuildchain facts verify --fact .buildchain/facts/kungfu.json\n```\n\nThe same implementation is available from\n`@kungfu-tech/buildchain/build-facts`. Release passports can include these\nfacts with repeated `--build-facts-json` arguments to\n`buildchain collect github-release`. See\n[`build-facts.md`](build-facts.md) for the config schema and Node API.\n\n`buildchain sample process-tree` wraps a long-running command and periodically\nwrites process-tree snapshots:\n\n```bash\nbuildchain sample process-tree \\\n --label native-build \\\n --interval-ms 15000 \\\n --output .buildchain/diagnostics/process-samples.jsonl \\\n --summary-output .buildchain/diagnostics/process-summary.json \\\n -- \\\n make -j20\n```\n\nThe command returns the wrapped command's exit status. The JSONL file contains\nsmall timestamped samples; the summary JSON records requested parallelism,\nobserved concurrency, sampled CPU, command categories, and top command\nbasenames. Use it when a native build requests high parallelism but appears to\nspend long stretches in low-concurrency compile, archive, link, or cache steps.\n\n`buildchain doctor` checks repository readiness before remote side effects:\n\n```bash\nbuildchain doctor --json\n```\n\nIt validates `.buildchain/buildchain.toml`, package-manager detection, Git repository state,\nand the reusable workflow caller. For `version.strategy = \"anchored\"` with\n`version.next = \"manual\"`, it also embeds the anchored package release contract\ncheck: anchor manifest readability, configured version files, trusted\npublishing, package publish order, and required lifecycle stages. Add\n`--require-publish-source-lock` inside a publish job when the doctor report\nshould also fail unless the job is running from a resolved `publish-gate/*`\nsource lock.\n\nAnchored/manual package publish jobs can run the narrower source-lock gate\ndirectly:\n\n```bash\nbuildchain publish-source validate-anchored-release --json\n```\n\nThe command requires `BUILDCHAIN_PUBLISH_SOURCE_REF`,\n`BUILDCHAIN_PUBLISH_SOURCE_SHA`, and `BUILDCHAIN_PUBLISH_SOURCE_LOCKED` from the\nreusable build workflow outputs. It fails closed for direct `alpha/*` or\n`release/*` channel-branch publication, and checks the publish-gate consumer\nversion against configured version files and the anchor manifest. The JSON\nresult is shaped for future `buildchain.libkungfu.dev` fact ingestion.\n\n`buildchain release`, `buildchain web-surface`, `buildchain infra-contract`,\n`buildchain publication-artifact`, `buildchain publish-source`,\n`buildchain badges`, `buildchain homebrew`, and `buildchain build-contract`\nroute to the same implementation used by\nBuildchain's package APIs or GitHub Actions workflows. This keeps local\ninspection and CI behavior on the same implementation path.\n\nGenerate publication artifact metadata after building a paper or report:\n\n```bash\nbuildchain publication-artifact manifest \\\n --source-sha \"$(git rev-parse HEAD)\" \\\n --json\n```\n\nGenerate the Buildchain-owned npm paper package contents from declared\npublication facts:\n\n```bash\nbuildchain publication-artifact npm-package --json\n```\n\nThis command reads `project.type = \"publication-artifact\"`,\n`publication.version`, and `[publish] kind = \"npm-paper-package\"` plus\n`publish.package`; it writes `.buildchain/publication/npm-package` by default.\nThe `paper-release.yml@v2` reusable workflow uses the same command before\nrunning the standard npm publish transaction.\n\nThe command writes `.buildchain/publication/publication-artifact.json`,\n`.buildchain/publication/publication-artifact-passport.json`, a source bundle,\nand, when `[publication.archive]` is configured,\n`.buildchain/publication/publication-registry.json` by default. See\n[`publication-artifacts.md`](publication-artifacts.md) for the repository\ncontract, pinned LaTeX builder, and reusable workflow.\n\nGenerate, check, or update the managed README badge block:\n\n```bash\nbuildchain badges readme --json\nbuildchain badges readme --check\nbuildchain badges readme --write\nbuildchain badges bundle --json\nbuildchain badges bundle --check\nbuildchain badges bundle --write\nbuildchain badges bundle --claims kfd-1,release-passport --write\n```\n\nThe `--json` form emits the `kungfu-buildchain-readme-badge-facts` object.\n`--check` fails closed when the README marker block is missing or stale.\n`--write` inserts or replaces only the marked block. KFD passed badges come\nfrom the repository's own verified release passport; unreleased repositories\ndowngrade to explicit local declarations such as `declared`, `aligned`, or\n`planned`. `buildchain badges bundle` is the focused trust-badge entrypoint: it\nemits `kungfu-buildchain-badge-bundle-facts` and defaults to KFD-1, KFD-2,\nKFD-3, and Release Passport. See [`readme-badges.md`](readme-badges.md) for the\nmarker contract and `[badges]` / `[badges.bundle]` configuration.\n\nGenerate or check Homebrew tap projections from upstream release passports:\n\n```bash\nbuildchain homebrew update-formula \\\n --package buildchain \\\n --release-passport https://github.com/kungfu-systems/buildchain/releases/download/v2.8.15/buildchain.release.json \\\n --write\n\nbuildchain homebrew check --json\n```\n\n`update-formula` writes `Formula/buildchain.rb` and `tap-manifest.json` from\nupstream release passport evidence. `check` fails closed when the Formula,\nmanifest, artifact digests, or KFD status drift from the upstream passport. See\n[`homebrew.md`](homebrew.md) for the distribution-index project contract.\n\n`buildchain collect github-release` creates a release passport bundle from\nGitHub Release assets or a local asset directory:\n\n```bash\nbuildchain collect github-release \\\n --tag v2.2.0 \\\n --repository kungfu-systems/buildchain \\\n --assets-dir dist \\\n --output-dir .buildchain/release-passport\n```\n\nThe bundle includes `buildchain.release.json`, `artifact-evidence.json`,\n`impact.json`, `agent-index.json`, `product-mechanism.json`, `check-report.json`,\nand `llms.txt`. Production binary distribution defaults to GitHub-hosted\nrunners so other projects can reproduce the release lane; self-hosted runners\nremain compatibility fixtures and are recorded as runner facts when used.\n\nFor publish-transaction releases, pass the additional evidence inputs so\n`buildchain.release.json` becomes the unified passport instead of a binary-only\nasset summary:\n\n```bash\nbuildchain collect github-release \\\n --tag v2.3.2 \\\n --repository kungfu-systems/buildchain \\\n --assets-dir dist \\\n --publish-evidence-json .buildchain/release-evidence/v2.3.2/evidence.json \\\n --transaction-json .buildchain/release-state/v2.3.2/state.json \\\n --package-set-json package-set.json \\\n --impact-json impact.json \\\n --trusted-publishing-json trusted-publishing.json \\\n --anchor-manifest-json libnode.release.json \\\n --build-summary-json .buildchain/artifacts/build-summary.json \\\n --platform-manifest-json .buildchain/artifacts/linux-x64/manifest.json \\\n --platform-manifest-json .buildchain/artifacts/darwin-arm64/manifest.json \\\n --platform-manifest-json .buildchain/artifacts/win32-x64/manifest.json \\\n --dist-tag-evidence-json .buildchain/release-evidence/v2.3.2/dist-tag-evidence.json \\\n --kfd-1-witness-json .buildchain/kfd/kfd-1/contract-world.witness.json \\\n --kfd-2-claim-json .buildchain/kfd/kfd-2/release-claims.json \\\n --kfd-3-prebuild-witness-json .buildchain/kfd/kfd-3/collaboration-interface.prebuild.json \\\n --kfd-3-artifact-verify-cmd \"kungfu agent verify --json\" \\\n --release-extra-json '{\"channel\":\"release\",\"targetRef\":\"release/v2/v2.3\"}' \\\n --output-dir .buildchain/release-passport\n```\n\nThe generated passport records the main and platform packages, npm dist-tags,\npublished versions, release source/ref state, anchor manifest digest, registry\nartifact digests, trusted publishing evidence, and Buildchain transaction\nresult. It also records `buildSummary`, `platformArtifactManifests`, and\n`distTagPromotion` when those JSON inputs are supplied. `packageSet` keeps the\nordered package set; `publish.packages[]` is the agent-readable npm publication\nsummary for each main/platform package. For Buildchain releases, verification\nexpects the supplied package set to include the main package plus the three\nplatform packages with version, dist-tag, and digest evidence. Verification\nfails closed if supplied sections are internally incomplete or point to\nartifacts without matching evidence.\n\n`--kfd-1-witness-json` attaches a KFD-1 contract-world release gate. The witness\nis structured JSON: consumers declare the contract world, canonical JSON policy,\nartifact paths, and expected SHA-256 digests. Buildchain imports KFD-owned\nmetadata from `@kungfu-tech/kfd`, freezes the witness before build publication,\nthen verifies the resulting artifact bytes itself and writes the evidence under\nthe KFD-provided top-level key currently named `kfd-1`. Consumers should not\nduplicate this by running repository-specific scripts or invoking the Kungfu\nSDK from their release workflow.\n\nFor the KFD repository, KFD-1 witnesses may be self-hosted standard-contract\nwitnesses: docs, schemas, standards metadata, package exports, and\nsite-consumption entrypoints are checked from source hashes to packaged artifact\nhashes, and the passport records schema IDs, self-hosting boundary, result, and\nresponsibility state.\n\n`--kfd-2-claim-json` attaches explicit public release claims to the KFD-2\nrelease trust passport audit. Buildchain also derives KFD-2 claims from KFD-1\nand KFD-3 gate evidence. Public claims must bind declared sources,\nmachine-readable evidence, hashes, artifact coordinates, verification results,\naudit boundary, responsibility state, and residual risk. Unbound claims fail\npassport verification; prose-only claims downgrade the KFD-2 audit and emit a\nwarning.\n\n`--kfd-3-prebuild-witness-json` attaches a KFD-3 collaboration-interface\nrelease gate. The product remains the source of truth: it emits a pre-build\nwitness that contains or points to its KFD-3 collaboration interface, declared\nparticipant-facing public surfaces, and registry digest. Buildchain freezes\nthat declaration before publication. The artifact side is supplied either by\n`--kfd-3-artifact-witness-json` or by a product-owned command such as\n`--kfd-3-artifact-verify-cmd \"kungfu agent verify --json\"`. Buildchain then\nchecks closure: every declared shipped public surface must be present in the\nartifact witness, and every artifact-exposed participant-facing public surface\nmust have been declared. The generated passport writes this evidence under the\nKFD-provided top-level key currently named `kfd-3`.\n\nThis gate is useful for agent-facing products because it turns KFD-3 from prose\ninto release evidence. A package cannot claim KFD-3 collaboration-interface\nsupport merely because the docs mention it; the release passport must show the\nfrozen declaration, the artifact-side witness digest, and a passing closure\ncomparison.\n\n`--invariant-passport-json` attaches a product-owned invariant Passport to the\nrelease gate and may be repeated. `--invariant-passport-cmd` runs a product\ncommand that emits one Passport JSON document. Buildchain verifies the\nPassport root, exact clean source identity, `verified` verdict, complete\nplatform coverage, and residual-risk shape; it does not redefine the product's\ninvariant semantics. Declared invariant Passport input is fail-closed.\nFor the KFD repository itself, the witness can declare docs, schemas, standards\nmetadata, package exports, and site-consumption contracts as grouped public\nsurfaces; the artifact witness must expose the same enumerable package/site\nsurfaces or verification fails closed.\n\n`--impact-json` supplies the surface-aware impact ledger. Production release\npassports (`release/*`) and major publish-gate passports require\n`surfaceImpacts[]`; alpha, local, and legacy passport contexts keep it\noptional. When `surfaceImpacts[]` is required or supplied, the verifier requires\neach entry to include an id, impact, and rationale, and requires\n`versionImpact.final` to match the highest declared surface impact. The\ncollector copies `versionImpact` plus `surfaceImpacts` into\n`buildchain.release.json`. This lets\n`buildchain explain release --for agent --json` state why a release is patch,\nminor, or major instead of relying on file-path memory.\n\nFor a promote-only stable transaction, Buildchain can derive a patch-level\nrelease-governance ledger when the PR-stage release-candidate passport proves\nthe stable source tree is exactly the previously qualified candidate tree.\nThis fallback is unavailable when candidate evidence is absent, stale, or not\ntree-equivalent.\n\nBuildchain dogfoods its observability toolkit in this lane. The standalone\nbuilder writes API-generated events, while the workflow uses `buildchain mark`,\n`buildchain span`, `buildchain verify observability-log`, and `buildchain log\nsummary`; the event logs and summaries are published as release passport assets.\n\nVerify and explain release passports:\n\n```bash\nbuildchain verify release-passport .buildchain/release-passport/buildchain.release.json\nbuildchain explain release --passport .buildchain/release-passport/buildchain.release.json --for agent --json\nbuildchain inspect release --passport .buildchain/release-passport/buildchain.release.json\n```\n\nThe verifier fails closed when required protocol files are absent, artifacts are\nnot covered by evidence, or digests disagree. The explanation output is shaped\nfor agents: trust, completeness, impact, recovery route, and next action.\n\nVerify a published artifact by subject:\n\n```bash\nbuildchain verify artifact ./Kungfu-2.8.0-windows-x64.exe\nbuildchain inspect artifact ./Kungfu-2.8.0-windows-x64.exe --json\nbuildchain explain artifact ./Kungfu-2.8.0-windows-x64.exe --for agent --json\nbuildchain verify artifact npm:@kungfu-tech/libnode@22.22.3-kf.3-alpha.18 \\\n --repository kungfu-systems/libnode \\\n --tag v22.22.3-kf.3-alpha.18 \\\n --json\n```\n\n`verify artifact` computes or obtains the subject digest, discovers the\ndetached release passport, verifies the passport, then requires that the\nsubject digest appears in the passport's release assets, package set, publish\nevidence, or artifact evidence. Outcomes are explicit: `pass`, `fail`, or\n`unverifiable`. A filename is only a hint; trust comes from digest equality.\nFor `npm:<name>@<version>` subjects, Buildchain resolves `dist.integrity` from\nthe npm registry before matching passport evidence. Use `--npm-registry <url>`\nto verify packages from a custom registry; otherwise Buildchain uses\n`npm_config_registry` or `https://registry.npmjs.org/`.\n\nDiscovery is fail-closed and ordered:\n\n1. `--passport <file-or-url>`.\n2. Sidecar pointer, such as `<artifact>.buildchain-passport.json`.\n3. Embedded/package pointer, such as `package.json` `buildchain.releasePassport`.\n4. Local config or org index, such as `.buildchain/artifact-passport-locators.json`.\n5. GitHub Release default discovery from `github-release:` subjects, GitHub\n Release asset URLs, or `--repository <owner/repo> --tag <tag>`.\n6. Custom `--locator-config <json-or-url>`.\n7. `unverifiable` with retry guidance.\n\nLocator files are policy, not protocol. They map subject fields such as\n`name`, `kind`, `version`, `digest`, `repository`, or `tag` to a detached\npassport location:\n\n```json\n{\n \"schemaVersion\": 1,\n \"contract\": \"kungfu-buildchain-artifact-passport-locator\",\n \"locators\": [\n {\n \"match\": {\n \"name\": \"Kungfu-2.8.0-windows-x64.exe\",\n \"digest\": \"sha256:...\"\n },\n \"passport\": \"../release-passport/buildchain.release.json\"\n }\n ]\n}\n```\n\nSupported subject shapes include local files and directories, URLs,\n`npm:<name>@<version>`, `oci:...`, `s3:...`,\n`github-release:<owner/repo>@<tag>/<asset>`, and deployment endpoints. Local\nfiles, directories, and URLs are digestable directly; remote package, OCI,\nobject storage, and deployment subjects should provide a digest or resolve to a\nlocator that records one.\n\nSeal an exact artifact verification with the Node API, then verify or project\nthe resulting KFX admission envelope without reconstructing its roots:\n\n```bash\nbuildchain verify artifact-envelope envelope.json \\\n --assessment-time 150 \\\n --expected-root sha256:... \\\n --expected-issuer buildchain.libkungfu.dev \\\n --expected-publisher kungfu-systems \\\n --expected-contract buildchain.release/v1 \\\n --json\n\nbuildchain project kfx-admission envelope.json \\\n --assessment-time 150 \\\n --json\n```\n\nBoth commands call the public artifact-verification-envelope verifier. The\nprojected `attestation`, `trustInputs`, and `kfdAssessment` are direct copies of\nthe sealed envelope, and `envelopeRoot` stays identical across Node and CLI.\nSee [`artifact-verification-envelope.md`](artifact-verification-envelope.md).\n\nVerify infra-contract lifecycle evidence bundles:\n\n```bash\nbuildchain infra-contract --mode ci --source-sha \"$GITHUB_SHA\"\nbuildchain verify infra-contract-evidence-bundle .buildchain/infra-contract-evidence-bundle.json\n```\n\nThe infra-contract `ci` mode is mutation-free. It writes validate, plan,\ncontract, propagation dry-run, evidence bundle, and verification JSON artifacts\nunder `.buildchain/`, giving reusable workflows one standard responsibility\nchain instead of hand-written command sequences.\n\nThe infra-contract verifier is read-only. It recomputes the bundle hash and\nchecks that desired, plan, approval, apply, observe, contract, and propagate\nevidence remain bound to the same contract artifact. It also recomputes the\nbundle validation summary, so stale or misleading summary booleans fail closed\neven when the bundle hash has been refreshed.\n\n`buildchain release --dry-run` explains the release-line state machine before a\nmaintainer opens or merges a channel PR:\n\n```bash\nbuildchain release --dry-run --target-ref alpha/v2/v2.2\nbuildchain release --dry-run --target-ref release/v2/v2.2 --sha <verified-sha>\nbuildchain release dry-run --target-ref publish-gate/major --source-ref release/v2/v2.2\nbuildchain release explain --target-ref alpha/v2/v2.1 --json\n```\n\nThis is a Buildchain-level dry-run, not an npm dry-run. It explains the legal\nsource branch, exact release or alpha tags, floating tags, channel branches,\nversion-state files, governance checks, and publish transaction behavior that\nwould apply if the corresponding PR merge were promoted. It does not move\nbranches, move tags, edit files, publish npm packages, or run lifecycle publish\ncommands. `release explain` is the same explanation surface with a clearer name.\nPass `--json` for a machine-readable plan.\n\n`buildchain transaction inspect` is the top-level recovery inspection command\nfor the publish transaction state:\n\n```bash\nbuildchain transaction inspect --version v2.1.0-alpha.0\n```\n\nIt reads or locally initializes the durable transaction record and validates\navailable publish evidence. Remote durable refs and public Git ref finalization\nremain owned by `actions/promote-buildchain-ref`; the CLI inspection surface is\nfor preflight and recovery reasoning before a maintainer reruns or resumes a\npromotion.\n\n`buildchain npm dry-run` verifies the package shape before a release tag exists:\n\n```bash\nbuildchain npm dry-run --json\n```\n\nThe command validates `package.json`, infers the exact release tag\n`v${package.json.version}`, chooses npm dist-tag `alpha` for prereleases and\n`latest` for stable releases, runs `npm pack --dry-run --json`, and then runs\n`npm publish --dry-run --access public --tag <alpha|latest>` unless\n`--skip-npm-publish-dry-run` is passed. It never performs a real publish.\n\n## npm Publish Gate\n\nBuildchain's own npm package is published from\n`.github/workflows/buildchain-ref-promotion.yml`, inside the same publish\ntransaction that promotes release refs:\n\n- `v2.0.13-alpha.0` publishes to npm with dist-tag `alpha`.\n- `v2.0.13` publishes to npm with dist-tag `latest`.\n- moving refs such as `v2`, `v2.0`, and `v2.0-alpha` do not match the publish\n workflow and do not publish.\n\nThe promotion workflow uses npm Trusted Publishing through GitHub Actions OIDC.\nIt runs on a GitHub-hosted runner with `id-token: write`, but it does not\nmanually run the release-candidate resolver or promote action. Buildchain's own\ndogfood path calls the declarative `release-candidate-promote.yml` wrapper with\nchannel, target ref/SHA, PR-stage workflow, artifact, status-check, and passport\ninputs. The wrapper generates the version-state commit, runs\n`lifecycle.verify`, runs `lifecycle.publish`, writes Buildchain publish\nevidence, validates that evidence, and only then moves exact tags and floating\nrefs.\n\n```bash\nnode scripts/npm-publish-transaction.mjs\n```\n\nBefore the first real release, configure npm Trusted Publishing for:\n\n- package: `@kungfu-tech/buildchain`\n- repository: `kungfu-systems/buildchain`\n- workflow: `.github/workflows/buildchain-ref-promotion.yml`\n\nNo npm package is published by manual dispatch or ordinary branch builds.\nManual dispatch on `.github/workflows/npm-publish.yml` remains dry-run only, so\nmaintainers can verify package contents and npm publish shape before opening or\nmerging the release PR."
|
|
546
546
|
},
|
|
547
547
|
{
|
|
548
548
|
"id": "manual:consumer-issue-reporting",
|
|
@@ -2139,7 +2139,7 @@
|
|
|
2139
2139
|
],
|
|
2140
2140
|
"maturity": "stable",
|
|
2141
2141
|
"sourcePath": "docs/toolkit-observability.md",
|
|
2142
|
-
"digest": "sha256:
|
|
2142
|
+
"digest": "sha256:d7f4179c3912d7bbc5940bfba69e674fb03d020a740063c0b877a171bd5789e3",
|
|
2143
2143
|
"headings": [
|
|
2144
2144
|
{
|
|
2145
2145
|
"level": 1,
|
|
@@ -2177,7 +2177,7 @@
|
|
|
2177
2177
|
"anchor": "release-gate"
|
|
2178
2178
|
}
|
|
2179
2179
|
],
|
|
2180
|
-
"markdown": "# Toolkit Observability\n\nBuildchain ships a small logging toolkit for repository workflows and project\nscripts. The goal is to separate time spent in Buildchain's framework from time\nspent in the consumer's own build, test, packaging, and publish steps.\n\n## Choose API or CLI\n\n`@kungfu-tech/buildchain` is not only a CLI package. It exports ESM toolkit APIs\nthat project scripts can import directly:\n\n```js\nimport { createBuildchainLogger } from \"@kungfu-tech/buildchain/logging\";\n```\n\nUse the API inside JavaScript or TypeScript build code. Do not spawn\n`buildchain`, download the standalone binary, or shell out through `npx` from\ncode that can import the package. The CLI is for GitHub Actions steps, shell\nscripts, and non-JavaScript tools.\n\nWhen a script runs inside `buildchain lifecycle run`, the lifecycle runner sets\n`BUILDCHAIN_LOG_PATH` and `BUILDCHAIN_LOG_RUN_ID`. Imported loggers pick up those\nenvironment variables automatically, so events emitted deep inside the build are\ngrouped into the same lifecycle summary.\n\nOutside a Buildchain lifecycle or GitHub Actions run, the logger defaults to\nconsole output unless a path is provided. Pass `path` when local scripts should\nwrite a reusable JSONL log:\n\n```js\nconst logger = createBuildchainLogger({\n path: \".buildchain/logs/native-build.jsonl\",\n source: \"user\",\n component: \"native-build\",\n});\n```\n\n## Library API\n\n```js\nimport {\n createBuildchainLogger,\n verifyBuildchainLogEvents,\n} from \"@kungfu-tech/buildchain/logging\";\n\nconst logger = createBuildchainLogger({\n source: \"user\",\n component: \"native-build\",\n});\n\nlogger.mark(\"configure.ready\", {\n phase: \"configure\",\n attributes: { preset: \"release\" },\n});\n\nawait logger.span(\"native.compile\", {\n phase: \"build\",\n attributes: { target: \"release\" },\n}, async () => {\n await compile();\n});\n\nlogger.spanSync(\"native.archive\", {\n phase: \"build\",\n attributes: { tool: \"libtool\" },\n}, () => {\n archiveStaticLibraries();\n});\n\nlogger.spawnSync(\"native.build\", \"make\", [\"-j20\"], {\n stdio: \"inherit\",\n}, {\n phase: \"build\",\n attributes: { requestedJobs: 20 },\n});\n\nconst report = verifyBuildchainLogEvents({\n path: logger.path,\n minEvents: 3,\n requirePhases: [\"configure\", \"build\"],\n requireEvents: [\n \"configure.ready\",\n \"native.compile.start\",\n \"native.compile.end\",\n ],\n});\n\nif (!report.ok) {\n throw new Error(\"Buildchain observability verification failed\");\n}\n```\n\nUse the API when a build script has internal stages that are invisible to the\nouter workflow. Keep secret values out of attributes; known sensitive keys are\nredacted, but callers should still avoid logging private material.\n\n## Candidate timelines and critical-path-safe timing\n\nLifecycle diagnostics retain their existing summed-duration tables for\ncompatibility. Do not interpret those tables as elapsed time when spans are\nnested or jobs run in parallel. Use the candidate timeline contract when a\nchange must be followed from pull-request admission through Merge Queue attempts\nto its final merge:\n\n```js\nimport {\n createCandidateTimeline,\n formatCandidateTimelineReport,\n} from \"@kungfu-tech/buildchain/candidate-timeline\";\n\nconst timeline = createCandidateTimeline({\n candidate: {\n repository: \"owner/repository\",\n baseBranch: \"dev/v4/v4.0\",\n sourceSha,\n pullRequest: 123,\n },\n events,\n});\n\nconsole.log(formatCandidateTimelineReport(timeline));\n```\n\nEach event binds a stable event id to one attempt id and may also bind a Gate\nid, merge-group SHA, workflow run, platform, partition, cache outcome, execution\nboundary, and parent span. Terminal execution states (`success`, `failure`, and\n`cancelled`) require start and completion timestamps. Non-executed states use\n`skipped`, `dependency-blocked`, or `not-required` without invented timings.\nRecord the clock and timestamp precision explicitly: GitHub Actions timestamps\nare normally provider wall-clock observations with one-second precision, while\nan in-process span may also carry a monotonic duration with millisecond or\nbetter precision.\n\nThe `buildchain.candidate-timeline/v1` artifact reports an independent critical\npath for every attempt. Its critical-path duration is the attempt's observed\nwall-clock envelope; its active duration and per-phase durations are interval\nunions. This prevents nested or parallel spans from being added twice, and it\ndoes not combine a failed or dequeued attempt with a later retry. Missing\nrequired measurements make that attempt `incomplete` instead of producing fake\nprecision.\n\nEach attempt also reports measured execution lanes, lane skew, cache outcome\ncounts, the ten longest actionable spans, and one falsifiable next optimization\ntarget. Queue residence, whole-workflow envelopes, and job parents are excluded\nfrom the actionable ranking so they cannot hide the build or qualification\nstage that can actually be changed. The target is an observation, not a causal\nclaim: repeat the same source-bound cohort and disprove it by reducing that span\nbelow the next measured span without increasing attempt elapsed time or\nfailures.\n\nShell and workflow consumers can generate the same machine artifact plus a\ncompact report:\n\n```sh\nbuildchain candidate timeline \\\n --input .buildchain/candidate-timeline-input.json \\\n --output .buildchain/candidate-timeline.json\n```\n\nThe input and output should contain only bounded correlation facts and timing\nreceipts. Do not include tokens, environment dumps, full commands, raw process\ndumps, or private absolute paths.\n\nCommonJS scripts should import Buildchain's ESM surfaces dynamically:\n\n```js\nconst { createBuildchainLogger } = await import(\"@kungfu-tech/buildchain/logging\");\nconst { collectRunnerDiagnostics } = await import(\"@kungfu-tech/buildchain/diagnostics\");\n```\n\n## Diagnostics API\n\nThe diagnostics surface collects local, non-telemetry build facts that are\nuseful when a native build is slow or flaky:\n\n```js\nimport {\n collectBuildchainDiagnostics,\n collectCacheDiagnostics,\n collectCompilerCacheDiagnostics,\n collectRunnerDiagnostics,\n collectToolDiagnostics,\n detectRequestedParallelism,\n startProcessSampler,\n summarizeDiagnosticsArtifacts,\n summarizeLifecycleObservability,\n summarizeProcessSamples,\n validateAnchoredPackageRelease,\n writeDiagnosticsArtifact,\n} from \"@kungfu-tech/buildchain/diagnostics\";\n\nconst lifecycleObservability = summarizeLifecycleObservability({\n logPath: \".buildchain/logs/events.jsonl\",\n});\nconst buildCommand = \"make\";\nconst buildArgs = [\"-j20\"];\nconst requestedParallelism = detectRequestedParallelism({\n command: buildCommand,\n args: buildArgs,\n});\nconst processSampler = startProcessSampler({\n intervalMs: 15000,\n label: \"native-build\",\n command: buildCommand,\n args: buildArgs,\n});\n// Run the long native build while the sampler is active.\nconst processSummary = summarizeProcessSamples({\n requestedParallelism: requestedParallelism.value,\n samples: processSampler.stop(),\n});\nconst cacheDiagnostics = collectCacheDiagnostics({ cwd: process.cwd() });\n\nwriteDiagnosticsArtifact(\".buildchain/artifacts/diagnostics.json\", {\n contract: \"consumer-build-diagnostics\",\n buildchain: collectBuildchainDiagnostics({ cwd: process.cwd() }),\n runner: collectRunnerDiagnostics(),\n tools: collectToolDiagnostics({ cwd: process.cwd() }),\n cache: cacheDiagnostics,\n lifecycleObservability,\n process: processSummary,\n});\n```\n\n`collectCacheDiagnostics()` includes package-manager/workspace context, selected\ncache directory stats, and compiler-cache stats from `ccache --show-stats\n--json` plus `sccache --show-stats --stats-format json` when those tools are\npresent. If a ccache build does not support JSON stats, Buildchain falls back to\nplain `ccache --show-stats` and parses the text counters. Missing cache tools\nare recorded as unavailable instead of failing the diagnostics artifact. Call\n`collectCompilerCacheDiagnostics()` directly when a consumer script only needs\ncompiler cache data. Native diagnostics also expose `compilerCaches` and\n`nativeCacheDirs` as top-level fields in each diagnostics artifact and aggregate\nsummary, so reviewers do not have to dig through nested cache sections first.\n\nProcess samples are intentionally summarized before they become long-lived\nartifacts. The summary records requested parallelism, the source of that value\n(`command`, `process-tree`, `env:MAKEFLAGS`,\n`env:CMAKE_BUILD_PARALLEL_LEVEL`, or `explicit`), observed active process\nconcurrency, elapsed sample time, total sampled CPU, and conservative command\ncategories such as `compiler`, `archive`, `linker`, `build-tool`, and `cache`.\nThe sampler detects common `make -j N`, `ninja -j N`, CMake/MSBuild/Xcode job\nflags, and MAKEFLAGS. This lets native projects distinguish \"we asked for\n`make -j20`\" from \"the build graph only kept two active compiler or archive\nchildren busy during the sampled window\" without storing environment dumps.\n\nNative repositories can opt into a reusable diagnostics profile in\n`buildchain.toml`:\n\n```toml\n[diagnostics.native]\nenabled = true\nsample_process_tree = true\ncompiler_cache = \"auto\"\nexpected_tools = [\"ccache\", \"sccache\", \"clang\", \"cl\", \"cmake\", \"ninja\"]\nartifact_dirs = [\"build\", \"dist\", \"build/Release\"]\ncache_dirs = [\".ccache\", \".sccache\"]\n```\n\nWhen enabled, diagnostics artifacts include the normalized profile, selected\ntool versions, compiler-cache stats, and configured artifact/cache directory\nstats. The profile is data-driven: Buildchain does not assume a specific\nproject such as libnode. The reusable build workflow also exposes\n`sample-process-tree`, which wraps the build lifecycle with the process sampler\nand carries the generated summary into the final diagnostics artifact. Custom\nworkflows can call `buildchain sample process-tree` directly when they need a\ndifferent command boundary.\n\nAnchored/manual package projects can also run one higher-level release-shape\ncheck instead of assembling lower-level config calls:\n\n```js\nconst anchoredReport = validateAnchoredPackageRelease({\n cwd: process.cwd(),\n requireManifest: true,\n requirePackageSetOrder: \"platforms-first-main-last\",\n requireTrustedPublishing: true,\n});\n\nif (!anchoredReport.ok) {\n throw new Error(\"Anchored package release contract failed\");\n}\n```\n\nIn an actual publish job, make that check source-lock aware:\n\n```js\nconst publishReady = validateAnchoredPackageRelease({\n cwd: process.cwd(),\n requirePublishGateSourceLock: true,\n});\n```\n\nThe source-lock inputs are read from `BUILDCHAIN_PUBLISH_SOURCE_REF`,\n`BUILDCHAIN_PUBLISH_SOURCE_SHA`, and `BUILDCHAIN_PUBLISH_SOURCE_LOCKED`, which\nthe reusable build workflow emits after resolving `publish-source-ref`. That\nturns direct channel-branch publication from `alpha/*` or `release/*` into a\nhard failure, while `publish-gate/alpha/<line>/<version>` and\n`publish-gate/release/<line>/<version>` also validate the requested consumer\nversion against configured version files and the anchor manifest.\n\n`buildchain lifecycle run` writes this small diagnostics artifact next to the\nplatform manifest by default. The per-platform diagnostics upload includes the\ncompact `diagnostics.json`, `diagnostics-manifest.json`, lifecycle\n`events.jsonl`, and, when process sampling is enabled, copied\n`process-summary.json` and `process-samples.jsonl` sidecars. The sidecar\nmanifest records each uploaded diagnostics file with its relative path, byte\ncount, and sha256 hash. It is intended to stay small enough to download without\nfetching large binary packages, and it should not include full environment dumps\nor secret-looking values.\n\nUse `summarizeDiagnosticsArtifacts()` when a matrix build uploads one\ndiagnostics artifact per platform. The summary keeps each platform's lifecycle\nstage table, adds a lifecycle total duration, carries the top slow spans, and\naggregates warning/error counts plus the slowest platforms. Per-platform rows\nalso include compact runner facts, checked tool versions/missing tools, package\nmanager/cache directory details, compiler cache availability, and a compact\nprocess sampler view with requested parallelism, observed max active processes,\nthe ratio between them, sample count, process categories, and top sampled\ncommand basenames. That gives release reviewers a small cross-platform timing,\nrunner, tool, cache, and concurrency view without downloading full build outputs\nor process sidecars.\n\nThe reusable build workflow writes that rollup as `diagnostics-summary.json` and\nuploads it in a separate aggregate diagnostics summary artifact. Consumers can\nread the `build-diagnostics-summary-artifact` output when they need only timing,\nwarning/error, runner, cache, and process-sampler context instead of the build\nsummary or binary artifacts. Per-platform rows keep the diagnostics `links`\nobject, including the binary artifact name, manifest artifact name, diagnostics\nartifact name, platform id, diagnostics sidecar manifest path, manifest path,\nsummary path, and process sidecar paths when present. They also keep compact\nrunner/tool/cache summaries so reviewers can tell whether a slow row ran on the\nexpected runner, missed an expected tool, or lacked useful compiler-cache stats.\nWhen the downloaded platform diagnostics include a sibling\n`diagnostics-manifest.json`, `summarizeDiagnosticsArtifacts()` carries a compact\n`diagnosticsManifest` section for that platform and verifies the manifest's\n`diagnostics.json` byte count and sha256. Missing or mismatched sidecar manifests\nincrement `diagnosticsManifestWarningCount`, so reviewers can distinguish\ndiagnostics sidecar drift from lifecycle warnings or build failures.\nThe same summary carries `diagnosticsContract` per platform and aggregates\n`diagnosticsContractWarningCount` when a downloaded `diagnostics.json` does not\nmatch `BUILDCHAIN_DIAGNOSTICS_CONTRACT`.\n\nThe diagnostics SDK also exports stable contract constants such as\n`BUILDCHAIN_DIAGNOSTICS_SUMMARY_CONTRACT`,\n`BUILDCHAIN_DIAGNOSTICS_MANIFEST_CONTRACT`,\n`BUILDCHAIN_PROCESS_SAMPLE_REPORT_CONTRACT`,\n`BUILDCHAIN_PROCESS_SAMPLE_SUMMARY_CONTRACT`, and\n`BUILDCHAIN_ANCHORED_PACKAGE_RELEASE_VALIDATION_CONTRACT` from\n`@kungfu-tech/buildchain/diagnostics`; consumers should compare against those\nconstants instead of hardcoding contract strings.\n\nThe CLI exposes the same aggregation for shell and workflow steps:\n\n```bash\nbuildchain diagnostics summary \\\n .buildchain/artifacts/linux-x64/diagnostics.json \\\n .buildchain/artifacts/macos-arm64/diagnostics.json \\\n --output .buildchain/artifacts/diagnostics-summary.json \\\n --json\n```\n\nOmit `--json` when the workflow log should show a compact platform table with\nlifecycle stages, artifact scan/upload time, total time, requested jobs,\nobserved active processes, warnings, and errors.\n\nFor long native build commands, the CLI can also sample the child process tree\nwhile preserving the wrapped command's exit code:\n\n```bash\nbuildchain sample process-tree \\\n --label native-build \\\n --interval-ms 15000 \\\n --output .buildchain/diagnostics/process-samples.jsonl \\\n --summary-output .buildchain/diagnostics/process-summary.json \\\n -- \\\n make -j20\n```\n\nThe JSONL sample file stores timestamped process-tree snapshots with full\nredacted command lines, command basenames, CPU percentages when available,\nelapsed time, and requested parallelism context. Unix and macOS snapshots read\nthe full `ps args` field instead of truncated `comm` names. Windows snapshots\nread `Win32_Process` command lines through PowerShell so the sampler no longer\nreturns an empty process set on Windows runners. The summary file records\nobserved concurrency, total sampled CPU, command categories, and top command\nbasenames. This is intended for diagnosing low-utilization tails such as\narchive/link phases without logging full environment dumps.\n\nThe lifecycle observability summary is stage-wide, not just final-step timing:\nwhen install and build write to the same Buildchain log, the final platform\nmanifest can show both stages and the slowest spans.\n\n## CLI Logging\n\n```bash\nbuildchain mark \\\n --event native.configure \\\n --phase configure \\\n --component cmake \\\n --attribute preset=release\n\nbuildchain span \\\n --event native.build \\\n --phase build \\\n --component cmake \\\n -- cmake --build build --config Release\n\nbuildchain log summary --json\nbuildchain verify observability-log .buildchain/logs/events.jsonl --min-events 4\n```\n\nEvery event records a timestamp. `span` records duration and preserves the\nwrapped command's exit code.\n\n## Release Gate\n\nBuildchain's own binary distribution lane verifies required log events before\nuploading release assets. Consumers can apply the same pattern:\n\n```bash\nbuildchain verify observability-log .buildchain/logs/events.jsonl \\\n --require-phase build \\\n --require-phase package \\\n --require-component workflow \\\n --require-event native.build.start \\\n --require-event native.build.end\n```\n\nThis makes missing instrumentation a release failure instead of a dashboard\nafterthought."
|
|
2180
|
+
"markdown": "# Toolkit Observability\n\nBuildchain ships a small logging toolkit for repository workflows and project\nscripts. The goal is to separate time spent in Buildchain's framework from time\nspent in the consumer's own build, test, packaging, and publish steps.\n\n## Choose API or CLI\n\n`@kungfu-tech/buildchain` is not only a CLI package. It exports ESM toolkit APIs\nthat project scripts can import directly:\n\n```js\nimport { createBuildchainLogger } from \"@kungfu-tech/buildchain/logging\";\n```\n\nUse the API inside JavaScript or TypeScript build code. Do not spawn\n`buildchain`, download the standalone binary, or shell out through `npx` from\ncode that can import the package. The CLI is for GitHub Actions steps, shell\nscripts, and non-JavaScript tools.\n\nWhen a script runs inside `buildchain lifecycle run`, the lifecycle runner sets\n`BUILDCHAIN_LOG_PATH` and `BUILDCHAIN_LOG_RUN_ID`. Imported loggers pick up those\nenvironment variables automatically, so events emitted deep inside the build are\ngrouped into the same lifecycle summary.\n\nOutside a Buildchain lifecycle or GitHub Actions run, the logger defaults to\nconsole output unless a path is provided. Pass `path` when local scripts should\nwrite a reusable JSONL log:\n\n```js\nconst logger = createBuildchainLogger({\n path: \".buildchain/logs/native-build.jsonl\",\n source: \"user\",\n component: \"native-build\",\n});\n```\n\n## Library API\n\n```js\nimport {\n createBuildchainLogger,\n verifyBuildchainLogEvents,\n} from \"@kungfu-tech/buildchain/logging\";\n\nconst logger = createBuildchainLogger({\n source: \"user\",\n component: \"native-build\",\n});\n\nlogger.mark(\"configure.ready\", {\n phase: \"configure\",\n attributes: { preset: \"release\" },\n});\n\nawait logger.span(\"native.compile\", {\n phase: \"build\",\n attributes: { target: \"release\" },\n}, async () => {\n await compile();\n});\n\nlogger.spanSync(\"native.archive\", {\n phase: \"build\",\n attributes: { tool: \"libtool\" },\n}, () => {\n archiveStaticLibraries();\n});\n\nlogger.spawnSync(\"native.build\", \"make\", [\"-j20\"], {\n stdio: \"inherit\",\n}, {\n phase: \"build\",\n attributes: { requestedJobs: 20 },\n});\n\nconst report = verifyBuildchainLogEvents({\n path: logger.path,\n minEvents: 3,\n requirePhases: [\"configure\", \"build\"],\n requireEvents: [\n \"configure.ready\",\n \"native.compile.start\",\n \"native.compile.end\",\n ],\n});\n\nif (!report.ok) {\n throw new Error(\"Buildchain observability verification failed\");\n}\n```\n\nUse the API when a build script has internal stages that are invisible to the\nouter workflow. Keep secret values out of attributes; known sensitive keys are\nredacted, but callers should still avoid logging private material.\n\n## Candidate timelines and critical-path-safe timing\n\nLifecycle diagnostics retain their existing summed-duration tables for\ncompatibility. Do not interpret those tables as elapsed time when spans are\nnested or jobs run in parallel. Use the candidate timeline contract when a\nchange must be followed from pull-request admission through Merge Queue attempts\nto its final merge:\n\n```js\nimport {\n createCandidateTimeline,\n formatCandidateTimelineReport,\n} from \"@kungfu-tech/buildchain/candidate-timeline\";\n\nconst timeline = createCandidateTimeline({\n candidate: {\n repository: \"owner/repository\",\n baseBranch: \"dev/v4/v4.0\",\n sourceSha,\n pullRequest: 123,\n },\n events,\n});\n\nconsole.log(formatCandidateTimelineReport(timeline));\n```\n\nEach event binds a stable event id to one attempt id and may also bind a Gate\nid, merge-group SHA, workflow run, platform, partition, cache outcome, execution\nboundary, and parent span. Terminal execution states (`success`, `failure`, and\n`cancelled`) require start and completion timestamps. Non-executed states use\n`skipped`, `dependency-blocked`, or `not-required` without invented timings.\nRecord the clock and timestamp precision explicitly: GitHub Actions timestamps\nare normally provider wall-clock observations with one-second precision, while\nan in-process span may also carry a monotonic duration with millisecond or\nbetter precision.\n\nThe `buildchain.candidate-timeline/v1` artifact reports an independent critical\npath for every attempt. Its critical-path duration is the attempt's observed\nwall-clock envelope; its active duration and per-phase durations are interval\nunions. This prevents nested or parallel spans from being added twice, and it\ndoes not combine a failed or dequeued attempt with a later retry. Missing\nrequired measurements make that attempt `incomplete` instead of producing fake\nprecision.\n\nEach attempt also reports measured execution lanes, lane skew, cache outcome\ncounts, the ten longest actionable spans, and one falsifiable next optimization\ntarget. Queue residence, whole-workflow envelopes, and job parents are excluded\nfrom the actionable ranking so they cannot hide the build or qualification\nstage that can actually be changed. The target is an observation, not a causal\nclaim: repeat the same source-bound cohort and disprove it by reducing that span\nbelow the next measured span without increasing attempt elapsed time or\nfailures.\n\nShell and workflow consumers can generate the same machine artifact plus a\ncompact report:\n\n```sh\nbuildchain candidate timeline \\\n --input .buildchain/candidate-timeline-input.json \\\n --output .buildchain/candidate-timeline.json\n```\n\nThe input and output should contain only bounded correlation facts and timing\nreceipts. Do not include tokens, environment dumps, full commands, raw process\ndumps, or private absolute paths.\n\nCommonJS scripts should import Buildchain's ESM surfaces dynamically:\n\n```js\nconst { createBuildchainLogger } = await import(\"@kungfu-tech/buildchain/logging\");\nconst { collectRunnerDiagnostics } = await import(\"@kungfu-tech/buildchain/diagnostics\");\n```\n\n## Diagnostics API\n\nThe diagnostics surface collects local, non-telemetry build facts that are\nuseful when a native build is slow or flaky:\n\n```js\nimport {\n collectBuildchainDiagnostics,\n collectCacheDiagnostics,\n collectCompilerCacheDiagnostics,\n collectRunnerDiagnostics,\n collectToolDiagnostics,\n detectRequestedParallelism,\n startProcessSampler,\n summarizeDiagnosticsArtifacts,\n summarizeLifecycleObservability,\n summarizeProcessSamples,\n validateAnchoredPackageRelease,\n writeDiagnosticsArtifact,\n} from \"@kungfu-tech/buildchain/diagnostics\";\n\nconst lifecycleObservability = summarizeLifecycleObservability({\n logPath: \".buildchain/logs/events.jsonl\",\n});\nconst buildCommand = \"make\";\nconst buildArgs = [\"-j20\"];\nconst requestedParallelism = detectRequestedParallelism({\n command: buildCommand,\n args: buildArgs,\n});\nconst processSampler = startProcessSampler({\n intervalMs: 15000,\n label: \"native-build\",\n command: buildCommand,\n args: buildArgs,\n});\n// Run the long native build while the sampler is active.\nconst processSummary = summarizeProcessSamples({\n requestedParallelism: requestedParallelism.value,\n samples: processSampler.stop(),\n});\nconst cacheDiagnostics = collectCacheDiagnostics({ cwd: process.cwd() });\n\nwriteDiagnosticsArtifact(\".buildchain/artifacts/diagnostics.json\", {\n contract: \"consumer-build-diagnostics\",\n buildchain: collectBuildchainDiagnostics({ cwd: process.cwd() }),\n runner: collectRunnerDiagnostics(),\n tools: collectToolDiagnostics({ cwd: process.cwd() }),\n cache: cacheDiagnostics,\n lifecycleObservability,\n process: processSummary,\n});\n```\n\n`collectCacheDiagnostics()` includes package-manager/workspace context, selected\ncache directory stats, and compiler-cache stats from `ccache --show-stats\n--json` plus `sccache --show-stats --stats-format json` when those tools are\npresent. If a ccache build does not support JSON stats, Buildchain falls back to\nplain `ccache --show-stats` and parses the text counters. Missing cache tools\nare recorded as unavailable instead of failing the diagnostics artifact. Call\n`collectCompilerCacheDiagnostics()` directly when a consumer script only needs\ncompiler cache data. Native diagnostics also expose `compilerCaches` and\n`nativeCacheDirs` as top-level fields in each diagnostics artifact and aggregate\nsummary, so reviewers do not have to dig through nested cache sections first.\n\nProcess samples are intentionally summarized before they become long-lived\nartifacts. The summary records requested parallelism, the source of that value\n(`command`, `process-tree`, `env:MAKEFLAGS`,\n`env:CMAKE_BUILD_PARALLEL_LEVEL`, or `explicit`), observed active process\nconcurrency, elapsed sample time, total sampled CPU, and conservative command\ncategories such as `compiler`, `archive`, `linker`, `build-tool`, and `cache`.\nThe sampler detects common `make -j N`, `ninja -j N`, CMake/MSBuild/Xcode job\nflags, and MAKEFLAGS. This lets native projects distinguish \"we asked for\n`make -j20`\" from \"the build graph only kept two active compiler or archive\nchildren busy during the sampled window\" without storing environment dumps.\n\nNative repositories can opt into a reusable diagnostics profile in\n`buildchain.toml`:\n\n```toml\n[diagnostics.native]\nenabled = true\nsample_process_tree = true\ncompiler_cache = \"auto\"\nexpected_tools = [\"ccache\", \"sccache\", \"clang\", \"cl\", \"cmake\", \"ninja\"]\nartifact_dirs = [\"build\", \"dist\", \"build/Release\"]\ncache_dirs = [\".ccache\", \".sccache\"]\n```\n\nWhen enabled, diagnostics artifacts include the normalized profile, selected\ntool versions, compiler-cache stats, and configured artifact/cache directory\nstats. The profile is data-driven: Buildchain does not assume a specific\nproject such as libnode. The reusable build workflow also exposes\n`sample-process-tree`, which wraps the build lifecycle with the process sampler\nand carries the generated summary into the final diagnostics artifact. Custom\nworkflows can call `buildchain sample process-tree` directly when they need a\ndifferent command boundary.\n\nAnchored/manual package projects can also run one higher-level release-shape\ncheck instead of assembling lower-level config calls:\n\n```js\nconst anchoredReport = validateAnchoredPackageRelease({\n cwd: process.cwd(),\n requireManifest: true,\n requirePackageSetOrder: \"platforms-first-main-last\",\n requireTrustedPublishing: true,\n});\n\nif (!anchoredReport.ok) {\n throw new Error(\"Anchored package release contract failed\");\n}\n```\n\nIn an actual publish job, make that check source-lock aware:\n\n```js\nconst publishReady = validateAnchoredPackageRelease({\n cwd: process.cwd(),\n requirePublishGateSourceLock: true,\n});\n```\n\nThe source-lock inputs are read from `BUILDCHAIN_PUBLISH_SOURCE_REF`,\n`BUILDCHAIN_PUBLISH_SOURCE_SHA`, and `BUILDCHAIN_PUBLISH_SOURCE_LOCKED`, which\nthe reusable build workflow emits after resolving `publish-source-ref`. That\nturns direct channel-branch publication from `alpha/*` or `release/*` into a\nhard failure, while `publish-gate/alpha/<line>/<version>` and\n`publish-gate/release/<line>/<version>` also validate the requested consumer\nversion against configured version files and the anchor manifest.\n\n`buildchain lifecycle run` writes this small diagnostics artifact next to the\nplatform manifest by default. The per-platform diagnostics upload includes the\ncompact `diagnostics.json`, `diagnostics-manifest.json`, lifecycle\n`events.jsonl`, and, when process sampling is enabled, copied\n`process-summary.json` and `process-samples.jsonl` sidecars. The sidecar\nmanifest records each uploaded diagnostics file with its relative path, byte\ncount, and sha256 hash. It is intended to stay small enough to download without\nfetching large binary packages, and it should not include full environment dumps\nor secret-looking values.\n\nUse `summarizeDiagnosticsArtifacts()` when a matrix build uploads one\ndiagnostics artifact per platform. The summary keeps each platform's lifecycle\nstage table, adds a lifecycle total duration, carries the top slow spans, and\naggregates warning/error counts plus the slowest platforms. Per-platform rows\nalso include compact runner facts, checked tool versions/missing tools, package\nmanager/cache directory details, compiler cache availability, and a compact\nprocess sampler view with requested parallelism, observed max active processes,\nthe ratio between them, sample count, process categories, and top sampled\ncommand basenames. That gives release reviewers a small cross-platform timing,\nrunner, tool, cache, and concurrency view without downloading full build outputs\nor process sidecars.\n\nThe reusable build workflow writes that rollup as `diagnostics-summary.json` and\nuploads it in a separate aggregate diagnostics summary artifact. Consumers can\nread the `build-diagnostics-summary-artifact` output when they need only timing,\nwarning/error, runner, cache, and process-sampler context instead of the build\nsummary or binary artifacts. Per-platform rows keep the diagnostics `links`\nobject, including the binary artifact name, manifest artifact name, diagnostics\nartifact name, platform id, diagnostics sidecar manifest path, manifest path,\nsummary path, and process sidecar paths when present. They also keep compact\nrunner/tool/cache summaries so reviewers can tell whether a slow row ran on the\nexpected runner, missed an expected tool, or lacked useful compiler-cache stats.\nWhen the downloaded platform diagnostics include a sibling\n`diagnostics-manifest.json`, `summarizeDiagnosticsArtifacts()` carries a compact\n`diagnosticsManifest` section for that platform and verifies the manifest's\n`diagnostics.json` byte count and sha256. Missing or mismatched sidecar manifests\nincrement `diagnosticsManifestWarningCount`, so reviewers can distinguish\ndiagnostics sidecar drift from lifecycle warnings or build failures.\nThe same summary carries `diagnosticsContract` per platform and aggregates\n`diagnosticsContractWarningCount` when a downloaded `diagnostics.json` does not\nmatch `BUILDCHAIN_DIAGNOSTICS_CONTRACT`.\n\nThe diagnostics SDK also exports stable contract constants such as\n`BUILDCHAIN_DIAGNOSTICS_SUMMARY_CONTRACT`,\n`BUILDCHAIN_DIAGNOSTICS_MANIFEST_CONTRACT`,\n`BUILDCHAIN_PROCESS_SAMPLE_REPORT_CONTRACT`,\n`BUILDCHAIN_PROCESS_SAMPLE_SUMMARY_CONTRACT`, and\n`BUILDCHAIN_ANCHORED_PACKAGE_RELEASE_VALIDATION_CONTRACT` from\n`@kungfu-tech/buildchain/diagnostics`; consumers should compare against those\nconstants instead of hardcoding contract strings.\n\nThe CLI exposes the same aggregation for shell and workflow steps:\n\n```bash\nbuildchain diagnostics summary \\\n .buildchain/artifacts/linux-x64/diagnostics.json \\\n .buildchain/artifacts/macos-arm64/diagnostics.json \\\n --output .buildchain/artifacts/diagnostics-summary.json \\\n --json\n```\n\nOmit `--json` when the workflow log should show a compact platform table with\nlifecycle stages, artifact scan/upload time, total time, requested jobs,\nobserved active processes, warnings, and errors.\n\nFor long native build commands, the CLI can also sample the child process tree\nwhile preserving the wrapped command's exit code:\n\n```bash\nbuildchain sample process-tree \\\n --label native-build \\\n --interval-ms 15000 \\\n --output .buildchain/diagnostics/process-samples.jsonl \\\n --summary-output .buildchain/diagnostics/process-summary.json \\\n -- \\\n make -j20\n```\n\nThe JSONL sample file stores timestamped process-tree snapshots with full\nredacted command lines, command basenames, CPU percentages when available,\nelapsed time, and requested parallelism context. Unix and macOS snapshots read\nthe full `ps args` field instead of truncated `comm` names. Windows snapshots\nread `Win32_Process` command lines through PowerShell so the sampler no longer\nreturns an empty process set on Windows runners. The summary file records\nobserved concurrency, total sampled CPU, command categories, and top command\nbasenames. This is intended for diagnosing low-utilization tails such as\narchive/link phases without logging full environment dumps.\n\nThe lifecycle observability summary is stage-wide, not just final-step timing:\nwhen install and build write to the same Buildchain log, the final platform\nmanifest can show both stages and the slowest spans.\n\n## CLI Logging\n\n```bash\nbuildchain mark \\\n --event native.configure \\\n --phase configure \\\n --component cmake \\\n --attribute preset=release\n\nbuildchain span \\\n --event native.build \\\n --phase build \\\n --component cmake \\\n -- cmake --build build --config Release\n\nbuildchain log summary --json\nbuildchain verify observability-log .buildchain/logs/events.jsonl --min-events 4\n```\n\nEvery event records a timestamp. `span` records duration and preserves the\nwrapped command's exit code.\n\nBuildchain also records local control-plane outcome events for workflow-friction\nincident handling and production release-intent PR handling. `log summary`\nreports the observed incident reuse rate, release-intent suppression rate, and\nsuppression reasons. A reused incident means an equivalent occurrence found the\nsame fingerprint and was commented, cooled down, or otherwise reused; a\nsuppressed release intent means Buildchain proved that the source commit already\nhad a qualifying merged release PR. These are operational facts, not release\npolicy inputs, and logging failure remains non-fatal by default.\n\nThe reusable promotion workflow uploads `.buildchain/logs/events.jsonl` when a\nfriction report is produced. The web-surface production release PR handoff\nartifact includes the same path, so a real run can falsify the P0 claim instead\nof relying only on unit tests.\n\n## Release Gate\n\nBuildchain's own binary distribution lane verifies required log events before\nuploading release assets. Consumers can apply the same pattern:\n\n```bash\nbuildchain verify observability-log .buildchain/logs/events.jsonl \\\n --require-phase build \\\n --require-phase package \\\n --require-component workflow \\\n --require-event native.build.start \\\n --require-event native.build.end\n```\n\nThis makes missing instrumentation a release failure instead of a dashboard\nafterthought."
|
|
2181
2181
|
},
|
|
2182
2182
|
{
|
|
2183
2183
|
"id": "manual:versioning",
|
|
@@ -2846,7 +2846,7 @@
|
|
|
2846
2846
|
"path": "docs/toolkit-observability.md",
|
|
2847
2847
|
"plane": "use",
|
|
2848
2848
|
"exists": true,
|
|
2849
|
-
"digest": "sha256:
|
|
2849
|
+
"digest": "sha256:d7f4179c3912d7bbc5940bfba69e674fb03d020a740063c0b877a171bd5789e3"
|
|
2850
2850
|
},
|
|
2851
2851
|
{
|
|
2852
2852
|
"id": "site-bundle-contract",
|
|
@@ -2886,7 +2886,7 @@
|
|
|
2886
2886
|
"path": "docs/cli.md",
|
|
2887
2887
|
"plane": "use",
|
|
2888
2888
|
"exists": true,
|
|
2889
|
-
"digest": "sha256:
|
|
2889
|
+
"digest": "sha256:f7a27ef72c0ffe3e18ad5d4d0520e14d8f343a55a417182c5da74a150b8f58fc"
|
|
2890
2890
|
},
|
|
2891
2891
|
{
|
|
2892
2892
|
"id": "build-facts",
|
|
@@ -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": "
|
|
24
|
+
"sha256": "ddaa4f26cc5ed42f56bac53ec7813b344846580c8d4957cfa836e086d099a78b",
|
|
25
25
|
"summary": {
|
|
26
26
|
"cliCommandCount": 87,
|
|
27
27
|
"workflowCount": 53,
|
|
@@ -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": "
|
|
231
|
+
"sha256": "ddaa4f26cc5ed42f56bac53ec7813b344846580c8d4957cfa836e086d099a78b",
|
|
232
232
|
"summary": {
|
|
233
233
|
"cliCommandCount": 87,
|
|
234
234
|
"workflowCount": 53,
|
|
@@ -206,7 +206,7 @@
|
|
|
206
206
|
"title": "Toolkit observability",
|
|
207
207
|
"path": "docs/toolkit-observability.md",
|
|
208
208
|
"plane": "use",
|
|
209
|
-
"digest": "sha256:
|
|
209
|
+
"digest": "sha256:d7f4179c3912d7bbc5940bfba69e674fb03d020a740063c0b877a171bd5789e3",
|
|
210
210
|
"capabilityGroup": "observability-diagnostics",
|
|
211
211
|
"audience": [
|
|
212
212
|
"developer",
|
|
@@ -275,7 +275,7 @@
|
|
|
275
275
|
"title": "CLI and npm package",
|
|
276
276
|
"path": "docs/cli.md",
|
|
277
277
|
"plane": "use",
|
|
278
|
-
"digest": "sha256:
|
|
278
|
+
"digest": "sha256:f7a27ef72c0ffe3e18ad5d4d0520e14d8f343a55a417182c5da74a150b8f58fc",
|
|
279
279
|
"capabilityGroup": "api-cli-reference",
|
|
280
280
|
"audience": [
|
|
281
281
|
"agent",
|
|
@@ -164,7 +164,7 @@
|
|
|
164
164
|
"specifier": "@kungfu-tech/buildchain/issue-reporting",
|
|
165
165
|
"export": "./issue-reporting",
|
|
166
166
|
"target": "./packages/core/issue-reporting.js",
|
|
167
|
-
"digest": "sha256:
|
|
167
|
+
"digest": "sha256:4e6807067b14db5cf78b7de7596bf27ce23b211ae9b24f5ae36bed4fb568d56b",
|
|
168
168
|
"summary": "Buildchain-owned issue reporting API for workflow friction feedback.",
|
|
169
169
|
"capabilityGroup": "observability-diagnostics",
|
|
170
170
|
"audience": [
|
|
@@ -255,7 +255,7 @@
|
|
|
255
255
|
"specifier": "@kungfu-tech/buildchain/logging",
|
|
256
256
|
"export": "./logging",
|
|
257
257
|
"target": "./packages/core/logging.js",
|
|
258
|
-
"digest": "sha256:
|
|
258
|
+
"digest": "sha256:36d8aaea7db446d02fb0a1d7d7e6d5d34cc10cff19156596bb8dfbd1a1ff2382",
|
|
259
259
|
"summary": "Buildchain JSONL logging, span, summary, and verification APIs.",
|
|
260
260
|
"capabilityGroup": "observability-diagnostics",
|
|
261
261
|
"audience": [
|
|
@@ -477,7 +477,7 @@
|
|
|
477
477
|
{
|
|
478
478
|
"id": "cli-and-node-package",
|
|
479
479
|
"path": "docs/cli.md",
|
|
480
|
-
"digest": "sha256:
|
|
480
|
+
"digest": "sha256:f7a27ef72c0ffe3e18ad5d4d0520e14d8f343a55a417182c5da74a150b8f58fc"
|
|
481
481
|
},
|
|
482
482
|
{
|
|
483
483
|
"id": "build-facts",
|