@rsconcept/rstool 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,78 @@
1
+ # Концептуальная схема
2
+
3
+ Справка про проектирование КС как системы определений. Для механики см. `CONSTITUENTA.md`, `SYNTAX.md`, `TYPIFICATION.md`.
4
+
5
+ ## Цель схемы
6
+
7
+ КС ценна не числом конституент, а различениями, которые она вводит.
8
+
9
+ - Добавляй понятие, если оно дает новый критерий, роль, отношение, инвариант или правило.
10
+ - Если пользователь постоянно переформулирует одно различие, введи отдельную конституенту.
11
+
12
+ ## Текстовые поля
13
+
14
+ `term`, `definitionText`, `convention` держи в языке схемы и в ее словаре.
15
+
16
+ - `term` — короткое имя понятия.
17
+ - `definitionText` — текстовая интерпретация формального определения.
18
+ - `convention` — соглашение для неопределяемого понятия.
19
+
20
+ Перед записью `definitionText` проверь существительные: важный предметный термин должен быть введен как `N#`, `X#`, `C#`, `S#` или `D#`.
21
+
22
+ ## Номиноиды и атрибутирование
23
+
24
+ `N#` — номиноид: именованная сущность для словаря схемы. Он помогает фиксировать термин до точной родоструктурной формализации.
25
+
26
+ Атрибутирование связывает номиноид с другими конституентами через атрибуты. Это отдельная атрибутивная экспликация, не замена `S#`, `D#`, `A#` в родоструктурной экспликации.
27
+
28
+ Правило для `rstool`: не смешивай атрибутивную и родоструктурную экспликацию. Используй `N#` как словарную опору, но не превращай атрибуты в RS-формулы и не добавляй атрибутивные связи, если пользователь явно не просит совместить эти способы.
29
+
30
+ ## Родовые структуры
31
+
32
+ `S#` — родовая структура. Ее `definitionFormal` задает типизацию, а смысл задают конвенция, интерпретация и аксиомы.
33
+
34
+ Паттерн для отношения:
35
+
36
+ 1. `X1` — базисное множество.
37
+ 2. `S1: ℬ(X1×X1)` — отношение; порядок пары описан в `convention`.
38
+ 3. `D# := Pr1(S1)`, `D# := Pr2(S1)` — именованные компоненты.
39
+ 4. Сложные термы строятся поверх этих `D#`.
40
+
41
+ Если повторяется цепочка вроде `Pr2(Fi1[D](S7))`, введи промежуточный терм или уточни конвенцию/аксиому для `S7`.
42
+
43
+ ## Аксиомы
44
+
45
+ `A#` — логическое требование к модели. Используй аксиомы, чтобы:
46
+
47
+ - фиксировать смысл `S#`;
48
+ - задавать уникальность, тотальность, непересечение, порядок, область и диапазон;
49
+ - оправдывать `debool(...)`: внутреннее множество должно быть гарантированно одноэлементным.
50
+
51
+ ## Проверка на маленькой модели
52
+
53
+ Когда семантика определения не очевидна, используй концептуальную модель как тестовый стенд: задай минимальные значения для `X#`, `C#`, `S#` и вычисли проверяемые `D#`, `F#`, `P#`, `A#`.
54
+
55
+ Это особенно полезно для проекций, фильтров, `red`, `bool` / `debool` и аксиом. Если проверка важна для будущих изменений, перенеси ее в скрипт-тест: собрать маленькую сессию, задать значения неопределяемых конституент, вычислить целевые конституенты и проверить не только `success`, но и ожидаемое `value`.
56
+
57
+ Подробный цикл: `MODEL-TESTING.md`.
58
+
59
+ ## Быстрое ревью
60
+
61
+ - Атрибутивная экспликация не смешана с родоструктурной без явного запроса пользователя.
62
+ - Не добавляй проверки принадлежности к собственной типизации: если `x` уже объявлен в `X1`, `x ∈ X1` избыточно.
63
+ - Покрыты главные предметные сущности, роли, отношения и утверждения.
64
+ - Слои идут так: `X#`/`C#` → `S#` → простые `D#` → сложные `D#`/`F#`/`P#` → `A#`/`T#`.
65
+ - У каждой аксиомы понятная цель.
66
+ - Частые падения аксиом в модели указывают на ошибку данных или семантики схемы.
67
+ - Сомнительные выражения проверены на маленькой КМ, если есть показательные тестовые данные.
68
+
69
+ ## Рабочий порядок
70
+
71
+ 1. Собери словарь предметной области.
72
+ 2. Добавь `X#` и `C#` с конвенциями.
73
+ 3. Добавь ключевые `S#` с типизацией и конвенцией.
74
+ 4. Назови важные компоненты через `D#`: `Pr*`, `pr*`, `red`.
75
+ 5. Добавляй выводимые `D#`, `F#`, `P#` маленькими шагами.
76
+ 6. Добавь `A#` и `T#` по необходимости.
77
+ 7. Перед upsert проверяй `analyzeExpression`.
78
+ 8. Для сомнительной семантики собери маленькую КМ и вычисли ожидаемые значения.
@@ -1,71 +1,53 @@
1
- # Constituenta reference
1
+ # Конституенты
2
2
 
