archctx-contracts 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/fixtures/invalid/projection-result-applied-incomplete-coverage.json +3 -3
  2. package/fixtures/valid/archctx-capabilities.json +2 -2
  3. package/fixtures/valid/flow-selector-check.json +1 -1
  4. package/fixtures/valid/product-version-manifest.json +5 -11
  5. package/fixtures/valid/projection-manifest.json +1 -1
  6. package/fixtures/valid/projection-result.json +3 -3
  7. package/package.json +4 -1
  8. package/schemas/repo/refactor-decision.schema.json +283 -37
  9. package/schemas/runtime/archctx-capabilities.schema.json +144 -20
  10. package/schemas/runtime/architecture-debt-delta.schema.json +58 -19
  11. package/schemas/runtime/architecture-debt.schema.json +42 -42
  12. package/schemas/runtime/architecture-event.schema.json +1 -1
  13. package/schemas/runtime/architecture-history.schema.json +354 -0
  14. package/schemas/runtime/capability-dependencies.schema.json +266 -59
  15. package/schemas/runtime/cli-check.schema.json +197 -0
  16. package/schemas/runtime/cli-help.schema.json +28 -0
  17. package/schemas/runtime/dependency-constraint-evaluation.schema.json +67 -68
  18. package/schemas/runtime/docs-anchors.schema.json +250 -67
  19. package/schemas/runtime/doctor-code-facts.schema.json +49 -0
  20. package/schemas/runtime/evidence-binding.schema.json +1 -1
  21. package/schemas/runtime/flow-selector-check.schema.json +179 -46
  22. package/schemas/runtime/hook-debt-checkpoint.schema.json +12 -12
  23. package/schemas/runtime/index-seed.schema.json +56 -0
  24. package/schemas/runtime/path-context.schema.json +108 -0
  25. package/schemas/runtime/product-version-manifest.schema.json +142 -54
  26. package/schemas/runtime/projection-apply-readback.schema.json +2 -2
  27. package/schemas/runtime/projection-apply-recovery.schema.json +1 -1
  28. package/schemas/runtime/projection-result.schema.json +1 -1
  29. package/schemas/runtime/projection-slice.schema.json +34 -34
  30. package/schemas/runtime/recommendation-v3.schema.json +372 -1
  31. package/schemas/runtime/ref-impact-batch-request.schema.json +20 -7
  32. package/schemas/runtime/ref-impact-batch.schema.json +83 -13
  33. package/schemas/runtime/ref-impact.schema.json +68 -61
  34. package/schemas/runtime/refactor-scan-v2.schema.json +434 -0
  35. package/schemas/runtime/refactor-simulate.schema.json +505 -0
  36. package/schemas/runtime/refactor-verify-v2.schema.json +172 -0
  37. package/schemas/runtime/resolve-path.schema.json +69 -0
  38. package/schemas/runtime/runtime-recommendation-show.schema.json +531 -2
  39. package/schemas/runtime/runtime-refactor-scan.schema.json +498 -2
  40. package/schemas/runtime/runtime-verify.schema.json +274 -56
  41. package/schemas/runtime/state-machine-check.schema.json +357 -89
  42. package/schemas/runtime/structural-observation-payload.schema.json +372 -1
  43. package/schemas/runtime/sync-check.schema.json +65 -0
  44. package/src/architecture-debt.ts +125 -38
  45. package/src/architecture-history.ts +168 -42
  46. package/src/architecture.ts +100 -0
  47. package/src/cli-read.ts +228 -0
  48. package/src/docs-anchors.ts +105 -50
  49. package/src/explorer-occurrence-ports.ts +175 -0
  50. package/src/explorer-query-ports.ts +270 -0
  51. package/src/failure.ts +3 -0
  52. package/src/index-seed.ts +42 -0
  53. package/src/index.ts +5 -0
  54. package/src/ledger-records.ts +262 -0
  55. package/src/ledger.ts +27 -566
  56. package/src/ownership-dependencies.ts +115 -5
  57. package/src/ports.ts +12 -543
  58. package/src/product-version.ts +75 -56
  59. package/src/projection-apply-types.ts +216 -0
  60. package/src/projection-apply-validators.ts +355 -0
  61. package/src/projection-capabilities.ts +181 -0
  62. package/src/projection-constants.ts +317 -0
  63. package/src/projection-manifest-types.ts +298 -0
  64. package/src/projection-manifest.ts +12 -299
  65. package/src/projection-recovery-validators.ts +229 -0
  66. package/src/projection-request-validators.ts +326 -0
  67. package/src/projection-types.ts +365 -0
  68. package/src/projection-validation-helpers.ts +15 -0
  69. package/src/projection.ts +7 -1689
  70. package/src/ref-impact.ts +225 -33
  71. package/src/refactor-constants.ts +213 -0
  72. package/src/refactor-decision-validators.ts +350 -0
  73. package/src/refactor-evidence-types.ts +286 -0
  74. package/src/refactor-observation-validators.ts +359 -0
  75. package/src/refactor-resolution-validators.ts +229 -0
  76. package/src/refactor-snapshot-validators.ts +368 -0
  77. package/src/refactor-types.ts +270 -0
  78. package/src/refactor-v2.ts +389 -0
  79. package/src/refactor-validation-helpers.ts +195 -0
  80. package/src/refactor.ts +7 -1849
  81. package/src/review-guards.ts +3 -23
  82. package/src/runtime-verify.ts +87 -0
  83. package/src/schema-kit.ts +183 -0
  84. package/src/schema-registry.ts +73 -0
  85. package/src/schema.ts +0 -4
  86. package/src/state-machine-schemas.ts +192 -0
  87. package/src/state-machine-types.ts +188 -0
  88. package/src/state-machine.ts +9 -189
  89. package/fixtures/boundary/agent-job-expired.json +0 -33
  90. package/fixtures/invalid/adapter-fidelity-reverse-sync.json +0 -9
  91. package/fixtures/invalid/agent-job-direct-mutation.json +0 -32
  92. package/fixtures/invalid/cloud-egress-envelope-private-field.json +0 -12
  93. package/fixtures/invalid/investigation-report-direct-mutation.json +0 -38
  94. package/fixtures/invalid/investigation-report-missing-proposed-delta.json +0 -19
  95. package/fixtures/invalid/notification-event-code-field.json +0 -11
  96. package/fixtures/valid/adapter-fidelity.json +0 -9
  97. package/fixtures/valid/agent-job.json +0 -33
  98. package/fixtures/valid/architecture-candidate-delta-policy.json +0 -45
  99. package/fixtures/valid/architecture-candidate-delta.json +0 -188
  100. package/fixtures/valid/chatgpt-ga-tool.json +0 -9
  101. package/fixtures/valid/cloud-egress-envelope.json +0 -11
  102. package/fixtures/valid/entitlement.json +0 -12
  103. package/fixtures/valid/investigation-report.json +0 -38
  104. package/fixtures/valid/likec4-mapping.json +0 -14
  105. package/fixtures/valid/notification-event.json +0 -10
  106. package/fixtures/valid/notification-provider.json +0 -12
  107. package/fixtures/valid/structurizr-mapping.json +0 -15
  108. package/schemas/cloud/cloud-egress-envelope.schema.json +0 -19
  109. package/schemas/cloud/entitlement.schema.json +0 -24
  110. package/schemas/integrations/adapter-fidelity.schema.json +0 -21
  111. package/schemas/integrations/chatgpt-ga-tool.schema.json +0 -25
  112. package/schemas/integrations/likec4-mapping.schema.json +0 -32
  113. package/schemas/integrations/structurizr-mapping.schema.json +0 -33
  114. package/schemas/runtime/agent-job.schema.json +0 -63
  115. package/schemas/runtime/architecture-candidate-delta-policy.schema.json +0 -129
  116. package/schemas/runtime/architecture-candidate-delta.schema.json +0 -386
  117. package/schemas/runtime/investigation-report.schema.json +0 -119
  118. package/schemas/runtime/notification-event.schema.json +0 -18
  119. package/schemas/runtime/notification-provider.schema.json +0 -26
