@rsconcept/rstool 0.2.1 → 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.
@@ -1,168 +1,78 @@
1
- # Conceptual schema (КС) — agent recommendations
1
+ # Концептуальная схема
2
2
 
3
- This note complements the mechanistic references:
3
+ Справка про проектирование КС как системы определений. Для механики см. `CONSTITUENTA.md`, `SYNTAX.md`, `TYPIFICATION.md`.
4
4
 
5
- - `CONSTITUENTA.md` — how to upsert constituents correctly (fields, order, validation)
6
- - `SYNTAX.md` / `TYPIFICATION.md` — how to construct correct RS expressions
5
+ ## Цель схемы
7
6
 
8
- Here we focus on **how to design and analyse a conceptual schema as a system of constituents**.
7
+ КС ценна не числом конституент, а различениями, которые она вводит.
9
8
 
10
- ## What makes a schema valuable
9
+ - Добавляй понятие, если оно дает новый критерий, роль, отношение, инвариант или правило.
10
+ - Если пользователь постоянно переформулирует одно различие, введи отдельную конституенту.
11
11
 
12
- The value of a conceptual schema is the **diversity of concepts expressed in it**.
12
+ ## Текстовые поля
13
13
 
14
- - A good schema forms a **domain thesaurus**: a stable set of terms and distinctions that people can use for communication and decision-making.
15
- - “Diversity” is not the same as “many aliases”. Prefer concepts that introduce **new distinctions** (new criteria, roles, constraints, invariants) instead of synonyms.
14
+ `term`, `definitionText`, `convention` держи в языке схемы и в ее словаре.
16
15
 
17
- Practical agent heuristic:
16
+ - `term` — короткое имя понятия.
17
+ - `definitionText` — текстовая интерпретация формального определения.
18
+ - `convention` — соглашение для неопределяемого понятия.
18
19
 
19
- - If you can remove a derived concept `D#` and lose no important language for reasoning, it is probably redundant.
20
- - If stakeholders keep rephrasing the same thing in different words, the schema likely misses one or more constituents that capture the missing distinction.
20
+ Перед записью `definitionText` проверь существительные: важный предметный термин должен быть введен как `N#`, `X#`, `C#`, `S#` или `D#`.
21
21
 
22
- ## Rule for text fields (term / definitionText / convention)
22
+ ## Номиноиды и атрибутирование
23
23
 
24
- When you write natural-language text in a schema, follow this strict rule:
24
+ `N#` номиноид: именованная сущность для словаря схемы. Он помогает фиксировать термин до точной родоструктурной формализации.
25
25
 
26
- - **Use only terms that are introduced in the schema itself.**
26
+ Атрибутирование связывает номиноид с другими конституентами через атрибуты. Это отдельная атрибутивная экспликация, не замена `S#`, `D#`, `A#` в родоструктурной экспликации.
27
27
 
28
- Rationale:
28
+ Правило для `rstool`: не смешивай атрибутивную и родоструктурную экспликацию. Используй `N#` как словарную опору, но не превращай атрибуты в RS-формулы и не добавляй атрибутивные связи, если пользователь явно не просит совместить эти способы.
29
29
 
30
- - Text definitions that rely on “external vocabulary” quietly import unstated assumptions and weaken the schema as a shared thesaurus.
30
+ ## Родовые структуры
31
31
 
32
- Agent checklist:
32
+ `S#` — родовая структура. Ее `definitionFormal` задает типизацию, а смысл задают конвенция, интерпретация и аксиомы.
33
33
 
34
- - When you add a new `definitionText`, scan it for nouns/terms. If a term is essential, introduce it explicitly (typically as `N#`, `X#`, `S#`, or a derived `D#`).
35
- - Prefer short “closed-world” definitions: explain a concept using already-introduced schema terms plus logical connectives (“and”, “or”, “not”), quantifiers (“for all”, “exists”), and references to RS expressions.
34
+ Паттерн для отношения:
36
35
 
37
- ## Modeling genus structures (родовые структуры) as `S#`
36
+ 1. `X1` базисное множество.
37
+ 2. `S1: ℬ(X1×X1)` — отношение; порядок пары описан в `convention`.
38
+ 3. `D# := Pr1(S1)`, `D# := Pr2(S1)` — именованные компоненты.
39
+ 4. Сложные термы строятся поверх этих `D#`.
38
40
 
39
- `S#` constituents represent **base structured concepts**: their `definitionFormal` is a **typification** (grade), and their meaning is set by `convention` plus axioms.
41
+ Если повторяется цепочка вроде `Pr2(Fi1[D](S7))`, введи промежуточный терм или уточни конвенцию/аксиому для `S7`.
40
42
 
41
- ### Define structure components explicitly
43
+ ## Аксиомы
42
44
 
