@rsconcept/rstool 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,7 +4,7 @@ Agent-facing library for **incremental RSForm construction**, **RSLang expressio
4
4
 
5
5
  ## Agent skill
6
6
 
7
- RS language + rstool workflows for agents: `skills/rstool-helper/` (`GUIDE.md`, `REFERENCE.md`, `EXAMPLES.md`) and `docs/` (`DOMAIN.md`, `CONCEPTUAL-SCHEMA.md` for relation-first KS design, `SYNTAX.md`, …). A **thin** entry skill is installed into the project’s agent skills folder; see [Installing the agent skill](#installing-the-agent-skill) below.
7
+ RS language + rstool workflows for agents: `skills/rstool-helper/` (`GUIDE.md`, `REFERENCE.md`, `EXAMPLES.md`) and `docs/` (`DOMAIN.md`, `CONCEPTUAL-SCHEMA.md`, `SYNTAX.md`, …). A **thin** entry skill is installed into the project’s agent skills folder; see [Installing the agent skill](#installing-the-agent-skill) below.
8
8
 
9
9
  ## Install
10
10
 
@@ -12,7 +12,21 @@ RS language + rstool workflows for agents: `skills/rstool-helper/` (`GUIDE.md`,
12
12
  npm install @rsconcept/rstool
13
13
  ```
14
14
 
15
- `@rsconcept/domain` is a peer-of-dependency installed automatically. No Portal checkout is required.
15
+ `@rsconcept/domain` is a peer-of-dependency installed automatically.
16
+
17
+ ## Installing the agent skill
18
+
19
+ After `npm install @rsconcept/rstool`, **you do not copy files yourself**. Ask your agent, for example:
20
+
21
+ > Install the rstool agent skill according to the package instructions.
22
+
23
+ The agent should read and follow:
24
+
25
+ `node_modules/@rsconcept/rstool/skills/INSTALL.md`
26
+
27
+ That copies `skills/rstool-helper/SKILL.md` from the package into your host’s project skills directory (for example `.agents/skills/rstool-helper/SKILL.md`). Full guidance stays in the package (`skills/rstool-helper/GUIDE.md`, `docs/*.md`) and is read from `node_modules` when needed.
28
+
29
+ Details: `skills/README.md`.
16
30
 
17
31
  ## Quick use (library)
18
32
 
@@ -50,7 +64,6 @@ await client.close();
50
64
  - Parse / syntax / semantic / type analysis for expressions.
51
65
  - In-memory modeling: set base bindings and structured values; evaluate expressions and constituents.
52
66
  - Deterministic diagnostics and export/import for reproducible agent workflows.
53
- - Library API + stdio JSON wrapper as the only supported transports (MCP adapter lives in [`@rsconcept/rstool-mcp`](../rstool-mcp/)).
54
67
 
55
68
  ## Publishing
56
69
 
@@ -128,20 +141,6 @@ The example:
128
141
  - sets a base binding and evaluates a term
129
142
  - fetches diagnostics
130
143
 
131
- ## Installing the agent skill
132
-
133
- After `npm install @rsconcept/rstool`, **you do not copy files yourself**. Ask your agent, for example:
134
-
135
- > Install the rstool agent skill according to the package instructions.
136
-
137
- The agent should read and follow:
138
-
139
- `node_modules/@rsconcept/rstool/skills/INSTALL.md`
140
-
141
- That copies `skills/rstool-helper/SKILL.md` from the package into your host’s project skills directory (for example `.agents/skills/rstool-helper/SKILL.md`). Full guidance stays in the package (`skills/rstool-helper/GUIDE.md`, `docs/*.md`) and is read from `node_modules` when needed.
142
-
143
- Details: `skills/README.md`.
144
-
145
144
  ## License
146
145
 
147
146
  MIT
@@ -1,57 +1,70 @@
1
1
  # Концептуальная схема
2
2
 
3
- Справка про проектирование КС как системы определений. Для механики см. `CONSTITUENTA.md`, `SYNTAX.md`, `TYPIFICATION.md`.
3
+ Общие правила проектирования КС как системы определений. Механика: `CONSTITUENTA.md`, `SYNTAX.md`, `TYPIFICATION.md`.
4
4
 
5
- ## Цель схемы
5
+ ## Цель
6
6
 
7
- КС ценна не числом конституент, а различениями, которые она вводит.
7
+ КС ценна не числом конституент, а различениями.
8
8
 
9
- - Добавляй понятие, если оно дает новый критерий, роль, отношение, инвариант или правило.
10
- - Если пользователь постоянно переформулирует одно различие, введи отдельную конституенту.
9
+ - Добавляй конституенту, если есть новый критерий выбора, роль, отношение, инвариант или правило.
10
+ - Если одно различие постоянно переформулируется, выдели отдельную конституенту.
11
+ - Не копируй источник дословно. Строй предметную модель.
12
+ - Разработка КС ведется итеративно - вводи понятия, экспликцируй определения, формируй новый понтия, исследуй предметную область.
11
13
 
12
- Подробнее про структуру и поля конституент см. в [CONSTITUENTA.md](./CONSTITUENTA.md).
14
+ ## Предметная редукция
15
+
16
+ Концептуализация решает задачу, не переписывает весь источник.
17
+
18
+ - Рассматривай только нужный аспект определения.
19
+ - Нужно опускать неважные отношения.
20
+ - Можно не различать предметные термины, если задача не требует различения.
21
+ - Если различение влияет на критерий, вывод или проверку, введи его явно.
13
22
 
14
23
  ## Номиноиды и атрибутирование
15
24
 
16
- `N#` — номиноид: именованная сущность для словаря схемы. Он помогает фиксировать термин до точной родоструктурной формализации.
25
+ `N#` — номиноид: именованная сущность словаря до точной родоструктурной формализации.
26
+
27
+ Атрибутирование связывает `N#` с конституентами отношением "быть атрибутом". Это отдельная атрибутивная экспликация, не замена `S#`, `D#`, `A#`.
17
28
 
18
- Атрибутирование связывает номиноид с другими конституентами через атрибуты. Это отдельная атрибутивная экспликация, не замена `S#`, `D#`, `A#` в родоструктурной экспликации.
29
+ Правило: не смешивай атрибутивную и родоструктурную экспликацию без явного запроса.
19
30
 
20
- Правило для `rstool`: не смешивай атрибутивную и родоструктурную экспликацию если явно не указано пользователем.
31
+ ## Базовые понятия
32
+
33
+ `X#`, `C#`, и `S#` — это базовые понятия, их нельзя строить одно из другого и включать друг в друга как элементы или подмножества.
34
+ Если такое возникает — значит есть скрытое отношение, его нужно явно оформить отдельной производной конституентой.
35
+ Если базисные множества пересекаются по интерпретации или набор констант показывает какой-то атрибут — отсутствует нужное отношение, его надо ввести.
21
36
 
22
37
  ## Родовые структуры
23
38
 
24
- `S#` — родовая структура. Ее `definitionFormal` задает типизацию, а смысл задают конвенция, интерпретация и аксиомы.
39
+ `S#` — родовая структура. `definitionFormal` задает типизацию; смысл задают `convention`, интерпретация, аксиомы.
25
40
 
26
- Паттерн для отношения:
41
+ Паттерн отношения:
27
42
 
28
43
  1. `X1` — базисное множество.
29
44
  2. `S1: ℬ(X1×X1)` — отношение; предметное пояснение в `convention`.
30
45
  3. `D# := Pr1(S1)`, `D# := Pr2(S1)` — именованные компоненты.
31
46
  4. Сложные термы строятся поверх этих `D#` и `S#`.
32
47
 
33
- Если повторяется цепочка вроде `Pr2(Fi1[D](S7))`, введи промежуточный терм или функцию `F#`.
34
-
35
- ## Подход relation-first
48
+ Повторяется `Pr2(Fi1[...](...))` или похожая цепочка -> введи промежуточный `D#` или `F#`.
36
49
 
37
- Используй при объединении нескольких исходных КС в одну предметную модель и при появлении длинных цепочек `∃d1…∃dn` в разных термах.
50
+ ## Relation-first
38
51
 
39
- ### Семантическая лестница
52
+ Используй, когда нужно объединить несколько КС или в термах повторяются длинные цепочки `∃d1…∃dn`.
40
53
 
41
- Строй схему слоями; каждый следующий слой ссылается только на предыдущие:
54
+ Строй слоями; слой ссылается только на предыдущие:
42
55
 
43
- | Слой | Роль | Что вводить |
44
- | :--- | :--------------------- | :------------------------------------------------------------------------------------------- |
45
- | 1 | Базис | `X#`, `C#` пустой `definitionFormal`, смысл в `convention` / `definitionText` из источника |
46
- | 2 | Структуры | `S#` типизация `ℬ(…×…)` и конвенция на кортеж |
47
- | 3 | Инварианты | `A#` короткие ограничения (см. ниже про `card`) |
48
- | 4 | Параметрический доступ | `F#` «локальный API»: `[α∈…] Pr*(Fi*[…](S#))` |
49
- | 5 | Центральное отношение | один `D#` (или `S#` с конвенцией), задающий полную траекторию синтеза |
50
- | 6 | Витрина понятий | `D#` через `Pr*`, `Fi*`, `card`, `red`; узкие `F#` для аналитики |
56
+ | Слой | Роль | Ввод |
57
+ | :--- | :-------------------- | :----------------------------------------------------------------------------- |
58
+ | 1 | Базисные множества | `X#`, `C#`; пустой `definitionFormal`, смысл в `convention` / `definitionText` |
59
+ | 2 | Структуры | `S#`; типизация `ℬ(…×…)`, конвенция кортежа |
60
+ | 3 | Инварианты | `A#`; короткие ограничения, чаще через `card` |
61
+ | 4 | Доступ | `F#`; локальный API вида `[α∈…] Pr*(Fi*[…](S#))` |
62
+ | 5 | Центральное отношение | один `D#` или `S#`, задающий полную траекторию синтеза |
63
+ | 6 | Витрина | `D#` через `Pr*`, `Fi*`, `card`, `red`; узкие `F#` для аналитики |
51
64
 
52
- ### Центральное отношение
65
+ ## Центральное отношение
53
66
 
54
- Когда в тексте описан единый сценарий, зафиксируй его **одним** объектом:
67
+ Единый сценарий фиксируй одним объектом:
55
68
 
56
69
  ```text
57
70
  D13 ::= I{(α, ξ1, τ, ξ2, β1, β2, ρ, ξ3) |
@@ -59,58 +72,56 @@ D13 ::= I{(α, ξ1, τ, ξ2, β1, β2, ρ, ξ3) |
59
72
  }
60
73
  ```
61
74
 
62
- (Имена и арность по предметной области; важна форма: кортеж + ограничения через уже введённые `F#` и `S#`.)
75
+ Имена и арность зависят от предметной области. Важна форма: кортеж + ограничения через уже введенные `F#` и `S#`.
63
76
 
64
- Далее можешь дать название необходимым частям кортежа с помощью `D#` через `Pr#`
77
+ Части кортежа называй через `D# := Pr#(D13)`.
65
78
 
66
- ### Инварианты: `card` вместо длинных `∀`
79
+ ## Инварианты
67
80
 
68
- Для функциональности отношения удобно:
81
+ Для функциональности отношения предпочитай `card`:
69
82
 
70
83
  ```text
71
84
  card(S1) = card(Pr1,2(S1))
72
85
  ```
73
86
 
74
- Эквивалентно идее `∀d1,d2∈S1 ...`
75
-
76
- Оставляй `∀`/`∃`, когда не получается заменить на теоретико-множественные и структурные конструкции.
87
+ Это заменяет длинные `∀d1,d2∈S1 ...`. Оставляй `∀` / `∃`, только если выражение нельзя задать через множества, проекции, фильтры, `card`.
77
88
 
78
- ### Проекции вместо повторных кванторов
89
+ ## Производные термы
79
90
 
80
- Если условие уже задано на `S#` или центральном `D#`, производный терм — это почти всегда:
91
+ Если условие уже задано на `S#` или центральном `D#`, производный терм обычно:
81
92
 
82
93
  - `Prk(…)` / `Pri,j(…)`;
83
94
  - `Fi*k[{…}](…)`;
84
- - `D{ξ∈… | F[ξ] = …}` или `card(F[ξ]) = 1`.
95
+ - `D{ξ∈… | F[ξ] = …}`;
96
+ - `card(F[ξ]) = 1`.
85
97
 
86
- Перед тем как писать `D{x∈… | ∃d1∈… ∃d2∈…}`, проверь: нельзя ли выразить через `Pr` от уже введённого отношения.
98
+ Перед `D{x∈… | ∃d1∈… ∃d2∈…}` проверь, нельзя ли взять `Pr` от уже введенного отношения.
87
99
 
88
- ## Проверка на маленькой модели
100
+ ## Проверка на маленькой КМ
89
101
 
90
- Когда семантика определения не очевидна, используй концептуальную модель как тестовый стенд: задай минимальные значения для `X#`, `C#`, `S#` и вычисли проверяемые `D#`, `F#`, `P#`, `A#`.
102
+ Если семантика не очевидна, собери минимальную модель: значения для `X#`, `C#`, `S#`; затем вычисли целевые `D#`, `F#`, `P#`, `A#`.
91
103
 
92
- Это особенно полезно для проекций, фильтров, `red`, `bool` / `debool` и аксиом. Если проверка важна для будущих изменений, перенеси ее в скрипт-тест: собрать маленькую сессию, задать значения неопределяемых конституент, вычислить целевые конституенты и проверить не только `success`, но и ожидаемое `value`.
104
+ Особенно проверяй проекции, фильтры, `red`, `bool` / `debool`, аксиомы. Для важной проверки сделай скрипт-тест: сессия + значения неопределяемых конституент + проверка `success` и ожидаемого `value`.
93
105
 
94
- Подробный цикл: `MODEL-TESTING.md`.
106
+ Цикл: `MODEL-TESTING.md`.
95
107
 
96
108
  ## Быстрое ревью
97
109
 
98
- - Атрибутивная экспликация не смешана с родоструктурной без явного запроса пользователя.
99
- - Не добавляй проверки принадлежности к собственной типизации: если `x` уже объявлен в `X1`, `x ∈ X1` избыточно.
100
- - Покрыты главные предметные сущности, роли, отношения и утверждения.
101
- - Повторяющиеся отборы вынесены в `F#`, а не размазаны по термам.
102
- - У каждой аксиомы понятна цель.
103
- - Частые падения аксиом в модели указывают на ошибку данных или семантики схемы.
104
- - Сомнительные выражения проверены на маленькой КМ, если есть показательные тестовые данные.
110
+ - Атрибутивная и родоструктурная экспликации не смешаны без запроса.
111
+ - Нет проверки принадлежности к собственной типизации: `x∈X1` избыточно, если `x` уже объявлен в `X1`.
112
+ - Покрыты главные сущности, роли, отношения, утверждения.
113
+ - Повторяющиеся отборы вынесены в `F#`.
114
+ - Каждая аксиома имеет понятную цель.
115
+ - Сомнительная семантика проверена на маленькой КМ при наличии тестовых данных.
105
116
 
106
117
  ## Рабочий порядок
107
118
 
108
- 1. Собери словарь предметной области (базисы, ключевые отношения, сценарий синтеза).
109
- 2. Добавь `X#` и `C#` с конвенциями из источника.
110
- 3. Добавь базовые `S#` (трансформация, перевод, допускание, выбор, цели, субъекты).
111
- 4. Добавь `A#` на структуры (`card`, покрытие `Pr1,2(S#)=…`, принадлежность выбора).
112
- 5. Введи `F#` для типовых запросов.
113
- 6. Производные понятия — `Pr*` / `Fi*` / `F#` от центрального `D#` и базовых `S#`.
114
- 7. Узкие классификаторы (`для любой обстановки`, `для одного индивида`) через `F#` и `card`/`=` с `X#`, не новые монолиты.
115
- 8. Перед каждым upsert `analyzeExpression`.
116
- 9. Для сомнительной семантики маленькая КМ (`MODEL-TESTING.md`).
119
+ 1. Собери словарь: базовые понятия, ключевые отношения, сценарий синтеза.
120
+ 2. Добавь `X#`, `C#` с конвенциями из источника.
121
+ 3. Добавь базовые `S#`: трансформация, перевод, допускание, выбор, цели, субъекты.
122
+ 4. Проверь, что базовые понятия независимы и не выводятся друг из друга.
123
+ 5. Добавь `A#` на структуры: `card`, покрытие `Pr1,2(S#)=…`, принадлежность выбора.
124
+ 6. Введи `F#` для типовых запросов.
125
+ 7. Производные понятия строй через `Pr*`, `Fi*`, `F#` от центрального `D#` и базовых `S#`.
126
+ 8. Перед каждым upsert запускай `analyzeExpression`.
127
+ 9. Для сомнительной семантики собери маленькую КМ (`MODEL-TESTING.md`).
package/docs/DOMAIN.md CHANGED
@@ -12,13 +12,21 @@
12
12
  - **Типизация / ступень** — структура значений выражения: элемент, целое, кортеж, множество, `Logic`.
13
13
  - **Граф термов** — зависимости: конституента ссылается на другую в формальном определении.
14
14
 
15
+ ## Классификация понятий КС
16
+
17
+ - **Базовое (неопределяемое) понятие** — конституента, вводимая конвенцией (и при необходимости аксиомами), а не формальным определением. В родоструктурной экспликации: `X#`, `C#`, `S#`. Смысл задают `convention`, интерпретация и аксиомы.
18
+ - **Производное понятие** — конституента с формальным определением на RSLang: `D#`, `F#`, `P#` и связанные выводимые конструкции. Значение получают из определения при заданной интерпретации базовых понятий.
19
+ - **Ядро КС** — базовые понятия, аксиомы и производные понятия, необходимые для их формулировки.
20
+ - **Тело КС** — остальные конституенты схемы, не входящие в ядро.
21
+ - **Интерпретация** — соотнесение понятий КС с сущностями предметной области. В концептуальной модели задаётся значениями неопределяемых конституент и вычислением производных.
22
+
15
23
  ## Конституенты
16
24
 
17
25
  **Конституента** — часть КС. Главное для агента: `alias`, `cstType`, `definitionFormal`, `term`, `definitionText`, `convention`. `comment` — комментарий и пояснения разработчика схемы, полезно для контекста.
18
26
 
19
27
  - `N#` — **номиноид**: словарная сущность. В родоструктурной экспликации не используется.
20
28
  - `X#` — **базисное множество**: неопределяемое понятие, формула пустая.
21
- - `C#` — **константное множество**: неопределяемое множество для арифметики и порядка, формула пустая.
29
+ - `C#` — **константное множество**: неопределяемое понятие для арифметики и порядка, формула пустая.
22
30
  - `S#` — **родовая структура**: неопределяемое структурное понятие; формула задает типизацию.
23
31
  - `D#` — **терм**: определяемое понятие; формула вычисляет значение.
24
32
  - `F#` — **терм-функция**: параметризованный терм.
@@ -16,7 +16,7 @@
16
16
  1. Создай отдельную `createSession` или изолированную копию текущей сессии.
17
17
  2. Добавь только нужные поставщики: `X#`, `C#`, `S#` и проверяемые `D#` / `F#` / `P#` / `A#`.
18
18
  3. Проверь формулы через `analyzeExpression` и `addOrUpdateConstituenta`.
19
- 4. Задай значения базисов и структур через `setConstituentaValue` или `setConstituentaValues`.
19
+ 4. Задай значения базовых понятий через `setConstituentaValue` или `setConstituentaValues`.
20
20
  5. Вычисли проверяемую формулу через `evaluateExpression` или сохраненную конституенту через `evaluateConstituenta`.
21
21
  6. Сравни результат с ожидаемым значением; если есть несколько зависимых определений, запусти `recalculateModel`.
22
22
 
@@ -32,7 +32,13 @@ const TUPLE_ID = -111;
32
32
  tool.setConstituentaValues(sessionId, {
33
33
  items: [
34
34
  { target: 1, value: { 0: 'ann', 1: 'bob', 2: 'cat' } },
35
- { target: 2, value: [[TUPLE_ID, 0, 1], [TUPLE_ID, 0, 2]] }
35
+ {
36
+ target: 2,
37
+ value: [
38
+ [TUPLE_ID, 0, 1],
39
+ [TUPLE_ID, 0, 2]
40
+ ]
41
+ }
36
42
  ]
37
43
  });
38
44
  ```
package/docs/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  ## Какой файл читать
6
6
 
7
- - **DOMAIN.md** — термины Portal: конституента, концептуальная схема/модель, ОСС, синтез.
7
+ - **DOMAIN.md** — термины Portal: конституента, базовые и производные понятия, ядро/тело КС, интерпретация, ОСС, синтез.
8
8
  - **CONCEPTUAL-SCHEMA.md** — проектирование и ревью концептуальных схем.
9
9
  - **CONSTITUENTA.md** — структура и правила конституент.
10
10
  - **SYNTAX.md** — операторы, кванторы, функции и примеры выражений.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsconcept/rstool",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "description": "Agent-facing library for incremental RSForm construction, RSLang analysis, diagnostics, modeling, and evaluation. Wraps @rsconcept/domain with a deterministic session contract and stdio wrapper.",
5
5
  "license": "MIT",
6
6
  "author": "IRBorisov",
@@ -4,8 +4,6 @@ Short examples for agents. For full scripts, see `../../examples/`.
4
4
 
5
5
  ## Minimal Session
6
6
 
7
- `S1` carries typification `ℬ(X1×X1)` for relation pairs. `D1` computes `Pr1(S1)`. Do not put bare `X1×X1` on a `term` when you mean a relation structure.
8
-
9
7
  ```ts
10
8
  import { CstType, RSToolAgent } from '@rsconcept/rstool';
11
9
 
@@ -48,58 +46,7 @@ if (!analysis.success) {
48
46
  }
49
47
  ```
50
48
 
51
- Fix the reported `from` / `to` range, then re-run analysis. Do not retry unchanged input.
52
-
53
- ## Wrapper Client
54
-
55
- Use the wrapper when the agent talks to a separate `rstool-wrapper` process.
56
-
57
- ```ts
58
- import { CstType } from '@rsconcept/rstool';
59
- import { RSToolWrapperClient } from '@rsconcept/rstool/wrapper';
60
-
61
- const client = new RSToolWrapperClient();
62
- await client.waitUntilReady();
63
-
64
- const { sessionId } = await client.call<{ sessionId: string }>('createSession');
65
-
66
- await client.call('addOrUpdateConstituenta', {
67
- sessionId,
68
- input: {
69
- draft: { id: 1, alias: 'X1', cstType: CstType.BASE, definitionFormal: '' }
70
- }
71
- });
72
-
73
- const diagnostics = await client.call('listDiagnostics', { sessionId });
74
- console.log(diagnostics);
75
-
76
- await client.close();
77
- ```
78
-
79
- Manual stdio is one JSON request per line:
80
-
81
- ```jsonl
82
- { "id": "1", "method": "createSession", "params": {} }
83
- { "id": "2", "method": "addOrUpdateConstituenta", "params": { "sessionId": "...", "input": { "draft": { "id": 1, "alias": "X1", "cstType": "basic", "definitionFormal": "" } } } }
84
- ```
85
-
86
- ## Export / Import
87
-
88
- ```ts
89
- const payload = tool.exportSession(sessionId);
90
- const restored = tool.importSession(payload);
91
- ```
92
-
93
- Export includes session state and model values.
94
-
95
- To create files the user can upload to an existing Portal object:
96
-
97
- ```ts
98
- const schemaJson = tool.exportPortalSchema(sessionId);
99
- const modelJson = tool.exportPortalModel(sessionId);
100
- ```
101
-
102
- Use `schemaJson` on a schema page and `modelJson` on a model page via **Load from JSON**.
49
+ Fix the reported `from` / `to` range, then re-run analysis. Maybe rethink the whole definition or split into multiple constituents
103
50
 
104
51
  ## Evaluation
105
52
 
@@ -162,70 +109,62 @@ if (!result.success || result.status !== EvalStatus.HAS_DATA || JSON.stringify(r
162
109
 
163
110
  Use this pattern for tests that protect important definitions. Full kinship model: `../../examples/build-kinship-rsmodel.ts`. More notes: `../../docs/MODEL-TESTING.md`.
164
111
 
165
- ## Relation-first synthesis (layered KS)
112
+ ## Wrapper Client
113
+
114
+ Use the wrapper when the agent talks to a separate `rstool-wrapper` process.
115
+
116
+ ```ts
117
+ import { CstType } from '@rsconcept/rstool';
118
+ import { RSToolWrapperClient } from '@rsconcept/rstool/wrapper';
166
119
 
167
- Pattern for merging sub-schemas (transformation + transition + choice → stimulation). Reference: Portal `D01B03` / rsform `843`.
120
+ const client = new RSToolWrapperClient();
121
+ await client.waitUntilReady();
168
122
 
169
- 1. **Structures** one `S#` per mechanism, typification only:
123
+ const { sessionId } = await client.call<{ sessionId: string }>('createSession');
170
124
 
171
- ```text
172
- S1: ℬ(X1×X2×X1) // transformation
173
- S2: ℬ(X2×X3×X2) // transition
174
- S4: ℬ(X2×X1×X3) // allowance (flat triple, not ℬ(X2×X1×ℬ(X3)))
175
- S5: ℬ(X1×ℬ(X3)×X3) // choice
176
- ```
125
+ await client.call('addOrUpdateConstituenta', {
126
+ sessionId,
127
+ input: {
128
+ draft: { id: 1, alias: 'X1', cstType: CstType.BASE, definitionFormal: '' }
129
+ }
130
+ });
177
131
 
178
- 2. **Axioms** short invariants:
132
+ const diagnostics = await client.call('listDiagnostics', { sessionId });
133
+ console.log(diagnostics);
179
134
 
180
- ```text
181
- A1: Pr1,2(S1) = X1×X2
182
- A2: card(S1) = card(Pr1,2(S1))
183
- A4: card(S5) = card(Pr1,2(S5))
184
- A5: ∀d∈S5 pr3(d)∈pr2(d)
135
+ await client.close();
185
136
  ```
186
137
 
187
- 3. **Functions** parameterized access (reuse everywhere):
138
+ Manual stdio is one JSON request per line:
188
139
 
189
- ```text
190
- F5[α,β] := Pr3(Fi1,2[{(β,α)}](S4)) // possible actions
191
- F7[α,ξ] := F6[α, F5[α,ξ]] // chosen action in situation
140
+ ```jsonl
141
+ { "id": "1", "method": "createSession", "params": {} }
142
+ { "id": "2", "method": "addOrUpdateConstituenta", "params": { "sessionId": "...", "input": { "draft": { "id": 1, "alias": "X1", "cstType": "basic", "definitionFormal": "" } } } }
192
143
  ```
193
144
 
194
- 4. **Central term** — one tuple relation, then projections:
145
+ ## Export / Import
195
146
 
196
- ```text
197
- D13 ::= I{(α,ξ1,τ,ξ2,β1,β2,ρ,ξ3) | α∈S6; ξ1∈X2; τ∈F7[α,ξ1]; …; ξ3∈S3}
198
- D14 := Pr3(D13) // stimuli
199
- D18 := Pr2(D13) // initial situations
147
+ ```ts
148
+ const payload = tool.exportSession(sessionId);
149
+ const restored = tool.importSession(payload);
200
150
  ```
201
151
 
202
- 5. **Classifiers** filter via `F#`, not a new `∃` chain:
152
+ Export includes session state and model values.
153
+
154
+ To create files the user can upload to an existing Portal object:
203
155
 
204
- ```text
205
- F8[α] := Pr2(Fi3[{α}](D13))
206
- D22 := D{ξ∈D14 | F8[ξ] = X2} // stimulus valid in any situation
156
+ ```ts
157
+ const schemaJson = tool.exportPortalSchema(sessionId);
158
+ const modelJson = tool.exportPortalModel(sessionId);
207
159
  ```
208
160
 
209
- Upsert in dependency order; run `analyzeExpression` on `I{…}` before committing the central `D#`.
161
+ Use `schemaJson` on a schema page and `modelJson` on a model page via **Load from JSON**.
210
162
 
211
163
  ## Common mistakes
212
164
 
213
- - `definitionFormal: 'Z'` on `basic` / `constant` → `definitionNotAllowed`.
214
- - `D1` uses `D2` before `D2` exists → global not typed / undeclared.
215
165
  - Wrong `cstType` in `analyzeExpression` → role-specific errors.
216
166
  - `term` with `X1×X1` for a relation → full Cartesian product, not relation typification.
217
167
  - `structure` with `Pr1(S1)` → wrong role; projections belong on `term` / `function`.
218
168
  - Same long `∃d1…∃dn` chain in many `D#` → define one central `D#` and use `Pr*` / `F#`.
219
- - `S4: ℬ(X2×X1×ℬ(X3))` when you only need «individual allows actions» → prefer `ℬ(X2×X1×X3)` + `F5`.
220
- - `∀x∈A, ∀y∈B` → invalid; nest: `∀x∈A (∀y∈B (…))`.
221
- - Functional relation axiom as huge `∀⇒` → prefer `card(S)=card(Pr1,2(S))` when equivalent.
222
169
  - `setConstituentaValue` on `term`, `axiom`, or `statement` → cannot set computed constituents directly.
223
170
  - Evaluation before base bindings → missing value, empty result, or evaluation failure.
224
-
225
- ## Fix Syntax
226
-
227
- 1. `analyzeExpression` with the broken fragment and correct `cstType`.
228
- 2. Read `{ code, from, to, params }`.
229
- 3. Edit the substring of `definitionFormal` at those offsets.
230
- 4. Re-run analysis.
231
- 5. Upsert with the same `id` / `alias`.
@@ -32,16 +32,18 @@ Paths are relative to this file.
32
32
  Use this when editing or checking schemas and models.
33
33
 
34
34
  1. `createSession`.
35
- 2. Add `basic` (`X#`) and `constant` (`C#`) with `definitionFormal: ''`.
35
+ 2. Develop schema - add constituents with proper type and attributes.
36
36
  3. Add dependencies before dependents.
37
37
  4. Use `analyzeExpression` before upsert when unsure.
38
- 5. When unsure about semantics, build a tiny conceptual model and evaluate test data.
39
- 6. Fix diagnostics by `from` / `to` range in `definitionFormal`.
38
+ 5. Fix diagnostics by `from` / `to` range in `definitionFormal`.
39
+ 6. When unsure about semantics, build a tiny conceptual model and evaluate test data.
40
+
41
+ - Set base/model values with `setConstituentaValue(s)`.
42
+ - Evaluate with `evaluateExpression`, `evaluateConstituenta`, or `recalculateModel`.
43
+
40
44
  7. `commitStep` when the state is coherent.
41
- 8. Set base/model values with `setConstituentaValue(s)`.
42
- 9. Evaluate with `evaluateExpression`, `evaluateConstituenta`, or `recalculateModel`.
43
- 10. Persist with `exportSession` / `importSession`.
44
- 11. For user-uploadable Portal files, use `exportPortalSchema` for schema JSON or `exportPortalModel` for model JSON.
45
+ 8. Persist with `exportSession` / `importSession`.
46
+ 9. For user-uploadable Portal files, use `exportPortalSchema` for schema JSON or `exportPortalModel` for model JSON.
45
47
 
46
48
  ## Diagnostics Loop
47
49
 
@@ -64,5 +66,3 @@ Use this when editing or checking schemas and models.
64
66
  - [ ] `cstType` matches the role.
65
67
  - [ ] Check schema and fix errors before showing result.
66
68
  - [ ] Diagnostics handled before commit/export.
67
- - [ ] Ambiguous semantics checked on a small model.
68
- - [ ] Base values set before evaluation.
@@ -34,8 +34,8 @@
34
34
  ```ts
35
35
  {
36
36
  id: number; // stable id within session
37
- alias: string; // e.g. "D1", "X1"
38
- cstType: CstType; // see GUIDE.md table
37
+ alias: string;
38
+ cstType: CstType;
39
39
  definitionFormal: string;
40
40
  term?: string;
41
41
  definitionText?: string;
@@ -62,7 +62,7 @@ All default to `''` when omitted.
62
62
  ### Model and evaluation types
63
63
 
64
64
  ```ts
65
- type RSToolValue = number | RSToolValue[]; // runtime value (sets, tuples, logic 0/1)
65
+ type RSToolValue = number | RSToolValue[]; // runtime value
66
66
  type BasicBinding = Record<number, string>; // base-set element labels
67
67
 
68
68
  interface SessionModelState {
@@ -115,34 +115,32 @@ Example chain:
115
115
  ```ts
116
116
  interface AnalysisResult {
117
117
  success: boolean;
118
- type: Record<string, unknown> | null; // typification tree
118
+ type: Record<string, unknown> | null;
119
119
  valueClass: 'value' | 'property' | null;
120
120
  diagnostics: { code: number; from: number; to: number; params?: string[] }[];
121
121
  }
122
122
  ```
123
123
 
124
- ## RS language — conceptual model
125
-
126
- - **Typification**: structure type of an expression; grades include elements (`Xi`, `Ci`), `Z`, tuples `(H1×…×Hn)`, sets `ℬ(H)`, logic `Logic`, parameterized `Hr 🠔 [H1,…,Hi]`. On `structure` (`S#`), `definitionFormal` **is** the typification. On `term` (`D#`), typification is **inferred from** the definition.
127
- - **Term graph**: directed dependencies between constituenta via alias references in definitions.
128
- - **`S#` vs `D#`**: same `×` token — in `ℬ(X1×X1)` on `S#` it forms a **grade** (pair type); in `X1×X1` on `D#` it is the **Cartesian product** (all pairs). Relations: `S#` + `convention`, then derived `D#` (`Pr1(S1)`, …).
124
+ ## RS language
129
125
 
130
126
  Intro (help): language is FOL-based; set vs logic expression split; parameterized templates for term/predicate functions.
131
127
 
132
- ## Grammar tokens (selected)
128
+ - **Typification**: structure type of an expression; grades include elements (`Xi`, `Ci`), `Z`, tuples `(H1×…×Hn)`, sets `ℬ(H)`, logic `Logic`, parameterized `Hr 🠔 [H1,…,Hi]`. On `structure` (`S#`), `definitionFormal` **is** the typification. On `term` (`D#`), typification is **inferred from** the definition.
129
+
130
+ ## Grammar tokens
133
131
 
134
132
  From `rslang.grammar`:
135
133
 
136
- | Category | Tokens / forms |
137
- | ---------------------- | ---------------------------------------------------------- |
138
- | Globals | `X`, `C`, `S`, `D`, `A`, `T`, `N` + digits (`Global` rule) |
139
- | Functions / predicates | `F<n>`, `P<n>` |
140
- | Radicals | `R<n>` |
141
- | Locals | `_a-zα-ω` + optional digits |
142
- | Logic | `¬` `∀` `∃` `⇔` `⇒` `∨` `&` |
143
- | Sets | `ℬ` `∪` `\` `∆` `∩` `×` `∈` `∉` `⊆` `⊂` … |
144
- | Ops | `Pr`, `pr`, `Fi`, `card`, `bool`, `debool`, `red` |
145
- | Literals | digits, `Z`, `∅` |
134
+ | Category | Tokens / forms |
135
+ | ---------------------- | ----------------------------------------------------- |
136
+ | Globals | `X`, `C`, `S`, `D`, `A`, `T` + digits (`Global` rule) |
137
+ | Functions / predicates | `F<n>`, `P<n>` |
138
+ | Radicals | `R<n>` |
139
+ | Locals | `_a-zα-ω` + optional digits |
140
+ | Logic | `¬` `∀` `∃` `⇔` `⇒` `∨` `&` |
141
+ | Sets | `ℬ` `∪` `\` `∆` `∩` `×` `∈` `∉` `⊆` `⊂` … |
142
+ | Ops | `Pr`, `pr`, `Fi`, `card`, `bool`, `debool`, `red` |
143
+ | Literals | digits, `Z`, `∅` |
146
144
 
147
145
  Full grammar pointers and precedence notes: `docs/GRAMMAR-REF.md`.
148
146
 
@@ -167,7 +165,7 @@ Standalone agents should consult the bundled distilled docs (`docs/*.md` inside
167
165
  | Portal REST API | `docs/PORTAL-API.md` |
168
166
  | Grammar tokens / precedence | `docs/GRAMMAR-REF.md` |
169
167
 
170
- ## Error codes (rstool-relevant)
168
+ ## Error codes
171
169
 
172
170
  rstool re-exports `RSErrorCode.definitionNotAllowed` (`0x8862`) for base/constant violations.
173
171
 
@@ -197,7 +195,5 @@ For **Load from JSON** on an existing Portal schema or model:
197
195
  - `exportPortalSchema(sessionId)` — schema file
198
196
  - `exportPortalModel(sessionId)` — model file
199
197
 
200
- Both return `contract_version` `1.0.0` plus required `title`, `alias`, `description`, and `items`. Schema files may include `attribution`. Values come from `state.title`, `state.alias`, and `state.comment` (empty fields fall back to `Conceptual schema` / `SCHEMA` or `Conceptual model` / `MODEL` and `""`).
201
-
202
198
  - Schema `items[]`: versioned constituent fields (`cst_type`, `definition_formal`, `term_raw`, …).
203
199
  - Model `items[]`: `{ id, type, value }` per binding.
@@ -1,12 +1,10 @@
1
1
  ---
2
2
  name: rstool-helper
3
3
  description: >-
4
- RS language and @rsconcept/rstool for agents. After npm install, read GUIDE and
5
- docs from node_modules. If the entry skill is not installed in the project yet,
6
- follow skills/INSTALL.md in this package.
4
+ RS language, formal definitions and conceptual schema design for agents. Read GUIDE and docs from node_modules.
7
5
  ---
8
6
 
9
- # rstool-helper (npm install)
7
+ # rstool-helper
10
8
 
11
9
  Thin **entry** skill. Full guide and docs stay in the package — use the Read tool on the paths below (from the project root).
12
10