@@ -0,0 +1,359 @@
1
+ import { ARCHITECTURE_MAJOR_CHANGE_REASON_CODES } from "./projection-constants";
2
+ import {
3
+ REFACTOR_ASSESSMENT_SCHEMA_VERSION,
4
+ REFACTOR_EVIDENCE_ID_LIST_LIMIT,
5
+ REFACTOR_OBSERVATION_EVIDENCE_LIMIT
6
+ } from "./refactor-constants";
7
+ import type {
8
+ RefactorAssessmentV1,
9
+ RefactorEvidenceDirectionViolationV1,
10
+ RefactorEvidenceImportEdgeV1,
11
+ RefactorEvidencePairDirectionV1,
12
+ RefactorEvidenceUnresolvedImportV1,
13
+ RefactorObservationEvidenceV1,
14
+ RefactorObservationV1
15
+ } from "./refactor-evidence-types";
16
+ import { refactorAssessmentDigest } from "./refactor-snapshot-validators";
17
+ import {
18
+ compareLine,
19
+ compareText,
20
+ digestIssues,
21
+ lineIssues,
22
+ ratioIssues,
23
+ repoPathIssues,
24
+ sortedUniqueIssues,
25
+ specifierIssues
26
+ } from "./refactor-validation-helpers";
27
+
28
+ /**
29
+ * How a pair's evidence sample of `limit` entries is split: the thin direction first, but one slot
30
+ * is kept for the thick direction whenever there are two or more slots, so both directions are
31
+ * always shown. Taking the thin direction first is what keeps a single thin edge visible beside
32
+ * any number of thick ones. Resampling a sample with a smaller limit gives exactly this split of
33
+ * the population, so the planner's evidence cut stays on the same rule.
34
+ */
35
+ export function refactorPairSampleAllocation(thinTotal: number, thickTotal: number, limit: number): { thin: number; thick: number } {
36
+ const slots = Math.max(0, Math.min(limit, thinTotal + thickTotal));
37
+ const reserve = thickTotal > 0 && slots >= 2 ? 1 : 0;
38
+ const thin = Math.min(thinTotal, slots - reserve);
39
+ return { thin, thick: Math.min(thickTotal, slots - thin) };
40
+ }
41
+
42
+ /**
43
+ * Cuts a pair's evidence to `limit` entries under `refactorPairSampleAllocation`. `evidence.edges`
44
+ * may be the whole population or an earlier sample of it: each direction keeps its first entries in
45
+ * canonical order, and the result is re-sorted canonically.
46
+ */
47
+ export function sampleRefactorPairEvidence(
48
+ evidence: Extract<RefactorObservationEvidenceV1, { kind: "cycle" }>,
49
+ limit: number
50
+ ): Extract<RefactorObservationEvidenceV1, { kind: "cycle" }> {
51
+ const [thin, thick] = evidence.directions as [RefactorEvidencePairDirectionV1, RefactorEvidencePairDirectionV1];
52
+ const allocation = refactorPairSampleAllocation(thin.totalCount, thick.totalCount, Math.min(limit, REFACTOR_OBSERVATION_EVIDENCE_LIMIT));
53
+ const sorted = [...evidence.edges].sort(compareRefactorEvidenceImportEdges);
54
+ const inDirection = (direction: RefactorEvidencePairDirectionV1) => sorted.filter((edge) =>
55
+ edge.fromNodeId === direction.fromNodeId && edge.toNodeId === direction.toNodeId);
56
+ const thinEdges = inDirection(thin).slice(0, allocation.thin);
57
+ const thickEdges = inDirection(thick).slice(0, allocation.thick);
58
+ const edges = [...thinEdges, ...thickEdges].sort(compareRefactorEvidenceImportEdges);
59
+ return {
60
+ ...evidence,
61
+ directions: [
62
+ { ...thin, sampledCount: thinEdges.length },
63
+ { ...thick, sampledCount: thickEdges.length }
64
+ ],
65
+ edges,
66
+ truncated: evidence.totalCount > edges.length
67
+ };
68
+ }
69
+
70
+ export function refactorAssessmentInvariantIssues(assessment: RefactorAssessmentV1, prefix = "assessment"): string[] {
71
+ const issues = [
72
+ ...digestIssues(`${prefix}.assessmentDigest`, assessment.assessmentDigest),
73
+ ...digestIssues(`${prefix}.statisticsSnapshotDigest`, assessment.statisticsSnapshotDigest),
74
+ ...digestIssues(`${prefix}.modelDigest`, assessment.modelDigest),
75
+ ...digestIssues(`${prefix}.codeFactsDigest`, assessment.codeFactsDigest),
76
+ ...sortedUniqueIssues(`${prefix}.affectedNodeIds`, assessment.affectedNodeIds),
77
+ ...sortedUniqueIssues(`${prefix}.scaleReasonCodes`, assessment.scaleReasonCodes),
78
+ ...sortedUniqueIssues(`${prefix}.majorChangeReasons`, assessment.majorChangeReasons)
79
+ ];
80
+ if (assessment.schemaVersion !== REFACTOR_ASSESSMENT_SCHEMA_VERSION) issues.push(`${prefix}.schemaVersion is invalid`);
81
+ if (assessment.proposalDigest !== null) issues.push(...digestIssues(`${prefix}.proposalDigest`, assessment.proposalDigest));
82
+ if ((assessment.scale === null) !== (assessment.proposalDigest === null)) {
83
+ issues.push(`${prefix}.scale must be null exactly when proposalDigest is null`);
84
+ }
85
+ if (assessment.scale === "architecture" && assessment.majorChangeReasons.length === 0) {
86
+ issues.push(`${prefix}.architecture scale requires at least one majorChangeReason`);
87
+ }
88
+ const allowedReasons = new Set<string>(ARCHITECTURE_MAJOR_CHANGE_REASON_CODES);
89
+ for (const reason of assessment.majorChangeReasons) {
90
+ if (!allowedReasons.has(reason)) issues.push(`${prefix}.majorChangeReasons contains unsupported reason: ${reason}`);
91
+ }
92
+ for (const [index, observation] of assessment.observations.entries()) {
93
+ if (observation.subjectSelectorId.trim() === "") issues.push(`${prefix}.observations[${index}].subjectSelectorId must not be empty`);
94
+ issues.push(...sortedUniqueIssues(`${prefix}.observations[${index}].signalIds`, observation.signalIds));
95
+ issues.push(...(Array.isArray(observation.affectedNodeIds)
96
+ ? sortedUniqueIssues(`${prefix}.observations[${index}].affectedNodeIds`, observation.affectedNodeIds)
97
+ : [`${prefix}.observations[${index}].affectedNodeIds must be an array`]));
98
+ issues.push(...refactorObservationEvidenceIssues(observation, `${prefix}.observations[${index}]`));
99
+ }
100
+ issues.push(...ratioIssues(`${prefix}.confidence.callerCoverage`, assessment.confidence.callerCoverage));
101
+ if (!Number.isInteger(assessment.pressure.score) || assessment.pressure.score < 0 || assessment.pressure.score > 100) {
102
+ issues.push(`${prefix}.pressure.score must be an integer between 0 and 100`);
103
+ }
104
+ issues.push(...sortedUniqueIssues(`${prefix}.pressure.signalIds`, assessment.pressure.signalIds));
105
+ if (refactorAssessmentDigest(assessment) !== assessment.assessmentDigest) {
106
+ issues.push(`${prefix}.assessmentDigest must bind the assessed payload`);
107
+ }
108
+ return issues;
109
+ }
110
+
111
+ /** The one ordering for evidence edges: path, line, target, specifier, then owners. */
112
+ export function compareRefactorEvidenceImportEdges(left: RefactorEvidenceImportEdgeV1, right: RefactorEvidenceImportEdgeV1): number {
113
+ return compareText(left.fromPath, right.fromPath)
114
+ || compareLine(left.fromLine, right.fromLine)
115
+ || compareText(left.toPath, right.toPath)
116
+ || compareText(left.specifier, right.specifier)
117
+ || compareText(left.fromNodeId, right.fromNodeId)
118
+ || compareText(left.toNodeId, right.toNodeId);
119
+ }
120
+
121
+ export function compareRefactorEvidenceDirectionViolations(
122
+ left: RefactorEvidenceDirectionViolationV1,
123
+ right: RefactorEvidenceDirectionViolationV1
124
+ ): number {
125
+ return compareText(left.constraintId, right.constraintId) || compareRefactorEvidenceImportEdges(left, right);
126
+ }
127
+
128
+ export function compareRefactorEvidenceUnresolvedImports(
129
+ left: RefactorEvidenceUnresolvedImportV1,
130
+ right: RefactorEvidenceUnresolvedImportV1
131
+ ): number {
132
+ return compareText(left.fromPath, right.fromPath)
133
+ || compareLine(left.fromLine, right.fromLine)
134
+ || compareText(left.specifier, right.specifier);
135
+ }
136
+
137
+ /**
138
+ * Validates one observation's evidence against the observation it explains: matching kind, the
139
+ * fixed sample and id-list bounds, an honest `truncated` flag and id-list counts, the canonical
140
+ * order, repo-relative paths, positive lines and one-line bounded specifiers. Where a metric counts exactly the evidence population,
141
+ * `totalCount` must equal it, so the sample can never describe a different measurement.
142
+ */
143
+ export function refactorObservationEvidenceIssues(observation: RefactorObservationV1, prefix = "observation"): string[] {
144
+ const evidence = observation.evidence as RefactorObservationEvidenceV1 | undefined;
145
+ const label = `${prefix}.evidence`;
146
+ if (!evidence || typeof evidence !== "object") return [`${label} is required`];
147
+ if (evidence.kind !== observation.kind) return [`${label}.kind must equal the observation kind ${observation.kind}`];
148
+ const issues: string[] = [];
149
+ const sample = (entries: readonly unknown[], field: string): void => {
150
+ if (entries.length > REFACTOR_OBSERVATION_EVIDENCE_LIMIT) {
151
+ issues.push(`${label}.${field} must hold at most ${REFACTOR_OBSERVATION_EVIDENCE_LIMIT} entries`);
152
+ }
153
+ if (!Number.isInteger(evidence.totalCount) || evidence.totalCount < entries.length) {
154
+ issues.push(`${label}.totalCount must be an integer no smaller than the ${field} length`);
155
+ }
156
+ if (evidence.truncated !== evidence.totalCount > entries.length) {
157
+ issues.push(`${label}.truncated must be true exactly when totalCount exceeds the ${field} length`);
158
+ }
159
+ };
160
+ const ordered = <T>(entries: readonly T[], field: string, compare: (left: T, right: T) => number): void => {
161
+ for (let index = 1; index < entries.length; index += 1) {
162
+ if (compare(entries[index - 1]!, entries[index]!) >= 0) {
163
+ issues.push(`${label}.${field} must be sorted and unique`);
164
+ return;
165
+ }
166
+ }
167
+ };
168
+ const edgeIssues = (edge: RefactorEvidenceImportEdgeV1, field: string): void => {
169
+ issues.push(...repoPathIssues(`${label}.${field}.fromPath`, edge.fromPath), ...repoPathIssues(`${label}.${field}.toPath`, edge.toPath));
170
+ issues.push(...lineIssues(`${label}.${field}.fromLine`, edge.fromLine), ...specifierIssues(`${label}.${field}.specifier`, edge.specifier));
171
+ if (edge.fromNodeId.trim() === "" || edge.toNodeId.trim() === "") issues.push(`${label}.${field} node ids must not be empty`);
172
+ };
173
+ // An id list is the sorted prefix of a population of `count`: exactly min(count, limit) long.
174
+ const idList = (ids: readonly string[], count: unknown, field: string, countField: string): void => {
175
+ issues.push(...sortedUniqueIssues(`${label}.${field}`, ids));
176
+ if (!Number.isInteger(count) || (count as number) < 0) {
177
+ issues.push(`${label}.${countField} must be a non-negative integer`);
178
+ } else if (ids.length !== Math.min(count as number, REFACTOR_EVIDENCE_ID_LIST_LIMIT)) {
179
+ issues.push(`${label}.${field} must hold min(${countField}, ${REFACTOR_EVIDENCE_ID_LIST_LIMIT}) entries`);
180
+ }
181
+ };
182
+ switch (evidence.kind) {
183
+ case "cycle": {
184
+ sample(evidence.edges, "edges");
185
+ ordered(evidence.edges, "edges", compareRefactorEvidenceImportEdges);
186
+ issues.push(...pairEvidenceIssues(observation, evidence, label));
187
+ for (const edge of evidence.edges) edgeIssues(edge, "edges");
188
+ break;
189
+ }
190
+ case "residual-cycle": {
191
+ sample(evidence.edges, "edges");
192
+ ordered(evidence.edges, "edges", compareRefactorEvidenceImportEdges);
193
+ idList(evidence.memberNodeIds, observation.metrics.memberCount, "memberNodeIds", "metrics.memberCount");
194
+ // Membership is checkable only against the complete member list.
195
+ const complete = evidence.memberNodeIds.length === observation.metrics.memberCount;
196
+ for (const edge of evidence.edges) {
197
+ edgeIssues(edge, "edges");
198
+ if (complete && (!evidence.memberNodeIds.includes(edge.fromNodeId) || !evidence.memberNodeIds.includes(edge.toNodeId))) {
199
+ issues.push(`${label}.edges must stay inside the component's member nodes`);
200
+ }
201
+ }
202
+ break;
203
+ }
204
+ case "direction-violation":
205
+ sample(evidence.violations, "violations");
206
+ ordered(evidence.violations, "violations", compareRefactorEvidenceDirectionViolations);
207
+ idList(evidence.constraintIds, evidence.constraintCount, "constraintIds", "constraintCount");
208
+ for (const violation of evidence.violations) {
209
+ edgeIssues(violation, "violations");
210
+ if (!evidence.constraintIds.includes(violation.constraintId)) issues.push(`${label}.violations must name a listed constraintId`);
211
+ }
212
+ if (evidence.totalCount !== observation.metrics.directionViolationCount) {
213
+ issues.push(`${label}.totalCount must equal metrics.directionViolationCount`);
214
+ }
215
+ break;
216
+ case "ownership-ambiguous":
217
+ case "undeclared-footprint":
218
+ case "unowned-paths":
219
+ sample(evidence.paths, "paths");
220
+ ordered(evidence.paths, "paths", (left, right) => compareText(left.path, right.path));
221
+ for (const entry of evidence.paths) {
222
+ issues.push(...repoPathIssues(`${label}.paths.path`, entry.path));
223
+ idList(entry.candidateOwnerNodeIds, entry.candidateOwnerCount, "paths.candidateOwnerNodeIds", "paths.candidateOwnerCount");
224
+ }
225
+ if (evidence.kind === "unowned-paths" && evidence.totalCount !== observation.metrics.unownedFileCount) {
226
+ issues.push(`${label}.totalCount must equal metrics.unownedFileCount`);
227
+ }
228
+ break;
229
+ case "evidence-gap":
230
+ sample(evidence.unresolvedImports, "unresolvedImports");
231
+ ordered(evidence.unresolvedImports, "unresolvedImports", compareRefactorEvidenceUnresolvedImports);
232
+ issues.push(...sortedUniqueIssues(`${label}.reasonCodes`, evidence.reasonCodes));
233
+ for (const entry of evidence.unresolvedImports) {
234
+ issues.push(...repoPathIssues(`${label}.unresolvedImports.fromPath`, entry.fromPath));
235
+ issues.push(...lineIssues(`${label}.unresolvedImports.fromLine`, entry.fromLine));
236
+ issues.push(...specifierIssues(`${label}.unresolvedImports.specifier`, entry.specifier));
237
+ }
238
+ if (evidence.totalCount !== observation.metrics.unresolvedImportCount) {
239
+ issues.push(`${label}.totalCount must equal metrics.unresolvedImportCount`);
240
+ }
241
+ break;
242
+ case "low-cohesion-god-file":
243
+ sample(evidence.files, "files");
244
+ ordered(evidence.files, "files", (left, right) => compareText(left.path, right.path));
245
+ for (const entry of evidence.files) {
246
+ issues.push(...repoPathIssues(`${label}.files.path`, entry.path));
247
+ if (!Number.isInteger(entry.lineCount) || entry.lineCount < 0) issues.push(`${label}.files.lineCount must be a non-negative integer`);
248
+ if (!Number.isInteger(entry.topLevelSymbolCount) || entry.topLevelSymbolCount < 0) issues.push(`${label}.files.topLevelSymbolCount must be a non-negative integer`);
249
+ if (!Number.isInteger(entry.clusterCount) || entry.clusterCount < 0) issues.push(`${label}.files.clusterCount must be a non-negative integer`);
250
+ for (const cluster of entry.clusters) {
251
+ issues.push(...sortedUniqueIssues(`${label}.files.clusters.symbols`, cluster.symbols));
252
+ if (!Number.isInteger(cluster.startLine) || cluster.startLine < 1 || !Number.isInteger(cluster.endLine) || cluster.endLine < cluster.startLine) {
253
+ issues.push(`${label}.files.clusters line range is invalid`);
254
+ }
255
+ if (!Number.isInteger(cluster.intraClusterEdges) || cluster.intraClusterEdges < 0 || !Number.isInteger(cluster.crossClusterEdges) || cluster.crossClusterEdges < 0) {
256
+ issues.push(`${label}.files.clusters edge counts must be non-negative integers`);
257
+ }
258
+ }
259
+ }
260
+ break;
261
+ case "entrypoint-bypass":
262
+ issues.push(...sortedUniqueIssues(`${label}.declaredEntrypointPaths`, evidence.declaredEntrypointPaths));
263
+ for (const path of evidence.declaredEntrypointPaths) issues.push(...repoPathIssues(`${label}.declaredEntrypointPaths`, path));
264
+ sample(evidence.edges, "edges");
265
+ ordered(evidence.edges, "edges", compareRefactorEvidenceImportEdges);
266
+ for (const edge of evidence.edges) edgeIssues(edge, "edges");
267
+ break;
268
+ case "unstable-dependency":
269
+ if (!Number.isInteger(evidence.sourceFanIn) || evidence.sourceFanIn < 0) issues.push(`${label}.sourceFanIn must be a non-negative integer`);
270
+ issues.push(...ratioIssues(`${label}.sourceInstability`, evidence.sourceInstability));
271
+ sample(evidence.targets, "targets");
272
+ ordered(evidence.targets, "targets", (left, right) => compareText(left.targetNodeId, right.targetNodeId));
273
+ for (const target of evidence.targets) {
274
+ if (target.targetNodeId.trim() === "") issues.push(`${label}.targets.targetNodeId must not be empty`);
275
+ issues.push(...ratioIssues(`${label}.targets.targetInstability`, target.targetInstability));
276
+ if (!Number.isFinite(target.delta) || target.delta < -1 || target.delta > 1) issues.push(`${label}.targets.delta must be between -1 and 1`);
277
+ if (!Number.isInteger(target.edgeCount) || target.edgeCount < 1) issues.push(`${label}.targets.edgeCount must be a positive integer`);
278
+ }
279
+ break;
280
+ case "co-change-coupling":
281
+ idList(evidence.memberNodeIds, evidence.memberNodeIds.length, "memberNodeIds", "memberNodeCount");
282
+ if (!["complete", "shallow", "insufficient-history", "unavailable"].includes(evidence.coverageStatus)) {
283
+ issues.push(`${label}.coverageStatus is invalid`);
284
+ }
285
+ if (!Number.isInteger(evidence.windowLimit) || evidence.windowLimit < 1) issues.push(`${label}.windowLimit must be a positive integer`);
286
+ if (!Number.isInteger(evidence.observedCommitCount) || evidence.observedCommitCount < 0) issues.push(`${label}.observedCommitCount must be a non-negative integer`);
287
+ sample(evidence.pairs, "pairs");
288
+ ordered(evidence.pairs, "pairs", (left, right) => compareText(left.pathA, right.pathA) || compareText(left.pathB, right.pathB));
289
+ for (const pair of evidence.pairs) {
290
+ issues.push(...repoPathIssues(`${label}.pairs.pathA`, pair.pathA), ...repoPathIssues(`${label}.pairs.pathB`, pair.pathB));
291
+ if (!Number.isInteger(pair.coChangeCount) || pair.coChangeCount < 1) issues.push(`${label}.pairs.coChangeCount must be a positive integer`);
292
+ issues.push(...ratioIssues(`${label}.pairs.jaccard`, pair.jaccard));
293
+ }
294
+ break;
295
+ default:
296
+ issues.push(`${label}.kind is unsupported`);
297
+ }
298
+ return [...new Set(issues)];
299
+ }
300
+
301
+ /**
302
+ * A pair's evidence explains exactly that pair: its two ends are the observation's affected nodes,
303
+ * every edge runs between them in one of the two listed directions, the thin direction (by the
304
+ * observation's own distinct-file-edge counts, ties to the forward direction) comes first, each
305
+ * direction's `sampledCount` is the number of its edges in the sample, and the split is the one
306
+ * `refactorPairSampleAllocation` prescribes for the sample size.
307
+ */
308
+ function pairEvidenceIssues(
309
+ observation: RefactorObservationV1,
310
+ evidence: Extract<RefactorObservationEvidenceV1, { kind: "cycle" }>,
311
+ label: string
312
+ ): string[] {
313
+ const issues: string[] = [];
314
+ const members = evidence.memberNodeIds;
315
+ if (!Array.isArray(members) || members.length !== 2 || !(members[0]! < members[1]!)) {
316
+ return [`${label}.memberNodeIds must be the two pair ends, sorted`];
317
+ }
318
+ const [first, second] = members as [string, string];
319
+ if (Array.isArray(observation.affectedNodeIds) && (observation.affectedNodeIds.length !== 2
320
+ || observation.affectedNodeIds[0] !== first || observation.affectedNodeIds[1] !== second)) {
321
+ issues.push(`${label}.memberNodeIds must equal the observation affectedNodeIds`);
322
+ }
323
+ const forward = observation.metrics.forwardEdgeCount;
324
+ const backward = observation.metrics.backwardEdgeCount;
325
+ if (!Number.isInteger(forward) || !Number.isInteger(backward) || (forward as number) < 1 || (backward as number) < 1) {
326
+ issues.push(`${label} requires positive integer metrics.forwardEdgeCount and metrics.backwardEdgeCount`);
327
+ return issues;
328
+ }
329
+ if (observation.metrics.thinDirectionEdgeCount !== Math.min(forward as number, backward as number)) {
330
+ issues.push(`${label} requires metrics.thinDirectionEdgeCount = min(forwardEdgeCount, backwardEdgeCount)`);
331
+ }
332
+ if (observation.metrics.totalEdgeCount !== (forward as number) + (backward as number)) {
333
+ issues.push(`${label} requires metrics.totalEdgeCount = forwardEdgeCount + backwardEdgeCount`);
334
+ }
335
+ const directions = evidence.directions;
336
+ if (!Array.isArray(directions) || directions.length !== 2) return [...issues, `${label}.directions must list the thin then the thick direction`];
337
+ const [thin, thick] = directions as [RefactorEvidencePairDirectionV1, RefactorEvidencePairDirectionV1];
338
+ const forwardIsThin = (forward as number) <= (backward as number);
339
+ const expectedThin = forwardIsThin ? [first, second] : [second, first];
340
+ if (thin.fromNodeId !== expectedThin[0] || thin.toNodeId !== expectedThin[1]
341
+ || thick.fromNodeId !== expectedThin[1] || thick.toNodeId !== expectedThin[0]) {
342
+ issues.push(`${label}.directions must be [thin, thick] by the pair's distinct file edge counts`);
343
+ }
344
+ for (const direction of directions) {
345
+ if (!Number.isInteger(direction.totalCount) || direction.totalCount < 1) issues.push(`${label}.directions totalCount must be a positive integer`);
346
+ const sampled = evidence.edges.filter((edge) => edge.fromNodeId === direction.fromNodeId && edge.toNodeId === direction.toNodeId).length;
347
+ if (direction.sampledCount !== sampled) issues.push(`${label}.directions sampledCount must count the sampled edges of that direction`);
348
+ if (sampled > direction.totalCount) issues.push(`${label}.directions sample must not exceed the direction population`);
349
+ }
350
+ if (thin.totalCount + thick.totalCount !== evidence.totalCount) issues.push(`${label}.totalCount must be the sum of both directions`);
351
+ if (evidence.edges.some((edge) => !((edge.fromNodeId === first && edge.toNodeId === second) || (edge.fromNodeId === second && edge.toNodeId === first)))) {
352
+ issues.push(`${label}.edges must run between the pair's two ends`);
353
+ }
354
+ const allocation = refactorPairSampleAllocation(thin.totalCount, thick.totalCount, evidence.edges.length);
355
+ if (thin.sampledCount !== allocation.thin || thick.sampledCount !== allocation.thick) {
356
+ issues.push(`${label}.edges must sample the thin direction first and keep one slot for the thick direction`);
357
+ }
358
+ return issues;
359
+ }
@@ -0,0 +1,229 @@
1
+ import type { RecommendationV3, RefactorProposalPayloadV1, StructuralObservationPayloadV1 } from "./ledger";
2
+ import { RECOMMENDATION_CATEGORIES, RECOMMENDATION_V3_SCHEMA_VERSION } from "./ledger-records";
3
+ import { REFACTOR_RESOLUTION_EVIDENCE_SCHEMA_VERSION } from "./refactor-constants";
4
+ import type { RefactorAssessmentV1, RefactorResolutionEvidenceV1 } from "./refactor-evidence-types";
5
+ import {
6
+ refactorAssessmentInvariantIssues,
7
+ refactorObservationEvidenceIssues
8
+ } from "./refactor-observation-validators";
9
+ import {
10
+ moduleStatisticsSnapshotInvariantIssues,
11
+ refactorProposalInvariantIssues,
12
+ refactorResolutionEvidenceDigest
13
+ } from "./refactor-snapshot-validators";
14
+ import type { ModuleStatisticsSnapshotV1, RefactorProposalV1 } from "./refactor-types";
15
+ import {
16
+ digestIssues,
17
+ isPresent,
18
+ isRefactorProposalAuthorSource,
19
+ outcomeIssues as outcomeIssuesWithFallback,
20
+ outcomeSatisfied,
21
+ recommendationPayloadShapeIssues,
22
+ refactorProposalAuthorIssues,
23
+ sortedUniqueIssues
24
+ } from "./refactor-validation-helpers";
25
+ import { digestJson } from "./schema";
26
+
27
+ export function refactorResolutionEvidenceInvariantIssues(
28
+ evidence: RefactorResolutionEvidenceV1,
29
+ prefix = "resolutionEvidence"
30
+ ): string[] {
31
+ const issues = [
32
+ ...digestIssues(`${prefix}.resolutionDigest`, evidence.resolutionDigest),
33
+ ...digestIssues(`${prefix}.recommendationDigest`, evidence.recommendationDigest),
34
+ ...digestIssues(`${prefix}.beforeSnapshotDigest`, evidence.beforeSnapshotDigest),
35
+ ...digestIssues(`${prefix}.afterSnapshotDigest`, evidence.afterSnapshotDigest),
36
+ ...outcomeIssuesWithFallback(`${prefix}.expectedOutcomes`, evidence.expectedOutcomes),
37
+ ...sortedUniqueIssues(`${prefix}.observedOutcomes.outcomeId`, evidence.observedOutcomes.map((outcome) => outcome.outcomeId))
38
+ ];
39
+ if (evidence.schemaVersion !== REFACTOR_RESOLUTION_EVIDENCE_SCHEMA_VERSION) issues.push(`${prefix}.schemaVersion is invalid`);
40
+ const observedById = new Map(evidence.observedOutcomes.map((outcome) => [outcome.outcomeId, outcome]));
41
+ for (const expected of evidence.expectedOutcomes) {
42
+ if (!observedById.has(expected.outcomeId)) issues.push(`${prefix}.observedOutcomes is missing outcome ${expected.outcomeId}`);
43
+ }
44
+ for (const ref of evidence.executionEvidenceRefs) {
45
+ if (!/^[a-f0-9]{64}$/.test(ref.sha256)) issues.push(`${prefix}.executionEvidenceRefs.sha256 must be a bare SHA-256 hex digest`);
46
+ if (ref.locator.trim() === "") issues.push(`${prefix}.executionEvidenceRefs.locator must not be empty`);
47
+ }
48
+ for (const expected of evidence.expectedOutcomes) {
49
+ const observed = observedById.get(expected.outcomeId);
50
+ if (!observed) continue;
51
+ const recomputed = outcomeSatisfied(expected, observed.observedValue);
52
+ if (observed.satisfied !== recomputed) {
53
+ issues.push(
54
+ `${prefix}.observedOutcomes ${expected.outcomeId} claims satisfied=${observed.satisfied} but ${expected.metric} ${expected.operator} ${expected.value} against ${observed.observedValue} is ${recomputed}`
55
+ );
56
+ }
57
+ }
58
+ if (evidence.disposition !== "stale") {
59
+ const required = evidence.expectedOutcomes.filter((outcome) => outcome.required);
60
+ const observedRequired = required
61
+ .map((outcome) => {
62
+ const observed = observedById.get(outcome.outcomeId);
63
+ return observed ? { outcome, satisfied: outcomeSatisfied(outcome, observed.observedValue) } : undefined;
64
+ })
65
+ .filter(isPresent);
66
+ const regressed = evidence.observedOutcomes.some((outcome) => outcome.direction === "regressed");
67
+ const satisfiedCount = observedRequired.filter((entry) => entry.satisfied).length;
68
+ if (regressed && evidence.disposition !== "regressed") {
69
+ issues.push(`${prefix}.disposition must be regressed when any observed outcome regressed`);
70
+ }
71
+ if (!regressed && required.length > 0) {
72
+ if (satisfiedCount === required.length && evidence.disposition !== "resolved") {
73
+ issues.push(`${prefix}.disposition must be resolved when every required outcome is satisfied`);
74
+ }
75
+ if (satisfiedCount === 0 && evidence.disposition !== "not_improved") {
76
+ issues.push(`${prefix}.disposition must be not_improved when no required outcome is satisfied`);
77
+ }
78
+ if (satisfiedCount > 0 && satisfiedCount < required.length && evidence.disposition !== "partially_resolved") {
79
+ issues.push(`${prefix}.disposition must be partially_resolved when only some required outcomes are satisfied`);
80
+ }
81
+ }
82
+ }
83
+ if (refactorResolutionEvidenceDigest(evidence) !== evidence.resolutionDigest) {
84
+ issues.push(`${prefix}.resolutionDigest must bind the verified payload`);
85
+ }
86
+ return issues;
87
+ }
88
+
89
+ /**
90
+ * Guards the one invariant the `RecommendationV3` union cannot enforce at
91
+ * runtime: that `payload` matches `category`. A non-object or mismatched
92
+ * payload yields issues instead of throwing. Every other field is trusted to
93
+ * match its declared type; structural validation of untrusted ingress is the
94
+ * job of the JSON Schemas, not of this validator.
95
+ *
96
+ * The fingerprint hash itself stays owned by `recommendationFingerprint()` in
97
+ * `packages/core/recommendation-engine`: contracts must not import core, and
98
+ * re-deriving the hash here would fork it into two definitions. This validator
99
+ * therefore checks the fingerprint's shape, not its value.
100
+ */
101
+ export function recommendationV3InvariantIssues(recommendation: RecommendationV3, prefix = "recommendation"): string[] {
102
+ const issues = [
103
+ ...sortedUniqueIssues(`${prefix}.evidenceBindingIds`, recommendation.evidenceBindingIds),
104
+ ...digestIssues(`${prefix}.fingerprint`, recommendation.fingerprint)
105
+ ];
106
+ if (recommendation.schemaVersion !== RECOMMENDATION_V3_SCHEMA_VERSION) issues.push(`${prefix}.schemaVersion is invalid`);
107
+ if (!(RECOMMENDATION_CATEGORIES as readonly string[]).includes(recommendation.category)) {
108
+ issues.push(`${prefix}.category is unsupported: ${recommendation.category}`);
109
+ return issues;
110
+ }
111
+ if (recommendation.subjectSelectorId.trim() === "") issues.push(`${prefix}.subjectSelectorId must not be empty`);
112
+ if (recommendation.authoredBy.id.trim() === "") issues.push(`${prefix}.authoredBy.id must not be empty`);
113
+ const shapeIssues = recommendationPayloadShapeIssues(recommendation.category, recommendation.payload, prefix);
114
+ issues.push(...shapeIssues);
115
+ if (recommendation.category === "practice" && !recommendation.practiceId) {
116
+ issues.push(`${prefix}.practiceId is required for practice recommendations`);
117
+ }
118
+ if (recommendation.category === "structural_observation") {
119
+ if (recommendation.authoredBy.source !== "daemon") {
120
+ issues.push(`${prefix}.structural_observation must be authored by the daemon`);
121
+ }
122
+ if (recommendation.authoredBy.kind !== "daemon") {
123
+ issues.push(`${prefix}.structural_observation must be authored by the daemon actor kind`);
124
+ }
125
+ if (recommendation.enforcement !== "advisory") {
126
+ issues.push(`${prefix}.structural_observation enforcement must be advisory`);
127
+ }
128
+ if (shapeIssues.length === 0) {
129
+ // The payload is self-contained: the observation's metrics, signals and evidence travel with
130
+ // it, so the same evidence rules bind a recorded record and a fresh assessment.
131
+ const payload = recommendation.payload as StructuralObservationPayloadV1;
132
+ issues.push(
133
+ ...sortedUniqueIssues(`${prefix}.payload.signalIds`, payload.signalIds),
134
+ ...refactorObservationEvidenceIssues(
135
+ {
136
+ kind: payload.kind,
137
+ subjectSelectorId: recommendation.subject,
138
+ affectedNodeIds: payload.affectedNodeIds,
139
+ signalIds: payload.signalIds,
140
+ metrics: payload.metrics,
141
+ evidence: payload.evidence
142
+ },
143
+ `${prefix}.payload`
144
+ )
145
+ );
146
+ }
147
+ }
148
+ if (recommendation.category === "refactor_proposal") {
149
+ if (!isRefactorProposalAuthorSource(recommendation.authoredBy.source)) {
150
+ issues.push(`${prefix}.refactor_proposal must not be authored by ${recommendation.authoredBy.source}`);
151
+ }
152
+ issues.push(...refactorProposalAuthorIssues(recommendation.authoredBy, prefix));
153
+ if (shapeIssues.length === 0) {
154
+ const payload = recommendation.payload as RefactorProposalPayloadV1;
155
+ const expected = payload.scale === "architecture" ? "complete" : "checkpoint";
156
+ if (recommendation.enforcement !== expected) {
157
+ issues.push(`${prefix}.refactor_proposal with scale ${payload.scale} requires ${expected} enforcement`);
158
+ }
159
+ issues.push(
160
+ ...digestIssues(`${prefix}.payload.proposalDigest`, payload.proposalDigest),
161
+ ...sortedUniqueIssues(`${prefix}.payload.affectedNodeIds`, payload.affectedNodeIds),
162
+ ...sortedUniqueIssues(`${prefix}.payload.majorChangeReasons`, payload.majorChangeReasons)
163
+ );
164
+ }
165
+ }
166
+ return issues;
167
+ }
168
+
169
+ export function refactorScanInvariantIssues(input: {
170
+ snapshot: ModuleStatisticsSnapshotV1;
171
+ assessment: RefactorAssessmentV1;
172
+ proposal?: RefactorProposalV1;
173
+ }): string[] {
174
+ const issues = [
175
+ ...moduleStatisticsSnapshotInvariantIssues(input.snapshot),
176
+ ...refactorAssessmentInvariantIssues(input.assessment),
177
+ ...(input.proposal ? refactorProposalInvariantIssues(input.proposal) : [])
178
+ ];
179
+ if (input.assessment.statisticsSnapshotDigest !== input.snapshot.snapshotDigest) {
180
+ issues.push("assessment.statisticsSnapshotDigest must reference the measured snapshot");
181
+ }
182
+ if (input.snapshot.scope !== undefined && digestJson(input.snapshot.scope) !== digestJson(input.assessment.requestedScope)) {
183
+ issues.push("assessment.requestedScope must match the measured snapshot scope");
184
+ }
185
+ if (input.assessment.modelDigest !== input.snapshot.modelDigest) {
186
+ issues.push("assessment.modelDigest must match the snapshot modelDigest");
187
+ }
188
+ const proposalDigest = input.proposal ? input.proposal.proposalDigest : null;
189
+ if (input.assessment.proposalDigest !== proposalDigest) {
190
+ issues.push("assessment.proposalDigest must reference the submitted proposal");
191
+ }
192
+ const unresolved = input.proposal?.targetDelta?.unresolvedTargets ?? [];
193
+ if (unresolved.length > 0 && input.assessment.scale !== "insufficient_evidence") {
194
+ issues.push("assessment.scale must be insufficient_evidence while targetDelta.unresolvedTargets is non-empty");
195
+ }
196
+ if (unresolved.length > 0 && !input.assessment.scaleReasonCodes.includes("target-unresolved")) {
197
+ issues.push("assessment.scaleReasonCodes must include target-unresolved while targets stay unresolved");
198
+ }
199
+ return issues;
200
+ }
201
+
202
+ export function refactorVerifyInvariantIssues(
203
+ afterSnapshot: ModuleStatisticsSnapshotV1,
204
+ evidence: RefactorResolutionEvidenceV1
205
+ ): string[] {
206
+ const issues = [
207
+ ...moduleStatisticsSnapshotInvariantIssues(afterSnapshot, "afterSnapshot"),
208
+ ...refactorResolutionEvidenceInvariantIssues(evidence)
209
+ ];
210
+ if (evidence.afterSnapshotDigest !== afterSnapshot.snapshotDigest) {
211
+ issues.push("resolutionEvidence.afterSnapshotDigest must reference the re-measured snapshot");
212
+ }
213
+ if (evidence.verifiedHeadSha !== afterSnapshot.worktree.headSha) {
214
+ issues.push("resolutionEvidence.verifiedHeadSha must match the re-measured worktree HEAD");
215
+ }
216
+ if (evidence.verifiedWorktreeDigest !== afterSnapshot.worktree.worktreeDigest) {
217
+ issues.push("resolutionEvidence.verifiedWorktreeDigest must match the re-measured worktree digest");
218
+ }
219
+ if (afterSnapshot.codeFacts.coverage !== "complete" && evidence.disposition === "resolved") {
220
+ issues.push("resolutionEvidence.disposition must not be resolved while after-snapshot coverage is incomplete");
221
+ }
222
+ const indexCoversWorktree =
223
+ afterSnapshot.codeFacts.indexedWorktreeDigest !== null
224
+ && afterSnapshot.codeFacts.indexedWorktreeDigest === afterSnapshot.worktree.worktreeDigest;
225
+ if (!indexCoversWorktree && evidence.disposition === "resolved") {
226
+ issues.push("resolutionEvidence.disposition must not be resolved while the after-snapshot index does not cover the verified worktree");
227
+ }
228
+ return issues;
229
+ }