3
- Use this when upserting constituents via `addOrUpdateConstituenta`.
3
+ Читай перед `addOrUpdateConstituenta`.
4
4
 
5
- ## `ConstituentaDraft` fields
5
+ ## Поля черновика
6
6
 
7
- | Field | Required | Description |
8
- | ------------------ | ------------------ | -------------------------------------------------------------- |
9
- | `id` | yes | Stable integer id within the session |
10
- | `alias` | yes | Display alias (`X1`, `D5`, `F2`) must match `cstType` prefix |
11
- | `cstType` | yes | One of `CstType` values (see table below) |
12
- | `definitionFormal` | yes (may be empty) | RS expression. Empty for `basic` / `constant` |
13
- | `term` | optional | Natural-language term name |
14
- | `definitionText` | optional | Natural-language definition / interpretation |
15
- | `convention` | optional | Convention text for undefined concepts |
7
+ - `id` стабильный id внутри сессии.
8
+ - `alias` имя вида `X1`, `D5`, `F2`; префикс должен совпадать с `cstType`.
9
+ - `cstType` роль конституенты.
10
+ - `definitionFormal` формальное определение; для `basic` и `constant` строго `''`.
11
+ - `term` естественно-языковое имя.
12
+ - `definitionText` текстовая интерпретация формулы.
13
+ - `convention` соглашение для неопределяемого понятия.
16
14
 
17
- Omitted text fields default to `''` in stored state.
15
+ Пропущенные текстовые поля сохраняются как `''`. Пиши `term`, `definitionText`, `convention` на одном языке: в языке схемы или, для новой схемы, в языке запроса.
18
16
 
19
- ## `cstType` table
17
+ ## `cstType`
20
18
 
21
- | `cstType` (value) | Prefix | Formal definition | Notes |
22
- | ----------------- | ------ | ------------------------- | ------------------------------------------------------------------------------------------------- |
23
- | `basic` (`X`) | `X#` | **must be empty** | Base set; non-empty formal → `definitionNotAllowed` |
24
- | `constant` (`C`) | `C#` | **must be empty** | Constant set; same rule |
25
- | `nominal` (`N`) | `N#` | allowed | Free vocabulary item, no semantic constraint |
26
- | `structure` (`S`) | `S#` | allowed | **Base** structured concept; `definitionFormal` is its **typification** (grade), not a definition |
27
- | `term` (`D`) | `D#` | allowed | **Derived** concept; `definitionFormal` is its **definition** (value computed in the model) |
28
- | `axiom` (`A`) | `A#` | allowed (must be `Logic`) | Logical statement asserting a requirement |
29
- | `statement` (`T`) | `T#` | allowed (must be `Logic`) | Logical assertion about the model |
30
- | `function` (`F`) | `F#` | allowed (parameterised) | Term-function |
31
- | `predicate` (`P`) | `P#` | allowed (parameterised) | Predicate-function |
19
+ - `nominal` / `N#` номиноид. В родоструктурной экспликации не используется.
20
+ - `basic` / `X#` базисное множество; формула пустая.
21
+ - `constant` / `C#` константное множество; формула пустая.
22
+ - `structure` / `S#` родовая структура; формула задает типизацию.
23
+ - `term` / `D#` терм; формула задает вычисляемое значение.
24
+ - `function` / `F#` терм-функция.
25
+ - `predicate` / `P#` предикат-функция.
26
+ - `axiom` / `A#` аксиома; нужна типизация `Logic`.
27
+ - `statement` / `T#` высказывание; нужна типизация `Logic`.
32
28
 
33
- ### Interpretability and inferrability
29
+ `basic`, `constant`, `structure` можно интерпретировать через `setConstituentaValue`. `term`, `axiom`, `statement` вычисляются и напрямую не задаются.
34
30
 
35
- - **Interpretable** (a value can be assigned via `setConstituentaValue`): `basic`, `constant`, `structure`.
36
- - **Inferrable** (computed from definitions, never set directly): `term`, `axiom`, `statement`. Assigning to an inferrable raises an error.
31
+ ## `S#` и `D#`
37
32
 
38
- ## Structure (`S#`) vs term (`D#`)
33
+ `S#` неопределяемая родовая структура. `definitionFormal: 'ℬ(X1×X1)'` описывает ступень элемента: множество пар над `X1`.
39
34
 
40
- Do not treat `structure` and `term` as interchangeable because both may contain `×`, `ℬ`, or projections.
35
+ `D#` терм. `definitionFormal: 'X1×X1'` строит полный декартов продукт.
41
36
 
