@kungfu-tech/buildchain 4.0.1-alpha.42 → 4.0.1-alpha.54

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.
Files changed (68) hide show
  1. package/architecture/agent-change-map.md +1015 -0
  2. package/architecture/ci-lane-change-budget.json +17 -0
  3. package/architecture/internal-capabilities.json +156 -11
  4. package/architecture/maintainability-debt.json +3229 -0
  5. package/architecture/maintainability-policy.json +474 -125
  6. package/architecture/v3-core-mechanism-inventory.json +4 -3
  7. package/architecture/v3-v4-capability-closure.md +59 -0
  8. package/architecture/v3-v4-live-capability-inventory.json +102404 -0
  9. package/architecture/v4-cross-platform-adopter-qualification.json +52 -0
  10. package/architecture/v4-delivery-warrant-shadow-fixtures.json +3 -3
  11. package/architecture/v4-runtime-semantic-closure.json +710 -0
  12. package/bin/internal/trust-release-release-handlers.mjs +5 -0
  13. package/contracts/fixtures/v4-tail-reseal-v1/valid.json +1 -1
  14. package/dist/site/buildchain-contract.json +71 -31
  15. package/dist/site/buildchain-site.json +38 -18
  16. package/dist/site/capability-registry.json +2 -2
  17. package/dist/site/cli-registry.json +5 -2
  18. package/dist/site/controller-registry.json +37 -5
  19. package/dist/site/kfd-claims.json +76 -14
  20. package/dist/site/kfd-upstream-aggregate.json +1 -1
  21. package/dist/site/manual-registry.json +4 -4
  22. package/dist/site/node-api-registry.json +1168 -203
  23. package/dist/site/page-registry.json +30 -10
  24. package/dist/site/public-surface-audit.json +46 -17
  25. package/dist/site/publication-registry.json +4 -4
  26. package/dist/site/release-provenance.json +3 -0
  27. package/dist/site/site-manifest.json +8 -8
  28. package/dist/site/workflow-registry.json +47 -18
  29. package/docs/cli-reference.md +4 -4
  30. package/docs/dev-delivery-warrant.md +12 -9
  31. package/docs/node-api-reference.md +224 -169
  32. package/docs/publish-transaction.md +11 -4
  33. package/docs/v4-adopter-delivery.md +23 -4
  34. package/package.json +6 -3
  35. package/packages/core/adopter-delivery-passport.js +36 -0
  36. package/packages/core/dev-delivery-warrant-settlement.js +5 -1
  37. package/packages/core/dev-delivery-warrant.js +13 -4
  38. package/packages/core/github-governance-authority.js +4 -4
  39. package/packages/core/paper-scaffold-content.js +401 -0
  40. package/packages/core/paper.js +12 -378
  41. package/packages/core/publication-control-plane-audit.js +135 -111
  42. package/packages/core/publication-rehearsal-projection.js +104 -0
  43. package/packages/core/publication-rehearsal-runtime.js +190 -0
  44. package/packages/core/release-candidate-recovery.js +1 -0
  45. package/packages/core/release-passport.js +82 -184
  46. package/packages/core/v4-cross-platform-adopter-qualification.js +343 -0
  47. package/packages/core/v4-floating-consumer-policy.js +3 -2
  48. package/packages/core/v4-floating-consumer-release-passport.js +119 -0
  49. package/scripts/audit-publication-control-plane.mjs +17 -17
  50. package/scripts/buildchain-cli-help.mjs +3 -0
  51. package/scripts/check-internal-architecture.mjs +23 -3
  52. package/scripts/check-inventory.mjs +21 -3
  53. package/scripts/check-maintainability.mjs +145 -4
  54. package/scripts/check-v3-v4-capability-inventory.mjs +574 -0
  55. package/scripts/check-v4-floating-consumer-policy-contract.mjs +10 -3
  56. package/scripts/check-v4-runtime-semantic-closure.mjs +266 -0
  57. package/scripts/generate-agent-change-map.mjs +118 -0
  58. package/scripts/maintainability-domain-metrics.mjs +237 -0
  59. package/scripts/maintainability-governance.mjs +473 -0
  60. package/scripts/maintainability-metrics.mjs +28 -6
  61. package/scripts/promotion-routing-evidence.mjs +35 -6
  62. package/scripts/release-line-policy.mjs +25 -15
  63. package/scripts/release-tail.mjs +19 -2
  64. package/scripts/resume-from-candidate-run.mjs +1 -1
  65. package/scripts/run-lifecycle-core.mjs +341 -376
  66. package/scripts/site-capability-metadata.mjs +3 -0
  67. package/scripts/v3-v4-capability-catalog.mjs +439 -0
  68. package/scripts/v4-cross-platform-adopter-qualification.mjs +228 -0