43
- For a genus structure `S#`, it is often useful to define **all components** as named derived terms.
45
+ `A#` логическое требование к модели. Используй аксиомы, чтобы:
44
46
 
45
- Why:
47
+ - фиксировать смысл `S#`;
48
+ - задавать уникальность, тотальность, непересечение, порядок, область и диапазон;
49
+ - оправдывать `debool(...)`: внутреннее множество должно быть гарантированно одноэлементным.
46
50
 
47
- - It gives names to projections / reduced parts of a structure, making the thesaurus usable.
48
- - It shortens later formulas and prevents agents from repeating long projection chains differently in different places.
51
+ ## Проверка на маленькой модели
49
52
 
50
- Typical pattern for a binary relation over a base set:
53
+ Когда семантика определения не очевидна, используй концептуальную модель как тестовый стенд: задай минимальные значения для `X#`, `C#`, `S#` и вычисли проверяемые `D#`, `F#`, `P#`, `A#`.
51
54
 
52
- - `X1` base set (undefined)
53
- - `S1 : ℬ(X1×X1)` — relation as a structure (undefined, meaning via convention)
54
- - Component terms:
55
- - `D_dom := Pr1(S1)` — “domain” / “left elements”
56
- - `D_cod := Pr2(S1)` — “codomain” / “right elements”
57
- - `D_pairs := red(bool(S1))` is usually nonsense; instead name the parts you truly use
58
- - For higher-arity structures, define `Pr1`, `Pr2`, … and relevant multi-projections (`Pr1,3`, etc.)
55
+ Это особенно полезно для проекций, фильтров, `red`, `bool` / `debool` и аксиом. Если проверка важна для будущих изменений, перенеси ее в скрипт-тест: собрать маленькую сессию, задать значения неопределяемых конституент, вычислить целевые конституенты и проверить не только `success`, но и ожидаемое `value`.
59
56
 
60
- More generally:
57
+ Подробный цикл: `MODEL-TESTING.md`.
61
58
 
62
- - **Projections** (`Pr*`, `pr*`) are the main tool for naming components.
63
- - **Reduce** (`red`) is useful when a component is a set-of-sets and you need a flattened union; introduce a named `D#` when you use `red` in more than one place.
59
+ ## Быстрое ревью
64
60
 
65
- ### Avoid “anonymous structure usage”
61
+ - Атрибутивная экспликация не смешана с родоструктурной без явного запроса пользователя.
62
+ - Не добавляй проверки принадлежности к собственной типизации: если `x` уже объявлен в `X1`, `x ∈ X1` избыточно.
63
+ - Покрыты главные предметные сущности, роли, отношения и утверждения.
64
+ - Слои идут так: `X#`/`C#` → `S#` → простые `D#` → сложные `D#`/`F#`/`P#` → `A#`/`T#`.
65
+ - У каждой аксиомы понятная цель.
66
+ - Частые падения аксиом в модели указывают на ошибку данных или семантики схемы.
67
+ - Сомнительные выражения проверены на маленькой КМ, если есть показательные тестовые данные.
66
68
 
67
- If later definitions repeatedly use expressions like `Pr2(Fi1[D](S7))`, it is usually a sign that:
69
+ ## Рабочий порядок
68
70
 
