@rsconcept/domain 3.0.0 → 3.0.1

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 (82) hide show
  1. package/dist/{analyzer-fNhkwO-6.d.ts → analyzer-CzFaWR7w.d.ts} +4 -4
  2. package/dist/{api-Bf0f_uiI.d.ts → api-DgecYHjR.d.ts} +5 -3
  3. package/dist/{arguments-extractor-ngatANBI.d.ts → arguments-extractor-CXWRT5Ou.d.ts} +4 -4
  4. package/dist/{ast-C8sIpKdL.d.ts → ast-D-D6Rq3T.d.ts} +2 -3
  5. package/dist/{ast-annotations-CiIx8qBM.d.ts → ast-annotations-x4PJ_Lhc.d.ts} +4 -4
  6. package/dist/{calculator-DE89LtIM.d.ts → calculator-uPaTV3hc.d.ts} +5 -5
  7. package/dist/cctext/language-api.d.ts +0 -1
  8. package/dist/{diagnostics-ndGYbvgh.js → diagnostics-D1Cp21nP.js} +16 -3
  9. package/dist/{diagnostics-ndGYbvgh.js.map → diagnostics-D1Cp21nP.js.map} +1 -1
  10. package/dist/{diagnostics-DsEhmFh0.d.ts → diagnostics-DKyMf6q-.d.ts} +20 -6
  11. package/dist/{expression-generator-CoucLIkE.d.ts → expression-generator-CADzBw-C.d.ts} +3 -2
  12. package/dist/graph/index.d.ts +1 -0
  13. package/dist/index-CnuO4w8e.d.ts +13 -0
  14. package/dist/index-D5RahF1K.d.ts +2 -0
  15. package/dist/{index-DpiTybDB.d.ts → index-DCO4mxiO.d.ts} +9 -7
  16. package/dist/index-DntDUXW1.d.ts +1 -0
  17. package/dist/index-x0_Y5uPV.d.ts +2 -0
  18. package/dist/index.d.ts +13 -13
  19. package/dist/index.js +1 -1
  20. package/dist/{lezer-tree-iS7LpLBJ.d.ts → lezer-tree-BQZqBT5A.d.ts} +1 -2
  21. package/dist/library/diagnostics.d.ts +1 -1
  22. package/dist/library/diagnostics.js +1 -1
  23. package/dist/library/index.d.ts +2 -3
  24. package/dist/library/index.js +1 -1
  25. package/dist/library/oss-api.d.ts +11 -3
  26. package/dist/library/oss-api.js +45 -4
  27. package/dist/library/oss-api.js.map +1 -1
  28. package/dist/library/oss-layout-api.d.ts +0 -1
  29. package/dist/library/oss.d.ts +21 -16
  30. package/dist/library/oss.js +19 -13
  31. package/dist/library/oss.js.map +1 -1
  32. package/dist/library/rsengine.d.ts +6 -5
  33. package/dist/library/rsengine.js +1 -1
  34. package/dist/library/rsform-api/index.d.ts +1 -1
  35. package/dist/library/rsform-api/index.js +1 -1
  36. package/dist/library/rsform.d.ts +1 -1
  37. package/dist/library/rsmodel-api.d.ts +5 -5
  38. package/dist/library/rsmodel-api.js +1 -1
  39. package/dist/library/rsmodel.d.ts +1 -1
  40. package/dist/library/structure-planner.d.ts +3 -3
  41. package/dist/library/structure-planner.js +1 -1
  42. package/dist/{parser-Bwd8LxJ1.d.ts → parser-DkejtiOR.d.ts} +1 -2
  43. package/dist/parsing/ast.d.ts +1 -1
  44. package/dist/parsing/index.d.ts +3 -2
  45. package/dist/parsing/lezer-tree.d.ts +1 -1
  46. package/dist/rslang/api.d.ts +2 -2
  47. package/dist/rslang/ast-annotations.d.ts +1 -1
  48. package/dist/rslang/eval/calculator.d.ts +1 -1
  49. package/dist/rslang/eval/evaluation-cache.d.ts +3 -3
  50. package/dist/rslang/eval/evaluator.d.ts +3 -3
  51. package/dist/rslang/eval/value-api.d.ts +1 -1
  52. package/dist/rslang/eval/value.d.ts +1 -1
  53. package/dist/rslang/index.d.ts +11 -10
  54. package/dist/rslang/labels.d.ts +3 -3
  55. package/dist/rslang/parser/expression-generator.d.ts +1 -1
  56. package/dist/rslang/parser/normalize.d.ts +2 -1
  57. package/dist/rslang/parser/parser.d.ts +1 -1
  58. package/dist/rslang/parser/parser.terms.d.ts +1 -40
  59. package/dist/rslang/parser/syntax-errors/index.d.ts +3 -3
  60. package/dist/rslang/semantic/analyzer.d.ts +1 -1
  61. package/dist/rslang/semantic/arguments-extractor.d.ts +1 -1
  62. package/dist/rslang/semantic/type-auditor.d.ts +3 -3
  63. package/dist/rslang/semantic/typification-api.d.ts +1 -2
  64. package/dist/rslang/semantic/typification-parser.d.ts +1 -1
  65. package/dist/rslang/semantic/typification.d.ts +1 -1
  66. package/dist/rslang/semantic/value-auditor.d.ts +2 -2
  67. package/dist/rslang/typification-graph.d.ts +1 -1
  68. package/dist/shared/index.d.ts +1 -0
  69. package/dist/{typification-graph-BY_oGT82.d.ts → typification-graph-CSxDt18X.d.ts} +2 -3
  70. package/dist/{typification-9lNu9R4k.d.ts → typification-hWUoWCba.d.ts} +2 -1
  71. package/dist/{typification-parser-Dytsv9CI.d.ts → typification-parser-DFxj4JiQ.d.ts} +2 -3
  72. package/dist/{value-BduA_ZGp.d.ts → value-XpJOVzMP.d.ts} +2 -1
  73. package/dist/{value-api-CXLl_zg0.d.ts → value-api-Dw8UkwCD.d.ts} +3 -4
  74. package/package.json +8 -8
  75. package/src/library/diagnostics.ts +16 -2
  76. package/src/library/oss-api.test.ts +100 -5
  77. package/src/library/oss-api.ts +71 -5
  78. package/src/library/oss.ts +22 -16
  79. package/dist/index-BKZ67WMa.d.ts +0 -1
  80. package/dist/index-BVVgDSdq.d.ts +0 -1
  81. package/dist/index-DmtQKWjk.d.ts +0 -1
  82. package/dist/index-_6s0AX1B.d.ts +0 -1
@@ -1,8 +1,8 @@
1
- import { t as AstNode } from "./ast-C8sIpKdL.js";
2
- import { f as ExpressionType, g as TypeClass } from "./typification-9lNu9R4k.js";
1
+ import { t as AstNode } from "./ast-D-D6Rq3T.js";
2
+ import "./index-D5RahF1K.js";
3
+ import { f as ExpressionType, g as TypeClass } from "./typification-hWUoWCba.js";
3
4
  import { i as RSErrorDescription } from "./error-B0EkIx4K.js";
4
5
  import { t as ValueClass } from "./value-class-CNI-lqXJ.js";
5
-
6
6
  //#region src/rslang/semantic/analyzer.d.ts