42
- | | `structure` (`S#`) | `term` (`D#`) |
43
- | ------------------ | ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
44
- | `definitionFormal` | **Typification** — which grade the elements have (e.g. `ℬ(X1×X1)` = set of pairs over `X1`) | **Definition** — how to obtain the concept (e.g. `Pr1(S1)` = first projection of relation `S1`) |
45
- | Introduction | `convention` (+ optional axioms); interpretation from the subject domain | Formal expression only; interpretation is **evaluated** |
46
- | `X1×X1` in context | Inside a grade: **one** pair type `(X1, X1)` | As the whole body: **Cartesian product** `X1 × X1` (all pairs) — rarely what you want for a relation |
37
+ Для бинарного отношения обычно нужно:
47
38
 
48
- **Typical pattern (relation over a base set):**
39
+ 1. `X1` базисное множество.
40
+ 2. `S1` — `definitionFormal: 'ℬ(X1×X1)'`; конвенция объясняет порядок пары.
41
+ 3. `D#` — проекции и фильтры: `Pr1(S1)`, `Pr2(S1)`, `Fi1[D1](S1)`.
49
42
 
50
- 1. `X1` — base set, empty formal, `convention` names the domain elements.
51
- 2. `S1` — `definitionFormal: 'ℬ(X1×X1)'`, `convention` explains pair order (e.g. parent, child).
52
- 3. `D1` — `definitionFormal: 'Pr1(S1)'` (or filters / term-functions), `definitionText` explains the derived set.
43
+ Пример: `examples/build-kinship-rsform.ts`.
53
44
 
54
- Worked example: `examples/build-kinship-rsform.ts`.
45
+ ## Валидация
55
46
 
56
- ## Validation rules
47
+ 1. Префикс `alias` соответствует `cstType`.
48
+ 2. У `basic` и `constant` пустая формула, иначе `definitionNotAllowed` (`0x8862`).
49
+ 3. Все глобальные ссылки уже есть в сессии.
50
+ 4. `axiom` и `statement` имеют типизацию `Logic`, иначе `expectedLogic`.
51
+ 5. Выводимая конституента с пустой формулой дает `cstEmptyDerived`.
57
52
 