69
- - the schema is missing a named constituent for that concept, or
70
- - the structure `S7` is underspecified (needs conventions/axioms).
71
-
72
- Prefer to introduce:
73
-
74
- - an intermediate derived term `D#` for the filtered relation/set, and
75
- - separate terms for the projections you interpret in text.
76
-
77
- ## Axioms as semantic direction
78
-
79
- An axiom `A#` is a **true statement** that:
80
-
81
- - defines the intended semantics of genus structures, and
82
- - enables safe derivations (“in a certain direction”) by providing guarantees needed for operations.
83
-
84
- Think of axioms as giving you _permission to use certain operators_ without risking typification/runtime failures or semantic ambiguity.
85
-
86
- ### Example: singleton guarantee for `debool`
87
-
88
- `debool(S)` is only meaningful when `S` is guaranteed to be a **singleton**.
89
-
90
- In practice, when you build `S` as a projection/filter result, you often need an axiom that guarantees uniqueness.
91
-
92
- For example, for a binary relation `S1 : ℬ(X1×X1)` you may want to define a function-like choice:
93
-
94
- - `D_childOf(x) := debool(Pr2(Fi1[bool(x)](S1)))`
95
-
96
- This is only valid if for every `x` the filtered projection yields exactly one element.
97
- That guarantee is provided by an axiom of **right-uniqueness** (functional dependency) for the relation (written in RS logic for your specific structure).
98
-
99
- Agent rule:
100
-
101
- - If you see `debool(...)` in a definition, ensure there is an axiom that makes the inner set a singleton on the intended domain.
102
- - If the axiom is absent, either (a) add the axiom, (b) replace `debool` by keeping the set-valued result, or (c) restrict the domain explicitly so the singleton property holds.
103
-
104
- ## Expression hygiene: avoid tautological membership checks
105
-
106
- In well-typed/correct RS expressions, you should avoid adding membership predicates that only restate what is already guaranteed by typification and by the correctness model.
107
-
108
- Specifically, avoid “sanity checks” like:
109
-
110
- - `x ∈ X1`
111
- - `x ∈ ℬ(X1)` (and other plain grade constructions such as `X1×X2`, `B(X1)`, etc.)
112
-
113
- when `x` is already bound/typed as an element compatible with `X1` (or with the intended element structure induced by `ℬ(X1)`, `X1×X2`, …).
114
-
115
- Why this is usually meaningless:
116
-
117
- - `AnalysisResult` checks expressions in a **global context** where identifiers must have known typifications and must satisfy **bijective portability**.
118
- - Under these guarantees, values of an element grade “already belong” to the corresponding set/grade in the semantic sense; so the predicate becomes (effectively) TRUE and adds no discriminating information.
119
-
120
- Agent rule:
121
-
122
- - Use membership (`∈` / `Fi*`) to express *nontrivial* schema semantics (e.g. defining/characterising derived sets), not to re-check that a value matches its own typification.
123
-
124
- ## Bijective portability (биективная переносимость)
125
-
126
- **Bijective portability** means that a formal meaning/definition of a constituent depends only on the *structure* that the schema intends, and not on arbitrary “names” of undefined-concept interpretations.
127
-
128
- Concretely, if you replace interpretations of undefined concepts by a bijective renaming (structure-preserving renaming), then:
129
-
130
- - the evaluation result of every bijectively portable definition is unchanged up to the same renaming,
131
- - therefore definitions are stable and reusable across equivalent models.
132
-
133
- In rstool’s correctness model this property is not optional for the formal part:
134
-
135
- - all formal definitions are required to be **bijectively portable**,
136
- - expression checking assumes bijective portability for every referenced identifier.
137
-
138
- Because of this, membership checks against base sets/grades become redundant in correct expressions: the type discipline plus portability already guarantee the relevant “belonging” constraints.
139
-
140
- ## Analysis: how to review a schema as a system
141
-
142
- ### Thesaurus health
143
-
144
- - **Coverage**: do core domain nouns/roles appear as constituents (`N#`, `X#`, `S#`, `D#`)?
145
- - **Non-synonymy**: if two terms are interchangeable in all axioms/definitions, collapse or differentiate them.
146
- - **Naming stability**: avoid renaming “public” terms frequently; prefer adding refined terms and marking old ones as deprecated in text (if your workflow supports that).
147
-
148
- ### Term graph health (dependencies)
149
-
150
- - Prefer a **layered graph**: bases/constants → core structures → derived projections/components → higher-level derived concepts → axioms/statements.
151
-
152
- ### Axiom health
153
-
154
- - Every axiom should have a clear intent: uniqueness, totality, disjointness, ordering, invariance, domain/range constraints, etc.
155
- - Prefer a small set of high-leverage axioms that unlock safe derivations, rather than many weak axioms with overlapping meaning.
156
- - If axioms regularly fail in model evaluation, either the interpretation data violates the intended semantics or the semantics are wrong — in both cases the schema needs revision.
157
-
158
- ## Practical workflow for agents (recommended)
159
-
160
- 1. **Start with a vocabulary list** (domain nouns, roles, relations) → introduce `N#` for stable names when formalisation is not ready yet.
161
- 2. **Introduce bases/constants** (`X#`, `C#`) early with conventions.
162
- 3. **Introduce core structures** (`S#`) with typifications + conventions; immediately add the most important component terms (`Pr*`, `red`-based terms).
163
- 4. **Add derived concepts** (`D#`, `F#`, `P#`) incrementally; keep definitions short by using named components.
164
- 5. **Add axioms** (`A#`) that:
165
- - encode intended semantics of structures,
166
- - justify `debool`/functional choices, and
167
- - restrict domains/ranges so derived concepts remain meaningful.
168
- 6. Run analysis on scratch expressions before committing, and keep text definitions closed-world (schema terms only).
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,78 +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
- ## Language of text fields
17
+ ## `cstType`
20
18
 
21
- The natural-language fields `term`, `definitionText`, and `convention` should be written in **one consistent language**:
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`.
22
28
 
23
- - When editing/extending an existing schema, keep the **same language** that is already used in the schema’s text fields.
24
- - When creating a new schema from scratch, use the **language of the user’s request**.
29
+ `basic`, `constant`, `structure` можно интерпретировать через `setConstituentaValue`. `term`, `axiom`, `statement` вычисляются и напрямую не задаются.
25
30
 
26
- ## `cstType` table
31
+ ## `S#` и `D#`
27
32
 
