@webpieces/nx-webpieces-rules 0.4.779 → 0.4.781

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 (34) hide show
  1. package/package.json +6 -6
  2. package/src/executors/generate/executor.d.ts +2 -1
  3. package/src/executors/generate/executor.js +16 -4
  4. package/src/executors/generate/executor.js.map +1 -1
  5. package/src/executors/validate-architecture-unchanged/executor.d.ts +17 -0
  6. package/src/executors/validate-architecture-unchanged/executor.js +32 -25
  7. package/src/executors/validate-architecture-unchanged/executor.js.map +1 -1
  8. package/src/executors/validate-runtime-architecture/executor.js +32 -8
  9. package/src/executors/validate-runtime-architecture/executor.js.map +1 -1
  10. package/src/executors/visualize/executor.js +3 -1
  11. package/src/executors/visualize/executor.js.map +1 -1
  12. package/src/lib/api-contract-files.d.ts +54 -0
  13. package/src/lib/api-contract-files.js +138 -0
  14. package/src/lib/api-contract-files.js.map +1 -0
  15. package/src/lib/api-usage/api-contract-errors.d.ts +1 -1
  16. package/src/lib/api-usage/api-contract-errors.js +4 -4
  17. package/src/lib/api-usage/api-contract-errors.js.map +1 -1
  18. package/src/lib/api-usage/api-relations.d.ts +6 -5
  19. package/src/lib/api-usage/api-relations.js +1 -1
  20. package/src/lib/api-usage/api-relations.js.map +1 -1
  21. package/src/lib/api-usage/api-scanner.d.ts +2 -1
  22. package/src/lib/api-usage/api-scanner.js +2 -1
  23. package/src/lib/api-usage/api-scanner.js.map +1 -1
  24. package/src/lib/graph-loader.d.ts +18 -22
  25. package/src/lib/graph-loader.js +49 -31
  26. package/src/lib/graph-loader.js.map +1 -1
  27. package/src/lib/runtime-graph.js +4 -4
  28. package/src/lib/runtime-graph.js.map +1 -1
  29. package/src/lib/runtime-visualizer.js +1 -1
  30. package/src/lib/runtime-visualizer.js.map +1 -1
  31. package/src/plugin.js +1 -0
  32. package/src/plugin.js.map +1 -1
  33. package/src/runtime-targets.js +1 -0
  34. package/src/runtime-targets.js.map +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/nx-webpieces-rules",
3
- "version": "0.4.779",
3
+ "version": "0.4.781",
4
4
  "description": "Nx-specific webpieces validation rules and graph tooling. Bundles all @webpieces rule packages with Nx graph validators and an inference plugin.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -18,11 +18,11 @@
18
18
  "README.md"
19
19
  ],
20
20
  "dependencies": {
21
- "@webpieces/ai-hook-rules": "0.4.779",
22
- "@webpieces/code-rules": "0.4.779",
23
- "@webpieces/eslint-rules": "0.4.779",
24
- "@webpieces/pr-gate": "0.4.779",
25
- "@webpieces/rules-config": "0.4.779",
21
+ "@webpieces/ai-hook-rules": "0.4.781",
22
+ "@webpieces/code-rules": "0.4.781",
23
+ "@webpieces/eslint-rules": "0.4.781",
24
+ "@webpieces/pr-gate": "0.4.781",
25
+ "@webpieces/rules-config": "0.4.781",
26
26
  "madge": "8.0.0"
27
27
  },