58
- 1. **Prefix ↔ `cstType`**: `alias` letter must match the type prefix.
59
- 2. **Empty formal for undefined concepts**: `basic` and `constant` must have `definitionFormal === ''`. Any non-empty value triggers `definitionNotAllowed` (`0x8862`).
60
- 3. **Dependency declaration order**: every global identifier referenced in `definitionFormal` must correspond to an already-upserted constituent in the session.
61
- 4. **Logical-only definitions**: `axiom` and `statement` definitions must typecheck to `Logic`; otherwise `expectedLogic`.
62
- 5. **Empty derived expression**: a derived constituent with empty `definitionFormal` triggers `cstEmptyDerived`.
63
-
64
- ## Recommended upsert order
65
-
66
- 1. All `basic` (`X#`) and `constant` (`C#`) constituents (empty formal).
67
- 2. Core `structure` (`S#`) and crucial concepts.
68
- 3. Topological order of derived concepts: every dependency upserted before its dependent.
69
- 4. Axioms and statements after the constituents they reference.
70
-
71
- Use `analyzeExpression` on a scratch expression before upsert; use `addOrUpdateConstituenta` only when the expression typechecks. Read `result.diagnostics` for actionable error info and patch by `from`/`to` ranges.
53
+ Цикл: `analyzeExpression` на черновике исправить `diagnostics[].from/to` → `addOrUpdateConstituenta`.
@@ -1,130 +1,85 @@
1
- # Diagnostics reference
2
-
3
- Use this when an `analyzeExpression` / `addOrUpdateConstituenta` call returns errors in `result.diagnostics`.
4
-
5
- ## How to read a diagnostic
6
-
7
- Each `DiagnosticRecord` carries:
8
-
9
- - `code` — numeric `RSErrorCode` (see table). The high nibble identifies the class (`0x82xx` lexer, `0x84xx` parser, `0x88xx` semantic, `0x81xx` runtime, `0x28xx` warnings).
10
- - `params` — substitution arguments for the message (identifier names, sets, etc.).
11
- - `from`, `to` — character positions in the _expression text_ that should be patched. Always edit `definitionFormal` by range.
12
- - `constituentId` present in session diagnostics from `listDiagnostics`.
13
-
14
- Resolve `code` from **`@rsconcept/domain`** (installed: `node_modules/@rsconcept/domain/src/rslang/error.ts`):
15
-
16
- - **`RSErrorCode`** — reverse-lookup the numeric value to its symbol name (`missingParenthesis`, `globalNotTyped`, …). The identifier is the canonical error kind; inline comments on each member document the hex id.
17
- - **`getRSErrorPrefix(code)`**short label with class + hex (`P8406`, `S8803`, …).
18
- - **`params`**substitution arguments from the reporter (see `*.test.ts` cases in `domain/src/rslang/` for examples per code).
19
- - **Tables below** typical causes and agent fixes when patching `definitionFormal`.
20
-
21
- ## Class table
22
-
23
- | Mask | Class | Behaviour |
24
- | --------------- | -------------------- | ------------------------------------------------------------------------------ |
25
- | `0x8400` family | Parser | Lexical / syntactic problems; expression cannot be analysed further |
26
- | `0x8800` family | Semantic | Definition-level issues (types, scopes, structure) |
27
- | `0x8100` family | Runtime / evaluation | Raised during `evaluateExpression` / `evaluateConstituenta` |
28
- | `0x2800` family | Warning | Not critical; expression still valid |
29
- | `0x88Cx` | Schema-level | Rules enforced by the schema layer (`cstEmptyDerived`, `definitionNotAllowed`) |
30
-
31
- `isCritical(code)` returns `false` only for `localDoubleDeclare` and `localNotUsed`.
32
-
33
- ## High-priority codes
34
-
35
- ### Parser
36
-
37
- | Code | Symbol | Typical cause | Agent fix |
38
- | -------- | ---------------------- | ------------------------------------ | ------------------------------- |
39
- | `0x8400` | `unknownSyntax` | Stray token / typo | Re-tokenise around `from`–`to` |
40
- | `0x8406` | `missingParenthesis` | Unmatched `(` `)` | Insert matching paren near `to` |
41
- | `0x8407` | `missingCurlyBrace` | Unmatched `{` `}` | Insert matching brace |
42
- | `0x8408` | `missingSquareBracket` | Unmatched `[` `]` | Insert matching bracket |
43
- | `0x8409` | `bracketMismatch` | Mixed bracket types | Replace one bracket to match |
44
- | `0x840A` | `doubleParenthesis` | `(( ... ))` redundancy | Remove one pair |
45
- | `0x840B` | `missingOpenBracket` | Closing bracket without opener | Insert opening bracket earlier |
46
- | `0x8415` | `expectedLocal` | Quantifier or filter expects a local | Provide a lowercase variable |
47
- | `0x8416` | `expectedType` | Missing typification annotation | Add explicit grade |
48
-
49
- ### Semanticlocals and scopes
50
-
51
- | Code | Symbol | Typical cause | Agent fix |
52
- | -------- | -------------------- | -------------------------------- | ------------------------------- |
53
- | `0x8801` | `localUndeclared` | Variable used before declaration | Bind via quantifier / parameter |
54
- | `0x8802` | `localShadowing` | Local redeclared in inner scope | Rename inner variable |
55
- | `0x8815` | `localOutOfScope` | Local escapes its binder | Move usage inside the binder |
56
- | `0x2801` | `localDoubleDeclare` | Same local declared twice | Warning; rename |
57
- | `0x2802` | `localNotUsed` | Declared local never referenced | Warning; remove or use |
58
-
59
- ### Semantic — types
60
-
61
- | Code | Symbol | Typical cause | Agent fix |
62
- | -------- | ------------------------------- | ------------------------------------------------------ | --------------------------------------------------- |
63
- | `0x8803` | `typesNotEqual` | Operands have different typifications | Convert / project to matching grade |
64
- | `0x8804` | `globalNotTyped` | Referenced global has no typification | Ensure dependency is upserted and typechecked first |
65
- | `0x8805` | `invalidDecart` | Cartesian product on non-set operand | Wrap operand in `ℬ(...)` if appropriate |
66
- | `0x8806` | `invalidBoolean` | `ℬ(...)` applied to a non-set | Use a set-grade operand |
67
- | `0x8807` | `invalidTypeOperation` | Operator not defined for these types | Re-check the typification table |
68
- | `0x8808` | `invalidCard` | `card(...)` on a non-set | Use a set operand |
69
- | `0x8809` | `invalidDebool` | `debool(...)` on non-singleton | Ensure exactly one element first |
70
- | `0x880B` | `globalFuncWithoutArgs` | Calling a function without `[]` args | Provide arguments |
71
- | `0x8810` | `invalidReduce` | `red(...)` on something not `ℬ(ℬ(...))` | Wrap in extra `ℬ` or change source |
72
- | `0x8811` | `invalidProjectionTuple` | `pr_i((a,b))` with out-of-range index | Use valid index |
73
- | `0x8812` | `invalidProjectionSet` | `Pr_i(S)` on non-tuple set | Use a tuple-set source |
74
- | `0x8813` | `invalidEnumeration` | `{a, b}` with incompatible element types | Match element typifications |
75
- | `0x8814` | `invalidCortegeDeclare` | Tuple declaration with mismatched arity | Match declaration to use |
76
- | `0x8816` | `invalidElementPredicate` | S` typification mismatch | Match `ξ`'s grade to elements of `S` |
77
- | `0x8817` | `invalidEmptySetUsage` | `∅` in a position that needs a concrete element | Provide explicit typified operand |
78
- | `0x8818` | `invalidArgsArity` | Wrong number of arguments to function | Match function declaration |
79
- | `0x8819` | `invalidArgumentType` | Argument typification mismatch | Adjust caller or function signature |
80
- | `0x881C` | `globalStructure` | Wrong structural shape of referenced global | Re-check `structure` constituent shape |
81
- | `0x8821` | `radicalUsage` | Radical used outside parameter domain | Move usage into parameter declarations |
82
- | `0x8822` | `invalidFilterArgumentType` | `Fi[D](S)` parameter does not match index typification | Match `D` to projected grade |
83
- | `0x8823` | `invalidFilterArity` | Filter parameter count ≠ multi-index length | Align lengths |
84
- | `0x8824` | `arithmeticNotSupported` | Arithmetic operator outside integer context | Use integer expressions |
85
- | `0x8825` | `typesNotCompatible` | Generic type incompatibility | Re-examine surrounding context |
86
- | `0x8826` | `orderingNotSupported` | `<`, `≤` etc. used outside integer | Ensure operands are integers |
87
- | `0x8827` | `expectedLogic` | Definition where `Logic` is required | Wrap in logical expression or change `cstType` |
88
- | `0x8828` | `expectedSetexpr` | Definition where STE required | Convert from logic to set expression |
89
- | `0x8829` | `invalidArgumentCortegeDeclare` | Tuple parameter declaration mismatch | Match tuple arity in declaration |
90
-
91
- ### Schema / cstType validation
92
-
93
- | Code | Symbol | Trigger | Fix |
94
- | -------- | ---------------------- | ------------------------------------------------------ | ------------------------------------------------------ |
95
- | `0x8861` | `cstEmptyDerived` | Derived constituent with empty `definitionFormal` | Provide a definition |
96
- | `0x8862` | `definitionNotAllowed` | `basic`/`constant` with non-empty formal | Clear the formal |
97
- | `0x8840` | `globalNoValue` | Reference to global without a model value | Set value via `setConstituentaValue` before evaluating |
98
- | `0x8841` | `invalidPropertyUsage` | Property-only constituent used where value is required | Use a different operand |
99
-
100
- ### Runtime (evaluation)
101
-
102
- | Code | Symbol | Cause |
103
- | -------- | ------------------------- | ---------------------------------------- |
104
- | `0x8100` | `calcUnknownError` | Unspecified evaluation failure |
105
- | `0x8101` | `setOverflow` | Intermediate set too large |
106
- | `0x8102` | `booleanBaseLimit` | `ℬ(X)` overflow at runtime |
107
- | `0x8103` | `calcGlobalMissing` | Referenced global has no current value |
108
- | `0x8104` | `iterationsLimit` | Iterative computation exceeded limit |
109
- | `0x8105` | `calcInvalidDebool` | `debool` on multi-element set at runtime |
110
- | `0x8106` | `iterateInfinity` | Iteration over an infinite set |
111
- | `0x8107` | `calculationNotSupported` | Construct cannot be evaluated |
112
-
113
- ## Common agent mistakes
114
-
115
- - **Setting a value on a derived constituent**: derived `term`, `axiom`, `statement` are inferrable. Use `evaluateConstituenta` / `recalculateModel`. Setting them throws `Constituent <alias> is inferrable and cannot be set directly`.
116
- - **Forgetting empty formal on `basic` / `constant`**: results in `definitionNotAllowed`. Pass `definitionFormal: ''`.
117
- - **Out-of-order dependencies**: referencing `D2` before upserting it raises `localUndeclared` or `globalNotTyped`. Always topologically sort.
118
- - **Wrong cstType for the role**: `axiom`/`statement` whose definition is not `Logic` raises `expectedLogic`. A `term` whose body is logical raises `expectedSetexpr`.
119
- - **Negative literals**: `-5` does not parse. Use `0 - 5`.
120
- - **Radicals in result expressions**: `[α∈R1] (α, R1)` raises `radicalUsage`. Use radicals only in parameter domains.
121
- - **Evaluating before bindings are set**: `evaluateExpression` referencing `X1` without a `setConstituentaValue(..., target: <X1.id>)` raises `calcGlobalMissing` (`0x8103`).
122
-
123
- ## Diagnostics loop
124
-
125
- 1. Run `analyzeExpression` on a scratch.
126
- 2. If `analysis.success === false`, iterate `analysis.diagnostics`.
127
- 3. For each diagnostic: read `code`, `from`, `to`, and `params`. Look up `code` in `RSErrorCode` (`error.ts`) and use `getRSErrorPrefix` if you need a display id.
128
- 4. Patch `definitionFormal` based on the range — never blindly retry without changing the input.
129
- 5. Re-send. Repeat until success.
130
- 6. Only then call `addOrUpdateConstituenta` to commit the constituent into the session.
1
+ # Диагностика
2
+
3
+ Читай, когда `analyzeExpression` или `addOrUpdateConstituenta` вернули `diagnostics`.
4
+
5
+ ## `DiagnosticRecord`
6
+
7
+ - `code` — числовой `RSErrorCode`.
8
+ - `params` — аргументы сообщения.
9
+ - `from`, `to` диапазон в `definitionFormal`.
10
+ - `constituentId` — есть в диагностике сессии из `listDiagnostics`.
11
+
12
+ Источник истины: `@rsconcept/domain/src/rslang/error.ts`. Для короткого вида UI/логов используй `getRSErrorPrefix(code)`.
13
+
14
+ ## Классы кодов
15
+
16
+ - `0x8400` parser: синтаксис и скобки.
17
+ - `0x8800`semantic: типизации, области видимости, структура.
18
+ - `0x8100`runtime/evaluation: вычисление модели.
19
+ - `0x2800`warning: обычно не блокирует выражение.
20
+ - `0x88Cx` — правила схемы и `cstType`.
21
+
22
+ ## Частые parser-коды
23
+
24
+ - `0x8400 unknownSyntax` неопределенная синтаксическая ошибка.
25
+ - `0x8406 missingParenthesis` не закрыты `(` `)`.
26
+ - `0x8407 missingCurlyBrace` не закрыты `{` `}`.
27
+ - `0x8408 missingSquareBracket` не закрыты `[` `]`.
28
+ - `0x8409 bracketMismatch` смешаны типы скобок.
29
+ - `0x840A doubleParenthesis` лишняя пара скобок.
30
+ - `0x840B missingOpenBracket` — закрывающая скобка без открывающей.
31
+ - `0x8415 expectedLocal` нужна локальная переменная.
32
+ - `0x8416 expectedType` — нужна явная ступень.
33
+
34
+ ## Локальные переменные
35
+
36
+ - `0x8801 localUndeclared` — свяжи переменную квантором или параметром.
37
+ - `0x8802 localShadowing` переименуй внутреннюю переменную.
38
+ - `0x8815 localOutOfScope` перенеси использование внутрь области видимости.
39
+ - `0x2801 localDoubleDeclare` warning; объявление задублировано.
40
+ - `0x2802 localNotUsed` warning; переменная не используется.
41
+
42
+ ## Типизации и структура
43
+
44
+ - `0x8803 typesNotEqual` / `0x8825 typesNotCompatible` операнды несовместимы.
45
+ - `0x8804 globalNotTyped` сначала добавь и проанализируй поставщика.
46
+ - `0x8805 invalidDecart`, `0x8806 invalidBoolean`, `0x8810 invalidReduce` неверная ступень для операции.
47
+ - `0x8808 invalidCard` `card(...)` не над множеством.
48
+ - `0x8809 invalidDebool` — нет гарантии синглетона.
49
+ - `0x880B globalFuncWithoutArgs` функция вызвана без `[]`.
50
+ - `0x8811 invalidProjectionTuple`, `0x8812 invalidProjectionSet` — неверная проекция.
51
+ - `0x8813 invalidEnumeration` элементы перечисления разных ступеней.
52
+ - `0x8816 invalidElementPredicate` S` с несовместимыми ступенями.
53
+ - `0x8818 invalidArgsArity`, `0x8819 invalidArgumentType` неверный вызов функции.
54
+ - `0x8821 radicalUsage` радикал вне домена параметра.
55
+ - `0x8822 invalidFilterArgumentType`, `0x8823 invalidFilterArity` неверный `Fi`.
56
+ - `0x8824 arithmeticNotSupported`, `0x8826 orderingNotSupported` нужна ступень `Z`.
57
+ - `0x8827 expectedLogic` нужна логическая формула.
58
+ - `0x8828 expectedSetexpr` — нужно теоретико-множественное выражение, а не логика.
59
+
60
+ ## Схема и вычисление
61
+
62
+ - `0x8861 cstEmptyDerived` у выводимой конституенты пустая формула.
63
+ - `0x8862 definitionNotAllowed` у `basic`/`constant` непустая формула.
64
+ - `0x8840 globalNoValue` / `0x8103 calcGlobalMissing` нет значения в модели.
65
+ - `0x8841 invalidPropertyUsage` `Property` использован как вычислимое значение.
66
+ - `0x8101 setOverflow`, `0x8102 booleanBaseLimit`, `0x8104 iterationsLimit` выражение слишком дорого вычислять.
67
+ - `0x8105 calcInvalidDebool` `debool` получил не синглетон.
68
+ - `0x8106 iterateInfinity`, `0x8107 calculationNotSupported` конструкция не исполнима в конечной модели.
69
+
70
+ ## Типичные ошибки агентов
71
+
72
+ - Задавать значение `term`/`axiom`/`statement` напрямую.
73
+ - Писать формулу у `basic` или `constant`.
74
+ - Добавлять потребителя раньше поставщика.
75
+ - Давать логическое тело `term` или нелогическое тело `axiom`/`statement`.
76
+ - Использовать `R#` в теле результата.
77
+ - Вычислять производные понятия до привязки данных для базовых.
78
+
79
+ ## Цикл исправления
80
+
81
+ 1. Запусти `analyzeExpression`.
82
+ 2. Прочитай `code`, `from`, `to`, `params`.
83
+ 3. Исправь именно диапазон в `definitionFormal`.
84
+ 4. Не повторяй вызов без изменения ввода.
85
+ 5. После успеха вызывай `addOrUpdateConstituenta`.
package/docs/DOMAIN.md CHANGED
@@ -1,91 +1,68 @@
1
- # Domain reference
2
-
3
- Compact English distillation of the canonical Russian domain glossary (`CONTEXT.md`). Read this first if you are an agent unfamiliar with the Concept Portal vocabulary.
4
-
5
- ## Core concepts
6
-
7
- - **Subject domain**a sphere of human activity that requires coordination and communication.
8
- - **Conceptual schema (`КС`)** — a formal system of definitions for a subject domain, made of constituents.
9
- - **Conceptual model (`РСМодель`)** — a pairing of a conceptual schema with an interpretation in concrete data.
10
- - **Operations Synthesis Schema (`ОСС`)** — a graph of load and synthesis operations that drives schema construction and evolution.
11
- - **RS language (`родоструктурная экспликация`)** — the formal genus-structure language used to define concepts, relations and operations inside a schema.
12
- - **Typification** the computable structural type of a constituent's formal definition; the formal constraint on admissible interpretations.
13
- - **Term graph**a directed dependency graph over constituents; an edge means "constituent A appears in constituent B's definition".
14
-
15
- ## Constituents
16
-
17
- A **constituent** is the atomic building block of a conceptual schema. Each constituent may carry a term, a convention, a typification, a formal definition, a textual interpretation, and a comment. By role, a constituent is either undefined, derived, or a statement.
18
-
19
- Constituent aliases follow a strict prefix scheme:
20
-
21
- | Alias prefix | Role | Notes |
22
- |-----|------|-------|
23
- | `N#` | Nominoid | Free vocabulary item, no formal definition |
24
- | `X#` | Base set | Undefined concept, set of distinguishable elements |
25
- | `C#` | Constant set | Undefined concept, set-theoretic constant with operations |
26
- | `S#` | Structured concept (**genus structure**) | Undefined concept; `definitionFormal` gives **typification**; meaning via `convention` / axioms |
27
- | `D#` | Term | Derived concept; `definitionFormal` is the **definition**; value computed in a model |
28
- | `F#` | Term-function | Parameterised derived concept yielding an STE |
29
- | `P#` | Predicate-function | Parameterised derived concept yielding a logical expression |
30
- | `A#` | Axiom | Logical statement asserting requirements |
31
- | `T#` | Statement | Logical assertion about the model |
32
- | `R#` | Radical | Template placeholder for arbitrary typification |
33
-
34
- **Undefined concepts** (`X#`, `C#`, `S#`) are introduced by conventions (and optional axioms). For `S#`, the formal field states **typification** (the grade of elements), not a defining construction. **Derived concepts** (`D#`, `F#`, `P#`, `A#`, `T#`) carry a formal **definition** and must follow declaration order — every referenced constituent must already exist; their model values are obtained by evaluation.
35
-
36
- **Structure vs term:** `S#` with `ℬ(X1×X1)` declares “elements are pairs over `X1`”; the actual pairs come from interpretation. `D#` with `X1×X1` as the whole expression denotes the **full Cartesian product** (all pairs), which is a computed set use `S#` + projections when modeling a relation.
37
-
38
- A **crucial constituent** is marked as content-bearing for filtering / focus; it has no semantic effect on the formal calculus.
39
-
40
- ## Statuses
41
-
42
- Each constituent has one of the following correctness statuses:
43
-
44
- | Status | Meaning |
45
- |--------|---------|
46
- | Unknown | Not yet validated |
47
- | OK | Validated as correct |
48
- | Error | Validation failed |
49
- | Property | Defines a non-computable set; only membership tests are admissible |
50
- | Incalculable | Cannot be evaluated directly (e.g. expected exponential blow-up) |
51
-
52
- ## RSModel evaluation states
53
-
54
- In a conceptual model each item has one of the following evaluation statuses:
55
-
56
- | Status | Meaning |
57
- |--------|---------|
58
- | `NO_EVAL` (1) | Not evaluated (definition is not interpretable) |
59
- | `NOT_PROCESSED` (2) | Interpretation has not been computed yet |
60
- | `INVALID_DATA` (3) | Provided data is invalid |
61
- | `EVAL_FAIL` (4) | Evaluation raised an error |
62
- | `AXIOM_FALSE` (5) | Axiom evaluated to FALSE |
63
- | `EMPTY` (6) | Result is the empty set |
64
- | `HAS_DATA` (7) | Interpretation computed and non-empty |
65
-
66
- ## Synthesis and OSS
67
-
68
- - **Load operation** attaches an existing schema to the OSS graph.
69
- - **Synthesis operation** combines operand schemas via an **identification table** (pairs of constituents to be treated as equivalent) and produces a result schema with **inherited constituents**.
70
- - **Cross-cutting changes** propagate edits from a **source constituent** to its **inherited constituents** through the OSS. Inherited constituents are not edited directly.
71
- - **Diamond synthesis** uses operand schemas with shared ancestors.
72
- - **Concept block** is a nominal grouping of schemas inside the OSS.
73
-
74
- ## Relationships
75
-
76
- - A conceptual schema **contains** many constituents.
77
- - A conceptual model **interprets** exactly one schema at a given state.
78
- - An OSS **contains** load and synthesis operations.
79
- - A synthesis operation **consumes** one or more input schemas plus an identification table and **produces** a result schema with inherited constituents.
80
- - Cross-cutting changes **propagate** from a source constituent to its inherited descendants.
81
- - The term graph is **derived** from the formal definitions of constituents.
82
-
83
- ## Dependency vocabulary
84
-
85
- - **Consumers** — constituents that mention this one in their definitions.
86
- - **Suppliers** — constituents this one mentions in its definition.
87
- - **Dependents** — direct and transitive consumers.
88
- - **Influencers** — direct and transitive suppliers.
89
- - **Generating expression** — a definition referencing a single external constituent with no added content.
90
- - **Base concept (for generation)** — the constituent on which a generating expression is built.
91
- - **Generated concept** — a constituent produced from a generating expression.
1
+ # Доменная справка
2
+
3
+ Термины, используемые в Concept Portal.
4
+
5
+ ## Основные термины
6
+
7
+ - **Предметная область**область, для которой строится система определений.
8
+ - **Концептуальная схема (`КС`)** — система понятий, утверждений и связей между ними.
9
+ - **Концептуальная модель (`КМ`)** — КС плюс интерпретация ее понятий на конечных данных.
10
+ - **Операционная схема синтеза (`ОСС`)** — граф загрузок и синтезов КС.
11
+ - **Родоструктурная экспликация (`RSLang`)** — формальный язык для понятий, отношений, операций и утверждений.
12
+ - **Типизация / ступень** структура значений выражения: элемент, целое, кортеж, множество, `Logic`.
13
+ - **Граф термов**зависимости: конституента ссылается на другую в формальном определении.
14
+
15
+ ## Конституенты
16
+
17
+ **Конституента** часть КС. Главное для агента: `alias`, `cstType`, `definitionFormal`, `term`, `definitionText`, `convention`. `comment` комментарий и пояснения разработчика схемы, полезно для контекста.
18
+
19
+ - `N#` **номиноид**: словарная сущность. В родоструктурной экспликации не используется.
20
+ - `X#` — **базисное множество**: неопределяемое понятие, формула пустая.
21
+ - `C#` **константное множество**: неопределяемое множество для арифметики и порядка, формула пустая.
22
+ - `S#` — **родовая структура**: неопределяемое структурное понятие; формула задает типизацию.
23
+ - `D#` **терм**: определяемое понятие; формула вычисляет значение.
24
+ - `F#` **терм-функция**: параметризованный терм.
25
+ - `P#` **предикат-функция**: параметризованное логическое выражение.
26
+ - `A#` **аксиома**: логическое требование к модели.
27
+ - `T#` **высказывание**: логическое утверждение о модели.
28
+ - `R#` **радикал**: шаблонная ступень в параметрах.
29
+
30
+ Правило: `X#`, `C#`, `S#` задаются конвенцией и интерпретацией; `D#`, `F#`, `P#`, `A#`, `T#` выводятся по формуле. Поставщики должны идти раньше потребителей.
31
+
32
+ Не путай `S#` и `D#`: `S1: ℬ(X1×X1)` интерпретируемое отношение из пар; `D1 := X1×X1` — декартово произведение.
33
+
34
+ ## Статусы выражений
35
+
36
+ - `Unknown` — не проверено.
37
+ - `OK` — корректно.
38
+ - `Error` ошибка в определении.
39
+ - `Property` — неразмерное: доступна только проверка принадлежности.
40
+ - `Incalculable` — невычислимо напрямую.
41
+
42
+ ## Статусы вычисления в модели
43
+
44
+ - `NO_EVAL` нечего вычислять.
45
+ - `NOT_PROCESSED` — вычисление не запускалось.
46
+ - `INVALID_DATA` неверная интерпретация.
47
+ - `EVAL_FAIL` ошибка вычисления.
48
+ - `AXIOM_FALSE` аксиома ложна.
49
+ - `EMPTY` результат пуст.
50
+ - `HAS_DATA` результат вычислен и непустой.
51
+
52
+ ## Зависимости
53
+
54
+ - **Поставщики** конституенты, на которые ссылается текущая.
55
+ - **Потребители** — конституенты, которые ссылаются на текущую.
56
+ - **Влияющие** прямые и транзитивные поставщики.
57
+ - **Зависимые** — прямые и транзитивные потребители.
58
+ - **Основание** конституента, из которой формально порождают новые термы.
59
+ - **Порожденная конституента** построена из основания без новой предметной договоренности.
60
+
61
+ ## ОСС и синтез
62
+
63
+ - **Загрузка** добавляет внешнюю или собственную КС в ОСС.
64
+ - **Синтез** строит новую КС из операций-аргументов через таблицу отождествлений.
65
+ - **Наследованные конституенты** пришли из исходных схем; их определения обычно read-only.
66
+ - **Сквозные изменения** идут от исходной конституенты к наследникам.
67
+ - **Ромбовидный синтез** использует КС с общими предками; чаще требует ручного отождествления дублей.
68
+ - **Концептуальный блок** группа схем внутри предметной области.