28
- | `cstType` (value) | Prefix | Formal definition | Notes |
29
- | ----------------- | ------ | ------------------------- | ------------------------------------------------------------------------------------------------- |
30
- | `basic` (`X`) | `X#` | **must be empty** | Base set; non-empty formal → `definitionNotAllowed` |
31
- | `constant` (`C`) | `C#` | **must be empty** | Constant set; same rule |
32
- | `nominal` (`N`) | `N#` | allowed | Free vocabulary item, no semantic constraint |
33
- | `structure` (`S`) | `S#` | allowed | **Base** structured concept; `definitionFormal` is its **typification** (grade), not a definition |
34
- | `term` (`D`) | `D#` | allowed | **Derived** concept; `definitionFormal` is its **definition** (value computed in the model) |
35
- | `axiom` (`A`) | `A#` | allowed (must be `Logic`) | Logical statement asserting a requirement |
36
- | `statement` (`T`) | `T#` | allowed (must be `Logic`) | Logical assertion about the model |
37
- | `function` (`F`) | `F#` | allowed (parameterised) | Term-function |
38
- | `predicate` (`P`) | `P#` | allowed (parameterised) | Predicate-function |
33
+ `S#` — неопределяемая родовая структура. `definitionFormal: 'ℬ(X1×X1)'` описывает ступень элемента: множество пар над `X1`.
39
34
 
40
- ### Interpretability and inferrability
35
+ `D#` терм. `definitionFormal: 'X1×X1'` строит полный декартов продукт.
41
36
 
42
- - **Interpretable** (a value can be assigned via `setConstituentaValue`): `basic`, `constant`, `structure`.
43
- - **Inferrable** (computed from definitions, never set directly): `term`, `axiom`, `statement`. Assigning to an inferrable raises an error.
37
+ Для бинарного отношения обычно нужно:
44
38
 
45
- ## Structure (`S#`) vs term (`D#`)
39
+ 1. `X1` базисное множество.
40
+ 2. `S1` — `definitionFormal: 'ℬ(X1×X1)'`; конвенция объясняет порядок пары.
41
+ 3. `D#` — проекции и фильтры: `Pr1(S1)`, `Pr2(S1)`, `Fi1[D1](S1)`.
46
42
 
47
- Do not treat `structure` and `term` as interchangeable because both may contain `×`, `ℬ`, or projections.
43
+ Пример: `examples/build-kinship-rsform.ts`.
48
44
 
49
- | | `structure` (`S#`) | `term` (`D#`) |
50
- | ------------------ | ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
51
- | `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`) |
52
- | Introduction | `convention` (+ optional axioms); interpretation from the subject domain | Formal expression only; interpretation is **evaluated** |
53
- | `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 |
45
+ ## Валидация
54
46
 
55
- **Typical pattern (relation over a base set):**
47
+ 1. Префикс `alias` соответствует `cstType`.
48
+ 2. У `basic` и `constant` пустая формула, иначе `definitionNotAllowed` (`0x8862`).
49
+ 3. Все глобальные ссылки уже есть в сессии.
50
+ 4. `axiom` и `statement` имеют типизацию `Logic`, иначе `expectedLogic`.
51
+ 5. Выводимая конституента с пустой формулой дает `cstEmptyDerived`.
56
52
 
57
- 1. `X1` base set, empty formal, `convention` names the domain elements.
58
- 2. `S1` — `definitionFormal: 'ℬ(X1×X1)'`, `convention` explains pair order (e.g. parent, child).
59
- 3. `D1` — `definitionFormal: 'Pr1(S1)'` (or filters / term-functions), `definitionText` explains the derived set.
60
-
61
- Worked example: `examples/build-kinship-rsform.ts`.
62
-
63
- ## Validation rules
64
-
65
- 1. **Prefix ↔ `cstType`**: `alias` letter must match the type prefix.
66
- 2. **Empty formal for undefined concepts**: `basic` and `constant` must have `definitionFormal === ''`. Any non-empty value triggers `definitionNotAllowed` (`0x8862`).
67
- 3. **Dependency declaration order**: every global identifier referenced in `definitionFormal` must correspond to an already-upserted constituent in the session.
68
- 4. **Logical-only definitions**: `axiom` and `statement` definitions must typecheck to `Logic`; otherwise `expectedLogic`.
69
- 5. **Empty derived expression**: a derived constituent with empty `definitionFormal` triggers `cstEmptyDerived`.
70
-
71
- ## Recommended upsert order
72
-
73
- 1. All `basic` (`X#`) and `constant` (`C#`) constituents (empty formal).
74
- 2. Core `structure` (`S#`) and crucial concepts.
75
- 3. Topological order of derived concepts: every dependency upserted before its dependent.
76
- 4. Axioms and statements after the constituents they reference.
77
-
78
- 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`.