28
28
  "peerDependencies": {
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * Generate Executor
3
3
  *
4
- * Generates the architecture dependency graph and saves it to architecture/dependencies.json.
4
+ * Generates the architecture dependency graph and saves it to architecture/dependencies.json, plus
5
+ * one contract file per API under architecture/apis/ (stale ones are deleted).
5
6
  *
6
7
  * Usage:
7
8
  * nx run architecture:generate
@@ -2,7 +2,8 @@
2
2
  /**
3
3
  * Generate Executor
4
4
  *
5
- * Generates the architecture dependency graph and saves it to architecture/dependencies.json.
5
+ * Generates the architecture dependency graph and saves it to architecture/dependencies.json, plus
6
+ * one contract file per API under architecture/apis/ (stale ones are deleted).
6
7
  *
7
8
  * Usage:
8
9
  * nx run architecture:generate
@@ -14,6 +15,7 @@ const graph_generator_1 = require("../../lib/graph-generator");
14
15
  const graph_sorter_1 = require("../../lib/graph-sorter");
15
16
  const graph_cycles_1 = require("../../lib/graph-cycles");
16
17
  const graph_loader_1 = require("../../lib/graph-loader");
18
+ const api_contract_files_1 = require("../../lib/api-contract-files");
17
19
  const graph_metadata_1 = require("../../lib/graph-metadata");
18
20
  const api_scanner_1 = require("../../lib/api-usage/api-scanner");
19
21
  const external_systems_1 = require("../../lib/api-usage/external-systems");
@@ -148,11 +150,21 @@ async function generateEverything(workspaceRoot, graphPath) {
148
150
  // read the same derived truth.
149
151
  const scanned = scanApiRelations(workspaceRoot, enhancedGraph, projectInfos);
150
152
  const apiContracts = scanned.apiContracts;
151
- // Step 4: Save the graph, INCLUDING the per-contract method table and the external-system
153
+ // Step 4: Write one contract file per API (architecture/apis/<Api>.json) and delete the files of
154
+ // APIs that no longer exist. dependencies.json only LINKS to them, so an endpoint change rewrites
155
+ // an api file and never the dependency graph. The runtime validator reads these files back.
156
+ const effectiveGraphPath = graphPath ?? graph_loader_1.DEFAULT_GRAPH_PATH;
157
+ const contractFiles = new api_contract_files_1.ApiContractFiles();
158
+ const written = contractFiles.write(workspaceRoot, effectiveGraphPath, apiContracts);
159
+ console.log(`āœ… Wrote ${written.written.length} api contract file(s)`);
160
+ for (const deleted of written.deleted)
161
+ console.log(`šŸ—‘ļø Deleted stale api contract file ${deleted}`);
162
+ // Step 4a: Save the graph, INCLUDING the contract-file links and the external-system
152
163
  // declarations the runtime derivation reads back — generate derives from the in-memory graph,
153
- // validate from the file, so anything not written here would make the two disagree.
164
+ // validate from the files, so anything not written here would make the two disagree.
154
165
  console.log('šŸ’¾ Saving graph to architecture/dependencies.json...');
155
- (0, graph_loader_1.saveGraph)(enhancedGraph, workspaceRoot, graphPath, apiContracts, scanned.externalSystems);
166
+ const contractRefs = contractFiles.refsFor(apiContracts);
167
+ (0, graph_loader_1.saveGraph)(enhancedGraph, workspaceRoot, effectiveGraphPath, contractRefs, scanned.externalSystems);
156
168
  console.log('āœ… Graph saved successfully');
157
169
  // Step 4b: Write the committed, clickable HTML view next to the JSON so
158
170
  // dependencies.html regenerates in lock-step with dependencies.json.
@@ -1 +1 @@
1
- {"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../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B,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,IAAA,iBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,2FAA2F;QAC3F,2FAA2F;QAC3F,2EAA2E;QAC3E,MAAM,QAAQ,GAAG,KAAK,YAAY,4BAAa,CAAC,CAAC,CAAC,IAAA,qCAAsB,EAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC;QAChG,OAAO,CAAC,KAAK,CAAC,4BAA4B,EAAE,QAAQ,CAAC,CAAC;QACtD,IAAI,KAAK,YAAY,wCAAuB,EAAE,CAAC;YAC3C,MAAM,MAAM,GAAG,IAAA,4BAAa,EAAC,aAAa,EAAE,+BAA+B,CAAC,CAAC;YAC7E,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YAClB,OAAO,CAAC,KAAK,CAAC,mBAAmB,GAAG,MAAM,GAAG,qDAAqD,CAAC,CAAC;QACxG,CAAC;QACD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;AACL,CAAC","sourcesContent":["/**\n * Generate Executor\n *\n * Generates the architecture dependency graph and saves it to architecture/dependencies.json.\n *\n * Usage:\n * nx run architecture:generate\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport { writeTemplate, RuleFailError, renderRuleFailForHuman } from '@webpieces/rules-config';\nimport { generateReducedGraph } from '../../lib/graph-generator';\nimport { sortGraphTopologically } from '../../lib/graph-sorter';\nimport { ProjectCycleDetector } from '../../lib/graph-cycles';\nimport { saveGraph } from '../../lib/graph-loader';\nimport { collectProjectInfo, enrichGraph, MetadataValidationError } from '../../lib/graph-metadata';\nimport { ProjectInfo } from '../../lib/project-info';\nimport {\n scanAndAttachApiRelations,\n describeUnresolvedApiCalls,\n describeNonLiteralDecoratorArgs,\n buildApiContracts,\n describeMismatchedEndpointKinds,\n} from '../../lib/api-usage/api-scanner';\nimport { buildExternalSystems } from '../../lib/api-usage/external-systems';\nimport type { ApiContracts, ExternalSystemDecls } from '../../lib/api-usage/api-relations';\nimport { loadRuntimeConfig } from '../../lib/runtime-config';\nimport type { EnhancedGraph, GraphEntry } from '../../lib/graph-sorter';\nimport { GraphVisualizer } from '../../lib/graph-visualizer';\nimport { deriveRuntimeGraphReport, saveRuntimeGraph } from '../../lib/runtime-graph';\nimport { printAutoHiddenServers } from '../../lib/runtime-participant-resolver';\nimport { toError } from '../../toError';\n\nexport interface GenerateExecutorOptions {\n graphPath?: string;\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\n/**\n * Generate the runtime microservice graph alongside the compile-time graph, DERIVED from the same\n * dependencies.json (its per-project apiRelations) — one regenerate produces both committed files, and\n * validate derives from the SAME source so they can't diverge. rpc APIs become direct runtime edges;\n * pubsub APIs become edges the viz draws through a queue.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, like the rest of this executor file\nfunction generateRuntimeGraph(\n workspaceRoot: string,\n graph: EnhancedGraph,\n hiddenProjects: Set<string>,\n apiContracts: ApiContracts,\n externalSystems: ExternalSystemDecls,\n): void {\n console.log('šŸ“” Deriving runtime graph from dependencies.json (implements Ɨ uses per API)...');\n const report = deriveRuntimeGraphReport(graph, hiddenProjects, apiContracts, externalSystems);\n saveRuntimeGraph(report.graph, workspaceRoot);\n const serviceCount = Object.keys(report.graph.services).length;\n const queueCount = Object.keys(report.graph.queues).length;\n console.log(\n `āœ… Runtime graph saved (${serviceCount} services, ${report.graph.runtimeEdges.length} runtime edges, ` +\n `${queueCount} queues, ${report.graph.triggers.length} cron/external triggers)`,\n );\n // Every edge the derivation had to GUESS at. Loud on purpose: a fanned-out edge is committed and\n // then reasoned about as if it were derived, which is how a fictional call survives for months.\n printRuntimeWarnings(report.warnings);\n printAutoHiddenServers(report.autoHidden);\n // Printed here, FAILED by validate-runtime-architecture: generate must still write the graph,\n // or the validator would have nothing to compare against and the error would be unfixable.\n if (report.problems.length > 0) {\n console.error(`āŒ ${report.problems.length} client call(s) name a service no module answers to:`);\n for (const problem of report.problems) console.error(` • ${problem}`);\n console.error(' This FAILS architecture:validate-runtime-architecture.');\n }\n}\n\n/** Print the derivation's guessed-edge warnings (nothing at all when the graph is fully targeted). */\n// webpieces-disable no-function-outside-class -- executor step helper, like the rest of this executor file\nfunction printRuntimeWarnings(warnings: string[]): void {\n if (warnings.length === 0) return;\n console.warn(`āš ļø ${warnings.length} runtime edge(s) could not be targeted to ONE service:`);\n for (const warning of warnings) console.warn(` • ${warning}`);\n}\n\n/**\n * Scan for api relations and attach them, surfacing any contract we could NOT map back to source.\n * Unresolved contracts mean the graph we are about to WRITE is incomplete, so they must be loud —\n * a green run that quietly omits a service gets committed, rendered, and trusted.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, like the rest of this executor file\nfunction scanApiRelations(\n workspaceRoot: string,\n graph: EnhancedGraph,\n projectInfos: Map<string, ProjectInfo>,\n): ScannedTables {\n console.log('šŸ”Ž Scanning source for implements/uses API relations...');\n const externalApiPaths = loadRuntimeConfig(workspaceRoot).externalApiPaths;\n const scan = scanAndAttachApiRelations(workspaceRoot, graph, projectInfos, externalApiPaths);\n if (scan.unresolvedApiCalls.length > 0) console.warn(describeUnresolvedApiCalls(scan.unresolvedApiCalls));\n // A decorator argument we could not read costs the graph a basePath, a method, or a whole\n // contract — none of which leaves a trace in the output. Name them before anything is written.\n if (scan.nonLiteralDecoratorArgs.length > 0) {\n console.warn(describeNonLiteralDecoratorArgs(scan.nonLiteralDecoratorArgs));\n }\n const contracts = buildApiContracts(scan);\n // An endpoint whose declared trigger its api kind cannot deliver would silently draw a queue or a\n // clock that nothing could ever fire — name it here, where the fix is one decorator away.\n const mismatches = describeMismatchedEndpointKinds(contracts);\n if (mismatches.length > 0) {\n console.error(`āŒ ${mismatches.length} @Endpoint kind(s) conflict with their api kind:`);\n for (const mismatch of mismatches) console.error(` • ${mismatch}`);\n }\n return new ScannedTables(contracts, buildExternalSystems(scan.apiIndex, projectInfos));\n}\n\n/** The two committed tables one scan produces, kept together so callers cannot persist just one. */\nclass ScannedTables {\n constructor(\n public readonly apiContracts: ApiContracts,\n public readonly externalSystems: ExternalSystemDecls,\n ) {}\n}\n\n/** Projects tagged drawOnGraph:false — kept in the JSON, omitted from every rendered graph. */\n// webpieces-disable no-function-outside-class -- executor step helper, like the rest of this executor file\nfunction hiddenProjectsIn(graph: EnhancedGraph): Set<string> {\n const hidden = new Set<string>();\n for (const name of Object.keys(graph)) {\n if (graph[name].drawOnGraph === false) hidden.add(name);\n }\n return hidden;\n}\n\n// webpieces-disable no-function-outside-class -- executor step helper, like the rest of this executor file\nfunction printGraphSummary(graph: EnhancedGraph): void {\n const levels = new Set(Object.values(graph).map((entry: GraphEntry) => entry.level));\n console.log(`\\nšŸ“ˆ Graph Summary:`);\n console.log(` Projects: ${Object.keys(graph).length}`);\n console.log(` Levels: ${levels.size} (0-${Math.max(...levels)})`);\n}\n\n/**\n * The whole generation pipeline. Split out of runExecutor so that function stays a thin\n * try/catch-and-report shell — the error reporting is what a caller reads on failure, and it should\n * not be separated from the throw by fifty lines of steps.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, like the rest of this executor file\nasync function generateEverything(workspaceRoot: string, graphPath: string | undefined): Promise<void> {\n // Step 1: Build the full graph from nx, then transitively reduce it to the view\n console.log(\"šŸ“Š Generating dependency graph from nx's project graph...\");\n const reducedGraph = await generateReducedGraph();\n\n // Step 1b: The graph is a BUILD graph — refuse a cyclic one, naming EVERY cycle. This runs\n // before the sort deliberately: the sort also refuses, but reports one cycle and an\n // undifferentiated list of everything tangled with it, so a repo with several cycles pays one\n // full regeneration per cycle to discover them.\n console.log('šŸ”„ Checking the project graph is acyclic...');\n const cycles = new ProjectCycleDetector();\n cycles.assertAcyclic(reducedGraph, 'the nx project graph');\n\n // Step 2: Topological sort (to assign levels for visualization)\n console.log('šŸ”„ Computing topological layers...');\n const enhancedGraph = sortGraphTopologically(reducedGraph);\n // ...and assert the stratification it just produced actually holds: every dependency strictly\n // below its dependent. Safe to assert only because the graph was sorted a line ago — a stale\n // committed file is never checked this way.\n cycles.assertLevelsDescend(reducedGraph, cycles.levelsOf(enhancedGraph), 'the freshly sorted graph');\n\n // Step 3: Enrich with AI metadata (framework, shortDescription, file\n // pointers). This VALIDATES (responsibilities.md required per project)\n // and throws before any write, so a failure never clobbers the file.\n console.log('šŸ·ļø Enriching graph with framework + responsibilities metadata...');\n const projectInfos = await collectProjectInfo();\n enrichGraph(enhancedGraph, projectInfos, workspaceRoot);\n\n // Step 3b: Classify each api-lib edge (implements/uses + rpc/pubsub) by\n // scanning source, so dependencies.json + the viz + the runtime graph all\n // read the same derived truth.\n const scanned = scanApiRelations(workspaceRoot, enhancedGraph, projectInfos);\n const apiContracts = scanned.apiContracts;\n\n // Step 4: Save the graph, INCLUDING the per-contract method table and the external-system\n // declarations the runtime derivation reads back — generate derives from the in-memory graph,\n // validate from the file, so anything not written here would make the two disagree.\n console.log('šŸ’¾ Saving graph to architecture/dependencies.json...');\n saveGraph(enhancedGraph, workspaceRoot, graphPath, apiContracts, scanned.externalSystems);\n console.log('āœ… Graph saved successfully');\n\n // Step 4b: Write the committed, clickable HTML view next to the JSON so\n // dependencies.html regenerates in lock-step with dependencies.json.\n const vizPaths = new GraphVisualizer().writeVisualization(enhancedGraph, workspaceRoot);\n console.log(`āœ… Wrote ${vizPaths.htmlPath}`);\n\n // Step 5: Generate the runtime microservice graph from the same scan.\n // Projects tagged drawOnGraph:false are threaded through so the runtime\n // graph hides them too (they stay flagged in runtime-dependencies.json).\n generateRuntimeGraph(\n workspaceRoot,\n enhancedGraph,\n hiddenProjectsIn(enhancedGraph),\n apiContracts,\n scanned.externalSystems,\n );\n\n printGraphSummary(enhancedGraph);\n}\n\nexport default async function runExecutor(\n options: GenerateExecutorOptions,\n context: ExecutorContext\n): Promise<ExecutorResult> {\n const graphPath = options.graphPath;\n const workspaceRoot = context.root;\n\n console.log('\\nšŸ“Š Architecture Graph Generator\\n');\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n await generateEverything(workspaceRoot, graphPath);\n return { success: true };\n } catch (err: unknown) {\n const error = toError(err);\n // A RuleFailError carries its cures as Option[]; `Error.message` is only the aiMessage, so\n // printing that alone silently drops them. renderRuleFailForHuman is the ONE renderer that\n // numbers them, and this catch is the top-level handler for the nx target.\n const rendered = error instanceof RuleFailError ? renderRuleFailForHuman(error) : error.message;\n console.error('āŒ Graph generation failed:', rendered);\n if (error instanceof MetadataValidationError) {\n const mdPath = writeTemplate(workspaceRoot, 'webpieces.responsibilities.md');\n console.error('');\n console.error('āš ļø *** Refer to ' + mdPath + ' for how to author responsibilities.md files *** āš ļø');\n }\n return { success: false };\n }\n}\n"]}
1
+ {"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/generate/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;AAoNH,8BA2BC;AA5OD,0DAA+F;AAC/F,+DAAiE;AACjE,yDAAgE;AAChE,yDAA8D;AAC9D,yDAAuE;AACvE,qEAAgE;AAChE,6DAAoG;AAEpG,iEAMyC;AACzC,2EAA4E;AAE5E,6DAA6D;AAE7D,iEAA6D;AAC7D,2DAAqF;AACrF,yFAAgF;AAChF,2CAAwC;AAUxC;;;;;GAKG;AACH,2GAA2G;AAC3G,SAAS,oBAAoB,CACzB,aAAqB,EACrB,KAAoB,EACpB,cAA2B,EAC3B,YAA0B,EAC1B,eAAoC;IAEpC,OAAO,CAAC,GAAG,CAAC,iFAAiF,CAAC,CAAC;IAC/F,MAAM,MAAM,GAAG,IAAA,wCAAwB,EAAC,KAAK,EAAE,cAAc,EAAE,YAAY,EAAE,eAAe,CAAC,CAAC;IAC9F,IAAA,gCAAgB,EAAC,MAAM,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC;IAC9C,MAAM,YAAY,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC;IAC/D,MAAM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AAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC;QAChG,OAAO,CAAC,KAAK,CAAC,4BAA4B,EAAE,QAAQ,CAAC,CAAC;QACtD,IAAI,KAAK,YAAY,wCAAuB,EAAE,CAAC;YAC3C,MAAM,MAAM,GAAG,IAAA,4BAAa,EAAC,aAAa,EAAE,+BAA+B,CAAC,CAAC;YAC7E,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YAClB,OAAO,CAAC,KAAK,CAAC,mBAAmB,GAAG,MAAM,GAAG,qDAAqD,CAAC,CAAC;QACxG,CAAC;QACD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;AACL,CAAC","sourcesContent":["/**\n * Generate Executor\n *\n * Generates the architecture dependency graph and saves it to architecture/dependencies.json, plus\n * one contract file per API under architecture/apis/ (stale ones are deleted).\n *\n * Usage:\n * nx run architecture:generate\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport { writeTemplate, RuleFailError, renderRuleFailForHuman } from '@webpieces/rules-config';\nimport { generateReducedGraph } from '../../lib/graph-generator';\nimport { sortGraphTopologically } from '../../lib/graph-sorter';\nimport { ProjectCycleDetector } from '../../lib/graph-cycles';\nimport { saveGraph, DEFAULT_GRAPH_PATH } from '../../lib/graph-loader';\nimport { ApiContractFiles } from '../../lib/api-contract-files';\nimport { collectProjectInfo, enrichGraph, MetadataValidationError } from '../../lib/graph-metadata';\nimport { ProjectInfo } from '../../lib/project-info';\nimport {\n scanAndAttachApiRelations,\n describeUnresolvedApiCalls,\n describeNonLiteralDecoratorArgs,\n buildApiContracts,\n describeMismatchedEndpointKinds,\n} from '../../lib/api-usage/api-scanner';\nimport { buildExternalSystems } from '../../lib/api-usage/external-systems';\nimport type { ApiContracts, ExternalSystemDecls } from '../../lib/api-usage/api-relations';\nimport { loadRuntimeConfig } from '../../lib/runtime-config';\nimport type { EnhancedGraph, GraphEntry } from '../../lib/graph-sorter';\nimport { GraphVisualizer } from '../../lib/graph-visualizer';\nimport { deriveRuntimeGraphReport, saveRuntimeGraph } from '../../lib/runtime-graph';\nimport { printAutoHiddenServers } from '../../lib/runtime-participant-resolver';\nimport { toError } from '../../toError';\n\nexport interface GenerateExecutorOptions {\n graphPath?: string;\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\n/**\n * Generate the runtime microservice graph alongside the compile-time graph, DERIVED from the same\n * dependencies.json (its per-project apiRelations) — one regenerate produces both committed files, and\n * validate derives from the SAME source so they can't diverge. rpc APIs become direct runtime edges;\n * pubsub APIs become edges the viz draws through a queue.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, like the rest of this executor file\nfunction generateRuntimeGraph(\n workspaceRoot: string,\n graph: EnhancedGraph,\n hiddenProjects: Set<string>,\n apiContracts: ApiContracts,\n externalSystems: ExternalSystemDecls,\n): void {\n console.log('šŸ“” Deriving runtime graph from dependencies.json (implements Ɨ uses per API)...');\n const report = deriveRuntimeGraphReport(graph, hiddenProjects, apiContracts, externalSystems);\n saveRuntimeGraph(report.graph, workspaceRoot);\n const serviceCount = Object.keys(report.graph.services).length;\n const queueCount = Object.keys(report.graph.queues).length;\n console.log(\n `āœ… Runtime graph saved (${serviceCount} services, ${report.graph.runtimeEdges.length} runtime edges, ` +\n `${queueCount} queues, ${report.graph.triggers.length} cron/external triggers)`,\n );\n // Every edge the derivation had to GUESS at. Loud on purpose: a fanned-out edge is committed and\n // then reasoned about as if it were derived, which is how a fictional call survives for months.\n printRuntimeWarnings(report.warnings);\n printAutoHiddenServers(report.autoHidden);\n // Printed here, FAILED by validate-runtime-architecture: generate must still write the graph,\n // or the validator would have nothing to compare against and the error would be unfixable.\n if (report.problems.length > 0) {\n console.error(`āŒ ${report.problems.length} client call(s) name a service no module answers to:`);\n for (const problem of report.problems) console.error(` • ${problem}`);\n console.error(' This FAILS architecture:validate-runtime-architecture.');\n }\n}\n\n/** Print the derivation's guessed-edge warnings (nothing at all when the graph is fully targeted). */\n// webpieces-disable no-function-outside-class -- executor step helper, like the rest of this executor file\nfunction printRuntimeWarnings(warnings: string[]): void {\n if (warnings.length === 0) return;\n console.warn(`āš ļø ${warnings.length} runtime edge(s) could not be targeted to ONE service:`);\n for (const warning of warnings) console.warn(` • ${warning}`);\n}\n\n/**\n * Scan for api relations and attach them, surfacing any contract we could NOT map back to source.\n * Unresolved contracts mean the graph we are about to WRITE is incomplete, so they must be loud —\n * a green run that quietly omits a service gets committed, rendered, and trusted.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, like the rest of this executor file\nfunction scanApiRelations(\n workspaceRoot: string,\n graph: EnhancedGraph,\n projectInfos: Map<string, ProjectInfo>,\n): ScannedTables {\n console.log('šŸ”Ž Scanning source for implements/uses API relations...');\n const externalApiPaths = loadRuntimeConfig(workspaceRoot).externalApiPaths;\n const scan = scanAndAttachApiRelations(workspaceRoot, graph, projectInfos, externalApiPaths);\n if (scan.unresolvedApiCalls.length > 0) console.warn(describeUnresolvedApiCalls(scan.unresolvedApiCalls));\n // A decorator argument we could not read costs the graph a basePath, a method, or a whole\n // contract — none of which leaves a trace in the output. Name them before anything is written.\n if (scan.nonLiteralDecoratorArgs.length > 0) {\n console.warn(describeNonLiteralDecoratorArgs(scan.nonLiteralDecoratorArgs));\n }\n const contracts = buildApiContracts(scan);\n // An endpoint whose declared trigger its api kind cannot deliver would silently draw a queue or a\n // clock that nothing could ever fire — name it here, where the fix is one decorator away.\n const mismatches = describeMismatchedEndpointKinds(contracts);\n if (mismatches.length > 0) {\n console.error(`āŒ ${mismatches.length} @Endpoint kind(s) conflict with their api kind:`);\n for (const mismatch of mismatches) console.error(` • ${mismatch}`);\n }\n return new ScannedTables(contracts, buildExternalSystems(scan.apiIndex, projectInfos));\n}\n\n/** The two committed tables one scan produces, kept together so callers cannot persist just one. */\nclass ScannedTables {\n constructor(\n public readonly apiContracts: ApiContracts,\n public readonly externalSystems: ExternalSystemDecls,\n ) {}\n}\n\n/** Projects tagged drawOnGraph:false — kept in the JSON, omitted from every rendered graph. */\n// webpieces-disable no-function-outside-class -- executor step helper, like the rest of this executor file\nfunction hiddenProjectsIn(graph: EnhancedGraph): Set<string> {\n const hidden = new Set<string>();\n for (const name of Object.keys(graph)) {\n if (graph[name].drawOnGraph === false) hidden.add(name);\n }\n return hidden;\n}\n\n// webpieces-disable no-function-outside-class -- executor step helper, like the rest of this executor file\nfunction printGraphSummary(graph: EnhancedGraph): void {\n const levels = new Set(Object.values(graph).map((entry: GraphEntry) => entry.level));\n console.log(`\\nšŸ“ˆ Graph Summary:`);\n console.log(` Projects: ${Object.keys(graph).length}`);\n console.log(` Levels: ${levels.size} (0-${Math.max(...levels)})`);\n}\n\n/**\n * The whole generation pipeline. Split out of runExecutor so that function stays a thin\n * try/catch-and-report shell — the error reporting is what a caller reads on failure, and it should\n * not be separated from the throw by fifty lines of steps.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, like the rest of this executor file\nasync function generateEverything(workspaceRoot: string, graphPath: string | undefined): Promise<void> {\n // Step 1: Build the full graph from nx, then transitively reduce it to the view\n console.log(\"šŸ“Š Generating dependency graph from nx's project graph...\");\n const reducedGraph = await generateReducedGraph();\n\n // Step 1b: The graph is a BUILD graph — refuse a cyclic one, naming EVERY cycle. This runs\n // before the sort deliberately: the sort also refuses, but reports one cycle and an\n // undifferentiated list of everything tangled with it, so a repo with several cycles pays one\n // full regeneration per cycle to discover them.\n console.log('šŸ”„ Checking the project graph is acyclic...');\n const cycles = new ProjectCycleDetector();\n cycles.assertAcyclic(reducedGraph, 'the nx project graph');\n\n // Step 2: Topological sort (to assign levels for visualization)\n console.log('šŸ”„ Computing topological layers...');\n const enhancedGraph = sortGraphTopologically(reducedGraph);\n // ...and assert the stratification it just produced actually holds: every dependency strictly\n // below its dependent. Safe to assert only because the graph was sorted a line ago — a stale\n // committed file is never checked this way.\n cycles.assertLevelsDescend(reducedGraph, cycles.levelsOf(enhancedGraph), 'the freshly sorted graph');\n\n // Step 3: Enrich with AI metadata (framework, shortDescription, file\n // pointers). This VALIDATES (responsibilities.md required per project)\n // and throws before any write, so a failure never clobbers the file.\n console.log('šŸ·ļø Enriching graph with framework + responsibilities metadata...');\n const projectInfos = await collectProjectInfo();\n enrichGraph(enhancedGraph, projectInfos, workspaceRoot);\n\n // Step 3b: Classify each api-lib edge (implements/uses + rpc/pubsub) by\n // scanning source, so dependencies.json + the viz + the runtime graph all\n // read the same derived truth.\n const scanned = scanApiRelations(workspaceRoot, enhancedGraph, projectInfos);\n const apiContracts = scanned.apiContracts;\n\n // Step 4: Write one contract file per API (architecture/apis/<Api>.json) and delete the files of\n // APIs that no longer exist. dependencies.json only LINKS to them, so an endpoint change rewrites\n // an api file and never the dependency graph. The runtime validator reads these files back.\n const effectiveGraphPath = graphPath ?? DEFAULT_GRAPH_PATH;\n const contractFiles = new ApiContractFiles();\n const written = contractFiles.write(workspaceRoot, effectiveGraphPath, apiContracts);\n console.log(`āœ… Wrote ${written.written.length} api contract file(s)`);\n for (const deleted of written.deleted) console.log(`šŸ—‘ļø Deleted stale api contract file ${deleted}`);\n\n // Step 4a: Save the graph, INCLUDING the contract-file links and the external-system\n // declarations the runtime derivation reads back — generate derives from the in-memory graph,\n // validate from the files, so anything not written here would make the two disagree.\n console.log('šŸ’¾ Saving graph to architecture/dependencies.json...');\n const contractRefs = contractFiles.refsFor(apiContracts);\n saveGraph(enhancedGraph, workspaceRoot, effectiveGraphPath, contractRefs, scanned.externalSystems);\n console.log('āœ… Graph saved successfully');\n\n // Step 4b: Write the committed, clickable HTML view next to the JSON so\n // dependencies.html regenerates in lock-step with dependencies.json.\n const vizPaths = new GraphVisualizer().writeVisualization(enhancedGraph, workspaceRoot);\n console.log(`āœ… Wrote ${vizPaths.htmlPath}`);\n\n // Step 5: Generate the runtime microservice graph from the same scan.\n // Projects tagged drawOnGraph:false are threaded through so the runtime\n // graph hides them too (they stay flagged in runtime-dependencies.json).\n generateRuntimeGraph(\n workspaceRoot,\n enhancedGraph,\n hiddenProjectsIn(enhancedGraph),\n apiContracts,\n scanned.externalSystems,\n );\n\n printGraphSummary(enhancedGraph);\n}\n\nexport default async function runExecutor(\n options: GenerateExecutorOptions,\n context: ExecutorContext\n): Promise<ExecutorResult> {\n const graphPath = options.graphPath;\n const workspaceRoot = context.root;\n\n console.log('\\nšŸ“Š Architecture Graph Generator\\n');\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n await generateEverything(workspaceRoot, graphPath);\n return { success: true };\n } catch (err: unknown) {\n const error = toError(err);\n // A RuleFailError carries its cures as Option[]; `Error.message` is only the aiMessage, so\n // printing that alone silently drops them. renderRuleFailForHuman is the ONE renderer that\n // numbers them, and this catch is the top-level handler for the nx target.\n const rendered = error instanceof RuleFailError ? renderRuleFailForHuman(error) : error.message;\n console.error('āŒ Graph generation failed:', rendered);\n if (error instanceof MetadataValidationError) {\n const mdPath = writeTemplate(workspaceRoot, 'webpieces.responsibilities.md');\n console.error('');\n console.error('āš ļø *** Refer to ' + mdPath + ' for how to author responsibilities.md files *** āš ļø');\n }\n return { success: false };\n }\n}\n"]}
@@ -8,10 +8,27 @@
8
8
  * nx run architecture:validate-architecture-unchanged
9
9
  */
10
10
  import type { ExecutorContext } from '@nx/devkit';
11
+ import type { DependenciesFile } from '../../lib/graph-loader';
12
+ import type { ExternalSystemDecls } from '../../lib/api-usage/api-relations';
13
+ import type { ApiContractFileRefs } from '../../lib/api-contract-files';
14
+ import type { EnhancedGraph } from '../../lib/graph-sorter';
11
15
  export interface ValidateArchitectureUnchangedOptions {
12
16
  graphPath?: string;
13
17
  }
14
18
  export interface ExecutorResult {
15
19
  success: boolean;
16
20
  }
21
+ /**
22
+ * Drift in EITHER side table of dependencies.json — the api contract-file links or the
23
+ * external-system declarations — or null when both match. The first difference found is reported;
24
+ * fixing it is the same single command either way, so listing both adds noise rather than information.
25
+ */
26
+ export declare function describeTableDrift(current: CurrentArchitecture, saved: DependenciesFile): string | null;
27
+ /** The regenerated graph plus the two tables beside it — everything dependencies.json holds. */
28
+ export declare class CurrentArchitecture {
29
+ readonly graph: EnhancedGraph;
30
+ readonly apiContractFiles: ApiContractFileRefs;
31
+ readonly externalSystems: ExternalSystemDecls;
32
+ constructor(graph: EnhancedGraph, apiContractFiles: ApiContractFileRefs, externalSystems: ExternalSystemDecls);
33
+ }
17
34
  export default function runExecutor(options: ValidateArchitectureUnchangedOptions, context: ExecutorContext): Promise<ExecutorResult>;
@@ -9,6 +9,8 @@
9
9
  * nx run architecture:validate-architecture-unchanged
10
10
  */
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.CurrentArchitecture = void 0;
13
+ exports.describeTableDrift = describeTableDrift;
12
14
  exports.default = runExecutor;
13
15
  const rules_config_1 = require("@webpieces/rules-config");
14
16
  const graph_generator_1 = require("../../lib/graph-generator");
@@ -18,6 +20,7 @@ const graph_loader_1 = require("../../lib/graph-loader");
18
20
  const graph_metadata_1 = require("../../lib/graph-metadata");
19
21
  const api_scanner_1 = require("../../lib/api-usage/api-scanner");
20
22
  const external_systems_1 = require("../../lib/api-usage/external-systems");
23
+ const api_contract_files_1 = require("../../lib/api-contract-files");
21
24
  const runtime_config_1 = require("../../lib/runtime-config");
22
25
  const rule_gate_1 = require("../../lib/rule-gate");
23
26
  const toError_1 = require("../../toError");
@@ -47,45 +50,45 @@ function reportMismatch(summary, workspaceRoot) {
47
50
  console.error(' 3. Commit the updated architecture/dependencies.json');
48
51
  }
49
52
  /**
50
- * A human-readable summary of how the regenerated api contract table differs from the committed one,
51
- * or null when they match. Named per contract so the message points at the api that changed rather
52
- * than dumping two JSON blobs.
53
+ * Which APIs dependencies.json links to a contract file, compared by LINK only — an added or removed
54
+ * API. The endpoints inside `architecture/apis/<Api>.json` are deliberately NOT compared (#949): an
55
+ * endpoint change must not fail this rule. Null when the links match.
53
56
  */
54
57
  // webpieces-disable no-function-outside-class -- executor step helper, matches reportMismatch in this file
55
- function describeContractDrift(current, saved) {
58
+ function describeContractLinkDrift(current, saved) {
56
59
  const names = [...new Set([...Object.keys(current), ...Object.keys(saved)])].sort();
57
60
  const changes = [];
58
61
  for (const name of names) {
59
62
  const a = current[name];
60
63
  const b = saved[name];
61
64
  if (a === undefined)
62
- changes.push(` - ${name}: in dependencies.json but no longer in source`);
65
+ changes.push(` - ${name}: linked in dependencies.json but no longer in source`);
63
66
  else if (b === undefined)
64
- changes.push(` + ${name}: in source but missing from dependencies.json`);
65
- else if (JSON.stringify(a) !== JSON.stringify(b))
66
- changes.push(` ~ ${name}: endpoints/kinds/queues changed`);
67
+ changes.push(` + ${name}: in source but not linked from dependencies.json`);
68
+ else if (a !== b)
69
+ changes.push(` ~ ${name}: contract file link changed (${b} -> ${a})`);
67
70
  }
68
71
  if (changes.length === 0)
69
72
  return null;
70
- return `apiContracts drift (${changes.length} contract(s)):\n${changes.join('\n')}`;
73
+ return `apiContractFiles drift (${changes.length} api(s)):\n${changes.join('\n')}`;
71
74
  }
72
75
  /**
73
- * Drift in EITHER side table of dependencies.json — the api contracts or the external-system
74
- * declarations — or null when both match. The first difference found is reported; fixing it is the
75
- * same single command either way, so listing both adds noise rather than information.
76
+ * Drift in EITHER side table of dependencies.json — the api contract-file links or the
77
+ * external-system declarations — or null when both match. The first difference found is reported;
78
+ * fixing it is the same single command either way, so listing both adds noise rather than information.
76
79
  */
77
- // webpieces-disable no-function-outside-class -- executor step helper, matches describeContractDrift above
80
+ // webpieces-disable no-function-outside-class -- executor step helper, matches describeContractLinkDrift above
78
81
  function describeTableDrift(current, saved) {
79
- const contractDrift = describeContractDrift(current.apiContracts, saved.apiContracts);
80
- if (contractDrift !== null)
81
- return contractDrift;
82
+ const linkDrift = describeContractLinkDrift(current.apiContractFiles, saved.apiContractFiles);
83
+ if (linkDrift !== null)
84
+ return linkDrift;
82
85
  return describeExternalSystemDrift(current.externalSystems, saved.externalSystems);
83
86
  }
84
87
  /**
85
88
  * The same drift report for the declared external systems, or null when they match. Named per
86
89
  * system so the message points at the database that changed rather than dumping two JSON blobs.
87
90
  */
88
- // webpieces-disable no-function-outside-class -- executor step helper, matches describeContractDrift above
91
+ // webpieces-disable no-function-outside-class -- executor step helper, matches describeContractLinkDrift above
89
92
  function describeExternalSystemDrift(current, saved) {
90
93
  const names = [...new Set([...Object.keys(current), ...Object.keys(saved)])].sort();
91
94
  const changes = [];
@@ -122,19 +125,20 @@ async function buildCurrentGraph(workspaceRoot) {
122
125
  // relation from the regenerated graph and report drift against a perfectly fresh file.
123
126
  const externalApiPaths = (0, runtime_config_1.loadRuntimeConfig)(workspaceRoot).externalApiPaths;
124
127
  const scan = (0, api_scanner_1.scanAndAttachApiRelations)(workspaceRoot, currentGraph, projectInfos, externalApiPaths);
125
- return new CurrentArchitecture(currentGraph, (0, api_scanner_1.buildApiContracts)(scan), (0, external_systems_1.buildExternalSystems)(scan.apiIndex, projectInfos));
128
+ return new CurrentArchitecture(currentGraph, new api_contract_files_1.ApiContractFiles().refsFor((0, api_scanner_1.buildApiContracts)(scan)), (0, external_systems_1.buildExternalSystems)(scan.apiIndex, projectInfos));
126
129
  }
127
130
  /** The regenerated graph plus the two tables beside it — everything dependencies.json holds. */
128
131
  class CurrentArchitecture {
129
132
  graph;
130
- apiContracts;
133
+ apiContractFiles;
131
134
  externalSystems;
132
- constructor(graph, apiContracts, externalSystems) {
135
+ constructor(graph, apiContractFiles, externalSystems) {
133
136
  this.graph = graph;
134
- this.apiContracts = apiContracts;
137
+ this.apiContractFiles = apiContractFiles;
135
138
  this.externalSystems = externalSystems;
136
139
  }
137
140
  }
141
+ exports.CurrentArchitecture = CurrentArchitecture;
138
142
  /** The bootstrap path: there is nothing to diff against yet, so say how to create it. */
139
143
  // webpieces-disable no-function-outside-class -- executor step helper, matches reportMismatch in this file
140
144
  function reportMissingGraph() {
@@ -179,9 +183,9 @@ async function runExecutor(options, context) {
179
183
  reportMismatch(comparison.summary, workspaceRoot);
180
184
  return { success: false };
181
185
  }
182
- // Step 6: Compare the two side tables as well. Neither is part of the project graph, so a
183
- // changed @Endpoint kind, queue name, or external-system declaration would otherwise pass
184
- // here AND pass validate-runtime-architecture (which derives from this same stale file).
186
+ // Step 6: Compare the two side tables as well: which APIs are linked to a contract file, and
187
+ // the external-system declarations. The endpoints inside architecture/apis/<Api>.json are
188
+ // NOT compared — an endpoint change must never fail this rule (#949).
185
189
  const tableDrift = describeTableDrift(currentGraph, savedGraph);
186
190
  if (tableDrift !== null) {
187
191
  reportMismatch(tableDrift, workspaceRoot);
@@ -192,7 +196,10 @@ async function runExecutor(options, context) {
192
196
  }
193
197
  catch (err) {
194
198
  const error = (0, toError_1.toError)(err);
195
- console.error('āŒ Architecture validation failed:', error.message);
199
+ // A RuleFailError (e.g. a dependencies.json still carrying the moved `apiContracts` key)
200
+ // carries its cures in Option[]; render them rather than dropping them with `.message`.
201
+ const rendered = error instanceof rules_config_1.RuleFailError ? (0, rules_config_1.renderRuleFailForHuman)(error) : error.message;
202
+ console.error('āŒ Architecture validation failed:', rendered);
196
203
  if (error instanceof graph_metadata_1.MetadataValidationError) {
197
204
  const mdPath = (0, rules_config_1.writeTemplate)(workspaceRoot, 'webpieces.responsibilities.md');
198
205
  console.error('');
@@ -1 +1 @@
1
- {"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/validate-architecture-unchanged/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;AA0JH,8BAkEC;AAzND,0DAAwD;AACxD,+DAAiE;AACjE,yDAAgE;AAChE,iEAA2D;AAC3D,yDAA2E;AAE3E,6DAAoG;AACpG,iEAA+F;AAC/F,2EAA4E;AAE5E,6DAA6D;AAC7D,mDAA+C;AAE/C,2CAAwC;AAUxC,MAAM,WAAW,GAAG,2BAA2B,CAAC;AAEhD;;;GAGG;AACH,SAAS,wBAAwB,CAAC,aAAqB;IACnD,MAAM,MAAM,GAAG,IAAA,4BAAa,EAAC,aAAa,EAAE,WAAW,CAAC,CAAC;IAEzD,OAAO,MAAM,CAAC;AAClB,CAAC;AAED;;GAEG;AACH,SAAS,cAAc,CAA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K,GAAG,IAAA,iBAAO,EAAC,GAAG,CAAC,CAAC;QAC3B,OAAO,CAAC,KAAK,CAAC,mCAAmC,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QAClE,IAAI,KAAK,YAAY,wCAAuB,EAAE,CAAC;YAC3C,MAAM,MAAM,GAAG,IAAA,4BAAa,EAAC,aAAa,EAAE,+BAA+B,CAAC,CAAC;YAC7E,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YAClB,OAAO,CAAC,KAAK,CAAC,mBAAmB,GAAG,MAAM,GAAG,qDAAqD,CAAC,CAAC;QACxG,CAAC;QACD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;AACL,CAAC","sourcesContent":["/**\n * Validate Architecture Unchanged Executor\n *\n * Validates that the current architecture graph matches the saved blessed graph.\n * This ensures no unapproved architecture changes have been made.\n *\n * Usage:\n * nx run architecture:validate-architecture-unchanged\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport { writeTemplate } from '@webpieces/rules-config';\nimport { generateReducedGraph } from '../../lib/graph-generator';\nimport { sortGraphTopologically } from '../../lib/graph-sorter';\nimport { compareGraphs } from '../../lib/graph-comparator';\nimport { loadBlessedGraph, graphFileExists } from '../../lib/graph-loader';\nimport type { DependenciesFile } from '../../lib/graph-loader';\nimport { collectProjectInfo, enrichGraph, MetadataValidationError } from '../../lib/graph-metadata';\nimport { scanAndAttachApiRelations, buildApiContracts } from '../../lib/api-usage/api-scanner';\nimport { buildExternalSystems } from '../../lib/api-usage/external-systems';\nimport type { ApiContracts, ExternalSystemDecls } from '../../lib/api-usage/api-relations';\nimport { loadRuntimeConfig } from '../../lib/runtime-config';\nimport { RuleGate } from '../../lib/rule-gate';\nimport type { EnhancedGraph } from '../../lib/graph-sorter';\nimport { toError } from '../../toError';\n\nexport interface ValidateArchitectureUnchangedOptions {\n graphPath?: string;\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\nconst TMP_MD_FILE = 'webpieces.dependencies.md';\n\n/**\n * Write the instructions documentation to .webpieces/instruct-ai/.\n * Sourced from @webpieces/rules-config.\n */\nfunction writeTmpInstructionsFile(workspaceRoot: string): string {\n const mdPath = writeTemplate(workspaceRoot, TMP_MD_FILE);\n\n return mdPath;\n}\n\n/**\n * Report a current-vs-saved graph mismatch and write the AI instructions file.\n */\nfunction reportMismatch(summary: string, workspaceRoot: string): void {\n const mdPath = writeTmpInstructionsFile(workspaceRoot);\n\n console.error('āŒ Architecture has changed since last update!');\n console.error('\\nDifferences:');\n console.error(summary);\n console.error('');\n console.error('āš ļø *** Refer to ' + mdPath + ' for instructions on how to fix *** āš ļø');\n console.error('');\n console.error('To fix:');\n console.error(' 1. Review the changes above');\n console.error(' 2. If intentional, ASK USER to run: nx run architecture:generate since this is a critical change');\n console.error(' 3. Commit the updated architecture/dependencies.json');\n}\n\n/**\n * A human-readable summary of how the regenerated api contract table differs from the committed one,\n * or null when they match. Named per contract so the message points at the api that changed rather\n * than dumping two JSON blobs.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, matches reportMismatch in this file\nfunction describeContractDrift(current: ApiContracts, saved: ApiContracts): string | null {\n const names = [...new Set([...Object.keys(current), ...Object.keys(saved)])].sort();\n const changes: string[] = [];\n for (const name of names) {\n const a = current[name];\n const b = saved[name];\n if (a === undefined) changes.push(` - ${name}: in dependencies.json but no longer in source`);\n else if (b === undefined) changes.push(` + ${name}: in source but missing from dependencies.json`);\n else if (JSON.stringify(a) !== JSON.stringify(b)) changes.push(` ~ ${name}: endpoints/kinds/queues changed`);\n }\n if (changes.length === 0) return null;\n return `apiContracts drift (${changes.length} contract(s)):\\n${changes.join('\\n')}`;\n}\n\n/**\n * Drift in EITHER side table of dependencies.json — the api contracts or the external-system\n * declarations — or null when both match. The first difference found is reported; fixing it is the\n * same single command either way, so listing both adds noise rather than information.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, matches describeContractDrift above\nfunction describeTableDrift(current: CurrentArchitecture, saved: DependenciesFile): string | null {\n const contractDrift = describeContractDrift(current.apiContracts, saved.apiContracts);\n if (contractDrift !== null) return contractDrift;\n return describeExternalSystemDrift(current.externalSystems, saved.externalSystems);\n}\n\n/**\n * The same drift report for the declared external systems, or null when they match. Named per\n * system so the message points at the database that changed rather than dumping two JSON blobs.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, matches describeContractDrift above\nfunction describeExternalSystemDrift(current: ExternalSystemDecls, saved: ExternalSystemDecls): string | null {\n const names = [...new Set([...Object.keys(current), ...Object.keys(saved)])].sort();\n const changes: string[] = [];\n for (const name of names) {\n const a = current[name];\n const b = saved[name];\n if (a === undefined) changes.push(` - ${name}: in dependencies.json but no longer declared in source`);\n else if (b === undefined) changes.push(` + ${name}: declared in source but missing from dependencies.json`);\n else if (JSON.stringify(a) !== JSON.stringify(b)) changes.push(` ~ ${name}: kind/label/declarers changed`);\n }\n if (changes.length === 0) return null;\n return `externalSystems drift (${changes.length} system(s)):\\n${changes.join('\\n')}`;\n}\n\n/**\n * Build the current dependency graph exactly as the generator does: reduce the nx\n * graph, sort into levels, enrich with metadata, and attach the derived\n * apiRelations — so this validator compares like-for-like against the committed file.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, matches reportMismatch/writeTmpInstructionsFile in this file\nasync function buildCurrentGraph(workspaceRoot: string): Promise<CurrentArchitecture> {\n console.log('šŸ“Š Generating current dependency graph...');\n const reducedGraph = await generateReducedGraph();\n console.log('šŸ”„ Computing topological layers...');\n const currentGraph = sortGraphTopologically(reducedGraph);\n console.log('šŸ·ļø Enriching graph with framework + responsibilities metadata...');\n const projectInfos = await collectProjectInfo();\n enrichGraph(currentGraph, projectInfos, workspaceRoot);\n console.log('šŸ”Ž Scanning source for implements/uses API relations...');\n // The SAME externalApiPaths the generator uses: scanning without them would drop every vendor\n // relation from the regenerated graph and report drift against a perfectly fresh file.\n const externalApiPaths = loadRuntimeConfig(workspaceRoot).externalApiPaths;\n const scan = scanAndAttachApiRelations(workspaceRoot, currentGraph, projectInfos, externalApiPaths);\n return new CurrentArchitecture(\n currentGraph,\n buildApiContracts(scan),\n buildExternalSystems(scan.apiIndex, projectInfos),\n );\n}\n\n/** The regenerated graph plus the two tables beside it — everything dependencies.json holds. */\nclass CurrentArchitecture {\n constructor(\n public readonly graph: EnhancedGraph,\n public readonly apiContracts: ApiContracts,\n public readonly externalSystems: ExternalSystemDecls,\n ) {}\n}\n\n/** The bootstrap path: there is nothing to diff against yet, so say how to create it. */\n// webpieces-disable no-function-outside-class -- executor step helper, matches reportMismatch in this file\nfunction reportMissingGraph(): void {\n console.error('āŒ No saved graph found at architecture/dependencies.json');\n console.error('');\n console.error('To initialize:');\n console.error(' 1. Run: nx run architecture:generate');\n console.error(' 2. Run: nx run architecture:visualize');\n console.error(' 3. Manually inspect the generated graph to confirm it is the desired architecture');\n console.error(' 4. Commit architecture/dependencies.json');\n}\n\nexport default async function runExecutor(\n options: ValidateArchitectureUnchangedOptions,\n context: ExecutorContext\n): Promise<ExecutorResult> {\n const graphPath = options.graphPath;\n const workspaceRoot = context.root;\n\n // Epoch-gateable: this rule diffs against the blessed architecture/dependencies.json, so\n // \"grandfather the current drift until <epoch>\" is meaningful — hence honorEpoch = true.\n if (new RuleGate().isDisabled(workspaceRoot, 'validate-architecture-unchanged', true)) {\n return { success: true };\n }\n\n console.log('\\nšŸ” Validating Architecture Unchanged\\n');\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // Check if saved graph exists\n if (!graphFileExists(workspaceRoot, graphPath)) {\n reportMissingGraph();\n return { success: false };\n }\n\n // Steps 1-3: build + enrich + scan the current graph (same pipeline the\n // generator runs, so any drift is caught).\n const currentGraph = await buildCurrentGraph(workspaceRoot);\n\n // Step 4: Load saved graph\n console.log('šŸ“‚ Loading saved graph...');\n const savedGraph = loadBlessedGraph(workspaceRoot, graphPath);\n\n if (!savedGraph) {\n console.error('āŒ Could not load saved graph');\n return { success: false };\n }\n\n // Step 5: Compare graphs\n console.log('šŸ” Comparing current graph to saved graph...');\n const comparison = compareGraphs(currentGraph.graph, savedGraph.projects);\n\n if (!comparison.identical) {\n reportMismatch(comparison.summary, workspaceRoot);\n return { success: false };\n }\n\n // Step 6: Compare the two side tables as well. Neither is part of the project graph, so a\n // changed @Endpoint kind, queue name, or external-system declaration would otherwise pass\n // here AND pass validate-runtime-architecture (which derives from this same stale file).\n const tableDrift = describeTableDrift(currentGraph, savedGraph);\n if (tableDrift !== null) {\n reportMismatch(tableDrift, workspaceRoot);\n return { success: false };\n }\n\n console.log('āœ… Architecture unchanged - current graph matches saved graph');\n return { success: true };\n } catch (err: unknown) {\n const error = toError(err);\n console.error('āŒ Architecture validation failed:', error.message);\n if (error instanceof MetadataValidationError) {\n const mdPath = writeTemplate(workspaceRoot, 'webpieces.responsibilities.md');\n console.error('');\n console.error('āš ļø *** Refer to ' + mdPath + ' for how to author responsibilities.md files *** āš ļø');\n }\n return { success: false };\n }\n}\n"]}
1
+ {"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/validate-architecture-unchanged/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;AAoFH,gDAIC;AAoED,8BAqEC;AA9ND,0DAA+F;AAC/F,+DAAiE;AACjE,yDAAgE;AAChE,iEAA2D;AAC3D,yDAA2E;AAE3E,6DAAoG;AACpG,iEAA+F;AAC/F,2EAA4E;AAE5E,qEAAgE;AAEhE,6DAA6D;AAC7D,mDAA+C;AAE/C,2CAAwC;AAUxC,MAAM,WAAW,GAAG,2BAA2B,CAAC;AAEhD;;;GAGG;AACH,SAAS,wBAAwB,CAAC,aAAqB;IACnD,MAAM,MAAM,GAAG,IAAA,4BAAa,EAAC,aAAa,EAAE,WAAW,CAAC,CAAC;IAEzD,OAAO,MAAM,CAAC;AAClB,CAAC;AAED;;GAEG;AACH,SAAS,cAAc,CAAC,OAAe,EAAE,aAAqB;IAC1D,MAAM,MAAM,GAAG,wBAAwB,CAAC,aAAa,CAAC,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AC3B,yFAAyF;QACzF,wFAAwF;QACxF,MAAM,QAAQ,GAAG,KAAK,YAAY,4BAAa,CAAC,CAAC,CAAC,IAAA,qCAAsB,EAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC;QAChG,OAAO,CAAC,KAAK,CAAC,mCAAmC,EAAE,QAAQ,CAAC,CAAC;QAC7D,IAAI,KAAK,YAAY,wCAAuB,EAAE,CAAC;YAC3C,MAAM,MAAM,GAAG,IAAA,4BAAa,EAAC,aAAa,EAAE,+BAA+B,CAAC,CAAC;YAC7E,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YAClB,OAAO,CAAC,KAAK,CAAC,mBAAmB,GAAG,MAAM,GAAG,qDAAqD,CAAC,CAAC;QACxG,CAAC;QACD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;AACL,CAAC","sourcesContent":["/**\n * Validate Architecture Unchanged Executor\n *\n * Validates that the current architecture graph matches the saved blessed graph.\n * This ensures no unapproved architecture changes have been made.\n *\n * Usage:\n * nx run architecture:validate-architecture-unchanged\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport { writeTemplate, RuleFailError, renderRuleFailForHuman } from '@webpieces/rules-config';\nimport { generateReducedGraph } from '../../lib/graph-generator';\nimport { sortGraphTopologically } from '../../lib/graph-sorter';\nimport { compareGraphs } from '../../lib/graph-comparator';\nimport { loadBlessedGraph, graphFileExists } from '../../lib/graph-loader';\nimport type { DependenciesFile } from '../../lib/graph-loader';\nimport { collectProjectInfo, enrichGraph, MetadataValidationError } from '../../lib/graph-metadata';\nimport { scanAndAttachApiRelations, buildApiContracts } from '../../lib/api-usage/api-scanner';\nimport { buildExternalSystems } from '../../lib/api-usage/external-systems';\nimport type { ExternalSystemDecls } from '../../lib/api-usage/api-relations';\nimport { ApiContractFiles } from '../../lib/api-contract-files';\nimport type { ApiContractFileRefs } from '../../lib/api-contract-files';\nimport { loadRuntimeConfig } from '../../lib/runtime-config';\nimport { RuleGate } from '../../lib/rule-gate';\nimport type { EnhancedGraph } from '../../lib/graph-sorter';\nimport { toError } from '../../toError';\n\nexport interface ValidateArchitectureUnchangedOptions {\n graphPath?: string;\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\nconst TMP_MD_FILE = 'webpieces.dependencies.md';\n\n/**\n * Write the instructions documentation to .webpieces/instruct-ai/.\n * Sourced from @webpieces/rules-config.\n */\nfunction writeTmpInstructionsFile(workspaceRoot: string): string {\n const mdPath = writeTemplate(workspaceRoot, TMP_MD_FILE);\n\n return mdPath;\n}\n\n/**\n * Report a current-vs-saved graph mismatch and write the AI instructions file.\n */\nfunction reportMismatch(summary: string, workspaceRoot: string): void {\n const mdPath = writeTmpInstructionsFile(workspaceRoot);\n\n console.error('āŒ Architecture has changed since last update!');\n console.error('\\nDifferences:');\n console.error(summary);\n console.error('');\n console.error('āš ļø *** Refer to ' + mdPath + ' for instructions on how to fix *** āš ļø');\n console.error('');\n console.error('To fix:');\n console.error(' 1. Review the changes above');\n console.error(' 2. If intentional, ASK USER to run: nx run architecture:generate since this is a critical change');\n console.error(' 3. Commit the updated architecture/dependencies.json');\n}\n\n/**\n * Which APIs dependencies.json links to a contract file, compared by LINK only — an added or removed\n * API. The endpoints inside `architecture/apis/<Api>.json` are deliberately NOT compared (#949): an\n * endpoint change must not fail this rule. Null when the links match.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, matches reportMismatch in this file\nfunction describeContractLinkDrift(current: ApiContractFileRefs, saved: ApiContractFileRefs): string | null {\n const names = [...new Set([...Object.keys(current), ...Object.keys(saved)])].sort();\n const changes: string[] = [];\n for (const name of names) {\n const a = current[name];\n const b = saved[name];\n if (a === undefined) changes.push(` - ${name}: linked in dependencies.json but no longer in source`);\n else if (b === undefined) changes.push(` + ${name}: in source but not linked from dependencies.json`);\n else if (a !== b) changes.push(` ~ ${name}: contract file link changed (${b} -> ${a})`);\n }\n if (changes.length === 0) return null;\n return `apiContractFiles drift (${changes.length} api(s)):\\n${changes.join('\\n')}`;\n}\n\n/**\n * Drift in EITHER side table of dependencies.json — the api contract-file links or the\n * external-system declarations — or null when both match. The first difference found is reported;\n * fixing it is the same single command either way, so listing both adds noise rather than information.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, matches describeContractLinkDrift above\nexport function describeTableDrift(current: CurrentArchitecture, saved: DependenciesFile): string | null {\n const linkDrift = describeContractLinkDrift(current.apiContractFiles, saved.apiContractFiles);\n if (linkDrift !== null) return linkDrift;\n return describeExternalSystemDrift(current.externalSystems, saved.externalSystems);\n}\n\n/**\n * The same drift report for the declared external systems, or null when they match. Named per\n * system so the message points at the database that changed rather than dumping two JSON blobs.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, matches describeContractLinkDrift above\nfunction describeExternalSystemDrift(current: ExternalSystemDecls, saved: ExternalSystemDecls): string | null {\n const names = [...new Set([...Object.keys(current), ...Object.keys(saved)])].sort();\n const changes: string[] = [];\n for (const name of names) {\n const a = current[name];\n const b = saved[name];\n if (a === undefined) changes.push(` - ${name}: in dependencies.json but no longer declared in source`);\n else if (b === undefined) changes.push(` + ${name}: declared in source but missing from dependencies.json`);\n else if (JSON.stringify(a) !== JSON.stringify(b)) changes.push(` ~ ${name}: kind/label/declarers changed`);\n }\n if (changes.length === 0) return null;\n return `externalSystems drift (${changes.length} system(s)):\\n${changes.join('\\n')}`;\n}\n\n/**\n * Build the current dependency graph exactly as the generator does: reduce the nx\n * graph, sort into levels, enrich with metadata, and attach the derived\n * apiRelations — so this validator compares like-for-like against the committed file.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, matches reportMismatch/writeTmpInstructionsFile in this file\nasync function buildCurrentGraph(workspaceRoot: string): Promise<CurrentArchitecture> {\n console.log('šŸ“Š Generating current dependency graph...');\n const reducedGraph = await generateReducedGraph();\n console.log('šŸ”„ Computing topological layers...');\n const currentGraph = sortGraphTopologically(reducedGraph);\n console.log('šŸ·ļø Enriching graph with framework + responsibilities metadata...');\n const projectInfos = await collectProjectInfo();\n enrichGraph(currentGraph, projectInfos, workspaceRoot);\n console.log('šŸ”Ž Scanning source for implements/uses API relations...');\n // The SAME externalApiPaths the generator uses: scanning without them would drop every vendor\n // relation from the regenerated graph and report drift against a perfectly fresh file.\n const externalApiPaths = loadRuntimeConfig(workspaceRoot).externalApiPaths;\n const scan = scanAndAttachApiRelations(workspaceRoot, currentGraph, projectInfos, externalApiPaths);\n return new CurrentArchitecture(\n currentGraph,\n new ApiContractFiles().refsFor(buildApiContracts(scan)),\n buildExternalSystems(scan.apiIndex, projectInfos),\n );\n}\n\n/** The regenerated graph plus the two tables beside it — everything dependencies.json holds. */\nexport class CurrentArchitecture {\n constructor(\n public readonly graph: EnhancedGraph,\n public readonly apiContractFiles: ApiContractFileRefs,\n public readonly externalSystems: ExternalSystemDecls,\n ) {}\n}\n\n/** The bootstrap path: there is nothing to diff against yet, so say how to create it. */\n// webpieces-disable no-function-outside-class -- executor step helper, matches reportMismatch in this file\nfunction reportMissingGraph(): void {\n console.error('āŒ No saved graph found at architecture/dependencies.json');\n console.error('');\n console.error('To initialize:');\n console.error(' 1. Run: nx run architecture:generate');\n console.error(' 2. Run: nx run architecture:visualize');\n console.error(' 3. Manually inspect the generated graph to confirm it is the desired architecture');\n console.error(' 4. Commit architecture/dependencies.json');\n}\n\nexport default async function runExecutor(\n options: ValidateArchitectureUnchangedOptions,\n context: ExecutorContext\n): Promise<ExecutorResult> {\n const graphPath = options.graphPath;\n const workspaceRoot = context.root;\n\n // Epoch-gateable: this rule diffs against the blessed architecture/dependencies.json, so\n // \"grandfather the current drift until <epoch>\" is meaningful — hence honorEpoch = true.\n if (new RuleGate().isDisabled(workspaceRoot, 'validate-architecture-unchanged', true)) {\n return { success: true };\n }\n\n console.log('\\nšŸ” Validating Architecture Unchanged\\n');\n\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // Check if saved graph exists\n if (!graphFileExists(workspaceRoot, graphPath)) {\n reportMissingGraph();\n return { success: false };\n }\n\n // Steps 1-3: build + enrich + scan the current graph (same pipeline the\n // generator runs, so any drift is caught).\n const currentGraph = await buildCurrentGraph(workspaceRoot);\n\n // Step 4: Load saved graph\n console.log('šŸ“‚ Loading saved graph...');\n const savedGraph = loadBlessedGraph(workspaceRoot, graphPath);\n\n if (!savedGraph) {\n console.error('āŒ Could not load saved graph');\n return { success: false };\n }\n\n // Step 5: Compare graphs\n console.log('šŸ” Comparing current graph to saved graph...');\n const comparison = compareGraphs(currentGraph.graph, savedGraph.projects);\n\n if (!comparison.identical) {\n reportMismatch(comparison.summary, workspaceRoot);\n return { success: false };\n }\n\n // Step 6: Compare the two side tables as well: which APIs are linked to a contract file, and\n // the external-system declarations. The endpoints inside architecture/apis/<Api>.json are\n // NOT compared — an endpoint change must never fail this rule (#949).\n const tableDrift = describeTableDrift(currentGraph, savedGraph);\n if (tableDrift !== null) {\n reportMismatch(tableDrift, workspaceRoot);\n return { success: false };\n }\n\n console.log('āœ… Architecture unchanged - current graph matches saved graph');\n return { success: true };\n } catch (err: unknown) {\n const error = toError(err);\n // A RuleFailError (e.g. a dependencies.json still carrying the moved `apiContracts` key)\n // carries its cures in Option[]; render them rather than dropping them with `.message`.\n const rendered = error instanceof RuleFailError ? renderRuleFailForHuman(error) : error.message;\n console.error('āŒ Architecture validation failed:', rendered);\n if (error instanceof MetadataValidationError) {\n const mdPath = writeTemplate(workspaceRoot, 'webpieces.responsibilities.md');\n console.error('');\n console.error('āš ļø *** Refer to ' + mdPath + ' for how to author responsibilities.md files *** āš ļø');\n }\n return { success: false };\n }\n}\n"]}
@@ -24,6 +24,7 @@ exports.checkServersPresent = checkServersPresent;
24
24
  exports.default = runExecutor;
25
25
  const rules_config_1 = require("@webpieces/rules-config");
26
26
  const graph_loader_1 = require("../../lib/graph-loader");
27
+ const api_contract_files_1 = require("../../lib/api-contract-files");
27
28
  const toError_1 = require("../../toError");
28
29
  const runtime_graph_1 = require("../../lib/runtime-graph");
29
30
  const runtime_participant_resolver_1 = require("../../lib/runtime-participant-resolver");
@@ -42,11 +43,34 @@ const runtime_config_1 = require("../../lib/runtime-config");
42
43
  * its report-only window — an architecture with no deploy order is not a style preference.
43
44
  */
44
45
  // webpieces-disable no-function-outside-class -- executor step helper, matches checkUnchanged in this file
45
- function deriveOrRender(depsFile, hiddenProjects) {
46
+ function deriveOrRender(workspaceRoot, depsFile, hiddenProjects) {
46
47
  // webpieces-disable no-unmanaged-exceptions -- top-level handler for this nx target; it renders, it does not swallow
47
48
  // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
48
49
  try {
49
- return (0, runtime_graph_1.deriveRuntimeGraphReport)(depsFile.projects, hiddenProjects, depsFile.apiContracts, depsFile.externalSystems);
50
+ // The queue/trigger data comes from the generated architecture/apis/<Api>.json files that
51
+ // dependencies.json links to — the same files generate wrote from its in-memory table.
52
+ const apiContracts = new api_contract_files_1.ApiContractFiles().load(workspaceRoot, graph_loader_1.DEFAULT_GRAPH_PATH, depsFile.apiContractFiles);
53
+ return (0, runtime_graph_1.deriveRuntimeGraphReport)(depsFile.projects, hiddenProjects, apiContracts, depsFile.externalSystems);
54
+ }
55
+ catch (err) {
56
+ const error = (0, toError_1.toError)(err);
57
+ if (error instanceof rules_config_1.RuleFailError)
58
+ return (0, rules_config_1.renderRuleFailForHuman)(error);
59
+ throw error;
60
+ }
61
+ }
62
+ /**
63
+ * The committed dependencies.json, or the RENDERED failure when it is absent or cannot be read as the
64
+ * current shape (e.g. it still carries the retired `apiContracts` key). Rendered here for the same
65
+ * reason as deriveOrRender: this executor is the top-level handler for its nx target.
66
+ */
67
+ // webpieces-disable no-function-outside-class -- executor step helper, matches deriveOrRender in this file
68
+ function loadOrRender(workspaceRoot) {
69
+ // webpieces-disable no-unmanaged-exceptions -- top-level handler for this nx target; it renders, it does not swallow
70
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
71
+ try {
72
+ const depsFile = (0, graph_loader_1.loadBlessedGraph)(workspaceRoot);
73
+ return depsFile ?? 'No architecture/dependencies.json — run: nx run architecture:generate';
50
74
  }
51
75
  catch (err) {
52
76
  const error = (0, toError_1.toError)(err);
@@ -99,9 +123,9 @@ async function runExecutor(_options, context) {
99
123
  // architecture:generate derives from — so the unchanged-check compares like-for-like and can
100
124
  // never fail on a clean, freshly-generated tree. (validate-architecture-unchanged separately
101
125
  // guarantees dependencies.json itself is fresh.)
102
- const depsFile = (0, graph_loader_1.loadBlessedGraph)(workspaceRoot);
103
- if (depsFile === null) {
104
- console.error('āŒ No architecture/dependencies.json — run: nx run architecture:generate');
126
+ const depsFile = loadOrRender(workspaceRoot);
127
+ if (typeof depsFile === 'string') {
128
+ console.error(`\nāŒ Runtime architecture validation failed:\n\n${depsFile}\n`);
105
129
  return { success: false };
106
130
  }
107
131
  const hiddenProjects = new Set();
@@ -109,11 +133,11 @@ async function runExecutor(_options, context) {
109
133
  if (depsFile.projects[name].drawOnGraph === false)
110
134
  hiddenProjects.add(name);
111
135
  }
112
- // apiContracts comes from the SAME loaded file, so the queue/trigger data the derivation sees
113
- // here is byte-identical to what generate saw in memory.
136
+ // The api contracts come from the per-API files dependencies.json links to, which generate
137
+ // wrote from the table it derived from in memory.
114
138
  // A cyclic graph leaves no graph to run the rest of the checks against, and is the one failure
115
139
  // this rule never softens through the report-only window below — see deriveOrRender.
116
- const derived = deriveOrRender(depsFile, hiddenProjects);
140
+ const derived = deriveOrRender(workspaceRoot, depsFile, hiddenProjects);
117
141
  if (typeof derived === 'string') {
118
142
  console.error(`\nāŒ Runtime architecture validation failed:\n\n${derived}\n`);
119
143
  return { success: false };
@@ -1 +1 @@
1
- {"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/validate-runtime-architecture/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;GAmBG;;AAgEH,kDAgBC;AAYD,8BAmEC;AA5JD,0DAAgF;AAChF,yDAA0D;AAE1D,2CAAwC;AAExC,2DAKiC;AAEjC,yF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AE,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;IAEpD,MAAM,UAAU,GAAG,IAAA,kCAAiB,EAAC,MAAM,CAAC,CAAC;IAC7C,IAAI,UAAU,CAAC,IAAI,EAAE,CAAC;QAClB,OAAO,CAAC,GAAG,CAAC,+BAA+B,UAAU,CAAC,MAAM,MAAM,CAAC,CAAC;QACpE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["/**\n * Validate Runtime Architecture Executor (workspace)\n *\n * Workspace-level checks on the runtime microservice graph:\n * 1. Unchanged: the freshly-assembled graph must match the committed\n * architecture/runtime-dependencies.json (run `architecture:generate`).\n * 2. Every role:server project has a node on the graph.\n *\n * CYCLES ARE NOT CHECKED HERE, and there is deliberately no allowlist for them any more. A runtime\n * cycle now fails inside the DERIVATION — `assignLevels` (lib/runtime-graph-levels.ts) throws a\n * RuleFailError naming every chain, because CD deploys in dependency order and a cyclic architecture\n * has no such order. `deriveRuntimeGraphReport` below therefore cannot return a cyclic graph, and the\n * only way past it is to break the cycle, or to declare ONE edge with a `cutLegacyCycle:<target>` nx\n * tag on the CALLING project.\n *\n * On/off + a whole-rule grace window come from webpieces.config.json\n * (rule: runtime-architecture).\n *\n * Usage: nx run architecture:validate-runtime-architecture\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport { RuleFailError, renderRuleFailForHuman } from '@webpieces/rules-config';\nimport { loadBlessedGraph } from '../../lib/graph-loader';\nimport type { DependenciesFile } from '../../lib/graph-loader';\nimport { toError } from '../../toError';\nimport type { EnhancedGraph } from '../../lib/graph-sorter';\nimport {\n deriveRuntimeGraphReport,\n loadRuntimeGraph,\n runtimeGraphFileExists,\n serializeRuntimeGraph,\n} from '../../lib/runtime-graph';\nimport type { RuntimeGraph, RuntimeGraphReport } from '../../lib/runtime-graph';\nimport { printAutoHiddenServers } from '../../lib/runtime-participant-resolver';\nimport { loadRuntimeConfig, runtimeReportOnly, RUNTIME_RULE_NAME } from '../../lib/runtime-config';\n\nexport interface ValidateRuntimeArchitectureOptions {\n // Config comes from webpieces.config.json at runtime.\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\n/**\n * The derived report, or the RENDERED failure when the derivation refused to produce one.\n *\n * `assignLevels` throws a `RuleFailError` on a cyclic graph, and its cures live in that error's\n * `Option[]` — which `Error.message` does NOT carry. This executor is the top-level handler for its\n * nx target, so it renders through the one human renderer here; letting the throw escape `runExecutor`\n * would print the message with every cure silently dropped. Nothing is swallowed: the caller reports\n * the rendered text and fails, and anything that is not a rule verdict is rethrown untouched.\n *\n * A rendered failure ends the run rather than joining `problems`: there is no graph left to run the\n * other checks against, and a cycle is deliberately the one failure this rule does NOT route through\n * its report-only window — an architecture with no deploy order is not a style preference.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, matches checkUnchanged in this file\nfunction deriveOrRender(\n depsFile: DependenciesFile,\n hiddenProjects: Set<string>,\n): RuntimeGraphReport | string {\n // webpieces-disable no-unmanaged-exceptions -- top-level handler for this nx target; it renders, it does not swallow\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return deriveRuntimeGraphReport(\n depsFile.projects, hiddenProjects, depsFile.apiContracts, depsFile.externalSystems);\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof RuleFailError) return renderRuleFailForHuman(error);\n throw error;\n }\n}\n\n/**\n * Every `role:server` project must have a NODE in the runtime graph. A pure set difference against\n * what the derivation produced, and it exists because the derivation once dropped relation-less\n * servers silently: the diagram claimed to be complete while a deployed service was missing from it.\n * Now the only sanctioned way for a server to be absent from the drawing is `drawOnGraph:false`, and\n * anything else that ever removes one fails the build by name instead of disappearing quietly.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, matches checkUnchanged in this file\nexport function checkServersPresent(\n projects: EnhancedGraph,\n hiddenProjects: Set<string>,\n graph: RuntimeGraph,\n): string[] {\n const problems: string[] = [];\n for (const name of Object.keys(projects).sort()) {\n if (projects[name].role !== 'server') continue;\n if (hiddenProjects.has(name)) continue;\n if (graph.services[name] !== undefined) continue;\n problems.push(\n `role:server '${name}' has no node in the runtime graph. Tag it drawOnGraph:false in its ` +\n `project.json if that is intended.`,\n );\n }\n return problems;\n}\n\n/** Returns an unchanged-check message, or null if the committed graph matches. */\nfunction checkUnchanged(workspaceRoot: string, current: RuntimeGraph): string | null {\n if (!runtimeGraphFileExists(workspaceRoot)) {\n return 'No committed architecture/runtime-dependencies.json — run: nx run architecture:generate';\n }\n const saved = loadRuntimeGraph(workspaceRoot);\n if (saved && serializeRuntimeGraph(saved) === serializeRuntimeGraph(current)) return null;\n return 'Runtime graph changed since last commit — run: nx run architecture:generate and commit the result';\n}\n\nexport default async function runExecutor(\n _options: ValidateRuntimeArchitectureOptions,\n context: ExecutorContext,\n): Promise<ExecutorResult> {\n const workspaceRoot = context.root;\n const config = loadRuntimeConfig(workspaceRoot);\n\n if (config.off) {\n console.log(`\\nā­ļø Skipping ${RUNTIME_RULE_NAME} (mode: OFF)\\n`);\n return { success: true };\n }\n\n console.log('\\nšŸ“” Validating runtime microservice architecture\\n');\n // Derive the \"current\" runtime graph from the committed dependencies.json — the SAME source\n // architecture:generate derives from — so the unchanged-check compares like-for-like and can\n // never fail on a clean, freshly-generated tree. (validate-architecture-unchanged separately\n // guarantees dependencies.json itself is fresh.)\n const depsFile = loadBlessedGraph(workspaceRoot);\n if (depsFile === null) {\n console.error('āŒ No architecture/dependencies.json — run: nx run architecture:generate');\n return { success: false };\n }\n const hiddenProjects = new Set<string>();\n for (const name of Object.keys(depsFile.projects)) {\n if (depsFile.projects[name].drawOnGraph === false) hiddenProjects.add(name);\n }\n // apiContracts comes from the SAME loaded file, so the queue/trigger data the derivation sees\n // here is byte-identical to what generate saw in memory.\n // A cyclic graph leaves no graph to run the rest of the checks against, and is the one failure\n // this rule never softens through the report-only window below — see deriveOrRender.\n const derived = deriveOrRender(depsFile, hiddenProjects);\n if (typeof derived === 'string') {\n console.error(`\\nāŒ Runtime architecture validation failed:\\n\\n${derived}\\n`);\n return { success: false };\n }\n const report = derived;\n const graph = report.graph;\n for (const warning of report.warnings) console.warn(`āš ļø ${warning}`);\n printAutoHiddenServers(report.autoHidden);\n\n // A call site naming a service no module answers to FAILS: the contract is served in-repo, so\n // the name is a typo or a stale rename, and the graph only ever hid it by fanning the edge out.\n const problems: string[] = [\n ...report.problems,\n ...checkServersPresent(depsFile.projects, hiddenProjects, graph),\n ];\n const unchanged = checkUnchanged(workspaceRoot, graph);\n if (unchanged) problems.push(unchanged);\n\n for (const u of graph.unresolvedUses) {\n console.log(`āš ļø ${u.service} uses \"${u.api}\" but no in-repo service implements it (external?)`);\n }\n\n if (problems.length === 0) {\n console.log('āœ… Runtime architecture valid (graph unchanged)\\n');\n return { success: true };\n }\n\n console.error('\\nāŒ Runtime architecture validation failed:\\n');\n for (const p of problems) console.error(` - ${p}`);\n\n const reportOnly = runtimeReportOnly(config);\n if (reportOnly.skip) {\n console.log(`ā³ Reported but not failing (${reportOnly.reason}).\\n`);\n return { success: true };\n }\n return { success: false };\n}\n"]}
1
+ {"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../packages/tooling/nx-webpieces-rules/src/executors/validate-runtime-architecture/executor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;GAmBG;;AAyFH,kDAgBC;AAYD,8BAmEC;AArLD,0DAAgF;AAChF,yDAA8E;AAC9E,qEAAgE;AAEhE,2CAAwC;AAExC,2DAKiC;AAEjC,yFAAgF;AAChF,6DAAmG;AAUnG;;;;;;;;;;;;GAYG;AACH,2GAA2G;AAC3G,SAAS,cAAc,CACnB,aAAqB,EACrB,QAA0B,EAC1B,cAA2B;IAE3B,qHAAqH;IACrH,8DAA8D;IAC9D,IAAI,CAAC;QACD,0FAA0F;QAC1F,uFAAuF;QACvF,MAAM,YAAY,GAAG,IAAI,qCAAgB,EAAE,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Ac,EAAE,CAAC;QACnC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,OAAO,UAAU,CAAC,CAAC,GAAG,oDAAoD,CAAC,CAAC;IACrG,CAAC;IAED,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACxB,OAAO,CAAC,GAAG,CAAC,kDAAkD,CAAC,CAAC;QAChE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IAED,OAAO,CAAC,KAAK,CAAC,+CAA+C,CAAC,CAAC;IAC/D,KAAK,MAAM,CAAC,IAAI,QAAQ;QAAE,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;IAEpD,MAAM,UAAU,GAAG,IAAA,kCAAiB,EAAC,MAAM,CAAC,CAAC;IAC7C,IAAI,UAAU,CAAC,IAAI,EAAE,CAAC;QAClB,OAAO,CAAC,GAAG,CAAC,+BAA+B,UAAU,CAAC,MAAM,MAAM,CAAC,CAAC;QACpE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7B,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["/**\n * Validate Runtime Architecture Executor (workspace)\n *\n * Workspace-level checks on the runtime microservice graph:\n * 1. Unchanged: the freshly-assembled graph must match the committed\n * architecture/runtime-dependencies.json (run `architecture:generate`).\n * 2. Every role:server project has a node on the graph.\n *\n * CYCLES ARE NOT CHECKED HERE, and there is deliberately no allowlist for them any more. A runtime\n * cycle now fails inside the DERIVATION — `assignLevels` (lib/runtime-graph-levels.ts) throws a\n * RuleFailError naming every chain, because CD deploys in dependency order and a cyclic architecture\n * has no such order. `deriveRuntimeGraphReport` below therefore cannot return a cyclic graph, and the\n * only way past it is to break the cycle, or to declare ONE edge with a `cutLegacyCycle:<target>` nx\n * tag on the CALLING project.\n *\n * On/off + a whole-rule grace window come from webpieces.config.json\n * (rule: runtime-architecture).\n *\n * Usage: nx run architecture:validate-runtime-architecture\n */\n\nimport type { ExecutorContext } from '@nx/devkit';\nimport { RuleFailError, renderRuleFailForHuman } from '@webpieces/rules-config';\nimport { loadBlessedGraph, DEFAULT_GRAPH_PATH } from '../../lib/graph-loader';\nimport { ApiContractFiles } from '../../lib/api-contract-files';\nimport type { DependenciesFile } from '../../lib/graph-loader';\nimport { toError } from '../../toError';\nimport type { EnhancedGraph } from '../../lib/graph-sorter';\nimport {\n deriveRuntimeGraphReport,\n loadRuntimeGraph,\n runtimeGraphFileExists,\n serializeRuntimeGraph,\n} from '../../lib/runtime-graph';\nimport type { RuntimeGraph, RuntimeGraphReport } from '../../lib/runtime-graph';\nimport { printAutoHiddenServers } from '../../lib/runtime-participant-resolver';\nimport { loadRuntimeConfig, runtimeReportOnly, RUNTIME_RULE_NAME } from '../../lib/runtime-config';\n\nexport interface ValidateRuntimeArchitectureOptions {\n // Config comes from webpieces.config.json at runtime.\n}\n\nexport interface ExecutorResult {\n success: boolean;\n}\n\n/**\n * The derived report, or the RENDERED failure when the derivation refused to produce one.\n *\n * `assignLevels` throws a `RuleFailError` on a cyclic graph, and its cures live in that error's\n * `Option[]` — which `Error.message` does NOT carry. This executor is the top-level handler for its\n * nx target, so it renders through the one human renderer here; letting the throw escape `runExecutor`\n * would print the message with every cure silently dropped. Nothing is swallowed: the caller reports\n * the rendered text and fails, and anything that is not a rule verdict is rethrown untouched.\n *\n * A rendered failure ends the run rather than joining `problems`: there is no graph left to run the\n * other checks against, and a cycle is deliberately the one failure this rule does NOT route through\n * its report-only window — an architecture with no deploy order is not a style preference.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, matches checkUnchanged in this file\nfunction deriveOrRender(\n workspaceRoot: string,\n depsFile: DependenciesFile,\n hiddenProjects: Set<string>,\n): RuntimeGraphReport | string {\n // webpieces-disable no-unmanaged-exceptions -- top-level handler for this nx target; it renders, it does not swallow\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // The queue/trigger data comes from the generated architecture/apis/<Api>.json files that\n // dependencies.json links to — the same files generate wrote from its in-memory table.\n const apiContracts = new ApiContractFiles().load(\n workspaceRoot, DEFAULT_GRAPH_PATH, depsFile.apiContractFiles);\n return deriveRuntimeGraphReport(\n depsFile.projects, hiddenProjects, apiContracts, depsFile.externalSystems);\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof RuleFailError) return renderRuleFailForHuman(error);\n throw error;\n }\n}\n\n/**\n * The committed dependencies.json, or the RENDERED failure when it is absent or cannot be read as the\n * current shape (e.g. it still carries the retired `apiContracts` key). Rendered here for the same\n * reason as deriveOrRender: this executor is the top-level handler for its nx target.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, matches deriveOrRender in this file\nfunction loadOrRender(workspaceRoot: string): DependenciesFile | string {\n // webpieces-disable no-unmanaged-exceptions -- top-level handler for this nx target; it renders, it does not swallow\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n const depsFile = loadBlessedGraph(workspaceRoot);\n return depsFile ?? 'No architecture/dependencies.json — run: nx run architecture:generate';\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof RuleFailError) return renderRuleFailForHuman(error);\n throw error;\n }\n}\n\n/**\n * Every `role:server` project must have a NODE in the runtime graph. A pure set difference against\n * what the derivation produced, and it exists because the derivation once dropped relation-less\n * servers silently: the diagram claimed to be complete while a deployed service was missing from it.\n * Now the only sanctioned way for a server to be absent from the drawing is `drawOnGraph:false`, and\n * anything else that ever removes one fails the build by name instead of disappearing quietly.\n */\n// webpieces-disable no-function-outside-class -- executor step helper, matches checkUnchanged in this file\nexport function checkServersPresent(\n projects: EnhancedGraph,\n hiddenProjects: Set<string>,\n graph: RuntimeGraph,\n): string[] {\n const problems: string[] = [];\n for (const name of Object.keys(projects).sort()) {\n if (projects[name].role !== 'server') continue;\n if (hiddenProjects.has(name)) continue;\n if (graph.services[name] !== undefined) continue;\n problems.push(\n `role:server '${name}' has no node in the runtime graph. Tag it drawOnGraph:false in its ` +\n `project.json if that is intended.`,\n );\n }\n return problems;\n}\n\n/** Returns an unchanged-check message, or null if the committed graph matches. */\nfunction checkUnchanged(workspaceRoot: string, current: RuntimeGraph): string | null {\n if (!runtimeGraphFileExists(workspaceRoot)) {\n return 'No committed architecture/runtime-dependencies.json — run: nx run architecture:generate';\n }\n const saved = loadRuntimeGraph(workspaceRoot);\n if (saved && serializeRuntimeGraph(saved) === serializeRuntimeGraph(current)) return null;\n return 'Runtime graph changed since last commit — run: nx run architecture:generate and commit the result';\n}\n\nexport default async function runExecutor(\n _options: ValidateRuntimeArchitectureOptions,\n context: ExecutorContext,\n): Promise<ExecutorResult> {\n const workspaceRoot = context.root;\n const config = loadRuntimeConfig(workspaceRoot);\n\n if (config.off) {\n console.log(`\\nā­ļø Skipping ${RUNTIME_RULE_NAME} (mode: OFF)\\n`);\n return { success: true };\n }\n\n console.log('\\nšŸ“” Validating runtime microservice architecture\\n');\n // Derive the \"current\" runtime graph from the committed dependencies.json — the SAME source\n // architecture:generate derives from — so the unchanged-check compares like-for-like and can\n // never fail on a clean, freshly-generated tree. (validate-architecture-unchanged separately\n // guarantees dependencies.json itself is fresh.)\n const depsFile = loadOrRender(workspaceRoot);\n if (typeof depsFile === 'string') {\n console.error(`\\nāŒ Runtime architecture validation failed:\\n\\n${depsFile}\\n`);\n return { success: false };\n }\n const hiddenProjects = new Set<string>();\n for (const name of Object.keys(depsFile.projects)) {\n if (depsFile.projects[name].drawOnGraph === false) hiddenProjects.add(name);\n }\n // The api contracts come from the per-API files dependencies.json links to, which generate\n // wrote from the table it derived from in memory.\n // A cyclic graph leaves no graph to run the rest of the checks against, and is the one failure\n // this rule never softens through the report-only window below — see deriveOrRender.\n const derived = deriveOrRender(workspaceRoot, depsFile, hiddenProjects);\n if (typeof derived === 'string') {\n console.error(`\\nāŒ Runtime architecture validation failed:\\n\\n${derived}\\n`);\n return { success: false };\n }\n const report = derived;\n const graph = report.graph;\n for (const warning of report.warnings) console.warn(`āš ļø ${warning}`);\n printAutoHiddenServers(report.autoHidden);\n\n // A call site naming a service no module answers to FAILS: the contract is served in-repo, so\n // the name is a typo or a stale rename, and the graph only ever hid it by fanning the edge out.\n const problems: string[] = [\n ...report.problems,\n ...checkServersPresent(depsFile.projects, hiddenProjects, graph),\n ];\n const unchanged = checkUnchanged(workspaceRoot, graph);\n if (unchanged) problems.push(unchanged);\n\n for (const u of graph.unresolvedUses) {\n console.log(`āš ļø ${u.service} uses \"${u.api}\" but no in-repo service implements it (external?)`);\n }\n\n if (problems.length === 0) {\n console.log('āœ… Runtime architecture valid (graph unchanged)\\n');\n return { success: true };\n }\n\n console.error('\\nāŒ Runtime architecture validation failed:\\n');\n for (const p of problems) console.error(` - ${p}`);\n\n const reportOnly = runtimeReportOnly(config);\n if (reportOnly.skip) {\n console.log(`ā³ Reported but not failing (${reportOnly.reason}).\\n`);\n return { success: true };\n }\n return { success: false };\n}\n"]}
@@ -12,6 +12,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.default = runExecutor;
13
13
  const graph_loader_1 = require("../../lib/graph-loader");
14
14
  const graph_visualizer_1 = require("../../lib/graph-visualizer");
15
+ const rules_config_1 = require("@webpieces/rules-config");
15
16
  const toError_1 = require("../../toError");
16
17
  async function runExecutor(options, context) {
17
18
  const graphPath = options.graphPath;
@@ -45,7 +46,8 @@ async function runExecutor(options, context) {
45
46
  }
46
47
  catch (err) {
47
48
  const error = (0, toError_1.toError)(err);
48
- console.error('āŒ Visualization failed:', error.message);
49
+ const rendered = error instanceof rules_config_1.RuleFailError ? (0, rules_config_1.renderRuleFailForHuman)(error) : error.message;
50
+ console.error('āŒ Visualization failed:', rendered);
49
51
  return { success: false };
50
52
  }
51
53
  }