@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.
- package/docs/CONCEPTUAL-SCHEMA.md +50 -140
- package/docs/CONSTITUENTA.md +37 -62
- package/docs/DIAGNOSTICS.md +85 -130
- package/docs/DOMAIN.md +68 -91
- package/docs/GRAMMAR-REF.md +35 -86
- package/docs/MODEL-TESTING.md +57 -0
- package/docs/PORTAL-API.md +22 -36
- package/docs/README.md +14 -13
- package/docs/SYNTAX.md +49 -104
- package/docs/TYPIFICATION.md +41 -60
- package/package.json +1 -1
- package/skills/README.md +6 -8
- package/skills/rstool-helper/EXAMPLES.md +83 -106
- package/skills/rstool-helper/GUIDE.md +66 -114
- package/skills/rstool-helper/REFERENCE.md +1 -0
- package/skills/rstool-helper/SKILL.md +5 -8
|
@@ -1,168 +1,78 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Концептуальная схема
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Справка про проектирование КС как системы определений. Для механики см. `CONSTITUENTA.md`, `SYNTAX.md`, `TYPIFICATION.md`.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
- `SYNTAX.md` / `TYPIFICATION.md` — how to construct correct RS expressions
|
|
5
|
+
## Цель схемы
|
|
7
6
|
|
|
8
|
-
|
|
7
|
+
КС ценна не числом конституент, а различениями, которые она вводит.
|
|
9
8
|
|
|
10
|
-
|
|
9
|
+
- Добавляй понятие, если оно дает новый критерий, роль, отношение, инвариант или правило.
|
|
10
|
+
- Если пользователь постоянно переформулирует одно различие, введи отдельную конституенту.
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
## Текстовые поля
|
|
13
13
|
|
|
14
|
-
|
|
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
|
-
|
|
16
|
+
- `term` — короткое имя понятия.
|
|
17
|
+
- `definitionText` — текстовая интерпретация формального определения.
|
|
18
|
+
- `convention` — соглашение для неопределяемого понятия.
|
|
18
19
|
|
|
19
|
-
|
|
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
|
-
##
|
|
22
|
+
## Номиноиды и атрибутирование
|
|
23
23
|
|
|
24
|
-
|
|
24
|
+
`N#` — номиноид: именованная сущность для словаря схемы. Он помогает фиксировать термин до точной родоструктурной формализации.
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
Атрибутирование связывает номиноид с другими конституентами через атрибуты. Это отдельная атрибутивная экспликация, не замена `S#`, `D#`, `A#` в родоструктурной экспликации.
|
|
27
27
|
|
|
28
|
-
|
|
28
|
+
Правило для `rstool`: не смешивай атрибутивную и родоструктурную экспликацию. Используй `N#` как словарную опору, но не превращай атрибуты в RS-формулы и не добавляй атрибутивные связи, если пользователь явно не просит совместить эти способы.
|
|
29
29
|
|
|
30
|
-
|
|
30
|
+
## Родовые структуры
|
|
31
31
|
|
|
32
|
-
|
|
32
|
+
`S#` — родовая структура. Ее `definitionFormal` задает типизацию, а смысл задают конвенция, интерпретация и аксиомы.
|
|
33
33
|
|
|
34
|
-
|
|
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
|
-
|
|
36
|
+
1. `X1` — базисное множество.
|
|
37
|
+
2. `S1: ℬ(X1×X1)` — отношение; порядок пары описан в `convention`.
|
|
38
|
+
3. `D# := Pr1(S1)`, `D# := Pr2(S1)` — именованные компоненты.
|
|
39
|
+
4. Сложные термы строятся поверх этих `D#`.
|
|
38
40
|
|
|
39
|
-
|
|
41
|
+
Если повторяется цепочка вроде `Pr2(Fi1[D](S7))`, введи промежуточный терм или уточни конвенцию/аксиому для `S7`.
|
|
40
42
|
|
|
41
|
-
|
|
43
|
+
## Аксиомы
|
|
42
44
|
|
|
43
|
-
|
|
45
|
+
`A#` — логическое требование к модели. Используй аксиомы, чтобы:
|
|
44
46
|
|
|
45
|
-
|
|
47
|
+
- фиксировать смысл `S#`;
|
|
48
|
+
- задавать уникальность, тотальность, непересечение, порядок, область и диапазон;
|
|
49
|
+
- оправдывать `debool(...)`: внутреннее множество должно быть гарантированно одноэлементным.
|
|
46
50
|
|
|
47
|
-
|
|
48
|
-
- It shortens later formulas and prevents agents from repeating long projection chains differently in different places.
|
|
51
|
+
## Проверка на маленькой модели
|
|
49
52
|
|
|
50
|
-
|
|
53
|
+
Когда семантика определения не очевидна, используй концептуальную модель как тестовый стенд: задай минимальные значения для `X#`, `C#`, `S#` и вычисли проверяемые `D#`, `F#`, `P#`, `A#`.
|
|
51
54
|
|
|
52
|
-
|
|
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
|
-
|
|
57
|
+
Подробный цикл: `MODEL-TESTING.md`.
|
|
61
58
|
|
|
62
|
-
|
|
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
|
-
|
|
61
|
+
- Атрибутивная экспликация не смешана с родоструктурной без явного запроса пользователя.
|
|
62
|
+
- Не добавляй проверки принадлежности к собственной типизации: если `x` уже объявлен в `X1`, `x ∈ X1` избыточно.
|
|
63
|
+
- Покрыты главные предметные сущности, роли, отношения и утверждения.
|
|
64
|
+
- Слои идут так: `X#`/`C#` → `S#` → простые `D#` → сложные `D#`/`F#`/`P#` → `A#`/`T#`.
|
|
65
|
+
- У каждой аксиомы понятная цель.
|
|
66
|
+
- Частые падения аксиом в модели указывают на ошибку данных или семантики схемы.
|
|
67
|
+
- Сомнительные выражения проверены на маленькой КМ, если есть показательные тестовые данные.
|
|
66
68
|
|
|
67
|
-
|
|
69
|
+
## Рабочий порядок
|
|
68
70
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
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. Для сомнительной семантики собери маленькую КМ и вычисли ожидаемые значения.
|
package/docs/CONSTITUENTA.md
CHANGED
|
@@ -1,78 +1,53 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Конституенты
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Читай перед `addOrUpdateConstituenta`.
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## Поля черновика
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
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
|
-
|
|
15
|
+
Пропущенные текстовые поля сохраняются как `''`. Пиши `term`, `definitionText`, `convention` на одном языке: в языке схемы или, для новой схемы, в языке запроса.
|
|
18
16
|
|
|
19
|
-
##
|
|
17
|
+
## `cstType`
|
|
20
18
|
|
|
21
|
-
|
|
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
|
-
|
|
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
|
-
## `
|
|
31
|
+
## `S#` и `D#`
|
|
27
32
|
|
|
28
|
-
|
|
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
|
-
|
|
35
|
+
`D#` — терм. `definitionFormal: 'X1×X1'` строит полный декартов продукт.
|
|
41
36
|
|
|
42
|
-
|
|
43
|
-
- **Inferrable** (computed from definitions, never set directly): `term`, `axiom`, `statement`. Assigning to an inferrable raises an error.
|
|
37
|
+
Для бинарного отношения обычно нужно:
|
|
44
38
|
|
|
45
|
-
|
|
39
|
+
1. `X1` — базисное множество.
|
|
40
|
+
2. `S1` — `definitionFormal: 'ℬ(X1×X1)'`; конвенция объясняет порядок пары.
|
|
41
|
+
3. `D#` — проекции и фильтры: `Pr1(S1)`, `Pr2(S1)`, `Fi1[D1](S1)`.
|
|
46
42
|
|
|
47
|
-
|
|
43
|
+
Пример: `examples/build-kinship-rsform.ts`.
|
|
48
44
|
|
|
49
|
-
|
|
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
|
-
|
|
47
|
+
1. Префикс `alias` соответствует `cstType`.
|
|
48
|
+
2. У `basic` и `constant` пустая формула, иначе `definitionNotAllowed` (`0x8862`).
|
|
49
|
+
3. Все глобальные ссылки уже есть в сессии.
|
|
50
|
+
4. `axiom` и `statement` имеют типизацию `Logic`, иначе `expectedLogic`.
|
|
51
|
+
5. Выводимая конституента с пустой формулой дает `cstEmptyDerived`.
|
|
56
52
|
|
|
57
|
-
|
|
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`.
|
package/docs/DIAGNOSTICS.md
CHANGED
|
@@ -1,130 +1,85 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
##
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
- `
|
|
10
|
-
- `
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
-
|
|
17
|
-
-
|
|
18
|
-
-
|
|
19
|
-
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
`
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
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`.
|