@@ -4,6 +4,10 @@ import {
4
4
  v4FloatingConsumerDocumentRoot,
5
5
  verifyV4FloatingConsumerPolicyCertification,
6
6
  } from "./v4-floating-consumer-evidence.js";
7
+ import {
8
+ verifyV4RuntimeAuthorizationReceipt,
9
+ verifyV4RuntimeResumeLineage,
10
+ } from "./v4-runtime-ref-resume-authority.js";
7
11
  const SHA256_ROOT = /^sha256:[0-9a-f]{64}$/u;
8
12
  export function isV4PromotionRouting(value = undefined) {
9
13
  return [
@@ -151,3 +155,118 @@ export function releasePassportCertificationVerificationOptions({
151
155
  alphaLockPath: authority.contractLocks?.alpha?.path || "",
152
156
  };
153
157
  }
158
+ export function normalizePromotionRouting(value = undefined) {
159
+ if (value === undefined) return undefined;
160
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
161
+ throw new Error("release.promotionRouting must be a JSON object");
162
+ }
163
+ if (value.contract !== "buildchain.promotion-routing/v1") {
164
+ throw new Error(
165
+ "release.promotionRouting contract must be buildchain.promotion-routing/v1",
166
+ );
167
+ }
168
+ for (const [label, field] of [
169
+ ["router.ref", value.router?.ref],
170
+ ["router.sha", value.router?.sha],
171
+ ["shell.ref", value.shell?.ref],
172
+ ["shell.sha", value.shell?.sha],
173
+ ["runtime.requestedRef", value.runtime?.requestedRef],
174
+ ["runtime.resolvedSha", value.runtime?.resolvedSha],
175
+ ["contractLock.path", value.contractLock?.path],
176
+ ["contractLock.digest", value.contractLock?.digest],
177
+ ["publication.channel", value.publication?.channel],
178
+ ["publication.targetRef", value.publication?.targetRef],
179
+ ]) {
180
+ if (!String(field || "").trim())
181
+ throw new Error(`release.promotionRouting.${label} is required`);
182
+ }
183
+ for (const [label, sha] of [
184
+ ["router.sha", value.router.sha],
185
+ ["shell.sha", value.shell.sha],
186
+ ["runtime.resolvedSha", value.runtime.resolvedSha],
187
+ ]) {
188
+ if (!/^[0-9a-f]{40}$/i.test(String(sha))) {
189
+ throw new Error(
190
+ `release.promotionRouting.${label} must be a 40-character Git SHA`,
191
+ );
192
+ }
193
+ }
194
+ if (!/^sha256:[0-9a-f]{64}$/i.test(String(value.contractLock.digest))) {
195
+ throw new Error(
196
+ "release.promotionRouting.contractLock.digest must be a sha256 digest",
197
+ );
198
+ }
199
+ return JSON.parse(JSON.stringify(value));
200
+ }
201
+
202
+ export function normalizePromotionEvidence({
203
+ release = {},
204
+ v4ConsumerPolicyCertification: certification,
205
+ v4ConsumerPolicyCertificationRoot: certificationRoot,
206
+ v4RuntimeResumeEvidence,
207
+ repository,
208
+ sourceSha,
209
+ cwd,
210
+ }) {
211
+ const routing = normalizePromotionRouting(release.promotionRouting);
212
+ const identity = resolveV4ConsumerPolicyCertificationIdentity({
213
+ release: { ...release, certification },
214
+ routing,
215
+ runtimeResume: v4RuntimeResumeEvidence,
216
+ sourceSha,
217
+ });
218
+ return {
219
+ routing,
220
+ consumerPolicy: requireV4ConsumerPolicyCertification({
221
+ value: certification,
222
+ repository,
223
+ sourceSha: identity.sourceSha,
224
+ runtimeSha: identity.runtimeSha,
225
+ routing,
226
+ cwd,
227
+ certificationRoot,
228
+ }),
229
+ };
230
+ }
231
+
232
+ export function normalizeV4RuntimeResumeEvidence(value, expected = {}) {
233
+ if (value === undefined || value === null || value === "") return undefined;
234
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
235
+ throw new Error("v4RuntimeResumeEvidence must be a JSON object");
236
+ }
237
+ const authorizationVerification = verifyV4RuntimeAuthorizationReceipt({
238
+ receipt: value.authorization,
239
+ receiptRoot: value.authorizationRoot,
240
+ repository: expected.repository,
241
+ sourceSha: expected.sourceSha,
242
+ runtimeSha: expected.resumeRuntimeSha,
243
+ consumerPolicyReceiptRoot: expected.consumerPolicyReceiptRoot,
244
+ });
245
+ if (!authorizationVerification.ok) {
246
+ throw new Error(
247
+ `v4 runtime authorization invalid: ${authorizationVerification.failures.join(", ")}`,
248
+ );
249
+ }
250
+ const lineageVerification = verifyV4RuntimeResumeLineage({
251
+ lineage: value.lineage,
252
+ lineageRoot: value.lineageRoot,
253
+ repository: expected.repository,
254
+ sourceSha: expected.sourceSha,
255
+ resumeRuntimeSha: expected.resumeRuntimeSha,
256
+ consumerPolicyReceiptRoot: expected.consumerPolicyReceiptRoot,
257
+ });
258
+ if (!lineageVerification.ok) {
259
+ throw new Error(
260
+ `v4 runtime resume lineage invalid: ${lineageVerification.failures.join(", ")}`,
261
+ );
262
+ }
263
+ if (value.lineage?.authorizationRoot !== value.authorizationRoot) {
264
+ throw new Error("v4 runtime resume lineage authorization root mismatch");
265
+ }
266
+ return {
267
+ authorizationRoot: value.authorizationRoot,
268
+ authorization: structuredClone(value.authorization),
269
+ lineageRoot: value.lineageRoot,
270
+ lineage: structuredClone(value.lineage),
271
+ };
272
+ }
@@ -11,10 +11,9 @@ import {
11
11
 
12
12
  const GITHUB_JSON_MAX_BUFFER = 16 * 1024 * 1024;
13
13
 
14
- function flag(name, fallback = "") {
15
- const index = process.argv.indexOf(`--${name}`);
16
- return index === -1 ? fallback : String(process.argv[index + 1] || "");
17
- }
14
+ const flag = (name, fallback = "") => process.argv.includes(`--${name}`)
15
+ ? String(process.argv[process.argv.indexOf(`--${name}`) + 1] || "")
16
+ : fallback;
18
17
 
19
18
  function commandJson(command, args, label, { publicReadFallback = false } = {}) {
20
19
  const options = {
@@ -42,13 +41,9 @@ function commandJson(command, args, label, { publicReadFallback = false } = {})
42
41
  }
43
42
  }
44
43
 
45
- function githubJson(apiPath, label, { publicReadFallback = false } = {}) {
46
- return commandJson("gh", ["api", apiPath, "-H", "Accept: application/vnd.github+json"], label, { publicReadFallback });
47
- }
44
+ const githubJson = (apiPath, label, { publicReadFallback = false } = {}) => commandJson("gh", ["api", apiPath, "-H", "Accept: application/vnd.github+json"], label, { publicReadFallback });
48
45
 
49
- function githubPublicJson(apiPath, label) {
50
- return githubJson(apiPath, label, { publicReadFallback: true });
51
- }
46
+ const githubPublicJson = (apiPath, label) => githubJson(apiPath, label, { publicReadFallback: true });
52
47
 
53
48
  function githubJsonOptional(apiPath, label, fallback, fallbackPattern = /404|not found/i) {
54
49
  const result = spawnSyncCommand("gh", ["api", apiPath, "-H", "Accept: application/vnd.github+json"], {
@@ -68,9 +63,7 @@ function githubJsonOptional(apiPath, label, fallback, fallbackPattern = /404|not
68
63
  }
69
64
  }
70
65
 
71
- function githubJsonReadLimited(apiPath, label, fallback) {
72
- return githubJsonOptional(apiPath, label, fallback, /401|403|404|unauthorized|forbidden|not found/i);
73
- }
66
+ const githubJsonReadLimited = (apiPath, label, fallback) => githubJsonOptional(apiPath, label, fallback, /401|403|404|unauthorized|forbidden|not found/i);
74
67
 
75
68
  function rulesetIncludesBranch(ruleset, branch, defaultBranch) {
76
69
  const includes = ruleset.conditions?.ref_name?.include || [];
@@ -102,7 +95,7 @@ function normalizeRulesetBranchPolicy(rulesets, branch, defaultBranch) {
102
95
  };
103
96
  }
104
97
 
105
- function jobBlock(workflowText, jobId) {
98
+ function jobBlock(workflowText, jobId, delegated = false) {
106
99
  const lines = String(workflowText).split(/\r?\n/);
107
100
  const jobsIndex = lines.findIndex((line) => /^jobs:\s*$/.test(line));
108
101
  if (jobsIndex === -1) return "";
@@ -115,14 +108,21 @@ function jobBlock(workflowText, jobId) {
115
108
  break;
116
109
  }
117
110
  }
118
- return lines.slice(start, end).join("\n");
111
+ const block = lines.slice(start, end).join("\n");
112
+ if (delegated) return block;
113
+ const declarations = [...block.matchAll(/^ {4}# buildchain-publication-authority-job:\s*([A-Za-z0-9_-]+)\s*$/gm)];
114
+ if (declarations.length > 1 || declarations[0]?.[1] === jobId) throw new Error(`publication authority job delegation is invalid: ${jobId}`);
115
+ if (!declarations.length) return block;
116
+ const delegatedJobId = declarations[0][1];
117
+ const delegatedBlock = jobBlock(workflowText, delegatedJobId, true);
118
+ if (!delegatedBlock) throw new Error(`delegated publication workflow job is missing: ${delegatedJobId}`);
119
+ return delegatedBlock;
119
120
  }
120
121
 
121
122
  function first(value, keys) {
122
123
  for (const key of keys) {
123
- const parts = key.split(".");
124
124
  let current = value;
125
- for (const part of parts) current = current && typeof current === "object" ? current[part] : undefined;
125
+ for (const part of key.split(".")) current = current && typeof current === "object" ? current[part] : undefined;
126
126
  if (current !== undefined && current !== null && current !== "") return current;
127
127
  }
128
128
  return undefined;
@@ -51,6 +51,8 @@ export const BUILDCHAIN_USAGE = `Usage:
51
51
  buildchain release-tail compat --hooks-json <json-or-path> [--output <path>]
52
52
  buildchain release-tail rehearse --capsule <absolute-path>
53
53
  --candidate-root <absolute-path>
54
+ [--capsule-root <absolute-path>]
55
+ [--environment-json <empty-json-or-path>]
54
56
  --mode <simulate|replay>
55
57
  --state <absolute-path>
56
58
  --evidence <absolute-path>
@@ -70,6 +72,7 @@ export const BUILDCHAIN_USAGE = `Usage:
70
72
  buildchain release <inspect|recover|finalize|abort> ...
71
73
  buildchain transaction inspect ...
72
74
  buildchain collect github-release --tag <tag> [--repository <owner/repo>]
75
+ [--adopter-delivery-json <legacy-json-or-path>]
73
76
  [--assets-dir <dir>] [--assets-json <json-or-path>]
74
77
  [--release-json <json-or-path>] [--package-set-json <json-or-path>]
75
78
  [--product-name <name>]
@@ -100,8 +100,8 @@ function dependencyCycles(graph) {
100
100
  }
101
101
 
102
102
  function assertIndexShape(index) {
103
- if (index?.schemaVersion !== 1) {
104
- throw new Error("internal architecture index schemaVersion must be 1");
103
+ if (index?.schemaVersion !== 2) {
104
+ throw new Error("internal architecture index schemaVersion must be 2");
105
105
  }
106
106
  for (const field of [
107
107
  "coverageRoots",
@@ -209,7 +209,27 @@ function evaluateCapabilities(root, index) {
209
209
  if (!Array.isArray(capability.tests) || capability.tests.length === 0) {
210
210
  issues.push(`${capability.id}: test mapping is empty`);
211
211
  }
212
- for (const field of ["implementation", "tests", "contracts"]) {
212
+ if (!Array.isArray(capability.generatedOutputs)) {
213
+ issues.push(`${capability.id}: generated output mapping is missing`);
214
+ }
215
+ if (
216
+ !Array.isArray(capability.validationCommands) ||
217
+ capability.validationCommands.length === 0
218
+ ) {
219
+ issues.push(`${capability.id}: validation command mapping is empty`);
220
+ } else if (
221
+ capability.validationCommands.some(
222
+ (command) => !String(command || "").trim(),
223
+ )
224
+ ) {
225
+ issues.push(`${capability.id}: validation command is empty`);
226
+ }
227
+ for (const field of [
228
+ "implementation",
229
+ "tests",
230
+ "contracts",
231
+ "generatedOutputs",
232
+ ]) {
213
233
  for (const relativePath of capability[field] || []) {
214
234
  if (!fs.existsSync(path.resolve(root, relativePath))) {
215
235
  issues.push(
@@ -285,6 +285,10 @@ const channelPromotionWorkflow = fs.readFileSync(
285
285
  path.join(root, ".github/workflows/release-candidate-promote.yml"),
286
286
  "utf8",
287
287
  );
288
+ const boundedAlphaRecoveryWorkflow = fs.readFileSync(
289
+ path.join(root, ".github/workflows/buildchain-ref-promotion-recovery.yml"),
290
+ "utf8",
291
+ );
288
292
  const promotionShellRouting = parsePromotionShellRouting(
289
293
  fs.readFileSync(path.join(root, ".buildchain/promotion-shell-routing.json"), "utf8"),
290
294
  { major: Number(selfDogfoodMajor) },
@@ -295,6 +299,20 @@ if (channelPromotionWorkflow !== generateChannelPromotionWorkflow(advancedPromot
295
299
  })) {
296
300
  throw new Error("generated channel promotion workflow is stale");
297
301
  }
302
+ for (const requiredSnippet of [
303
+ "uses: kungfu-systems/buildchain/.github/workflows/.release-candidate-promote.yml@alpha/v4/v4.0",
304
+ "promotion-shell-ref: ${{ needs.consumer-admission.outputs.shell-call-ref }}",
305
+ "declarative-release-tail: true",
306
+ ]) {
307
+ if (!boundedAlphaRecoveryWorkflow.includes(requiredSnippet)) {
308
+ throw new Error(`bounded alpha recovery missing bootstrap contract: ${requiredSnippet}`);
309
+ }
310
+ }
311
+ for (const workflowSource of [boundedAlphaRecoveryWorkflow, channelPromotionWorkflow]) {
312
+ if (workflowSource.includes("channel-finalization-recovery")) {
313
+ throw new Error("Buildchain-only alpha bootstrap must not add a public or recovery workflow input");
314
+ }
315
+ }
298
316
  for (const requiredSnippet of [
299
317
  "buildchain-channel:",
300
318
  `/${promotionShellRouting.alpha.workflowPath}@${promotionShellRouting.alpha.callRef}`,
@@ -1021,16 +1039,16 @@ for (const forbiddenSnippet of [
1021
1039
  for (const requiredSnippet of [
1022
1040
  "id-token: write",
1023
1041
  "actions: write",
1024
- "uses: kungfu-systems/buildchain/.github/workflows/release-candidate-promote.yml@v4-alpha",
1042
+ "uses: kungfu-systems/buildchain/.github/workflows/.release-candidate-promote.yml@v4-alpha",
1025
1043
  "github.event.workflow_run.event == 'push'",
1026
1044
  "!startsWith(github.event.workflow_run.display_title, 'chore(release): prepare v')",
1027
1045
  "!startsWith(github.event.workflow_run.display_title, 'chore(release): release v')",
1028
1046
  "resume-candidate-run-id:",
1029
1047
  "resume-expected-source-tree:",
1030
- "resume-buildchain-runtime-sha:",
1048
+ "resume-buildchain-runtime-ref:",
1031
1049
  "uses: kungfu-systems/buildchain/.github/workflows/release-candidate-promote.yml@v4",
1032
1050
  "release-passport-buildchain-self-kfd: true",
1033
- "buildchain-channel: alpha",
1051
+ "declarative-release-tail: true",
1034
1052
  "release-passport-impact-json: .buildchain/release-impact.json",
1035
1053
  ]) {
1036
1054
  if (!buildchainRefPromotionWorkflow.includes(requiredSnippet)) {
@@ -5,10 +5,52 @@ import path from "node:path";
5
5
  import { execFileSync } from "node:child_process";
6
6
  import { pathToFileURL } from "node:url";
7
7
  import {
8
- analyzeJavaScript,
8
+ analyzeSource,
9
+ analyzeWorkflow,
9
10
  collectMaintainabilityMetrics,
10
11
  isHandMaintainedSource,
11
12
  } from "./maintainability-metrics.mjs";
13
+ import {
14
+ calculateDebtMeasuredExcess,
15
+ evaluateDebtAuthority,
16
+ evaluateDebtBudget,
17
+ evaluateExceptionBudget,
18
+ evaluateExceptionGovernance,
19
+ evaluateTestBudgets,
20
+ evaluateWorkflowBudgets,
21
+ } from "./maintainability-governance.mjs";
22
+
23
+ function collectHotspots(root, current, limit = 20, shallowFallback = []) {
24
+ const maintained = new Set([
25
+ ...Object.keys(current.files || {}),
26
+ ...Object.keys(current.tests || {}),
27
+ ...Object.keys(current.workflows || {}),
28
+ ]);
29
+ // Shallow consumers cannot reproduce repository-wide churn ranking.
30
+ // Reuse the audited routes; full clones still re-rank them below.
31
+ // This keeps consumer verification deterministic without inventing history.
32
+ if (
33
+ gitOutput(root, ["rev-parse", "--is-shallow-repository"]).trim() === "true"
34
+ ) {
35
+ return shallowFallback.slice(0, limit);
36
+ }
37
+ const counts = new Map();
38
+ const record = (file) =>
39
+ maintained.has(file) && counts.set(file, (counts.get(file) || 0) + 1);
40
+ for (const args of [
41
+ ["log", "-n", "500", "--format=", "--name-only"],
42
+ ["diff", "--name-only"],
43
+ ])
44
+ for (const file of gitOutput(root, args).split("\n").filter(Boolean))
45
+ record(file);
46
+ return [...counts]
47
+ .sort(
48
+ ([leftPath, left], [rightPath, right]) =>
49
+ right - left || leftPath.localeCompare(rightPath),
50
+ )
51
+ .slice(0, limit)
52
+ .map(([file]) => file);
53
+ }
12
54
 
13
55
  function readJson(root, file) {
14
56
  return JSON.parse(fs.readFileSync(path.join(root, file), "utf8"));
@@ -68,7 +110,35 @@ function sourceMetricsAtRevision(root, revision) {
68
110
  return Object.fromEntries(
69
111
  files.map((file) => [
70
112
  file,
71
- analyzeJavaScript(file, gitOutput(root, ["show", `${revision}:${file}`])),
113
+ analyzeSource(file, gitOutput(root, ["show", `${revision}:${file}`])),
114
+ ]),
115
+ );
116
+ }
117
+
118
+ function testMetricsAtRevision(root, revision) {
119
+ const files = gitOutput(root, ["ls-tree", "-r", "--name-only", revision])
120
+ .split("\n")
121
+ .filter((file) =>
122
+ /(?:^tests\/|(?:^|\/)tests?\/).+\.(?:c|m)?js$/u.test(file),
123
+ )
124
+ .sort();
125
+ return Object.fromEntries(
126
+ files.map((file) => [
127
+ file,
128
+ analyzeSource(file, gitOutput(root, ["show", `${revision}:${file}`])),
129
+ ]),
130
+ );
131
+ }
132
+
133
+ function workflowMetricsAtRevision(root, revision) {
134
+ const files = gitOutput(root, ["ls-tree", "-r", "--name-only", revision])
135
+ .split("\n")
136
+ .filter((file) => /^\.github\/workflows\/.*\.ya?ml$/u.test(file))
137
+ .sort();
138
+ return Object.fromEntries(
139
+ files.map((file) => [
140
+ file,
141
+ analyzeWorkflow(file, gitOutput(root, ["show", `${revision}:${file}`])),
72
142
  ]),
73
143
  );
74
144
  }
@@ -276,10 +346,14 @@ function evaluateRepositoryBudgets({ current, policy }) {
276
346
  return issues;
277
347
  }
278
348
 
349
+ function budgetsForFile(policy, file) {
350
+ return file.endsWith(".rs") ? policy.rustBudgets : policy.sourceBudgets;
351
+ }
352
+
279
353
  function evaluateMaintainability({ current, baselineFiles, policy }) {
280
354
  const issues = [];
281
- const budgets = policy.sourceBudgets;
282
355
  for (const [file, metrics] of Object.entries(current.files)) {
356
+ const budgets = budgetsForFile(policy, file);
283
357
  const baseline = baselineFiles[file];
284
358
  if (!baseline) {
285
359
  const transition = policy.approvedNewFileTransitions?.[file];
@@ -381,15 +455,66 @@ function evaluateMaintainability({ current, baselineFiles, policy }) {
381
455
 
382
456
  function checkMaintainability({ root = process.cwd() } = {}) {
383
457
  const policy = readJson(root, "architecture/maintainability-policy.json");
458
+ if (policy.schemaVersion !== 2) {
459
+ throw new Error("maintainability policy schemaVersion must be 2");
460
+ }
384
461
  const baseline = readJson(root, policy.baseline);
385
462
  const enforcementRevision = policy.enforcementRevision || baseline.revision;
463
+ const extendedCoverageRevision =
464
+ policy.extendedCoverageRevision || enforcementRevision;
386
465
  const hydratedRevisions = ensureMaintainabilityRevisionsAvailable(root, {
387
466
  baselineRevision: baseline.revision,
388
467
  enforcementRevision,
389
468
  });
469
+ const hydratedExtendedCoverageRevision = ensureRevisionAvailable(
470
+ root,
471
+ extendedCoverageRevision,
472
+ );
390
473
  const current = collectMaintainabilityMetrics({ root });
474
+ const debt = readJson(root, "architecture/maintainability-debt.json");
475
+ const architecture = readJson(
476
+ root,
477
+ "architecture/internal-capabilities.json",
478
+ );
391
479
  const baselineFiles = sourceMetricsAtRevision(root, enforcementRevision);
392
- const issues = evaluateMaintainability({ current, baselineFiles, policy });
480
+ const extendedSourceFiles = sourceMetricsAtRevision(
481
+ root,
482
+ extendedCoverageRevision,
483
+ );
484
+ for (const [file, metrics] of Object.entries(extendedSourceFiles)) {
485
+ if (file.endsWith(".rs")) baselineFiles[file] = metrics;
486
+ }
487
+ const baselineTests = testMetricsAtRevision(root, extendedCoverageRevision);
488
+ const baselineWorkflows = workflowMetricsAtRevision(
489
+ root,
490
+ extendedCoverageRevision,
491
+ );
492
+ const issues = evaluateExceptionGovernance({ policy });
493
+ issues.push(...evaluateExceptionBudget({ policy }));
494
+ const hotspots = collectHotspots(root, current, 20, debt.hotspots || []);
495
+ issues.push(
496
+ ...evaluateDebtAuthority({
497
+ current,
498
+ policy,
499
+ debt,
500
+ capabilityIds: new Set(
501
+ architecture.capabilities.map((entry) => entry.id),
502
+ ),
503
+ hotspots,
504
+ }),
505
+ );
506
+ issues.push(...evaluateDebtBudget({ debt, policy }));
507
+ issues.push(...evaluateMaintainability({ current, baselineFiles, policy }));
508
+ issues.push(
509
+ ...evaluateTestBudgets({ current, baselineFiles: baselineTests, policy }),
510
+ );
511
+ issues.push(
512
+ ...evaluateWorkflowBudgets({
513
+ current,
514
+ baselineFiles: baselineWorkflows,
515
+ policy,
516
+ }),
517
+ );
393
518
  issues.push(...evaluateRepositoryBudgets({ current, policy }));
394
519
  issues.push(
395
520
  ...evaluatePublicSurface({ root, revision: enforcementRevision, policy }),
@@ -401,12 +526,18 @@ function checkMaintainability({ root = process.cwd() } = {}) {
401
526
  schemaVersion: 1,
402
527
  baselineRevision: baseline.revision,
403
528
  enforcementRevision,
529
+ extendedCoverageRevision,
404
530
  hydratedBaselineRevision: hydratedRevisions[baseline.revision],
405
531
  hydratedEnforcementRevision: hydratedRevisions[enforcementRevision],
532
+ hydratedExtendedCoverageRevision,
406
533
  trackedFiles: current.repository.trackedFiles,
407
534
  sourceFiles: current.repository.handMaintainedSourceFiles,
408
535
  publicSurface: current.publicSurface,
409
536
  hotspots: current.hotspots,
537
+ governedDebtSurfaces: Object.values(debt.surfaces).reduce(
538
+ (total, entries) => total + Object.keys(entries).length,
539
+ 0,
540
+ ),
410
541
  };
411
542
  }
412
543
 
@@ -427,11 +558,21 @@ if (
427
558
  }
428
559
 
429
560
  export {
561
+ calculateDebtMeasuredExcess,
430
562
  checkMaintainability,
563
+ collectHotspots,
431
564
  ensureMaintainabilityRevisionsAvailable,
432
565
  ensureRevisionAvailable,
433
566
  evaluateMaintainability,
567
+ evaluateDebtAuthority,
568
+ evaluateDebtBudget,
569
+ evaluateExceptionBudget,
570
+ evaluateExceptionGovernance,
434
571
  evaluateRepositoryBudgets,
572
+ evaluateTestBudgets,
573
+ evaluateWorkflowBudgets,
435
574
  evaluatePublicSurface,
436
575
  sourceMetricsAtRevision,
576
+ testMetricsAtRevision,
577
+ workflowMetricsAtRevision,
437
578
  };