7
7
  interface AnalysisBase {
8
8
  success: boolean;
@@ -35,4 +35,4 @@ declare class RSLangAnalyzer {
35
35
  }
36
36
  //#endregion
37
37
  export { RSLangAnalyzer as a, AnalysisOptions as i, AnalysisFast as n, AnalysisFull as r, AnalysisBase as t };
38
- //# sourceMappingURL=analyzer-fNhkwO-6.d.ts.map
38
+ //# sourceMappingURL=analyzer-CzFaWR7w.d.ts.map
@@ -1,5 +1,7 @@
1
- import { t as AstNode } from "./ast-C8sIpKdL.js";
2
- import { n as ArgumentsType } from "./arguments-extractor-ngatANBI.js";
1
+ import { t as AstNode } from "./ast-D-D6Rq3T.js";
2
+ import "./index-D5RahF1K.js";
3
+ import { n as ArgumentsType } from "./arguments-extractor-CXWRT5Ou.js";
4
+ import "./expression-generator-CADzBw-C.js";
3
5
  //#region src/rslang/api.d.ts
4
6
  /** Represents alias mapping. */
5
7
  type AliasMapping = Record<string, string>;
@@ -54,4 +56,4 @@ declare function applyAliasMapping(target: string, mapping: AliasMapping): strin
54
56
  declare function applyTypificationMapping(target: string, mapping: AliasMapping): string;
55
57
  //#endregion
56
58
  export { extractGlobals as a, isSimpleExpression as c, substituteLocalAliases as d, substituteTemplateArgs as f, extractArguments as i, parseRSLangExpression as l, applyAliasMapping as n, isGlobalAlias as o, applyTypificationMapping as r, isSetTypification as s, AliasMapping as t, splitTemplateDefinition as u };
57
- //# sourceMappingURL=api-Bf0f_uiI.d.ts.map
59
+ //# sourceMappingURL=api-DgecYHjR.d.ts.map
@@ -1,6 +1,6 @@
1
- import { t as AstNode } from "./ast-C8sIpKdL.js";
2
- import { f as ExpressionType } from "./typification-9lNu9R4k.js";
3
-
1
+ import { t as AstNode } from "./ast-D-D6Rq3T.js";
2
+ import "./index-D5RahF1K.js";
3
+ import { f as ExpressionType } from "./typification-hWUoWCba.js";
4
4
  //#region src/rslang/semantic/arguments-extractor.d.ts
5
5
  /** Represents function argument definition. */
6
6
  interface ArgumentsType {
@@ -35,4 +35,4 @@ declare class ArgumentsExtractor {
35
35
  }
36
36
  //#endregion
37
37
  export { ArgumentsType as n, ArgumentsExtractor as t };
38
- //# sourceMappingURL=arguments-extractor-ngatANBI.d.ts.map
38
+ //# sourceMappingURL=arguments-extractor-CXWRT5Ou.d.ts.map
@@ -1,5 +1,4 @@
1
- import { n as TreeCursor } from "./lezer-tree-iS7LpLBJ.js";
2
-
1
+ import { n as TreeCursor } from "./lezer-tree-BQZqBT5A.js";
3
2
  //#region src/parsing/ast.d.ts
4
3
  declare const TOKEN_ERROR = 0;
5
4
  /** Represents AST node data. */
@@ -48,4 +47,4 @@ declare function getNodeText(node: AstNode): string;
48
47
  declare function getNodeIndices(node: AstNode): number[];
49
48
  //#endregion
50
49
  export { TOKEN_ERROR as a, flattenAst as c, printAst as d, visitAstDFS as f, FlatAstNode as i, getNodeIndices as l, AstNodeBase as n, buildTree as o, FlatAST as r, findByUid as s, AstNode as t, getNodeText as u };
51
- //# sourceMappingURL=ast-C8sIpKdL.d.ts.map
50
+ //# sourceMappingURL=ast-D-D6Rq3T.d.ts.map
@@ -1,7 +1,7 @@
1
- import { t as AstNode } from "./ast-C8sIpKdL.js";
2
- import { f as ExpressionType } from "./typification-9lNu9R4k.js";
1
+ import { t as AstNode } from "./ast-D-D6Rq3T.js";
2
+ import "./index-D5RahF1K.js";
3
+ import { f as ExpressionType } from "./typification-hWUoWCba.js";
3
4
  import { a as RSErrorInfo, r as RSErrorCode } from "./error-B0EkIx4K.js";
4
-
5
5
  //#region src/rslang/ast-annotations.d.ts
6
6
  /** Appends {@link ExpressionType} onto the node's `annotation.rsType`. */
7
7
  declare function annotateType(node: AstNode, type: ExpressionType): void;
@@ -13,4 +13,4 @@ declare function annotateError(node: AstNode, code: RSErrorCode, params?: readon
13
13
  declare function readErrorAnnotation(node: AstNode): RSErrorInfo | null;
14
14
  //#endregion
15
15
  export { readTypeAnnotation as i, annotateType as n, readErrorAnnotation as r, annotateError as t };
16
- //# sourceMappingURL=ast-annotations-CiIx8qBM.d.ts.map
16
+ //# sourceMappingURL=ast-annotations-x4PJ_Lhc.d.ts.map
@@ -1,8 +1,8 @@
1
- import { t as AstNode } from "./ast-C8sIpKdL.js";
2
- import { f as ExpressionType } from "./typification-9lNu9R4k.js";
1
+ import { t as AstNode } from "./ast-D-D6Rq3T.js";
2
+ import "./index-D5RahF1K.js";
3
+ import { f as ExpressionType } from "./typification-hWUoWCba.js";
3
4
  import { i as RSErrorDescription } from "./error-B0EkIx4K.js";
4
- import { l as Value } from "./value-BduA_ZGp.js";
5
-
5
+ import { l as Value } from "./value-XpJOVzMP.js";
6
6
  //#region src/rslang/eval/calculator.d.ts
7
7
  /** Result of calculator evaluation. */
8
8
  interface CalculatorResult {
@@ -36,4 +36,4 @@ declare class RSCalculator {
36
36
  }
37
37
  //#endregion
38
38
  export { CalculatorResult as n, RSCalculator as r, CalculatorEvaluateOptions as t };
39
- //# sourceMappingURL=calculator-DE89LtIM.d.ts.map
39
+ //# sourceMappingURL=calculator-uPaTV3hc.d.ts.map
@@ -1,5 +1,4 @@
1
1
  import { EntityReference, Grammeme, IReference, SyntacticReference, TermContext, WordForm } from "./language.js";
2
-
3
2
  //#region src/cctext/language-api.d.ts
4
3
  /** Represents generated lexeme forms. */
5
4
  interface Lexeme {
@@ -1090,7 +1090,7 @@ const DiagnosticKind = {
1090
1090
  SCHEMA: "schema",
1091
1091
  MODEL: "model"
1092
1092
  };
1093
- /** Schema and model diagnostic codes (same numeric format as {@link RSErrorCode}). */
1093
+ /** Schema, model, and substitution-table diagnostic codes (same numeric format as {@link RSErrorCode}). */
1094
1094
  const RSDiagnosticCode = {
1095
1095
  schemaHomonym: 35073,
1096
1096
  schemaFormalDuplicate: 35074,
@@ -1101,7 +1101,20 @@ const RSDiagnosticCode = {
1101
1101
  modelEmpty: 35088,
1102
1102
  modelAxiomFalse: 35089,
1103
1103
  modelInvalidData: 35090,
1104
- modelEvalFail: 35091
1104
+ modelEvalFail: 35091,
1105
+ substitutionInvalidIDs: 35104,
1106
+ substitutionIncorrectCst: 35105,
1107
+ substitutionInvalidClasses: 35106,
1108
+ substitutionInvalidBasic: 35107,
1109
+ substitutionInvalidConstant: 35108,
1110
+ substitutionTypificationCycle: 35109,
1111
+ substitutionBaseNotSet: 35110,
1112
+ substitutionUnequalTypification: 35111,
1113
+ /** Non-blocking warning: formal definitions differ after mapping. */
1114
+ substitutionUnequalExpressions: 10536,
1115
+ substitutionUnequalArgsCount: 35113,
1116
+ substitutionUnequalArgs: 35114,
1117
+ substitutionInvalidNominal: 35115
1105
1118
  };
1106
1119
  /** Whether an item has a schema/model diagnostic with the given code. */
1107
1120
  function hasCstDiagnostic(cst, code) {
@@ -1252,4 +1265,4 @@ function modelStatusToCode(status, cstType) {
1252
1265
  //#endregion
1253
1266
  export { isFunctional as $, normalizeExpression as A, buildSequentialAliasMapping as B, isSchemaIssue as C, inferStatus as D, applyFilterCategory as E, refineAnalysisForDependencyCycles as F, validateNewAlias as G, maxAliasIndex as H, addAliasReference as I, getCstTypePrefix as J, canHaveManualTypification as K, allocateImportAliases as L, importAttributions as M, remapAttributionsUnderSubstitution as N, inferTemplate as O, getAnalysisFor as P, isBasicConcept as Q, applyMappingToConstituents as R, calculateSchemaStats as S, restoreConstituentOrder as T, removeAliasReference as U, generateAlias as V, validateAliasFormat as W, inferClass as X, guessCstType as Y, isBaseSet as Z, applyConstituentSubstitutions as _, formatDependencyCycle as a, getStructureName as b, insertItemAfter as c, inlineSynthesis as d, isLogical as et, sortItemsForInlineSynthesis as f, resolveConstituentTextChange as g, resolveAllConstituentTexts as h, detectDependencyCycleDiagnostics as i, filterAttributions as j, inferTemplatedType as k, moveIdsInOrder as l, buildTermReferenceGraph as m, RSDiagnosticCode as n, typeClassForCstType as nt, hasCstDiagnostic as o, buildDefinitionReferenceGraph as p, canProduceStructure as q, assignSchemaDiagnostics as r, modelStatusCstDiagnostic as s, DiagnosticKind as t, isTemplateCst as tt, reorderItemsByIds as u, remapSubstitutionsAfterImport as v, buildFormalDependencyGraph as w, inferNewSpawnPosition as x, findCstByStructure as y, argumentValuesToMapping as z };
1254
1267
 
1255
- //# sourceMappingURL=diagnostics-ndGYbvgh.js.map
1268
+ //# sourceMappingURL=diagnostics-D1Cp21nP.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"diagnostics-ndGYbvgh.js","names":[],"sources":["../src/library/rsform-api/cst-type.ts","../src/library/rsform-api/alias.ts","../src/library/rsform-api/analysis.ts","../src/library/rsform-api/attribution.ts","../src/library/rsform-api/expression.ts","../src/library/rsform-api/semantic-relations.ts","../src/library/rsform-api/formal-graph.ts","../src/library/rsform-api/stats.ts","../src/library/rsform-api/structure.ts","../src/library/rsform-api/substitution.ts","../src/library/rsform-api/text-resolution.ts","../src/library/rsform-api/synthesis.ts","../src/library/rsform-api/transforms.ts","../src/library/diagnostics.ts"],"sourcesContent":["/**\n * CstType classification, prefixes, and capability predicates.\n */\n\nimport { TypeClass, TypeID, type Typification } from '../../rslang';\nimport { type EchelonFunctional, isTypification } from '../../rslang/semantic/typification';\nimport { CstClass, CstType } from '../rsform';\n\nimport { type StructureCapableFields } from './types';\n\n/** Record of {@link CstType} prefixes. */\nconst CST_TYPE_PREFIX: Record<CstType, string> = {\n [CstType.NOMINAL]: 'N',\n [CstType.BASE]: 'X',\n [CstType.CONSTANT]: 'C',\n [CstType.STRUCTURED]: 'S',\n [CstType.AXIOM]: 'A',\n [CstType.TERM]: 'D',\n [CstType.FUNCTION]: 'F',\n [CstType.PREDICATE]: 'P',\n [CstType.STATEMENT]: 'T'\n};\n\n/** Record of {@link CstType} to {@link CstClass} mapping. */\nconst CST_TYPE_TO_CLASS: Record<CstType, CstClass> = {\n [CstType.NOMINAL]: CstClass.NOMINAL,\n [CstType.BASE]: CstClass.BASIC,\n [CstType.CONSTANT]: CstClass.BASIC,\n [CstType.STRUCTURED]: CstClass.BASIC,\n [CstType.TERM]: CstClass.DERIVED,\n [CstType.FUNCTION]: CstClass.DERIVED,\n [CstType.AXIOM]: CstClass.STATEMENT,\n [CstType.PREDICATE]: CstClass.DERIVED,\n [CstType.STATEMENT]: CstClass.STATEMENT\n};\n\n/** Prefix for alias indicating {@link CstType}. */\nexport function getCstTypePrefix(type: CstType): string {\n return CST_TYPE_PREFIX[type];\n}\n\n/** Guess {@link CstType} from user input hint. */\nexport function guessCstType(hint: string): CstType | null {\n if (hint.length !== 1) {\n return null;\n }\n for (const [type, prefix] of Object.entries(CST_TYPE_PREFIX)) {\n if (hint === prefix) {\n return type as CstType;\n }\n }\n return null;\n}\n\n/** Infers the {@link CstClass} based on the provided {@link CstType} and template status. */\nexport function inferClass(type: CstType, isTemplate: boolean = false): CstClass {\n if (isTemplate) {\n return CstClass.TEMPLATE;\n }\n return CST_TYPE_TO_CLASS[type];\n}\n\n/** Check if item type is a template or a category. */\nexport function isTemplateCst(cst: { cst_type: CstType }): boolean {\n return cst.cst_type === CstType.FUNCTION || cst.cst_type === CstType.PREDICATE || cst.cst_type === CstType.STATEMENT;\n}\n\n/** Evaluate if {@link CstType} is basic concept. */\nexport function isBasicConcept(type: CstType): boolean {\n switch (type) {\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.AXIOM:\n return true;\n\n case CstType.TERM:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n case CstType.STATEMENT:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} is base set or constant set. */\nexport function isBaseSet(type: CstType): boolean {\n switch (type) {\n case CstType.BASE:\n case CstType.CONSTANT:\n return true;\n\n case CstType.NOMINAL:\n case CstType.STRUCTURED:\n case CstType.AXIOM:\n case CstType.TERM:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n case CstType.STATEMENT:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} is a function. */\nexport function isFunctional(type: CstType): boolean {\n switch (type) {\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return true;\n\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.AXIOM:\n case CstType.TERM:\n case CstType.STATEMENT:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} is logical. */\nexport function isLogical(type: CstType): boolean {\n switch (type) {\n case CstType.AXIOM:\n case CstType.STATEMENT:\n return true;\n\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.TERM:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} can have manual typification. */\nexport function canHaveManualTypification(type: CstType): boolean {\n switch (type) {\n case CstType.STRUCTURED:\n case CstType.TERM:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return true;\n\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.AXIOM:\n case CstType.STATEMENT:\n return false;\n }\n}\n\n/** Checks whether a constituenta type supports formal definitions. */\nexport function canHaveFormalDefinition(cstType: CstType): boolean {\n return cstType !== CstType.BASE && cstType !== CstType.CONSTANT;\n}\n\n/** Returns expected {@link TypeClass} of formal definition for {@link CstType}. */\nexport function typeClassForCstType(cstType: CstType): TypeClass {\n switch (cstType) {\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.TERM:\n return TypeClass.typification;\n case CstType.FUNCTION:\n return TypeClass.function;\n case CstType.PREDICATE:\n return TypeClass.predicate;\n case CstType.AXIOM:\n case CstType.STATEMENT:\n return TypeClass.logic;\n }\n}\n\n/** Evaluate if an item can be used to produce structure. */\nexport function canProduceStructure(cst: StructureCapableFields): boolean {\n switch (cst.cst_type) {\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.AXIOM:\n case CstType.STATEMENT:\n case CstType.PREDICATE:\n return false;\n }\n if (!cst.effectiveType) {\n return false;\n }\n if (cst.cst_type === CstType.FUNCTION) {\n const result = (cst.effectiveType as EchelonFunctional).result;\n return typeCanProduceStructure(result);\n }\n if (!isTypification(cst.effectiveType)) {\n return false;\n }\n return typeCanProduceStructure(cst.effectiveType as Typification);\n}\n\nfunction typeCanProduceStructure(type: Typification): boolean {\n if (type.typeID === TypeID.basic || type.typeID === TypeID.integer || type.typeID === TypeID.anyTypification) {\n return false;\n } else if (type.typeID === TypeID.tuple) {\n return true;\n } else {\n return (\n type.base.typeID !== TypeID.basic &&\n type.base.typeID !== TypeID.integer &&\n type.base.typeID !== TypeID.anyTypification\n );\n }\n}\n","/**\n * Alias generation, validation, and remapping.\n */\n\nimport { applyEntityReferenceMapping } from '../../cctext/language-api';\nimport { type AliasMapping, applyAliasMapping, applyTypificationMapping } from '../../rslang/api';\nimport { type ArgumentValue, CstType, type RSForm } from '../rsform';\n\nimport { getCstTypePrefix } from './cst-type';\nimport { type AliasTypedFields } from './types';\n\n/** Fields updated in place by alias mapping. */\nexport interface MappableFields {\n alias: string;\n definition_formal: string;\n typification_manual: string;\n term_raw: string;\n definition_raw: string;\n}\n\n/** Build alias mapping from template argument bindings. */\nexport function argumentValuesToMapping(args: ArgumentValue[]): AliasMapping {\n const mapping: AliasMapping = {};\n for (const arg of args) {\n if (arg.value) {\n mapping[arg.alias] = arg.value;\n }\n }\n return mapping;\n}\n\n/** Validate alias format for a given {@link CstType} (prefix + digits, min length 2). */\nexport function validateAliasFormat(alias: string, type: CstType): boolean {\n if (alias.length < 2) {\n return false;\n }\n const prefix = getCstTypePrefix(type);\n if (!alias.startsWith(prefix)) {\n return false;\n }\n if (!/^\\d+$/.exec(alias.substring(prefix.length))) {\n return false;\n }\n return true;\n}\n\n/** Validate new alias against {@link CstType} and {@link RSForm}. */\nexport function validateNewAlias(alias: string, type: CstType, schema: RSForm): boolean {\n if (!validateAliasFormat(alias, type)) {\n return false;\n }\n if (schema.cstByAlias.has(alias)) {\n return false;\n }\n return true;\n}\n\n/** Generate alias for new {@link Constituenta} of a given {@link CstType} for current {@link RSForm}. */\nexport function generateAlias(type: CstType, schema: RSForm, takenAliases: string[] = []): string {\n const prefix = getCstTypePrefix(type);\n let index = schema.items.reduce((prev, cst) => {\n if (cst.cst_type !== type) {\n return prev;\n }\n const next = Number(cst.alias.substring(prefix.length)) + 1;\n return Math.max(prev, next);\n }, 1);\n let alias = `${prefix}${index}`;\n while (takenAliases.includes(alias)) {\n index = index + 1;\n alias = `${prefix}${index}`;\n }\n return alias;\n}\n\n/**\n * Remap formal expressions and terminological entity references in constituent fields.\n * Mutates each element of `items` in place; pass owned or cloned data only.\n */\nexport function applyMappingToConstituents<T extends MappableFields>(\n items: T[],\n mapping: AliasMapping,\n changeAliases: boolean\n): void {\n for (const cst of items) {\n if (changeAliases && cst.alias in mapping) {\n cst.alias = mapping[cst.alias];\n }\n cst.definition_formal = applyAliasMapping(cst.definition_formal, mapping);\n cst.typification_manual = applyTypificationMapping(cst.typification_manual, mapping);\n cst.term_raw = applyEntityReferenceMapping(cst.term_raw, mapping);\n cst.definition_raw = applyEntityReferenceMapping(cst.definition_raw, mapping);\n }\n}\n\n/** Highest numeric alias suffix for {@link type} among {@link items} (0 when none). */\nexport function maxAliasIndex(items: readonly AliasTypedFields[], type: CstType): number {\n const prefix = getCstTypePrefix(type);\n return items.reduce((max, cst) => {\n if (cst.cst_type !== type) {\n return max;\n }\n const index = Number(cst.alias.slice(prefix.length));\n return Number.isFinite(index) ? Math.max(max, index) : max;\n }, 0);\n}\n\n/**\n * Build alias → new-alias mapping that renumbers each type sequentially in list order.\n * Matches backend {@code RSFormCached.reset_aliases}.\n */\nexport function buildSequentialAliasMapping(items: readonly AliasTypedFields[]): AliasMapping {\n const counts: Record<string, number> = {};\n for (const value of Object.values(CstType)) {\n counts[value] = 1;\n }\n const mapping: AliasMapping = {};\n for (const cst of items) {\n const alias = `${getCstTypePrefix(cst.cst_type)}${counts[cst.cst_type]}`;\n counts[cst.cst_type] += 1;\n if (cst.alias !== alias) {\n mapping[cst.alias] = alias;\n }\n }\n return mapping;\n}\n\n/**\n * Allocate fresh aliases for {@link source} constituents being imported into a non-empty receiver.\n * Returns an empty mapping when the receiver has no items (aliases kept as-is).\n */\nexport function allocateImportAliases(\n receiver: readonly AliasTypedFields[],\n source: readonly AliasTypedFields[]\n): AliasMapping {\n if (receiver.length === 0) {\n return {};\n }\n const counts: Record<string, number> = {};\n for (const value of Object.values(CstType)) {\n counts[value] = maxAliasIndex(receiver, value);\n }\n const mapping: AliasMapping = {};\n for (const cst of source) {\n counts[cst.cst_type] += 1;\n mapping[cst.alias] = `${getCstTypePrefix(cst.cst_type)}${counts[cst.cst_type]}`;\n }\n return mapping;\n}\n\n/** Remove alias from expression. */\nexport function removeAliasReference(expression: string, alias: string): string {\n const escaped = alias.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return expression.replaceAll(new RegExp(`\\\\b${escaped}\\\\b`, 'g'), '').trim();\n}\n\n/** Add alias to expression. */\nexport function addAliasReference(expression: string, alias: string): string {\n return expression + ' ' + alias;\n}\n","/**\n * Formal expression analysis against an RSForm schema.\n */\n\nimport { type Graph } from '../../graph';\nimport { type AnalysisFull, RSErrorCode, ValueClass } from '../../rslang';\nimport { extractGlobals } from '../../rslang/api';\nimport { basic, bool, constant } from '../../rslang/semantic/typification';\nimport { formatDependencyCycle, RSDiagnosticCode } from '../diagnostics';\nimport { CstType, type RSForm } from '../rsform';\n\nimport { canHaveFormalDefinition, typeClassForCstType } from './cst-type';\n\nexport function getAnalysisFor(expression: string, cstType: CstType, schema: RSForm, alias?: string): AnalysisFull {\n if (!canHaveFormalDefinition(cstType)) {\n if (expression.trim().length === 0) {\n const fallbackAlias = alias && alias.length > 0 ? alias : 'X0';\n const type = cstType === CstType.BASE ? bool(basic(fallbackAlias)) : bool(constant(fallbackAlias));\n return {\n success: true,\n type,\n valueClass: ValueClass.VALUE,\n errors: [],\n ast: null\n };\n }\n return {\n success: false,\n type: null,\n valueClass: null,\n errors: [\n {\n code: RSErrorCode.definitionNotAllowed,\n from: 0,\n to: Math.max(expression.length, 1),\n params: [cstType, alias ?? '']\n }\n ],\n ast: null\n };\n }\n const analysis = schema.analyzer.checkFull(expression, {\n expected: typeClassForCstType(cstType),\n isDomain: cstType === CstType.STRUCTURED\n });\n return refineAnalysisForDependencyCycles(analysis, expression, schema, alias);\n}\n\n/**\n * When an untyped / bare F·P reference names a constituent on a definition cycle with the\n * current expression, replace that error with {@link RSDiagnosticCode.schemaDependencyCycle}.\n *\n * Covers both semantic `globalNotTyped` (e.g. `F3[σ]`) and parser `globalFuncWithoutArgs`\n * (bare `P1` / `F1` treated as a call without arguments).\n *\n * Uses a draft dependency graph: incoming edges of the edited constituent are taken from\n * `expression`, so Check works before Save.\n */\nexport function refineAnalysisForDependencyCycles(\n analysis: AnalysisFull,\n expression: string,\n schema: RSForm,\n alias?: string\n): AnalysisFull {\n if (analysis.errors.length === 0 || !schema.graph) {\n return analysis;\n }\n\n const currentId = alias ? schema.cstByAlias.get(alias)?.id : undefined;\n const expressionGlobals = extractGlobals(expression);\n const draftGraph =\n currentId !== undefined ? buildDraftDependencyGraph(schema, currentId, expressionGlobals) : schema.graph;\n\n let changed = false;\n const errors = analysis.errors.map(error => {\n if (error.code !== RSErrorCode.globalNotTyped && error.code !== RSErrorCode.globalFuncWithoutArgs) {\n return error;\n }\n const missingAlias = error.params?.[0];\n if (!missingAlias) {\n return error;\n }\n const missing = schema.cstByAlias.get(missingAlias);\n if (!missing) {\n return error;\n }\n const cycleText = resolveDependencyCycleText(schema, draftGraph, currentId, missing.id);\n if (!cycleText) {\n return error;\n }\n changed = true;\n return {\n ...error,\n code: RSErrorCode.schemaDependencyCycle,\n params: [cycleText]\n };\n });\n return changed ? { ...analysis, errors } : analysis;\n}\n\n/**\n * Clone the schema graph and replace dependencies of `currentId` with globals from the\n * expression under check (unsaved draft).\n */\nfunction buildDraftDependencyGraph(schema: RSForm, currentId: number, expressionGlobals: ReadonlySet<string>): Graph {\n const graph = schema.graph.clone();\n const node = graph.at(currentId);\n if (node) {\n for (const parentId of [...node.inputs]) {\n graph.removeEdge(parentId, currentId);\n }\n } else {\n graph.addNode(currentId);\n }\n for (const globalAlias of expressionGlobals) {\n const source = schema.cstByAlias.get(globalAlias);\n if (source) {\n graph.addEdge(source.id, currentId);\n }\n }\n return graph;\n}\n\n/**\n * Resolve formatted cycle text for an untyped global reference in analysis.\n *\n * Uses `graph` (often a draft graph built from the expression under check). When\n * `currentId` is omitted, falls back to schema diagnostics on `missingId`.\n *\n * @returns Closed alias path such as `F3 → P1 → F3`, or `null` when no shared cycle exists.\n */\nfunction resolveDependencyCycleText(\n schema: RSForm,\n graph: Graph,\n currentId: number | undefined,\n missingId: number\n): string | null {\n for (const cycle of graph.findCycles()) {\n const members = new Set(cycle);\n if (!members.has(missingId)) {\n continue;\n }\n if (currentId !== undefined && !members.has(currentId)) {\n continue;\n }\n return formatDependencyCycle(cycle.map(id => schema.cstByID.get(id)?.alias ?? String(id)));\n }\n\n if (currentId === undefined) {\n const cycleDiag = schema.cstByID\n .get(missingId)\n ?.diagnostics.find(item => item.code === RSDiagnosticCode.schemaDependencyCycle);\n return cycleDiag?.params?.[0] ?? null;\n }\n\n return null;\n}\n","/**\n * Attribution remapping helpers for substitution and schema embedding.\n */\n\nimport { type Attribution } from '../rsform';\n\nfunction attributionKey(attr: Attribution): string {\n return `${attr.container}:${attr.attribute}`;\n}\n\n/**\n * Remap attributions when constituents are substituted (original → replacement).\n * Drops self-loops and duplicates. Matches sandbox / backend substitute attribution rewrite.\n */\nexport function remapAttributionsUnderSubstitution(\n attributions: readonly Attribution[],\n origToSub: ReadonlyMap<number, number>\n): Attribution[] {\n const result: Attribution[] = [];\n const seen = new Set<string>();\n\n for (const attr of attributions) {\n if (!origToSub.has(attr.container) && !origToSub.has(attr.attribute)) {\n const key = attributionKey(attr);\n if (!seen.has(key)) {\n seen.add(key);\n result.push({ ...attr });\n }\n continue;\n }\n\n const container = origToSub.get(attr.container) ?? attr.container;\n const attribute = origToSub.get(attr.attribute) ?? attr.attribute;\n if (container === attribute) {\n continue;\n }\n const key = `${container}:${attribute}`;\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n result.push({ container, attribute });\n }\n\n return result;\n}\n\n/**\n * Copy attributions whose both endpoints are in {@link sourceIdSet}, remapping ids via {@link idMap}.\n * Appends onto a clone of {@link existing} with dedupe. Used by schema embedding / insert.\n */\nexport function importAttributions(\n sourceAttributions: readonly Attribution[],\n sourceIdSet: ReadonlySet<number>,\n idMap: Readonly<Record<number, number>>,\n existing: readonly Attribution[] = []\n): Attribution[] {\n const result = existing.map(attr => ({ ...attr }));\n const seen = new Set(result.map(attributionKey));\n\n for (const attr of sourceAttributions) {\n if (!sourceIdSet.has(attr.container) || !sourceIdSet.has(attr.attribute)) {\n continue;\n }\n const container = idMap[attr.container];\n const attribute = idMap[attr.attribute];\n if (container === undefined || attribute === undefined || container === attribute) {\n continue;\n }\n const key = `${container}:${attribute}`;\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n result.push({ container, attribute });\n }\n\n return result;\n}\n\n/** Drop attributions that reference any id in {@link deletedIds}. */\nexport function filterAttributions(\n attributions: readonly Attribution[],\n deletedIds: ReadonlySet<number>\n): Attribution[] {\n return attributions.filter(attr => !deletedIds.has(attr.container) && !deletedIds.has(attr.attribute));\n}\n","/**\n * Formal expression helpers: normalization, templates, status.\n */\n\nimport { type AstNode } from '../../parsing';\nimport { ValueClass } from '../../rslang';\nimport { generateExpressionFromAst, parseRSLangExpression } from '../../rslang/api';\nimport { type ArgumentValue, CstStatus, CstType } from '../rsform';\n\nimport { isBasicConcept } from './cst-type';\n\n/** Infers the status of an expression based on parsing and value information. */\nexport function inferStatus(parse: boolean, value?: ValueClass | null): CstStatus {\n if (!parse) {\n return CstStatus.INCORRECT;\n }\n if (value === null) {\n return CstStatus.INCALCULABLE;\n }\n if (value === ValueClass.PROPERTY) {\n return CstStatus.PROPERTY;\n }\n return CstStatus.VERIFIED;\n}\n\n/** Infers type of constituent for a given template and arguments. */\nexport function inferTemplatedType(templateType: CstType, args: ArgumentValue[]): CstType {\n if (args.length === 0 || args.some(arg => !arg.value)) {\n return templateType;\n } else if (templateType === CstType.PREDICATE) {\n return CstType.AXIOM;\n } else {\n return CstType.TERM;\n }\n}\n\n/**\n * Normalize a RSLang expression for duplicate comparison.\n *\n * Returns `null` for basic concepts without formal definitions. Pass a pre-parsed `ast`\n * when the expression was already analyzed to avoid re-parsing.\n */\nexport function normalizeExpression(expression: string, cst_type: CstType, ast?: AstNode | null): string | null {\n if (isBasicConcept(cst_type) && cst_type !== CstType.AXIOM) {\n return null;\n }\n const parsed = ast ?? parseRSLangExpression(expression);\n let normalized = '';\n if (parsed && !parsed.hasError) {\n normalized = generateExpressionFromAst(parsed, { normalize: true });\n } else {\n normalized = expression;\n }\n normalized = normalized.replace(/\\s+/g, '');\n return normalized === '' ? null : normalized;\n}\n\n/** Checks if given expression is a template. */\nexport function inferTemplate(expression: string): boolean {\n const match = expression.match(/R\\d+/g);\n return (match && match?.length > 0) ?? false;\n}\n\n/** Apply filter based on start item type within an ordered list. */\nexport function applyFilterCategory<T extends { cst_type: CstType }>(start: T, items: readonly T[]): T[] {\n const startIndex = items.indexOf(start);\n if (startIndex === -1) {\n return [];\n }\n const nextCategoryIndex = items.findIndex((cst, index) => index > startIndex && cst.cst_type === CstType.STATEMENT);\n\n return items.filter((_, index) => index >= startIndex && (nextCategoryIndex === -1 || index < nextCategoryIndex));\n}\n","/**\n * Semantic parent/children used when restoring constituent order.\n */\n\nimport { type Graph } from '../../graph';\nimport { extractGlobals, isSimpleExpression, splitTemplateDefinition } from '../../rslang/api';\nimport { CstType } from '../rsform';\n\nimport { isBaseSet, isFunctional } from './cst-type';\nimport { inferTemplate } from './expression';\nimport { type FormalOrderFields, type SemanticRelations } from './types';\n\n/**\n * Infer semantic parent/children used for clustering during restore order.\n * Port of backend {@code SemanticInfo}.\n */\nexport function computeSemanticRelations(items: readonly FormalOrderFields[], graph: Graph<number>): SemanticRelations {\n const byId = new Map(items.map(cst => [cst.id, cst]));\n const byAlias = new Map(items.map(cst => [cst.alias, cst]));\n const isTemplate = new Map<number, boolean>();\n const isSimple = new Map<number, boolean>();\n const parentOf = new Map<number, number>();\n const childrenOf = new Map<number, number[]>();\n\n for (const cst of items) {\n parentOf.set(cst.id, cst.id);\n childrenOf.set(cst.id, []);\n }\n\n function needCheckHead(sources: Set<number>, head: string): boolean {\n if (sources.size === 0) {\n return true;\n }\n if (sources.size !== 1) {\n return false;\n }\n const base = byId.get([...sources][0])!;\n return !isFunctional(base.cst_type) || splitTemplateDefinition(base.definition_formal).head !== head;\n }\n\n function extractSources(target: FormalOrderFields): Set<number> {\n const sources = new Set<number>();\n if (!isFunctional(target.cst_type)) {\n for (const parentId of graph.at(target.id)?.inputs ?? []) {\n if (!(isTemplate.get(parentId) && isSimple.get(parentId))) {\n sources.add(parentOf.get(parentId) ?? parentId);\n }\n }\n return sources;\n }\n\n const expression = splitTemplateDefinition(target.definition_formal);\n for (const alias of extractGlobals(expression.body)) {\n const parent = byAlias.get(alias);\n if (!parent) {\n continue;\n }\n if (!(isTemplate.get(parent.id) && isSimple.get(parent.id))) {\n sources.add(parentOf.get(parent.id) ?? parent.id);\n }\n }\n if (needCheckHead(sources, expression.head)) {\n for (const alias of extractGlobals(expression.head)) {\n const parent = byAlias.get(alias);\n if (!parent) {\n continue;\n }\n if (!isBaseSet(parent.cst_type) && !(isTemplate.get(parent.id) && isSimple.get(parent.id))) {\n sources.add(parentOf.get(parent.id) ?? parent.id);\n }\n }\n }\n return sources;\n }\n\n function inferSimple(target: FormalOrderFields): boolean {\n if (target.cst_type === CstType.STRUCTURED || isBaseSet(target.cst_type)) {\n return false;\n }\n const dependencies = graph.at(target.id)?.inputs ?? [];\n if (dependencies.some(id => isTemplate.get(id) && !isSimple.get(id))) {\n return false;\n }\n const expression = isFunctional(target.cst_type)\n ? splitTemplateDefinition(target.definition_formal).body\n : target.definition_formal;\n return isSimpleExpression(expression);\n }\n\n for (const cstId of graph.topologicalOrder()) {\n const cst = byId.get(cstId);\n if (!cst) {\n continue;\n }\n isTemplate.set(cstId, inferTemplate(cst.definition_formal));\n isSimple.set(cstId, inferSimple(cst));\n if (!isSimple.get(cstId) || cst.cst_type === CstType.STRUCTURED) {\n continue;\n }\n const sources = extractSources(cst);\n if (sources.size !== 1) {\n continue;\n }\n const parentId = [...sources][0];\n const parent = byId.get(parentId);\n if (!parent || isBaseSet(parent.cst_type)) {\n continue;\n }\n parentOf.set(cstId, parentId);\n childrenOf.get(parentId)!.push(cstId);\n }\n\n return { parentOf, childrenOf };\n}\n","/**\n * Formal dependency graph and declaration-order restore for RSForm constituents.\n */\n\nimport { Graph } from '../../graph';\nimport { extractGlobals } from '../../rslang/api';\nimport { CstType } from '../rsform';\n\nimport { computeSemanticRelations } from './semantic-relations';\nimport { type FormalOrderFields, type SemanticRelations } from './types';\n\n/**\n * Build the formal dependency graph: supplier → dependent.\n * Matches backend {@code RSForm.graph_formal}.\n */\nexport function buildFormalDependencyGraph(items: readonly FormalOrderFields[]): Graph<number> {\n const graph = new Graph<number>();\n const byAlias = new Map(items.map(cst => [cst.alias, cst]));\n for (const cst of items) {\n graph.addNode(cst.id);\n }\n for (const cst of items) {\n for (const alias of extractGlobals(cst.definition_formal)) {\n const supplier = byAlias.get(alias);\n if (supplier) {\n graph.addEdge(supplier.id, cst.id);\n }\n }\n }\n return graph;\n}\n\n/**\n * Reorder constituents: formal topology hard, semantic children sticky when ready,\n * otherwise stable against type/kernel preferred ranks.\n *\n * One Kahn pass over the formal dependency graph.\n */\nexport function restoreConstituentOrder<T extends FormalOrderFields>(\n items: readonly T[],\n graph: Graph<number> = buildFormalDependencyGraph(items),\n relations: SemanticRelations = computeSemanticRelations(items, graph)\n): T[] {\n if (items.length <= 1) {\n return [...items];\n }\n\n const byId = new Map(items.map(cst => [cst.id, cst]));\n const preferred = kernelPriority(items, graph, relations.parentOf);\n const rank = new Map(preferred.map((cst, index) => [cst.id, index]));\n\n const remainingInputs = new Map<number, number>();\n for (const cst of preferred) {\n const inputs = graph.at(cst.id)?.inputs ?? [];\n remainingInputs.set(\n cst.id,\n inputs.reduce((count, src) => count + (rank.has(src) ? 1 : 0), 0)\n );\n }\n\n const ready = new Set<number>();\n for (const cst of preferred) {\n if ((remainingInputs.get(cst.id) ?? 0) === 0) {\n ready.add(cst.id);\n }\n }\n\n const children = new Map<number, number[]>();\n for (const cst of preferred) {\n children.set(\n cst.id,\n (relations.childrenOf.get(cst.id) ?? []).filter(childId => rank.has(childId))\n );\n }\n\n const result: T[] = [];\n const pendingChildren: number[] = [];\n\n function enqueueSticky(candidateIds: readonly number[]): void {\n const sticky = candidateIds.filter(childId => ready.has(childId) && !pendingChildren.includes(childId));\n sticky.sort((left, right) => (rank.get(left) ?? 0) - (rank.get(right) ?? 0));\n pendingChildren.push(...sticky);\n }\n\n function pickReady(): number {\n while (pendingChildren.length > 0) {\n const childId = pendingChildren.shift()!;\n if (ready.has(childId)) {\n return childId;\n }\n }\n let best = -1;\n let bestRank = Number.POSITIVE_INFINITY;\n for (const nodeId of ready) {\n const nodeRank = rank.get(nodeId) ?? Number.POSITIVE_INFINITY;\n if (nodeRank < bestRank) {\n best = nodeId;\n bestRank = nodeRank;\n }\n }\n return best;\n }\n\n while (ready.size > 0 || pendingChildren.length > 0) {\n if (ready.size === 0) {\n pendingChildren.length = 0;\n continue;\n }\n const nodeId = pickReady();\n ready.delete(nodeId);\n result.push(byId.get(nodeId)!);\n\n for (const dependentId of graph.at(nodeId)?.outputs ?? []) {\n if (!remainingInputs.has(dependentId)) {\n continue;\n }\n const next = (remainingInputs.get(dependentId) ?? 0) - 1;\n remainingInputs.set(dependentId, next);\n if (next === 0) {\n ready.add(dependentId);\n }\n }\n\n enqueueSticky(children.get(nodeId) ?? []);\n }\n\n if (result.length < preferred.length) {\n const placed = new Set(result.map(cst => cst.id));\n for (const cst of preferred) {\n if (!placed.has(cst.id)) {\n result.push(cst);\n }\n }\n }\n\n return result;\n}\n\nfunction kernelPriority<T extends FormalOrderFields>(\n items: readonly T[],\n graph: Graph<number>,\n parentOf: Map<number, number>\n): T[] {\n const byId = new Map(items.map(cst => [cst.id, cst]));\n const seen = new Set<number>();\n const result: T[] = [];\n\n function push(cst: T): void {\n if (seen.has(cst.id)) {\n return;\n }\n seen.add(cst.id);\n result.push(cst);\n }\n\n for (const cst of items) {\n if (cst.cst_type === CstType.BASE) {\n push(cst);\n }\n }\n for (const cst of items) {\n if (cst.cst_type === CstType.CONSTANT) {\n push(cst);\n }\n }\n for (const cst of items) {\n if ((graph.at(cst.id)?.inputs.length ?? 0) === 0) {\n push(cst);\n }\n }\n\n const kernelSeeds = items\n .filter(cst => {\n const parentId = parentOf.get(cst.id) ?? cst.id;\n const parent = byId.get(parentId);\n return (\n cst.cst_type === CstType.STRUCTURED || cst.cst_type === CstType.AXIOM || parent?.cst_type === CstType.STRUCTURED\n );\n })\n .map(cst => cst.id);\n const kernel = new Set<number>([...kernelSeeds, ...graph.expandAllInputs(kernelSeeds)]);\n for (const cst of items) {\n if (kernel.has(cst.id)) {\n push(cst);\n }\n }\n for (const cst of items) {\n push(cst);\n }\n return result;\n}\n","/**\n * Schema-level statistics and issue flags.\n */\n\nimport { TypeID, type Typification, ValueClass } from '../../rslang';\nimport { hasCstDiagnostic, RSDiagnosticCode } from '../diagnostics';\nimport { CstStatus, CstType, type RSForm, type RSFormStats } from '../rsform';\n\nimport { isBasicConcept, isLogical } from './cst-type';\nimport { type BasicTextCheckFields, type SchemaIssueFields, type StructureCapableFields } from './types';\n\n/** Checks if an item is a schema issue. */\nexport function isSchemaIssue(cst: SchemaIssueFields): boolean {\n return (\n (cst.diagnostics?.length ?? 0) > 0 || cst.status === CstStatus.INCORRECT || cst.status === CstStatus.INCALCULABLE\n );\n}\n\n/** Calculate statistics for {@link RSForm}. */\nexport function calculateSchemaStats(target: RSForm): RSFormStats {\n const stats: RSFormStats = {\n count_all: target.items.length,\n count_crucial: 0,\n step_complexity: 0,\n count_problematic: 0,\n count_homonyms: 0,\n count_formal_duplicates: 0,\n count_missing_basic_text: 0,\n count_type_mismatch: 0,\n count_incorrect: 0,\n count_property: 0,\n count_incalculable: 0,\n count_inherited: 0,\n count_text_term: 0,\n count_definition: 0,\n count_convention: 0,\n count_comment: 0,\n count_base: 0,\n count_constant: 0,\n count_structured: 0,\n count_axiom: 0,\n count_term: 0,\n count_function: 0,\n count_predicate: 0,\n count_statement: 0,\n count_nominal: 0\n };\n\n for (const cst of target.items) {\n if (cst.crucial) {\n stats.count_crucial += 1;\n }\n stats.step_complexity += calculateStepComplexity(cst);\n\n if (isSchemaIssue(cst)) {\n stats.count_problematic += 1;\n }\n if (hasCstDiagnostic(cst, RSDiagnosticCode.schemaHomonym)) {\n stats.count_homonyms += 1;\n }\n if (hasCstDiagnostic(cst, RSDiagnosticCode.schemaFormalDuplicate)) {\n stats.count_formal_duplicates += 1;\n }\n if (isMissingBasicText(cst)) {\n stats.count_missing_basic_text += 1;\n }\n if (cst.is_type_mismatch) {\n stats.count_type_mismatch += 1;\n }\n if (cst.status === CstStatus.INCORRECT) {\n stats.count_incorrect += 1;\n }\n if (cst.analysis?.valueClass === ValueClass.PROPERTY) {\n stats.count_property += 1;\n }\n if (cst.analysis?.success && cst.analysis.valueClass === null) {\n stats.count_incalculable += 1;\n }\n if (cst.is_inherited) {\n stats.count_inherited += 1;\n }\n if (cst.term_raw) {\n stats.count_text_term += 1;\n }\n if (cst.definition_raw) {\n stats.count_definition += 1;\n }\n if (isBasicConcept(cst.cst_type) && cst.convention) {\n stats.count_convention += 1;\n }\n if (!isBasicConcept(cst.cst_type) && !cst.convention) {\n stats.count_comment += 1;\n }\n\n switch (cst.cst_type) {\n case CstType.BASE:\n stats.count_base += 1;\n break;\n case CstType.CONSTANT:\n stats.count_constant += 1;\n break;\n case CstType.STRUCTURED:\n stats.count_structured += 1;\n break;\n case CstType.AXIOM:\n stats.count_axiom += 1;\n break;\n case CstType.TERM:\n stats.count_term += 1;\n break;\n case CstType.FUNCTION:\n stats.count_function += 1;\n break;\n case CstType.PREDICATE:\n stats.count_predicate += 1;\n break;\n case CstType.STATEMENT:\n stats.count_statement += 1;\n break;\n case CstType.NOMINAL:\n stats.count_nominal += 1;\n break;\n }\n }\n\n return stats;\n}\n\nfunction calculateStepComplexity(cst: StructureCapableFields): number {\n if (cst.cst_type === CstType.AXIOM || cst.cst_type === CstType.NOMINAL || !isBasicConcept(cst.cst_type)) {\n return 0;\n }\n if (cst.cst_type === CstType.BASE || cst.cst_type === CstType.CONSTANT || !cst.effectiveType) {\n return 1;\n }\n\n const type = cst.effectiveType as Typification;\n return calculateTypificationComplexity(type) + 1;\n}\n\nfunction calculateTypificationComplexity(type: Typification): number {\n switch (type.typeID) {\n case TypeID.basic:\n case TypeID.integer:\n case TypeID.anyTypification:\n return 0;\n case TypeID.tuple:\n return (\n type.factors.length + type.factors.reduce((sum, factor) => sum + calculateTypificationComplexity(factor), 0)\n );\n case TypeID.collection:\n if (type.base.typeID === TypeID.tuple) {\n let sum = 0;\n type.base.factors.forEach(factor => {\n sum += calculateTypificationComplexity(factor);\n });\n return sum + type.base.factors.length;\n } else if (type.base.typeID === TypeID.collection) {\n return calculateTypificationComplexity(type.base) + 1;\n }\n return 0;\n }\n}\n\n/** Non-logical basic concept missing convention and/or resolved term (trimmed). */\nfunction isMissingBasicText(cst: BasicTextCheckFields): boolean {\n if (!isBasicConcept(cst.cst_type) || isLogical(cst.cst_type)) {\n return false;\n }\n return !cst.convention.trim() || !cst.term_resolved.trim();\n}\n","/**\n * Structure-path helpers for spawned constituents.\n */\n\nimport { TypeID, type TypePath, type Typification } from '../../rslang';\nimport { isTypification } from '../../rslang/semantic/typification';\nimport { applyPath } from '../../rslang/semantic/typification-api';\nimport { type Constituenta, type RSForm } from '../rsform';\n\nimport { type SpawnPathFields, type StructureCapableFields } from './types';\n\n/**\n * Id to pass as `insert_after` when creating a new {@link Constituenta} spawned by `targetId`:\n * after the last existing child of that spawner, or after the spawner itself if none.\n */\nexport function inferNewSpawnPosition(schema: RSForm, targetId: number): number {\n let last: number | null = null;\n for (const cst of schema.items) {\n if (cst.spawner === targetId) {\n last = cst.id;\n }\n }\n return last ?? targetId;\n}\n\n/** Finds schema item by absolute structure path under `targetId`. */\nexport function findCstByStructure(schema: RSForm, target: { id: number }, path: TypePath): Constituenta | null {\n const byId = schema.cstByID ?? new Map(schema.items.map(item => [item.id, item]));\n for (const cst of schema.items) {\n if (!cst.spawner_path) {\n continue;\n }\n const absolutePath = resolveAbsoluteSpawnerPath(cst, target.id, byId);\n if (absolutePath?.length === path.length && absolutePath.every((v, i) => v === path[i])) {\n return cst;\n }\n }\n return null;\n}\n\n/** Retrieves name for piece of target structure. */\nexport function getStructureName(\n schema: RSForm,\n target: StructureCapableFields & { id: number },\n path: TypePath\n): string {\n const representation = findCstByStructure(schema, target, path);\n if (representation) {\n return `${representation.alias}: ${representation.term_resolved}`;\n }\n if (!isTypification(target.effectiveType)) {\n return '';\n }\n const type = applyPath(target.effectiveType as Typification, path);\n if (type?.typeID === TypeID.basic) {\n const cst = schema.cstByAlias.get(type.baseID);\n if (cst?.term_resolved) {\n return `${cst.alias}: ${cst.term_resolved}`;\n }\n }\n return '';\n}\n\nfunction resolveAbsoluteSpawnerPath(\n cst: SpawnPathFields,\n targetId: number,\n byId: Map<number, SpawnPathFields>\n): TypePath | null {\n if (!cst.spawner_path || cst.spawner == null) {\n return null;\n }\n if (cst.spawner === targetId) {\n return cst.spawner_path;\n }\n\n const visited = new Set<number>([cst.id]);\n let currentPath: number[] = [...cst.spawner_path];\n let currentSpawnerId: number | null = cst.spawner;\n\n while (currentSpawnerId != null) {\n if (currentSpawnerId === targetId) {\n return currentPath as TypePath;\n }\n if (visited.has(currentSpawnerId)) {\n return null;\n }\n visited.add(currentSpawnerId);\n\n const parent = byId.get(currentSpawnerId);\n if (!parent?.spawner_path || parent.spawner == null) {\n return null;\n }\n\n currentPath = [...parent.spawner_path, ...currentPath];\n currentSpawnerId = parent.spawner;\n }\n\n return null;\n}\n","/**\n * Constituenta substitution and post-import substitution remapping.\n */\n\nimport { type AliasMapping } from '../../rslang/api';\nimport { type Attribution, type Substitution } from '../rsform';\n\nimport { applyMappingToConstituents, type MappableFields } from './alias';\nimport { remapAttributionsUnderSubstitution } from './attribution';\n\n/** Result of applying substitutions to a schema fragment. */\nexport interface SubstitutionResult<T> {\n items: T[];\n attributions: Attribution[];\n deletedIds: Set<number>;\n /** Replacement constituent ids (survivors referenced by substitutions). */\n replacementIds: number[];\n}\n\n/**\n * Apply constituenta substitutions: remap attributions, drop originals, rewrite aliases in survivors.\n * Does not resolve texts — call {@link resolveAllConstituentTexts} afterwards.\n */\nexport function applyConstituentSubstitutions<T extends MappableFields & { id: number; alias: string }>(\n items: readonly T[],\n attributions: readonly Attribution[],\n substitutions: readonly Substitution[]\n): SubstitutionResult<T> {\n if (substitutions.length === 0) {\n return {\n items: [...items],\n attributions: attributions.map(attr => ({ ...attr })),\n deletedIds: new Set(),\n replacementIds: []\n };\n }\n\n const byId = new Map(items.map(cst => [cst.id, cst]));\n const mapping: AliasMapping = {};\n const deletedIds = new Set<number>();\n const origToSub = new Map<number, number>();\n const replacementIds: number[] = [];\n\n for (const { original, substitution } of substitutions) {\n const originalCst = byId.get(original);\n const substitutionCst = byId.get(substitution);\n if (!originalCst || !substitutionCst) {\n throw new Error(`applyConstituentSubstitutions: unknown constituenta ${original} -> ${substitution}`);\n }\n mapping[originalCst.alias] = substitutionCst.alias;\n deletedIds.add(original);\n origToSub.set(original, substitution);\n replacementIds.push(substitution);\n }\n\n const nextItems = items.filter(cst => !deletedIds.has(cst.id));\n applyMappingToConstituents(nextItems, mapping, false);\n\n return {\n items: nextItems,\n attributions: remapAttributionsUnderSubstitution(attributions, origToSub),\n deletedIds,\n replacementIds\n };\n}\n\n/**\n * Remap substitution endpoints after source constituents were inserted under new ids.\n * If {@link original} was imported, map it; otherwise map {@link substitution}.\n */\nexport function remapSubstitutionsAfterImport(\n substitutions: readonly Substitution[],\n sourceIdSet: ReadonlySet<number>,\n idMap: Readonly<Record<number, number>>\n): Substitution[] {\n return substitutions.map(sub => {\n if (sourceIdSet.has(sub.original)) {\n return { original: idMap[sub.original], substitution: sub.substitution };\n }\n return { original: sub.original, substitution: idMap[sub.substitution] };\n });\n}\n","/**\n * Cascade resolution of constituenta term/definition entity references.\n * Matches backend {@code RSForm.resolve_all_text} / {@code resolve_term_change}.\n */\n\nimport { type TermContext } from '../../cctext/language';\nimport { extractEntities, parseGrammemes, resolveTextReferences } from '../../cctext/language-api';\nimport { Graph } from '../../graph';\n\nimport { type TextResolvableFields } from './types';\n\n/** Options controlling which texts to re-resolve after an edit. */\nexport interface TextChangeOptions {\n termChanged: boolean;\n termRawChanged: boolean;\n definitionRawChanged: boolean;\n clearTargetForms: boolean;\n}\n\n/** Build term-reference graph: referenced constituent → dependent (backend {@code graph_term}). */\nexport function buildTermReferenceGraph(items: readonly TextResolvableFields[]): Graph<number> {\n return buildReferenceGraph(items, 'term_raw');\n}\n\n/** Build definition-reference graph: referenced constituent → dependent (backend {@code graph_text}). */\nexport function buildDefinitionReferenceGraph(items: readonly TextResolvableFields[]): Graph<number> {\n return buildReferenceGraph(items, 'definition_raw');\n}\n\n/** Resolve all term and definition texts in topological order. Mutates items in place. */\nexport function resolveAllConstituentTexts(items: TextResolvableFields[]): void {\n const graphTerm = buildTermReferenceGraph(items);\n const idToItem = new Map(items.map(item => [item.id, item]));\n const context = buildTermContext(items);\n\n for (const id of graphTerm.topologicalOrder()) {\n const row = idToItem.get(id);\n if (!row) {\n continue;\n }\n const resolved = resolveTextReferences(row.term_raw, context);\n if (resolved !== row.term_resolved) {\n row.term_resolved = resolved;\n row.term_forms = [];\n context[row.alias] = { nominal: row.term_resolved, forms: [] };\n }\n }\n\n for (const row of items) {\n row.definition_resolved = resolveTextReferences(row.definition_raw, context);\n }\n}\n\n/**\n * Resolve texts after a single constituent change, cascading dependents when the term changed.\n * Mutates items in place.\n */\nexport function resolveConstituentTextChange(\n items: TextResolvableFields[],\n targetID: number,\n options: TextChangeOptions\n): void {\n const idToItem = new Map(items.map(item => [item.id, item]));\n const target = idToItem.get(targetID);\n if (!target) {\n throw new Error(`resolveConstituentTextChange: unknown target ${targetID}`);\n }\n\n const context = buildTermContext(items);\n if (options.termRawChanged) {\n target.term_resolved = resolveTextReferences(target.term_raw, context);\n if (options.clearTargetForms) {\n target.term_forms = [];\n }\n context[target.alias] = toContextItem(target);\n } else if (options.termChanged) {\n context[target.alias] = toContextItem(target);\n }\n\n if (options.definitionRawChanged && !options.termChanged) {\n target.definition_resolved = resolveTextReferences(target.definition_raw, context);\n }\n\n if (!options.termChanged) {\n return;\n }\n\n const graphTerm = buildTermReferenceGraph(items);\n const graphText = buildDefinitionReferenceGraph(items);\n const expansion = graphTerm.expandAllOutputs([targetID]);\n const expansionSet = new Set(expansion);\n\n for (const id of graphTerm.topologicalOrder()) {\n if (!expansionSet.has(id)) {\n continue;\n }\n const expanded = idToItem.get(id);\n if (!expanded) {\n continue;\n }\n const resolved = resolveTextReferences(expanded.term_raw, context);\n if (resolved !== expanded.term_resolved) {\n expanded.term_resolved = resolved;\n expanded.term_forms = [];\n context[expanded.alias] = { nominal: expanded.term_resolved, forms: [] };\n }\n }\n\n const updateDefs = new Set([targetID, ...expansion, ...graphText.expandAllOutputs([targetID, ...expansion])]);\n for (const item of items) {\n if (updateDefs.has(item.id)) {\n item.definition_resolved = resolveTextReferences(item.definition_raw, context);\n }\n }\n}\n\n// ====== Internals =======\n\nfunction buildReferenceGraph(\n items: readonly TextResolvableFields[],\n field: 'definition_raw' | 'term_raw'\n): Graph<number> {\n const graph = new Graph<number>();\n const idByAlias = new Map(items.map(row => [row.alias, row.id]));\n for (const row of items) {\n graph.addNode(row.id);\n }\n for (const row of items) {\n for (const entity of extractEntities(row[field])) {\n const source = idByAlias.get(entity);\n if (source !== undefined) {\n graph.addEdge(source, row.id);\n }\n }\n }\n return graph;\n}\n\nfunction buildTermContext(items: readonly TextResolvableFields[]): TermContext {\n const context: TermContext = {};\n for (const row of items) {\n context[row.alias] = toContextItem(row);\n }\n return context;\n}\n\nfunction toContextItem(row: TextResolvableFields): TermContext[string] {\n return {\n nominal: row.term_resolved,\n forms: row.term_forms.map(form => ({ text: form.text, grams: parseGrammemes(form.tags) }))\n };\n}\n","/**\n * Schema embedding (synthesis): insert constituents from a source schema into a receiver,\n * then apply an identification (substitution) table.\n *\n * Mirrors backend `inline_synthesis` / `insert_from` + `substitute`\n * (Portal UI: «Встраивание схемы»).\n */\n\nimport { type AliasMapping } from '../../rslang/api';\nimport { type LibraryItem } from '../library';\nimport { type Attribution, type CstType, type RSForm, type Substitution } from '../rsform';\n\nimport { allocateImportAliases, applyMappingToConstituents, type MappableFields } from './alias';\nimport { importAttributions } from './attribution';\nimport { applyConstituentSubstitutions, remapSubstitutionsAfterImport } from './substitution';\nimport { resolveAllConstituentTexts } from './text-resolution';\nimport { type AliasTypedFields, type TextResolvableFields } from './types';\n\n/** Field intersection required for embedding / synthesis transforms. */\nexport type SynthesizableFields = MappableFields &\n TextResolvableFields &\n AliasTypedFields & {\n id: number;\n alias: string;\n cst_type: CstType;\n };\n\n/** Input for {@link inlineSynthesis}. */\nexport interface InlineSynthesisInput<T extends SynthesizableFields> {\n /** Receiver schema constituents (order preserved; imports append). */\n receiverItems: readonly T[];\n /** Receiver attributions (default empty). */\n receiverAttributions?: readonly Attribution[];\n /**\n * Source constituents to insert (already filtered to the desired subset).\n * Cloned; originals are not mutated.\n */\n sourceItems: readonly T[];\n /** Source attributions whose both endpoints are among {@link sourceItems}. */\n sourceAttributions?: readonly Attribution[];\n /**\n * Identification table using pre-import ids:\n * one endpoint is a source id, the other a receiver id\n * (same rules as backend embedding / InlineSynthesis).\n */\n substitutions?: readonly Substitution[];\n /** Next free numeric id for inserted constituents. */\n nextId: number;\n}\n\n/** Result of {@link inlineSynthesis}. */\nexport interface InlineSynthesisResult<T extends SynthesizableFields> {\n items: T[];\n attributions: Attribution[];\n /** Updated next-id after inserts. */\n nextId: number;\n /** Source id → inserted id. */\n idMap: Record<number, number>;\n /** Alias remapping applied to imported constituents (empty when receiver was empty). */\n aliasMapping: AliasMapping;\n /** Ids removed by substitutions. */\n deletedIds: Set<number>;\n /** Ids of newly inserted constituents (before any were deleted by substitutions). */\n insertedIds: number[];\n /** Survivor ids referenced by applied substitutions. */\n replacementIds: number[];\n}\n\n/**\n * Embed {@link InlineSynthesisInput.sourceItems} into the receiver and apply substitutions.\n * Resolves term/definition entity references on the result.\n * Does not mutate inputs.\n */\nexport function inlineSynthesis<T extends SynthesizableFields>(\n input: InlineSynthesisInput<T>\n): InlineSynthesisResult<T> {\n const sourceItems = input.sourceItems;\n if (sourceItems.length === 0) {\n return {\n items: input.receiverItems.map(item => structuredClone(item)),\n attributions: (input.receiverAttributions ?? []).map(attr => ({ ...attr })),\n nextId: input.nextId,\n idMap: {},\n aliasMapping: {},\n deletedIds: new Set(),\n insertedIds: [],\n replacementIds: []\n };\n }\n\n const receiverItems = input.receiverItems.map(item => structuredClone(item));\n let attributions = (input.receiverAttributions ?? []).map(attr => ({ ...attr }));\n const aliasMapping = allocateImportAliases(receiverItems, sourceItems);\n const idMap: Record<number, number> = {};\n const inserted: T[] = [];\n const sourceIdSet = new Set(sourceItems.map(cst => cst.id));\n let nextId = input.nextId;\n\n for (const cst of sourceItems) {\n const newId = nextId;\n nextId += 1;\n idMap[cst.id] = newId;\n\n const cloned = structuredClone(cst);\n cloned.id = newId;\n if (Object.keys(aliasMapping).length > 0) {\n cloned.alias = aliasMapping[cst.alias];\n applyMappingToConstituents([cloned], aliasMapping, false);\n }\n inserted.push(cloned);\n }\n\n attributions = importAttributions(input.sourceAttributions ?? [], sourceIdSet, idMap, attributions);\n const items = receiverItems.concat(inserted);\n resolveAllConstituentTexts(items);\n\n const substitutions = input.substitutions ?? [];\n if (substitutions.length === 0) {\n return {\n items,\n attributions,\n nextId,\n idMap,\n aliasMapping,\n deletedIds: new Set(),\n insertedIds: inserted.map(cst => cst.id),\n replacementIds: []\n };\n }\n\n const remapped = remapSubstitutionsAfterImport(substitutions, sourceIdSet, idMap);\n const substituted = applyConstituentSubstitutions(items, attributions, remapped);\n resolveAllConstituentTexts(substituted.items);\n\n return {\n items: substituted.items,\n attributions: substituted.attributions,\n nextId,\n idMap,\n aliasMapping,\n deletedIds: substituted.deletedIds,\n insertedIds: inserted.map(cst => cst.id),\n replacementIds: substituted.replacementIds\n };\n}\n\n/** Sorts library items relevant for schema embedding with specified {@link RSForm}. */\nexport function sortItemsForInlineSynthesis(receiver: RSForm, items: readonly LibraryItem[]): LibraryItem[] {\n const result = items.filter(item => item.location === receiver.location);\n const included = new Set(result);\n for (const item of items) {\n if (item.visible && item.owner === receiver.owner && !included.has(item)) {\n result.push(item);\n included.add(item);\n }\n }\n for (const item of items) {\n if (item.visible && !included.has(item)) {\n result.push(item);\n included.add(item);\n }\n }\n for (const item of items) {\n if (!included.has(item)) {\n result.push(item);\n included.add(item);\n }\n }\n return result;\n}\n","/**\n * Pure constituenta list transforms: reorder, move, insert position.\n */\n\n/** Rebuild an item list following {@link orderedIds}. Throws if an id is missing. */\nexport function reorderItemsByIds<T extends { id: number }>(items: readonly T[], orderedIds: readonly number[]): T[] {\n const byId = new Map(items.map(item => [item.id, item]));\n return orderedIds.map(id => {\n const item = byId.get(id);\n if (!item) {\n throw new Error(`reorderItemsByIds: missing id ${id}`);\n }\n return item;\n });\n}\n\n/**\n * Move a subset of ids within an ordered id list.\n * {@link moveTo} is clamped to `[0, rest.length]` (index among non-moving items).\n */\nexport function moveIdsInOrder(ids: readonly number[], moving: readonly number[], moveTo: number): number[] {\n const movingSet = new Set(moving);\n const rest = ids.filter(id => !movingSet.has(id));\n const movingItems = ids.filter(id => movingSet.has(id));\n const clamped = Math.max(0, Math.min(moveTo, rest.length));\n return [...rest.slice(0, clamped), ...movingItems, ...rest.slice(clamped)];\n}\n\n/** Insert {@link item} after {@link insertAfter}, or append when null/undefined/missing. Mutates {@link items}. */\nexport function insertItemAfter<T extends { id: number }>(\n items: T[],\n item: T,\n insertAfter: number | null | undefined\n): void {\n if (insertAfter === null || insertAfter === undefined) {\n items.push(item);\n return;\n }\n const idx = items.findIndex(row => row.id === insertAfter);\n const insertAt = idx === -1 ? items.length : idx + 1;\n items.splice(insertAt, 0, item);\n}\n","/**\n * Module: Compact diagnostics for constituents (schema and model issue codes).\n */\n\nimport { type Graph } from '../graph';\nimport { type ExpressionType } from '../rslang';\nimport { labelType } from '../rslang/labels';\n\nimport { type BasicTextCheckFields } from './rsform-api/types';\nimport { type Constituenta, type CstType } from './rsform';\nimport { isBasicConcept, isLogical } from './rsform-api';\nimport { EvalStatus } from './rsmodel';\n\n/** Origin of a diagnostic. */\nexport const DiagnosticKind = {\n EXPRESSION: 'expression',\n SCHEMA: 'schema',\n MODEL: 'model'\n} as const;\nexport type DiagnosticKind = (typeof DiagnosticKind)[keyof typeof DiagnosticKind];\n\n/** Schema and model diagnostic codes (same numeric format as {@link RSErrorCode}). */\nexport const RSDiagnosticCode = {\n schemaHomonym: 0x8901,\n schemaFormalDuplicate: 0x8902,\n schemaMissingConvention: 0x8903,\n schemaMissingTerm: 0x8904,\n schemaTypeMismatch: 0x8905,\n schemaDependencyCycle: 0x8906,\n\n modelEmpty: 0x8910,\n modelAxiomFalse: 0x8911,\n modelInvalidData: 0x8912,\n modelEvalFail: 0x8913\n} as const;\nexport type RSDiagnosticCode = (typeof RSDiagnosticCode)[keyof typeof RSDiagnosticCode];\n\n/** Compact diagnostic stored on {@link Constituenta} after schema loading. */\nexport interface CstDiagnostic {\n kind: DiagnosticKind;\n code: number;\n /** Positional message arguments (per-code; homonyms/duplicates use `[aliases]`). */\n params?: readonly string[];\n}\n\n/** Whether an item has a schema/model diagnostic with the given code. */\nexport function hasCstDiagnostic(\n cst: { diagnostics?: readonly CstDiagnostic[] | null },\n code: RSDiagnosticCode\n): boolean {\n return cst.diagnostics?.some(item => item.code === code) ?? false;\n}\n\n/**\n * Populate `diagnostics` on each constituent (homonyms, duplicates, metadata, type mismatch, cycles).\n *\n * Requires normalized formal definitions for duplicate detection (same as Portal loader).\n * When `graph` is provided, dependency cycles are reported as {@link RSDiagnosticCode.schemaDependencyCycle}.\n */\nexport function assignSchemaDiagnostics(\n items: Constituenta[],\n resolveAlias: (id: number) => string,\n normalizedDefinitions: ReadonlyMap<number, string>,\n graph?: Graph\n): void {\n const homonymById = detectHomonymDiagnostics(items, resolveAlias);\n const duplicateById = detectFormalDuplicateDiagnostics(items, resolveAlias, normalizedDefinitions);\n const cycleById = graph ? detectDependencyCycleDiagnostics(graph, resolveAlias) : new Map<number, CstDiagnostic>();\n\n for (const cst of items) {\n const diagnostics: CstDiagnostic[] = [];\n const cycle = cycleById.get(cst.id);\n if (cycle) {\n diagnostics.push(cycle);\n }\n const homonym = homonymById.get(cst.id);\n if (homonym) {\n diagnostics.push(homonym);\n }\n const duplicate = duplicateById.get(cst.id);\n if (duplicate) {\n diagnostics.push(duplicate);\n }\n diagnostics.push(...collectLocalSchemaDiagnostics(cst));\n cst.diagnostics = diagnostics;\n }\n}\n\n/**\n * Format a closed dependency cycle as `A → B → A`.\n *\n * Rotates the path to start at the lexicographically smallest alias so the same\n * cycle always renders identically regardless of graph traversal order.\n *\n * @param aliases Closed or open alias path from {@link Graph.findCycles}.\n * @returns Human-readable cycle text joined with ` → `.\n */\nexport function formatDependencyCycle(aliases: readonly string[]): string {\n if (aliases.length < 2) {\n return aliases.join(' → ');\n }\n\n const closed = aliases[0] === aliases[aliases.length - 1];\n const open = closed ? aliases.slice(0, -1) : [...aliases];\n if (open.length === 0) {\n return aliases.join(' → ');\n }\n\n let bestStart = 0;\n for (let index = 1; index < open.length; index++) {\n const alias = open[index];\n const bestAlias = open[bestStart];\n if (alias !== undefined && bestAlias !== undefined && alias < bestAlias) {\n bestStart = index;\n }\n }\n const rotated = [...open.slice(bestStart), ...open.slice(0, bestStart)];\n if (closed) {\n const first = rotated[0];\n if (first !== undefined) {\n rotated.push(first);\n }\n }\n return rotated.join(' → ');\n}\n\n/**\n * Map each node id that participates in a dependency cycle to a schema diagnostic.\n *\n * `params[0]` is the closed cycle path (`F3 → P1 → F3`).\n *\n * @param graph Constituent dependency graph (provider → dependent edges).\n * @param resolveAlias Maps node id to display alias for cycle formatting.\n * @returns One {@link CstDiagnostic} per node on each cyclic SCC.\n */\nexport function detectDependencyCycleDiagnostics(\n graph: Graph,\n resolveAlias: (id: number) => string\n): Map<number, CstDiagnostic> {\n const result = new Map<number, CstDiagnostic>();\n for (const cycle of graph.findCycles()) {\n if (cycle.length < 2) {\n continue;\n }\n const aliases = cycle.map(id => resolveAlias(id));\n const cycleText = formatDependencyCycle(aliases);\n const memberIds = new Set(cycle);\n for (const id of memberIds) {\n result.set(id, {\n kind: DiagnosticKind.SCHEMA,\n code: RSDiagnosticCode.schemaDependencyCycle,\n params: [cycleText]\n });\n }\n }\n return result;\n}\n\n/** Map a model evaluation status to a compact diagnostic, or `null` when not an issue. */\nexport function modelStatusCstDiagnostic(status: EvalStatus, cstType: CstType): CstDiagnostic | null {\n const code = modelStatusToCode(status, cstType);\n if (code === null) {\n return null;\n }\n return { kind: DiagnosticKind.MODEL, code, params: [String(status)] };\n}\n\nfunction collectLocalSchemaDiagnostics(\n cst: BasicTextCheckFields & {\n is_type_mismatch: boolean;\n typification_manual: string;\n analysis: { type: ExpressionType | null };\n }\n): CstDiagnostic[] {\n const result: CstDiagnostic[] = [];\n if (cst.is_type_mismatch) {\n result.push({\n kind: DiagnosticKind.SCHEMA,\n code: RSDiagnosticCode.schemaTypeMismatch,\n params: [cst.typification_manual, labelType(cst.analysis.type)]\n });\n }\n if (isBasicConcept(cst.cst_type) && !isLogical(cst.cst_type)) {\n if (!cst.convention.trim()) {\n result.push({ kind: DiagnosticKind.SCHEMA, code: RSDiagnosticCode.schemaMissingConvention });\n }\n if (!cst.term_resolved.trim()) {\n result.push({ kind: DiagnosticKind.SCHEMA, code: RSDiagnosticCode.schemaMissingTerm });\n }\n }\n return result;\n}\n\nfunction detectGroupedAliasDiagnostics<T extends { id: number }>(\n items: readonly T[],\n resolveAlias: (id: number) => string,\n groupKey: (cst: T) => string | undefined,\n code: RSDiagnosticCode\n): Map<number, CstDiagnostic> {\n const groups = new Map<string, T[]>();\n for (const cst of items) {\n const key = groupKey(cst);\n if (!key) {\n continue;\n }\n const group = groups.get(key) ?? [];\n group.push(cst);\n groups.set(key, group);\n }\n\n const result = new Map<number, CstDiagnostic>();\n for (const group of groups.values()) {\n if (group.length <= 1) {\n continue;\n }\n for (const cst of group) {\n const aliases = group\n .filter(other => other.id !== cst.id)\n .map(other => resolveAlias(other.id))\n .join(', ');\n result.set(cst.id, {\n kind: DiagnosticKind.SCHEMA,\n code,\n params: [aliases]\n });\n }\n }\n return result;\n}\n\nfunction detectHomonymDiagnostics(\n items: readonly { id: number; term_resolved: string }[],\n resolveAlias: (id: number) => string\n): Map<number, CstDiagnostic> {\n return detectGroupedAliasDiagnostics(\n items,\n resolveAlias,\n cst => {\n const key = cst.term_resolved.trim().toLocaleLowerCase();\n return key === '' ? undefined : key;\n },\n RSDiagnosticCode.schemaHomonym\n );\n}\n\nfunction detectFormalDuplicateDiagnostics(\n items: readonly { id: number }[],\n resolveAlias: (id: number) => string,\n normalizedDefinitions: ReadonlyMap<number, string>\n): Map<number, CstDiagnostic> {\n return detectGroupedAliasDiagnostics(\n items,\n resolveAlias,\n cst => normalizedDefinitions.get(cst.id),\n RSDiagnosticCode.schemaFormalDuplicate\n );\n}\n\nfunction modelStatusToCode(status: EvalStatus, cstType: CstType): RSDiagnosticCode | null {\n switch (status) {\n case EvalStatus.EMPTY:\n return isBasicConcept(cstType) ? RSDiagnosticCode.modelEmpty : null;\n case EvalStatus.AXIOM_FALSE:\n return RSDiagnosticCode.modelAxiomFalse;\n case EvalStatus.INVALID_DATA:\n return RSDiagnosticCode.modelInvalidData;\n case EvalStatus.EVAL_FAIL:\n return RSDiagnosticCode.modelEvalFail;\n default:\n return null;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAWA,MAAM,kBAA2C;EAC9C,QAAQ,UAAU;EAClB,QAAQ,OAAO;EACf,QAAQ,WAAW;EACnB,QAAQ,aAAa;EACrB,QAAQ,QAAQ;EAChB,QAAQ,OAAO;EACf,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,yBAAS,IAAI,IAAiB;CACpC,KAAK,MAAM,OAAO,OAAO;EACvB,MAAM,MAAM,SAAS,GAAG;EACxB,IAAI,CAAC,KACH;EAEF,MAAM,QAAQ,OAAO,IAAI,GAAG,KAAK,CAAC;EAClC,MAAM,KAAK,GAAG;EACd,OAAO,IAAI,KAAK,KAAK;CACvB;CAEA,MAAM,yBAAS,IAAI,IAA2B;CAC9C,KAAK,MAAM,SAAS,OAAO,OAAO,GAAG;EACnC,IAAI,MAAM,UAAU,GAClB;EAEF,KAAK,MAAM,OAAO,OAAO;GACvB,MAAM,UAAU,MACb,QAAO,UAAS,MAAM,OAAO,IAAI,EAAE,CAAC,CACpC,KAAI,UAAS,aAAa,MAAM,EAAE,CAAC,CAAC,CACpC,KAAK,IAAI;GACZ,OAAO,IAAI,IAAI,IAAI;IACjB,MAAM,eAAe;IACrB;IACA,QAAQ,CAAC,OAAO;GAClB,CAAC;EACH;CACF;CACA,OAAO;AACT;AAEA,SAAS,yBACP,OACA,cAC4B;CAC5B,OAAO,8BACL,OACA,eACA,QAAO;EACL,MAAM,MAAM,IAAI,cAAc,KAAK,CAAC,CAAC,kBAAkB;EACvD,OAAO,QAAQ,KAAK,SAAY;CAClC,GACA,iBAAiB,aACnB;AACF;AAEA,SAAS,iCACP,OACA,cACA,uBAC4B;CAC5B,OAAO,8BACL,OACA,eACA,QAAO,sBAAsB,IAAI,IAAI,EAAE,GACvC,iBAAiB,qBACnB;AACF;AAEA,SAAS,kBAAkB,QAAoB,SAA2C;CACxF,QAAQ,QAAR;EACE,KAAK,WAAW,OACd,OAAO,eAAe,OAAO,IAAI,iBAAiB,aAAa;EACjE,KAAK,WAAW,aACd,OAAO,iBAAiB;EAC1B,KAAK,WAAW,cACd,OAAO,iBAAiB;EAC1B,KAAK,WAAW,WACd,OAAO,iBAAiB;EAC1B,SACE,OAAO;CACX;AACF"}
1
+ {"version":3,"file":"diagnostics-D1Cp21nP.js","names":[],"sources":["../src/library/rsform-api/cst-type.ts","../src/library/rsform-api/alias.ts","../src/library/rsform-api/analysis.ts","../src/library/rsform-api/attribution.ts","../src/library/rsform-api/expression.ts","../src/library/rsform-api/semantic-relations.ts","../src/library/rsform-api/formal-graph.ts","../src/library/rsform-api/stats.ts","../src/library/rsform-api/structure.ts","../src/library/rsform-api/substitution.ts","../src/library/rsform-api/text-resolution.ts","../src/library/rsform-api/synthesis.ts","../src/library/rsform-api/transforms.ts","../src/library/diagnostics.ts"],"sourcesContent":["/**\n * CstType classification, prefixes, and capability predicates.\n */\n\nimport { TypeClass, TypeID, type Typification } from '../../rslang';\nimport { type EchelonFunctional, isTypification } from '../../rslang/semantic/typification';\nimport { CstClass, CstType } from '../rsform';\n\nimport { type StructureCapableFields } from './types';\n\n/** Record of {@link CstType} prefixes. */\nconst CST_TYPE_PREFIX: Record<CstType, string> = {\n [CstType.NOMINAL]: 'N',\n [CstType.BASE]: 'X',\n [CstType.CONSTANT]: 'C',\n [CstType.STRUCTURED]: 'S',\n [CstType.AXIOM]: 'A',\n [CstType.TERM]: 'D',\n [CstType.FUNCTION]: 'F',\n [CstType.PREDICATE]: 'P',\n [CstType.STATEMENT]: 'T'\n};\n\n/** Record of {@link CstType} to {@link CstClass} mapping. */\nconst CST_TYPE_TO_CLASS: Record<CstType, CstClass> = {\n [CstType.NOMINAL]: CstClass.NOMINAL,\n [CstType.BASE]: CstClass.BASIC,\n [CstType.CONSTANT]: CstClass.BASIC,\n [CstType.STRUCTURED]: CstClass.BASIC,\n [CstType.TERM]: CstClass.DERIVED,\n [CstType.FUNCTION]: CstClass.DERIVED,\n [CstType.AXIOM]: CstClass.STATEMENT,\n [CstType.PREDICATE]: CstClass.DERIVED,\n [CstType.STATEMENT]: CstClass.STATEMENT\n};\n\n/** Prefix for alias indicating {@link CstType}. */\nexport function getCstTypePrefix(type: CstType): string {\n return CST_TYPE_PREFIX[type];\n}\n\n/** Guess {@link CstType} from user input hint. */\nexport function guessCstType(hint: string): CstType | null {\n if (hint.length !== 1) {\n return null;\n }\n for (const [type, prefix] of Object.entries(CST_TYPE_PREFIX)) {\n if (hint === prefix) {\n return type as CstType;\n }\n }\n return null;\n}\n\n/** Infers the {@link CstClass} based on the provided {@link CstType} and template status. */\nexport function inferClass(type: CstType, isTemplate: boolean = false): CstClass {\n if (isTemplate) {\n return CstClass.TEMPLATE;\n }\n return CST_TYPE_TO_CLASS[type];\n}\n\n/** Check if item type is a template or a category. */\nexport function isTemplateCst(cst: { cst_type: CstType }): boolean {\n return cst.cst_type === CstType.FUNCTION || cst.cst_type === CstType.PREDICATE || cst.cst_type === CstType.STATEMENT;\n}\n\n/** Evaluate if {@link CstType} is basic concept. */\nexport function isBasicConcept(type: CstType): boolean {\n switch (type) {\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.AXIOM:\n return true;\n\n case CstType.TERM:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n case CstType.STATEMENT:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} is base set or constant set. */\nexport function isBaseSet(type: CstType): boolean {\n switch (type) {\n case CstType.BASE:\n case CstType.CONSTANT:\n return true;\n\n case CstType.NOMINAL:\n case CstType.STRUCTURED:\n case CstType.AXIOM:\n case CstType.TERM:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n case CstType.STATEMENT:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} is a function. */\nexport function isFunctional(type: CstType): boolean {\n switch (type) {\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return true;\n\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.AXIOM:\n case CstType.TERM:\n case CstType.STATEMENT:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} is logical. */\nexport function isLogical(type: CstType): boolean {\n switch (type) {\n case CstType.AXIOM:\n case CstType.STATEMENT:\n return true;\n\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.TERM:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} can have manual typification. */\nexport function canHaveManualTypification(type: CstType): boolean {\n switch (type) {\n case CstType.STRUCTURED:\n case CstType.TERM:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return true;\n\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.AXIOM:\n case CstType.STATEMENT:\n return false;\n }\n}\n\n/** Checks whether a constituenta type supports formal definitions. */\nexport function canHaveFormalDefinition(cstType: CstType): boolean {\n return cstType !== CstType.BASE && cstType !== CstType.CONSTANT;\n}\n\n/** Returns expected {@link TypeClass} of formal definition for {@link CstType}. */\nexport function typeClassForCstType(cstType: CstType): TypeClass {\n switch (cstType) {\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.TERM:\n return TypeClass.typification;\n case CstType.FUNCTION:\n return TypeClass.function;\n case CstType.PREDICATE:\n return TypeClass.predicate;\n case CstType.AXIOM:\n case CstType.STATEMENT:\n return TypeClass.logic;\n }\n}\n\n/** Evaluate if an item can be used to produce structure. */\nexport function canProduceStructure(cst: StructureCapableFields): boolean {\n switch (cst.cst_type) {\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.AXIOM:\n case CstType.STATEMENT:\n case CstType.PREDICATE:\n return false;\n }\n if (!cst.effectiveType) {\n return false;\n }\n if (cst.cst_type === CstType.FUNCTION) {\n const result = (cst.effectiveType as EchelonFunctional).result;\n return typeCanProduceStructure(result);\n }\n if (!isTypification(cst.effectiveType)) {\n return false;\n }\n return typeCanProduceStructure(cst.effectiveType as Typification);\n}\n\nfunction typeCanProduceStructure(type: Typification): boolean {\n if (type.typeID === TypeID.basic || type.typeID === TypeID.integer || type.typeID === TypeID.anyTypification) {\n return false;\n } else if (type.typeID === TypeID.tuple) {\n return true;\n } else {\n return (\n type.base.typeID !== TypeID.basic &&\n type.base.typeID !== TypeID.integer &&\n type.base.typeID !== TypeID.anyTypification\n );\n }\n}\n","/**\n * Alias generation, validation, and remapping.\n */\n\nimport { applyEntityReferenceMapping } from '../../cctext/language-api';\nimport { type AliasMapping, applyAliasMapping, applyTypificationMapping } from '../../rslang/api';\nimport { type ArgumentValue, CstType, type RSForm } from '../rsform';\n\nimport { getCstTypePrefix } from './cst-type';\nimport { type AliasTypedFields } from './types';\n\n/** Fields updated in place by alias mapping. */\nexport interface MappableFields {\n alias: string;\n definition_formal: string;\n typification_manual: string;\n term_raw: string;\n definition_raw: string;\n}\n\n/** Build alias mapping from template argument bindings. */\nexport function argumentValuesToMapping(args: ArgumentValue[]): AliasMapping {\n const mapping: AliasMapping = {};\n for (const arg of args) {\n if (arg.value) {\n mapping[arg.alias] = arg.value;\n }\n }\n return mapping;\n}\n\n/** Validate alias format for a given {@link CstType} (prefix + digits, min length 2). */\nexport function validateAliasFormat(alias: string, type: CstType): boolean {\n if (alias.length < 2) {\n return false;\n }\n const prefix = getCstTypePrefix(type);\n if (!alias.startsWith(prefix)) {\n return false;\n }\n if (!/^\\d+$/.exec(alias.substring(prefix.length))) {\n return false;\n }\n return true;\n}\n\n/** Validate new alias against {@link CstType} and {@link RSForm}. */\nexport function validateNewAlias(alias: string, type: CstType, schema: RSForm): boolean {\n if (!validateAliasFormat(alias, type)) {\n return false;\n }\n if (schema.cstByAlias.has(alias)) {\n return false;\n }\n return true;\n}\n\n/** Generate alias for new {@link Constituenta} of a given {@link CstType} for current {@link RSForm}. */\nexport function generateAlias(type: CstType, schema: RSForm, takenAliases: string[] = []): string {\n const prefix = getCstTypePrefix(type);\n let index = schema.items.reduce((prev, cst) => {\n if (cst.cst_type !== type) {\n return prev;\n }\n const next = Number(cst.alias.substring(prefix.length)) + 1;\n return Math.max(prev, next);\n }, 1);\n let alias = `${prefix}${index}`;\n while (takenAliases.includes(alias)) {\n index = index + 1;\n alias = `${prefix}${index}`;\n }\n return alias;\n}\n\n/**\n * Remap formal expressions and terminological entity references in constituent fields.\n * Mutates each element of `items` in place; pass owned or cloned data only.\n */\nexport function applyMappingToConstituents<T extends MappableFields>(\n items: T[],\n mapping: AliasMapping,\n changeAliases: boolean\n): void {\n for (const cst of items) {\n if (changeAliases && cst.alias in mapping) {\n cst.alias = mapping[cst.alias];\n }\n cst.definition_formal = applyAliasMapping(cst.definition_formal, mapping);\n cst.typification_manual = applyTypificationMapping(cst.typification_manual, mapping);\n cst.term_raw = applyEntityReferenceMapping(cst.term_raw, mapping);\n cst.definition_raw = applyEntityReferenceMapping(cst.definition_raw, mapping);\n }\n}\n\n/** Highest numeric alias suffix for {@link type} among {@link items} (0 when none). */\nexport function maxAliasIndex(items: readonly AliasTypedFields[], type: CstType): number {\n const prefix = getCstTypePrefix(type);\n return items.reduce((max, cst) => {\n if (cst.cst_type !== type) {\n return max;\n }\n const index = Number(cst.alias.slice(prefix.length));\n return Number.isFinite(index) ? Math.max(max, index) : max;\n }, 0);\n}\n\n/**\n * Build alias → new-alias mapping that renumbers each type sequentially in list order.\n * Matches backend {@code RSFormCached.reset_aliases}.\n */\nexport function buildSequentialAliasMapping(items: readonly AliasTypedFields[]): AliasMapping {\n const counts: Record<string, number> = {};\n for (const value of Object.values(CstType)) {\n counts[value] = 1;\n }\n const mapping: AliasMapping = {};\n for (const cst of items) {\n const alias = `${getCstTypePrefix(cst.cst_type)}${counts[cst.cst_type]}`;\n counts[cst.cst_type] += 1;\n if (cst.alias !== alias) {\n mapping[cst.alias] = alias;\n }\n }\n return mapping;\n}\n\n/**\n * Allocate fresh aliases for {@link source} constituents being imported into a non-empty receiver.\n * Returns an empty mapping when the receiver has no items (aliases kept as-is).\n */\nexport function allocateImportAliases(\n receiver: readonly AliasTypedFields[],\n source: readonly AliasTypedFields[]\n): AliasMapping {\n if (receiver.length === 0) {\n return {};\n }\n const counts: Record<string, number> = {};\n for (const value of Object.values(CstType)) {\n counts[value] = maxAliasIndex(receiver, value);\n }\n const mapping: AliasMapping = {};\n for (const cst of source) {\n counts[cst.cst_type] += 1;\n mapping[cst.alias] = `${getCstTypePrefix(cst.cst_type)}${counts[cst.cst_type]}`;\n }\n return mapping;\n}\n\n/** Remove alias from expression. */\nexport function removeAliasReference(expression: string, alias: string): string {\n const escaped = alias.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return expression.replaceAll(new RegExp(`\\\\b${escaped}\\\\b`, 'g'), '').trim();\n}\n\n/** Add alias to expression. */\nexport function addAliasReference(expression: string, alias: string): string {\n return expression + ' ' + alias;\n}\n","/**\n * Formal expression analysis against an RSForm schema.\n */\n\nimport { type Graph } from '../../graph';\nimport { type AnalysisFull, RSErrorCode, ValueClass } from '../../rslang';\nimport { extractGlobals } from '../../rslang/api';\nimport { basic, bool, constant } from '../../rslang/semantic/typification';\nimport { formatDependencyCycle, RSDiagnosticCode } from '../diagnostics';\nimport { CstType, type RSForm } from '../rsform';\n\nimport { canHaveFormalDefinition, typeClassForCstType } from './cst-type';\n\nexport function getAnalysisFor(expression: string, cstType: CstType, schema: RSForm, alias?: string): AnalysisFull {\n if (!canHaveFormalDefinition(cstType)) {\n if (expression.trim().length === 0) {\n const fallbackAlias = alias && alias.length > 0 ? alias : 'X0';\n const type = cstType === CstType.BASE ? bool(basic(fallbackAlias)) : bool(constant(fallbackAlias));\n return {\n success: true,\n type,\n valueClass: ValueClass.VALUE,\n errors: [],\n ast: null\n };\n }\n return {\n success: false,\n type: null,\n valueClass: null,\n errors: [\n {\n code: RSErrorCode.definitionNotAllowed,\n from: 0,\n to: Math.max(expression.length, 1),\n params: [cstType, alias ?? '']\n }\n ],\n ast: null\n };\n }\n const analysis = schema.analyzer.checkFull(expression, {\n expected: typeClassForCstType(cstType),\n isDomain: cstType === CstType.STRUCTURED\n });\n return refineAnalysisForDependencyCycles(analysis, expression, schema, alias);\n}\n\n/**\n * When an untyped / bare F·P reference names a constituent on a definition cycle with the\n * current expression, replace that error with {@link RSDiagnosticCode.schemaDependencyCycle}.\n *\n * Covers both semantic `globalNotTyped` (e.g. `F3[σ]`) and parser `globalFuncWithoutArgs`\n * (bare `P1` / `F1` treated as a call without arguments).\n *\n * Uses a draft dependency graph: incoming edges of the edited constituent are taken from\n * `expression`, so Check works before Save.\n */\nexport function refineAnalysisForDependencyCycles(\n analysis: AnalysisFull,\n expression: string,\n schema: RSForm,\n alias?: string\n): AnalysisFull {\n if (analysis.errors.length === 0 || !schema.graph) {\n return analysis;\n }\n\n const currentId = alias ? schema.cstByAlias.get(alias)?.id : undefined;\n const expressionGlobals = extractGlobals(expression);\n const draftGraph =\n currentId !== undefined ? buildDraftDependencyGraph(schema, currentId, expressionGlobals) : schema.graph;\n\n let changed = false;\n const errors = analysis.errors.map(error => {\n if (error.code !== RSErrorCode.globalNotTyped && error.code !== RSErrorCode.globalFuncWithoutArgs) {\n return error;\n }\n const missingAlias = error.params?.[0];\n if (!missingAlias) {\n return error;\n }\n const missing = schema.cstByAlias.get(missingAlias);\n if (!missing) {\n return error;\n }\n const cycleText = resolveDependencyCycleText(schema, draftGraph, currentId, missing.id);\n if (!cycleText) {\n return error;\n }\n changed = true;\n return {\n ...error,\n code: RSErrorCode.schemaDependencyCycle,\n params: [cycleText]\n };\n });\n return changed ? { ...analysis, errors } : analysis;\n}\n\n/**\n * Clone the schema graph and replace dependencies of `currentId` with globals from the\n * expression under check (unsaved draft).\n */\nfunction buildDraftDependencyGraph(schema: RSForm, currentId: number, expressionGlobals: ReadonlySet<string>): Graph {\n const graph = schema.graph.clone();\n const node = graph.at(currentId);\n if (node) {\n for (const parentId of [...node.inputs]) {\n graph.removeEdge(parentId, currentId);\n }\n } else {\n graph.addNode(currentId);\n }\n for (const globalAlias of expressionGlobals) {\n const source = schema.cstByAlias.get(globalAlias);\n if (source) {\n graph.addEdge(source.id, currentId);\n }\n }\n return graph;\n}\n\n/**\n * Resolve formatted cycle text for an untyped global reference in analysis.\n *\n * Uses `graph` (often a draft graph built from the expression under check). When\n * `currentId` is omitted, falls back to schema diagnostics on `missingId`.\n *\n * @returns Closed alias path such as `F3 → P1 → F3`, or `null` when no shared cycle exists.\n */\nfunction resolveDependencyCycleText(\n schema: RSForm,\n graph: Graph,\n currentId: number | undefined,\n missingId: number\n): string | null {\n for (const cycle of graph.findCycles()) {\n const members = new Set(cycle);\n if (!members.has(missingId)) {\n continue;\n }\n if (currentId !== undefined && !members.has(currentId)) {\n continue;\n }\n return formatDependencyCycle(cycle.map(id => schema.cstByID.get(id)?.alias ?? String(id)));\n }\n\n if (currentId === undefined) {\n const cycleDiag = schema.cstByID\n .get(missingId)\n ?.diagnostics.find(item => item.code === RSDiagnosticCode.schemaDependencyCycle);\n return cycleDiag?.params?.[0] ?? null;\n }\n\n return null;\n}\n","/**\n * Attribution remapping helpers for substitution and schema embedding.\n */\n\nimport { type Attribution } from '../rsform';\n\nfunction attributionKey(attr: Attribution): string {\n return `${attr.container}:${attr.attribute}`;\n}\n\n/**\n * Remap attributions when constituents are substituted (original → replacement).\n * Drops self-loops and duplicates. Matches sandbox / backend substitute attribution rewrite.\n */\nexport function remapAttributionsUnderSubstitution(\n attributions: readonly Attribution[],\n origToSub: ReadonlyMap<number, number>\n): Attribution[] {\n const result: Attribution[] = [];\n const seen = new Set<string>();\n\n for (const attr of attributions) {\n if (!origToSub.has(attr.container) && !origToSub.has(attr.attribute)) {\n const key = attributionKey(attr);\n if (!seen.has(key)) {\n seen.add(key);\n result.push({ ...attr });\n }\n continue;\n }\n\n const container = origToSub.get(attr.container) ?? attr.container;\n const attribute = origToSub.get(attr.attribute) ?? attr.attribute;\n if (container === attribute) {\n continue;\n }\n const key = `${container}:${attribute}`;\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n result.push({ container, attribute });\n }\n\n return result;\n}\n\n/**\n * Copy attributions whose both endpoints are in {@link sourceIdSet}, remapping ids via {@link idMap}.\n * Appends onto a clone of {@link existing} with dedupe. Used by schema embedding / insert.\n */\nexport function importAttributions(\n sourceAttributions: readonly Attribution[],\n sourceIdSet: ReadonlySet<number>,\n idMap: Readonly<Record<number, number>>,\n existing: readonly Attribution[] = []\n): Attribution[] {\n const result = existing.map(attr => ({ ...attr }));\n const seen = new Set(result.map(attributionKey));\n\n for (const attr of sourceAttributions) {\n if (!sourceIdSet.has(attr.container) || !sourceIdSet.has(attr.attribute)) {\n continue;\n }\n const container = idMap[attr.container];\n const attribute = idMap[attr.attribute];\n if (container === undefined || attribute === undefined || container === attribute) {\n continue;\n }\n const key = `${container}:${attribute}`;\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n result.push({ container, attribute });\n }\n\n return result;\n}\n\n/** Drop attributions that reference any id in {@link deletedIds}. */\nexport function filterAttributions(\n attributions: readonly Attribution[],\n deletedIds: ReadonlySet<number>\n): Attribution[] {\n return attributions.filter(attr => !deletedIds.has(attr.container) && !deletedIds.has(attr.attribute));\n}\n","/**\n * Formal expression helpers: normalization, templates, status.\n */\n\nimport { type AstNode } from '../../parsing';\nimport { ValueClass } from '../../rslang';\nimport { generateExpressionFromAst, parseRSLangExpression } from '../../rslang/api';\nimport { type ArgumentValue, CstStatus, CstType } from '../rsform';\n\nimport { isBasicConcept } from './cst-type';\n\n/** Infers the status of an expression based on parsing and value information. */\nexport function inferStatus(parse: boolean, value?: ValueClass | null): CstStatus {\n if (!parse) {\n return CstStatus.INCORRECT;\n }\n if (value === null) {\n return CstStatus.INCALCULABLE;\n }\n if (value === ValueClass.PROPERTY) {\n return CstStatus.PROPERTY;\n }\n return CstStatus.VERIFIED;\n}\n\n/** Infers type of constituent for a given template and arguments. */\nexport function inferTemplatedType(templateType: CstType, args: ArgumentValue[]): CstType {\n if (args.length === 0 || args.some(arg => !arg.value)) {\n return templateType;\n } else if (templateType === CstType.PREDICATE) {\n return CstType.AXIOM;\n } else {\n return CstType.TERM;\n }\n}\n\n/**\n * Normalize a RSLang expression for duplicate comparison.\n *\n * Returns `null` for basic concepts without formal definitions. Pass a pre-parsed `ast`\n * when the expression was already analyzed to avoid re-parsing.\n */\nexport function normalizeExpression(expression: string, cst_type: CstType, ast?: AstNode | null): string | null {\n if (isBasicConcept(cst_type) && cst_type !== CstType.AXIOM) {\n return null;\n }\n const parsed = ast ?? parseRSLangExpression(expression);\n let normalized = '';\n if (parsed && !parsed.hasError) {\n normalized = generateExpressionFromAst(parsed, { normalize: true });\n } else {\n normalized = expression;\n }\n normalized = normalized.replace(/\\s+/g, '');\n return normalized === '' ? null : normalized;\n}\n\n/** Checks if given expression is a template. */\nexport function inferTemplate(expression: string): boolean {\n const match = expression.match(/R\\d+/g);\n return (match && match?.length > 0) ?? false;\n}\n\n/** Apply filter based on start item type within an ordered list. */\nexport function applyFilterCategory<T extends { cst_type: CstType }>(start: T, items: readonly T[]): T[] {\n const startIndex = items.indexOf(start);\n if (startIndex === -1) {\n return [];\n }\n const nextCategoryIndex = items.findIndex((cst, index) => index > startIndex && cst.cst_type === CstType.STATEMENT);\n\n return items.filter((_, index) => index >= startIndex && (nextCategoryIndex === -1 || index < nextCategoryIndex));\n}\n","/**\n * Semantic parent/children used when restoring constituent order.\n */\n\nimport { type Graph } from '../../graph';\nimport { extractGlobals, isSimpleExpression, splitTemplateDefinition } from '../../rslang/api';\nimport { CstType } from '../rsform';\n\nimport { isBaseSet, isFunctional } from './cst-type';\nimport { inferTemplate } from './expression';\nimport { type FormalOrderFields, type SemanticRelations } from './types';\n\n/**\n * Infer semantic parent/children used for clustering during restore order.\n * Port of backend {@code SemanticInfo}.\n */\nexport function computeSemanticRelations(items: readonly FormalOrderFields[], graph: Graph<number>): SemanticRelations {\n const byId = new Map(items.map(cst => [cst.id, cst]));\n const byAlias = new Map(items.map(cst => [cst.alias, cst]));\n const isTemplate = new Map<number, boolean>();\n const isSimple = new Map<number, boolean>();\n const parentOf = new Map<number, number>();\n const childrenOf = new Map<number, number[]>();\n\n for (const cst of items) {\n parentOf.set(cst.id, cst.id);\n childrenOf.set(cst.id, []);\n }\n\n function needCheckHead(sources: Set<number>, head: string): boolean {\n if (sources.size === 0) {\n return true;\n }\n if (sources.size !== 1) {\n return false;\n }\n const base = byId.get([...sources][0])!;\n return !isFunctional(base.cst_type) || splitTemplateDefinition(base.definition_formal).head !== head;\n }\n\n function extractSources(target: FormalOrderFields): Set<number> {\n const sources = new Set<number>();\n if (!isFunctional(target.cst_type)) {\n for (const parentId of graph.at(target.id)?.inputs ?? []) {\n if (!(isTemplate.get(parentId) && isSimple.get(parentId))) {\n sources.add(parentOf.get(parentId) ?? parentId);\n }\n }\n return sources;\n }\n\n const expression = splitTemplateDefinition(target.definition_formal);\n for (const alias of extractGlobals(expression.body)) {\n const parent = byAlias.get(alias);\n if (!parent) {\n continue;\n }\n if (!(isTemplate.get(parent.id) && isSimple.get(parent.id))) {\n sources.add(parentOf.get(parent.id) ?? parent.id);\n }\n }\n if (needCheckHead(sources, expression.head)) {\n for (const alias of extractGlobals(expression.head)) {\n const parent = byAlias.get(alias);\n if (!parent) {\n continue;\n }\n if (!isBaseSet(parent.cst_type) && !(isTemplate.get(parent.id) && isSimple.get(parent.id))) {\n sources.add(parentOf.get(parent.id) ?? parent.id);\n }\n }\n }\n return sources;\n }\n\n function inferSimple(target: FormalOrderFields): boolean {\n if (target.cst_type === CstType.STRUCTURED || isBaseSet(target.cst_type)) {\n return false;\n }\n const dependencies = graph.at(target.id)?.inputs ?? [];\n if (dependencies.some(id => isTemplate.get(id) && !isSimple.get(id))) {\n return false;\n }\n const expression = isFunctional(target.cst_type)\n ? splitTemplateDefinition(target.definition_formal).body\n : target.definition_formal;\n return isSimpleExpression(expression);\n }\n\n for (const cstId of graph.topologicalOrder()) {\n const cst = byId.get(cstId);\n if (!cst) {\n continue;\n }\n isTemplate.set(cstId, inferTemplate(cst.definition_formal));\n isSimple.set(cstId, inferSimple(cst));\n if (!isSimple.get(cstId) || cst.cst_type === CstType.STRUCTURED) {\n continue;\n }\n const sources = extractSources(cst);\n if (sources.size !== 1) {\n continue;\n }\n const parentId = [...sources][0];\n const parent = byId.get(parentId);\n if (!parent || isBaseSet(parent.cst_type)) {\n continue;\n }\n parentOf.set(cstId, parentId);\n childrenOf.get(parentId)!.push(cstId);\n }\n\n return { parentOf, childrenOf };\n}\n","/**\n * Formal dependency graph and declaration-order restore for RSForm constituents.\n */\n\nimport { Graph } from '../../graph';\nimport { extractGlobals } from '../../rslang/api';\nimport { CstType } from '../rsform';\n\nimport { computeSemanticRelations } from './semantic-relations';\nimport { type FormalOrderFields, type SemanticRelations } from './types';\n\n/**\n * Build the formal dependency graph: supplier → dependent.\n * Matches backend {@code RSForm.graph_formal}.\n */\nexport function buildFormalDependencyGraph(items: readonly FormalOrderFields[]): Graph<number> {\n const graph = new Graph<number>();\n const byAlias = new Map(items.map(cst => [cst.alias, cst]));\n for (const cst of items) {\n graph.addNode(cst.id);\n }\n for (const cst of items) {\n for (const alias of extractGlobals(cst.definition_formal)) {\n const supplier = byAlias.get(alias);\n if (supplier) {\n graph.addEdge(supplier.id, cst.id);\n }\n }\n }\n return graph;\n}\n\n/**\n * Reorder constituents: formal topology hard, semantic children sticky when ready,\n * otherwise stable against type/kernel preferred ranks.\n *\n * One Kahn pass over the formal dependency graph.\n */\nexport function restoreConstituentOrder<T extends FormalOrderFields>(\n items: readonly T[],\n graph: Graph<number> = buildFormalDependencyGraph(items),\n relations: SemanticRelations = computeSemanticRelations(items, graph)\n): T[] {\n if (items.length <= 1) {\n return [...items];\n }\n\n const byId = new Map(items.map(cst => [cst.id, cst]));\n const preferred = kernelPriority(items, graph, relations.parentOf);\n const rank = new Map(preferred.map((cst, index) => [cst.id, index]));\n\n const remainingInputs = new Map<number, number>();\n for (const cst of preferred) {\n const inputs = graph.at(cst.id)?.inputs ?? [];\n remainingInputs.set(\n cst.id,\n inputs.reduce((count, src) => count + (rank.has(src) ? 1 : 0), 0)\n );\n }\n\n const ready = new Set<number>();\n for (const cst of preferred) {\n if ((remainingInputs.get(cst.id) ?? 0) === 0) {\n ready.add(cst.id);\n }\n }\n\n const children = new Map<number, number[]>();\n for (const cst of preferred) {\n children.set(\n cst.id,\n (relations.childrenOf.get(cst.id) ?? []).filter(childId => rank.has(childId))\n );\n }\n\n const result: T[] = [];\n const pendingChildren: number[] = [];\n\n function enqueueSticky(candidateIds: readonly number[]): void {\n const sticky = candidateIds.filter(childId => ready.has(childId) && !pendingChildren.includes(childId));\n sticky.sort((left, right) => (rank.get(left) ?? 0) - (rank.get(right) ?? 0));\n pendingChildren.push(...sticky);\n }\n\n function pickReady(): number {\n while (pendingChildren.length > 0) {\n const childId = pendingChildren.shift()!;\n if (ready.has(childId)) {\n return childId;\n }\n }\n let best = -1;\n let bestRank = Number.POSITIVE_INFINITY;\n for (const nodeId of ready) {\n const nodeRank = rank.get(nodeId) ?? Number.POSITIVE_INFINITY;\n if (nodeRank < bestRank) {\n best = nodeId;\n bestRank = nodeRank;\n }\n }\n return best;\n }\n\n while (ready.size > 0 || pendingChildren.length > 0) {\n if (ready.size === 0) {\n pendingChildren.length = 0;\n continue;\n }\n const nodeId = pickReady();\n ready.delete(nodeId);\n result.push(byId.get(nodeId)!);\n\n for (const dependentId of graph.at(nodeId)?.outputs ?? []) {\n if (!remainingInputs.has(dependentId)) {\n continue;\n }\n const next = (remainingInputs.get(dependentId) ?? 0) - 1;\n remainingInputs.set(dependentId, next);\n if (next === 0) {\n ready.add(dependentId);\n }\n }\n\n enqueueSticky(children.get(nodeId) ?? []);\n }\n\n if (result.length < preferred.length) {\n const placed = new Set(result.map(cst => cst.id));\n for (const cst of preferred) {\n if (!placed.has(cst.id)) {\n result.push(cst);\n }\n }\n }\n\n return result;\n}\n\nfunction kernelPriority<T extends FormalOrderFields>(\n items: readonly T[],\n graph: Graph<number>,\n parentOf: Map<number, number>\n): T[] {\n const byId = new Map(items.map(cst => [cst.id, cst]));\n const seen = new Set<number>();\n const result: T[] = [];\n\n function push(cst: T): void {\n if (seen.has(cst.id)) {\n return;\n }\n seen.add(cst.id);\n result.push(cst);\n }\n\n for (const cst of items) {\n if (cst.cst_type === CstType.BASE) {\n push(cst);\n }\n }\n for (const cst of items) {\n if (cst.cst_type === CstType.CONSTANT) {\n push(cst);\n }\n }\n for (const cst of items) {\n if ((graph.at(cst.id)?.inputs.length ?? 0) === 0) {\n push(cst);\n }\n }\n\n const kernelSeeds = items\n .filter(cst => {\n const parentId = parentOf.get(cst.id) ?? cst.id;\n const parent = byId.get(parentId);\n return (\n cst.cst_type === CstType.STRUCTURED || cst.cst_type === CstType.AXIOM || parent?.cst_type === CstType.STRUCTURED\n );\n })\n .map(cst => cst.id);\n const kernel = new Set<number>([...kernelSeeds, ...graph.expandAllInputs(kernelSeeds)]);\n for (const cst of items) {\n if (kernel.has(cst.id)) {\n push(cst);\n }\n }\n for (const cst of items) {\n push(cst);\n }\n return result;\n}\n","/**\n * Schema-level statistics and issue flags.\n */\n\nimport { TypeID, type Typification, ValueClass } from '../../rslang';\nimport { hasCstDiagnostic, RSDiagnosticCode } from '../diagnostics';\nimport { CstStatus, CstType, type RSForm, type RSFormStats } from '../rsform';\n\nimport { isBasicConcept, isLogical } from './cst-type';\nimport { type BasicTextCheckFields, type SchemaIssueFields, type StructureCapableFields } from './types';\n\n/** Checks if an item is a schema issue. */\nexport function isSchemaIssue(cst: SchemaIssueFields): boolean {\n return (\n (cst.diagnostics?.length ?? 0) > 0 || cst.status === CstStatus.INCORRECT || cst.status === CstStatus.INCALCULABLE\n );\n}\n\n/** Calculate statistics for {@link RSForm}. */\nexport function calculateSchemaStats(target: RSForm): RSFormStats {\n const stats: RSFormStats = {\n count_all: target.items.length,\n count_crucial: 0,\n step_complexity: 0,\n count_problematic: 0,\n count_homonyms: 0,\n count_formal_duplicates: 0,\n count_missing_basic_text: 0,\n count_type_mismatch: 0,\n count_incorrect: 0,\n count_property: 0,\n count_incalculable: 0,\n count_inherited: 0,\n count_text_term: 0,\n count_definition: 0,\n count_convention: 0,\n count_comment: 0,\n count_base: 0,\n count_constant: 0,\n count_structured: 0,\n count_axiom: 0,\n count_term: 0,\n count_function: 0,\n count_predicate: 0,\n count_statement: 0,\n count_nominal: 0\n };\n\n for (const cst of target.items) {\n if (cst.crucial) {\n stats.count_crucial += 1;\n }\n stats.step_complexity += calculateStepComplexity(cst);\n\n if (isSchemaIssue(cst)) {\n stats.count_problematic += 1;\n }\n if (hasCstDiagnostic(cst, RSDiagnosticCode.schemaHomonym)) {\n stats.count_homonyms += 1;\n }\n if (hasCstDiagnostic(cst, RSDiagnosticCode.schemaFormalDuplicate)) {\n stats.count_formal_duplicates += 1;\n }\n if (isMissingBasicText(cst)) {\n stats.count_missing_basic_text += 1;\n }\n if (cst.is_type_mismatch) {\n stats.count_type_mismatch += 1;\n }\n if (cst.status === CstStatus.INCORRECT) {\n stats.count_incorrect += 1;\n }\n if (cst.analysis?.valueClass === ValueClass.PROPERTY) {\n stats.count_property += 1;\n }\n if (cst.analysis?.success && cst.analysis.valueClass === null) {\n stats.count_incalculable += 1;\n }\n if (cst.is_inherited) {\n stats.count_inherited += 1;\n }\n if (cst.term_raw) {\n stats.count_text_term += 1;\n }\n if (cst.definition_raw) {\n stats.count_definition += 1;\n }\n if (isBasicConcept(cst.cst_type) && cst.convention) {\n stats.count_convention += 1;\n }\n if (!isBasicConcept(cst.cst_type) && !cst.convention) {\n stats.count_comment += 1;\n }\n\n switch (cst.cst_type) {\n case CstType.BASE:\n stats.count_base += 1;\n break;\n case CstType.CONSTANT:\n stats.count_constant += 1;\n break;\n case CstType.STRUCTURED:\n stats.count_structured += 1;\n break;\n case CstType.AXIOM:\n stats.count_axiom += 1;\n break;\n case CstType.TERM:\n stats.count_term += 1;\n break;\n case CstType.FUNCTION:\n stats.count_function += 1;\n break;\n case CstType.PREDICATE:\n stats.count_predicate += 1;\n break;\n case CstType.STATEMENT:\n stats.count_statement += 1;\n break;\n case CstType.NOMINAL:\n stats.count_nominal += 1;\n break;\n }\n }\n\n return stats;\n}\n\nfunction calculateStepComplexity(cst: StructureCapableFields): number {\n if (cst.cst_type === CstType.AXIOM || cst.cst_type === CstType.NOMINAL || !isBasicConcept(cst.cst_type)) {\n return 0;\n }\n if (cst.cst_type === CstType.BASE || cst.cst_type === CstType.CONSTANT || !cst.effectiveType) {\n return 1;\n }\n\n const type = cst.effectiveType as Typification;\n return calculateTypificationComplexity(type) + 1;\n}\n\nfunction calculateTypificationComplexity(type: Typification): number {\n switch (type.typeID) {\n case TypeID.basic:\n case TypeID.integer:\n case TypeID.anyTypification:\n return 0;\n case TypeID.tuple:\n return (\n type.factors.length + type.factors.reduce((sum, factor) => sum + calculateTypificationComplexity(factor), 0)\n );\n case TypeID.collection:\n if (type.base.typeID === TypeID.tuple) {\n let sum = 0;\n type.base.factors.forEach(factor => {\n sum += calculateTypificationComplexity(factor);\n });\n return sum + type.base.factors.length;\n } else if (type.base.typeID === TypeID.collection) {\n return calculateTypificationComplexity(type.base) + 1;\n }\n return 0;\n }\n}\n\n/** Non-logical basic concept missing convention and/or resolved term (trimmed). */\nfunction isMissingBasicText(cst: BasicTextCheckFields): boolean {\n if (!isBasicConcept(cst.cst_type) || isLogical(cst.cst_type)) {\n return false;\n }\n return !cst.convention.trim() || !cst.term_resolved.trim();\n}\n","/**\n * Structure-path helpers for spawned constituents.\n */\n\nimport { TypeID, type TypePath, type Typification } from '../../rslang';\nimport { isTypification } from '../../rslang/semantic/typification';\nimport { applyPath } from '../../rslang/semantic/typification-api';\nimport { type Constituenta, type RSForm } from '../rsform';\n\nimport { type SpawnPathFields, type StructureCapableFields } from './types';\n\n/**\n * Id to pass as `insert_after` when creating a new {@link Constituenta} spawned by `targetId`:\n * after the last existing child of that spawner, or after the spawner itself if none.\n */\nexport function inferNewSpawnPosition(schema: RSForm, targetId: number): number {\n let last: number | null = null;\n for (const cst of schema.items) {\n if (cst.spawner === targetId) {\n last = cst.id;\n }\n }\n return last ?? targetId;\n}\n\n/** Finds schema item by absolute structure path under `targetId`. */\nexport function findCstByStructure(schema: RSForm, target: { id: number }, path: TypePath): Constituenta | null {\n const byId = schema.cstByID ?? new Map(schema.items.map(item => [item.id, item]));\n for (const cst of schema.items) {\n if (!cst.spawner_path) {\n continue;\n }\n const absolutePath = resolveAbsoluteSpawnerPath(cst, target.id, byId);\n if (absolutePath?.length === path.length && absolutePath.every((v, i) => v === path[i])) {\n return cst;\n }\n }\n return null;\n}\n\n/** Retrieves name for piece of target structure. */\nexport function getStructureName(\n schema: RSForm,\n target: StructureCapableFields & { id: number },\n path: TypePath\n): string {\n const representation = findCstByStructure(schema, target, path);\n if (representation) {\n return `${representation.alias}: ${representation.term_resolved}`;\n }\n if (!isTypification(target.effectiveType)) {\n return '';\n }\n const type = applyPath(target.effectiveType as Typification, path);\n if (type?.typeID === TypeID.basic) {\n const cst = schema.cstByAlias.get(type.baseID);\n if (cst?.term_resolved) {\n return `${cst.alias}: ${cst.term_resolved}`;\n }\n }\n return '';\n}\n\nfunction resolveAbsoluteSpawnerPath(\n cst: SpawnPathFields,\n targetId: number,\n byId: Map<number, SpawnPathFields>\n): TypePath | null {\n if (!cst.spawner_path || cst.spawner == null) {\n return null;\n }\n if (cst.spawner === targetId) {\n return cst.spawner_path;\n }\n\n const visited = new Set<number>([cst.id]);\n let currentPath: number[] = [...cst.spawner_path];\n let currentSpawnerId: number | null = cst.spawner;\n\n while (currentSpawnerId != null) {\n if (currentSpawnerId === targetId) {\n return currentPath as TypePath;\n }\n if (visited.has(currentSpawnerId)) {\n return null;\n }\n visited.add(currentSpawnerId);\n\n const parent = byId.get(currentSpawnerId);\n if (!parent?.spawner_path || parent.spawner == null) {\n return null;\n }\n\n currentPath = [...parent.spawner_path, ...currentPath];\n currentSpawnerId = parent.spawner;\n }\n\n return null;\n}\n","/**\n * Constituenta substitution and post-import substitution remapping.\n */\n\nimport { type AliasMapping } from '../../rslang/api';\nimport { type Attribution, type Substitution } from '../rsform';\n\nimport { applyMappingToConstituents, type MappableFields } from './alias';\nimport { remapAttributionsUnderSubstitution } from './attribution';\n\n/** Result of applying substitutions to a schema fragment. */\nexport interface SubstitutionResult<T> {\n items: T[];\n attributions: Attribution[];\n deletedIds: Set<number>;\n /** Replacement constituent ids (survivors referenced by substitutions). */\n replacementIds: number[];\n}\n\n/**\n * Apply constituenta substitutions: remap attributions, drop originals, rewrite aliases in survivors.\n * Does not resolve texts — call {@link resolveAllConstituentTexts} afterwards.\n */\nexport function applyConstituentSubstitutions<T extends MappableFields & { id: number; alias: string }>(\n items: readonly T[],\n attributions: readonly Attribution[],\n substitutions: readonly Substitution[]\n): SubstitutionResult<T> {\n if (substitutions.length === 0) {\n return {\n items: [...items],\n attributions: attributions.map(attr => ({ ...attr })),\n deletedIds: new Set(),\n replacementIds: []\n };\n }\n\n const byId = new Map(items.map(cst => [cst.id, cst]));\n const mapping: AliasMapping = {};\n const deletedIds = new Set<number>();\n const origToSub = new Map<number, number>();\n const replacementIds: number[] = [];\n\n for (const { original, substitution } of substitutions) {\n const originalCst = byId.get(original);\n const substitutionCst = byId.get(substitution);\n if (!originalCst || !substitutionCst) {\n throw new Error(`applyConstituentSubstitutions: unknown constituenta ${original} -> ${substitution}`);\n }\n mapping[originalCst.alias] = substitutionCst.alias;\n deletedIds.add(original);\n origToSub.set(original, substitution);\n replacementIds.push(substitution);\n }\n\n const nextItems = items.filter(cst => !deletedIds.has(cst.id));\n applyMappingToConstituents(nextItems, mapping, false);\n\n return {\n items: nextItems,\n attributions: remapAttributionsUnderSubstitution(attributions, origToSub),\n deletedIds,\n replacementIds\n };\n}\n\n/**\n * Remap substitution endpoints after source constituents were inserted under new ids.\n * If {@link original} was imported, map it; otherwise map {@link substitution}.\n */\nexport function remapSubstitutionsAfterImport(\n substitutions: readonly Substitution[],\n sourceIdSet: ReadonlySet<number>,\n idMap: Readonly<Record<number, number>>\n): Substitution[] {\n return substitutions.map(sub => {\n if (sourceIdSet.has(sub.original)) {\n return { original: idMap[sub.original], substitution: sub.substitution };\n }\n return { original: sub.original, substitution: idMap[sub.substitution] };\n });\n}\n","/**\n * Cascade resolution of constituenta term/definition entity references.\n * Matches backend {@code RSForm.resolve_all_text} / {@code resolve_term_change}.\n */\n\nimport { type TermContext } from '../../cctext/language';\nimport { extractEntities, parseGrammemes, resolveTextReferences } from '../../cctext/language-api';\nimport { Graph } from '../../graph';\n\nimport { type TextResolvableFields } from './types';\n\n/** Options controlling which texts to re-resolve after an edit. */\nexport interface TextChangeOptions {\n termChanged: boolean;\n termRawChanged: boolean;\n definitionRawChanged: boolean;\n clearTargetForms: boolean;\n}\n\n/** Build term-reference graph: referenced constituent → dependent (backend {@code graph_term}). */\nexport function buildTermReferenceGraph(items: readonly TextResolvableFields[]): Graph<number> {\n return buildReferenceGraph(items, 'term_raw');\n}\n\n/** Build definition-reference graph: referenced constituent → dependent (backend {@code graph_text}). */\nexport function buildDefinitionReferenceGraph(items: readonly TextResolvableFields[]): Graph<number> {\n return buildReferenceGraph(items, 'definition_raw');\n}\n\n/** Resolve all term and definition texts in topological order. Mutates items in place. */\nexport function resolveAllConstituentTexts(items: TextResolvableFields[]): void {\n const graphTerm = buildTermReferenceGraph(items);\n const idToItem = new Map(items.map(item => [item.id, item]));\n const context = buildTermContext(items);\n\n for (const id of graphTerm.topologicalOrder()) {\n const row = idToItem.get(id);\n if (!row) {\n continue;\n }\n const resolved = resolveTextReferences(row.term_raw, context);\n if (resolved !== row.term_resolved) {\n row.term_resolved = resolved;\n row.term_forms = [];\n context[row.alias] = { nominal: row.term_resolved, forms: [] };\n }\n }\n\n for (const row of items) {\n row.definition_resolved = resolveTextReferences(row.definition_raw, context);\n }\n}\n\n/**\n * Resolve texts after a single constituent change, cascading dependents when the term changed.\n * Mutates items in place.\n */\nexport function resolveConstituentTextChange(\n items: TextResolvableFields[],\n targetID: number,\n options: TextChangeOptions\n): void {\n const idToItem = new Map(items.map(item => [item.id, item]));\n const target = idToItem.get(targetID);\n if (!target) {\n throw new Error(`resolveConstituentTextChange: unknown target ${targetID}`);\n }\n\n const context = buildTermContext(items);\n if (options.termRawChanged) {\n target.term_resolved = resolveTextReferences(target.term_raw, context);\n if (options.clearTargetForms) {\n target.term_forms = [];\n }\n context[target.alias] = toContextItem(target);\n } else if (options.termChanged) {\n context[target.alias] = toContextItem(target);\n }\n\n if (options.definitionRawChanged && !options.termChanged) {\n target.definition_resolved = resolveTextReferences(target.definition_raw, context);\n }\n\n if (!options.termChanged) {\n return;\n }\n\n const graphTerm = buildTermReferenceGraph(items);\n const graphText = buildDefinitionReferenceGraph(items);\n const expansion = graphTerm.expandAllOutputs([targetID]);\n const expansionSet = new Set(expansion);\n\n for (const id of graphTerm.topologicalOrder()) {\n if (!expansionSet.has(id)) {\n continue;\n }\n const expanded = idToItem.get(id);\n if (!expanded) {\n continue;\n }\n const resolved = resolveTextReferences(expanded.term_raw, context);\n if (resolved !== expanded.term_resolved) {\n expanded.term_resolved = resolved;\n expanded.term_forms = [];\n context[expanded.alias] = { nominal: expanded.term_resolved, forms: [] };\n }\n }\n\n const updateDefs = new Set([targetID, ...expansion, ...graphText.expandAllOutputs([targetID, ...expansion])]);\n for (const item of items) {\n if (updateDefs.has(item.id)) {\n item.definition_resolved = resolveTextReferences(item.definition_raw, context);\n }\n }\n}\n\n// ====== Internals =======\n\nfunction buildReferenceGraph(\n items: readonly TextResolvableFields[],\n field: 'definition_raw' | 'term_raw'\n): Graph<number> {\n const graph = new Graph<number>();\n const idByAlias = new Map(items.map(row => [row.alias, row.id]));\n for (const row of items) {\n graph.addNode(row.id);\n }\n for (const row of items) {\n for (const entity of extractEntities(row[field])) {\n const source = idByAlias.get(entity);\n if (source !== undefined) {\n graph.addEdge(source, row.id);\n }\n }\n }\n return graph;\n}\n\nfunction buildTermContext(items: readonly TextResolvableFields[]): TermContext {\n const context: TermContext = {};\n for (const row of items) {\n context[row.alias] = toContextItem(row);\n }\n return context;\n}\n\nfunction toContextItem(row: TextResolvableFields): TermContext[string] {\n return {\n nominal: row.term_resolved,\n forms: row.term_forms.map(form => ({ text: form.text, grams: parseGrammemes(form.tags) }))\n };\n}\n","/**\n * Schema embedding (synthesis): insert constituents from a source schema into a receiver,\n * then apply an identification (substitution) table.\n *\n * Mirrors backend `inline_synthesis` / `insert_from` + `substitute`\n * (Portal UI: «Встраивание схемы»).\n */\n\nimport { type AliasMapping } from '../../rslang/api';\nimport { type LibraryItem } from '../library';\nimport { type Attribution, type CstType, type RSForm, type Substitution } from '../rsform';\n\nimport { allocateImportAliases, applyMappingToConstituents, type MappableFields } from './alias';\nimport { importAttributions } from './attribution';\nimport { applyConstituentSubstitutions, remapSubstitutionsAfterImport } from './substitution';\nimport { resolveAllConstituentTexts } from './text-resolution';\nimport { type AliasTypedFields, type TextResolvableFields } from './types';\n\n/** Field intersection required for embedding / synthesis transforms. */\nexport type SynthesizableFields = MappableFields &\n TextResolvableFields &\n AliasTypedFields & {\n id: number;\n alias: string;\n cst_type: CstType;\n };\n\n/** Input for {@link inlineSynthesis}. */\nexport interface InlineSynthesisInput<T extends SynthesizableFields> {\n /** Receiver schema constituents (order preserved; imports append). */\n receiverItems: readonly T[];\n /** Receiver attributions (default empty). */\n receiverAttributions?: readonly Attribution[];\n /**\n * Source constituents to insert (already filtered to the desired subset).\n * Cloned; originals are not mutated.\n */\n sourceItems: readonly T[];\n /** Source attributions whose both endpoints are among {@link sourceItems}. */\n sourceAttributions?: readonly Attribution[];\n /**\n * Identification table using pre-import ids:\n * one endpoint is a source id, the other a receiver id\n * (same rules as backend embedding / InlineSynthesis).\n */\n substitutions?: readonly Substitution[];\n /** Next free numeric id for inserted constituents. */\n nextId: number;\n}\n\n/** Result of {@link inlineSynthesis}. */\nexport interface InlineSynthesisResult<T extends SynthesizableFields> {\n items: T[];\n attributions: Attribution[];\n /** Updated next-id after inserts. */\n nextId: number;\n /** Source id → inserted id. */\n idMap: Record<number, number>;\n /** Alias remapping applied to imported constituents (empty when receiver was empty). */\n aliasMapping: AliasMapping;\n /** Ids removed by substitutions. */\n deletedIds: Set<number>;\n /** Ids of newly inserted constituents (before any were deleted by substitutions). */\n insertedIds: number[];\n /** Survivor ids referenced by applied substitutions. */\n replacementIds: number[];\n}\n\n/**\n * Embed {@link InlineSynthesisInput.sourceItems} into the receiver and apply substitutions.\n * Resolves term/definition entity references on the result.\n * Does not mutate inputs.\n */\nexport function inlineSynthesis<T extends SynthesizableFields>(\n input: InlineSynthesisInput<T>\n): InlineSynthesisResult<T> {\n const sourceItems = input.sourceItems;\n if (sourceItems.length === 0) {\n return {\n items: input.receiverItems.map(item => structuredClone(item)),\n attributions: (input.receiverAttributions ?? []).map(attr => ({ ...attr })),\n nextId: input.nextId,\n idMap: {},\n aliasMapping: {},\n deletedIds: new Set(),\n insertedIds: [],\n replacementIds: []\n };\n }\n\n const receiverItems = input.receiverItems.map(item => structuredClone(item));\n let attributions = (input.receiverAttributions ?? []).map(attr => ({ ...attr }));\n const aliasMapping = allocateImportAliases(receiverItems, sourceItems);\n const idMap: Record<number, number> = {};\n const inserted: T[] = [];\n const sourceIdSet = new Set(sourceItems.map(cst => cst.id));\n let nextId = input.nextId;\n\n for (const cst of sourceItems) {\n const newId = nextId;\n nextId += 1;\n idMap[cst.id] = newId;\n\n const cloned = structuredClone(cst);\n cloned.id = newId;\n if (Object.keys(aliasMapping).length > 0) {\n cloned.alias = aliasMapping[cst.alias];\n applyMappingToConstituents([cloned], aliasMapping, false);\n }\n inserted.push(cloned);\n }\n\n attributions = importAttributions(input.sourceAttributions ?? [], sourceIdSet, idMap, attributions);\n const items = receiverItems.concat(inserted);\n resolveAllConstituentTexts(items);\n\n const substitutions = input.substitutions ?? [];\n if (substitutions.length === 0) {\n return {\n items,\n attributions,\n nextId,\n idMap,\n aliasMapping,\n deletedIds: new Set(),\n insertedIds: inserted.map(cst => cst.id),\n replacementIds: []\n };\n }\n\n const remapped = remapSubstitutionsAfterImport(substitutions, sourceIdSet, idMap);\n const substituted = applyConstituentSubstitutions(items, attributions, remapped);\n resolveAllConstituentTexts(substituted.items);\n\n return {\n items: substituted.items,\n attributions: substituted.attributions,\n nextId,\n idMap,\n aliasMapping,\n deletedIds: substituted.deletedIds,\n insertedIds: inserted.map(cst => cst.id),\n replacementIds: substituted.replacementIds\n };\n}\n\n/** Sorts library items relevant for schema embedding with specified {@link RSForm}. */\nexport function sortItemsForInlineSynthesis(receiver: RSForm, items: readonly LibraryItem[]): LibraryItem[] {\n const result = items.filter(item => item.location === receiver.location);\n const included = new Set(result);\n for (const item of items) {\n if (item.visible && item.owner === receiver.owner && !included.has(item)) {\n result.push(item);\n included.add(item);\n }\n }\n for (const item of items) {\n if (item.visible && !included.has(item)) {\n result.push(item);\n included.add(item);\n }\n }\n for (const item of items) {\n if (!included.has(item)) {\n result.push(item);\n included.add(item);\n }\n }\n return result;\n}\n","/**\n * Pure constituenta list transforms: reorder, move, insert position.\n */\n\n/** Rebuild an item list following {@link orderedIds}. Throws if an id is missing. */\nexport function reorderItemsByIds<T extends { id: number }>(items: readonly T[], orderedIds: readonly number[]): T[] {\n const byId = new Map(items.map(item => [item.id, item]));\n return orderedIds.map(id => {\n const item = byId.get(id);\n if (!item) {\n throw new Error(`reorderItemsByIds: missing id ${id}`);\n }\n return item;\n });\n}\n\n/**\n * Move a subset of ids within an ordered id list.\n * {@link moveTo} is clamped to `[0, rest.length]` (index among non-moving items).\n */\nexport function moveIdsInOrder(ids: readonly number[], moving: readonly number[], moveTo: number): number[] {\n const movingSet = new Set(moving);\n const rest = ids.filter(id => !movingSet.has(id));\n const movingItems = ids.filter(id => movingSet.has(id));\n const clamped = Math.max(0, Math.min(moveTo, rest.length));\n return [...rest.slice(0, clamped), ...movingItems, ...rest.slice(clamped)];\n}\n\n/** Insert {@link item} after {@link insertAfter}, or append when null/undefined/missing. Mutates {@link items}. */\nexport function insertItemAfter<T extends { id: number }>(\n items: T[],\n item: T,\n insertAfter: number | null | undefined\n): void {\n if (insertAfter === null || insertAfter === undefined) {\n items.push(item);\n return;\n }\n const idx = items.findIndex(row => row.id === insertAfter);\n const insertAt = idx === -1 ? items.length : idx + 1;\n items.splice(insertAt, 0, item);\n}\n","/**\n * Module: Compact diagnostics for constituents (schema and model issue codes).\n */\n\nimport { type Graph } from '../graph';\nimport { type ExpressionType } from '../rslang';\nimport { labelType } from '../rslang/labels';\n\nimport { type BasicTextCheckFields } from './rsform-api/types';\nimport { type Constituenta, type CstType } from './rsform';\nimport { isBasicConcept, isLogical } from './rsform-api';\nimport { EvalStatus } from './rsmodel';\n\n/** Origin of a diagnostic. */\nexport const DiagnosticKind = {\n EXPRESSION: 'expression',\n SCHEMA: 'schema',\n MODEL: 'model'\n} as const;\nexport type DiagnosticKind = (typeof DiagnosticKind)[keyof typeof DiagnosticKind];\n\n/** Schema, model, and substitution-table diagnostic codes (same numeric format as {@link RSErrorCode}). */\nexport const RSDiagnosticCode = {\n schemaHomonym: 0x8901,\n schemaFormalDuplicate: 0x8902,\n schemaMissingConvention: 0x8903,\n schemaMissingTerm: 0x8904,\n schemaTypeMismatch: 0x8905,\n schemaDependencyCycle: 0x8906,\n\n modelEmpty: 0x8910,\n modelAxiomFalse: 0x8911,\n modelInvalidData: 0x8912,\n modelEvalFail: 0x8913,\n\n substitutionInvalidIDs: 0x8920,\n substitutionIncorrectCst: 0x8921,\n substitutionInvalidClasses: 0x8922,\n substitutionInvalidBasic: 0x8923,\n substitutionInvalidConstant: 0x8924,\n substitutionTypificationCycle: 0x8925,\n substitutionBaseNotSet: 0x8926,\n substitutionUnequalTypification: 0x8927,\n /** Non-blocking warning: formal definitions differ after mapping. */\n substitutionUnequalExpressions: 0x2928,\n substitutionUnequalArgsCount: 0x8929,\n substitutionUnequalArgs: 0x892a,\n substitutionInvalidNominal: 0x892b\n} as const;\nexport type RSDiagnosticCode = (typeof RSDiagnosticCode)[keyof typeof RSDiagnosticCode];\n\n/** Compact diagnostic stored on {@link Constituenta} after schema loading. */\nexport interface CstDiagnostic {\n kind: DiagnosticKind;\n code: number;\n /** Positional message arguments (per-code; homonyms/duplicates use `[aliases]`). */\n params?: readonly string[];\n}\n\n/** Whether an item has a schema/model diagnostic with the given code. */\nexport function hasCstDiagnostic(\n cst: { diagnostics?: readonly CstDiagnostic[] | null },\n code: RSDiagnosticCode\n): boolean {\n return cst.diagnostics?.some(item => item.code === code) ?? false;\n}\n\n/**\n * Populate `diagnostics` on each constituent (homonyms, duplicates, metadata, type mismatch, cycles).\n *\n * Requires normalized formal definitions for duplicate detection (same as Portal loader).\n * When `graph` is provided, dependency cycles are reported as {@link RSDiagnosticCode.schemaDependencyCycle}.\n */\nexport function assignSchemaDiagnostics(\n items: Constituenta[],\n resolveAlias: (id: number) => string,\n normalizedDefinitions: ReadonlyMap<number, string>,\n graph?: Graph\n): void {\n const homonymById = detectHomonymDiagnostics(items, resolveAlias);\n const duplicateById = detectFormalDuplicateDiagnostics(items, resolveAlias, normalizedDefinitions);\n const cycleById = graph ? detectDependencyCycleDiagnostics(graph, resolveAlias) : new Map<number, CstDiagnostic>();\n\n for (const cst of items) {\n const diagnostics: CstDiagnostic[] = [];\n const cycle = cycleById.get(cst.id);\n if (cycle) {\n diagnostics.push(cycle);\n }\n const homonym = homonymById.get(cst.id);\n if (homonym) {\n diagnostics.push(homonym);\n }\n const duplicate = duplicateById.get(cst.id);\n if (duplicate) {\n diagnostics.push(duplicate);\n }\n diagnostics.push(...collectLocalSchemaDiagnostics(cst));\n cst.diagnostics = diagnostics;\n }\n}\n\n/**\n * Format a closed dependency cycle as `A → B → A`.\n *\n * Rotates the path to start at the lexicographically smallest alias so the same\n * cycle always renders identically regardless of graph traversal order.\n *\n * @param aliases Closed or open alias path from {@link Graph.findCycles}.\n * @returns Human-readable cycle text joined with ` → `.\n */\nexport function formatDependencyCycle(aliases: readonly string[]): string {\n if (aliases.length < 2) {\n return aliases.join(' → ');\n }\n\n const closed = aliases[0] === aliases[aliases.length - 1];\n const open = closed ? aliases.slice(0, -1) : [...aliases];\n if (open.length === 0) {\n return aliases.join(' → ');\n }\n\n let bestStart = 0;\n for (let index = 1; index < open.length; index++) {\n const alias = open[index];\n const bestAlias = open[bestStart];\n if (alias !== undefined && bestAlias !== undefined && alias < bestAlias) {\n bestStart = index;\n }\n }\n const rotated = [...open.slice(bestStart), ...open.slice(0, bestStart)];\n if (closed) {\n const first = rotated[0];\n if (first !== undefined) {\n rotated.push(first);\n }\n }\n return rotated.join(' → ');\n}\n\n/**\n * Map each node id that participates in a dependency cycle to a schema diagnostic.\n *\n * `params[0]` is the closed cycle path (`F3 → P1 → F3`).\n *\n * @param graph Constituent dependency graph (provider → dependent edges).\n * @param resolveAlias Maps node id to display alias for cycle formatting.\n * @returns One {@link CstDiagnostic} per node on each cyclic SCC.\n */\nexport function detectDependencyCycleDiagnostics(\n graph: Graph,\n resolveAlias: (id: number) => string\n): Map<number, CstDiagnostic> {\n const result = new Map<number, CstDiagnostic>();\n for (const cycle of graph.findCycles()) {\n if (cycle.length < 2) {\n continue;\n }\n const aliases = cycle.map(id => resolveAlias(id));\n const cycleText = formatDependencyCycle(aliases);\n const memberIds = new Set(cycle);\n for (const id of memberIds) {\n result.set(id, {\n kind: DiagnosticKind.SCHEMA,\n code: RSDiagnosticCode.schemaDependencyCycle,\n params: [cycleText]\n });\n }\n }\n return result;\n}\n\n/** Map a model evaluation status to a compact diagnostic, or `null` when not an issue. */\nexport function modelStatusCstDiagnostic(status: EvalStatus, cstType: CstType): CstDiagnostic | null {\n const code = modelStatusToCode(status, cstType);\n if (code === null) {\n return null;\n }\n return { kind: DiagnosticKind.MODEL, code, params: [String(status)] };\n}\n\nfunction collectLocalSchemaDiagnostics(\n cst: BasicTextCheckFields & {\n is_type_mismatch: boolean;\n typification_manual: string;\n analysis: { type: ExpressionType | null };\n }\n): CstDiagnostic[] {\n const result: CstDiagnostic[] = [];\n if (cst.is_type_mismatch) {\n result.push({\n kind: DiagnosticKind.SCHEMA,\n code: RSDiagnosticCode.schemaTypeMismatch,\n params: [cst.typification_manual, labelType(cst.analysis.type)]\n });\n }\n if (isBasicConcept(cst.cst_type) && !isLogical(cst.cst_type)) {\n if (!cst.convention.trim()) {\n result.push({ kind: DiagnosticKind.SCHEMA, code: RSDiagnosticCode.schemaMissingConvention });\n }\n if (!cst.term_resolved.trim()) {\n result.push({ kind: DiagnosticKind.SCHEMA, code: RSDiagnosticCode.schemaMissingTerm });\n }\n }\n return result;\n}\n\nfunction detectGroupedAliasDiagnostics<T extends { id: number }>(\n items: readonly T[],\n resolveAlias: (id: number) => string,\n groupKey: (cst: T) => string | undefined,\n code: RSDiagnosticCode\n): Map<number, CstDiagnostic> {\n const groups = new Map<string, T[]>();\n for (const cst of items) {\n const key = groupKey(cst);\n if (!key) {\n continue;\n }\n const group = groups.get(key) ?? [];\n group.push(cst);\n groups.set(key, group);\n }\n\n const result = new Map<number, CstDiagnostic>();\n for (const group of groups.values()) {\n if (group.length <= 1) {\n continue;\n }\n for (const cst of group) {\n const aliases = group\n .filter(other => other.id !== cst.id)\n .map(other => resolveAlias(other.id))\n .join(', ');\n result.set(cst.id, {\n kind: DiagnosticKind.SCHEMA,\n code,\n params: [aliases]\n });\n }\n }\n return result;\n}\n\nfunction detectHomonymDiagnostics(\n items: readonly { id: number; term_resolved: string }[],\n resolveAlias: (id: number) => string\n): Map<number, CstDiagnostic> {\n return detectGroupedAliasDiagnostics(\n items,\n resolveAlias,\n cst => {\n const key = cst.term_resolved.trim().toLocaleLowerCase();\n return key === '' ? undefined : key;\n },\n RSDiagnosticCode.schemaHomonym\n );\n}\n\nfunction detectFormalDuplicateDiagnostics(\n items: readonly { id: number }[],\n resolveAlias: (id: number) => string,\n normalizedDefinitions: ReadonlyMap<number, string>\n): Map<number, CstDiagnostic> {\n return detectGroupedAliasDiagnostics(\n items,\n resolveAlias,\n cst => normalizedDefinitions.get(cst.id),\n RSDiagnosticCode.schemaFormalDuplicate\n );\n}\n\nfunction modelStatusToCode(status: EvalStatus, cstType: CstType): RSDiagnosticCode | null {\n switch (status) {\n case EvalStatus.EMPTY:\n return isBasicConcept(cstType) ? RSDiagnosticCode.modelEmpty : null;\n case EvalStatus.AXIOM_FALSE:\n return RSDiagnosticCode.modelAxiomFalse;\n case EvalStatus.INVALID_DATA:\n return RSDiagnosticCode.modelInvalidData;\n case EvalStatus.EVAL_FAIL:\n return RSDiagnosticC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